title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Build a Machine Learning Model to Identify Credit Card Fraud in 5 Steps | by Claudia Ng | Towards Data Science
With the surge in e-commerce and digital transactions, identity fraud is has also risen to affect millions of people every year. In 2019, fraud losses in the US alone were estimated to be at around US$16.9 billion, a substantial portion of which includes losses from credit card fraud1. In addition to strengthening cybersecurity measures, financial institutions are increasingly turning to machine learning to identify and reject fraudulent transactions when they happen, so as to limit losses. I came across a credit card fraud dataset on Kaggle and built a classification model to predict fraudulent transactions. In this article, I will walk through the 5 steps to building a supervised machine learning model. Below is a an outline of the five steps: Exploratory Data AnalysisTrain-test splitModelingHyperparameter TuningEvaluating Final Model Performance Exploratory Data Analysis Train-test split Modeling Hyperparameter Tuning Evaluating Final Model Performance When starting a new modeling project, it is important to start with EDA in order to understand the dataset. In this case, the credit card fraud dataset from Kaggle contains 284,807 rows with 31 columns. This particular dataset contains no nulls, but note that this may not be the case when dealing with datasets in reality. Our target variable is named class, and it is a binary output of 0’s and 1’s, with 1’s representing fraudulent transactions and 0’s as non-fraudulent ones. The remaining 30 columns are features that we will use to train our model, the vast majority of which have been transformed using PCA and thus anonymized, while only two (time and amount) are labeled. Our dataset is highly imbalanced, as the majority of rows (99.8%) in the dataset are non-fraudulent transactions and have a class = 0. Fraudulent transactions only represent ~0.2% of the dataset. This class imbalance problem is common with fraud detection, as fraud (hopefully) is a rare event. Because of this class imbalance issue, our model may not have enough fraudulent examples to learn from and we will mitigate this by experimenting with sampling methods in the modeling stage. To get a preliminary look at our features, I find seaborn’s pairplot function to be very useful, especially because we can plot out the distributions by the target variable if we introduce thehue='class' argument. Below is a plot showing the first 10 features in our dataset by label, with orange representing 0 or non-fraudulent transactions and blue representing 1 or fraudulent transactions. As you can see from the pairplot, the distributions of some features differ by label, giving an indication that these features may be useful for the model. Since the dataset has already been cleaned, we can move on to split our dataset into the train and test sets. This is an important step as you cannot effectively evaluate the performance of your model on data that it has trained on! I used scikit-learn’s train_test_split function to split 75% of our dataset as the train set and the remaining 25% as the test set. It is important to note that I set the stratify argument to be equal to the label or y in the train_test_split function to make sure there are proportional examples of our label in both the train and test sets. Otherwise, if there were no examples where the label is 1 in our train set, the model would not learn what fraudulent transactions are like. Likewise, if there were no examples where the label is 1 in our test set, we would not know how well the model would perform when it encounters fraud. X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, stratify=y) Since our dataset is anonymized, there is no feature engineering to be done, so the next step is modeling. There are different classification models to choose from, and I experimented with building simple models to pick the best one that we will later tune the hyperparameters of to optimize. In this case, I trained a logistic regression model, random forest model and XGBoost model to compare their performances. Due to class imbalance, accuracy is not a meaningful metric in this case. Instead I used AUC as the evaluation metric, which takes on values between 0 and 1. The AUC measures the probability that the model will rank a random positive example (class = 1) higher than a random negative example. To evaluate model performances, I used stratified K-Fold Cross Validation to stratify sampling by class label, since our dataset is highly imbalanced. Using the model AUC scores, I made a boxplot to compare the ranges of AUC scores by model. Not surprisingly, XGBoost appears to be the best model of our three choices. The median AUC score of the XGBoost model is 0.970, compared to 0.944 for that of the random forest model and 0.911 for that of the logistic regression model. So, I selected XGboost as my model of choice going forward. As mentioned previously, I also experimented with different sampling techniques to deal with the class imbalance issue. I tried outimblearn's random oversampling, random undersampling and SMOTE functions: Random oversampling samples the minority class with replacement until a defined threshold, which I left at the default of 0.5, so our new dataset has a 50/50 split between labels of 0’s and 1’s. Random undersampling samples the majority class, without replacement by default but you can set it to sample with replacement, until our dataset has a 50/50 split between labels of 0’s and 1’s. SMOTE (Synthetic Minority Oversampling Technique) is a data augmentation method that randomly selects an example from the minority class, finds k of its nearest neighbours (usually k=5), chooses a random neighbour and creates a synthetic new example in the feature space between this random neighbour and the original example. I used the Pipeline function fromimblearn.pipeline to avoid leakage, then used stratified K-Fold Cross Validation to compare performances of XGBoost models with the three different sampling techniques listed above. The median AUC scores of the three sampling methods are quite close at between 0.974 to 0.976. In the end, I chose SMOTE because of the smaller range in AUC scores. I chose to use Bayesian hyperparameter tuning with a package called hyperopt, because it is faster and more informed than other methods such as grid search or randomized search. The hyperparameters that I wanted to tune for my XGBoost model were: max_depth: maximum depth of a tree; values between 4 to 10. min_child_weight: minimum sum of weights of samples to form a leaf node or the end of a branch; values between 1 to 20. subsample: random sample of observations for each tree; values between 0.5 to 0.9. colsample_bytree: random sample of columns or features for each tree; values between 0.5 to 0.9. gamma: minimum loss reduction needed to split a node and used to prevent overfitting; values between 0 and 5. eta: learning_rate; values between 0.01 and 0.3. To use hyperopt, I first set up my search space with hyperparameters and their respective bounds to search through: space = { 'max_depth': hp.quniform('max_depth', 4, 10, 2), 'min_child_weight': hp.quniform('min_child_weight', 5, 30, 2), 'gamma': hp.quniform('gamma', 0, 10, 2), 'subsample': hp.uniform('subsample', 0.5, 0.9), 'colsample_bytree': hp.uniform('colsample_bytree', 0.5, 0.9), 'eta': hp.uniform('eta', 0.01, 0.3), 'objective': 'binary:logistic', 'eval_metric': 'auc'} Next, I defined an objective function to minimize that will receive values from the previously defined search space: def objective(params): params = {'max_depth': int(params['max_depth']), 'min_child_weight': int(params['min_child_weight']), 'gamma': params['gamma'], 'subsample': params['subsample'], 'colsample_bytree': params['colsample_bytree'], 'eta': params['eta'], 'objective': params['objective'], 'eval_metric': params['eval_metric']} xgb_clf = XGBClassifier(num_boost_rounds=num_boost_rounds, early_stopping_rounds=early_stopping_rounds, **params) best_score = cross_val_score(xgb_clf, X_train, y_train, scoring='roc_auc', cv=5, n_jobs=3).mean() loss = 1 - best_score return loss The best hyperparameters returned are listed below and we will use this to train our final model! best_params = {'colsample_bytree': 0.7, 'eta': 0.2, 'gamma': 1.5, 'max_depth': 10, 'min_child_weight': 6, 'subsample': 0.9} To train the final model, I used imblearn's pipeline to avoid leakage. In the pipeline, I first used SMOTE to augment the dataset and include more positive classes for the model to learn from, then trained a XGBoost model with the best hyperparameters found in step IV. final_model = imblearn.pipeline.Pipeline([ ('smote',SMOTE(random_state=1)), ('xgb', XGBClassifier(num_boost_rounds=1000, early_stopping_rounds=10, **best_params))]) Below are some metrics to evaluate the performance of the final model: AUC The AUC score of the final model is 0.991! This indicates that our final model is able to rank order fraud risk quite well. Classification Report Precision True Positives/(True Positives + False Positives) Precision for class 0 is 1, indicating that all items labeled as belonging to class 0 are indeed non-fraudulent transactions. Precision for class 1 is 0.86, meaning that 86% of items labeled as class 1 are indeed fraudulent transactions. In other words, the final model correctly predicted 100% of non-fraudulent transactions and 86% of fraudulent transactions. Recall True Positives/(True Positives + False Negatives) Recall for class 0 is 1, meaning that all non-fraudulent transactions were labeled as such, i.e. belonging to class 0. Recall for class 1 is 0.9, so 90% of fraudulent transactions were labeled as belonging to class 1 by our final model. This means that the final model is able to catch 90% of all fraudulent transactions. F1 score 2 * (Recall * Precision)/(Recall + Precision) The F1 score is a weighted harmonic mean of precision and recall. The F1 score of the final model predictions on the test set for class 0 is 1, while that for class 1 is 0.88. To understand the model, it is useful to look at the Shap summary and feature importances plots. Unfortunately, most features have been anonymized in this dataset, but the plots show that v14, v4 and v12 are the top 3 most important features in the final model. In merely five steps, we built an XGBoost model capable of predicting whether a transaction is fraudulent or not based on the 30 features provided in this dataset. Our final model has an AUC score of 0.991, which is incredibly high! However, it is worth noting that this was done with a pre-cleaned (and manipulated) dataset. In reality, feature engineering is a vital step in modeling but we did not have the chance to do so here due to limits of working with an anonymized dataset. I hope that this hands-on modeling exercise using a real dataset helped you better understand the mechanics behind creating a machine learning model to predict fraud. I am very curious to know what the anonymized features were, especially the most predictive ones. If you have any ideas on what they could be, please comment below! To see the code, please check out my jupyter notebook file on Github. Thank you! Kaggle Credit Card Fraud Dataset Jupyter Notebook file [1]: Javelin Strategy. 2020 Identity Fraud Study: Genesis of the Identity Fraud Crisis. https://www.javelinstrategy.com/coverage-area/2020-identity-fraud-study-genesis-identity-fraud-crisis
[ { "code": null, "e": 459, "s": 172, "text": "With the surge in e-commerce and digital transactions, identity fraud is has also risen to affect millions of people every year. In 2019, fraud losses in the US alone were estimated to be at around US$16.9 billion, a substantial portion of which includes losses from credit card fraud1." }, { "code": null, "e": 668, "s": 459, "text": "In addition to strengthening cybersecurity measures, financial institutions are increasingly turning to machine learning to identify and reject fraudulent transactions when they happen, so as to limit losses." }, { "code": null, "e": 928, "s": 668, "text": "I came across a credit card fraud dataset on Kaggle and built a classification model to predict fraudulent transactions. In this article, I will walk through the 5 steps to building a supervised machine learning model. Below is a an outline of the five steps:" }, { "code": null, "e": 1033, "s": 928, "text": "Exploratory Data AnalysisTrain-test splitModelingHyperparameter TuningEvaluating Final Model Performance" }, { "code": null, "e": 1059, "s": 1033, "text": "Exploratory Data Analysis" }, { "code": null, "e": 1076, "s": 1059, "text": "Train-test split" }, { "code": null, "e": 1085, "s": 1076, "text": "Modeling" }, { "code": null, "e": 1107, "s": 1085, "text": "Hyperparameter Tuning" }, { "code": null, "e": 1142, "s": 1107, "text": "Evaluating Final Model Performance" }, { "code": null, "e": 1466, "s": 1142, "text": "When starting a new modeling project, it is important to start with EDA in order to understand the dataset. In this case, the credit card fraud dataset from Kaggle contains 284,807 rows with 31 columns. This particular dataset contains no nulls, but note that this may not be the case when dealing with datasets in reality." }, { "code": null, "e": 1823, "s": 1466, "text": "Our target variable is named class, and it is a binary output of 0’s and 1’s, with 1’s representing fraudulent transactions and 0’s as non-fraudulent ones. The remaining 30 columns are features that we will use to train our model, the vast majority of which have been transformed using PCA and thus anonymized, while only two (time and amount) are labeled." }, { "code": null, "e": 2019, "s": 1823, "text": "Our dataset is highly imbalanced, as the majority of rows (99.8%) in the dataset are non-fraudulent transactions and have a class = 0. Fraudulent transactions only represent ~0.2% of the dataset." }, { "code": null, "e": 2309, "s": 2019, "text": "This class imbalance problem is common with fraud detection, as fraud (hopefully) is a rare event. Because of this class imbalance issue, our model may not have enough fraudulent examples to learn from and we will mitigate this by experimenting with sampling methods in the modeling stage." }, { "code": null, "e": 2704, "s": 2309, "text": "To get a preliminary look at our features, I find seaborn’s pairplot function to be very useful, especially because we can plot out the distributions by the target variable if we introduce thehue='class' argument. Below is a plot showing the first 10 features in our dataset by label, with orange representing 0 or non-fraudulent transactions and blue representing 1 or fraudulent transactions." }, { "code": null, "e": 2860, "s": 2704, "text": "As you can see from the pairplot, the distributions of some features differ by label, giving an indication that these features may be useful for the model." }, { "code": null, "e": 3093, "s": 2860, "text": "Since the dataset has already been cleaned, we can move on to split our dataset into the train and test sets. This is an important step as you cannot effectively evaluate the performance of your model on data that it has trained on!" }, { "code": null, "e": 3728, "s": 3093, "text": "I used scikit-learn’s train_test_split function to split 75% of our dataset as the train set and the remaining 25% as the test set. It is important to note that I set the stratify argument to be equal to the label or y in the train_test_split function to make sure there are proportional examples of our label in both the train and test sets. Otherwise, if there were no examples where the label is 1 in our train set, the model would not learn what fraudulent transactions are like. Likewise, if there were no examples where the label is 1 in our test set, we would not know how well the model would perform when it encounters fraud." }, { "code": null, "e": 3812, "s": 3728, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, stratify=y)" }, { "code": null, "e": 3919, "s": 3812, "text": "Since our dataset is anonymized, there is no feature engineering to be done, so the next step is modeling." }, { "code": null, "e": 4227, "s": 3919, "text": "There are different classification models to choose from, and I experimented with building simple models to pick the best one that we will later tune the hyperparameters of to optimize. In this case, I trained a logistic regression model, random forest model and XGBoost model to compare their performances." }, { "code": null, "e": 4520, "s": 4227, "text": "Due to class imbalance, accuracy is not a meaningful metric in this case. Instead I used AUC as the evaluation metric, which takes on values between 0 and 1. The AUC measures the probability that the model will rank a random positive example (class = 1) higher than a random negative example." }, { "code": null, "e": 4762, "s": 4520, "text": "To evaluate model performances, I used stratified K-Fold Cross Validation to stratify sampling by class label, since our dataset is highly imbalanced. Using the model AUC scores, I made a boxplot to compare the ranges of AUC scores by model." }, { "code": null, "e": 5058, "s": 4762, "text": "Not surprisingly, XGBoost appears to be the best model of our three choices. The median AUC score of the XGBoost model is 0.970, compared to 0.944 for that of the random forest model and 0.911 for that of the logistic regression model. So, I selected XGboost as my model of choice going forward." }, { "code": null, "e": 5263, "s": 5058, "text": "As mentioned previously, I also experimented with different sampling techniques to deal with the class imbalance issue. I tried outimblearn's random oversampling, random undersampling and SMOTE functions:" }, { "code": null, "e": 5458, "s": 5263, "text": "Random oversampling samples the minority class with replacement until a defined threshold, which I left at the default of 0.5, so our new dataset has a 50/50 split between labels of 0’s and 1’s." }, { "code": null, "e": 5652, "s": 5458, "text": "Random undersampling samples the majority class, without replacement by default but you can set it to sample with replacement, until our dataset has a 50/50 split between labels of 0’s and 1’s." }, { "code": null, "e": 5979, "s": 5652, "text": "SMOTE (Synthetic Minority Oversampling Technique) is a data augmentation method that randomly selects an example from the minority class, finds k of its nearest neighbours (usually k=5), chooses a random neighbour and creates a synthetic new example in the feature space between this random neighbour and the original example." }, { "code": null, "e": 6194, "s": 5979, "text": "I used the Pipeline function fromimblearn.pipeline to avoid leakage, then used stratified K-Fold Cross Validation to compare performances of XGBoost models with the three different sampling techniques listed above." }, { "code": null, "e": 6359, "s": 6194, "text": "The median AUC scores of the three sampling methods are quite close at between 0.974 to 0.976. In the end, I chose SMOTE because of the smaller range in AUC scores." }, { "code": null, "e": 6606, "s": 6359, "text": "I chose to use Bayesian hyperparameter tuning with a package called hyperopt, because it is faster and more informed than other methods such as grid search or randomized search. The hyperparameters that I wanted to tune for my XGBoost model were:" }, { "code": null, "e": 6666, "s": 6606, "text": "max_depth: maximum depth of a tree; values between 4 to 10." }, { "code": null, "e": 6786, "s": 6666, "text": "min_child_weight: minimum sum of weights of samples to form a leaf node or the end of a branch; values between 1 to 20." }, { "code": null, "e": 6869, "s": 6786, "text": "subsample: random sample of observations for each tree; values between 0.5 to 0.9." }, { "code": null, "e": 6966, "s": 6869, "text": "colsample_bytree: random sample of columns or features for each tree; values between 0.5 to 0.9." }, { "code": null, "e": 7076, "s": 6966, "text": "gamma: minimum loss reduction needed to split a node and used to prevent overfitting; values between 0 and 5." }, { "code": null, "e": 7125, "s": 7076, "text": "eta: learning_rate; values between 0.01 and 0.3." }, { "code": null, "e": 7241, "s": 7125, "text": "To use hyperopt, I first set up my search space with hyperparameters and their respective bounds to search through:" }, { "code": null, "e": 7629, "s": 7241, "text": "space = { 'max_depth': hp.quniform('max_depth', 4, 10, 2), 'min_child_weight': hp.quniform('min_child_weight', 5, 30, 2), 'gamma': hp.quniform('gamma', 0, 10, 2), 'subsample': hp.uniform('subsample', 0.5, 0.9), 'colsample_bytree': hp.uniform('colsample_bytree', 0.5, 0.9), 'eta': hp.uniform('eta', 0.01, 0.3), 'objective': 'binary:logistic', 'eval_metric': 'auc'}" }, { "code": null, "e": 7746, "s": 7629, "text": "Next, I defined an objective function to minimize that will receive values from the previously defined search space:" }, { "code": null, "e": 8442, "s": 7746, "text": "def objective(params): params = {'max_depth': int(params['max_depth']), 'min_child_weight': int(params['min_child_weight']), 'gamma': params['gamma'], 'subsample': params['subsample'], 'colsample_bytree': params['colsample_bytree'], 'eta': params['eta'], 'objective': params['objective'], 'eval_metric': params['eval_metric']} xgb_clf = XGBClassifier(num_boost_rounds=num_boost_rounds, early_stopping_rounds=early_stopping_rounds, **params) best_score = cross_val_score(xgb_clf, X_train, y_train, scoring='roc_auc', cv=5, n_jobs=3).mean() loss = 1 - best_score return loss" }, { "code": null, "e": 8540, "s": 8442, "text": "The best hyperparameters returned are listed below and we will use this to train our final model!" }, { "code": null, "e": 8734, "s": 8540, "text": "best_params = {'colsample_bytree': 0.7, 'eta': 0.2, 'gamma': 1.5, 'max_depth': 10, 'min_child_weight': 6, 'subsample': 0.9}" }, { "code": null, "e": 9004, "s": 8734, "text": "To train the final model, I used imblearn's pipeline to avoid leakage. In the pipeline, I first used SMOTE to augment the dataset and include more positive classes for the model to learn from, then trained a XGBoost model with the best hyperparameters found in step IV." }, { "code": null, "e": 9340, "s": 9004, "text": "final_model = imblearn.pipeline.Pipeline([ ('smote',SMOTE(random_state=1)), ('xgb', XGBClassifier(num_boost_rounds=1000, early_stopping_rounds=10, **best_params))])" }, { "code": null, "e": 9411, "s": 9340, "text": "Below are some metrics to evaluate the performance of the final model:" }, { "code": null, "e": 9415, "s": 9411, "text": "AUC" }, { "code": null, "e": 9539, "s": 9415, "text": "The AUC score of the final model is 0.991! This indicates that our final model is able to rank order fraud risk quite well." }, { "code": null, "e": 9561, "s": 9539, "text": "Classification Report" }, { "code": null, "e": 9571, "s": 9561, "text": "Precision" }, { "code": null, "e": 9621, "s": 9571, "text": "True Positives/(True Positives + False Positives)" }, { "code": null, "e": 9983, "s": 9621, "text": "Precision for class 0 is 1, indicating that all items labeled as belonging to class 0 are indeed non-fraudulent transactions. Precision for class 1 is 0.86, meaning that 86% of items labeled as class 1 are indeed fraudulent transactions. In other words, the final model correctly predicted 100% of non-fraudulent transactions and 86% of fraudulent transactions." }, { "code": null, "e": 9990, "s": 9983, "text": "Recall" }, { "code": null, "e": 10040, "s": 9990, "text": "True Positives/(True Positives + False Negatives)" }, { "code": null, "e": 10362, "s": 10040, "text": "Recall for class 0 is 1, meaning that all non-fraudulent transactions were labeled as such, i.e. belonging to class 0. Recall for class 1 is 0.9, so 90% of fraudulent transactions were labeled as belonging to class 1 by our final model. This means that the final model is able to catch 90% of all fraudulent transactions." }, { "code": null, "e": 10371, "s": 10362, "text": "F1 score" }, { "code": null, "e": 10417, "s": 10371, "text": "2 * (Recall * Precision)/(Recall + Precision)" }, { "code": null, "e": 10593, "s": 10417, "text": "The F1 score is a weighted harmonic mean of precision and recall. The F1 score of the final model predictions on the test set for class 0 is 1, while that for class 1 is 0.88." }, { "code": null, "e": 10855, "s": 10593, "text": "To understand the model, it is useful to look at the Shap summary and feature importances plots. Unfortunately, most features have been anonymized in this dataset, but the plots show that v14, v4 and v12 are the top 3 most important features in the final model." }, { "code": null, "e": 11019, "s": 10855, "text": "In merely five steps, we built an XGBoost model capable of predicting whether a transaction is fraudulent or not based on the 30 features provided in this dataset." }, { "code": null, "e": 11339, "s": 11019, "text": "Our final model has an AUC score of 0.991, which is incredibly high! However, it is worth noting that this was done with a pre-cleaned (and manipulated) dataset. In reality, feature engineering is a vital step in modeling but we did not have the chance to do so here due to limits of working with an anonymized dataset." }, { "code": null, "e": 11671, "s": 11339, "text": "I hope that this hands-on modeling exercise using a real dataset helped you better understand the mechanics behind creating a machine learning model to predict fraud. I am very curious to know what the anonymized features were, especially the most predictive ones. If you have any ideas on what they could be, please comment below!" }, { "code": null, "e": 11752, "s": 11671, "text": "To see the code, please check out my jupyter notebook file on Github. Thank you!" }, { "code": null, "e": 11785, "s": 11752, "text": "Kaggle Credit Card Fraud Dataset" }, { "code": null, "e": 11807, "s": 11785, "text": "Jupyter Notebook file" } ]
Undefined Behavior in C and C++ - GeeksforGeeks
Undefined Behavior in C and C++ Name Mangling and extern “C” in C++ How does ‘void*’ differ in C and C++? Write a program that produces different results in C and C++ Type difference of character literals in C and C++ Difference Between C Structures and C++ Structures Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction) Virtual Function in C++ Polymorphism in C++ Encapsulation in C++ Abstraction in C++ Structure vs class in C++ Can a C++ class have an object of self type? Why is the Size of an Empty Class Not Zero in C++? Static data members in C++ Some interesting facts about static member functions in C++ Friend class and function in C++ Local Classes in C++ Nested Classes in C++ Simulating final Class in C++ Constructors in C++ Copy Constructor in C++ Destructors in C++ Virtual Destructor Pure Virtual Destructor in C++ Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ What is Memory Leak? How can we avoid? Undefined Behavior in C and C++ Name Mangling and extern “C” in C++ How does ‘void*’ differ in C and C++? Write a program that produces different results in C and C++ Type difference of character literals in C and C++ Difference Between C Structures and C++ Structures Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction) Virtual Function in C++ Polymorphism in C++ Encapsulation in C++ Abstraction in C++ Structure vs class in C++ Can a C++ class have an object of self type? Why is the Size of an Empty Class Not Zero in C++? Static data members in C++ Some interesting facts about static member functions in C++ Friend class and function in C++ Local Classes in C++ Nested Classes in C++ Simulating final Class in C++ Constructors in C++ Copy Constructor in C++ Destructors in C++ Virtual Destructor Pure Virtual Destructor in C++ Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ What is Memory Leak? How can we avoid? Difficulty Level : Easy When we run a code, sometimes we see absurd results instead of expected output. So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended. Whenever the result of an executing program is unpredictable, it is said to have undefined behavior. As a C programmer, understanding undefined behavior is very important for optimal coding and for the program to yield a good efficiency, especially when it comes to there are C codes embedded in system design. Division By Zero int val = 5; return val / 0; // undefined behavior Memory accesses outside of array bounds int arr[4] = {0, 1, 2, 3}; return arr[5]; // undefined behavior for indexing out of bounds Signed integer overflow int x = INT_MAX; printf("%d", x + 1); // undefined behavior Null pointer dereference val = 0; int ptr = *val; // undefined behavior for dereferencing a null pointer Modification of string literal char* s = "geeksforgeeks"; s[0] = 'e'; // undefined behavior Accessing a NULL Pointer, etc. int* ptr = NULL; printf("%d", *ptr); // undefined behavior for accessing NULL Pointer Sometimes compilers may diagnose simple errors, however, sometimes they are not designed to diagnose the undefined behavior. Following are some C/C++ programs that showcase undefined behavior: Program 1: C // C Program to demonstrate// division by 0 #include <stdio.h> // Driver Codeint main(){ int x = 25, y = 0; int z = x / y; printf("%d", z); return 0;} Program 2: C // C Program to demonstrate// Uninitialized variables #include <stdio.h> // Driver Codeint main(){ bool val; if (val) printf("TRUE"); else printf("FALSE");} Program 3: C // C Program to demonstrate// accessing value of NULL// pointer #include <stdio.h> // Driver Codeint main(){ int* ptr = NULL; printf("%d", *ptr); return 0;} Program 4: C // C program to demonstrate// accessing out of bound #include <stdio.h> // Driver Codeint main(){ int arr[5]; // We access arr[5] in last iteration. for (int i = 0; i <= 5; i++) printf("%d ", arr[i]);} Program 5: C // C Program to demonstrate going// beyond limit of signed int #include <stdio.h> // Driver Codeint main(){ int x = INT_MAX; printf("%d", x + 1); return 0;} Program 6: C // C Program to demonstrate trying to// modify a string literal #include <stdio.h> // Driver Codeint main(){ char* s = "geeksforgeeks"; s[0] = 'e'; return 0;} Program 7: C // C Program to demonstrate modifying a variable// multiple times before a defined// sequence point #include <stdio.h> // Driver Codeint main(){ int i = 8; int p = i++ * i++; printf("%d\n", p);} 72 Explanation: The program produces 72 as output in most of the compilers, but implementing software based on this assumption is not a good idea. The output of all of the above programs is unpredictable (or undefined). The compilers (implementing the C/C++ standard) are free to do anything as these are undefined by the C and C++ standards. Language like Java, trap errors as soon as they are found but languages like C and C++ in a few cases keep on executing the code in a faulty manner which may result in unpredictable results. The program can crash with any type of error message, or it can unknowingly corrupt the data which is a grave issue to deal with. Importance of knowing about Undefined Behavior: If a user starts learning in a C/C++ environment and is unclear with the concept of undefined behavior then that can bring plenty of problems in the future like while debugging someone else’s code might be actually difficult in tracing the root to the undefined error. Risks and Disadvantages of Undefined Behavior The programmers sometimes rely on a particular implementation (or compiler) of undefined behavior which may cause problems when the compiler is changed/upgraded. For example, the last program produces 72 as output in most of the compilers, but implementing software based on this assumption is not a good idea. Undefined behaviors may also cause security vulnerabilities, especially due to the cases when an array out of bound is not checked (causes buffer overflow attack). Advantages of Undefined Behavior C and C++ have undefined behaviors because it allows compilers to avoid lots of checks. Suppose a set of code with a greater performing array need not keep a look at the bounds, which avoids the need for a complex optimization pass to check such conditions outside loops. The tightly bound loops and speed up the program from thirty to fifty percent when it gains an advantage of the undefined nature of signed overflow, which is generally offered by the C compiler. We also have another advantage of this as it allows us to store a variable’s value in a processor register and manipulate it over time that is larger than the variable in the source code. It also helps in wrap-around then compile-time checks which would not be possible without the greater knowledge of the undefined behavior in the C/C++ compiler. More Examples of undefined behavior Sequence Points in C | Set 1“delete this” in C++Passing NULL to printf in CAccessing array out of bounds in C/C++Use of realloc()Execution of printf with ++ operatorsVirtual destruction using shared_ptr in C++Virtual Destructor Sequence Points in C | Set 1 “delete this” in C++ Passing NULL to printf in C Accessing array out of bounds in C/C++ Use of realloc() Execution of printf with ++ operatorsVirtual destruction using shared_ptr in C++ Virtual Destructor chhabradhanvi anshikajain26 cpp-advanced C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ Command line arguments in C/C++ rand() and srand() in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Inheritance in C++ Socket Programming in C/C++ Initialize a vector in C++ (6 different ways) Operator Overloading in C++
[ { "code": null, "e": 22194, "s": 22162, "text": "Undefined Behavior in C and C++" }, { "code": null, "e": 22230, "s": 22194, "text": "Name Mangling and extern “C” in C++" }, { "code": null, "e": 22268, "s": 22230, "text": "How does ‘void*’ differ in C and C++?" }, { "code": null, "e": 22329, "s": 22268, "text": "Write a program that produces different results in C and C++" }, { "code": null, "e": 22380, "s": 22329, "text": "Type difference of character literals in C and C++" }, { "code": null, "e": 22431, "s": 22380, "text": "Difference Between C Structures and C++ Structures" }, { "code": null, "e": 22504, "s": 22431, "text": "Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)" }, { "code": null, "e": 22528, "s": 22504, "text": "Virtual Function in C++" }, { "code": null, "e": 22548, "s": 22528, "text": "Polymorphism in C++" }, { "code": null, "e": 22569, "s": 22548, "text": "Encapsulation in C++" }, { "code": null, "e": 22588, "s": 22569, "text": "Abstraction in C++" }, { "code": null, "e": 22614, "s": 22588, "text": "Structure vs class in C++" }, { "code": null, "e": 22659, "s": 22614, "text": "Can a C++ class have an object of self type?" }, { "code": null, "e": 22710, "s": 22659, "text": "Why is the Size of an Empty Class Not Zero in C++?" }, { "code": null, "e": 22737, "s": 22710, "text": "Static data members in C++" }, { "code": null, "e": 22797, "s": 22737, "text": "Some interesting facts about static member functions in C++" }, { "code": null, "e": 22830, "s": 22797, "text": "Friend class and function in C++" }, { "code": null, "e": 22851, "s": 22830, "text": "Local Classes in C++" }, { "code": null, "e": 22873, "s": 22851, "text": "Nested Classes in C++" }, { "code": null, "e": 22903, "s": 22873, "text": "Simulating final Class in C++" }, { "code": null, "e": 22923, "s": 22903, "text": "Constructors in C++" }, { "code": null, "e": 22947, "s": 22923, "text": "Copy Constructor in C++" }, { "code": null, "e": 22966, "s": 22947, "text": "Destructors in C++" }, { "code": null, "e": 22985, "s": 22966, "text": "Virtual Destructor" }, { "code": null, "e": 23016, "s": 22985, "text": "Pure Virtual Destructor in C++" }, { "code": null, "e": 23032, "s": 23016, "text": "Arrays in C/C++" }, { "code": null, "e": 23110, "s": 23032, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 23133, "s": 23110, "text": "std::sort() in C++ STL" }, { "code": null, "e": 23160, "s": 23133, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 23199, "s": 23160, "text": "What is Memory Leak? How can we avoid?" }, { "code": null, "e": 23231, "s": 23199, "text": "Undefined Behavior in C and C++" }, { "code": null, "e": 23267, "s": 23231, "text": "Name Mangling and extern “C” in C++" }, { "code": null, "e": 23305, "s": 23267, "text": "How does ‘void*’ differ in C and C++?" }, { "code": null, "e": 23366, "s": 23305, "text": "Write a program that produces different results in C and C++" }, { "code": null, "e": 23417, "s": 23366, "text": "Type difference of character literals in C and C++" }, { "code": null, "e": 23468, "s": 23417, "text": "Difference Between C Structures and C++ Structures" }, { "code": null, "e": 23541, "s": 23468, "text": "Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)" }, { "code": null, "e": 23565, "s": 23541, "text": "Virtual Function in C++" }, { "code": null, "e": 23585, "s": 23565, "text": "Polymorphism in C++" }, { "code": null, "e": 23606, "s": 23585, "text": "Encapsulation in C++" }, { "code": null, "e": 23625, "s": 23606, "text": "Abstraction in C++" }, { "code": null, "e": 23651, "s": 23625, "text": "Structure vs class in C++" }, { "code": null, "e": 23696, "s": 23651, "text": "Can a C++ class have an object of self type?" }, { "code": null, "e": 23747, "s": 23696, "text": "Why is the Size of an Empty Class Not Zero in C++?" }, { "code": null, "e": 23774, "s": 23747, "text": "Static data members in C++" }, { "code": null, "e": 23834, "s": 23774, "text": "Some interesting facts about static member functions in C++" }, { "code": null, "e": 23867, "s": 23834, "text": "Friend class and function in C++" }, { "code": null, "e": 23888, "s": 23867, "text": "Local Classes in C++" }, { "code": null, "e": 23910, "s": 23888, "text": "Nested Classes in C++" }, { "code": null, "e": 23940, "s": 23910, "text": "Simulating final Class in C++" }, { "code": null, "e": 23960, "s": 23940, "text": "Constructors in C++" }, { "code": null, "e": 23984, "s": 23960, "text": "Copy Constructor in C++" }, { "code": null, "e": 24003, "s": 23984, "text": "Destructors in C++" }, { "code": null, "e": 24022, "s": 24003, "text": "Virtual Destructor" }, { "code": null, "e": 24053, "s": 24022, "text": "Pure Virtual Destructor in C++" }, { "code": null, "e": 24069, "s": 24053, "text": "Arrays in C/C++" }, { "code": null, "e": 24147, "s": 24069, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 24170, "s": 24147, "text": "std::sort() in C++ STL" }, { "code": null, "e": 24197, "s": 24170, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 24236, "s": 24197, "text": "What is Memory Leak? How can we avoid?" }, { "code": null, "e": 24260, "s": 24236, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 24675, "s": 24260, "text": "When we run a code, sometimes we see absurd results instead of expected output. So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended. Whenever the result of an executing program is unpredictable, it is said to have undefined behavior. " }, { "code": null, "e": 24885, "s": 24675, "text": "As a C programmer, understanding undefined behavior is very important for optimal coding and for the program to yield a good efficiency, especially when it comes to there are C codes embedded in system design." }, { "code": null, "e": 24902, "s": 24885, "text": "Division By Zero" }, { "code": null, "e": 24953, "s": 24902, "text": "int val = 5;\nreturn val / 0; // undefined behavior" }, { "code": null, "e": 24993, "s": 24953, "text": "Memory accesses outside of array bounds" }, { "code": null, "e": 25085, "s": 24993, "text": "int arr[4] = {0, 1, 2, 3};\nreturn arr[5]; // undefined behavior for indexing out of bounds" }, { "code": null, "e": 25109, "s": 25085, "text": "Signed integer overflow" }, { "code": null, "e": 25173, "s": 25109, "text": "int x = INT_MAX;\nprintf(\"%d\", x + 1); // undefined behavior" }, { "code": null, "e": 25198, "s": 25173, "text": "Null pointer dereference" }, { "code": null, "e": 25285, "s": 25198, "text": "val = 0;\nint ptr = *val; // undefined behavior for dereferencing a null pointer" }, { "code": null, "e": 25316, "s": 25285, "text": "Modification of string literal" }, { "code": null, "e": 25393, "s": 25316, "text": "char* s = \"geeksforgeeks\";\ns[0] = 'e'; // undefined behavior " }, { "code": null, "e": 25424, "s": 25393, "text": "Accessing a NULL Pointer, etc." }, { "code": null, "e": 25511, "s": 25424, "text": "int* ptr = NULL;\nprintf(\"%d\", *ptr); // undefined behavior for accessing NULL Pointer" }, { "code": null, "e": 25636, "s": 25511, "text": "Sometimes compilers may diagnose simple errors, however, sometimes they are not designed to diagnose the undefined behavior." }, { "code": null, "e": 25705, "s": 25636, "text": "Following are some C/C++ programs that showcase undefined behavior: " }, { "code": null, "e": 25716, "s": 25705, "text": "Program 1:" }, { "code": null, "e": 25718, "s": 25716, "text": "C" }, { "code": "// C Program to demonstrate// division by 0 #include <stdio.h> // Driver Codeint main(){ int x = 25, y = 0; int z = x / y; printf(\"%d\", z); return 0;}", "e": 25881, "s": 25718, "text": null }, { "code": null, "e": 25892, "s": 25881, "text": "Program 2:" }, { "code": null, "e": 25894, "s": 25892, "text": "C" }, { "code": "// C Program to demonstrate// Uninitialized variables #include <stdio.h> // Driver Codeint main(){ bool val; if (val) printf(\"TRUE\"); else printf(\"FALSE\");}", "e": 26074, "s": 25894, "text": null }, { "code": null, "e": 26085, "s": 26074, "text": "Program 3:" }, { "code": null, "e": 26087, "s": 26085, "text": "C" }, { "code": "// C Program to demonstrate// accessing value of NULL// pointer #include <stdio.h> // Driver Codeint main(){ int* ptr = NULL; printf(\"%d\", *ptr); return 0;}", "e": 26253, "s": 26087, "text": null }, { "code": null, "e": 26264, "s": 26253, "text": "Program 4:" }, { "code": null, "e": 26266, "s": 26264, "text": "C" }, { "code": "// C program to demonstrate// accessing out of bound #include <stdio.h> // Driver Codeint main(){ int arr[5]; // We access arr[5] in last iteration. for (int i = 0; i <= 5; i++) printf(\"%d \", arr[i]);}", "e": 26485, "s": 26266, "text": null }, { "code": null, "e": 26496, "s": 26485, "text": "Program 5:" }, { "code": null, "e": 26498, "s": 26496, "text": "C" }, { "code": "// C Program to demonstrate going// beyond limit of signed int #include <stdio.h> // Driver Codeint main(){ int x = INT_MAX; printf(\"%d\", x + 1); return 0;}", "e": 26664, "s": 26498, "text": null }, { "code": null, "e": 26675, "s": 26664, "text": "Program 6:" }, { "code": null, "e": 26677, "s": 26675, "text": "C" }, { "code": "// C Program to demonstrate trying to// modify a string literal #include <stdio.h> // Driver Codeint main(){ char* s = \"geeksforgeeks\"; s[0] = 'e'; return 0;}", "e": 26845, "s": 26677, "text": null }, { "code": null, "e": 26856, "s": 26845, "text": "Program 7:" }, { "code": null, "e": 26858, "s": 26856, "text": "C" }, { "code": "// C Program to demonstrate modifying a variable// multiple times before a defined// sequence point #include <stdio.h> // Driver Codeint main(){ int i = 8; int p = i++ * i++; printf(\"%d\\n\", p);}", "e": 27062, "s": 26858, "text": null }, { "code": null, "e": 27065, "s": 27062, "text": "72" }, { "code": null, "e": 27210, "s": 27065, "text": "Explanation: The program produces 72 as output in most of the compilers, but implementing software based on this assumption is not a good idea. " }, { "code": null, "e": 27407, "s": 27210, "text": "The output of all of the above programs is unpredictable (or undefined). The compilers (implementing the C/C++ standard) are free to do anything as these are undefined by the C and C++ standards. " }, { "code": null, "e": 27729, "s": 27407, "text": "Language like Java, trap errors as soon as they are found but languages like C and C++ in a few cases keep on executing the code in a faulty manner which may result in unpredictable results. The program can crash with any type of error message, or it can unknowingly corrupt the data which is a grave issue to deal with. " }, { "code": null, "e": 28046, "s": 27729, "text": "Importance of knowing about Undefined Behavior: If a user starts learning in a C/C++ environment and is unclear with the concept of undefined behavior then that can bring plenty of problems in the future like while debugging someone else’s code might be actually difficult in tracing the root to the undefined error." }, { "code": null, "e": 28093, "s": 28046, "text": "Risks and Disadvantages of Undefined Behavior " }, { "code": null, "e": 28404, "s": 28093, "text": "The programmers sometimes rely on a particular implementation (or compiler) of undefined behavior which may cause problems when the compiler is changed/upgraded. For example, the last program produces 72 as output in most of the compilers, but implementing software based on this assumption is not a good idea." }, { "code": null, "e": 28568, "s": 28404, "text": "Undefined behaviors may also cause security vulnerabilities, especially due to the cases when an array out of bound is not checked (causes buffer overflow attack)." }, { "code": null, "e": 28602, "s": 28568, "text": "Advantages of Undefined Behavior " }, { "code": null, "e": 29069, "s": 28602, "text": "C and C++ have undefined behaviors because it allows compilers to avoid lots of checks. Suppose a set of code with a greater performing array need not keep a look at the bounds, which avoids the need for a complex optimization pass to check such conditions outside loops. The tightly bound loops and speed up the program from thirty to fifty percent when it gains an advantage of the undefined nature of signed overflow, which is generally offered by the C compiler." }, { "code": null, "e": 29257, "s": 29069, "text": "We also have another advantage of this as it allows us to store a variable’s value in a processor register and manipulate it over time that is larger than the variable in the source code." }, { "code": null, "e": 29418, "s": 29257, "text": "It also helps in wrap-around then compile-time checks which would not be possible without the greater knowledge of the undefined behavior in the C/C++ compiler." }, { "code": null, "e": 29456, "s": 29418, "text": "More Examples of undefined behavior " }, { "code": null, "e": 29684, "s": 29456, "text": "Sequence Points in C | Set 1“delete this” in C++Passing NULL to printf in CAccessing array out of bounds in C/C++Use of realloc()Execution of printf with ++ operatorsVirtual destruction using shared_ptr in C++Virtual Destructor" }, { "code": null, "e": 29713, "s": 29684, "text": "Sequence Points in C | Set 1" }, { "code": null, "e": 29734, "s": 29713, "text": "“delete this” in C++" }, { "code": null, "e": 29762, "s": 29734, "text": "Passing NULL to printf in C" }, { "code": null, "e": 29801, "s": 29762, "text": "Accessing array out of bounds in C/C++" }, { "code": null, "e": 29818, "s": 29801, "text": "Use of realloc()" }, { "code": null, "e": 29899, "s": 29818, "text": "Execution of printf with ++ operatorsVirtual destruction using shared_ptr in C++" }, { "code": null, "e": 29918, "s": 29899, "text": "Virtual Destructor" }, { "code": null, "e": 29932, "s": 29918, "text": "chhabradhanvi" }, { "code": null, "e": 29946, "s": 29932, "text": "anshikajain26" }, { "code": null, "e": 29959, "s": 29946, "text": "cpp-advanced" }, { "code": null, "e": 29970, "s": 29959, "text": "C Language" }, { "code": null, "e": 29974, "s": 29970, "text": "C++" }, { "code": null, "e": 29978, "s": 29974, "text": "CPP" }, { "code": null, "e": 30076, "s": 29978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30085, "s": 30076, "text": "Comments" }, { "code": null, "e": 30098, "s": 30085, "text": "Old Comments" }, { "code": null, "e": 30133, "s": 30098, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 30165, "s": 30133, "text": "Command line arguments in C/C++" }, { "code": null, "e": 30193, "s": 30165, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 30205, "s": 30193, "text": "fork() in C" }, { "code": null, "e": 30245, "s": 30205, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 30263, "s": 30245, "text": "Vector in C++ STL" }, { "code": null, "e": 30282, "s": 30263, "text": "Inheritance in C++" }, { "code": null, "e": 30310, "s": 30282, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30356, "s": 30310, "text": "Initialize a vector in C++ (6 different ways)" } ]
Amazon SageMaker Fast File Mode. Methods for Streaming Training Data... | by Chaim Rand | Towards Data Science
Last year we published a blog post in which we surveyed different methods for streaming training data stored in Amazon S3 into an Amazon SageMaker training session. We highlighted some of the strengths and weaknesses of the different options and examined their ability to address some specific needs such as: dynamic boosting, which requires changing how the data is sampled mid-training,the freedom to choose data formats other than the TFRecord format, andrandom access to data records. dynamic boosting, which requires changing how the data is sampled mid-training, the freedom to choose data formats other than the TFRecord format, and random access to data records. Last month AWS announced a new mechanism called Fast File Mode (FFM) for training in Amazon SageMaker with data from Amazon S3. In this post we will review some of the properties of this new method and compare it to some of the alternative methods we reviewed in our previous post. As in our previous post, the scenario we address is one in which the size of our dataset is so large that it is either impossible or inefficient to download it in its entirety to a local disk before training. Instead, we stream the data directly from S3 into the training loop. We will focus on training in TensorFlow, specifically version 2.6, although most of the observations we will make are just as relevant to other training frameworks, as well. To program your Amazon SageMaker training session to stream data from S3 using Fast File Mode you need to set the input_mode to FastFile and enter your dataset S3 path(s) to the fit function, as shown in the code block below: from sagemaker.tensorflow import TensorFlowestimator=TensorFlow(entry_point='main.py', role=<AWS IAM role>, py_version='py37', framework_version='2.6.0', #tf version instance_count=1, instance_type='ml.g4dn.xlarge', input_mode='FastFile' )train_data="s3://sagemaker-path-to-train-data"test_data="s3://sagemaker-path-to-test-data"estimator.fit({'train':train_data, 'test':test_data}) Here we have defined two channels named train and test. The training job will start up with two environment variables SM_CHANNEL_TRAIN and SM_CHANNEL_TEST corresponding to the two data channels. Each will be set to a local path that appears to the training application as a POSIX file system mount of all of the data within programmed paths in S3. Thus, in order to access a file at s3://sagemaker-path-to-train-data/relative-path, rather than downloading the file (e.g. using boto3) the training application would simply open:path=os.path.join(os.environ["SM_CHANNEL_TRAIN"],<relative-path>)For example, if your files are stored in TFRecord format you could use TFRecordDataset to create a dataset as in the code block below: paths=[<list of relative filepaths>]local_root=os.environ["SM_CHANNEL_TRAIN"]filepaths=[os.path.join(local_root,path) for path in paths]ds=tf.data.TFRecordDataset( filepaths, num_parallel_reads=tf.data.experimental.AUTOTUNE) In our previous blog post we covered several options for streaming data from S3 into an Amazon SageMaker training session. In this section we highlight some of the advantages of FFM compared to other methods, with particular focus on the Amazon SageMaker Pipe Mode alternative. For more details on Pipe Mode check out this previous post. As we have discussed in the past, the number of data streams that is supported by Pipe Mode is limited to 20 (as of the time of this writing). Using multiple data streams can solve certain needs such as data partitioning (where we partition data according to class) or stream duplication (e.g. streaming the same dataset with unique shuffling to multiple processes when performing data distributed training). As detailed in this blog post, the restriction on the number of channel streams can pose a challenge that may require creativity to overcome. With FFM, multiple datasets can be defined using a single data channel configuration. All you need to do is to configure the channel’s base S3 path to be the root of all the datasets. When you program a job to use Pipe Mode you configure a fixed set of files to be streamed through the pipe and may optionally delegate shuffling and/or sharding to the pipe mode manager. Once the training starts you cannot change the contents of the pipe or its configuration. Relative to pipe mode, FFM offers far greater control: Shuffling — you can apply your own data shuffling policy as well as capture the randomly generated parameters. Sharding — you can define your own sharding policy. Updating dataset contents during training — you can change the mixture of the data while the model is training. File chunk support — FFM supports reading a portion of a file without pulling the entire file. This may have implications on your choice of file format for your data in S3 as some formats rely on file chunking. Note that while file chunking could be used (assuming an appropriate file format) to implement random access to data records, this may have severe implications on performance. However, you could implement some level of random access by analyzing the minimum acceptable chunk size for your machine learning project. In the code block below we demonstrate how a custom generator can be created that controls (and records) shuffling, sharding, and changing the data mixture mid-training. import randomdef generator(): paths=... # optionally shard filepaths for e in range(num_epochs): seed=random.randrange(100) print(f"starting epoch {e}. Random seed is {seed}") random.seed(seed) random.shuffle(paths) # optionally modify contents based on current metrics paths=... for p in paths: yield pfilepaths_ds=tf.data.Dataset.from_generator( generator, output_types=tf.string, output_shapes=())ds=tf.data.TFRecordDataset( filepaths_ds, num_parallel_reads=tf.data.experimental.AUTOTUNE) See here for an example of how to employ this scheme to implement dynamic boosting with two classes. While Pipe Mode can be configured to stream any binary data, and thus any file format, the high level Amazon SageMaker SDK provides support only for the TFRecord file format, via the PipeModeDataset. Using any other file format with pipe mode would require a bit of effort. Contrary to pipe mode, FFM does not favor any file format over the other.In a previous post, we surveyed several different file format options for training in TensorFlow. Using FFM you are free to use any one of them. Keep in mind that there are best practices for storing files in the cloud. In particular, these practices dictate optimal file sizes. We typically store our data in files with sizes that are a few hundred MB.Another consideration is the number of files. According to the FFM documentation, the training start up time may be impacted by the total number of files. As demonstrated above, when using FFM we can use the same standard TensorFlow dataset classes that we would use in a local environment. This is contrary to pipe mode that requires a special custom dataset, PIPEmodeDataset. This has several implications: Easier to program — fewer modifications are required to adapt your code from a local training session to a cloud based training session. Easier to debug — the similarity to a local run makes it easier to debug issues. API support — the use of standardized TensorFlow datasets means automatic support for all TensorFlow dataset utility APIs. In this section we provide a performance comparison between FFM, Pipe Mode, and direct S3 access on a dataset comprised of TFRecord files. The metrics we have compared are: 1. the average data throughput, measured in the number of records per second, and 2. the average CPU utilization. Measuring the CPU utilization is important in order to assess the degree to which the input mode might contribute to potential CPU bottlenecks. The code we have used to perform the test can be found in the code block below: count = 0begin = time.time()stime = beginfor x in ds: count = count + 1 if count % 1000 == 0: etime = time.time() print(f"step: {count} step/sec: {float(1000)/(etime-stime)}") stime = time.time() if count==100000: breakprint(f"average step/sec: {float(100000)/(time.time()-stime)}") Note that we isolate our analysis to the data input portion of the pipeline by iterating over the dataset without actually feeding the data into the training pipeline. The tests were performed on an ml.c5.xlarge instance type. The results are shared in the chart below. In the test we have run, FFM has the best (lowest) step time with Pipe Mode coming in at a close second. At the same time, note the increase in CPU utilization. These results are provided as one example of the type of comparative metrics you might see. These metrics may be highly dependent on your model architecture and the results you get may be very different. For example, if your step time is currently solely determined by your GPU activity, you may be wholly indifferent to the data input mode. The recently announced Amazon SageMaker Fast File Mode provides a new method for efficient streaming of training data directly into an Amazon SageMaker training session. It offers the potential performance of Pipe Mode combined with the conveniences and flexibility of a local dataset. Importantly, every machine learning project is unique; performance behaviors observed in one model may be wholly different than those observed in another. It is critical that you evaluate the performance impact of adopting FFM before converting your project and recommended that you code your solution in a way that makes switching between streaming options easy. Best of luck!
[ { "code": null, "e": 481, "s": 172, "text": "Last year we published a blog post in which we surveyed different methods for streaming training data stored in Amazon S3 into an Amazon SageMaker training session. We highlighted some of the strengths and weaknesses of the different options and examined their ability to address some specific needs such as:" }, { "code": null, "e": 661, "s": 481, "text": "dynamic boosting, which requires changing how the data is sampled mid-training,the freedom to choose data formats other than the TFRecord format, andrandom access to data records." }, { "code": null, "e": 741, "s": 661, "text": "dynamic boosting, which requires changing how the data is sampled mid-training," }, { "code": null, "e": 812, "s": 741, "text": "the freedom to choose data formats other than the TFRecord format, and" }, { "code": null, "e": 843, "s": 812, "text": "random access to data records." }, { "code": null, "e": 1125, "s": 843, "text": "Last month AWS announced a new mechanism called Fast File Mode (FFM) for training in Amazon SageMaker with data from Amazon S3. In this post we will review some of the properties of this new method and compare it to some of the alternative methods we reviewed in our previous post." }, { "code": null, "e": 1577, "s": 1125, "text": "As in our previous post, the scenario we address is one in which the size of our dataset is so large that it is either impossible or inefficient to download it in its entirety to a local disk before training. Instead, we stream the data directly from S3 into the training loop. We will focus on training in TensorFlow, specifically version 2.6, although most of the observations we will make are just as relevant to other training frameworks, as well." }, { "code": null, "e": 1803, "s": 1577, "text": "To program your Amazon SageMaker training session to stream data from S3 using Fast File Mode you need to set the input_mode to FastFile and enter your dataset S3 path(s) to the fit function, as shown in the code block below:" }, { "code": null, "e": 2325, "s": 1803, "text": "from sagemaker.tensorflow import TensorFlowestimator=TensorFlow(entry_point='main.py', role=<AWS IAM role>, py_version='py37', framework_version='2.6.0', #tf version instance_count=1, instance_type='ml.g4dn.xlarge', input_mode='FastFile' )train_data=\"s3://sagemaker-path-to-train-data\"test_data=\"s3://sagemaker-path-to-test-data\"estimator.fit({'train':train_data, 'test':test_data})" }, { "code": null, "e": 3052, "s": 2325, "text": "Here we have defined two channels named train and test. The training job will start up with two environment variables SM_CHANNEL_TRAIN and SM_CHANNEL_TEST corresponding to the two data channels. Each will be set to a local path that appears to the training application as a POSIX file system mount of all of the data within programmed paths in S3. Thus, in order to access a file at s3://sagemaker-path-to-train-data/relative-path, rather than downloading the file (e.g. using boto3) the training application would simply open:path=os.path.join(os.environ[\"SM_CHANNEL_TRAIN\"],<relative-path>)For example, if your files are stored in TFRecord format you could use TFRecordDataset to create a dataset as in the code block below:" }, { "code": null, "e": 3306, "s": 3052, "text": "paths=[<list of relative filepaths>]local_root=os.environ[\"SM_CHANNEL_TRAIN\"]filepaths=[os.path.join(local_root,path) for path in paths]ds=tf.data.TFRecordDataset( filepaths, num_parallel_reads=tf.data.experimental.AUTOTUNE)" }, { "code": null, "e": 3644, "s": 3306, "text": "In our previous blog post we covered several options for streaming data from S3 into an Amazon SageMaker training session. In this section we highlight some of the advantages of FFM compared to other methods, with particular focus on the Amazon SageMaker Pipe Mode alternative. For more details on Pipe Mode check out this previous post." }, { "code": null, "e": 4379, "s": 3644, "text": "As we have discussed in the past, the number of data streams that is supported by Pipe Mode is limited to 20 (as of the time of this writing). Using multiple data streams can solve certain needs such as data partitioning (where we partition data according to class) or stream duplication (e.g. streaming the same dataset with unique shuffling to multiple processes when performing data distributed training). As detailed in this blog post, the restriction on the number of channel streams can pose a challenge that may require creativity to overcome. With FFM, multiple datasets can be defined using a single data channel configuration. All you need to do is to configure the channel’s base S3 path to be the root of all the datasets." }, { "code": null, "e": 4711, "s": 4379, "text": "When you program a job to use Pipe Mode you configure a fixed set of files to be streamed through the pipe and may optionally delegate shuffling and/or sharding to the pipe mode manager. Once the training starts you cannot change the contents of the pipe or its configuration. Relative to pipe mode, FFM offers far greater control:" }, { "code": null, "e": 4822, "s": 4711, "text": "Shuffling — you can apply your own data shuffling policy as well as capture the randomly generated parameters." }, { "code": null, "e": 4874, "s": 4822, "text": "Sharding — you can define your own sharding policy." }, { "code": null, "e": 4986, "s": 4874, "text": "Updating dataset contents during training — you can change the mixture of the data while the model is training." }, { "code": null, "e": 5512, "s": 4986, "text": "File chunk support — FFM supports reading a portion of a file without pulling the entire file. This may have implications on your choice of file format for your data in S3 as some formats rely on file chunking. Note that while file chunking could be used (assuming an appropriate file format) to implement random access to data records, this may have severe implications on performance. However, you could implement some level of random access by analyzing the minimum acceptable chunk size for your machine learning project." }, { "code": null, "e": 5682, "s": 5512, "text": "In the code block below we demonstrate how a custom generator can be created that controls (and records) shuffling, sharding, and changing the data mixture mid-training." }, { "code": null, "e": 6323, "s": 5682, "text": "import randomdef generator(): paths=... # optionally shard filepaths for e in range(num_epochs): seed=random.randrange(100) print(f\"starting epoch {e}. Random seed is {seed}\") random.seed(seed) random.shuffle(paths) # optionally modify contents based on current metrics paths=... for p in paths: yield pfilepaths_ds=tf.data.Dataset.from_generator( generator, output_types=tf.string, output_shapes=())ds=tf.data.TFRecordDataset( filepaths_ds, num_parallel_reads=tf.data.experimental.AUTOTUNE)" }, { "code": null, "e": 6424, "s": 6323, "text": "See here for an example of how to employ this scheme to implement dynamic boosting with two classes." }, { "code": null, "e": 6916, "s": 6424, "text": "While Pipe Mode can be configured to stream any binary data, and thus any file format, the high level Amazon SageMaker SDK provides support only for the TFRecord file format, via the PipeModeDataset. Using any other file format with pipe mode would require a bit of effort. Contrary to pipe mode, FFM does not favor any file format over the other.In a previous post, we surveyed several different file format options for training in TensorFlow. Using FFM you are free to use any one of them." }, { "code": null, "e": 7279, "s": 6916, "text": "Keep in mind that there are best practices for storing files in the cloud. In particular, these practices dictate optimal file sizes. We typically store our data in files with sizes that are a few hundred MB.Another consideration is the number of files. According to the FFM documentation, the training start up time may be impacted by the total number of files." }, { "code": null, "e": 7533, "s": 7279, "text": "As demonstrated above, when using FFM we can use the same standard TensorFlow dataset classes that we would use in a local environment. This is contrary to pipe mode that requires a special custom dataset, PIPEmodeDataset. This has several implications:" }, { "code": null, "e": 7670, "s": 7533, "text": "Easier to program — fewer modifications are required to adapt your code from a local training session to a cloud based training session." }, { "code": null, "e": 7751, "s": 7670, "text": "Easier to debug — the similarity to a local run makes it easier to debug issues." }, { "code": null, "e": 7874, "s": 7751, "text": "API support — the use of standardized TensorFlow datasets means automatic support for all TensorFlow dataset utility APIs." }, { "code": null, "e": 8385, "s": 7874, "text": "In this section we provide a performance comparison between FFM, Pipe Mode, and direct S3 access on a dataset comprised of TFRecord files. The metrics we have compared are: 1. the average data throughput, measured in the number of records per second, and 2. the average CPU utilization. Measuring the CPU utilization is important in order to assess the degree to which the input mode might contribute to potential CPU bottlenecks. The code we have used to perform the test can be found in the code block below:" }, { "code": null, "e": 8683, "s": 8385, "text": "count = 0begin = time.time()stime = beginfor x in ds: count = count + 1 if count % 1000 == 0: etime = time.time() print(f\"step: {count} step/sec: {float(1000)/(etime-stime)}\") stime = time.time() if count==100000: breakprint(f\"average step/sec: {float(100000)/(time.time()-stime)}\")" }, { "code": null, "e": 9456, "s": 8683, "text": "Note that we isolate our analysis to the data input portion of the pipeline by iterating over the dataset without actually feeding the data into the training pipeline. The tests were performed on an ml.c5.xlarge instance type. The results are shared in the chart below. In the test we have run, FFM has the best (lowest) step time with Pipe Mode coming in at a close second. At the same time, note the increase in CPU utilization. These results are provided as one example of the type of comparative metrics you might see. These metrics may be highly dependent on your model architecture and the results you get may be very different. For example, if your step time is currently solely determined by your GPU activity, you may be wholly indifferent to the data input mode." } ]
Kth Frequency | Practice | GeeksforGeeks
Geek hosted a coding competition, some of the questions were easy and some of them were hard. You are given an array arr of positive integers of size N and an integer K, arr[i] represents the hardness of each problem of geeks' contest. Among those N numbers, your task is to find the numbers which appear more than K times and print them in increasing order. If no number appears more than K times than print -1. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains two space-separated integers N and K. 3. The second line contains N space-separated positive integers represents array arr. Output: For each test case, print the maximum number of chocolates you can collect Constraints: 1. 1 <= T <= 10 2. 1 <= K, N <= 100000 3. 1 <= arr[i] <= 10^9 Example: Input: 3 3 1 5 5 6 6 1 2 2 3 3 4 4 4 2 1 2 2 3 Output: 5 2 3 4 -1 Explanation: Test case 1: The only problem with hardness 5 appears more than once +1 avinav26113 months ago Easy C++ Solution +1 rohanpandey7493 months ago Simple use of map and vector: #include<iostream>; #include<bits/stdc++.h>; using namespace std; int main() { //code int t; cin >> t; while(t--){ int n,k; cin >> n >> k; int a[n]; for(int i=0;i<n;i++){ cin >> a[i]; } vector<int>answer; map<int,int>mp; for(int i=0;i<n;i++){ mp[a[i]]++; } for(auto it:mp){ if(it.second>k){ answer.push_back(it.first); } } if(answer.size()==0){ answer.push_back(-1); } for(int i=0;i<answer.size();i++){ cout << answer[i] << " "; } cout << "\n"; } return 0; } 0 am79041ak3 months ago Don't use Freq Array, it gives runtime error(I think bcz of using more memory). Instead use a frequency map to get A.C. Here is my Java Code. class GFG { public static void main (String[] args) { //code Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ Map<Integer,Integer> mp=new HashMap<>(); List<Integer> ans=new ArrayList<>(); int n=sc.nextInt(); int k=sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); if(mp.get(arr[i])==null) mp.put(arr[i],1); else { int pos=mp.get(arr[i]); mp.put(arr[i],pos+1); } } for(int key:mp.keySet()){ if(mp.get(key)>k) ans.add(key); } if(ans.size()==0) System.out.print(-1); for(int e:ans) System.out.print(e + " "); System.out.println(); } } } 0 imranwahid6 months ago Easy C++ solution +1 imranwahid6 months ago Easy C++ solution +1 badgujarsachin836 months ago #include<iostream> #include<map> #include<vector> using namespace std; int main() { //code int t; cin>>t; while(t--){ int n,k; cin>>n>>k; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } map<int,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } vector<int> v; for(auto it:mp) { if(it.second>k){ v.push_back(it.first); cout<<it.first<<" "; } } if(v.empty()){ cout<<-1; } cout<<endl; } return 0; } -1 aakashrarya19977 months ago Output: For each test case, print the maximum number of chocolates you can collect There is no concept related to chocolates ,this problem based on hardness of problem... 0 Aaryan Rawat7 months ago Aaryan Rawat in one of the Test Case input is 8 31 2 1 8 1 6 9 5 no value for t what to do there ? 0 ANAS MALVAT9 months ago ANAS MALVAT int main() {//codeint T;cin >> T;while(T--){ int N, K; cin >> N >> K; int arr[N]; map <int,int> mp; for(int i = 0 ; i < N ; i ++) { cin >> arr[i]; mp[arr[i]] ++; } int flag = 1; for(auto i: mp) { if(i.second > K) { flag = 0; cout<<i.first<<" ";="" }="" }="" if(flag)="" cout<<-1;="" cout<<endl;="" }="" return="" 0;="" <="" code=""> +1 soumik9 months ago soumik def kfreq(arr,n,k): d={} for num in arr: d.setdefault(num,0) d[num]+=1 res={key:value for (key,value) in d.items() if value>k} if bool(res)==True: print(*sorted(list(res))) else: print(-1)t=int(input())for i in range(t): n,k=input().split() n=int(n) k=int(k) arr=list(map(int,input().split())) kfreq(arr,n,k) 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": 651, "s": 238, "text": "Geek hosted a coding competition, some of the questions were easy and some of them were hard. You are given an array arr of positive integers of size N and an integer K, arr[i] represents the hardness of each problem of geeks' contest. Among those N numbers, your task is to find the numbers which appear more than K times and print them in increasing order. If no number appears more than K times than print -1." }, { "code": null, "e": 1181, "s": 651, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains two space-separated integers N and K.\n3. The second line contains N space-separated positive integers represents array arr.\n\nOutput: For each test case, print the maximum number of chocolates you can collect\n\nConstraints:\n1. 1 <= T <= 10\n2. 1 <= K, N <= 100000\n3. 1 <= arr[i] <= 10^9\n\nExample:\nInput:\n3\n3 1\n5 5 6\n6 1\n2 2 3 3 4 4\n4 2\n1 2 2 3" }, { "code": null, "e": 1200, "s": 1181, "text": "Output:\n5\n2 3 4\n-1" }, { "code": null, "e": 1282, "s": 1200, "text": "Explanation:\nTest case 1: The only problem with hardness 5 appears more than once" }, { "code": null, "e": 1285, "s": 1282, "text": "+1" }, { "code": null, "e": 1308, "s": 1285, "text": "avinav26113 months ago" }, { "code": null, "e": 1326, "s": 1308, "text": "Easy C++ Solution" }, { "code": null, "e": 1331, "s": 1328, "text": "+1" }, { "code": null, "e": 1358, "s": 1331, "text": "rohanpandey7493 months ago" }, { "code": null, "e": 1389, "s": 1358, "text": "Simple use of map and vector: " }, { "code": null, "e": 2083, "s": 1389, "text": "#include<iostream>;\n#include<bits/stdc++.h>;\nusing namespace std;\nint main()\n {\n\t//code\n int t;\n cin >> t;\n while(t--){\n int n,k;\n cin >> n >> k;\n int a[n];\n for(int i=0;i<n;i++){\n cin >> a[i];\n }\n vector<int>answer;\n map<int,int>mp;\n for(int i=0;i<n;i++){\n mp[a[i]]++;\n }\n for(auto it:mp){\n if(it.second>k){\n answer.push_back(it.first);\n }\n }\n if(answer.size()==0){\n answer.push_back(-1);\n }\n for(int i=0;i<answer.size();i++){\n cout << answer[i] << \" \";\n }\n cout << \"\\n\";\n }\n\treturn 0;\n}" }, { "code": null, "e": 2085, "s": 2083, "text": "0" }, { "code": null, "e": 2107, "s": 2085, "text": "am79041ak3 months ago" }, { "code": null, "e": 2249, "s": 2107, "text": "Don't use Freq Array, it gives runtime error(I think bcz of using more memory). Instead use a frequency map to get A.C. Here is my Java Code." }, { "code": null, "e": 3007, "s": 2249, "text": "class GFG {\n\tpublic static void main (String[] args) {\n\t\t//code\n\t\tScanner sc=new Scanner(System.in);\n\t\tint t=sc.nextInt();\n\t\twhile(t-->0){\n\t\t\n\t\t Map<Integer,Integer> mp=new HashMap<>();\n\t\t List<Integer> ans=new ArrayList<>();\n\t\t \n\t\t int n=sc.nextInt(); int k=sc.nextInt();\n\t\t int[] arr = new int[n];\n\t\t \n\t\t for(int i=0;i<n;i++){\n\t\t arr[i]=sc.nextInt();\n\t\t if(mp.get(arr[i])==null) mp.put(arr[i],1);\n\t\t else {\n\t\t int pos=mp.get(arr[i]);\n\t\t mp.put(arr[i],pos+1);\n\t\t }\n\t\t }\n\t\t for(int key:mp.keySet()){\n\t\t if(mp.get(key)>k) ans.add(key);\n\t\t }\n\t\t if(ans.size()==0) System.out.print(-1);\n\t\t for(int e:ans) System.out.print(e + \" \");\n\t\t System.out.println();\n\t\t}\n\t}\n}" }, { "code": null, "e": 3009, "s": 3007, "text": "0" }, { "code": null, "e": 3032, "s": 3009, "text": "imranwahid6 months ago" }, { "code": null, "e": 3050, "s": 3032, "text": "Easy C++ solution" }, { "code": null, "e": 3053, "s": 3050, "text": "+1" }, { "code": null, "e": 3076, "s": 3053, "text": "imranwahid6 months ago" }, { "code": null, "e": 3094, "s": 3076, "text": "Easy C++ solution" }, { "code": null, "e": 3097, "s": 3094, "text": "+1" }, { "code": null, "e": 3126, "s": 3097, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 3682, "s": 3126, "text": "#include<iostream>\n#include<map>\n#include<vector>\nusing namespace std;\nint main()\n {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t int n,k;\n\t cin>>n>>k;\n\t int arr[n];\n\t for(int i=0;i<n;i++){\n\t cin>>arr[i];\n\t }\n\t map<int,int> mp;\n\t for(int i=0;i<n;i++){\n\t mp[arr[i]]++;\n\t \n\t }\n\t vector<int> v;\n\t for(auto it:mp)\n\t {\n\t if(it.second>k){\n\t v.push_back(it.first);\n\t cout<<it.first<<\" \";\n\t }\n\t }\n\t if(v.empty()){\n\t cout<<-1;\n\t }\n\t cout<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 3685, "s": 3682, "text": "-1" }, { "code": null, "e": 3713, "s": 3685, "text": "aakashrarya19977 months ago" }, { "code": null, "e": 3797, "s": 3713, "text": "Output: For each test case, print the maximum number of chocolates you can collect " }, { "code": null, "e": 3885, "s": 3797, "text": "There is no concept related to chocolates ,this problem based on hardness of problem..." }, { "code": null, "e": 3887, "s": 3885, "text": "0" }, { "code": null, "e": 3912, "s": 3887, "text": "Aaryan Rawat7 months ago" }, { "code": null, "e": 3925, "s": 3912, "text": "Aaryan Rawat" }, { "code": null, "e": 3977, "s": 3925, "text": "in one of the Test Case input is 8 31 2 1 8 1 6 9 5" }, { "code": null, "e": 4012, "s": 3977, "text": "no value for t what to do there ?" }, { "code": null, "e": 4014, "s": 4012, "text": "0" }, { "code": null, "e": 4038, "s": 4014, "text": "ANAS MALVAT9 months ago" }, { "code": null, "e": 4050, "s": 4038, "text": "ANAS MALVAT" }, { "code": null, "e": 4465, "s": 4050, "text": "int main() {//codeint T;cin >> T;while(T--){ int N, K; cin >> N >> K; int arr[N]; map <int,int> mp; for(int i = 0 ; i < N ; i ++) { cin >> arr[i]; mp[arr[i]] ++; } int flag = 1; for(auto i: mp) { if(i.second > K) { flag = 0; cout<<i.first<<\" \";=\"\" }=\"\" }=\"\" if(flag)=\"\" cout<<-1;=\"\" cout<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 4468, "s": 4465, "text": "+1" }, { "code": null, "e": 4487, "s": 4468, "text": "soumik9 months ago" }, { "code": null, "e": 4494, "s": 4487, "text": "soumik" }, { "code": null, "e": 4865, "s": 4494, "text": "def kfreq(arr,n,k): d={} for num in arr: d.setdefault(num,0) d[num]+=1 res={key:value for (key,value) in d.items() if value>k} if bool(res)==True: print(*sorted(list(res))) else: print(-1)t=int(input())for i in range(t): n,k=input().split() n=int(n) k=int(k) arr=list(map(int,input().split())) kfreq(arr,n,k)" }, { "code": null, "e": 5011, "s": 4865, "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": 5047, "s": 5011, "text": " Login to access your submissions. " }, { "code": null, "e": 5057, "s": 5047, "text": "\nProblem\n" }, { "code": null, "e": 5067, "s": 5057, "text": "\nContest\n" }, { "code": null, "e": 5130, "s": 5067, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5278, "s": 5130, "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": 5486, "s": 5278, "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": 5592, "s": 5486, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Execute a Script in SQLite using Python? - GeeksforGeeks
09 May, 2021 In this article, we are going to see how to execute a script in SQLite using Python. Here we are executing create table and insert records into table scripts through Python. In Python, the sqlite3 module supports SQLite database for storing the data in the database. Step 1: First we need to import the sqlite3 module in Python. import sqlite3 Step 2: Connect to the database by creating the database. We can connect to the database by simply create a database named geeks_db.db or we can simply create a database in our memory by using :memory: Database creation by name connection_object = sqlite3.connect(“database_name.db”) Database creation in Memory: connection_object = sqlite3.connect:memory:) Step 3: Create the cursor object after making the database connection. cursor_object = connection_object.cursor() Step 4: Write the SQL query that can be executable. cursor_object.executescript(“script”) Step 5: Execute the cursor object cursor_object(“sql statement”) Step 6: Get the data inside the table from the database. cursor_object.fetchall() Example 1: Python3 # import sqlite3 moduleimport sqlite3 # create con object to connect # the database geeks_db.dbcon = sqlite3.connect("geeks_db.db") # create the cursor objectcur = con.cursor() # execute the script by creating the # table named geeks_demo and insert the datacur.executescript(""" create table geeks_demo( geek_id, geek_name ); insert into geeks_demo values ( '7058', 'sravan kumar' ); insert into geeks_demo values ( '7059', 'Jyothika' ); insert into geeks_demo values ( '7072', 'Harsha' ); insert into geeks_demo values ( '7075', 'Deepika' ); """) # display the data in the table by # executing the cursor objectcur.execute("SELECT * from geeks_demo") # fetch all the dataprint(cur.fetchall()) Output: Example 2: Python3 # import sqlite3 moduleimport sqlite3 # create con object to connect # the database geeks_db.dbcon = sqlite3.connect("geeks_db.db") # create the cursor objectcur = con.cursor() # execute the script by creating the table# named geeks1 and insert the datacur.executescript(""" create table geeks1( geek_id, geek_name, address ); insert into geeks1 values ( '7058', 'sravan kumar','hyd' ); insert into geeks1 values ( '7059', 'Jyothika' ,'ponnur' ); insert into geeks1 values ( '7072', 'Harsha','chebrolu' ); insert into geeks1 values ( '7075', 'Deepika','tenali' ); """) # display the data in the table by # executing the cursor objectcur.execute("SELECT * from geeks1") # fetch all the dataprint(cur.fetchall()) Output: Picked Python-SQLite Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25555, "s": 25527, "text": "\n09 May, 2021" }, { "code": null, "e": 25822, "s": 25555, "text": "In this article, we are going to see how to execute a script in SQLite using Python. Here we are executing create table and insert records into table scripts through Python. In Python, the sqlite3 module supports SQLite database for storing the data in the database." }, { "code": null, "e": 25884, "s": 25822, "text": "Step 1: First we need to import the sqlite3 module in Python." }, { "code": null, "e": 25899, "s": 25884, "text": "import sqlite3" }, { "code": null, "e": 26101, "s": 25899, "text": "Step 2: Connect to the database by creating the database. We can connect to the database by simply create a database named geeks_db.db or we can simply create a database in our memory by using :memory:" }, { "code": null, "e": 26127, "s": 26101, "text": "Database creation by name" }, { "code": null, "e": 26183, "s": 26127, "text": "connection_object = sqlite3.connect(“database_name.db”)" }, { "code": null, "e": 26212, "s": 26183, "text": "Database creation in Memory:" }, { "code": null, "e": 26257, "s": 26212, "text": "connection_object = sqlite3.connect:memory:)" }, { "code": null, "e": 26328, "s": 26257, "text": "Step 3: Create the cursor object after making the database connection." }, { "code": null, "e": 26371, "s": 26328, "text": "cursor_object = connection_object.cursor()" }, { "code": null, "e": 26423, "s": 26371, "text": "Step 4: Write the SQL query that can be executable." }, { "code": null, "e": 26461, "s": 26423, "text": "cursor_object.executescript(“script”)" }, { "code": null, "e": 26495, "s": 26461, "text": "Step 5: Execute the cursor object" }, { "code": null, "e": 26526, "s": 26495, "text": "cursor_object(“sql statement”)" }, { "code": null, "e": 26583, "s": 26526, "text": "Step 6: Get the data inside the table from the database." }, { "code": null, "e": 26608, "s": 26583, "text": "cursor_object.fetchall()" }, { "code": null, "e": 26619, "s": 26608, "text": "Example 1:" }, { "code": null, "e": 26627, "s": 26619, "text": "Python3" }, { "code": "# import sqlite3 moduleimport sqlite3 # create con object to connect # the database geeks_db.dbcon = sqlite3.connect(\"geeks_db.db\") # create the cursor objectcur = con.cursor() # execute the script by creating the # table named geeks_demo and insert the datacur.executescript(\"\"\" create table geeks_demo( geek_id, geek_name ); insert into geeks_demo values ( '7058', 'sravan kumar' ); insert into geeks_demo values ( '7059', 'Jyothika' ); insert into geeks_demo values ( '7072', 'Harsha' ); insert into geeks_demo values ( '7075', 'Deepika' ); \"\"\") # display the data in the table by # executing the cursor objectcur.execute(\"SELECT * from geeks_demo\") # fetch all the dataprint(cur.fetchall())", "e": 27364, "s": 26627, "text": null }, { "code": null, "e": 27372, "s": 27364, "text": "Output:" }, { "code": null, "e": 27383, "s": 27372, "text": "Example 2:" }, { "code": null, "e": 27391, "s": 27383, "text": "Python3" }, { "code": "# import sqlite3 moduleimport sqlite3 # create con object to connect # the database geeks_db.dbcon = sqlite3.connect(\"geeks_db.db\") # create the cursor objectcur = con.cursor() # execute the script by creating the table# named geeks1 and insert the datacur.executescript(\"\"\" create table geeks1( geek_id, geek_name, address ); insert into geeks1 values ( '7058', 'sravan kumar','hyd' ); insert into geeks1 values ( '7059', 'Jyothika' ,'ponnur' ); insert into geeks1 values ( '7072', 'Harsha','chebrolu' ); insert into geeks1 values ( '7075', 'Deepika','tenali' ); \"\"\") # display the data in the table by # executing the cursor objectcur.execute(\"SELECT * from geeks1\") # fetch all the dataprint(cur.fetchall())", "e": 28153, "s": 27391, "text": null }, { "code": null, "e": 28161, "s": 28153, "text": "Output:" }, { "code": null, "e": 28168, "s": 28161, "text": "Picked" }, { "code": null, "e": 28182, "s": 28168, "text": "Python-SQLite" }, { "code": null, "e": 28189, "s": 28182, "text": "Python" }, { "code": null, "e": 28287, "s": 28189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28319, "s": 28287, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28361, "s": 28319, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28403, "s": 28361, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28459, "s": 28403, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28486, "s": 28459, "text": "Python Classes and Objects" }, { "code": null, "e": 28517, "s": 28486, "text": "Python | os.path.join() method" }, { "code": null, "e": 28546, "s": 28517, "text": "Create a directory in Python" }, { "code": null, "e": 28585, "s": 28546, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28621, "s": 28585, "text": "Python | Pandas dataframe.groupby()" } ]
Jagged Array in Java - GeeksforGeeks
15 Nov, 2021 Prerequisite: Arrays in Java A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as Jagged arrays. Pictorial representation of Jagged array in Memory: Jagged_array Declaration and Initialization of Jagged array : Syntax: data_type array_name[][] = new data_type[n][]; //n: no. of rows array_name[] = new data_type[n1] //n1= no. of columns in row-1 array_name[] = new data_type[n2] //n2= no. of columns in row-2 array_name[] = new data_type[n3] //n3= no. of columns in row-3 . . . array_name[] = new data_type[nk] //nk=no. of columns in row-n Alternative, ways to Initialize a Jagged array : int arr_name[][] = new int[][] { new int[] {10, 20, 30 ,40}, new int[] {50, 60, 70, 80, 90, 100}, new int[] {110, 120} }; OR int[][] arr_name = { new int[] {10, 20, 30 ,40}, new int[] {50, 60, 70, 80, 90, 100}, new int[] {110, 120} }; OR int[][] arr_name = { {10, 20, 30 ,40}, {50, 60, 70, 80, 90, 100}, {110, 120} }; Following are Java programs to demonstrate the above concept. Java // Program to demonstrate 2-D jagged array in Javaclass Main { public static void main(String[] args) { // Declaring 2-D array with 2 rows int arr[][] = new int[2][]; // Making the above array Jagged // First row has 3 columns arr[0] = new int[3]; // Second row has 2 columns arr[1] = new int[2]; // Initializing array int count = 0; for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[i].length; j++) arr[i][j] = count++; // Displaying the values of 2D Jagged array System.out.println("Contents of 2D Jagged Array"); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) System.out.print(arr[i][j] + " "); System.out.println(); } }} Contents of 2D Jagged Array 0 1 2 3 4 Following is another example where i’th row has i columns, i.e., the first row has 1 element, the second row has two elements and so on. Java // Another Java program to demonstrate 2-D jagged// array such that first row has 1 element, second// row has two elements and so on.class Main { public static void main(String[] args) { int r = 5; // Declaring 2-D array with 5 rows int arr[][] = new int[r][]; // Creating a 2D array such that first row // has 1 element, second row has two // elements and so on. for (int i = 0; i < arr.length; i++) arr[i] = new int[i + 1]; // Initializing array int count = 0; for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[i].length; j++) arr[i][j] = count++; // Displaying the values of 2D Jagged array System.out.println("Contents of 2D Jagged Array"); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) System.out.print(arr[i][j] + " "); System.out.println(); } }} Contents of 2D Jagged Array 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 This article is contributed by Rahul Agrawal. 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 madhav_mohan aadarsh baid sweetyty Java-Array-Programs Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Stream In Java Reverse a string in Java Arrays.sort() in Java with examples How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java Generics in Java
[ { "code": null, "e": 30305, "s": 30277, "text": "\n15 Nov, 2021" }, { "code": null, "e": 30334, "s": 30305, "text": "Prerequisite: Arrays in Java" }, { "code": null, "e": 30561, "s": 30334, "text": "A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as Jagged arrays. " }, { "code": null, "e": 30613, "s": 30561, "text": "Pictorial representation of Jagged array in Memory:" }, { "code": null, "e": 30626, "s": 30613, "text": "Jagged_array" }, { "code": null, "e": 30677, "s": 30628, "text": "Declaration and Initialization of Jagged array :" }, { "code": null, "e": 31165, "s": 30677, "text": "Syntax: data_type array_name[][] = new data_type[n][]; //n: no. of rows\n array_name[] = new data_type[n1] //n1= no. of columns in row-1\n array_name[] = new data_type[n2] //n2= no. of columns in row-2\n array_name[] = new data_type[n3] //n3= no. of columns in row-3\n .\n .\n .\n array_name[] = new data_type[nk] //nk=no. of columns in row-n" }, { "code": null, "e": 31216, "s": 31167, "text": "Alternative, ways to Initialize a Jagged array :" }, { "code": null, "e": 32274, "s": 31216, "text": " int arr_name[][] = new int[][] {\n new int[] {10, 20, 30 ,40},\n new int[] {50, 60, 70, 80, 90, 100},\n new int[] {110, 120}\n };\n \n OR \n \n int[][] arr_name = {\n new int[] {10, 20, 30 ,40},\n new int[] {50, 60, 70, 80, 90, 100},\n new int[] {110, 120}\n };\n \n OR \n \n int[][] arr_name = {\n {10, 20, 30 ,40},\n {50, 60, 70, 80, 90, 100},\n {110, 120}\n };" }, { "code": null, "e": 32337, "s": 32274, "text": "Following are Java programs to demonstrate the above concept. " }, { "code": null, "e": 32342, "s": 32337, "text": "Java" }, { "code": "// Program to demonstrate 2-D jagged array in Javaclass Main { public static void main(String[] args) { // Declaring 2-D array with 2 rows int arr[][] = new int[2][]; // Making the above array Jagged // First row has 3 columns arr[0] = new int[3]; // Second row has 2 columns arr[1] = new int[2]; // Initializing array int count = 0; for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[i].length; j++) arr[i][j] = count++; // Displaying the values of 2D Jagged array System.out.println(\"Contents of 2D Jagged Array\"); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) System.out.print(arr[i][j] + \" \"); System.out.println(); } }}", "e": 33185, "s": 32342, "text": null }, { "code": null, "e": 33225, "s": 33185, "text": "Contents of 2D Jagged Array\n0 1 2 \n3 4 " }, { "code": null, "e": 33362, "s": 33225, "text": "Following is another example where i’th row has i columns, i.e., the first row has 1 element, the second row has two elements and so on." }, { "code": null, "e": 33367, "s": 33362, "text": "Java" }, { "code": "// Another Java program to demonstrate 2-D jagged// array such that first row has 1 element, second// row has two elements and so on.class Main { public static void main(String[] args) { int r = 5; // Declaring 2-D array with 5 rows int arr[][] = new int[r][]; // Creating a 2D array such that first row // has 1 element, second row has two // elements and so on. for (int i = 0; i < arr.length; i++) arr[i] = new int[i + 1]; // Initializing array int count = 0; for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[i].length; j++) arr[i][j] = count++; // Displaying the values of 2D Jagged array System.out.println(\"Contents of 2D Jagged Array\"); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) System.out.print(arr[i][j] + \" \"); System.out.println(); } }}", "e": 34349, "s": 33367, "text": null }, { "code": null, "e": 34417, "s": 34349, "text": "Contents of 2D Jagged Array\n0 \n1 2 \n3 4 5 \n6 7 8 9 \n10 11 12 13 14 " }, { "code": null, "e": 34810, "s": 34417, "text": "This article is contributed by Rahul Agrawal. 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": 34823, "s": 34810, "text": "madhav_mohan" }, { "code": null, "e": 34836, "s": 34823, "text": "aadarsh baid" }, { "code": null, "e": 34845, "s": 34836, "text": "sweetyty" }, { "code": null, "e": 34865, "s": 34845, "text": "Java-Array-Programs" }, { "code": null, "e": 34877, "s": 34865, "text": "Java-Arrays" }, { "code": null, "e": 34882, "s": 34877, "text": "Java" }, { "code": null, "e": 34887, "s": 34882, "text": "Java" }, { "code": null, "e": 34985, "s": 34887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35029, "s": 34985, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35044, "s": 35029, "text": "Stream In Java" }, { "code": null, "e": 35069, "s": 35044, "text": "Reverse a string in Java" }, { "code": null, "e": 35105, "s": 35069, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 35136, "s": 35105, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35168, "s": 35136, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 35192, "s": 35168, "text": "Singleton Class in Java" }, { "code": null, "e": 35220, "s": 35192, "text": "Initializing a List in Java" }, { "code": null, "e": 35266, "s": 35220, "text": "Different ways of Reading a text file in Java" } ]
HTML <object> vspace Attribute - GeeksforGeeks
14 Dec, 2021 The HTML <object> vspace Attribute is used to specify the number of whitespace on the bottom and top side of an object. Syntax: <object vspace="pixels"> Attribute: pixels: It specifies the number of whitespaces on the top and bottom of an object in terms of pixels. Note: The <object> vspace Attribute is not supported in HTML 5. Use CSS margin property instead of this attribute. Below examples illustrate the <object> vspace attribute in HTML:Example 1: In this example the object with 50px margin on top and bottom. html <!DOCTYPE html><html> <head> <title> HTML object vspace Attribute </title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h4> HTML <object> vspace Attribute </h4> <br> <object data="https://www.geeksforgeeks.org/wp-content/uploads/Geek_logi_-low_res.png" width="350px" height="150px" vspace=50> GeeksforGeeks </object> </center></body> </html> Output: Example 2: html <!DOCTYPE html><html> <head> <title> HTML object vspace Attribute </title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h4> HTML <object> vspace Attribute </h4> <h4>Object without vspace:</h4> <object data="https://media.geeksforgeeks.org/wp-content/uploads/20190822082748/child.png" width="50%" height="150px"> GeeksforGeeks </object> <h4>Object with 25 vspace:</h4> <object data="https://media.geeksforgeeks.org/wp-content/uploads/20190822082748/child.png" width="50%" height="150px" vspace="25"> GeeksforGeeks </object> </center> </body> </html> Output: Supported Browsers: The browsers supported by HTML <Object> vspace attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubham_singh arorakashish0911 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n14 Dec, 2021" }, { "code": null, "e": 26259, "s": 26139, "text": "The HTML <object> vspace Attribute is used to specify the number of whitespace on the bottom and top side of an object." }, { "code": null, "e": 26269, "s": 26259, "text": "Syntax: " }, { "code": null, "e": 26295, "s": 26269, "text": "<object vspace=\"pixels\"> " }, { "code": null, "e": 26306, "s": 26295, "text": "Attribute:" }, { "code": null, "e": 26408, "s": 26306, "text": "pixels: It specifies the number of whitespaces on the top and bottom of an object in terms of pixels." }, { "code": null, "e": 26523, "s": 26408, "text": "Note: The <object> vspace Attribute is not supported in HTML 5. Use CSS margin property instead of this attribute." }, { "code": null, "e": 26661, "s": 26523, "text": "Below examples illustrate the <object> vspace attribute in HTML:Example 1: In this example the object with 50px margin on top and bottom." }, { "code": null, "e": 26666, "s": 26661, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML object vspace Attribute </title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h4> HTML <object> vspace Attribute </h4> <br> <object data=\"https://www.geeksforgeeks.org/wp-content/uploads/Geek_logi_-low_res.png\" width=\"350px\" height=\"150px\" vspace=50> GeeksforGeeks </object> </center></body> </html>", "e": 27142, "s": 26666, "text": null }, { "code": null, "e": 27152, "s": 27142, "text": "Output: " }, { "code": null, "e": 27165, "s": 27152, "text": "Example 2: " }, { "code": null, "e": 27170, "s": 27165, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML object vspace Attribute </title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h4> HTML <object> vspace Attribute </h4> <h4>Object without vspace:</h4> <object data=\"https://media.geeksforgeeks.org/wp-content/uploads/20190822082748/child.png\" width=\"50%\" height=\"150px\"> GeeksforGeeks </object> <h4>Object with 25 vspace:</h4> <object data=\"https://media.geeksforgeeks.org/wp-content/uploads/20190822082748/child.png\" width=\"50%\" height=\"150px\" vspace=\"25\"> GeeksforGeeks </object> </center> </body> </html>", "e": 27897, "s": 27170, "text": null }, { "code": null, "e": 27905, "s": 27897, "text": "Output:" }, { "code": null, "e": 28002, "s": 27905, "text": "Supported Browsers: The browsers supported by HTML <Object> vspace attribute are listed below: " }, { "code": null, "e": 28016, "s": 28002, "text": "Google Chrome" }, { "code": null, "e": 28034, "s": 28016, "text": "Internet Explorer" }, { "code": null, "e": 28042, "s": 28034, "text": "Firefox" }, { "code": null, "e": 28048, "s": 28042, "text": "Opera" }, { "code": null, "e": 28055, "s": 28048, "text": "Safari" }, { "code": null, "e": 28192, "s": 28055, "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": 28206, "s": 28192, "text": "shubham_singh" }, { "code": null, "e": 28223, "s": 28206, "text": "arorakashish0911" }, { "code": null, "e": 28243, "s": 28223, "text": "hritikbhatnagar2182" }, { "code": null, "e": 28259, "s": 28243, "text": "HTML-Attributes" }, { "code": null, "e": 28264, "s": 28259, "text": "HTML" }, { "code": null, "e": 28281, "s": 28264, "text": "Web Technologies" }, { "code": null, "e": 28286, "s": 28281, "text": "HTML" }, { "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": 28408, "s": 28384, "text": "REST API (Introduction)" }, { "code": null, "e": 28449, "s": 28408, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28486, "s": 28449, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28515, "s": 28486, "text": "Form validation using jQuery" }, { "code": null, "e": 28535, "s": 28515, "text": "Angular File Upload" }, { "code": null, "e": 28575, "s": 28535, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28608, "s": 28575, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28653, "s": 28608, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28696, "s": 28653, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use GET method to send data in jQuery Ajax?
The jQuery.get( url, [data], [callback], [type] ) method loads data from the server using a GET HTTP request. Here is the description of all the parameters used by this method − url − A string containing the URL to which the request is sent data − This optional parameter represents key/value pairs that will be sent to the server. callback − This optional parameter represents a function to be executed whenever the data is loaded successfully. type − This optional parameter represents type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text". Assuming we have the following PHP content in result.php file − <?php if( $_REQUEST["name"] ) { $name = $_REQUEST['name']; echo "Welcome ". $name; } ?> Here's the code snippet to implement GET method in jQuery − <head> <title>The jQuery Example</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){ $.get( "result.php", { name: "Zara" }, function(data) { $('#stage').html(data); } ); }); }); </script> </head> <body> <p>Click on the button to load result.html file −</p> <span id = "stage" style = "background-color:#cc0;"> STAGE </span> <div><input type = "button" id = "driver" value = "Load Data" /></div> </body>
[ { "code": null, "e": 1172, "s": 1062, "text": "The jQuery.get( url, [data], [callback], [type] ) method loads data from the server using a GET HTTP request." }, { "code": null, "e": 1240, "s": 1172, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 1303, "s": 1240, "text": "url − A string containing the URL to which the request is sent" }, { "code": null, "e": 1394, "s": 1303, "text": "data − This optional parameter represents key/value pairs that will be sent to the server." }, { "code": null, "e": 1508, "s": 1394, "text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully." }, { "code": null, "e": 1653, "s": 1508, "text": "type − This optional parameter represents type of data to be returned to callback function: \"xml\", \"html\", \"script\", \"json\", \"jsonp\", or \"text\"." }, { "code": null, "e": 1717, "s": 1653, "text": "Assuming we have the following PHP content in result.php file −" }, { "code": null, "e": 1812, "s": 1717, "text": "<?php\nif( $_REQUEST[\"name\"] ) {\n\n $name = $_REQUEST['name'];\n echo \"Welcome \". $name;\n}\n?>" }, { "code": null, "e": 1872, "s": 1812, "text": "Here's the code snippet to implement GET method in jQuery −" }, { "code": null, "e": 2709, "s": 1872, "text": " <head>\n <title>The jQuery Example</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 $.get(\n \"result.php\",\n { name: \"Zara\" },\n function(data) {\n $('#stage').html(data);\n }\n );\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 <span id = \"stage\" style = \"background-color:#cc0;\">\n STAGE\n </span>\n \n <div><input type = \"button\" id = \"driver\"\n value = \"Load Data\" /></div>\n \n </body>" } ]
How to Color Scatter Plot Points in R ? - GeeksforGeeks
30 May, 2021 A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. But by default, the color of these points is black and sometimes there might be a need to change the color of these points. In this article, we will discuss how to change the color of points in scatterplot in the R Programming Language. The simple scatterplot is created using the plot() function. Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes) Let us first create a scatterplot without any color so that the difference is apparent. Example: R df<-read.csv("bestsellers.csv") plot(df$Reviews,df$Price,pch=16) Output: Now to change the colors of a scatterplot using plot(), simply select the column on basis of which different colors should be assigned to various points. Pass the column that will help differentiate between points to “col” attribute. Example: R df<-read.csv("bestsellers.csv") plot(df$Reviews,df$Price,pch=16,col=df$Genre) Output: ggplot2 module supports geom_point() function that can help plot scatterplot. Let us first see how a scatterplot will appear without providing any mechanism for changing colors. Example: R library("ggplot2") df<-read.csv("bestsellers.csv") ggplot(df,aes(x=Reviews,y=Price))+geom_point() Output: By using, ggplot there are various ways of adding colors to a scatterplot. Let us first discuss how colors are changed by default. For this simply pass the differentiating column to col attribute. Example: R library("ggplot2") df<-read.csv("bestsellers.csv") ggplot(df,aes(x=Reviews,y=Price,col=Genre))+geom_point() Output: Another way of producing the same result is to provide the grouping column to group attribute and again to color in geom_point() Example: R library("ggplot2") df<-read.csv("bestsellers.csv") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre)) Output: We can also add custom colors by using scale_color_manual() function with the list of colors to chose from. Example R library("ggplot2") df<-read.csv("bestsellers.csv") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))+ scale_color_manual(values=c('Yellow','Green')) Output: A scatterplot can also display colors only from grey scale, for this use scale_color_grey() function. Example: R library("ggplot2") df<-read.csv("bestsellers.csv") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))+ scale_color_grey() Output: scale_color_brewer() function is also a method to add colors to a scatterplot. This function takes the name of the palette to pick colors from. Example: R library("ggplot2") df<-read.csv("bestsellers.csv") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))+ scale_color_brewer(palette="Accent") Output: Picked R-Charts R-ggplot 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 How to filter R dataframe by multiple conditions? R - if statement 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": "\n30 May, 2021" }, { "code": null, "e": 26839, "s": 26597, "text": "A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. But by default, the color of these points is black and sometimes there might be a need to change the color of these points. " }, { "code": null, "e": 26952, "s": 26839, "text": "In this article, we will discuss how to change the color of points in scatterplot in the R Programming Language." }, { "code": null, "e": 27013, "s": 26952, "text": "The simple scatterplot is created using the plot() function." }, { "code": null, "e": 27068, "s": 27013, "text": "Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)" }, { "code": null, "e": 27156, "s": 27068, "text": "Let us first create a scatterplot without any color so that the difference is apparent." }, { "code": null, "e": 27165, "s": 27156, "text": "Example:" }, { "code": null, "e": 27167, "s": 27165, "text": "R" }, { "code": "df<-read.csv(\"bestsellers.csv\") plot(df$Reviews,df$Price,pch=16)", "e": 27233, "s": 27167, "text": null }, { "code": null, "e": 27241, "s": 27233, "text": "Output:" }, { "code": null, "e": 27475, "s": 27241, "text": "Now to change the colors of a scatterplot using plot(), simply select the column on basis of which different colors should be assigned to various points. Pass the column that will help differentiate between points to “col” attribute." }, { "code": null, "e": 27484, "s": 27475, "text": "Example:" }, { "code": null, "e": 27486, "s": 27484, "text": "R" }, { "code": "df<-read.csv(\"bestsellers.csv\") plot(df$Reviews,df$Price,pch=16,col=df$Genre)", "e": 27565, "s": 27486, "text": null }, { "code": null, "e": 27573, "s": 27565, "text": "Output:" }, { "code": null, "e": 27751, "s": 27573, "text": "ggplot2 module supports geom_point() function that can help plot scatterplot. Let us first see how a scatterplot will appear without providing any mechanism for changing colors." }, { "code": null, "e": 27760, "s": 27751, "text": "Example:" }, { "code": null, "e": 27762, "s": 27760, "text": "R" }, { "code": "library(\"ggplot2\") df<-read.csv(\"bestsellers.csv\") ggplot(df,aes(x=Reviews,y=Price))+geom_point()", "e": 27862, "s": 27762, "text": null }, { "code": null, "e": 27870, "s": 27862, "text": "Output:" }, { "code": null, "e": 28067, "s": 27870, "text": "By using, ggplot there are various ways of adding colors to a scatterplot. Let us first discuss how colors are changed by default. For this simply pass the differentiating column to col attribute." }, { "code": null, "e": 28076, "s": 28067, "text": "Example:" }, { "code": null, "e": 28078, "s": 28076, "text": "R" }, { "code": "library(\"ggplot2\") df<-read.csv(\"bestsellers.csv\") ggplot(df,aes(x=Reviews,y=Price,col=Genre))+geom_point()", "e": 28188, "s": 28078, "text": null }, { "code": null, "e": 28196, "s": 28188, "text": "Output:" }, { "code": null, "e": 28326, "s": 28196, "text": "Another way of producing the same result is to provide the grouping column to group attribute and again to color in geom_point() " }, { "code": null, "e": 28335, "s": 28326, "text": "Example:" }, { "code": null, "e": 28337, "s": 28335, "text": "R" }, { "code": "library(\"ggplot2\") df<-read.csv(\"bestsellers.csv\") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))", "e": 28468, "s": 28337, "text": null }, { "code": null, "e": 28476, "s": 28468, "text": "Output:" }, { "code": null, "e": 28584, "s": 28476, "text": "We can also add custom colors by using scale_color_manual() function with the list of colors to chose from." }, { "code": null, "e": 28592, "s": 28584, "text": "Example" }, { "code": null, "e": 28594, "s": 28592, "text": "R" }, { "code": "library(\"ggplot2\") df<-read.csv(\"bestsellers.csv\") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))+ scale_color_manual(values=c('Yellow','Green'))", "e": 28775, "s": 28594, "text": null }, { "code": null, "e": 28783, "s": 28775, "text": "Output:" }, { "code": null, "e": 28885, "s": 28783, "text": "A scatterplot can also display colors only from grey scale, for this use scale_color_grey() function." }, { "code": null, "e": 28894, "s": 28885, "text": "Example:" }, { "code": null, "e": 28896, "s": 28894, "text": "R" }, { "code": "library(\"ggplot2\") df<-read.csv(\"bestsellers.csv\") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))+ scale_color_grey()", "e": 29049, "s": 28896, "text": null }, { "code": null, "e": 29057, "s": 29049, "text": "Output:" }, { "code": null, "e": 29201, "s": 29057, "text": "scale_color_brewer() function is also a method to add colors to a scatterplot. This function takes the name of the palette to pick colors from." }, { "code": null, "e": 29210, "s": 29201, "text": "Example:" }, { "code": null, "e": 29212, "s": 29210, "text": "R" }, { "code": "library(\"ggplot2\") df<-read.csv(\"bestsellers.csv\") ggplot(df,aes(x=Reviews,y=Price,group=Genre))+ geom_point(aes(color=Genre))+ scale_color_brewer(palette=\"Accent\")", "e": 29381, "s": 29212, "text": null }, { "code": null, "e": 29389, "s": 29381, "text": "Output:" }, { "code": null, "e": 29396, "s": 29389, "text": "Picked" }, { "code": null, "e": 29405, "s": 29396, "text": "R-Charts" }, { "code": null, "e": 29414, "s": 29405, "text": "R-ggplot" }, { "code": null, "e": 29423, "s": 29414, "text": "R-Graphs" }, { "code": null, "e": 29431, "s": 29423, "text": "R-plots" }, { "code": null, "e": 29442, "s": 29431, "text": "R Language" }, { "code": null, "e": 29540, "s": 29442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29592, "s": 29540, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29627, "s": 29592, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29685, "s": 29627, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29723, "s": 29685, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29766, "s": 29723, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29816, "s": 29766, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29833, "s": 29816, "text": "R - if statement" }, { "code": null, "e": 29882, "s": 29833, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29919, "s": 29882, "text": "How to import an Excel File into R ?" } ]
What is the use of ON COMPLETION PRESERVE clause while creating the event?
As we know that an event is automatically dropped when it is expired and we would not be able to see it from SHOW EVENTS statement. To change such kind of behavior we can use ON COMPLETION PRESERVE while creating the event. It can be understood from the following example − mysql> Create table event_messages(ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, MESSAGE VARCHAR(255) NOT NULL, Generated_at DATETIME NOT NULL); Query OK, 0 rows affected (0.61 sec) The below query will create an event without the use of ON COMPLETION PRESERVE hence it would not be seen in the output of SHOW EVENTS FROM db_name query. mysql> CREATE EVENT testing_event_without_Preserves ON SCHEDULE AT CURRENT_TIMESTAMP DO INSERT INTO event_messages(message,generated_at) Values('Without Preserve',NOW()); Query OK, 0 rows affected (0.00 sec) mysql> Select * from event_messages; +----+------------------+---------------------+ | ID | MESSAGE | Generated_at | +----+------------------+---------------------+ | 1 | Without Preserve | 2017-11-22 20:32:13 | +----+------------------+---------------------+ 1 row in set (0.00 sec) mysql> SHOW EVENTS FROM query\G *************************** 1. row *************************** Db: query Name: testing_event5 Definer: root@localhost Time zone: SYSTEM Type: ONE TIME Execute at: 2017-11-22 17:09:11 Interval value: NULL Interval field: NULL Starts: NULL Ends: NULL Status: DISABLED Originator: 0 character_set_client: cp850 collation_connection: cp850_general_ci Database Collation: latin1_swedish_ci 1 row in set (0.00 sec) The below query will create an event with the use of ON COMPLETION PRESERVE hence it would be seen in the output of SHOW EVENTS FROM db_name query. mysql> CREATE EVENT testing_event_with_Preserves ON SCHEDULE AT CURRENT_TIMESTAMP ON COMPLETION PRESERVE DO INSERT INTO event_messages(message,generated_at) Values('With Preserve',NOW()); Query OK, 0 rows affected (0.00 sec) mysql> Select * from event_messages; +----+------------------+---------------------+ | ID | MESSAGE | Generated_at | +----+------------------+---------------------+ | 1 | Without Preserve | 2017-11-22 20:32:13 | | 2 | With Preserve | 2017-11-22 20:35:12 | +----+------------------+---------------------+ 2 rows in set (0.00 sec) mysql> SHOW EVENTS FROM query\G *************************** 1. row *************************** Db: query Name: testing_event5 Definer: root@localhost Time zone: SYSTEM Type: ONE TIME Execute at: 2017-11-22 17:09:11 Interval value: NULL Interval field: NULL Starts: NULL Ends: NULL Status: DISABLED Originator: 0 character_set_client: cp850 collation_connection: cp850_general_ci Database Collation: latin1_swedish_ci *************************** 2. row *************************** Db: query Name: testing_event_with_Preserves Definer: root@localhost Time zone: SYSTEM Type: ONE TIME Execute at: 2017-11-22 20:35:12 Interval value: NULL Interval field: NULL Starts: NULL Ends: NULL Status: DISABLED Originator: 0 character_set_client: cp850 collation_connection: cp850_general_ci Database Collation: latin1_swedish_ci 2 rows in set (0.00 sec)
[ { "code": null, "e": 1336, "s": 1062, "text": "As we know that an event is automatically dropped when it is expired and we would not be able to see it from SHOW EVENTS statement. To change such kind of behavior we can use ON COMPLETION PRESERVE while creating the event. It can be understood from the following example −" }, { "code": null, "e": 1516, "s": 1336, "text": "mysql> Create table event_messages(ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, MESSAGE VARCHAR(255) NOT NULL, Generated_at DATETIME NOT NULL);\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1671, "s": 1516, "text": "The below query will create an event without the use of ON COMPLETION PRESERVE hence it would not be seen in the output of SHOW EVENTS FROM db_name query." }, { "code": null, "e": 2775, "s": 1671, "text": "mysql> CREATE EVENT testing_event_without_Preserves ON SCHEDULE AT CURRENT_TIMESTAMP DO INSERT INTO event_messages(message,generated_at) Values('Without Preserve',NOW());\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select * from event_messages;\n+----+------------------+---------------------+\n| ID | MESSAGE | Generated_at |\n+----+------------------+---------------------+\n| 1 | Without Preserve | 2017-11-22 20:32:13 |\n+----+------------------+---------------------+\n1 row in set (0.00 sec)\n\nmysql> SHOW EVENTS FROM query\\G\n*************************** 1. row ***************************\n Db: query\n Name: testing_event5\n Definer: root@localhost\n Time zone: SYSTEM\n Type: ONE TIME\n Execute at: 2017-11-22 17:09:11\n Interval value: NULL\n Interval field: NULL\n Starts: NULL\n Ends: NULL\n Status: DISABLED\n Originator: 0\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n Database Collation: latin1_swedish_ci\n1 row in set (0.00 sec)" }, { "code": null, "e": 2923, "s": 2775, "text": "The below query will create an event with the use of ON COMPLETION PRESERVE hence it would be seen in the output of SHOW EVENTS FROM db_name query." }, { "code": null, "e": 4645, "s": 2923, "text": "mysql> CREATE EVENT testing_event_with_Preserves ON SCHEDULE AT CURRENT_TIMESTAMP ON COMPLETION PRESERVE DO INSERT INTO event_messages(message,generated_at) Values('With Preserve',NOW());\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select * from event_messages;\n+----+------------------+---------------------+\n| ID | MESSAGE | Generated_at |\n+----+------------------+---------------------+\n| 1 | Without Preserve | 2017-11-22 20:32:13 |\n| 2 | With Preserve | 2017-11-22 20:35:12 |\n+----+------------------+---------------------+\n2 rows in set (0.00 sec)\n\nmysql> SHOW EVENTS FROM query\\G\n*************************** 1. row ***************************\n Db: query\n Name: testing_event5\n Definer: root@localhost\n Time zone: SYSTEM\n Type: ONE TIME\n Execute at: 2017-11-22 17:09:11\n Interval value: NULL\n Interval field: NULL\n Starts: NULL\n Ends: NULL\n Status: DISABLED\n Originator: 0\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n Database Collation: latin1_swedish_ci\n*************************** 2. row ***************************\n Db: query\n Name: testing_event_with_Preserves\n Definer: root@localhost\n Time zone: SYSTEM\n Type: ONE TIME\n Execute at: 2017-11-22 20:35:12\n Interval value: NULL\n Interval field: NULL\n Starts: NULL\n Ends: NULL\n Status: DISABLED\n Originator: 0\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n Database Collation: latin1_swedish_ci\n2 rows in set (0.00 sec)" } ]
BigQuery CTEs by Example | Towards Data Science
This is my 20th year working with SQL (eek!). To mark this milestone, I recently wrote an article on the 10 SQL naming standards I live by, which I feel, produce SQL that is easy to read, debug, and maintain. towardsdatascience.com Following this theme, I thought I’d explore some of the other elements of the SQL language that I feel, help differentiate great SQL, from simply functional SQL. One element at the top of my list is the common table expression, or CTE for short. First launched around 2000, CTEs are now widely available in most modern database platforms, including MS SQL Server, Postgres, MySQL, and Google BigQuery. I have used Google BigQuery for my examples, but the syntax for CTEs will be very similar to other database platforms that you might be using. I’ve used the Santander cycle hire scheme dataset, part of Google’s publicly available datasets. A quick note for BigQuery users — in case you are wondering why my BigQuery UI looks different from yours, I’m using the updated UI for 2021, just released in preview. If you want to see what I think of the new features, have a read of the article I published a few days ago. towardsdatascience.com For those of you who are not familiar with CTEs, or perhaps just starting out in your Data Science careers, a CTE is a temporary result set from a SQL query, that you can reference in other parts of a wider SQL query as if it were a permanent table in your database. The CTE is temporary and only exists for the duration of the wider query being executed. You can alias (name) your CTEs, in a similar way to how you alias tables or columns names and can have multiple CTEs per query. Here is the basic syntax: with employee_cte as (select first_name, last_name from employee)select e.first_name, e.last_name, h.hire_datefrom employee_cte e inner join employee_hire h on h.employee_id = e.employee_id Follow my 5 tips and hopefully, by the end, you’ll have some good best practices to begin exploring them for yourself. So, in no particular order, let’s begin. In this query, I want to find all cycle stations that are within 500m of London’s city centre, and return the station name and the distance from the centre: select name as station_name, st_distance ( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_mfrom `bigquery-public-data.london_bicycles.cycle_stations`where st_distance( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865)) <= 500order by distance_from_city_centre_m Whilst this is perfectly functional and returns the correct result (below in case you were curious!), you will note the logic in bold to calc the distance is duplicated. This is something we want to avoid; logic should be defined once, making it easier to read and modify later on if required. Here is where a CTE comes to the rescue: with stationsas( select name as station_name, st_distance ( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_m from `bigquery-public-data.london_bicycles.cycle_stations`)select station_name, distance_from_city_centre_mfrom stationswhere distance_from_city_centre_m <= 500order by distance_from_city_centre_m No more duplicated logic. And, I think this much easier to read than the first query too — what do you think? And because my stations CTE is temporary, I haven’t had to clutter my database with any materialised (permanent) tables, or views. As in other areas of programming, and life for that matter, it really helps if you try and keep things simple where you can. One way we can use CTEs to achieve this in our SQL code is to use CTEs as a way of breaking up complex SQL queries into smaller, bite-size chunks. This produces SQL that is: Easier to read and understandEasier to debug; you build your SQL in stages, testing the output of each CTE before continuing to the next.Easier to maintain; changing logic can now be done in a more modulised way, and in a single place. Easier to read and understand Easier to debug; you build your SQL in stages, testing the output of each CTE before continuing to the next. Easier to maintain; changing logic can now be done in a more modulised way, and in a single place. In this example, I want to further explore the stations within 500m of the city centre, and single out the station that has seen the most journeys terminate there over the past 12 months. I then want to extract all other stations that have seen more journeys than this and analyse their distance from the city centre. One way to achieve this (without CTEs) is the following: select s.name as station_name, st_distance ( st_geogpoint( s.longitude, s.latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_m, count(j.rental_id) as journey_countfrom `bigquery-public-data.london_bicycles.cycle_stations` s inner join `bigquery-public-data.london_bicycles.cycle_hire` j on j.end_station_id = s.id and cast(j.end_date as date) >= date_sub('2017-1-1', interval 1 year)group by station_name, s.longitude, s.latitudehaving count(j.rental_id) > ( select journey_count from ( select dense_rank() over (order by count(j.rental_id) desc) as rank, s.id as station_id, count(j.rental_id) as journey_count from `bigquery-public-data.london_bicycles.cycle_stations` s inner join `bigquery-public-data.london_bicycles.cycle_hire` j on j.end_station_id = s.id and cast(j.end_date as date) >= date_sub('2017-1-1', interval 1 year) where j.end_station_id in ( select s.id as station_id from `bigquery-public-data.london_bicycles.cycle_stations` s where st_distance( st_geogpoint( s.longitude, s.latitude), st_geogpoint(-0.118092, 51.509865) ) <= 500 ) group by station_id ) where rank = 1) order by journey_count desc Again, this is perfectly functional code. However, there is duplicate logic (in bold), and I find this quite difficult to read. Also, if I had to debug this, it would be difficult — for example, validating the busiest station, as everything is intertwined. Applying CTEs, and we can greatly improve this (CTEs in bold): with station_proximityas( select id as station_id, name as station_name, st_distance( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_m from `bigquery-public-data.london_bicycles.cycle_stations`),station_journeys as(select s.station_id, s.station_name, s.distance_from_city_centre_m, count(1) as journey_countfrom station_proximity s inner join `bigquery-public-data.london_bicycles.cycle_hire` j on j.end_station_id = s.station_id and cast(j.end_date as date) >= date_sub('2017-1-1', interval 1 year)group by s.station_id, s.station_name, s.distance_from_city_centre_m),stations_near_centreas( select sp.station_id, sj.journey_count, dense_rank() over (order by sj.journey_count desc) journey_rank, from station_proximity sp inner join station_journeys sj on sj.station_id = sp.station_id where sp.distance_from_city_centre_m <= 500)select station_name, distance_from_city_centre_m, journey_countfrom station_journeys where journey_count >( select journey_count from stations_near_centre s where s.journey_rank = 1)order by journey_count desc I think this is much easier to read. If I wanted to debug this, I can easily change the final select to select from each CTE in turn, validating before I move onto the next one. (If you are interested, here are the results. As you’d expect, the majority of these stations are close to mainline railway links) My third tip is to take care when naming your CTEs. In my previous example, I took care to name my CTEs with meaningful names: with station_proximityas( --- ),station_journeys,as( -- ),stations_near_centreas( -- ) I often see this, and I’d always avoid if possible: with cte1as( --- ),cte2,as( -- ),cte3as( -- ) When working with data, we often have to consolidate data from different sources into a single, conformed table. CTEs lend themselves really well for this use case. Say we had cycle journeys held in two systems, A and B. We can effectively use CTEs when writing code to populate a single journeys table like this: with system_a_journeysas( some data wrangling of system a ),system_b_journeys,as( some data wrangling of system b),all_journeysas( select * from system_a_journeys union all select * from system_b_journeys) *note I’d never advocate using select * (list columns explicitly). Another novel use of CTEs that can improve the maintainability of your SQL, is to use them to make it easy to see which tables/views your SQL is referencing. This is especially useful for complex queries, spanning many lines, and referencing a lot of tables/views. To do this, at the start of your SQL statement, create CTE “wrappers” for all of the tables/views you are selecting from. You can also restrict the columns to just those you actually use — not only does this help identify which columns you are consuming, but can also improve performance. So in my example from tip 2, I would start the query with: with cycle_stations as ( select id as station_id, name as station_name, longitude, latitude from `bigquery-public-data.london_bicycles.cycle_stations`),cycle_journeys as( select station_id, end_date from `bigquery-public-data.london_bicycles.cycle_hire`) Hopefully from reading this you now have an understanding of common table expressions, and how they can be used to really improve your SQL writing. CTEs are something I personally use on a daily basis and are one of the best tools in the SQL toolbox for aiding readability and maintainability. They also make writing SQL, a much more pragmatic, and therefore enjoyable experience. I hope you agree :) 1. Learn more about Ancoris Data, Analytics & AI
[ { "code": null, "e": 381, "s": 172, "text": "This is my 20th year working with SQL (eek!). To mark this milestone, I recently wrote an article on the 10 SQL naming standards I live by, which I feel, produce SQL that is easy to read, debug, and maintain." }, { "code": null, "e": 404, "s": 381, "text": "towardsdatascience.com" }, { "code": null, "e": 566, "s": 404, "text": "Following this theme, I thought I’d explore some of the other elements of the SQL language that I feel, help differentiate great SQL, from simply functional SQL." }, { "code": null, "e": 806, "s": 566, "text": "One element at the top of my list is the common table expression, or CTE for short. First launched around 2000, CTEs are now widely available in most modern database platforms, including MS SQL Server, Postgres, MySQL, and Google BigQuery." }, { "code": null, "e": 1046, "s": 806, "text": "I have used Google BigQuery for my examples, but the syntax for CTEs will be very similar to other database platforms that you might be using. I’ve used the Santander cycle hire scheme dataset, part of Google’s publicly available datasets." }, { "code": null, "e": 1322, "s": 1046, "text": "A quick note for BigQuery users — in case you are wondering why my BigQuery UI looks different from yours, I’m using the updated UI for 2021, just released in preview. If you want to see what I think of the new features, have a read of the article I published a few days ago." }, { "code": null, "e": 1345, "s": 1322, "text": "towardsdatascience.com" }, { "code": null, "e": 1829, "s": 1345, "text": "For those of you who are not familiar with CTEs, or perhaps just starting out in your Data Science careers, a CTE is a temporary result set from a SQL query, that you can reference in other parts of a wider SQL query as if it were a permanent table in your database. The CTE is temporary and only exists for the duration of the wider query being executed. You can alias (name) your CTEs, in a similar way to how you alias tables or columns names and can have multiple CTEs per query." }, { "code": null, "e": 1855, "s": 1829, "text": "Here is the basic syntax:" }, { "code": null, "e": 2059, "s": 1855, "text": "with employee_cte as (select first_name, last_name from employee)select e.first_name, e.last_name, h.hire_datefrom employee_cte e inner join employee_hire h on h.employee_id = e.employee_id" }, { "code": null, "e": 2178, "s": 2059, "text": "Follow my 5 tips and hopefully, by the end, you’ll have some good best practices to begin exploring them for yourself." }, { "code": null, "e": 2219, "s": 2178, "text": "So, in no particular order, let’s begin." }, { "code": null, "e": 2376, "s": 2219, "text": "In this query, I want to find all cycle stations that are within 500m of London’s city centre, and return the station name and the distance from the centre:" }, { "code": null, "e": 2755, "s": 2376, "text": "select name as station_name, st_distance ( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_mfrom `bigquery-public-data.london_bicycles.cycle_stations`where st_distance( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865)) <= 500order by distance_from_city_centre_m" }, { "code": null, "e": 3049, "s": 2755, "text": "Whilst this is perfectly functional and returns the correct result (below in case you were curious!), you will note the logic in bold to calc the distance is duplicated. This is something we want to avoid; logic should be defined once, making it easier to read and modify later on if required." }, { "code": null, "e": 3090, "s": 3049, "text": "Here is where a CTE comes to the rescue:" }, { "code": null, "e": 3503, "s": 3090, "text": "with stationsas( select name as station_name, st_distance ( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_m from `bigquery-public-data.london_bicycles.cycle_stations`)select station_name, distance_from_city_centre_mfrom stationswhere distance_from_city_centre_m <= 500order by distance_from_city_centre_m" }, { "code": null, "e": 3613, "s": 3503, "text": "No more duplicated logic. And, I think this much easier to read than the first query too — what do you think?" }, { "code": null, "e": 3744, "s": 3613, "text": "And because my stations CTE is temporary, I haven’t had to clutter my database with any materialised (permanent) tables, or views." }, { "code": null, "e": 4043, "s": 3744, "text": "As in other areas of programming, and life for that matter, it really helps if you try and keep things simple where you can. One way we can use CTEs to achieve this in our SQL code is to use CTEs as a way of breaking up complex SQL queries into smaller, bite-size chunks. This produces SQL that is:" }, { "code": null, "e": 4279, "s": 4043, "text": "Easier to read and understandEasier to debug; you build your SQL in stages, testing the output of each CTE before continuing to the next.Easier to maintain; changing logic can now be done in a more modulised way, and in a single place." }, { "code": null, "e": 4309, "s": 4279, "text": "Easier to read and understand" }, { "code": null, "e": 4418, "s": 4309, "text": "Easier to debug; you build your SQL in stages, testing the output of each CTE before continuing to the next." }, { "code": null, "e": 4517, "s": 4418, "text": "Easier to maintain; changing logic can now be done in a more modulised way, and in a single place." }, { "code": null, "e": 4835, "s": 4517, "text": "In this example, I want to further explore the stations within 500m of the city centre, and single out the station that has seen the most journeys terminate there over the past 12 months. I then want to extract all other stations that have seen more journeys than this and analyse their distance from the city centre." }, { "code": null, "e": 4892, "s": 4835, "text": "One way to achieve this (without CTEs) is the following:" }, { "code": null, "e": 6304, "s": 4892, "text": "select s.name as station_name, st_distance ( st_geogpoint( s.longitude, s.latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_m, count(j.rental_id) as journey_countfrom `bigquery-public-data.london_bicycles.cycle_stations` s inner join `bigquery-public-data.london_bicycles.cycle_hire` j on j.end_station_id = s.id and cast(j.end_date as date) >= date_sub('2017-1-1', interval 1 year)group by station_name, s.longitude, s.latitudehaving count(j.rental_id) > ( select journey_count from ( select dense_rank() over (order by count(j.rental_id) desc) as rank, s.id as station_id, count(j.rental_id) as journey_count from `bigquery-public-data.london_bicycles.cycle_stations` s inner join `bigquery-public-data.london_bicycles.cycle_hire` j on j.end_station_id = s.id and cast(j.end_date as date) >= date_sub('2017-1-1', interval 1 year) where j.end_station_id in ( select s.id as station_id from `bigquery-public-data.london_bicycles.cycle_stations` s where st_distance( st_geogpoint( s.longitude, s.latitude), st_geogpoint(-0.118092, 51.509865) ) <= 500 ) group by station_id ) where rank = 1) order by journey_count desc" }, { "code": null, "e": 6561, "s": 6304, "text": "Again, this is perfectly functional code. However, there is duplicate logic (in bold), and I find this quite difficult to read. Also, if I had to debug this, it would be difficult — for example, validating the busiest station, as everything is intertwined." }, { "code": null, "e": 6624, "s": 6561, "text": "Applying CTEs, and we can greatly improve this (CTEs in bold):" }, { "code": null, "e": 7905, "s": 6624, "text": "with station_proximityas( select id as station_id, name as station_name, st_distance( st_geogpoint( longitude, latitude), st_geogpoint(-0.118092, 51.509865) ) as distance_from_city_centre_m from `bigquery-public-data.london_bicycles.cycle_stations`),station_journeys as(select s.station_id, s.station_name, s.distance_from_city_centre_m, count(1) as journey_countfrom station_proximity s inner join `bigquery-public-data.london_bicycles.cycle_hire` j on j.end_station_id = s.station_id and cast(j.end_date as date) >= date_sub('2017-1-1', interval 1 year)group by s.station_id, s.station_name, s.distance_from_city_centre_m),stations_near_centreas( select sp.station_id, sj.journey_count, dense_rank() over (order by sj.journey_count desc) journey_rank, from station_proximity sp inner join station_journeys sj on sj.station_id = sp.station_id where sp.distance_from_city_centre_m <= 500)select station_name, distance_from_city_centre_m, journey_countfrom station_journeys where journey_count >( select journey_count from stations_near_centre s where s.journey_rank = 1)order by journey_count desc" }, { "code": null, "e": 8083, "s": 7905, "text": "I think this is much easier to read. If I wanted to debug this, I can easily change the final select to select from each CTE in turn, validating before I move onto the next one." }, { "code": null, "e": 8214, "s": 8083, "text": "(If you are interested, here are the results. As you’d expect, the majority of these stations are close to mainline railway links)" }, { "code": null, "e": 8266, "s": 8214, "text": "My third tip is to take care when naming your CTEs." }, { "code": null, "e": 8341, "s": 8266, "text": "In my previous example, I took care to name my CTEs with meaningful names:" }, { "code": null, "e": 8428, "s": 8341, "text": "with station_proximityas( --- ),station_journeys,as( -- ),stations_near_centreas( -- )" }, { "code": null, "e": 8480, "s": 8428, "text": "I often see this, and I’d always avoid if possible:" }, { "code": null, "e": 8526, "s": 8480, "text": "with cte1as( --- ),cte2,as( -- ),cte3as( -- )" }, { "code": null, "e": 8639, "s": 8526, "text": "When working with data, we often have to consolidate data from different sources into a single, conformed table." }, { "code": null, "e": 8691, "s": 8639, "text": "CTEs lend themselves really well for this use case." }, { "code": null, "e": 8840, "s": 8691, "text": "Say we had cycle journeys held in two systems, A and B. We can effectively use CTEs when writing code to populate a single journeys table like this:" }, { "code": null, "e": 9051, "s": 8840, "text": "with system_a_journeysas( some data wrangling of system a ),system_b_journeys,as( some data wrangling of system b),all_journeysas( select * from system_a_journeys union all select * from system_b_journeys)" }, { "code": null, "e": 9118, "s": 9051, "text": "*note I’d never advocate using select * (list columns explicitly)." }, { "code": null, "e": 9383, "s": 9118, "text": "Another novel use of CTEs that can improve the maintainability of your SQL, is to use them to make it easy to see which tables/views your SQL is referencing. This is especially useful for complex queries, spanning many lines, and referencing a lot of tables/views." }, { "code": null, "e": 9672, "s": 9383, "text": "To do this, at the start of your SQL statement, create CTE “wrappers” for all of the tables/views you are selecting from. You can also restrict the columns to just those you actually use — not only does this help identify which columns you are consuming, but can also improve performance." }, { "code": null, "e": 9731, "s": 9672, "text": "So in my example from tip 2, I would start the query with:" }, { "code": null, "e": 10026, "s": 9731, "text": "with cycle_stations as ( select id as station_id, name as station_name, longitude, latitude from `bigquery-public-data.london_bicycles.cycle_stations`),cycle_journeys as( select station_id, end_date from `bigquery-public-data.london_bicycles.cycle_hire`)" }, { "code": null, "e": 10174, "s": 10026, "text": "Hopefully from reading this you now have an understanding of common table expressions, and how they can be used to really improve your SQL writing." }, { "code": null, "e": 10407, "s": 10174, "text": "CTEs are something I personally use on a daily basis and are one of the best tools in the SQL toolbox for aiding readability and maintainability. They also make writing SQL, a much more pragmatic, and therefore enjoyable experience." }, { "code": null, "e": 10427, "s": 10407, "text": "I hope you agree :)" } ]
C# - Infinite Loop - GeeksforGeeks
21 Jul, 2021 Infinite Loop is a loop that never terminates or ends and repeats indefinitely. Or in other words, an infinite loop is a loop in which the test condition does not evaluate to false and the loop continues forever until an external force is used to end it. You can create an infinite loop: Using for loop Using while loop Example 1: In this example, we are using a while loop to create an infinite loop by setting the condition to true. It will make while loop to never evaluates to false and the loop repeats indefinitely. C# // C# program to illustrate// infinite loopusing System; class GFG{ static public void Main (){ // Creating infinite loop // using while loop while (true) { // This statement will be printed // infinite times Console.WriteLine("Hey! GeeksforGeeks"); }}} Output: Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks Hey! GeeksforGeeks ......... Example 2: In this example, we are using for loop to create an infinite loop. C# // C# program to illustrate// infinite loopusing System; class GFG{ public static void Main(){ // Creating infinite loop // Using for loop for(;;) // This statement will be printed // infinite times Console.WriteLine("Welcome GFG!!");}} Output: Welcome GFG!! Welcome GFG!! Welcome GFG!! Welcome GFG!! Welcome GFG!! Welcome GFG!! Welcome GFG!! Welcome GFG!! ........ kapoorsagar226 anikakapoor C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# C# | How to insert an element in an Array? Convert String to Character Array in C# Lambda Expressions in C#
[ { "code": null, "e": 25657, "s": 25629, "text": "\n21 Jul, 2021" }, { "code": null, "e": 25945, "s": 25657, "text": "Infinite Loop is a loop that never terminates or ends and repeats indefinitely. Or in other words, an infinite loop is a loop in which the test condition does not evaluate to false and the loop continues forever until an external force is used to end it. You can create an infinite loop:" }, { "code": null, "e": 25960, "s": 25945, "text": "Using for loop" }, { "code": null, "e": 25977, "s": 25960, "text": "Using while loop" }, { "code": null, "e": 25988, "s": 25977, "text": "Example 1:" }, { "code": null, "e": 26179, "s": 25988, "text": "In this example, we are using a while loop to create an infinite loop by setting the condition to true. It will make while loop to never evaluates to false and the loop repeats indefinitely." }, { "code": null, "e": 26182, "s": 26179, "text": "C#" }, { "code": "// C# program to illustrate// infinite loopusing System; class GFG{ static public void Main (){ // Creating infinite loop // using while loop while (true) { // This statement will be printed // infinite times Console.WriteLine(\"Hey! GeeksforGeeks\"); }}}", "e": 26490, "s": 26182, "text": null }, { "code": null, "e": 26500, "s": 26490, "text": " Output:" }, { "code": null, "e": 26681, "s": 26500, "text": "Hey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\nHey! GeeksforGeeks\n........." }, { "code": null, "e": 26694, "s": 26683, "text": "Example 2:" }, { "code": null, "e": 26761, "s": 26694, "text": "In this example, we are using for loop to create an infinite loop." }, { "code": null, "e": 26764, "s": 26761, "text": "C#" }, { "code": "// C# program to illustrate// infinite loopusing System; class GFG{ public static void Main(){ // Creating infinite loop // Using for loop for(;;) // This statement will be printed // infinite times Console.WriteLine(\"Welcome GFG!!\");}}", "e": 27033, "s": 26764, "text": null }, { "code": null, "e": 27041, "s": 27033, "text": "Output:" }, { "code": null, "e": 27162, "s": 27041, "text": "Welcome GFG!!\nWelcome GFG!!\nWelcome GFG!!\nWelcome GFG!!\nWelcome GFG!!\nWelcome GFG!!\nWelcome GFG!!\nWelcome GFG!!\n........" }, { "code": null, "e": 27177, "s": 27162, "text": "kapoorsagar226" }, { "code": null, "e": 27189, "s": 27177, "text": "anikakapoor" }, { "code": null, "e": 27192, "s": 27189, "text": "C#" }, { "code": null, "e": 27290, "s": 27192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27313, "s": 27290, "text": "Extension Method in C#" }, { "code": null, "e": 27341, "s": 27313, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27358, "s": 27341, "text": "C# | Inheritance" }, { "code": null, "e": 27380, "s": 27358, "text": "Partial Classes in C#" }, { "code": null, "e": 27409, "s": 27380, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27449, "s": 27409, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27472, "s": 27449, "text": "Switch Statement in C#" }, { "code": null, "e": 27515, "s": 27472, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27555, "s": 27515, "text": "Convert String to Character Array in C#" } ]
Custom Notifications in ElectronJS - GeeksforGeeks
11 May, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Electron at its core is a NodeJS application having capabilities to interact with the native OS environment such as File System, System Tray etc. For creating interactive native OS applications Electron needs to integrate itself with OS functionalities. One such crucial functionality is Desktop Notifications. All three operating systems have provisions for sending Desktop Notifications. Electron provides the built-in Notification Module which allows the application to send Custom Notifications, using the operating systems native notification APIs to display it. This tutorial will demonstrate how to create Custom Desktop Notifications using the Notification Module. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Notifications In Electron: The Notification Module is a part of the Main Process. To import and use the Notification Module in the Renderer Process, we can use the Remote Module provided by Electron. In this tutorial, we will also be using Electron Remote. For more details on the Remote Module, Refer this link. Project Structure:Example: We will start by building the basic Electron Application by following the given steps.Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --save-devThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key.package.json:{ "name": "electron-notification", "version": "1.0.0", "description": "Custom notification in Electron", "main": "main.js", "scripts": { "start": "electron" }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's// specific main process code. You can also put them in // separate files and require them here.Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script></body> </html>Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:npm startNotification Options: Now we will create a Custom Desktop Notification on a Windows Machine. The Notification Module provides certain Instance Events, Instance Methods, and Options which are Operating System specific. If a property that is incompatible with the native OS is used, it is Simple Ignored. A detailed list of the same is provided below.title: String Supported by all OS. The Title of the Notification shown at top of Notification Windowsubtitle: String (Optional) Supported by macOS only. A Subtitle of the Notification. Shown Below the Titlebody: String Supported by all OS. The Body of the Notification Windowsilent: Boolean (Optional) Supported by all OS. Whether or not to omit OS Notification Sound on displaying the notificationicon: String (Optional) Supported by all OS. An Icon to display in the Notification Window. For the purpose of this tutorial, used a PNG image of the Electron logo saved in the ‘assets’ folderhasReply: Boolean (Optional) Supported by macOS only. To display an Inline Reply Option to the Notification windowreplyPlaceholder: String (Optional) Supported by macOS only. The Placeholder for the ‘hasReply’ input fieldurgency: String (Optional) Supported by Linux Only. The urgency of the Notification. Values can be ‘normal’, ‘critical’, or ‘low’.closeButtonText: String (Optional) Supported by macOS only. A Custom Title for the Close Button of the NotificationtimeoutType: String (Optional) Supported in Windows and Linux operating Systems. The Timeout Duration of the Notification. Values can be ‘default’ or ‘never’. As of Electron 8.0+, there is a bug associated with this property. Setting the value as ‘never’, the notification should only disappear on manual intervention by the user. However, This is not the case. Irrespective of the value, the notification will disappear on its own. You can follow the bug tracking here.actions: Object (Optional) Supported by macOS only. Actions to add to the Notification. It is an Array of Objects. Every Object consists of ‘type’ and ‘text’. There are certain limitations associated with using this property. In the case of multiple actions defined, only the first one is used. If multiple actions are provided then they will be listed as additional actions, i.e. displayed when the mouse is active over the first action button. This case is also incompatible with hasReply property and will be ignored if hasReply: true.For a detailed explanation, Refer this link.sound: String (Optional) Supported by macOS only. Sound File to play when the Notification is displayed. Any of the default sounds present in macOS can also be used in addition to a custom sound file. The sound file needs to be present within the app bundle or any of the following locations that are mentioned in this link. In this tutorial the custom sound file is present within the assets folder as sound.mp3The Notification Module also provides us with a Static Method,Notification.isSupported(). Returns a Boolean value stating whether Notifications are Supported in the Current System or not. In the index.html file, add the following code before the script tag.index.html:<br><br> <strong> Trigger Custom Notifications in Electron </strong> <button id="trigger"> Trigger Custom Notification </button>Output:The Trigger Custom Notification Button does not have any functionality associated with it. We will add an EventListener to the button to trigger the Custom Notification. We will also add EventListener to the Notification object. Create the index.js file following the project Structure and perform the following changes.index.js:const electron = require('electron');const path = require('path') // Importing the Notification Module from Electron,// Since it is a Part of the Main Process, Using the// Remote Module to Import it in Renderer Processconst Notification = electron.remote.Notification; var button = document.getElementById('trigger'); const options = { title: 'Custom Notification', subtitle: 'Subtitle of the Notification', body: 'Body of Custom Notification', silent: false, icon: path.join(__dirname, '../assets/image.png'), hasReply: true, timeoutType: 'never', replyPlaceholder: 'Reply Here', sound: path.join(__dirname, '../assets/sound.mp3'), urgency: 'critical' closeButtonText: 'Close Button' actions: [ { type: 'button', text: 'Show Button' }]} // Instantiating a new Notifications Object// with custom Optionsconst customNotification = new Notification(options); button.addEventListener('click', function (event) { console.log(Notification.isSupported()); customNotification.show(); // customNotification.close();}); // Instance Events for the new Notification ObjectcustomNotification.addListener('click', () => { console.log('Notification is Clicked');}); customNotification.addListener('show', () => { console.log('Notification is shown');}); customNotification.addListener('close', () => { console.log('Notification is Automatically Closed')});customNotification.show() Instance Method to immediately show the Notification to the user. In case the Notification has been shown, dismisses the previous one and creates a new Notification with identical Options.customNotification.close() Instance Method to dismiss the Notification.Event: ‘click’ Event is Emitted, when user clicks on the Notification.Event: ‘show’ Event is Emitted, when notification is shown to the user.Event: ‘close’ Event is Emitted, when Notification is Closed. Not guaranteed to be emitted every time. Notification will automatically close irrespective of ‘timeoutType’ property.Output:Instance events: Notification Module also provides two more Instance events which are supported by macOS only.// Emitted when user clicks the reply button from // 'hasReply: true' propertycustomNotification.addListener('reply', (event, reply) => { console.log('Replied String is - ', reply);}); // Emitted when the user clicks on any one action // defined in the actions:[{}] propertycustomNotification.addListener('action', (event, index) => { console.log('Index of the action clicked is - ', index);});Instance Properties: Electron Notification Module also Supports Instance Properties which can be set to the Notification Object. They can be used instead of Options and can also change pre-defined options when triggering Custom Notifications. A detailed list is given below.customNotification.title = 'Title has been Changed'; // Supported in macOScustomNotification.subtitle = 'Subtitle of the Notification'; customNotification.body = 'Body has been changed'; // Supported in macOScustomNotification.closeButtonText = 'Close Button' // Supported in macOScustomNotification.hasReply = true; // Supported in macOScustomNotification.replyPlaceholder = 'Reply Placeholder'; customNotification.silent = false; // Supported in LinuxcustomNotification.urgency = 'low'; // Supported in Windows and Linux OS // This is a bug, as described above.customNotification.timeoutType= 'default'; Example: We will start by building the basic Electron Application by following the given steps. Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --save-devThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key.package.json:{ "name": "electron-notification", "version": "1.0.0", "description": "Custom notification in Electron", "main": "main.js", "scripts": { "start": "electron" }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } npm init To generate the package.json file. Install Electron using npm if it is not installed. npm install electron --save-dev This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key. package.json: { "name": "electron-notification", "version": "1.0.0", "description": "Custom notification in Electron", "main": "main.js", "scripts": { "start": "electron" }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's// specific main process code. You can also put them in // separate files and require them here. main.js: const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's// specific main process code. You can also put them in // separate files and require them here. Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script></body> </html> index.html: <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script></body> </html> Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:npm start npm start Notification Options: Now we will create a Custom Desktop Notification on a Windows Machine. The Notification Module provides certain Instance Events, Instance Methods, and Options which are Operating System specific. If a property that is incompatible with the native OS is used, it is Simple Ignored. A detailed list of the same is provided below. title: String Supported by all OS. The Title of the Notification shown at top of Notification Window subtitle: String (Optional) Supported by macOS only. A Subtitle of the Notification. Shown Below the Title body: String Supported by all OS. The Body of the Notification Window silent: Boolean (Optional) Supported by all OS. Whether or not to omit OS Notification Sound on displaying the notification icon: String (Optional) Supported by all OS. An Icon to display in the Notification Window. For the purpose of this tutorial, used a PNG image of the Electron logo saved in the ‘assets’ folder hasReply: Boolean (Optional) Supported by macOS only. To display an Inline Reply Option to the Notification window replyPlaceholder: String (Optional) Supported by macOS only. The Placeholder for the ‘hasReply’ input field urgency: String (Optional) Supported by Linux Only. The urgency of the Notification. Values can be ‘normal’, ‘critical’, or ‘low’. closeButtonText: String (Optional) Supported by macOS only. A Custom Title for the Close Button of the Notification timeoutType: String (Optional) Supported in Windows and Linux operating Systems. The Timeout Duration of the Notification. Values can be ‘default’ or ‘never’. As of Electron 8.0+, there is a bug associated with this property. Setting the value as ‘never’, the notification should only disappear on manual intervention by the user. However, This is not the case. Irrespective of the value, the notification will disappear on its own. You can follow the bug tracking here. actions: Object (Optional) Supported by macOS only. Actions to add to the Notification. It is an Array of Objects. Every Object consists of ‘type’ and ‘text’. There are certain limitations associated with using this property. In the case of multiple actions defined, only the first one is used. If multiple actions are provided then they will be listed as additional actions, i.e. displayed when the mouse is active over the first action button. This case is also incompatible with hasReply property and will be ignored if hasReply: true.For a detailed explanation, Refer this link. sound: String (Optional) Supported by macOS only. Sound File to play when the Notification is displayed. Any of the default sounds present in macOS can also be used in addition to a custom sound file. The sound file needs to be present within the app bundle or any of the following locations that are mentioned in this link. In this tutorial the custom sound file is present within the assets folder as sound.mp3 The Notification Module also provides us with a Static Method,Notification.isSupported(). Returns a Boolean value stating whether Notifications are Supported in the Current System or not. In the index.html file, add the following code before the script tag. index.html:<br><br> <strong> Trigger Custom Notifications in Electron </strong> <button id="trigger"> Trigger Custom Notification </button> <br><br> <strong> Trigger Custom Notifications in Electron </strong> <button id="trigger"> Trigger Custom Notification </button> Output: The Trigger Custom Notification Button does not have any functionality associated with it. We will add an EventListener to the button to trigger the Custom Notification. We will also add EventListener to the Notification object. Create the index.js file following the project Structure and perform the following changes. index.js:const electron = require('electron');const path = require('path') // Importing the Notification Module from Electron,// Since it is a Part of the Main Process, Using the// Remote Module to Import it in Renderer Processconst Notification = electron.remote.Notification; var button = document.getElementById('trigger'); const options = { title: 'Custom Notification', subtitle: 'Subtitle of the Notification', body: 'Body of Custom Notification', silent: false, icon: path.join(__dirname, '../assets/image.png'), hasReply: true, timeoutType: 'never', replyPlaceholder: 'Reply Here', sound: path.join(__dirname, '../assets/sound.mp3'), urgency: 'critical' closeButtonText: 'Close Button' actions: [ { type: 'button', text: 'Show Button' }]} // Instantiating a new Notifications Object// with custom Optionsconst customNotification = new Notification(options); button.addEventListener('click', function (event) { console.log(Notification.isSupported()); customNotification.show(); // customNotification.close();}); // Instance Events for the new Notification ObjectcustomNotification.addListener('click', () => { console.log('Notification is Clicked');}); customNotification.addListener('show', () => { console.log('Notification is shown');}); customNotification.addListener('close', () => { console.log('Notification is Automatically Closed')}); const electron = require('electron');const path = require('path') // Importing the Notification Module from Electron,// Since it is a Part of the Main Process, Using the// Remote Module to Import it in Renderer Processconst Notification = electron.remote.Notification; var button = document.getElementById('trigger'); const options = { title: 'Custom Notification', subtitle: 'Subtitle of the Notification', body: 'Body of Custom Notification', silent: false, icon: path.join(__dirname, '../assets/image.png'), hasReply: true, timeoutType: 'never', replyPlaceholder: 'Reply Here', sound: path.join(__dirname, '../assets/sound.mp3'), urgency: 'critical' closeButtonText: 'Close Button' actions: [ { type: 'button', text: 'Show Button' }]} // Instantiating a new Notifications Object// with custom Optionsconst customNotification = new Notification(options); button.addEventListener('click', function (event) { console.log(Notification.isSupported()); customNotification.show(); // customNotification.close();}); // Instance Events for the new Notification ObjectcustomNotification.addListener('click', () => { console.log('Notification is Clicked');}); customNotification.addListener('show', () => { console.log('Notification is shown');}); customNotification.addListener('close', () => { console.log('Notification is Automatically Closed')}); customNotification.show() Instance Method to immediately show the Notification to the user. In case the Notification has been shown, dismisses the previous one and creates a new Notification with identical Options. customNotification.close() Instance Method to dismiss the Notification. Event: ‘click’ Event is Emitted, when user clicks on the Notification. Event: ‘show’ Event is Emitted, when notification is shown to the user. Event: ‘close’ Event is Emitted, when Notification is Closed. Not guaranteed to be emitted every time. Notification will automatically close irrespective of ‘timeoutType’ property. Output: Instance events: Notification Module also provides two more Instance events which are supported by macOS only. // Emitted when user clicks the reply button from // 'hasReply: true' propertycustomNotification.addListener('reply', (event, reply) => { console.log('Replied String is - ', reply);}); // Emitted when the user clicks on any one action // defined in the actions:[{}] propertycustomNotification.addListener('action', (event, index) => { console.log('Index of the action clicked is - ', index);}); Instance Properties: Electron Notification Module also Supports Instance Properties which can be set to the Notification Object. They can be used instead of Options and can also change pre-defined options when triggering Custom Notifications. A detailed list is given below. customNotification.title = 'Title has been Changed'; // Supported in macOScustomNotification.subtitle = 'Subtitle of the Notification'; customNotification.body = 'Body has been changed'; // Supported in macOScustomNotification.closeButtonText = 'Close Button' // Supported in macOScustomNotification.hasReply = true; // Supported in macOScustomNotification.replyPlaceholder = 'Reply Placeholder'; customNotification.silent = false; // Supported in LinuxcustomNotification.urgency = 'low'; // Supported in Windows and Linux OS // This is a bug, as described above.customNotification.timeoutType= 'default'; Output: Upon adding these Instance properties to the index.js file, we should see the following. All non-compatible instance properties are ignored.My Personal Notes arrow_drop_upSave ElectronJS Articles HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Mutex vs Semaphore Analysis of Algorithms | Set 3 (Asymptotic Notations) Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) Understanding "extern" keyword in C 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": 24277, "s": 24249, "text": "\n11 May, 2020" }, { "code": null, "e": 24577, "s": 24277, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 25250, "s": 24577, "text": "Electron at its core is a NodeJS application having capabilities to interact with the native OS environment such as File System, System Tray etc. For creating interactive native OS applications Electron needs to integrate itself with OS functionalities. One such crucial functionality is Desktop Notifications. All three operating systems have provisions for sending Desktop Notifications. Electron provides the built-in Notification Module which allows the application to send Custom Notifications, using the operating systems native notification APIs to display it. This tutorial will demonstrate how to create Custom Desktop Notifications using the Notification Module." }, { "code": null, "e": 25420, "s": 25250, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 25733, "s": 25420, "text": "Notifications In Electron: The Notification Module is a part of the Main Process. To import and use the Notification Module in the Renderer Process, we can use the Remote Module provided by Electron. In this tutorial, we will also be using Electron Remote. For more details on the Remote Module, Refer this link." }, { "code": null, "e": 36220, "s": 25733, "text": "Project Structure:Example: We will start by building the basic Electron Application by following the given steps.Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --save-devThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key.package.json:{\n \"name\": \"electron-notification\",\n \"version\": \"1.0.0\",\n \"description\": \"Custom notification in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n }\n}\nStep 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's// specific main process code. You can also put them in // separate files and require them here.Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script></body> </html>Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:npm startNotification Options: Now we will create a Custom Desktop Notification on a Windows Machine. The Notification Module provides certain Instance Events, Instance Methods, and Options which are Operating System specific. If a property that is incompatible with the native OS is used, it is Simple Ignored. A detailed list of the same is provided below.title: String Supported by all OS. The Title of the Notification shown at top of Notification Windowsubtitle: String (Optional) Supported by macOS only. A Subtitle of the Notification. Shown Below the Titlebody: String Supported by all OS. The Body of the Notification Windowsilent: Boolean (Optional) Supported by all OS. Whether or not to omit OS Notification Sound on displaying the notificationicon: String (Optional) Supported by all OS. An Icon to display in the Notification Window. For the purpose of this tutorial, used a PNG image of the Electron logo saved in the ‘assets’ folderhasReply: Boolean (Optional) Supported by macOS only. To display an Inline Reply Option to the Notification windowreplyPlaceholder: String (Optional) Supported by macOS only. The Placeholder for the ‘hasReply’ input fieldurgency: String (Optional) Supported by Linux Only. The urgency of the Notification. Values can be ‘normal’, ‘critical’, or ‘low’.closeButtonText: String (Optional) Supported by macOS only. A Custom Title for the Close Button of the NotificationtimeoutType: String (Optional) Supported in Windows and Linux operating Systems. The Timeout Duration of the Notification. Values can be ‘default’ or ‘never’. As of Electron 8.0+, there is a bug associated with this property. Setting the value as ‘never’, the notification should only disappear on manual intervention by the user. However, This is not the case. Irrespective of the value, the notification will disappear on its own. You can follow the bug tracking here.actions: Object (Optional) Supported by macOS only. Actions to add to the Notification. It is an Array of Objects. Every Object consists of ‘type’ and ‘text’. There are certain limitations associated with using this property. In the case of multiple actions defined, only the first one is used. If multiple actions are provided then they will be listed as additional actions, i.e. displayed when the mouse is active over the first action button. This case is also incompatible with hasReply property and will be ignored if hasReply: true.For a detailed explanation, Refer this link.sound: String (Optional) Supported by macOS only. Sound File to play when the Notification is displayed. Any of the default sounds present in macOS can also be used in addition to a custom sound file. The sound file needs to be present within the app bundle or any of the following locations that are mentioned in this link. In this tutorial the custom sound file is present within the assets folder as sound.mp3The Notification Module also provides us with a Static Method,Notification.isSupported(). Returns a Boolean value stating whether Notifications are Supported in the Current System or not. In the index.html file, add the following code before the script tag.index.html:<br><br> <strong> Trigger Custom Notifications in Electron </strong> <button id=\"trigger\"> Trigger Custom Notification </button>Output:The Trigger Custom Notification Button does not have any functionality associated with it. We will add an EventListener to the button to trigger the Custom Notification. We will also add EventListener to the Notification object. Create the index.js file following the project Structure and perform the following changes.index.js:const electron = require('electron');const path = require('path') // Importing the Notification Module from Electron,// Since it is a Part of the Main Process, Using the// Remote Module to Import it in Renderer Processconst Notification = electron.remote.Notification; var button = document.getElementById('trigger'); const options = { title: 'Custom Notification', subtitle: 'Subtitle of the Notification', body: 'Body of Custom Notification', silent: false, icon: path.join(__dirname, '../assets/image.png'), hasReply: true, timeoutType: 'never', replyPlaceholder: 'Reply Here', sound: path.join(__dirname, '../assets/sound.mp3'), urgency: 'critical' closeButtonText: 'Close Button' actions: [ { type: 'button', text: 'Show Button' }]} // Instantiating a new Notifications Object// with custom Optionsconst customNotification = new Notification(options); button.addEventListener('click', function (event) { console.log(Notification.isSupported()); customNotification.show(); // customNotification.close();}); // Instance Events for the new Notification ObjectcustomNotification.addListener('click', () => { console.log('Notification is Clicked');}); customNotification.addListener('show', () => { console.log('Notification is shown');}); customNotification.addListener('close', () => { console.log('Notification is Automatically Closed')});customNotification.show() Instance Method to immediately show the Notification to the user. In case the Notification has been shown, dismisses the previous one and creates a new Notification with identical Options.customNotification.close() Instance Method to dismiss the Notification.Event: ‘click’ Event is Emitted, when user clicks on the Notification.Event: ‘show’ Event is Emitted, when notification is shown to the user.Event: ‘close’ Event is Emitted, when Notification is Closed. Not guaranteed to be emitted every time. Notification will automatically close irrespective of ‘timeoutType’ property.Output:Instance events: Notification Module also provides two more Instance events which are supported by macOS only.// Emitted when user clicks the reply button from // 'hasReply: true' propertycustomNotification.addListener('reply', (event, reply) => { console.log('Replied String is - ', reply);}); // Emitted when the user clicks on any one action // defined in the actions:[{}] propertycustomNotification.addListener('action', (event, index) => { console.log('Index of the action clicked is - ', index);});Instance Properties: Electron Notification Module also Supports Instance Properties which can be set to the Notification Object. They can be used instead of Options and can also change pre-defined options when triggering Custom Notifications. A detailed list is given below.customNotification.title = 'Title has been Changed'; // Supported in macOScustomNotification.subtitle = 'Subtitle of the Notification'; customNotification.body = 'Body has been changed'; // Supported in macOScustomNotification.closeButtonText = 'Close Button' // Supported in macOScustomNotification.hasReply = true; // Supported in macOScustomNotification.replyPlaceholder = 'Reply Placeholder'; customNotification.silent = false; // Supported in LinuxcustomNotification.urgency = 'low'; // Supported in Windows and Linux OS // This is a bug, as described above.customNotification.timeoutType= 'default';" }, { "code": null, "e": 36316, "s": 36220, "text": "Example: We will start by building the basic Electron Application by following the given steps." }, { "code": null, "e": 37099, "s": 36316, "text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --save-devThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key.package.json:{\n \"name\": \"electron-notification\",\n \"version\": \"1.0.0\",\n \"description\": \"Custom notification in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n }\n}\n" }, { "code": null, "e": 37108, "s": 37099, "text": "npm init" }, { "code": null, "e": 37194, "s": 37108, "text": "To generate the package.json file. Install Electron using npm if it is not installed." }, { "code": null, "e": 37226, "s": 37194, "text": "npm install electron --save-dev" }, { "code": null, "e": 37468, "s": 37226, "text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key." }, { "code": null, "e": 37482, "s": 37468, "text": "package.json:" }, { "code": null, "e": 37796, "s": 37482, "text": "{\n \"name\": \"electron-notification\",\n \"version\": \"1.0.0\",\n \"description\": \"Custom notification in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n }\n}\n" }, { "code": null, "e": 39289, "s": 37796, "text": "Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's// specific main process code. You can also put them in // separate files and require them here." }, { "code": null, "e": 39298, "s": 39289, "text": "main.js:" }, { "code": "const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are // no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your app's// specific main process code. You can also put them in // separate files and require them here.", "e": 40509, "s": 39298, "text": null }, { "code": null, "e": 41418, "s": 40509, "text": "Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script></body> </html>" }, { "code": null, "e": 41430, "s": 41418, "text": "index.html:" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /></head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script></body> </html>", "e": 42123, "s": 41430, "text": null }, { "code": null, "e": 42250, "s": 42123, "text": "Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:npm start" }, { "code": null, "e": 42260, "s": 42250, "text": "npm start" }, { "code": null, "e": 42610, "s": 42260, "text": "Notification Options: Now we will create a Custom Desktop Notification on a Windows Machine. The Notification Module provides certain Instance Events, Instance Methods, and Options which are Operating System specific. If a property that is incompatible with the native OS is used, it is Simple Ignored. A detailed list of the same is provided below." }, { "code": null, "e": 42711, "s": 42610, "text": "title: String Supported by all OS. The Title of the Notification shown at top of Notification Window" }, { "code": null, "e": 42818, "s": 42711, "text": "subtitle: String (Optional) Supported by macOS only. A Subtitle of the Notification. Shown Below the Title" }, { "code": null, "e": 42888, "s": 42818, "text": "body: String Supported by all OS. The Body of the Notification Window" }, { "code": null, "e": 43012, "s": 42888, "text": "silent: Boolean (Optional) Supported by all OS. Whether or not to omit OS Notification Sound on displaying the notification" }, { "code": null, "e": 43205, "s": 43012, "text": "icon: String (Optional) Supported by all OS. An Icon to display in the Notification Window. For the purpose of this tutorial, used a PNG image of the Electron logo saved in the ‘assets’ folder" }, { "code": null, "e": 43320, "s": 43205, "text": "hasReply: Boolean (Optional) Supported by macOS only. To display an Inline Reply Option to the Notification window" }, { "code": null, "e": 43428, "s": 43320, "text": "replyPlaceholder: String (Optional) Supported by macOS only. The Placeholder for the ‘hasReply’ input field" }, { "code": null, "e": 43559, "s": 43428, "text": "urgency: String (Optional) Supported by Linux Only. The urgency of the Notification. Values can be ‘normal’, ‘critical’, or ‘low’." }, { "code": null, "e": 43675, "s": 43559, "text": "closeButtonText: String (Optional) Supported by macOS only. A Custom Title for the Close Button of the Notification" }, { "code": null, "e": 44146, "s": 43675, "text": "timeoutType: String (Optional) Supported in Windows and Linux operating Systems. The Timeout Duration of the Notification. Values can be ‘default’ or ‘never’. As of Electron 8.0+, there is a bug associated with this property. Setting the value as ‘never’, the notification should only disappear on manual intervention by the user. However, This is not the case. Irrespective of the value, the notification will disappear on its own. You can follow the bug tracking here." }, { "code": null, "e": 44729, "s": 44146, "text": "actions: Object (Optional) Supported by macOS only. Actions to add to the Notification. It is an Array of Objects. Every Object consists of ‘type’ and ‘text’. There are certain limitations associated with using this property. In the case of multiple actions defined, only the first one is used. If multiple actions are provided then they will be listed as additional actions, i.e. displayed when the mouse is active over the first action button. This case is also incompatible with hasReply property and will be ignored if hasReply: true.For a detailed explanation, Refer this link." }, { "code": null, "e": 45142, "s": 44729, "text": "sound: String (Optional) Supported by macOS only. Sound File to play when the Notification is displayed. Any of the default sounds present in macOS can also be used in addition to a custom sound file. The sound file needs to be present within the app bundle or any of the following locations that are mentioned in this link. In this tutorial the custom sound file is present within the assets folder as sound.mp3" }, { "code": null, "e": 45400, "s": 45142, "text": "The Notification Module also provides us with a Static Method,Notification.isSupported(). Returns a Boolean value stating whether Notifications are Supported in the Current System or not. In the index.html file, add the following code before the script tag." }, { "code": null, "e": 45560, "s": 45400, "text": "index.html:<br><br> <strong> Trigger Custom Notifications in Electron </strong> <button id=\"trigger\"> Trigger Custom Notification </button>" }, { "code": "<br><br> <strong> Trigger Custom Notifications in Electron </strong> <button id=\"trigger\"> Trigger Custom Notification </button>", "e": 45709, "s": 45560, "text": null }, { "code": null, "e": 45717, "s": 45709, "text": "Output:" }, { "code": null, "e": 46038, "s": 45717, "text": "The Trigger Custom Notification Button does not have any functionality associated with it. We will add an EventListener to the button to trigger the Custom Notification. We will also add EventListener to the Notification object. Create the index.js file following the project Structure and perform the following changes." }, { "code": null, "e": 47476, "s": 46038, "text": "index.js:const electron = require('electron');const path = require('path') // Importing the Notification Module from Electron,// Since it is a Part of the Main Process, Using the// Remote Module to Import it in Renderer Processconst Notification = electron.remote.Notification; var button = document.getElementById('trigger'); const options = { title: 'Custom Notification', subtitle: 'Subtitle of the Notification', body: 'Body of Custom Notification', silent: false, icon: path.join(__dirname, '../assets/image.png'), hasReply: true, timeoutType: 'never', replyPlaceholder: 'Reply Here', sound: path.join(__dirname, '../assets/sound.mp3'), urgency: 'critical' closeButtonText: 'Close Button' actions: [ { type: 'button', text: 'Show Button' }]} // Instantiating a new Notifications Object// with custom Optionsconst customNotification = new Notification(options); button.addEventListener('click', function (event) { console.log(Notification.isSupported()); customNotification.show(); // customNotification.close();}); // Instance Events for the new Notification ObjectcustomNotification.addListener('click', () => { console.log('Notification is Clicked');}); customNotification.addListener('show', () => { console.log('Notification is shown');}); customNotification.addListener('close', () => { console.log('Notification is Automatically Closed')});" }, { "code": "const electron = require('electron');const path = require('path') // Importing the Notification Module from Electron,// Since it is a Part of the Main Process, Using the// Remote Module to Import it in Renderer Processconst Notification = electron.remote.Notification; var button = document.getElementById('trigger'); const options = { title: 'Custom Notification', subtitle: 'Subtitle of the Notification', body: 'Body of Custom Notification', silent: false, icon: path.join(__dirname, '../assets/image.png'), hasReply: true, timeoutType: 'never', replyPlaceholder: 'Reply Here', sound: path.join(__dirname, '../assets/sound.mp3'), urgency: 'critical' closeButtonText: 'Close Button' actions: [ { type: 'button', text: 'Show Button' }]} // Instantiating a new Notifications Object// with custom Optionsconst customNotification = new Notification(options); button.addEventListener('click', function (event) { console.log(Notification.isSupported()); customNotification.show(); // customNotification.close();}); // Instance Events for the new Notification ObjectcustomNotification.addListener('click', () => { console.log('Notification is Clicked');}); customNotification.addListener('show', () => { console.log('Notification is shown');}); customNotification.addListener('close', () => { console.log('Notification is Automatically Closed')});", "e": 48905, "s": 47476, "text": null }, { "code": null, "e": 49120, "s": 48905, "text": "customNotification.show() Instance Method to immediately show the Notification to the user. In case the Notification has been shown, dismisses the previous one and creates a new Notification with identical Options." }, { "code": null, "e": 49192, "s": 49120, "text": "customNotification.close() Instance Method to dismiss the Notification." }, { "code": null, "e": 49263, "s": 49192, "text": "Event: ‘click’ Event is Emitted, when user clicks on the Notification." }, { "code": null, "e": 49335, "s": 49263, "text": "Event: ‘show’ Event is Emitted, when notification is shown to the user." }, { "code": null, "e": 49516, "s": 49335, "text": "Event: ‘close’ Event is Emitted, when Notification is Closed. Not guaranteed to be emitted every time. Notification will automatically close irrespective of ‘timeoutType’ property." }, { "code": null, "e": 49524, "s": 49516, "text": "Output:" }, { "code": null, "e": 49635, "s": 49524, "text": "Instance events: Notification Module also provides two more Instance events which are supported by macOS only." }, { "code": "// Emitted when user clicks the reply button from // 'hasReply: true' propertycustomNotification.addListener('reply', (event, reply) => { console.log('Replied String is - ', reply);}); // Emitted when the user clicks on any one action // defined in the actions:[{}] propertycustomNotification.addListener('action', (event, index) => { console.log('Index of the action clicked is - ', index);});", "e": 50037, "s": 49635, "text": null }, { "code": null, "e": 50312, "s": 50037, "text": "Instance Properties: Electron Notification Module also Supports Instance Properties which can be set to the Notification Object. They can be used instead of Options and can also change pre-defined options when triggering Custom Notifications. A detailed list is given below." }, { "code": "customNotification.title = 'Title has been Changed'; // Supported in macOScustomNotification.subtitle = 'Subtitle of the Notification'; customNotification.body = 'Body has been changed'; // Supported in macOScustomNotification.closeButtonText = 'Close Button' // Supported in macOScustomNotification.hasReply = true; // Supported in macOScustomNotification.replyPlaceholder = 'Reply Placeholder'; customNotification.silent = false; // Supported in LinuxcustomNotification.urgency = 'low'; // Supported in Windows and Linux OS // This is a bug, as described above.customNotification.timeoutType= 'default';", "e": 50931, "s": 50312, "text": null }, { "code": null, "e": 51115, "s": 50931, "text": "Output: Upon adding these Instance properties to the index.js file, we should see the following. All non-compatible instance properties are ignored.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 51126, "s": 51115, "text": "ElectronJS" }, { "code": null, "e": 51135, "s": 51126, "text": "Articles" }, { "code": null, "e": 51140, "s": 51135, "text": "HTML" }, { "code": null, "e": 51151, "s": 51140, "text": "JavaScript" }, { "code": null, "e": 51159, "s": 51151, "text": "Node.js" }, { "code": null, "e": 51176, "s": 51159, "text": "Web Technologies" }, { "code": null, "e": 51181, "s": 51176, "text": "HTML" }, { "code": null, "e": 51279, "s": 51181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51288, "s": 51279, "text": "Comments" }, { "code": null, "e": 51301, "s": 51288, "text": "Old Comments" }, { "code": null, "e": 51338, "s": 51301, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 51357, "s": 51338, "text": "Mutex vs Semaphore" }, { "code": null, "e": 51411, "s": 51357, "text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)" }, { "code": null, "e": 51474, "s": 51411, "text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" }, { "code": null, "e": 51510, "s": 51474, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 51572, "s": 51510, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 51622, "s": 51572, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 51682, "s": 51622, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 51730, "s": 51682, "text": "How to update Node.js and NPM to next version ?" } ]
Tryit Editor v3.7
Tryit: HTML article element
[]
Repdigit Numbers - GeeksforGeeks
23 Mar, 2021 Repdigit Number is a number N which has all the digits in its representation in base B equal.Some of the Repdigit number are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55.... Given a number N, the task is to check if N is an Repdigit Number in Base B or not. If N is a Repdigit Number in Base B then print “Yes” else print “No”.Examples: Input: N = 2000, B = 7 Output: Yes Explanation: 2000 in base 7 is 5555 which has all digits equal.Input: N = 112, B = 10 Output: No Approach: One by one find all the digits of N in base B. Compare every digit with its previous digit. If any digit is not equal to the previous digit then return false. Otherwise return true. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to check// if a number is Repdigit #include <iostream>using namespace std; // Function to check if a number// is a Repdigit numberbool isRepdigit(int num, int b){ // To store previous digit (Assigning // initial value which is less than any // digit) int prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num) { int digit = num % b; num /= b; if (prev != -1 && digit != prev) return false; prev = digit; } return true;} // Driver codeint main(){ int num = 2000, base = 7; isRepdigit(num, base) ? cout << "Yes" : cout << "No"; return 0;} // Java implementation to check// if a number is Repdigitclass GFG{ // Function to check if a number// is a Repdigit numberstatic boolean isRepdigit(int num, int b){ // To store previous digit (Assigning // initial value which is less than any // digit) int prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num != 0) { int digit = num % b; num /= b; if (prev != -1 && digit != prev) return false; prev = digit; } return true;} // Driver codepublic static void main(String args[]){ int num = 2000, base1 = 7; if(isRepdigit(num, base1)) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by Code_Mech # Python3 implementation to check# if a number is Repdigit # Function to check if a number# is a Repdigit numberdef isRepdigit(num, b) : # To store previous digit (Assigning # initial value which is less than any # digit) prev = -1 # Traverse all digits from right to # left and check if any digit is # smaller than previous. while (num) : digit = num % b num //= b if (prev != -1 and digit != prev) : return False prev = digit return True # Driver codenum = 2000base = 7if(isRepdigit(num, base)): print("Yes")else: print("No") # This code is contributed by Vishal Maurya. // C# implementation to check// if a number is Repdigitusing System;class GFG{ // Function to check if a number// is a Repdigit numberstatic bool isRepdigit(int num, int b){ // To store previous digit (Assigning // initial value which is less than any // digit) int prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num != 0) { int digit = num % b; num /= b; if (prev != -1 && digit != prev) return false; prev = digit; } return true;} // Driver codepublic static void Main(){ int num = 2000, base1 = 7; if(isRepdigit(num, base1)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by Code_Mech <script> // Javascript implementation to check// if a number is Repdigit // Function to check if a number // is a Repdigit number function isRepdigit( num ,b) { // To store previous digit (Assigning // initial value which is less than any // digit) let prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num != 0) { let digit = num % b; num = parseInt(num/b); if (prev != -1 && digit != prev) return false; prev = digit; } return true; } // Driver code let num = 2000, base1 = 7; if (isRepdigit(num, base1)) { document.write("Yes"); } else { document.write("No"); } // This code contributed by gauravrajput1 </script> Yes Time Complexity: O(n) Reference: http://www.numbersaplenty.com/set/repdigit/ vishu2908 Code_Mech GauravRajput1 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Fizz Buzz Implementation Program to multiply two matrices Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24301, "s": 24273, "text": "\n23 Mar, 2021" }, { "code": null, "e": 24429, "s": 24301, "text": "Repdigit Number is a number N which has all the digits in its representation in base B equal.Some of the Repdigit number are: " }, { "code": null, "e": 24484, "s": 24429, "text": "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55.... " }, { "code": null, "e": 24651, "s": 24486, "text": "Given a number N, the task is to check if N is an Repdigit Number in Base B or not. If N is a Repdigit Number in Base B then print “Yes” else print “No”.Examples: " }, { "code": null, "e": 24785, "s": 24651, "text": "Input: N = 2000, B = 7 Output: Yes Explanation: 2000 in base 7 is 5555 which has all digits equal.Input: N = 112, B = 10 Output: No " }, { "code": null, "e": 24799, "s": 24787, "text": "Approach: " }, { "code": null, "e": 24846, "s": 24799, "text": "One by one find all the digits of N in base B." }, { "code": null, "e": 24891, "s": 24846, "text": "Compare every digit with its previous digit." }, { "code": null, "e": 24958, "s": 24891, "text": "If any digit is not equal to the previous digit then return false." }, { "code": null, "e": 24981, "s": 24958, "text": "Otherwise return true." }, { "code": null, "e": 25033, "s": 24981, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25037, "s": 25033, "text": "C++" }, { "code": null, "e": 25042, "s": 25037, "text": "Java" }, { "code": null, "e": 25050, "s": 25042, "text": "Python3" }, { "code": null, "e": 25053, "s": 25050, "text": "C#" }, { "code": null, "e": 25064, "s": 25053, "text": "Javascript" }, { "code": "// C++ implementation to check// if a number is Repdigit #include <iostream>using namespace std; // Function to check if a number// is a Repdigit numberbool isRepdigit(int num, int b){ // To store previous digit (Assigning // initial value which is less than any // digit) int prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num) { int digit = num % b; num /= b; if (prev != -1 && digit != prev) return false; prev = digit; } return true;} // Driver codeint main(){ int num = 2000, base = 7; isRepdigit(num, base) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 25793, "s": 25064, "text": null }, { "code": "// Java implementation to check// if a number is Repdigitclass GFG{ // Function to check if a number// is a Repdigit numberstatic boolean isRepdigit(int num, int b){ // To store previous digit (Assigning // initial value which is less than any // digit) int prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num != 0) { int digit = num % b; num /= b; if (prev != -1 && digit != prev) return false; prev = digit; } return true;} // Driver codepublic static void main(String args[]){ int num = 2000, base1 = 7; if(isRepdigit(num, base1)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by Code_Mech", "e": 26607, "s": 25793, "text": null }, { "code": "# Python3 implementation to check# if a number is Repdigit # Function to check if a number# is a Repdigit numberdef isRepdigit(num, b) : # To store previous digit (Assigning # initial value which is less than any # digit) prev = -1 # Traverse all digits from right to # left and check if any digit is # smaller than previous. while (num) : digit = num % b num //= b if (prev != -1 and digit != prev) : return False prev = digit return True # Driver codenum = 2000base = 7if(isRepdigit(num, base)): print(\"Yes\")else: print(\"No\") # This code is contributed by Vishal Maurya.", "e": 27258, "s": 26607, "text": null }, { "code": "// C# implementation to check// if a number is Repdigitusing System;class GFG{ // Function to check if a number// is a Repdigit numberstatic bool isRepdigit(int num, int b){ // To store previous digit (Assigning // initial value which is less than any // digit) int prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num != 0) { int digit = num % b; num /= b; if (prev != -1 && digit != prev) return false; prev = digit; } return true;} // Driver codepublic static void Main(){ int num = 2000, base1 = 7; if(isRepdigit(num, base1)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by Code_Mech", "e": 28061, "s": 27258, "text": null }, { "code": "<script> // Javascript implementation to check// if a number is Repdigit // Function to check if a number // is a Repdigit number function isRepdigit( num ,b) { // To store previous digit (Assigning // initial value which is less than any // digit) let prev = -1; // Traverse all digits from right to // left and check if any digit is // smaller than previous. while (num != 0) { let digit = num % b; num = parseInt(num/b); if (prev != -1 && digit != prev) return false; prev = digit; } return true; } // Driver code let num = 2000, base1 = 7; if (isRepdigit(num, base1)) { document.write(\"Yes\"); } else { document.write(\"No\"); } // This code contributed by gauravrajput1 </script>", "e": 28947, "s": 28061, "text": null }, { "code": null, "e": 28951, "s": 28947, "text": "Yes" }, { "code": null, "e": 29031, "s": 28953, "text": "Time Complexity: O(n) Reference: http://www.numbersaplenty.com/set/repdigit/ " }, { "code": null, "e": 29041, "s": 29031, "text": "vishu2908" }, { "code": null, "e": 29051, "s": 29041, "text": "Code_Mech" }, { "code": null, "e": 29065, "s": 29051, "text": "GauravRajput1" }, { "code": null, "e": 29072, "s": 29065, "text": "series" }, { "code": null, "e": 29085, "s": 29072, "text": "Mathematical" }, { "code": null, "e": 29098, "s": 29085, "text": "Mathematical" }, { "code": null, "e": 29105, "s": 29098, "text": "series" }, { "code": null, "e": 29203, "s": 29105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29212, "s": 29203, "text": "Comments" }, { "code": null, "e": 29225, "s": 29212, "text": "Old Comments" }, { "code": null, "e": 29270, "s": 29225, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 29302, "s": 29270, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29346, "s": 29302, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29380, "s": 29346, "text": "Program to add two binary strings" }, { "code": null, "e": 29405, "s": 29380, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29438, "s": 29405, "text": "Program to multiply two matrices" }, { "code": null, "e": 29477, "s": 29438, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 29528, "s": 29477, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 29599, "s": 29528, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Get contents of a Tkinter Entry widget
An Entry widget is a basic one-line character widget that supports only single-line text input. An Entry widget can be defined by initializing the Entry(parent, width) constructor. To validate the Entry widget, we can use the get() method which results in the character entered in the Entry widget. Let us define an Entry widget that accepts single-line text input, and we will print the character that is input in the Entry widget. #Import the required Libraries from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame win = Tk() #Set the geometry of Tkinter frame win.geometry("750x250") def get_content(): #Get the content of Entry Widget print(entry.get()) #Create an entry widget entry= Entry(win, width= 40) entry.pack(pady= 20) #Create a button to validate the entry widget button= ttk.Button(win, text= "Get Content", command= get_content) button.pack(pady=10) win.mainloop() Running the above code will display a window that will contain an Entry widget and a button to get the content of the Entry widget. Now click the "Get Content" Button to print the Content of Entry Widget. Once we click the Button, it will print the output as, Hello World!
[ { "code": null, "e": 1243, "s": 1062, "text": "An Entry widget is a basic one-line character widget that supports only single-line text input. An Entry widget can be defined by initializing the Entry(parent, width) constructor." }, { "code": null, "e": 1361, "s": 1243, "text": "To validate the Entry widget, we can use the get() method which results in the character entered in the Entry widget." }, { "code": null, "e": 1495, "s": 1361, "text": "Let us define an Entry widget that accepts single-line text input, and we will print the character that is input in the Entry widget." }, { "code": null, "e": 1984, "s": 1495, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter frame\nwin = Tk()\n\n#Set the geometry of Tkinter frame\nwin.geometry(\"750x250\")\ndef get_content():\n #Get the content of Entry Widget\n print(entry.get())\n\n#Create an entry widget\nentry= Entry(win, width= 40)\nentry.pack(pady= 20)\n\n#Create a button to validate the entry widget\nbutton= ttk.Button(win, text= \"Get Content\", command= get_content)\nbutton.pack(pady=10)\n\nwin.mainloop()" }, { "code": null, "e": 2116, "s": 1984, "text": "Running the above code will display a window that will contain an Entry widget and a button to get the content of the Entry widget." }, { "code": null, "e": 2244, "s": 2116, "text": "Now click the \"Get Content\" Button to print the Content of Entry Widget. Once we click the Button, it will print the output as," }, { "code": null, "e": 2257, "s": 2244, "text": "Hello World!" } ]
How to clone an ArrayList to another ArrayList in Java? - GeeksforGeeks
08 Dec, 2020 The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object. Below program illustrate the Java.util.ArrayList.clone() method: Example: Java // Java program to clone an ArrayList to another ArrayList import java.util.ArrayList;public class GFG { public static void main(String a[]) { // create ArrayList ArrayList<String> ArrList1 = new ArrayList<String>(); // Insert elements in ArrayList ArrList1.add("Mukul"); ArrList1.add("Rahul"); ArrList1.add("Suraj"); ArrList1.add("Mayank"); // print ArrayList1 System.out.println("Original ArrayList = " + ArrList1); // clone ArrayList ArrayList ArrList2 = (ArrayList)ArrList1.clone(); // print ArrayList2 System.out.println("Clone ArrayList2 = " + ArrList2); }} Original ArrayList = [Mukul, Rahul, Suraj, Mayank] Clone ArrayList2 = [Mukul, Rahul, Suraj, Mayank] Example 2: Java // Java code to illustrate clone() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); // Use add() method // to add elements in the list list.add(16); list.add(32); list.add(48); // Displaying the list System.out.println("First ArrayList: " + list); // Creating another linked list and copying // creates a shallow copy ArrayList<Integer> sec_list = (ArrayList<Integer>)list.clone(); sec_list.add(64); // Displaying the list System.out.println("First ArrayList: " + list); // Displaying the other linked list System.out.println("Second ArrayList is: " + sec_list); }} Output First ArrayList: [16, 32, 48] First ArrayList: [16, 32, 48] Second ArrayList is: [16, 32, 48, 64] Java-ArrayList 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 HashMap in Java with Examples Interfaces in Java Initialize an ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java How to Iterate HashMap in Java?
[ { "code": null, "e": 24025, "s": 23997, "text": "\n08 Dec, 2020" }, { "code": null, "e": 24181, "s": 24025, "text": "The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. " }, { "code": null, "e": 24189, "s": 24181, "text": "Syntax:" }, { "code": null, "e": 24212, "s": 24189, "text": "public Object clone();" }, { "code": null, "e": 24282, "s": 24212, "text": "Return Value: This function returns a copy of the instance of Object." }, { "code": null, "e": 24347, "s": 24282, "text": "Below program illustrate the Java.util.ArrayList.clone() method:" }, { "code": null, "e": 24356, "s": 24347, "text": "Example:" }, { "code": null, "e": 24361, "s": 24356, "text": "Java" }, { "code": "// Java program to clone an ArrayList to another ArrayList import java.util.ArrayList;public class GFG { public static void main(String a[]) { // create ArrayList ArrayList<String> ArrList1 = new ArrayList<String>(); // Insert elements in ArrayList ArrList1.add(\"Mukul\"); ArrList1.add(\"Rahul\"); ArrList1.add(\"Suraj\"); ArrList1.add(\"Mayank\"); // print ArrayList1 System.out.println(\"Original ArrayList = \" + ArrList1); // clone ArrayList ArrayList ArrList2 = (ArrayList)ArrList1.clone(); // print ArrayList2 System.out.println(\"Clone ArrayList2 = \" + ArrList2); }}", "e": 25112, "s": 24361, "text": null }, { "code": null, "e": 25212, "s": 25112, "text": "Original ArrayList = [Mukul, Rahul, Suraj, Mayank]\nClone ArrayList2 = [Mukul, Rahul, Suraj, Mayank]" }, { "code": null, "e": 25223, "s": 25212, "text": "Example 2:" }, { "code": null, "e": 25228, "s": 25223, "text": "Java" }, { "code": "// Java code to illustrate clone() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String args[]) { // Creating an empty ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); // Use add() method // to add elements in the list list.add(16); list.add(32); list.add(48); // Displaying the list System.out.println(\"First ArrayList: \" + list); // Creating another linked list and copying // creates a shallow copy ArrayList<Integer> sec_list = (ArrayList<Integer>)list.clone(); sec_list.add(64); // Displaying the list System.out.println(\"First ArrayList: \" + list); // Displaying the other linked list System.out.println(\"Second ArrayList is: \" + sec_list); }}", "e": 26133, "s": 25228, "text": null }, { "code": null, "e": 26140, "s": 26133, "text": "Output" }, { "code": null, "e": 26238, "s": 26140, "text": "First ArrayList: [16, 32, 48]\nFirst ArrayList: [16, 32, 48]\nSecond ArrayList is: [16, 32, 48, 64]" }, { "code": null, "e": 26253, "s": 26238, "text": "Java-ArrayList" }, { "code": null, "e": 26260, "s": 26253, "text": "Picked" }, { "code": null, "e": 26284, "s": 26260, "text": "Technical Scripter 2020" }, { "code": null, "e": 26289, "s": 26284, "text": "Java" }, { "code": null, "e": 26303, "s": 26289, "text": "Java Programs" }, { "code": null, "e": 26322, "s": 26303, "text": "Technical Scripter" }, { "code": null, "e": 26327, "s": 26322, "text": "Java" }, { "code": null, "e": 26425, "s": 26327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26434, "s": 26425, "text": "Comments" }, { "code": null, "e": 26447, "s": 26434, "text": "Old Comments" }, { "code": null, "e": 26477, "s": 26447, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26496, "s": 26477, "text": "Interfaces in Java" }, { "code": null, "e": 26528, "s": 26496, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26560, "s": 26528, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26580, "s": 26560, "text": "Stack Class in Java" }, { "code": null, "e": 26624, "s": 26580, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26652, "s": 26624, "text": "Initializing a List in Java" }, { "code": null, "e": 26678, "s": 26652, "text": "Java Programming Examples" }, { "code": null, "e": 26712, "s": 26678, "text": "Convert Double to Integer in Java" } ]
Productivity Tip: Adding Jupyter and Anaconda shortcuts to Windows’ right-click context menu | by Gabriel Signoretti | Towards Data Science
This is going to be a quick one and, if you are anything like me and is used to mostly work with Linux computers for development, you may find this useful. As I just said, for most of my life I’ve primarily used Ubuntu systems to do almost all of my programming work. But recently I've gotten a little fed up with some compatibility issues and decided to give good old Windows a try. So, there I went setting up the fresh Windows installation, configuring the necessary programming environments, downloading and installing the Anaconda package and whatnot. Then I noticed the lack of a simple but extremely handy tool that I used quite a lot on Ubuntu: the “Open in Terminal” option on the right-click context menu. This might seem like not a big deal at all (and honestly, it might not even be haha), but it saved me a lot of time when I was working on multiple Jupyter notebooks in different folders. With it I could just navigate to the desired folder, open a new terminal window directly from there, run Jupyter, and just start working, instead of having to navigate to each and every folder from the terminal itself. So, I don’t know how much of a ‘missing feature’ this is for most people, but it certainly is for me! And if you’ve read this far, chances are that it is for you too, so lets cut to the chase, shall we? After searching for the possibility online, I discovered that it’s not so cut and dry to do, but is not that complicated either, so bear with me! The first thing to do is discover the PATH to your Anaconda installation. If you used the default location during the installation process it should be located somewhere like this: C:\Users\<your_user>\anaconda3 We need to know this location because we are going to be using the activate.bat batch script from the Scripts folder in order to open the Anaconda Prompt. The next thing you need to do is run the Registry Editor. To do so, just type regedit.exe in the Windows search and it should pop up even before you finished typing it. You should pay close attention for the next steps, as you DO NOT want to to mess with the wrong things here. So be advised! With that out of the way, lets get back to it. As you can see, there are a bunch of folders to the left, and you will have to navigate to the following one: HKEY_CLASSES_ROOT > Directory > Background > shell You can either find it by navigating the folder tree to the left or by typing the corresponding path in the address bar on top. Once you open it, you should see something like this on the left panel: This is where you can add custom commands to the context menu. As you can see, since I have both VSCode and PyCham installed, they each have a command listed here, as both of them have a “Open with ... “ option listed in the right-click context menu. So, in the shell folder you should create 3 new keys, one for each new command that we would like to add: AnacondaPrompt, JupyterLab, and JupyterNotebook. Right click on the shell folder and select New > Key. These keys should be on the same level as the cdm, PowerShell, and whichever other more appear on your system, otherwise it won’t work. When you select one of the new keys you should see something like this on the right panel: Double click on the default attribute and fill the value data field with the text that you want to appear on the context menu for that key: “Open folder in AnacondaPrompt”, “Open with JupyterLab”, and “Open with Jupyter Notebook” for example. After that, you should add a new key named command under each of the new keys that we have created (weird, I know). Then you should now have something like this: Finally, the last thing you have to do for it to work is to add the actual commands themselves, obviously. To do that you are going to repeat the processes that you did to add the text to the other keys: edit the default attribute on the command key and fill the value data field, but instead of plain text, you will write the actual command. For each of the corresponding keys they are: AnacondaPrompt > command: cmd.exe /K C:\Users\<your_user>\anaconda3\Scripts\activate.bat JupyterLab > command: cmd.exe /K C:\Users\<your_user>\anaconda3\Scripts\activate.bat && jupyter-lab JupyterNotebook > command: cmd.exe /K C:\Users\<your_user>\anaconda3\Scripts\activate.bat && jupyter-notebook Don’t forget to add your actual user name, or even change the entire anaconda path in case yours was installed somewhere else in your system. The important thing is to provide the correct address to the activavate.bat script, as it is the default script used to actually open the anaconda prompt. If you are curious to understand how these commands work, here is what each section of them does: cmd.exe — Opens the CMD on the respective folder (the one that you are right-clicking in); /K — Tells the CMD to issue the command that follows, and then stay open so that you can view results or type more commands; C:\...\activate.bat — Runs the activate.bat scripts, opening the AnacondaPrompt environment; && — An “And” logical operator. It runs the next command on the line after the first one has returned successfully; jupyter-lab or jupyter-notebook — command used to open either the jupyter lab or the jupyter notebook, whichever you prefer; So, after all that, you should have 3 brand new and working options on your right-click context menu! Go check it out in some folder, it will be looking something like this: Well, that’s great, it works like a charm! but the menu sure looks a little empty, doesn’t it? some might even say incomplete... Yes! and its actually pretty simple to do so. Go back to the new keys that you added (the top level ones, not the command ones), right click on it and select New > String. This should create a new row of attributes on the right panel. Name the attribute as Icon and provide a path to an icon file (.ico extension) as the value data. I`ve used some of the default icons that ship with the Anaconda package (how convenient) in my keys, here is where to locate them: AnacondaPrompt > Icon: C:\Users\<your_user>\anaconda3\Menu\anaconda-navigator.ico JupyterLab and JupyterNotebook > Icon: C:\Users\<your_user>\anaconda3\Menu\jupyter.ico Then, your final (much cooler) context menu will look like the one shown below, but feel free to use other icons if you prefer. With that we conclude this brief tutorial, I hope that you liked it and maybe even learned something new! Thanks for the read! You can export these newly created keys for backup or if you want to add them to other installations of Windows. All you have to do is right click on the desired key and select export; You can also add other commands using the same process to suit your specific needs, but be careful not to mess with other options that you are not familiar with. After all, with great power comes great responsibility;
[ { "code": null, "e": 431, "s": 47, "text": "This is going to be a quick one and, if you are anything like me and is used to mostly work with Linux computers for development, you may find this useful. As I just said, for most of my life I’ve primarily used Ubuntu systems to do almost all of my programming work. But recently I've gotten a little fed up with some compatibility issues and decided to give good old Windows a try." }, { "code": null, "e": 763, "s": 431, "text": "So, there I went setting up the fresh Windows installation, configuring the necessary programming environments, downloading and installing the Anaconda package and whatnot. Then I noticed the lack of a simple but extremely handy tool that I used quite a lot on Ubuntu: the “Open in Terminal” option on the right-click context menu." }, { "code": null, "e": 1169, "s": 763, "text": "This might seem like not a big deal at all (and honestly, it might not even be haha), but it saved me a lot of time when I was working on multiple Jupyter notebooks in different folders. With it I could just navigate to the desired folder, open a new terminal window directly from there, run Jupyter, and just start working, instead of having to navigate to each and every folder from the terminal itself." }, { "code": null, "e": 1372, "s": 1169, "text": "So, I don’t know how much of a ‘missing feature’ this is for most people, but it certainly is for me! And if you’ve read this far, chances are that it is for you too, so lets cut to the chase, shall we?" }, { "code": null, "e": 1518, "s": 1372, "text": "After searching for the possibility online, I discovered that it’s not so cut and dry to do, but is not that complicated either, so bear with me!" }, { "code": null, "e": 1699, "s": 1518, "text": "The first thing to do is discover the PATH to your Anaconda installation. If you used the default location during the installation process it should be located somewhere like this:" }, { "code": null, "e": 1730, "s": 1699, "text": "C:\\Users\\<your_user>\\anaconda3" }, { "code": null, "e": 1885, "s": 1730, "text": "We need to know this location because we are going to be using the activate.bat batch script from the Scripts folder in order to open the Anaconda Prompt." }, { "code": null, "e": 2054, "s": 1885, "text": "The next thing you need to do is run the Registry Editor. To do so, just type regedit.exe in the Windows search and it should pop up even before you finished typing it." }, { "code": null, "e": 2178, "s": 2054, "text": "You should pay close attention for the next steps, as you DO NOT want to to mess with the wrong things here. So be advised!" }, { "code": null, "e": 2335, "s": 2178, "text": "With that out of the way, lets get back to it. As you can see, there are a bunch of folders to the left, and you will have to navigate to the following one:" }, { "code": null, "e": 2386, "s": 2335, "text": "HKEY_CLASSES_ROOT > Directory > Background > shell" }, { "code": null, "e": 2586, "s": 2386, "text": "You can either find it by navigating the folder tree to the left or by typing the corresponding path in the address bar on top. Once you open it, you should see something like this on the left panel:" }, { "code": null, "e": 2837, "s": 2586, "text": "This is where you can add custom commands to the context menu. As you can see, since I have both VSCode and PyCham installed, they each have a command listed here, as both of them have a “Open with ... “ option listed in the right-click context menu." }, { "code": null, "e": 3182, "s": 2837, "text": "So, in the shell folder you should create 3 new keys, one for each new command that we would like to add: AnacondaPrompt, JupyterLab, and JupyterNotebook. Right click on the shell folder and select New > Key. These keys should be on the same level as the cdm, PowerShell, and whichever other more appear on your system, otherwise it won’t work." }, { "code": null, "e": 3273, "s": 3182, "text": "When you select one of the new keys you should see something like this on the right panel:" }, { "code": null, "e": 3516, "s": 3273, "text": "Double click on the default attribute and fill the value data field with the text that you want to appear on the context menu for that key: “Open folder in AnacondaPrompt”, “Open with JupyterLab”, and “Open with Jupyter Notebook” for example." }, { "code": null, "e": 3678, "s": 3516, "text": "After that, you should add a new key named command under each of the new keys that we have created (weird, I know). Then you should now have something like this:" }, { "code": null, "e": 4066, "s": 3678, "text": "Finally, the last thing you have to do for it to work is to add the actual commands themselves, obviously. To do that you are going to repeat the processes that you did to add the text to the other keys: edit the default attribute on the command key and fill the value data field, but instead of plain text, you will write the actual command. For each of the corresponding keys they are:" }, { "code": null, "e": 4092, "s": 4066, "text": "AnacondaPrompt > command:" }, { "code": null, "e": 4155, "s": 4092, "text": "cmd.exe /K C:\\Users\\<your_user>\\anaconda3\\Scripts\\activate.bat" }, { "code": null, "e": 4177, "s": 4155, "text": "JupyterLab > command:" }, { "code": null, "e": 4255, "s": 4177, "text": "cmd.exe /K C:\\Users\\<your_user>\\anaconda3\\Scripts\\activate.bat && jupyter-lab" }, { "code": null, "e": 4282, "s": 4255, "text": "JupyterNotebook > command:" }, { "code": null, "e": 4365, "s": 4282, "text": "cmd.exe /K C:\\Users\\<your_user>\\anaconda3\\Scripts\\activate.bat && jupyter-notebook" }, { "code": null, "e": 4662, "s": 4365, "text": "Don’t forget to add your actual user name, or even change the entire anaconda path in case yours was installed somewhere else in your system. The important thing is to provide the correct address to the activavate.bat script, as it is the default script used to actually open the anaconda prompt." }, { "code": null, "e": 4760, "s": 4662, "text": "If you are curious to understand how these commands work, here is what each section of them does:" }, { "code": null, "e": 4851, "s": 4760, "text": "cmd.exe — Opens the CMD on the respective folder (the one that you are right-clicking in);" }, { "code": null, "e": 4976, "s": 4851, "text": "/K — Tells the CMD to issue the command that follows, and then stay open so that you can view results or type more commands;" }, { "code": null, "e": 5069, "s": 4976, "text": "C:\\...\\activate.bat — Runs the activate.bat scripts, opening the AnacondaPrompt environment;" }, { "code": null, "e": 5185, "s": 5069, "text": "&& — An “And” logical operator. It runs the next command on the line after the first one has returned successfully;" }, { "code": null, "e": 5310, "s": 5185, "text": "jupyter-lab or jupyter-notebook — command used to open either the jupyter lab or the jupyter notebook, whichever you prefer;" }, { "code": null, "e": 5484, "s": 5310, "text": "So, after all that, you should have 3 brand new and working options on your right-click context menu! Go check it out in some folder, it will be looking something like this:" }, { "code": null, "e": 5613, "s": 5484, "text": "Well, that’s great, it works like a charm! but the menu sure looks a little empty, doesn’t it? some might even say incomplete..." }, { "code": null, "e": 5946, "s": 5613, "text": "Yes! and its actually pretty simple to do so. Go back to the new keys that you added (the top level ones, not the command ones), right click on it and select New > String. This should create a new row of attributes on the right panel. Name the attribute as Icon and provide a path to an icon file (.ico extension) as the value data." }, { "code": null, "e": 6077, "s": 5946, "text": "I`ve used some of the default icons that ship with the Anaconda package (how convenient) in my keys, here is where to locate them:" }, { "code": null, "e": 6100, "s": 6077, "text": "AnacondaPrompt > Icon:" }, { "code": null, "e": 6159, "s": 6100, "text": "C:\\Users\\<your_user>\\anaconda3\\Menu\\anaconda-navigator.ico" }, { "code": null, "e": 6198, "s": 6159, "text": "JupyterLab and JupyterNotebook > Icon:" }, { "code": null, "e": 6246, "s": 6198, "text": "C:\\Users\\<your_user>\\anaconda3\\Menu\\jupyter.ico" }, { "code": null, "e": 6374, "s": 6246, "text": "Then, your final (much cooler) context menu will look like the one shown below, but feel free to use other icons if you prefer." }, { "code": null, "e": 6501, "s": 6374, "text": "With that we conclude this brief tutorial, I hope that you liked it and maybe even learned something new! Thanks for the read!" }, { "code": null, "e": 6686, "s": 6501, "text": "You can export these newly created keys for backup or if you want to add them to other installations of Windows. All you have to do is right click on the desired key and select export;" } ]
Enumerable.Repeat method in C#
Enumerable.Repeat method is part of System.Linq namespace. It returns a collection with repeated elements in C#. Firstly, set which element you want to repeat and how many times. As an example, let us see how to repeat number 10, five times − Enumerable.Repeat(10, 5); The following is the complete example − Live Demo using System; using System.Linq; class Demo { static void Main() { var val = Enumerable.Repeat(10, 5); foreach (int res in val) { Console.WriteLine(res); } } } 10 10 10 10 10
[ { "code": null, "e": 1121, "s": 1062, "text": "Enumerable.Repeat method is part of System.Linq namespace." }, { "code": null, "e": 1175, "s": 1121, "text": "It returns a collection with repeated elements in C#." }, { "code": null, "e": 1241, "s": 1175, "text": "Firstly, set which element you want to repeat and how many times." }, { "code": null, "e": 1305, "s": 1241, "text": "As an example, let us see how to repeat number 10, five times −" }, { "code": null, "e": 1331, "s": 1305, "text": "Enumerable.Repeat(10, 5);" }, { "code": null, "e": 1371, "s": 1331, "text": "The following is the complete example −" }, { "code": null, "e": 1382, "s": 1371, "text": " Live Demo" }, { "code": null, "e": 1575, "s": 1382, "text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n var val = Enumerable.Repeat(10, 5);\n foreach (int res in val) {\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 1590, "s": 1575, "text": "10\n10\n10\n10\n10" } ]
Text Summarization with GloVe Embeddings.. | by Sayak Misra | Towards Data Science
This story is a continuation to our previous blog post, where we have discussed the basics of text summarization, the various approaches and how we implemented an encoder-decoder model(with attention) to solve the problem in hand. Just to recap, text summarization is a process of generating a concise and meaningful summary of text from multiple text resources such as books, news articles, blog posts, research papers, emails, and tweets. We have seen an encoder-decoder(seqtoseq) model is a perfect choice for summarization tasks, so we will continue with that architecture. Here in addition to that we will be using GloVe pre-trained word embeddings to give our model a head-start, and check if it really performs better in understanding the language semantics and in turn summarizing. “Word embeddings” are a family of natural language processing techniques aiming at mapping semantic meaning into a geometric space. This is done by associating a numeric vector to every word in a dictionary, such that the distance (e.g. L2 distance or more commonly cosine distance) between any two vectors would capture part of the semantic relationship between the two associated words. The geometric space formed by these vectors is called an embedding space. For instance, “coconut” and “polar bear” are words that are semantically quite different, so a reasonable embedding space would represent them as vectors that would be very far apart. But “kitchen” and “dinner” are related words, so they should be embedded close to each other. Ideally, in a good embeddings space, the “path” (a vector) to go from “kitchen” and “dinner” would capture precisely the semantic relationship between these two concepts. In this case the relationship is “where x occurs”, so you would expect the vector kitchen - dinner (difference of the two embedding vectors, i.e. path to go from dinner to kitchen) to capture this "where x occurs" relationship. Basically, we should have the vectorial identity: dinner + (where x occurs) = kitchen (at least approximately). If that's indeed the case, then we can use such a relationship vector to answer questions. For instance, starting from a new vector, e.g. "work", and applying this relationship vector, we should get sometime meaningful, e.g. work + (where x occurs) = office, answering "where does work occur?". Word embeddings are computed by applying dimensionality reduction techniques to datasets of co-occurence statistics between words in a corpus of text. This can be done via neural networks (the “word2vec” technique), or via matrix factorization. We can play with this beautiful Tensorflow projector, to get a better understanding of word embeddings. The two of the most common word embeddings are: Word2Vec and GloVe, and both of them are equally popular. But GloVe(“Global Vectors for Word Representation”) as the name suggests is better for preserving the global contexts as it creates a global co-occurrence matrix by estimating the probability a given word will co-occur with other words. Here for summarization the global context is a necessity, so we are moving ahead with GloVe but in most of the use-cases there is very little between the two to choose from. Specifically, we will use the 100-dimensional GloVe embeddings of 400k words computed on a 2014 dump of English Wikipedia. You can download them here (warning: following this link will start a 822MB download). Here is the complete code of the LSTM Encoder-Decoder model with Attention and GloVe embeddings added to it. We are not going through the details of the model architecture, as we have discussed it in our previous blog-post and in turn focusing on adding the GloVe embeddings to it and assessing the performance. First let’s download and unzip the GloVe embeddings. !wget 'http://nlp.stanford.edu/data/glove.6B.zip'!unzip '/content/glove.6B.zip' Next, we compute an index mapping words to known embeddings, by parsing the data dump of pre-trained embeddings: embeddings_index = {}f = open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt'))for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefsf.close()print('Found %s word vectors.' % len(embeddings_index)) At this point we can leverage our embedding_index dictionary and our word_index to compute our embedding matrix: EMBEDDING_DIM = 100embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix[i] = embedding_vector We load this embedding matrix into an Embedding layer. Note that we set trainable=False to prevent the weights from being updated during training. Previously we used the default Embedding layer, withtrainable=True , which learned the Embeddings through the training process. embedding_layer = Embedding(len(word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=False) Here, we are using the 100 dimension GloVe embeddings and the embeddings are saved in glove.6B.100d.txt. An Embedding layer should be fed sequences of integers, i.e. a 2D input of shape (samples, indices). These input sequences should be padded so that they all have the same length in a batch of input data (although an Embedding layer is capable of processing sequence of heterogenous length, if you don't pass an explicit input_length argument to the layer). All that the Embedding layer does is to map the integer inputs to the vectors found at the corresponding index in the embedding matrix, i.e. the sequence [1, 2] would be converted to [embeddings[1], embeddings[2]]. This means that the output of the Embedding layer will be a 3D tensor of shape (samples, sequence_length, embedding_dim). We get a validation loss of around 2.25 which is similar to what we got without the GloVe embeddings. Review: tried several tassimo discs gevalia best coffee ever tasted coffee snob love coffee Original summary: great coffee Predicted summary: best coffee everReview: almonds unbelievable amount salt love salt top bought brand stores never salty maybe machine went wacko processing cannot eat unless take time try wipe salt talks forever Original summary: too salty to eat Predicted summary: not the bestReview: sure much nourishment hair getting shampoo dandruff nice job cleaning hair leaving tangle free somewhat conditioned using pantene pro shampoo compares favorably pantene like way bottle made easy open dispensing far like way hair coming shampooing seem little better started used bottle seen little improvement really much improvement would say shampoo would worth trying nice job cleaning smells nice bottle easy use relatively inexpensive keep mind make many shampoos one person likes another hate Original summary: seems like an excellent shampoo Predicted summary: great for hair As we can see from the above examples, it performs quite well on most of the use-cases. Here is the colab-notebook of the complete implementation. To keep it short, NO. Though this model might produce better summaries for some cases but it can not be affirmed that it has better results across all the examples. The main reason behind this is we have enough records here(100000 to be exact) for our Embedding layer in Encoder-Decoder model to learn the semantics of the language, so it performed quite well even without the pre-trained embeddings. Pre-trained models (like GloVe here) can be used with great improvements in results if we have a short dataset. If the number of records in the dataset are less, the Embedding layer won’t be able to generate proper embeddings of it’s own and in those cases using pre-trained embeddings will enhance the performance accuracy. Here we have seen how we can add pre-trained embeddings to our existing LSTM Encoder-Decoder architecture, though the results didn’t spike up much, but it can perform brilliantly for a smaller dataset. We can further improve the summarising process by a huge margin if we can leverage the true essence of Transfer Learning, by using state-of-the pre-trained language models like: BERTSum, BART, T5. In our next story we shall look into the details of those model and how wonderfully they can summarize texts.
[ { "code": null, "e": 278, "s": 47, "text": "This story is a continuation to our previous blog post, where we have discussed the basics of text summarization, the various approaches and how we implemented an encoder-decoder model(with attention) to solve the problem in hand." }, { "code": null, "e": 488, "s": 278, "text": "Just to recap, text summarization is a process of generating a concise and meaningful summary of text from multiple text resources such as books, news articles, blog posts, research papers, emails, and tweets." }, { "code": null, "e": 837, "s": 488, "text": "We have seen an encoder-decoder(seqtoseq) model is a perfect choice for summarization tasks, so we will continue with that architecture. Here in addition to that we will be using GloVe pre-trained word embeddings to give our model a head-start, and check if it really performs better in understanding the language semantics and in turn summarizing." }, { "code": null, "e": 1300, "s": 837, "text": "“Word embeddings” are a family of natural language processing techniques aiming at mapping semantic meaning into a geometric space. This is done by associating a numeric vector to every word in a dictionary, such that the distance (e.g. L2 distance or more commonly cosine distance) between any two vectors would capture part of the semantic relationship between the two associated words. The geometric space formed by these vectors is called an embedding space." }, { "code": null, "e": 1578, "s": 1300, "text": "For instance, “coconut” and “polar bear” are words that are semantically quite different, so a reasonable embedding space would represent them as vectors that would be very far apart. But “kitchen” and “dinner” are related words, so they should be embedded close to each other." }, { "code": null, "e": 2384, "s": 1578, "text": "Ideally, in a good embeddings space, the “path” (a vector) to go from “kitchen” and “dinner” would capture precisely the semantic relationship between these two concepts. In this case the relationship is “where x occurs”, so you would expect the vector kitchen - dinner (difference of the two embedding vectors, i.e. path to go from dinner to kitchen) to capture this \"where x occurs\" relationship. Basically, we should have the vectorial identity: dinner + (where x occurs) = kitchen (at least approximately). If that's indeed the case, then we can use such a relationship vector to answer questions. For instance, starting from a new vector, e.g. \"work\", and applying this relationship vector, we should get sometime meaningful, e.g. work + (where x occurs) = office, answering \"where does work occur?\"." }, { "code": null, "e": 2629, "s": 2384, "text": "Word embeddings are computed by applying dimensionality reduction techniques to datasets of co-occurence statistics between words in a corpus of text. This can be done via neural networks (the “word2vec” technique), or via matrix factorization." }, { "code": null, "e": 2733, "s": 2629, "text": "We can play with this beautiful Tensorflow projector, to get a better understanding of word embeddings." }, { "code": null, "e": 3250, "s": 2733, "text": "The two of the most common word embeddings are: Word2Vec and GloVe, and both of them are equally popular. But GloVe(“Global Vectors for Word Representation”) as the name suggests is better for preserving the global contexts as it creates a global co-occurrence matrix by estimating the probability a given word will co-occur with other words. Here for summarization the global context is a necessity, so we are moving ahead with GloVe but in most of the use-cases there is very little between the two to choose from." }, { "code": null, "e": 3460, "s": 3250, "text": "Specifically, we will use the 100-dimensional GloVe embeddings of 400k words computed on a 2014 dump of English Wikipedia. You can download them here (warning: following this link will start a 822MB download)." }, { "code": null, "e": 3569, "s": 3460, "text": "Here is the complete code of the LSTM Encoder-Decoder model with Attention and GloVe embeddings added to it." }, { "code": null, "e": 3772, "s": 3569, "text": "We are not going through the details of the model architecture, as we have discussed it in our previous blog-post and in turn focusing on adding the GloVe embeddings to it and assessing the performance." }, { "code": null, "e": 3825, "s": 3772, "text": "First let’s download and unzip the GloVe embeddings." }, { "code": null, "e": 3905, "s": 3825, "text": "!wget 'http://nlp.stanford.edu/data/glove.6B.zip'!unzip '/content/glove.6B.zip'" }, { "code": null, "e": 4018, "s": 3905, "text": "Next, we compute an index mapping words to known embeddings, by parsing the data dump of pre-trained embeddings:" }, { "code": null, "e": 4302, "s": 4018, "text": "embeddings_index = {}f = open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt'))for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefsf.close()print('Found %s word vectors.' % len(embeddings_index))" }, { "code": null, "e": 4415, "s": 4302, "text": "At this point we can leverage our embedding_index dictionary and our word_index to compute our embedding matrix:" }, { "code": null, "e": 4728, "s": 4415, "text": "EMBEDDING_DIM = 100embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix[i] = embedding_vector" }, { "code": null, "e": 5003, "s": 4728, "text": "We load this embedding matrix into an Embedding layer. Note that we set trainable=False to prevent the weights from being updated during training. Previously we used the default Embedding layer, withtrainable=True , which learned the Embeddings through the training process." }, { "code": null, "e": 5254, "s": 5003, "text": "embedding_layer = Embedding(len(word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=False)" }, { "code": null, "e": 5359, "s": 5254, "text": "Here, we are using the 100 dimension GloVe embeddings and the embeddings are saved in glove.6B.100d.txt." }, { "code": null, "e": 5716, "s": 5359, "text": "An Embedding layer should be fed sequences of integers, i.e. a 2D input of shape (samples, indices). These input sequences should be padded so that they all have the same length in a batch of input data (although an Embedding layer is capable of processing sequence of heterogenous length, if you don't pass an explicit input_length argument to the layer)." }, { "code": null, "e": 6053, "s": 5716, "text": "All that the Embedding layer does is to map the integer inputs to the vectors found at the corresponding index in the embedding matrix, i.e. the sequence [1, 2] would be converted to [embeddings[1], embeddings[2]]. This means that the output of the Embedding layer will be a 3D tensor of shape (samples, sequence_length, embedding_dim)." }, { "code": null, "e": 6155, "s": 6053, "text": "We get a validation loss of around 2.25 which is similar to what we got without the GloVe embeddings." }, { "code": null, "e": 7158, "s": 6155, "text": "Review: tried several tassimo discs gevalia best coffee ever tasted coffee snob love coffee Original summary: great coffee Predicted summary: best coffee everReview: almonds unbelievable amount salt love salt top bought brand stores never salty maybe machine went wacko processing cannot eat unless take time try wipe salt talks forever Original summary: too salty to eat Predicted summary: not the bestReview: sure much nourishment hair getting shampoo dandruff nice job cleaning hair leaving tangle free somewhat conditioned using pantene pro shampoo compares favorably pantene like way bottle made easy open dispensing far like way hair coming shampooing seem little better started used bottle seen little improvement really much improvement would say shampoo would worth trying nice job cleaning smells nice bottle easy use relatively inexpensive keep mind make many shampoos one person likes another hate Original summary: seems like an excellent shampoo Predicted summary: great for hair" }, { "code": null, "e": 7246, "s": 7158, "text": "As we can see from the above examples, it performs quite well on most of the use-cases." }, { "code": null, "e": 7305, "s": 7246, "text": "Here is the colab-notebook of the complete implementation." }, { "code": null, "e": 7327, "s": 7305, "text": "To keep it short, NO." }, { "code": null, "e": 7706, "s": 7327, "text": "Though this model might produce better summaries for some cases but it can not be affirmed that it has better results across all the examples. The main reason behind this is we have enough records here(100000 to be exact) for our Embedding layer in Encoder-Decoder model to learn the semantics of the language, so it performed quite well even without the pre-trained embeddings." }, { "code": null, "e": 8031, "s": 7706, "text": "Pre-trained models (like GloVe here) can be used with great improvements in results if we have a short dataset. If the number of records in the dataset are less, the Embedding layer won’t be able to generate proper embeddings of it’s own and in those cases using pre-trained embeddings will enhance the performance accuracy." }, { "code": null, "e": 8233, "s": 8031, "text": "Here we have seen how we can add pre-trained embeddings to our existing LSTM Encoder-Decoder architecture, though the results didn’t spike up much, but it can perform brilliantly for a smaller dataset." } ]
Keras data generators and how to use them | by Ilya Michlin | Towards Data Science
You probably encountered a situation where you try to load a dataset but there is not enough memory in your machine. As the field of machine learning progresses, this problem becomes more and more common. Today this is already one of the challenges in the field of vision where large datasets of images and video files are processed. Here we will focus on how to build data generators for loading and processing images in Keras. In Keras Model class, there are three methods that interest us: fit_generator, evaluate_generator, and predict_generator. All three of them require data generator but not all generators are created equally. Let’s look into what kind of generator each method requires: Requires two generators, one for the training data and another for validation. Fortunately, both of them should return a tuple (inputs, targets) and both of them can be instance of Sequence class. The data generator here has same requirements as in fit_generator and can be the same as the training generator. The generator here is a bit different. It should return only inputs. With that in mind, let’s build some data generators. Because of the similarity between the generator in fit_generator and evaluate_generator, we will focus on building data generators of fit_generator and predict_generator. The ImageDataGenerator class is very useful in image classification. There are several ways to use this generator, depending on the method we use, here we will focus on flow_from_directory takes a path to the directory containing images sorted in sub directories and image augmentation parameters. Let’s look on an example: We will use a dataset that can be downloaded from https://www.kaggle.com/c/dogs-vs-cats/data where the structure is as follows: data/ train/ dogs/ dog001.jpg dog002.jpg ... cats/ cat001.jpg cat002.jpg ... validation/ dogs/ dog001.jpg dog002.jpg ... cats/ cat001.jpg cat002.jpg ... First, let’s import all the necessary libraries and create a data generator with some image augmentation. Finally, create a model and run the fit_generator method. The ImageDataGenerator is an easy way to load and augment images in batches for image classification tasks. But! What if you have a segmentation task? For that, we need to build a custom data generator. To build a custom data generator, we need to inherit from the Sequence class. Let’s do that and add the parameters we need. The Sequence class forces us to implement two methods; __len__ and __getitem__. We can also implement the method on_epoch_end if we want the generator to do something after every epoch. The __len__ method should return the number of batches per epoch. One possible implementation is shown below. on_epoch_end in this example can shuffle the indexes for the training if shuffle=True. But there can be any logic here that we want to run after every epoch. The second method that we must implement is __getitem__ and it does exactly what you would expect. It should return a batch of images and masks if we are predicting. This can be controlled by setting to_fit to True or False. The entire data generator should be similar to this: Assuming we have two directories, one holds the images and the other holds the mask images and every image has a corresponding mask with the same name, the following code will train the model using the custom data generator. Finally if we want to make predictions with the data generator, to_fit should be set to False and predict_generator should be called. While Keras provides data generators, they are limited in their capabilities. One of the reasons is that every task is needs a different data loader. Sometimes every image has one mask and some times several, sometimes the mask is saved as an image and sometimes it encoded, etc... For every task we will probably need to tweak our data generator but the structure will stay the same.
[ { "code": null, "e": 505, "s": 171, "text": "You probably encountered a situation where you try to load a dataset but there is not enough memory in your machine. As the field of machine learning progresses, this problem becomes more and more common. Today this is already one of the challenges in the field of vision where large datasets of images and video files are processed." }, { "code": null, "e": 600, "s": 505, "text": "Here we will focus on how to build data generators for loading and processing images in Keras." }, { "code": null, "e": 807, "s": 600, "text": "In Keras Model class, there are three methods that interest us: fit_generator, evaluate_generator, and predict_generator. All three of them require data generator but not all generators are created equally." }, { "code": null, "e": 868, "s": 807, "text": "Let’s look into what kind of generator each method requires:" }, { "code": null, "e": 1065, "s": 868, "text": "Requires two generators, one for the training data and another for validation. Fortunately, both of them should return a tuple (inputs, targets) and both of them can be instance of Sequence class." }, { "code": null, "e": 1178, "s": 1065, "text": "The data generator here has same requirements as in fit_generator and can be the same as the training generator." }, { "code": null, "e": 1247, "s": 1178, "text": "The generator here is a bit different. It should return only inputs." }, { "code": null, "e": 1471, "s": 1247, "text": "With that in mind, let’s build some data generators. Because of the similarity between the generator in fit_generator and evaluate_generator, we will focus on building data generators of fit_generator and predict_generator." }, { "code": null, "e": 1769, "s": 1471, "text": "The ImageDataGenerator class is very useful in image classification. There are several ways to use this generator, depending on the method we use, here we will focus on flow_from_directory takes a path to the directory containing images sorted in sub directories and image augmentation parameters." }, { "code": null, "e": 1795, "s": 1769, "text": "Let’s look on an example:" }, { "code": null, "e": 1923, "s": 1795, "text": "We will use a dataset that can be downloaded from https://www.kaggle.com/c/dogs-vs-cats/data where the structure is as follows:" }, { "code": null, "e": 2242, "s": 1923, "text": "data/ train/ dogs/ dog001.jpg dog002.jpg ... cats/ cat001.jpg cat002.jpg ... validation/ dogs/ dog001.jpg dog002.jpg ... cats/ cat001.jpg cat002.jpg ..." }, { "code": null, "e": 2348, "s": 2242, "text": "First, let’s import all the necessary libraries and create a data generator with some image augmentation." }, { "code": null, "e": 2406, "s": 2348, "text": "Finally, create a model and run the fit_generator method." }, { "code": null, "e": 2609, "s": 2406, "text": "The ImageDataGenerator is an easy way to load and augment images in batches for image classification tasks. But! What if you have a segmentation task? For that, we need to build a custom data generator." }, { "code": null, "e": 2733, "s": 2609, "text": "To build a custom data generator, we need to inherit from the Sequence class. Let’s do that and add the parameters we need." }, { "code": null, "e": 2919, "s": 2733, "text": "The Sequence class forces us to implement two methods; __len__ and __getitem__. We can also implement the method on_epoch_end if we want the generator to do something after every epoch." }, { "code": null, "e": 3029, "s": 2919, "text": "The __len__ method should return the number of batches per epoch. One possible implementation is shown below." }, { "code": null, "e": 3187, "s": 3029, "text": "on_epoch_end in this example can shuffle the indexes for the training if shuffle=True. But there can be any logic here that we want to run after every epoch." }, { "code": null, "e": 3412, "s": 3187, "text": "The second method that we must implement is __getitem__ and it does exactly what you would expect. It should return a batch of images and masks if we are predicting. This can be controlled by setting to_fit to True or False." }, { "code": null, "e": 3465, "s": 3412, "text": "The entire data generator should be similar to this:" }, { "code": null, "e": 3690, "s": 3465, "text": "Assuming we have two directories, one holds the images and the other holds the mask images and every image has a corresponding mask with the same name, the following code will train the model using the custom data generator." }, { "code": null, "e": 3824, "s": 3690, "text": "Finally if we want to make predictions with the data generator, to_fit should be set to False and predict_generator should be called." }, { "code": null, "e": 4106, "s": 3824, "text": "While Keras provides data generators, they are limited in their capabilities. One of the reasons is that every task is needs a different data loader. Sometimes every image has one mask and some times several, sometimes the mask is saved as an image and sometimes it encoded, etc..." } ]
10 Techniques to Speed Up Python Efficiency | Towards Data Science | Towards Data Science
Python is a scripting language. Compared with compiled languages like C/C++, Python has some disadvantages in efficiency and performance. However, we could use some techniques to speed up the efficiency of Python code. In this article, I will show you the speed-up techniques I usually used in my work. The test environment is Python 3.7, with macOS 10.14.6, and 2.3 GHz Intel Core i5. Before diving into the details of code optimization, we need to understand some basic principles of code optimization. Make sure that the code can work normally first. Because making the correct program faster is much easier than making the fast program correct.Weigh the cost of optimization. Optimization comes with a cost. For example, less runtime usually needs more space usage, or less space usage usually need more runtime.Optimization cannot sacrifice code readability. Make sure that the code can work normally first. Because making the correct program faster is much easier than making the fast program correct. Weigh the cost of optimization. Optimization comes with a cost. For example, less runtime usually needs more space usage, or less space usage usually need more runtime. Optimization cannot sacrifice code readability. According to the TimeComplexity of Python, the average case of x in s operation of list is O(n). On the other hand, the average case of x in s operation of set is O(1). We should use defaultdict for the initialization. # Bad: 447msnums_sum_list_comprehension = sum([num**2 for num in range(1000000)])# Good: 300msnums_sum_generator_expression = sum((num**2 for num in range(1000000))) Another benefit of generator expression is that we can get the result without building and holding the entire list object in memory before iteration. In other words, generator expression saves memory usage. import sys# Badnums_squared_list = [num**2 for num in range(1000000)]print(sys.getsizeof(nums_squared_list)) # 87632# Goodnums_squared_generator = (num**2 for num in range(1000000))print(sys.getsizeof(nums_squared_generator)) # 128 We should put the global variables into the function. The local variable is fast than the global variable. Every time we use . to access the function, it will trigger specific methods, like __getattribute__() and __getattr__(). These methods will use the dictionary operation, which will cause a time cost. We can use from xx import xx to remove such costs. According to the technique 3, We also can assign the global function to a local function. Furthermore, we could assign the list.append() method to a local function. The speed of accessing self._value is slower than accessing a local variable. We could assign the class property to a local variable to speed up the runtime. When use additional processing layers (such as decorators, property access, descriptors) to wrap the code, it will make the code slow. In most cases, it is necessary to reconsider whether it is necessary to use these layers. Some C/C++ programmers might follow the coding style that using the getter/setter function to access the property. But we could use a more simple writing style. The value_list is meaningless. The temp is no need. When using a + b to concatenate strings, Python will apply for memory space, and copy a and b to the newly applied memory space respectively. This is because the string data type in Python is an immutable object. If concatenating n string, it will generate n-1 intermediate results and every intermediate result will apply for memory space and copy the new string. On the other hand, join() will save time. It will first calculate the total memory space that needs to be applied, and then apply for the required memory at one time, and copy each string element into the memory. Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise, if the first value is true it checks the second and returns that value. Therefore, to save runtime, we can follow the below rules: if a and b: The variable a should have a high probability of False, so Python won't calculate b. if a or b: The variable a should have a higher probability of True, so Python won't calculate b. for loop is faster than while loop. We use the above example. We move the sqrt(x) from inner for loop to outer for loop. Numba can compile the Python function JIT into machine code for execution, which greatly improves the speed of the code. For more information about numba, see the homepage. We use the above example. We move the sqrt(x) from inner for loop to outer for loop. `cProfile` will output the time usage of each function. So we can find the time cost function. Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu https://wiki.python.org/moin/PythonSpeed/PerformanceTips https://realpython.com/introduction-to-python-generators/#building-generators-with-generator-expressions Writing Solid Python Code 91 Suggestions Python Cookbook, Third edition
[ { "code": null, "e": 475, "s": 172, "text": "Python is a scripting language. Compared with compiled languages like C/C++, Python has some disadvantages in efficiency and performance. However, we could use some techniques to speed up the efficiency of Python code. In this article, I will show you the speed-up techniques I usually used in my work." }, { "code": null, "e": 558, "s": 475, "text": "The test environment is Python 3.7, with macOS 10.14.6, and 2.3 GHz Intel Core i5." }, { "code": null, "e": 677, "s": 558, "text": "Before diving into the details of code optimization, we need to understand some basic principles of code optimization." }, { "code": null, "e": 1036, "s": 677, "text": "Make sure that the code can work normally first. Because making the correct program faster is much easier than making the fast program correct.Weigh the cost of optimization. Optimization comes with a cost. For example, less runtime usually needs more space usage, or less space usage usually need more runtime.Optimization cannot sacrifice code readability." }, { "code": null, "e": 1180, "s": 1036, "text": "Make sure that the code can work normally first. Because making the correct program faster is much easier than making the fast program correct." }, { "code": null, "e": 1349, "s": 1180, "text": "Weigh the cost of optimization. Optimization comes with a cost. For example, less runtime usually needs more space usage, or less space usage usually need more runtime." }, { "code": null, "e": 1397, "s": 1349, "text": "Optimization cannot sacrifice code readability." }, { "code": null, "e": 1566, "s": 1397, "text": "According to the TimeComplexity of Python, the average case of x in s operation of list is O(n). On the other hand, the average case of x in s operation of set is O(1)." }, { "code": null, "e": 1616, "s": 1566, "text": "We should use defaultdict for the initialization." }, { "code": null, "e": 1782, "s": 1616, "text": "# Bad: 447msnums_sum_list_comprehension = sum([num**2 for num in range(1000000)])# Good: 300msnums_sum_generator_expression = sum((num**2 for num in range(1000000)))" }, { "code": null, "e": 1989, "s": 1782, "text": "Another benefit of generator expression is that we can get the result without building and holding the entire list object in memory before iteration. In other words, generator expression saves memory usage." }, { "code": null, "e": 2223, "s": 1989, "text": "import sys# Badnums_squared_list = [num**2 for num in range(1000000)]print(sys.getsizeof(nums_squared_list)) # 87632# Goodnums_squared_generator = (num**2 for num in range(1000000))print(sys.getsizeof(nums_squared_generator)) # 128" }, { "code": null, "e": 2330, "s": 2223, "text": "We should put the global variables into the function. The local variable is fast than the global variable." }, { "code": null, "e": 2581, "s": 2330, "text": "Every time we use . to access the function, it will trigger specific methods, like __getattribute__() and __getattr__(). These methods will use the dictionary operation, which will cause a time cost. We can use from xx import xx to remove such costs." }, { "code": null, "e": 2671, "s": 2581, "text": "According to the technique 3, We also can assign the global function to a local function." }, { "code": null, "e": 2746, "s": 2671, "text": "Furthermore, we could assign the list.append() method to a local function." }, { "code": null, "e": 2904, "s": 2746, "text": "The speed of accessing self._value is slower than accessing a local variable. We could assign the class property to a local variable to speed up the runtime." }, { "code": null, "e": 3290, "s": 2904, "text": "When use additional processing layers (such as decorators, property access, descriptors) to wrap the code, it will make the code slow. In most cases, it is necessary to reconsider whether it is necessary to use these layers. Some C/C++ programmers might follow the coding style that using the getter/setter function to access the property. But we could use a more simple writing style." }, { "code": null, "e": 3321, "s": 3290, "text": "The value_list is meaningless." }, { "code": null, "e": 3342, "s": 3321, "text": "The temp is no need." }, { "code": null, "e": 3707, "s": 3342, "text": "When using a + b to concatenate strings, Python will apply for memory space, and copy a and b to the newly applied memory space respectively. This is because the string data type in Python is an immutable object. If concatenating n string, it will generate n-1 intermediate results and every intermediate result will apply for memory space and copy the new string." }, { "code": null, "e": 3920, "s": 3707, "text": "On the other hand, join() will save time. It will first calculate the total memory space that needs to be applied, and then apply for the required memory at one time, and copy each string element into the memory." }, { "code": null, "e": 4168, "s": 3920, "text": "Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise, if the first value is true it checks the second and returns that value." }, { "code": null, "e": 4227, "s": 4168, "text": "Therefore, to save runtime, we can follow the below rules:" }, { "code": null, "e": 4324, "s": 4227, "text": "if a and b: The variable a should have a high probability of False, so Python won't calculate b." }, { "code": null, "e": 4421, "s": 4324, "text": "if a or b: The variable a should have a higher probability of True, so Python won't calculate b." }, { "code": null, "e": 4457, "s": 4421, "text": "for loop is faster than while loop." }, { "code": null, "e": 4483, "s": 4457, "text": "We use the above example." }, { "code": null, "e": 4542, "s": 4483, "text": "We move the sqrt(x) from inner for loop to outer for loop." }, { "code": null, "e": 4715, "s": 4542, "text": "Numba can compile the Python function JIT into machine code for execution, which greatly improves the speed of the code. For more information about numba, see the homepage." }, { "code": null, "e": 4741, "s": 4715, "text": "We use the above example." }, { "code": null, "e": 4800, "s": 4741, "text": "We move the sqrt(x) from inner for loop to outer for loop." }, { "code": null, "e": 4895, "s": 4800, "text": "`cProfile` will output the time usage of each function. So we can find the time cost function." }, { "code": null, "e": 5005, "s": 4895, "text": "Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu" }, { "code": null, "e": 5062, "s": 5005, "text": "https://wiki.python.org/moin/PythonSpeed/PerformanceTips" }, { "code": null, "e": 5167, "s": 5062, "text": "https://realpython.com/introduction-to-python-generators/#building-generators-with-generator-expressions" }, { "code": null, "e": 5208, "s": 5167, "text": "Writing Solid Python Code 91 Suggestions" } ]
How to Show and Hide div elements using radio buttons?
03 Aug, 2021 In order to display data/content of a specific element by selecting the particular radio button in jQuery we can use the following two methods: hide() methods: This method is used to hiding the syntax or the element of html that you want to hide.Syntax:$(selector).hide(speed, callback);show() methods: This method is used to show the syntax or the element of html that you want the user to see.Syntax:$(selector).show(speed, callback); hide() methods: This method is used to hiding the syntax or the element of html that you want to hide.Syntax:$(selector).hide(speed, callback); $(selector).hide(speed, callback); show() methods: This method is used to show the syntax or the element of html that you want the user to see.Syntax:$(selector).show(speed, callback); $(selector).show(speed, callback); Approach: Selector name for radio button is same as the element which is used to display thecontent. CSS display property of each element is set to none using display: none; Use show() method for displaying the element, otherwise use hide() method for hiding. Example 1: <!DOCTYPE html><html> <head> <title> Show and Hide div elements using radio buttons </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style type="text/css"> .selectt { color: #fff; padding: 30px; display: none; margin-top: 30px; width: 60%; background: green } label { margin-right: 20px; } </style></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Show and Hide div elements using radio buttons </h3> <div> <label> <input type="radio" name="colorRadio" value="C"> C</label> <label> <input type="radio" name="colorRadio" value="Cplus"> C++</label> <label> <input type="radio" name="colorRadio" value="Python"> Python</label> <label> <input type="radio" name="colorRadio" value="Java"> Java</label> </div> <div class="C selectt"> <strong>C</strong> is a procedural programming language</div> <div class="Cplus selectt"> <strong>C++</strong> is a general purpose programming language</div> <div class="Python selectt"> <strong>Python</strong> is a widely used general-purpose, high level programming language.</div> <div class="Java selectt"> <strong>Java</strong> is a most popular programming language for many years.</div> <script type="text/javascript"> $(document).ready(function() { $('input[type="radio"]').click(function() { var inputValue = $(this).attr("value"); var targetBox = $("." + inputValue); $(".selectt").not(targetBox).hide(); $(targetBox).show(); }); }); </script> </center></body> </html> Output: Before selecting the any radio button: After selecting the radio button: Example 2: Along with alert method. <!DOCTYPE html><html> <head> <title> Show and Hide div elements using radio buttons </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style type="text/css"> .selectt { color: #fff; padding: 30px; display: none; margin-top: 30px; width: 60%; background: green } label { margin-right: 20px; } </style></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Show and Hide div elements using radio buttons </h3> <div> <label> <input type="radio" name="colorRadio" value="C"> C</label> <label> <input type="radio" name="colorRadio" value="Cplus"> C++</label> <label> <input type="radio" name="colorRadio" value="Python"> Python</label> <label> <input type="radio" name="colorRadio" value="Java"> Java</label> </div> <div class="C selectt"> <strong>C</strong> is a procedural programming language</div> <div class="Cplus selectt"> <strong>C++</strong> is a general purpose programming language</div> <div class="Python selectt"> <strong>Python</strong> is a widely used general-purpose, high level programming language.</div> <div class="Java selectt"> <strong>Java</strong> is a most popular programming language for many years.</div> <script type="text/javascript"> $(document).ready(function() { $('input[type="radio"]').click(function() { var inputValue = $(this).attr("value"); var targetBox = $("." + inputValue); $(".selectt").not(targetBox).hide(); $(targetBox).show(); alert("Radio button " + inputValue + " is selected"); }); }); </script> </center></body> </html> Output: Before selecting the any radio button: After selecting the radio button: After selecting the radio button: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery jQuery | children() with Examples Scroll to the top of the page using JavaScript/jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to get the value in an input text box using jQuery ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 172, "s": 28, "text": "In order to display data/content of a specific element by selecting the particular radio button in jQuery we can use the following two methods:" }, { "code": null, "e": 465, "s": 172, "text": "hide() methods: This method is used to hiding the syntax or the element of html that you want to hide.Syntax:$(selector).hide(speed, callback);show() methods: This method is used to show the syntax or the element of html that you want the user to see.Syntax:$(selector).show(speed, callback);" }, { "code": null, "e": 609, "s": 465, "text": "hide() methods: This method is used to hiding the syntax or the element of html that you want to hide.Syntax:$(selector).hide(speed, callback);" }, { "code": null, "e": 644, "s": 609, "text": "$(selector).hide(speed, callback);" }, { "code": null, "e": 794, "s": 644, "text": "show() methods: This method is used to show the syntax or the element of html that you want the user to see.Syntax:$(selector).show(speed, callback);" }, { "code": null, "e": 829, "s": 794, "text": "$(selector).show(speed, callback);" }, { "code": null, "e": 839, "s": 829, "text": "Approach:" }, { "code": null, "e": 930, "s": 839, "text": "Selector name for radio button is same as the element which is used to display thecontent." }, { "code": null, "e": 1003, "s": 930, "text": "CSS display property of each element is set to none using display: none;" }, { "code": null, "e": 1089, "s": 1003, "text": "Use show() method for displaying the element, otherwise use hide() method for hiding." }, { "code": null, "e": 1100, "s": 1089, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> Show and Hide div elements using radio buttons </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style type=\"text/css\"> .selectt { color: #fff; padding: 30px; display: none; margin-top: 30px; width: 60%; background: green } label { margin-right: 20px; } </style></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Show and Hide div elements using radio buttons </h3> <div> <label> <input type=\"radio\" name=\"colorRadio\" value=\"C\"> C</label> <label> <input type=\"radio\" name=\"colorRadio\" value=\"Cplus\"> C++</label> <label> <input type=\"radio\" name=\"colorRadio\" value=\"Python\"> Python</label> <label> <input type=\"radio\" name=\"colorRadio\" value=\"Java\"> Java</label> </div> <div class=\"C selectt\"> <strong>C</strong> is a procedural programming language</div> <div class=\"Cplus selectt\"> <strong>C++</strong> is a general purpose programming language</div> <div class=\"Python selectt\"> <strong>Python</strong> is a widely used general-purpose, high level programming language.</div> <div class=\"Java selectt\"> <strong>Java</strong> is a most popular programming language for many years.</div> <script type=\"text/javascript\"> $(document).ready(function() { $('input[type=\"radio\"]').click(function() { var inputValue = $(this).attr(\"value\"); var targetBox = $(\".\" + inputValue); $(\".selectt\").not(targetBox).hide(); $(targetBox).show(); }); }); </script> </center></body> </html>", "e": 3232, "s": 1100, "text": null }, { "code": null, "e": 3240, "s": 3232, "text": "Output:" }, { "code": null, "e": 3279, "s": 3240, "text": "Before selecting the any radio button:" }, { "code": null, "e": 3313, "s": 3279, "text": "After selecting the radio button:" }, { "code": null, "e": 3349, "s": 3313, "text": "Example 2: Along with alert method." }, { "code": "<!DOCTYPE html><html> <head> <title> Show and Hide div elements using radio buttons </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style type=\"text/css\"> .selectt { color: #fff; padding: 30px; display: none; margin-top: 30px; width: 60%; background: green } label { margin-right: 20px; } </style></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Show and Hide div elements using radio buttons </h3> <div> <label> <input type=\"radio\" name=\"colorRadio\" value=\"C\"> C</label> <label> <input type=\"radio\" name=\"colorRadio\" value=\"Cplus\"> C++</label> <label> <input type=\"radio\" name=\"colorRadio\" value=\"Python\"> Python</label> <label> <input type=\"radio\" name=\"colorRadio\" value=\"Java\"> Java</label> </div> <div class=\"C selectt\"> <strong>C</strong> is a procedural programming language</div> <div class=\"Cplus selectt\"> <strong>C++</strong> is a general purpose programming language</div> <div class=\"Python selectt\"> <strong>Python</strong> is a widely used general-purpose, high level programming language.</div> <div class=\"Java selectt\"> <strong>Java</strong> is a most popular programming language for many years.</div> <script type=\"text/javascript\"> $(document).ready(function() { $('input[type=\"radio\"]').click(function() { var inputValue = $(this).attr(\"value\"); var targetBox = $(\".\" + inputValue); $(\".selectt\").not(targetBox).hide(); $(targetBox).show(); alert(\"Radio button \" + inputValue + \" is selected\"); }); }); </script> </center></body> </html>", "e": 5553, "s": 3349, "text": null }, { "code": null, "e": 5561, "s": 5553, "text": "Output:" }, { "code": null, "e": 5600, "s": 5561, "text": "Before selecting the any radio button:" }, { "code": null, "e": 5634, "s": 5600, "text": "After selecting the radio button:" }, { "code": null, "e": 5668, "s": 5634, "text": "After selecting the radio button:" }, { "code": null, "e": 5936, "s": 5668, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 5943, "s": 5936, "text": "JQuery" }, { "code": null, "e": 5960, "s": 5943, "text": "Web Technologies" }, { "code": null, "e": 5987, "s": 5960, "text": "Web technologies Questions" }, { "code": null, "e": 6085, "s": 5987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6114, "s": 6085, "text": "Form validation using jQuery" }, { "code": null, "e": 6148, "s": 6114, "text": "jQuery | children() with Examples" }, { "code": null, "e": 6202, "s": 6148, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 6258, "s": 6202, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 6315, "s": 6258, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 6348, "s": 6315, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6410, "s": 6348, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6471, "s": 6410, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6521, "s": 6471, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Blur Image using Smoothing
28 Oct, 2021 Blurring is a simple and frequently used image processing operation. It is also called as Smoothing. Smoothing of an image removes noisy pixels from the image and applying a low-pass filter to an image. A low-pass filter means removing noise from an image while leaving the majority of the image undamaged. The most common type of filter is linear. In a linear filter, the weighted sum of the input pixels value determines the output pixels value. Prerequisite: Classes required to perform the operation: To read and write an image file we have to import the File class [ import java.io.File; ]. This class represents file and directory path names in general. To handle errors we use the IOException class [ import java.io.IOException; ] To hold the image we create the BufferedImage object for that we use BufferedImage class [ import java.awt.image.BufferedImage; ]. This object is used to store an image in RAM. To perform the image read-write operation we will import the ImageIO class [ import javax.imageio.ImageIO;]. This class has static methods to read and write an image. Approach: Smooth each pixel of image taking as 2D matrix Using some in-built methods of BufferedImage class and Color c Implementation: Example Java // Java Program to Blur Image using Smoothing // Importing required packagesimport java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException, InterruptedException { Color color[]; // Creating a File class object to // read the image in the form of file from directory // Directory path is passed as an argument File fin = new File("D:/test/Image.jpeg"); // Now object of BufferedImage class is created to // convert file into into image form BufferedImage input = ImageIO.read(fin); // Again creating an object of BufferedImage to // create output Image BufferedImage output = new BufferedImage( input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_RGB); // Setting dimensions for the image to be processed int i = 0; int max = 400, rad = 10; int a1 = 0, r1 = 0, g1 = 0, b1 = 0; color = new Color[max]; // Now this core section of code is responsible for // blurring of an image int x = 1, y = 1, x1, y1, ex = 5, d = 0; // Running nested for loops for each pixel // and blurring it for (x = rad; x < input.getHeight() - rad; x++) { for (y = rad; y < input.getWidth() - rad; y++) { for (x1 = x - rad; x1 < x + rad; x1++) { for (y1 = y - rad; y1 < y + rad; y1++) { color[i++] = new Color( input.getRGB(y1, x1)); } } // Smoothing colors of image i = 0; for (d = 0; d < max; d++) { a1 = a1 + color[d].getAlpha(); } a1 = a1 / (max); for (d = 0; d < max; d++) { r1 = r1 + color[d].getRed(); } r1 = r1 / (max); for (d = 0; d < max; d++) { g1 = g1 + color[d].getGreen(); } g1 = g1 / (max); for (d = 0; d < max; d++) { b1 = b1 + color[d].getBlue(); } b1 = b1 / (max); int sum1 = (a1 << 24) + (r1 << 16) + (g1 << 8) + b1; output.setRGB(y, x, (int)(sum1)); } } // Writing the blurred image on the disc where // directory is passed as an argument ImageIO.write( output, "jpeg", new File("D:/test/BlurredImage.jpeg")); // Message to be displayed in the console when // program is successfully executed System.out.println("Image blurred successfully !"); }} Output: On console Java Program to Blur Image using Smoothing After executing the program console will show a message that Image blurred successfully! This code will not run on an online IDE as it needs an image on disk. It is pictorially depicted in the pictorial format below as follows: sweetyty simmytarika5 saurabh1990aror Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Introduction to Java Exceptions in Java Java Programming Examples Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Traverse Through a HashMap in Java Extends vs Implements in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Oct, 2021" }, { "code": null, "e": 502, "s": 54, "text": "Blurring is a simple and frequently used image processing operation. It is also called as Smoothing. Smoothing of an image removes noisy pixels from the image and applying a low-pass filter to an image. A low-pass filter means removing noise from an image while leaving the majority of the image undamaged. The most common type of filter is linear. In a linear filter, the weighted sum of the input pixels value determines the output pixels value." }, { "code": null, "e": 516, "s": 502, "text": "Prerequisite:" }, { "code": null, "e": 559, "s": 516, "text": "Classes required to perform the operation:" }, { "code": null, "e": 714, "s": 559, "text": "To read and write an image file we have to import the File class [ import java.io.File; ]. This class represents file and directory path names in general." }, { "code": null, "e": 792, "s": 714, "text": "To handle errors we use the IOException class [ import java.io.IOException; ]" }, { "code": null, "e": 969, "s": 792, "text": "To hold the image we create the BufferedImage object for that we use BufferedImage class [ import java.awt.image.BufferedImage; ]. This object is used to store an image in RAM." }, { "code": null, "e": 1136, "s": 969, "text": "To perform the image read-write operation we will import the ImageIO class [ import javax.imageio.ImageIO;]. This class has static methods to read and write an image." }, { "code": null, "e": 1146, "s": 1136, "text": "Approach:" }, { "code": null, "e": 1193, "s": 1146, "text": "Smooth each pixel of image taking as 2D matrix" }, { "code": null, "e": 1256, "s": 1193, "text": "Using some in-built methods of BufferedImage class and Color c" }, { "code": null, "e": 1272, "s": 1256, "text": "Implementation:" }, { "code": null, "e": 1280, "s": 1272, "text": "Example" }, { "code": null, "e": 1285, "s": 1280, "text": "Java" }, { "code": "// Java Program to Blur Image using Smoothing // Importing required packagesimport java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException, InterruptedException { Color color[]; // Creating a File class object to // read the image in the form of file from directory // Directory path is passed as an argument File fin = new File(\"D:/test/Image.jpeg\"); // Now object of BufferedImage class is created to // convert file into into image form BufferedImage input = ImageIO.read(fin); // Again creating an object of BufferedImage to // create output Image BufferedImage output = new BufferedImage( input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_RGB); // Setting dimensions for the image to be processed int i = 0; int max = 400, rad = 10; int a1 = 0, r1 = 0, g1 = 0, b1 = 0; color = new Color[max]; // Now this core section of code is responsible for // blurring of an image int x = 1, y = 1, x1, y1, ex = 5, d = 0; // Running nested for loops for each pixel // and blurring it for (x = rad; x < input.getHeight() - rad; x++) { for (y = rad; y < input.getWidth() - rad; y++) { for (x1 = x - rad; x1 < x + rad; x1++) { for (y1 = y - rad; y1 < y + rad; y1++) { color[i++] = new Color( input.getRGB(y1, x1)); } } // Smoothing colors of image i = 0; for (d = 0; d < max; d++) { a1 = a1 + color[d].getAlpha(); } a1 = a1 / (max); for (d = 0; d < max; d++) { r1 = r1 + color[d].getRed(); } r1 = r1 / (max); for (d = 0; d < max; d++) { g1 = g1 + color[d].getGreen(); } g1 = g1 / (max); for (d = 0; d < max; d++) { b1 = b1 + color[d].getBlue(); } b1 = b1 / (max); int sum1 = (a1 << 24) + (r1 << 16) + (g1 << 8) + b1; output.setRGB(y, x, (int)(sum1)); } } // Writing the blurred image on the disc where // directory is passed as an argument ImageIO.write( output, \"jpeg\", new File(\"D:/test/BlurredImage.jpeg\")); // Message to be displayed in the console when // program is successfully executed System.out.println(\"Image blurred successfully !\"); }}", "e": 4179, "s": 1285, "text": null }, { "code": null, "e": 4198, "s": 4179, "text": "Output: On console" }, { "code": null, "e": 4241, "s": 4198, "text": "Java Program to Blur Image using Smoothing" }, { "code": null, "e": 4469, "s": 4241, "text": "After executing the program console will show a message that Image blurred successfully! This code will not run on an online IDE as it needs an image on disk. It is pictorially depicted in the pictorial format below as follows:" }, { "code": null, "e": 4478, "s": 4469, "text": "sweetyty" }, { "code": null, "e": 4491, "s": 4478, "text": "simmytarika5" }, { "code": null, "e": 4507, "s": 4491, "text": "saurabh1990aror" }, { "code": null, "e": 4512, "s": 4507, "text": "Java" }, { "code": null, "e": 4526, "s": 4512, "text": "Java Programs" }, { "code": null, "e": 4531, "s": 4526, "text": "Java" }, { "code": null, "e": 4629, "s": 4531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4644, "s": 4629, "text": "Stream In Java" }, { "code": null, "e": 4665, "s": 4644, "text": "Constructors in Java" }, { "code": null, "e": 4686, "s": 4665, "text": "Introduction to Java" }, { "code": null, "e": 4705, "s": 4686, "text": "Exceptions in Java" }, { "code": null, "e": 4731, "s": 4705, "text": "Java Programming Examples" }, { "code": null, "e": 4757, "s": 4731, "text": "Java Programming Examples" }, { "code": null, "e": 4791, "s": 4757, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4838, "s": 4791, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4873, "s": 4838, "text": "Traverse Through a HashMap in Java" } ]
Find the siblings of tags using BeautifulSoup
03 Mar, 2021 Prerequisite: BeautifulSoup BeautifulSoup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come in built-in with Python. To install this type the below command in the terminal. In this article, we will learn about siblings in HTML tags using BeautifulSoup. Here we will discuss these four sibling properties: previous_sibling is used to find the previous element of the given element next_sibling is used to find the next element of the given element previous_siblings is used to find all previous element of the given element next_siblings is used to find all next element of the given element Approach Import module Load or create HTML code Parse HTML code Print required sibling. Example 1: To print next immediate sibling Python3 # Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = """<a><b>text1</b><c>text2</c></a>""" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # next elementprint(soup.b.next_sibling) Output: <c>text2</c> Example 2: To get previous immediate sibling Python3 # Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = """<a><b>text1</b><c>text2</c></a>""" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # previous elementprint(soup.c.previous_sibling) Output: <b>text1</b> Suppose we want to find all the next elements of a tag. For that, we just simply iterate through siblings and print the required tag. Example 3: To get all siblings next to the tag Python3 # Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = """<a><b>text1</b><d>text3</d><c>text2</c></a>""" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # next elementfor element in soup.b.next_siblings: print(element) Output: <d>text3</d> <c>text2</c> Example 4: To get all previous siblings Python3 # Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = """<a><b>text1</b><d>text3</d><c>text2</c></a>""" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # previous elementfor element in soup.c.previous_siblings: print(element) Output: <d>text3</d> <b>text1</b> Picked Python BeautifulSoup Python bs4-Exercises Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2021" }, { "code": null, "e": 56, "s": 28, "text": "Prerequisite: BeautifulSoup" }, { "code": null, "e": 326, "s": 56, "text": "BeautifulSoup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come in built-in with Python. To install this type the below command in the terminal. In this article, we will learn about siblings in HTML tags using BeautifulSoup." }, { "code": null, "e": 378, "s": 326, "text": "Here we will discuss these four sibling properties:" }, { "code": null, "e": 453, "s": 378, "text": "previous_sibling is used to find the previous element of the given element" }, { "code": null, "e": 520, "s": 453, "text": "next_sibling is used to find the next element of the given element" }, { "code": null, "e": 596, "s": 520, "text": "previous_siblings is used to find all previous element of the given element" }, { "code": null, "e": 664, "s": 596, "text": "next_siblings is used to find all next element of the given element" }, { "code": null, "e": 673, "s": 664, "text": "Approach" }, { "code": null, "e": 687, "s": 673, "text": "Import module" }, { "code": null, "e": 712, "s": 687, "text": "Load or create HTML code" }, { "code": null, "e": 728, "s": 712, "text": "Parse HTML code" }, { "code": null, "e": 752, "s": 728, "text": "Print required sibling." }, { "code": null, "e": 795, "s": 752, "text": "Example 1: To print next immediate sibling" }, { "code": null, "e": 803, "s": 795, "text": "Python3" }, { "code": "# Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = \"\"\"<a><b>text1</b><c>text2</c></a>\"\"\" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # next elementprint(soup.b.next_sibling)", "e": 1017, "s": 803, "text": null }, { "code": null, "e": 1025, "s": 1017, "text": "Output:" }, { "code": null, "e": 1038, "s": 1025, "text": "<c>text2</c>" }, { "code": null, "e": 1083, "s": 1038, "text": "Example 2: To get previous immediate sibling" }, { "code": null, "e": 1091, "s": 1083, "text": "Python3" }, { "code": "# Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = \"\"\"<a><b>text1</b><c>text2</c></a>\"\"\" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # previous elementprint(soup.c.previous_sibling)", "e": 1313, "s": 1091, "text": null }, { "code": null, "e": 1321, "s": 1313, "text": "Output:" }, { "code": null, "e": 1334, "s": 1321, "text": "<b>text1</b>" }, { "code": null, "e": 1468, "s": 1334, "text": "Suppose we want to find all the next elements of a tag. For that, we just simply iterate through siblings and print the required tag." }, { "code": null, "e": 1515, "s": 1468, "text": "Example 3: To get all siblings next to the tag" }, { "code": null, "e": 1523, "s": 1515, "text": "Python3" }, { "code": "# Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = \"\"\"<a><b>text1</b><d>text3</d><c>text2</c></a>\"\"\" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # next elementfor element in soup.b.next_siblings: print(element)", "e": 1777, "s": 1523, "text": null }, { "code": null, "e": 1785, "s": 1777, "text": "Output:" }, { "code": null, "e": 1798, "s": 1785, "text": "<d>text3</d>" }, { "code": null, "e": 1811, "s": 1798, "text": "<c>text2</c>" }, { "code": null, "e": 1851, "s": 1811, "text": "Example 4: To get all previous siblings" }, { "code": null, "e": 1859, "s": 1851, "text": "Python3" }, { "code": "# Import Modulefrom bs4 import BeautifulSoup # HTML CODEhtml_code = \"\"\"<a><b>text1</b><d>text3</d><c>text2</c></a>\"\"\" # Parse HTML CODEsoup = BeautifulSoup(html_code, 'html.parser') # previous elementfor element in soup.c.previous_siblings: print(element)", "e": 2121, "s": 1859, "text": null }, { "code": null, "e": 2129, "s": 2121, "text": "Output:" }, { "code": null, "e": 2142, "s": 2129, "text": "<d>text3</d>" }, { "code": null, "e": 2155, "s": 2142, "text": "<b>text1</b>" }, { "code": null, "e": 2162, "s": 2155, "text": "Picked" }, { "code": null, "e": 2183, "s": 2162, "text": "Python BeautifulSoup" }, { "code": null, "e": 2204, "s": 2183, "text": "Python bs4-Exercises" }, { "code": null, "e": 2211, "s": 2204, "text": "Python" } ]
Armstrong Numbers | Practice | GeeksforGeeks
For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. Return "Yes" if it is a armstrong number else return "No". NOTE: 371 is an Armstrong number since 33 + 73 + 13 = 371 Example 1: Input: N = 153 Output: "Yes" Explanation: 153 is an Armstrong number since 13 + 53 + 33 = 153. Hence answer is "Yes". Example 2: Input: N = 370 Output: "Yes" Explanation: 370 is an Armstrong number since 33 + 73 + 03 = 370. Hence answer is "Yes". Your Task: You dont need to read input or print anything. Complete the function armstrongNumber() which takes n as input parameter and returns "Yes" if it is a armstrong number else returns "No".. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 100 ≤ n <1000 0 abhitan1413 hours ago string armstrongNumber(int n){ // code here int rem,sum = 0,real; real = n; while(n) { rem = n%10; sum += (rem*rem*rem); n /= 10; } if(sum == real) { return "Yes"; } else { return "No"; } } 0 abhikeshz0kb2 weeks ago string armstrongNumber(int n){ // code here int temp=n,rev=0; rev+=pow(temp%10,3);temp=temp/10; rev+=pow(temp%10,3);temp=temp/10; rev+=pow(temp%10,3); if(rev==n) return "Yes";else return "No"; } 0 dhirajhg9872 weeks ago class Solution { public: string armstrongNumber(int n){ int rem,sum=0,real; real=n; while(n!=0) { rem=n%10; sum=sum+rem*rem*rem; n=n/10; } if(sum==real) { cout<<"Yes"; } else { cout<<"No"; } }}; 0 shobhitgautam19993 weeks ago //User function Template for Javaclass Solution { static String armstrongNumber(int n){ int original = n; int rem = 0; int duplicate = n; int count =0; double sum=0; while(original !=0) { original = original/10; count = count+1; } while(duplicate !=0) { rem = duplicate%10; duplicate = duplicate/10; sum = sum + Math.pow(rem,count); } if(sum == n) { return ("Yes"); } else { return ("No"); } }} 0 mizanurhasan3 weeks ago #JavaScript let number=n; let armStrong=0; while(number!=0){ var x=number%10; armStrong+=x*x*x; number=parseInt(number/10); } if(armStrong===n){ return "Yes"; }else{ return "No"; } 0 dakshskrm113 weeks ago //This one is in O(1) as expected string armstrongNumber(int n){ // code here int a=n; int num=0; int i=1; string s1="No"; string s2="Yes"; num+=pow(n%10,3); n=n/10; num+=pow(n%10,3); n=n/10; num+=pow(n%10,3); n=n/10; if(n||a==num){ return s2; } return s1; // I always welcome corrections and optimisations 0 au00ay4 weeks ago // code here int r,sum=0,temp; temp=n; while(n>0) { r=n%10; sum=sum+(r*r*r); n=n/10; } if(temp==sum) cout<<"Yes"; else cout<<"No"; 0 rumi1w8ry1 month ago def armstrongNumber (ob, n): # code here n =str(n) sum_num = 0 for i in n: cube = int(i)**3 sum_num +=cube n = int(n) if sum_num == n: return "Yes" return "No" 0 jitendraprasadmahato1 month ago string armstrongNumber(int n){ // code here //according to armstrong number concept, // For example, 0, 1, 153, 370, 371, 407 are three-digit Armstrong numbers //and, 1634, 8208, 9474 are four-digit Armstrong numbers int sum=0,digit=0,num=n,rem=0; while(num>0){ digit++; num/=10; } num=n; while(num>0){ rem = num%10; if(rem!=0){ sum = sum + pow(rem,digit); } num/=10; } if(sum == n){ return "Yes"; }else{ return "No"; } } 0 rb0012 months ago O(1) time complexity; O(1) space class Solution { public: string armstrongNumber(int n){ // code here // Code By : Rahul Bisht int a=n%10,b= (n/10)%10,c = n/100; if(a*a*a + b*b*b +c*c*c == n) return "Yes"; else return "No"; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 565, "s": 238, "text": "For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. Return \"Yes\" if it is a armstrong number else return \"No\".\nNOTE: 371 is an Armstrong number since 33 + 73 + 13 = 371\n\nExample 1:" }, { "code": null, "e": 684, "s": 565, "text": "Input: N = 153\nOutput: \"Yes\"\nExplanation: 153 is an Armstrong number\nsince 13 + 53 + 33 = 153.\nHence answer is \"Yes\".\n" }, { "code": null, "e": 695, "s": 684, "text": "Example 2:" }, { "code": null, "e": 813, "s": 695, "text": "Input: N = 370\nOutput: \"Yes\"\nExplanation: 370 is an Armstrong number\nsince 33 + 73 + 03 = 370.\nHence answer is \"Yes\"." }, { "code": null, "e": 1104, "s": 813, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function armstrongNumber() which takes n as input parameter and returns \"Yes\" if it is a armstrong number else returns \"No\"..\n\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n100 ≤ n <1000" }, { "code": null, "e": 1106, "s": 1104, "text": "0" }, { "code": null, "e": 1128, "s": 1106, "text": "abhitan1413 hours ago" }, { "code": null, "e": 1442, "s": 1128, "text": "string armstrongNumber(int n){ // code here int rem,sum = 0,real; real = n; while(n) { rem = n%10; sum += (rem*rem*rem); n /= 10; } if(sum == real) { return \"Yes\"; } else { return \"No\"; } }" }, { "code": null, "e": 1444, "s": 1442, "text": "0" }, { "code": null, "e": 1468, "s": 1444, "text": "abhikeshz0kb2 weeks ago" }, { "code": null, "e": 1751, "s": 1468, "text": " string armstrongNumber(int n){\n // code here\n int temp=n,rev=0;\n rev+=pow(temp%10,3);temp=temp/10;\n rev+=pow(temp%10,3);temp=temp/10;\n rev+=pow(temp%10,3);\n if(rev==n)\n return \"Yes\";else return \"No\";\n }" }, { "code": null, "e": 1753, "s": 1751, "text": "0" }, { "code": null, "e": 1776, "s": 1753, "text": "dhirajhg9872 weeks ago" }, { "code": null, "e": 2098, "s": 1776, "text": "class Solution { public: string armstrongNumber(int n){ int rem,sum=0,real; real=n; while(n!=0) { rem=n%10; sum=sum+rem*rem*rem; n=n/10; } if(sum==real) { cout<<\"Yes\"; } else { cout<<\"No\"; } }};" }, { "code": null, "e": 2100, "s": 2098, "text": "0" }, { "code": null, "e": 2129, "s": 2100, "text": "shobhitgautam19993 weeks ago" }, { "code": null, "e": 2717, "s": 2129, "text": "//User function Template for Javaclass Solution { static String armstrongNumber(int n){ int original = n; int rem = 0; int duplicate = n; int count =0; double sum=0; while(original !=0) { original = original/10; count = count+1; } while(duplicate !=0) { rem = duplicate%10; duplicate = duplicate/10; sum = sum + Math.pow(rem,count); } if(sum == n) { return (\"Yes\"); } else { return (\"No\"); } }}" }, { "code": null, "e": 2719, "s": 2717, "text": "0" }, { "code": null, "e": 2743, "s": 2719, "text": "mizanurhasan3 weeks ago" }, { "code": null, "e": 2758, "s": 2743, "text": " #JavaScript" }, { "code": null, "e": 3021, "s": 2760, "text": "let number=n; let armStrong=0; while(number!=0){ var x=number%10; armStrong+=x*x*x; number=parseInt(number/10); } if(armStrong===n){ return \"Yes\"; }else{ return \"No\"; }" }, { "code": null, "e": 3023, "s": 3021, "text": "0" }, { "code": null, "e": 3046, "s": 3023, "text": "dakshskrm113 weeks ago" }, { "code": null, "e": 3080, "s": 3046, "text": "//This one is in O(1) as expected" }, { "code": null, "e": 3431, "s": 3080, "text": "string armstrongNumber(int n){ // code here int a=n; int num=0; int i=1; string s1=\"No\"; string s2=\"Yes\"; num+=pow(n%10,3); n=n/10; num+=pow(n%10,3); n=n/10; num+=pow(n%10,3); n=n/10; if(n||a==num){ return s2; } return s1;" }, { "code": null, "e": 3483, "s": 3433, "text": "// I always welcome corrections and optimisations" }, { "code": null, "e": 3485, "s": 3483, "text": "0" }, { "code": null, "e": 3503, "s": 3485, "text": "au00ay4 weeks ago" }, { "code": null, "e": 3718, "s": 3503, "text": "// code here int r,sum=0,temp; temp=n; while(n>0) { r=n%10; sum=sum+(r*r*r); n=n/10; } if(temp==sum) cout<<\"Yes\"; else cout<<\"No\";" }, { "code": null, "e": 3720, "s": 3718, "text": "0" }, { "code": null, "e": 3741, "s": 3720, "text": "rumi1w8ry1 month ago" }, { "code": null, "e": 3974, "s": 3741, "text": "def armstrongNumber (ob, n): # code here n =str(n) sum_num = 0 for i in n: cube = int(i)**3 sum_num +=cube n = int(n) if sum_num == n: return \"Yes\" return \"No\"" }, { "code": null, "e": 3976, "s": 3974, "text": "0" }, { "code": null, "e": 4008, "s": 3976, "text": "jitendraprasadmahato1 month ago" }, { "code": null, "e": 4643, "s": 4008, "text": " string armstrongNumber(int n){ // code here //according to armstrong number concept, // For example, 0, 1, 153, 370, 371, 407 are three-digit Armstrong numbers //and, 1634, 8208, 9474 are four-digit Armstrong numbers int sum=0,digit=0,num=n,rem=0; while(num>0){ digit++; num/=10; } num=n; while(num>0){ rem = num%10; if(rem!=0){ sum = sum + pow(rem,digit); } num/=10; } if(sum == n){ return \"Yes\"; }else{ return \"No\"; } }" }, { "code": null, "e": 4645, "s": 4643, "text": "0" }, { "code": null, "e": 4663, "s": 4645, "text": "rb0012 months ago" }, { "code": null, "e": 4685, "s": 4663, "text": "O(1) time complexity;" }, { "code": null, "e": 4697, "s": 4685, "text": "O(1) space " }, { "code": null, "e": 4774, "s": 4697, "text": "class Solution { public: string armstrongNumber(int n){ // code here" }, { "code": null, "e": 4942, "s": 4774, "text": "// Code By : Rahul Bisht int a=n%10,b= (n/10)%10,c = n/100; if(a*a*a + b*b*b +c*c*c == n) return \"Yes\"; else return \"No\"; }};" }, { "code": null, "e": 5088, "s": 4942, "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": 5124, "s": 5088, "text": " Login to access your submissions. " }, { "code": null, "e": 5134, "s": 5124, "text": "\nProblem\n" }, { "code": null, "e": 5144, "s": 5134, "text": "\nContest\n" }, { "code": null, "e": 5207, "s": 5144, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5392, "s": 5207, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5676, "s": 5392, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 5822, "s": 5676, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 5899, "s": 5822, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5940, "s": 5899, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5968, "s": 5940, "text": "Disable browser extensions." }, { "code": null, "e": 6039, "s": 5968, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6226, "s": 6039, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Ratio of area of a rectangle with the rectangle inscribed in it
11 Jul, 2022 Given two rectangles, X with a ratio of length to width a:b and Y with a ratio of length to width c:d respectively. Both the rectangles can be resized as long as the ratio of sides remains the same. The task is to place the second rectangle inside the first rectangle such that at least 1 side is equal and that side overlaps of both the rectangles and find the ratio of (space occupied by a 2nd rectangle) : (space occupied by the first rectangle).Examples: Input: a = 1, b = 1, c = 3, d = 2 Output: 2:3 The dimensions can be 3X3 and 3X2. Input: a = 4, b = 3, c = 2, d = 2 Output: 3:4 The dimensions can be 4X3 and 3X3 Approach: If we make one of the sides of rectangles equal then the required ratio would be the ratio of the other side. Consider 2 cases: a*d < b*c : We should make a and c equal. b*c < a*d : We should make b and d equal. Since multiplying both sides of a ratio does not change its value. First try to make a and c equal, it can be made equal to their lcm by multiplying (a:b) with lcm/a and (c:d) with lcm/c. After multiplication, the ratio of (b:d) will be the required answer. This ratio can be reduced by dividing b and d with gcd(b, d).Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the ratiovoid printRatio(int a, int b, int c, int d){ if (b * c > a * d) { swap(c, d); swap(a, b); } // LCM of numerators int lcm = (a * c) / __gcd(a, c); int x = lcm / a; b *= x; int y = lcm / c; d *= y; // Answer in reduced form int k = __gcd(b, d); b /= k; d /= k; cout << b << ":" << d;} // Driver codeint main(){ int a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); return 0;} // Java implementation of above approach import java.io.*; class GFG {// Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to find the ratio static void printRatio(int a, int b, int c, int d){ if (b * c > a * d) { int temp = c; c =d; d =c; temp =a; a =b; b=temp; } // LCM of numerators int lcm = (a * c) / __gcd(a, c); int x = lcm / a; b *= x; int y = lcm / c; d *= y; // Answer in reduced form int k = __gcd(b, d); b /= k; d /= k; System.out.print( b + ":" + d);} // Driver code public static void main (String[] args) { int a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); }} // This code is contributed by inder_verma.. import math# Python3 implementation of above approach # Function to find the ratiodef printRatio(a, b, c, d): if (b * c > a * d): swap(c, d) swap(a, b) # LCM of numerators lcm = (a * c) / math.gcd(a, c) x = lcm / a b = int(b * x) y = lcm / c d = int(d * y) # Answer in reduced form k = math.gcd(b,d) b =int(b / k) d = int(d / k) print(b,":",d) # Driver codeif __name__ == '__main__': a = 4 b = 3 c = 2 d = 2 printRatio(a, b, c, d) # This code is contributed by# Surendra_Gangwar // C# implementation of above approach using System; class GFG {// Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to find the ratiostatic void printRatio(int a, int b, int c, int d){ if (b * c > a * d) { int temp = c; c =d; d =c; temp =a; a =b; b=temp; } // LCM of numerators int lcm = (a * c) / __gcd(a, c); int x = lcm / a; b *= x; int y = lcm / c; d *= y; // Answer in reduced form int k = __gcd(b, d); b /= k; d /= k; Console.WriteLine( b + ":" + d);} // Driver code public static void Main () { int a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); }} // This code is contributed by inder_verma.. <?php// PHP implementation of above approach // Recursive function to return// gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // Function to find the ratiofunction printRatio($a, $b, $c, $d){ if ($b * $c > $a * $d) { $temp = $c; $c = $d; $d = $c; $temp = $a; $a = $b; $b = $temp; } // LCM of numerators $lcm = ($a * $c) / __gcd($a, $c); $x = $lcm / $a; $b *= $x; $y = $lcm / $c; $d *= $y; // Answer in reduced form $k = __gcd($b, $d); $b /= $k; $d /= $k; echo $b . ":" . $d;} // Driver code$a = 4; $b = 3; $c = 2; $d = 2; printRatio($a, $b, $c, $d); // This code is contributed// by Akanksha Rai?> <script>// Javascript implementation of above approach // Recursive function to return // gcd of a and b function __gcd(a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b,b); return __gcd(a, b - a); } // Function to find the ratiofunction printRatio(a, b, c, d){ if (b * c > a * d) { temp = c; c = d; d = c; temp = a; a = b; b = temp; } // LCM of numerators let lcm = (a * c) / __gcd(a, c); let x = lcm / a; b *= x; let y = lcm / c; d *= y; // Answer in reduced form let k = __gcd(b, d); b /= k; d /= k; document.write(b + ":" + d);} // Driver code let a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); // This code is contributed by Manoj </script> 3:4 Time complexity: O(log(max(a,c))+log(max(b,d))) Auxiliary Space: O(log(max(a,c))+log(max(b,d))) inderDuMCA SURENDRA_GANGWAR Akanksha_Rai mank1083 hasani subhammahato348 area-volume-programs Ratio and Proportion Algorithms Mathematical Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jul, 2022" }, { "code": null, "e": 489, "s": 28, "text": "Given two rectangles, X with a ratio of length to width a:b and Y with a ratio of length to width c:d respectively. Both the rectangles can be resized as long as the ratio of sides remains the same. The task is to place the second rectangle inside the first rectangle such that at least 1 side is equal and that side overlaps of both the rectangles and find the ratio of (space occupied by a 2nd rectangle) : (space occupied by the first rectangle).Examples: " }, { "code": null, "e": 651, "s": 489, "text": "Input: a = 1, b = 1, c = 3, d = 2\nOutput: 2:3\nThe dimensions can be 3X3 and 3X2.\n\nInput: a = 4, b = 3, c = 2, d = 2\nOutput: 3:4\nThe dimensions can be 4X3 and 3X3" }, { "code": null, "e": 793, "s": 653, "text": "Approach: If we make one of the sides of rectangles equal then the required ratio would be the ratio of the other side. Consider 2 cases: " }, { "code": null, "e": 835, "s": 793, "text": "a*d < b*c : We should make a and c equal." }, { "code": null, "e": 877, "s": 835, "text": "b*c < a*d : We should make b and d equal." }, { "code": null, "e": 1249, "s": 877, "text": "Since multiplying both sides of a ratio does not change its value. First try to make a and c equal, it can be made equal to their lcm by multiplying (a:b) with lcm/a and (c:d) with lcm/c. After multiplication, the ratio of (b:d) will be the required answer. This ratio can be reduced by dividing b and d with gcd(b, d).Below is the implementation of the above approach: " }, { "code": null, "e": 1253, "s": 1249, "text": "C++" }, { "code": null, "e": 1258, "s": 1253, "text": "Java" }, { "code": null, "e": 1266, "s": 1258, "text": "Python3" }, { "code": null, "e": 1269, "s": 1266, "text": "C#" }, { "code": null, "e": 1273, "s": 1269, "text": "PHP" }, { "code": null, "e": 1284, "s": 1273, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the ratiovoid printRatio(int a, int b, int c, int d){ if (b * c > a * d) { swap(c, d); swap(a, b); } // LCM of numerators int lcm = (a * c) / __gcd(a, c); int x = lcm / a; b *= x; int y = lcm / c; d *= y; // Answer in reduced form int k = __gcd(b, d); b /= k; d /= k; cout << b << \":\" << d;} // Driver codeint main(){ int a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); return 0;}", "e": 1842, "s": 1284, "text": null }, { "code": "// Java implementation of above approach import java.io.*; class GFG {// Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to find the ratio static void printRatio(int a, int b, int c, int d){ if (b * c > a * d) { int temp = c; c =d; d =c; temp =a; a =b; b=temp; } // LCM of numerators int lcm = (a * c) / __gcd(a, c); int x = lcm / a; b *= x; int y = lcm / c; d *= y; // Answer in reduced form int k = __gcd(b, d); b /= k; d /= k; System.out.print( b + \":\" + d);} // Driver code public static void main (String[] args) { int a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); }} // This code is contributed by inder_verma..", "e": 2926, "s": 1842, "text": null }, { "code": "import math# Python3 implementation of above approach # Function to find the ratiodef printRatio(a, b, c, d): if (b * c > a * d): swap(c, d) swap(a, b) # LCM of numerators lcm = (a * c) / math.gcd(a, c) x = lcm / a b = int(b * x) y = lcm / c d = int(d * y) # Answer in reduced form k = math.gcd(b,d) b =int(b / k) d = int(d / k) print(b,\":\",d) # Driver codeif __name__ == '__main__': a = 4 b = 3 c = 2 d = 2 printRatio(a, b, c, d) # This code is contributed by# Surendra_Gangwar", "e": 3480, "s": 2926, "text": null }, { "code": "// C# implementation of above approach using System; class GFG {// Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // Function to find the ratiostatic void printRatio(int a, int b, int c, int d){ if (b * c > a * d) { int temp = c; c =d; d =c; temp =a; a =b; b=temp; } // LCM of numerators int lcm = (a * c) / __gcd(a, c); int x = lcm / a; b *= x; int y = lcm / c; d *= y; // Answer in reduced form int k = __gcd(b, d); b /= k; d /= k; Console.WriteLine( b + \":\" + d);} // Driver code public static void Main () { int a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); }} // This code is contributed by inder_verma..", "e": 4535, "s": 3480, "text": null }, { "code": "<?php// PHP implementation of above approach // Recursive function to return// gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a);} // Function to find the ratiofunction printRatio($a, $b, $c, $d){ if ($b * $c > $a * $d) { $temp = $c; $c = $d; $d = $c; $temp = $a; $a = $b; $b = $temp; } // LCM of numerators $lcm = ($a * $c) / __gcd($a, $c); $x = $lcm / $a; $b *= $x; $y = $lcm / $c; $d *= $y; // Answer in reduced form $k = __gcd($b, $d); $b /= $k; $d /= $k; echo $b . \":\" . $d;} // Driver code$a = 4; $b = 3; $c = 2; $d = 2; printRatio($a, $b, $c, $d); // This code is contributed// by Akanksha Rai?>", "e": 5498, "s": 4535, "text": null }, { "code": "<script>// Javascript implementation of above approach // Recursive function to return // gcd of a and b function __gcd(a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b,b); return __gcd(a, b - a); } // Function to find the ratiofunction printRatio(a, b, c, d){ if (b * c > a * d) { temp = c; c = d; d = c; temp = a; a = b; b = temp; } // LCM of numerators let lcm = (a * c) / __gcd(a, c); let x = lcm / a; b *= x; let y = lcm / c; d *= y; // Answer in reduced form let k = __gcd(b, d); b /= k; d /= k; document.write(b + \":\" + d);} // Driver code let a = 4, b = 3, c = 2, d = 2; printRatio(a, b, c, d); // This code is contributed by Manoj </script>", "e": 6448, "s": 5498, "text": null }, { "code": null, "e": 6452, "s": 6448, "text": "3:4" }, { "code": null, "e": 6502, "s": 6454, "text": "Time complexity: O(log(max(a,c))+log(max(b,d)))" }, { "code": null, "e": 6550, "s": 6502, "text": "Auxiliary Space: O(log(max(a,c))+log(max(b,d)))" }, { "code": null, "e": 6561, "s": 6550, "text": "inderDuMCA" }, { "code": null, "e": 6578, "s": 6561, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 6591, "s": 6578, "text": "Akanksha_Rai" }, { "code": null, "e": 6600, "s": 6591, "text": "mank1083" }, { "code": null, "e": 6607, "s": 6600, "text": "hasani" }, { "code": null, "e": 6623, "s": 6607, "text": "subhammahato348" }, { "code": null, "e": 6644, "s": 6623, "text": "area-volume-programs" }, { "code": null, "e": 6665, "s": 6644, "text": "Ratio and Proportion" }, { "code": null, "e": 6676, "s": 6665, "text": "Algorithms" }, { "code": null, "e": 6689, "s": 6676, "text": "Mathematical" }, { "code": null, "e": 6702, "s": 6689, "text": "Mathematical" }, { "code": null, "e": 6713, "s": 6702, "text": "Algorithms" } ]
How to change a primary key in MySQL to auto_increment?
To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table. mysql> create table changePrimaryKeyInAutoIncrement -> ( -> StudentId int not null primary key, -> StudentName varchar(100), -> StudentAge int, -> StudentAddress varchar(100) -> ); Query OK, 0 rows affected (0.63 sec) Let us now check the description of table using desc command: mysql> desc changePrimaryKeyInAutoIncrement; This will produce the following output +----------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+-------+ | StudentId | int(11) | NO | PRI | NULL | | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentAddress | varchar(100) | YES | | NULL | | +----------------+--------------+------+-----+---------+-------+ 4 rows in set (0.00 sec) Look at the above sample output, StudentId column is a primary key. Now let us change the primary key to auto_increment: mysql> alter table changePrimaryKeyInAutoIncrement MODIFY StudentId INT AUTO_INCREMENT; Query OK, 0 rows affected (1.48 sec) Records: 0 Duplicates: 0 Warnings: 0 Let us check the table description of once again: mysql> desc changePrimaryKeyInAutoIncrement; This will produce the following output +----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentAddress | varchar(100) | YES | | NULL | | +----------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) Look at the above sample output, StudentId column has been changed to auto_increment.
[ { "code": null, "e": 1287, "s": 1187, "text": "To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table." }, { "code": null, "e": 1523, "s": 1287, "text": "mysql> create table changePrimaryKeyInAutoIncrement\n -> (\n -> StudentId int not null primary key,\n -> StudentName varchar(100),\n -> StudentAge int,\n -> StudentAddress varchar(100)\n -> );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1585, "s": 1523, "text": "Let us now check the description of table using desc command:" }, { "code": null, "e": 1630, "s": 1585, "text": "mysql> desc changePrimaryKeyInAutoIncrement;" }, { "code": null, "e": 1669, "s": 1630, "text": "This will produce the following output" }, { "code": null, "e": 2214, "s": 1669, "text": "+----------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+-------+\n| StudentId | int(11) | NO | PRI | NULL | |\n| StudentName | varchar(100) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n| StudentAddress | varchar(100) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2335, "s": 2214, "text": "Look at the above sample output, StudentId column is a primary key. Now let us change the primary key to auto_increment:" }, { "code": null, "e": 2497, "s": 2335, "text": "mysql> alter table changePrimaryKeyInAutoIncrement MODIFY StudentId INT AUTO_INCREMENT;\nQuery OK, 0 rows affected (1.48 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2547, "s": 2497, "text": "Let us check the table description of once again:" }, { "code": null, "e": 2592, "s": 2547, "text": "mysql> desc changePrimaryKeyInAutoIncrement;" }, { "code": null, "e": 2631, "s": 2592, "text": "This will produce the following output" }, { "code": null, "e": 3248, "s": 2631, "text": "+----------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n| StudentAddress | varchar(100) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+----------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 3334, "s": 3248, "text": "Look at the above sample output, StudentId column has been changed to auto_increment." } ]
Python script to get device vendor name from MAC Address
29 Dec, 2020 Prerequisite: Python Requests A MAC address is a unique identity of a network interface that is used to address the device in a Computer Network. A MAC address is made up of 12 hexadecimal digits, 6 octets separated by ‘:’. There are 6 octets in a MAC address. In the first half, the manufacturer info is stored. For this article, we will be using an API that will fetch the MAC Address for us. We will use a Python script to automate the fetching process so that we can use it later in the Softwares and websites that may require this functionality. We will use requests module to work with this API. Below is the implementation. Python3 import requestsimport argparse print("[*] Welcome") # Function to get the interface namedef get_arguments(): # This will give user a neat CLI parser = argparse.ArgumentParser() # We need the MAC address parser.add_argument("-m", "--macaddress", dest="mac_address", help="MAC Address of the device. " ) options = parser.parse_args() # Check if address was given if options.mac_address: return options.mac_address else: parser.error("[!] Invalid Syntax. " "Use --help for more details.") def get_mac_details(mac_address): # We will use an API to get the vendor details url = "https://api.macvendors.com/" # Use get method to fetch details response = requests.get(url+mac_address) if response.status_code != 200: raise Exception("[!] Invalid MAC Address!") return response.content.decode() # Driver Codeif __name__ == "__main__": mac_address = get_arguments() print("[+] Checking Details...") try: vendor_name = get_mac_details(mac_address) print("[+] Device vendor is "+vendor_name) except: # Incase something goes wrong print("[!] An error occured. Check " "your Internet connection.") Save this code as macdetails.py. We can use ‘-h’ or ‘–help’ to see the help on how to run this script from the terminal. Output : Python web-scraping-exercises Python-projects Python-requests python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 58, "s": 28, "text": "Prerequisite: Python Requests" }, { "code": null, "e": 174, "s": 58, "text": "A MAC address is a unique identity of a network interface that is used to address the device in a Computer Network." }, { "code": null, "e": 341, "s": 174, "text": "A MAC address is made up of 12 hexadecimal digits, 6 octets separated by ‘:’. There are 6 octets in a MAC address. In the first half, the manufacturer info is stored." }, { "code": null, "e": 579, "s": 341, "text": "For this article, we will be using an API that will fetch the MAC Address for us. We will use a Python script to automate the fetching process so that we can use it later in the Softwares and websites that may require this functionality." }, { "code": null, "e": 630, "s": 579, "text": "We will use requests module to work with this API." }, { "code": null, "e": 659, "s": 630, "text": "Below is the implementation." }, { "code": null, "e": 667, "s": 659, "text": "Python3" }, { "code": "import requestsimport argparse print(\"[*] Welcome\") # Function to get the interface namedef get_arguments(): # This will give user a neat CLI parser = argparse.ArgumentParser() # We need the MAC address parser.add_argument(\"-m\", \"--macaddress\", dest=\"mac_address\", help=\"MAC Address of the device. \" ) options = parser.parse_args() # Check if address was given if options.mac_address: return options.mac_address else: parser.error(\"[!] Invalid Syntax. \" \"Use --help for more details.\") def get_mac_details(mac_address): # We will use an API to get the vendor details url = \"https://api.macvendors.com/\" # Use get method to fetch details response = requests.get(url+mac_address) if response.status_code != 200: raise Exception(\"[!] Invalid MAC Address!\") return response.content.decode() # Driver Codeif __name__ == \"__main__\": mac_address = get_arguments() print(\"[+] Checking Details...\") try: vendor_name = get_mac_details(mac_address) print(\"[+] Device vendor is \"+vendor_name) except: # Incase something goes wrong print(\"[!] An error occured. Check \" \"your Internet connection.\")", "e": 2005, "s": 667, "text": null }, { "code": null, "e": 2126, "s": 2005, "text": "Save this code as macdetails.py. We can use ‘-h’ or ‘–help’ to see the help on how to run this script from the terminal." }, { "code": null, "e": 2136, "s": 2126, "text": "Output : " }, { "code": null, "e": 2166, "s": 2136, "text": "Python web-scraping-exercises" }, { "code": null, "e": 2182, "s": 2166, "text": "Python-projects" }, { "code": null, "e": 2198, "s": 2182, "text": "Python-requests" }, { "code": null, "e": 2213, "s": 2198, "text": "python-utility" }, { "code": null, "e": 2220, "s": 2213, "text": "Python" }, { "code": null, "e": 2318, "s": 2220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2350, "s": 2318, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2377, "s": 2350, "text": "Python Classes and Objects" }, { "code": null, "e": 2398, "s": 2377, "text": "Python OOPs Concepts" }, { "code": null, "e": 2421, "s": 2398, "text": "Introduction To PYTHON" }, { "code": null, "e": 2477, "s": 2421, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2508, "s": 2477, "text": "Python | os.path.join() method" }, { "code": null, "e": 2550, "s": 2508, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2592, "s": 2550, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2631, "s": 2592, "text": "Python | Get unique values from a list" } ]
GATE | GATE CS 2019 | Question 27
17 Aug, 2021 Consider the following C program: #include <stdio.h> int jumble(int x, int y) { x = 2 * x + y; return x; }int main() { int x = 2, y = 5; y = jumble(y, x); x = jumble(y, x); printf("%d\n", x); return 0; } The value printed by program is __________ . Note: This was Numerical Type question.(A) 26(B) 2(C) 5(D) 12Answer: (A)Explanation: #include <stdio.h> int jumble(int x, int y) { x = 2 * x + y; return x; }int main() { int x = 2, y = 5; y = jumble(y, x); x = jumble(y, x); printf("%d\n", x); return 0; } Initially x = 2, y = 5;jumble (5, 2) is called and y will updated as 12jumble (12, 2) is called and x will updated as 26Final value of x = 26 So, option (A) is correct. GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:001:14 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question sooda367 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 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2008 | Question 40 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2015 (Set 2) | Question 55 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Aug, 2021" }, { "code": null, "e": 86, "s": 52, "text": "Consider the following C program:" }, { "code": "#include <stdio.h> int jumble(int x, int y) { x = 2 * x + y; return x; }int main() { int x = 2, y = 5; y = jumble(y, x); x = jumble(y, x); printf(\"%d\\n\", x); return 0; }", "e": 270, "s": 86, "text": null }, { "code": null, "e": 315, "s": 270, "text": "The value printed by program is __________ ." }, { "code": null, "e": 400, "s": 315, "text": "Note: This was Numerical Type question.(A) 26(B) 2(C) 5(D) 12Answer: (A)Explanation:" }, { "code": "#include <stdio.h> int jumble(int x, int y) { x = 2 * x + y; return x; }int main() { int x = 2, y = 5; y = jumble(y, x); x = jumble(y, x); printf(\"%d\\n\", x); return 0; }", "e": 584, "s": 400, "text": null }, { "code": null, "e": 726, "s": 584, "text": "Initially x = 2, y = 5;jumble (5, 2) is called and y will updated as 12jumble (12, 2) is called and x will updated as 26Final value of x = 26" }, { "code": null, "e": 753, "s": 726, "text": "So, option (A) is correct." }, { "code": null, "e": 1786, "s": 753, "text": "GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:001:14 / 1:16:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fP8QED8d6ws\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 1795, "s": 1786, "text": "sooda367" }, { "code": null, "e": 1800, "s": 1795, "text": "GATE" }, { "code": null, "e": 1898, "s": 1800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1940, "s": 1898, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2002, "s": 1940, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2036, "s": 2002, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2078, "s": 2036, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2120, "s": 2078, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 2162, "s": 2120, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2196, "s": 2162, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 2230, "s": 2196, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 2272, "s": 2230, "text": "GATE | GATE-CS-2015 (Set 2) | Question 55" } ]
Line Clipping | Set 2 (Cyrus Beck Algorithm)
28 Jun, 2019 Background:Cyrus Beck is a line clipping algorithm that is made for convex polygons. It allows line clipping for non-rectangular windows, unlike Cohen Sutherland or Nicholl Le Nicholl. It also removes the repeated clipping needed in Cohen Sutherland. Input: 1. Convex area of interest which is defined by a set of coordinates given in a clockwise fashion. 2. vertices which are an array of coordinates: consisting of pairs (x, y) 3. n which is the number of vertices 4. A line to be clipped given by a set of coordinates. 5. line which is an array of coordinates: consisting of two pairs, (x0, y0) and (x1, y1) Output: 1. Coordinates of line clipping which is the Accepted clipping 2. Coordinates (-1, -1) which is the Rejected clipping Algorithm: Normals of every edge is calculated. Vector for the clipping line is calculated. Dot product between the difference of one vertex per edge and one selected end point of the clipping line and the normal of the edge is calculated (for all edges). Dot product between the vector of the clipping line and the normal of edge (for all edges) is calculated. The former dot product is divided by the latter dot product and multiplied by -1. This is ‘t’. The values of ‘t’ are classified as entering or exiting (from all edges) by observing their denominators (latter dot product). One value of ‘t’ is chosen from each group, and put into the parametric form of a line to calculate the coordinates. If the entering ‘t’ value is greater than the exiting ‘t’ value, then the clipping line is rejected. Cases: Case 1: The line is partially inside the clipping window:0 < tE < tL < 1 where tE is 't' value for entering intersection point tL is 't' value for exiting intersection point Case 2: The line has one point inside or both sides inside the window or the intersection points are on the end points of the line:0 ≤ tE ≤ tL ≤ 1Case 3: The line is completely outside the window:tL < tE Case 1: The line is partially inside the clipping window:0 < tE < tL < 1 where tE is 't' value for entering intersection point tL is 't' value for exiting intersection point 0 < tE < tL < 1 where tE is 't' value for entering intersection point tL is 't' value for exiting intersection point Case 2: The line has one point inside or both sides inside the window or the intersection points are on the end points of the line:0 ≤ tE ≤ tL ≤ 1 0 ≤ tE ≤ tL ≤ 1 Case 3: The line is completely outside the window:tL < tE tL < tE Pseudocode: First, calculate the parametric form of the line to be clipped and then follow the algorithm. Choose a point called P1 from the two points of the line (P0P1). Now for each edge of the polygon, calculate the normal pointing away from the centre of the polygon, namely N1, N2, etc. Now for each edge choose PEi (i -> ith edge) (choose any of the vertices of the corresponding edge, eg.: For polygon ABCD, for side AB, PEi can be either point A or point B) and calculateP0 - PEi P0 - PEi Then calculateP1 - P0 P1 - P0 Then calculate the following dot products for each edge:Ni . (P0 - PEi) Ni . (P1 - P0) where i -> ith edge of the convex polygon Ni . (P0 - PEi) Ni . (P1 - P0) where i -> ith edge of the convex polygon Then calculate the corresponding ‘t’ values for each edge by: Ni . (P0 - PEi) t = ------------------ -(Ni . (P1 - P0)) Ni . (P0 - PEi) t = ------------------ -(Ni . (P1 - P0)) Then club the ‘t’ values for which the Ni . (P1 – P0) came out to be negative and take the minimum of all of them and 1. Similarly club all the ‘t’ values for which the Ni . (P1 – P0) came out to be positive and take the maximum of all of the clubbed ‘t’ values and 0. Now the two ‘t’ values obtained from this algorithm are plugged into the parametric form of the ‘to be clipped’ line and the resulting two points obtained are the clipped points. Implementation: Here is an implementation of the above steps in SFML C++ Graphics Library. You can also press any key to unclip the line and press any key to clip the line.// C++ Program to implement Cyrus Beck #include <SFML/Graphics.hpp>#include <iostream>#include <utility>#include <vector> using namespace std;using namespace sf; // Function to draw a line in SFMLvoid drawline(RenderWindow* window, pair<int, int> p0, pair<int, int> p1){ Vertex line[] = { Vertex(Vector2f(p0.first, p0.second)), Vertex(Vector2f(p1.first, p1.second)) }; window->draw(line, 2, Lines);} // Function to draw a polygon, given verticesvoid drawPolygon(RenderWindow* window, pair<int, int> vertices[], int n){ for (int i = 0; i < n - 1; i++) drawline(window, vertices[i], vertices[i + 1]); drawline(window, vertices[0], vertices[n - 1]);} // Function to take dot productint dot(pair<int, int> p0, pair<int, int> p1){ return p0.first * p1.first + p0.second * p1.second;} // Function to calculate the max from a vector of floatsfloat max(vector<float> t){ float maximum = INT_MIN; for (int i = 0; i < t.size(); i++) if (t[i] > maximum) maximum = t[i]; return maximum;} // Function to calculate the min from a vector of floatsfloat min(vector<float> t){ float minimum = INT_MAX; for (int i = 0; i < t.size(); i++) if (t[i] < minimum) minimum = t[i]; return minimum;} // Cyrus Beck function, returns a pair of values// that are then displayed as a linepair<int, int>* CyrusBeck(pair<int, int> vertices[], pair<int, int> line[], int n){ // Temporary holder value that will be returned pair<int, int>* newPair = new pair<int, int>[2]; // Normals initialized dynamically(can do it statically also, doesn't matter) pair<int, int>* normal = new pair<int, int>[n]; // Calculating the normals for (int i = 0; i < n; i++) { normal[i].second = vertices[(i + 1) % n].first - vertices[i].first; normal[i].first = vertices[i].second - vertices[(i + 1) % n].second; } // Calculating P1 - P0 pair<int, int> P1_P0 = make_pair(line[1].first - line[0].first, line[1].second - line[0].second); // Initializing all values of P0 - PEi pair<int, int>* P0_PEi = new pair<int, int>[n]; // Calculating the values of P0 - PEi for all edges for (int i = 0; i < n; i++) { // Calculating PEi - P0, so that the // denominator won't have to multiply by -1 P0_PEi[i].first = vertices[i].first - line[0].first; // while calculating 't' P0_PEi[i].second = vertices[i].second - line[0].second; } int *numerator = new int[n], *denominator = new int[n]; // Calculating the numerator and denominators // using the dot function for (int i = 0; i < n; i++) { numerator[i] = dot(normal[i], P0_PEi[i]); denominator[i] = dot(normal[i], P1_P0); } // Initializing the 't' values dynamically float* t = new float[n]; // Making two vectors called 't entering' // and 't leaving' to group the 't's // according to their denominators vector<float> tE, tL; // Calculating 't' and grouping them accordingly for (int i = 0; i < n; i++) { t[i] = (float)(numerator[i]) / (float)(denominator[i]); if (denominator[i] > 0) tE.push_back(t[i]); else tL.push_back(t[i]); } // Initializing the final two values of 't' float temp[2]; // Taking the max of all 'tE' and 0, so pushing 0 tE.push_back(0.f); temp[0] = max(tE); // Taking the min of all 'tL' and 1, so pushing 1 tL.push_back(1.f); temp[1] = min(tL); // Entering 't' value cannot be // greater than exiting 't' value, // hence, this is the case when the line // is completely outside if (temp[0] > temp[1]) { newPair[0] = make_pair(-1, -1); newPair[1] = make_pair(-1, -1); return newPair; } // Calculating the coordinates in terms of x and y newPair[0].firs t = (float)line[0].first + (float)P1_P0.first * (float)temp[0]; newPair[0].second = (float)line[0].second + (float)P1_P0.second * (float)temp[0]; newPair[1].first = (float)line[0].first + (float)P1_P0.first * (float)temp[1]; newPair[1].second = (float)line[0].second + (float)P1_P0.second * (float)temp[1]; cout << '(' << newPair[0].first << ", " << newPair[0].second << ") (" << newPair[1].first << ", " << newPair[1].second << ")"; return newPair;} // Driver codeint main(){ // Setting up a window and loop // and the vertices of the polygon and line RenderWindow window(VideoMode(500, 500), "Cyrus Beck"); pair<int, int> vertices[] = { make_pair(200, 50), make_pair(250, 100), make_pair(200, 150), make_pair(100, 150), make_pair(50, 100), make_pair(100, 50) }; // Make sure that the vertices // are put in a clockwise order int n = sizeof(vertices) / sizeof(vertices[0]); pair<int, int> line[] = { make_pair(10, 10), make_pair(450, 200) }; pair<int, int>* temp1 = CyrusBeck(vertices, line, n); pair<int, int> temp2[2]; temp2[0] = line[0]; temp2[1] = line[1]; // To allow clipping and unclipping // of the line by just pressing a key bool trigger = false; while (window.isOpen()) { window.clear(); Event event; if (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (event.type == Event::KeyPressed) trigger = !trigger; } drawPolygon(&window, vertices, n); // Using the trigger value to clip // and unclip a line if (trigger) { line[0] = temp1[0]; line[1] = temp1[1]; } else { line[0] = temp2[0]; line[1] = temp2[1]; } drawline(&window, line[0], line[1]); window.display(); } return 0;}Output:(102, 50) (240, 109)Before Clipping:After Clipping:My Personal Notes arrow_drop_upSave Implementation: Here is an implementation of the above steps in SFML C++ Graphics Library. You can also press any key to unclip the line and press any key to clip the line. // C++ Program to implement Cyrus Beck #include <SFML/Graphics.hpp>#include <iostream>#include <utility>#include <vector> using namespace std;using namespace sf; // Function to draw a line in SFMLvoid drawline(RenderWindow* window, pair<int, int> p0, pair<int, int> p1){ Vertex line[] = { Vertex(Vector2f(p0.first, p0.second)), Vertex(Vector2f(p1.first, p1.second)) }; window->draw(line, 2, Lines);} // Function to draw a polygon, given verticesvoid drawPolygon(RenderWindow* window, pair<int, int> vertices[], int n){ for (int i = 0; i < n - 1; i++) drawline(window, vertices[i], vertices[i + 1]); drawline(window, vertices[0], vertices[n - 1]);} // Function to take dot productint dot(pair<int, int> p0, pair<int, int> p1){ return p0.first * p1.first + p0.second * p1.second;} // Function to calculate the max from a vector of floatsfloat max(vector<float> t){ float maximum = INT_MIN; for (int i = 0; i < t.size(); i++) if (t[i] > maximum) maximum = t[i]; return maximum;} // Function to calculate the min from a vector of floatsfloat min(vector<float> t){ float minimum = INT_MAX; for (int i = 0; i < t.size(); i++) if (t[i] < minimum) minimum = t[i]; return minimum;} // Cyrus Beck function, returns a pair of values// that are then displayed as a linepair<int, int>* CyrusBeck(pair<int, int> vertices[], pair<int, int> line[], int n){ // Temporary holder value that will be returned pair<int, int>* newPair = new pair<int, int>[2]; // Normals initialized dynamically(can do it statically also, doesn't matter) pair<int, int>* normal = new pair<int, int>[n]; // Calculating the normals for (int i = 0; i < n; i++) { normal[i].second = vertices[(i + 1) % n].first - vertices[i].first; normal[i].first = vertices[i].second - vertices[(i + 1) % n].second; } // Calculating P1 - P0 pair<int, int> P1_P0 = make_pair(line[1].first - line[0].first, line[1].second - line[0].second); // Initializing all values of P0 - PEi pair<int, int>* P0_PEi = new pair<int, int>[n]; // Calculating the values of P0 - PEi for all edges for (int i = 0; i < n; i++) { // Calculating PEi - P0, so that the // denominator won't have to multiply by -1 P0_PEi[i].first = vertices[i].first - line[0].first; // while calculating 't' P0_PEi[i].second = vertices[i].second - line[0].second; } int *numerator = new int[n], *denominator = new int[n]; // Calculating the numerator and denominators // using the dot function for (int i = 0; i < n; i++) { numerator[i] = dot(normal[i], P0_PEi[i]); denominator[i] = dot(normal[i], P1_P0); } // Initializing the 't' values dynamically float* t = new float[n]; // Making two vectors called 't entering' // and 't leaving' to group the 't's // according to their denominators vector<float> tE, tL; // Calculating 't' and grouping them accordingly for (int i = 0; i < n; i++) { t[i] = (float)(numerator[i]) / (float)(denominator[i]); if (denominator[i] > 0) tE.push_back(t[i]); else tL.push_back(t[i]); } // Initializing the final two values of 't' float temp[2]; // Taking the max of all 'tE' and 0, so pushing 0 tE.push_back(0.f); temp[0] = max(tE); // Taking the min of all 'tL' and 1, so pushing 1 tL.push_back(1.f); temp[1] = min(tL); // Entering 't' value cannot be // greater than exiting 't' value, // hence, this is the case when the line // is completely outside if (temp[0] > temp[1]) { newPair[0] = make_pair(-1, -1); newPair[1] = make_pair(-1, -1); return newPair; } // Calculating the coordinates in terms of x and y newPair[0].firs t = (float)line[0].first + (float)P1_P0.first * (float)temp[0]; newPair[0].second = (float)line[0].second + (float)P1_P0.second * (float)temp[0]; newPair[1].first = (float)line[0].first + (float)P1_P0.first * (float)temp[1]; newPair[1].second = (float)line[0].second + (float)P1_P0.second * (float)temp[1]; cout << '(' << newPair[0].first << ", " << newPair[0].second << ") (" << newPair[1].first << ", " << newPair[1].second << ")"; return newPair;} // Driver codeint main(){ // Setting up a window and loop // and the vertices of the polygon and line RenderWindow window(VideoMode(500, 500), "Cyrus Beck"); pair<int, int> vertices[] = { make_pair(200, 50), make_pair(250, 100), make_pair(200, 150), make_pair(100, 150), make_pair(50, 100), make_pair(100, 50) }; // Make sure that the vertices // are put in a clockwise order int n = sizeof(vertices) / sizeof(vertices[0]); pair<int, int> line[] = { make_pair(10, 10), make_pair(450, 200) }; pair<int, int>* temp1 = CyrusBeck(vertices, line, n); pair<int, int> temp2[2]; temp2[0] = line[0]; temp2[1] = line[1]; // To allow clipping and unclipping // of the line by just pressing a key bool trigger = false; while (window.isOpen()) { window.clear(); Event event; if (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (event.type == Event::KeyPressed) trigger = !trigger; } drawPolygon(&window, vertices, n); // Using the trigger value to clip // and unclip a line if (trigger) { line[0] = temp1[0]; line[1] = temp1[1]; } else { line[0] = temp2[0]; line[1] = temp2[1]; } drawline(&window, line[0], line[1]); window.display(); } return 0;} Output: (102, 50) (240, 109) Before Clipping: After Clipping: computer-graphics Algorithms Geometric Geometric Algorithms 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, 2019" }, { "code": null, "e": 279, "s": 28, "text": "Background:Cyrus Beck is a line clipping algorithm that is made for convex polygons. It allows line clipping for non-rectangular windows, unlike Cohen Sutherland or Nicholl Le Nicholl. It also removes the repeated clipping needed in Cohen Sutherland." }, { "code": null, "e": 798, "s": 279, "text": "Input: \n 1. Convex area of interest \n which is defined by a set of coordinates\n given in a clockwise fashion.\n 2. vertices which are an array of coordinates: \n consisting of pairs (x, y)\n 3. n which is the number of vertices\n 4. A line to be clipped \n given by a set of coordinates.\n 5. line which is an array of coordinates: \n consisting of two pairs, (x0, y0) and (x1, y1)\nOutput:\n 1. Coordinates of line clipping which is the Accepted clipping\n 2. Coordinates (-1, -1) which is the Rejected clipping\n" }, { "code": null, "e": 809, "s": 798, "text": "Algorithm:" }, { "code": null, "e": 846, "s": 809, "text": "Normals of every edge is calculated." }, { "code": null, "e": 890, "s": 846, "text": "Vector for the clipping line is calculated." }, { "code": null, "e": 1054, "s": 890, "text": "Dot product between the difference of one vertex per edge and one selected end point of the clipping line and the normal of the edge is calculated (for all edges)." }, { "code": null, "e": 1160, "s": 1054, "text": "Dot product between the vector of the clipping line and the normal of edge (for all edges) is calculated." }, { "code": null, "e": 1255, "s": 1160, "text": "The former dot product is divided by the latter dot product and multiplied by -1. This is ‘t’." }, { "code": null, "e": 1382, "s": 1255, "text": "The values of ‘t’ are classified as entering or exiting (from all edges) by observing their denominators (latter dot product)." }, { "code": null, "e": 1499, "s": 1382, "text": "One value of ‘t’ is chosen from each group, and put into the parametric form of a line to calculate the coordinates." }, { "code": null, "e": 1600, "s": 1499, "text": "If the entering ‘t’ value is greater than the exiting ‘t’ value, then the clipping line is rejected." }, { "code": null, "e": 1607, "s": 1600, "text": "Cases:" }, { "code": null, "e": 1992, "s": 1607, "text": "Case 1: The line is partially inside the clipping window:0 < tE < tL < 1\n\nwhere tE is 't' value for entering intersection point\n tL is 't' value for exiting intersection point\nCase 2: The line has one point inside or both sides inside the window or the intersection points are on the end points of the line:0 ≤ tE ≤ tL ≤ 1Case 3: The line is completely outside the window:tL < tE" }, { "code": null, "e": 2174, "s": 1992, "text": "Case 1: The line is partially inside the clipping window:0 < tE < tL < 1\n\nwhere tE is 't' value for entering intersection point\n tL is 't' value for exiting intersection point\n" }, { "code": null, "e": 2299, "s": 2174, "text": "0 < tE < tL < 1\n\nwhere tE is 't' value for entering intersection point\n tL is 't' value for exiting intersection point\n" }, { "code": null, "e": 2446, "s": 2299, "text": "Case 2: The line has one point inside or both sides inside the window or the intersection points are on the end points of the line:0 ≤ tE ≤ tL ≤ 1" }, { "code": null, "e": 2462, "s": 2446, "text": "0 ≤ tE ≤ tL ≤ 1" }, { "code": null, "e": 2520, "s": 2462, "text": "Case 3: The line is completely outside the window:tL < tE" }, { "code": null, "e": 2528, "s": 2520, "text": "tL < tE" }, { "code": null, "e": 2540, "s": 2528, "text": "Pseudocode:" }, { "code": null, "e": 2634, "s": 2540, "text": "First, calculate the parametric form of the line to be clipped and then follow the algorithm." }, { "code": null, "e": 2699, "s": 2634, "text": "Choose a point called P1 from the two points of the line (P0P1)." }, { "code": null, "e": 2820, "s": 2699, "text": "Now for each edge of the polygon, calculate the normal pointing away from the centre of the polygon, namely N1, N2, etc." }, { "code": null, "e": 3017, "s": 2820, "text": "Now for each edge choose PEi (i -> ith edge) (choose any of the vertices of the corresponding edge, eg.: For polygon ABCD, for side AB, PEi can be either point A or point B) and calculateP0 - PEi " }, { "code": null, "e": 3027, "s": 3017, "text": "P0 - PEi " }, { "code": null, "e": 3049, "s": 3027, "text": "Then calculateP1 - P0" }, { "code": null, "e": 3057, "s": 3049, "text": "P1 - P0" }, { "code": null, "e": 3188, "s": 3057, "text": "Then calculate the following dot products for each edge:Ni . (P0 - PEi)\nNi . (P1 - P0) \n\nwhere i -> ith edge of the convex polygon" }, { "code": null, "e": 3263, "s": 3188, "text": "Ni . (P0 - PEi)\nNi . (P1 - P0) \n\nwhere i -> ith edge of the convex polygon" }, { "code": null, "e": 3389, "s": 3263, "text": "Then calculate the corresponding ‘t’ values for each edge by: Ni . (P0 - PEi)\nt = ------------------\n -(Ni . (P1 - P0))" }, { "code": null, "e": 3454, "s": 3389, "text": " Ni . (P0 - PEi)\nt = ------------------\n -(Ni . (P1 - P0))" }, { "code": null, "e": 3575, "s": 3454, "text": "Then club the ‘t’ values for which the Ni . (P1 – P0) came out to be negative and take the minimum of all of them and 1." }, { "code": null, "e": 3723, "s": 3575, "text": "Similarly club all the ‘t’ values for which the Ni . (P1 – P0) came out to be positive and take the maximum of all of the clubbed ‘t’ values and 0." }, { "code": null, "e": 3902, "s": 3723, "text": "Now the two ‘t’ values obtained from this algorithm are plugged into the parametric form of the ‘to be clipped’ line and the resulting two points obtained are the clipped points." }, { "code": null, "e": 10131, "s": 3902, "text": "Implementation: Here is an implementation of the above steps in SFML C++ Graphics Library. You can also press any key to unclip the line and press any key to clip the line.// C++ Program to implement Cyrus Beck #include <SFML/Graphics.hpp>#include <iostream>#include <utility>#include <vector> using namespace std;using namespace sf; // Function to draw a line in SFMLvoid drawline(RenderWindow* window, pair<int, int> p0, pair<int, int> p1){ Vertex line[] = { Vertex(Vector2f(p0.first, p0.second)), Vertex(Vector2f(p1.first, p1.second)) }; window->draw(line, 2, Lines);} // Function to draw a polygon, given verticesvoid drawPolygon(RenderWindow* window, pair<int, int> vertices[], int n){ for (int i = 0; i < n - 1; i++) drawline(window, vertices[i], vertices[i + 1]); drawline(window, vertices[0], vertices[n - 1]);} // Function to take dot productint dot(pair<int, int> p0, pair<int, int> p1){ return p0.first * p1.first + p0.second * p1.second;} // Function to calculate the max from a vector of floatsfloat max(vector<float> t){ float maximum = INT_MIN; for (int i = 0; i < t.size(); i++) if (t[i] > maximum) maximum = t[i]; return maximum;} // Function to calculate the min from a vector of floatsfloat min(vector<float> t){ float minimum = INT_MAX; for (int i = 0; i < t.size(); i++) if (t[i] < minimum) minimum = t[i]; return minimum;} // Cyrus Beck function, returns a pair of values// that are then displayed as a linepair<int, int>* CyrusBeck(pair<int, int> vertices[], pair<int, int> line[], int n){ // Temporary holder value that will be returned pair<int, int>* newPair = new pair<int, int>[2]; // Normals initialized dynamically(can do it statically also, doesn't matter) pair<int, int>* normal = new pair<int, int>[n]; // Calculating the normals for (int i = 0; i < n; i++) { normal[i].second = vertices[(i + 1) % n].first - vertices[i].first; normal[i].first = vertices[i].second - vertices[(i + 1) % n].second; } // Calculating P1 - P0 pair<int, int> P1_P0 = make_pair(line[1].first - line[0].first, line[1].second - line[0].second); // Initializing all values of P0 - PEi pair<int, int>* P0_PEi = new pair<int, int>[n]; // Calculating the values of P0 - PEi for all edges for (int i = 0; i < n; i++) { // Calculating PEi - P0, so that the // denominator won't have to multiply by -1 P0_PEi[i].first = vertices[i].first - line[0].first; // while calculating 't' P0_PEi[i].second = vertices[i].second - line[0].second; } int *numerator = new int[n], *denominator = new int[n]; // Calculating the numerator and denominators // using the dot function for (int i = 0; i < n; i++) { numerator[i] = dot(normal[i], P0_PEi[i]); denominator[i] = dot(normal[i], P1_P0); } // Initializing the 't' values dynamically float* t = new float[n]; // Making two vectors called 't entering' // and 't leaving' to group the 't's // according to their denominators vector<float> tE, tL; // Calculating 't' and grouping them accordingly for (int i = 0; i < n; i++) { t[i] = (float)(numerator[i]) / (float)(denominator[i]); if (denominator[i] > 0) tE.push_back(t[i]); else tL.push_back(t[i]); } // Initializing the final two values of 't' float temp[2]; // Taking the max of all 'tE' and 0, so pushing 0 tE.push_back(0.f); temp[0] = max(tE); // Taking the min of all 'tL' and 1, so pushing 1 tL.push_back(1.f); temp[1] = min(tL); // Entering 't' value cannot be // greater than exiting 't' value, // hence, this is the case when the line // is completely outside if (temp[0] > temp[1]) { newPair[0] = make_pair(-1, -1); newPair[1] = make_pair(-1, -1); return newPair; } // Calculating the coordinates in terms of x and y newPair[0].firs t = (float)line[0].first + (float)P1_P0.first * (float)temp[0]; newPair[0].second = (float)line[0].second + (float)P1_P0.second * (float)temp[0]; newPair[1].first = (float)line[0].first + (float)P1_P0.first * (float)temp[1]; newPair[1].second = (float)line[0].second + (float)P1_P0.second * (float)temp[1]; cout << '(' << newPair[0].first << \", \" << newPair[0].second << \") (\" << newPair[1].first << \", \" << newPair[1].second << \")\"; return newPair;} // Driver codeint main(){ // Setting up a window and loop // and the vertices of the polygon and line RenderWindow window(VideoMode(500, 500), \"Cyrus Beck\"); pair<int, int> vertices[] = { make_pair(200, 50), make_pair(250, 100), make_pair(200, 150), make_pair(100, 150), make_pair(50, 100), make_pair(100, 50) }; // Make sure that the vertices // are put in a clockwise order int n = sizeof(vertices) / sizeof(vertices[0]); pair<int, int> line[] = { make_pair(10, 10), make_pair(450, 200) }; pair<int, int>* temp1 = CyrusBeck(vertices, line, n); pair<int, int> temp2[2]; temp2[0] = line[0]; temp2[1] = line[1]; // To allow clipping and unclipping // of the line by just pressing a key bool trigger = false; while (window.isOpen()) { window.clear(); Event event; if (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (event.type == Event::KeyPressed) trigger = !trigger; } drawPolygon(&window, vertices, n); // Using the trigger value to clip // and unclip a line if (trigger) { line[0] = temp1[0]; line[1] = temp1[1]; } else { line[0] = temp2[0]; line[1] = temp2[1]; } drawline(&window, line[0], line[1]); window.display(); } return 0;}Output:(102, 50) (240, 109)Before Clipping:After Clipping:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 10304, "s": 10131, "text": "Implementation: Here is an implementation of the above steps in SFML C++ Graphics Library. You can also press any key to unclip the line and press any key to clip the line." }, { "code": "// C++ Program to implement Cyrus Beck #include <SFML/Graphics.hpp>#include <iostream>#include <utility>#include <vector> using namespace std;using namespace sf; // Function to draw a line in SFMLvoid drawline(RenderWindow* window, pair<int, int> p0, pair<int, int> p1){ Vertex line[] = { Vertex(Vector2f(p0.first, p0.second)), Vertex(Vector2f(p1.first, p1.second)) }; window->draw(line, 2, Lines);} // Function to draw a polygon, given verticesvoid drawPolygon(RenderWindow* window, pair<int, int> vertices[], int n){ for (int i = 0; i < n - 1; i++) drawline(window, vertices[i], vertices[i + 1]); drawline(window, vertices[0], vertices[n - 1]);} // Function to take dot productint dot(pair<int, int> p0, pair<int, int> p1){ return p0.first * p1.first + p0.second * p1.second;} // Function to calculate the max from a vector of floatsfloat max(vector<float> t){ float maximum = INT_MIN; for (int i = 0; i < t.size(); i++) if (t[i] > maximum) maximum = t[i]; return maximum;} // Function to calculate the min from a vector of floatsfloat min(vector<float> t){ float minimum = INT_MAX; for (int i = 0; i < t.size(); i++) if (t[i] < minimum) minimum = t[i]; return minimum;} // Cyrus Beck function, returns a pair of values// that are then displayed as a linepair<int, int>* CyrusBeck(pair<int, int> vertices[], pair<int, int> line[], int n){ // Temporary holder value that will be returned pair<int, int>* newPair = new pair<int, int>[2]; // Normals initialized dynamically(can do it statically also, doesn't matter) pair<int, int>* normal = new pair<int, int>[n]; // Calculating the normals for (int i = 0; i < n; i++) { normal[i].second = vertices[(i + 1) % n].first - vertices[i].first; normal[i].first = vertices[i].second - vertices[(i + 1) % n].second; } // Calculating P1 - P0 pair<int, int> P1_P0 = make_pair(line[1].first - line[0].first, line[1].second - line[0].second); // Initializing all values of P0 - PEi pair<int, int>* P0_PEi = new pair<int, int>[n]; // Calculating the values of P0 - PEi for all edges for (int i = 0; i < n; i++) { // Calculating PEi - P0, so that the // denominator won't have to multiply by -1 P0_PEi[i].first = vertices[i].first - line[0].first; // while calculating 't' P0_PEi[i].second = vertices[i].second - line[0].second; } int *numerator = new int[n], *denominator = new int[n]; // Calculating the numerator and denominators // using the dot function for (int i = 0; i < n; i++) { numerator[i] = dot(normal[i], P0_PEi[i]); denominator[i] = dot(normal[i], P1_P0); } // Initializing the 't' values dynamically float* t = new float[n]; // Making two vectors called 't entering' // and 't leaving' to group the 't's // according to their denominators vector<float> tE, tL; // Calculating 't' and grouping them accordingly for (int i = 0; i < n; i++) { t[i] = (float)(numerator[i]) / (float)(denominator[i]); if (denominator[i] > 0) tE.push_back(t[i]); else tL.push_back(t[i]); } // Initializing the final two values of 't' float temp[2]; // Taking the max of all 'tE' and 0, so pushing 0 tE.push_back(0.f); temp[0] = max(tE); // Taking the min of all 'tL' and 1, so pushing 1 tL.push_back(1.f); temp[1] = min(tL); // Entering 't' value cannot be // greater than exiting 't' value, // hence, this is the case when the line // is completely outside if (temp[0] > temp[1]) { newPair[0] = make_pair(-1, -1); newPair[1] = make_pair(-1, -1); return newPair; } // Calculating the coordinates in terms of x and y newPair[0].firs t = (float)line[0].first + (float)P1_P0.first * (float)temp[0]; newPair[0].second = (float)line[0].second + (float)P1_P0.second * (float)temp[0]; newPair[1].first = (float)line[0].first + (float)P1_P0.first * (float)temp[1]; newPair[1].second = (float)line[0].second + (float)P1_P0.second * (float)temp[1]; cout << '(' << newPair[0].first << \", \" << newPair[0].second << \") (\" << newPair[1].first << \", \" << newPair[1].second << \")\"; return newPair;} // Driver codeint main(){ // Setting up a window and loop // and the vertices of the polygon and line RenderWindow window(VideoMode(500, 500), \"Cyrus Beck\"); pair<int, int> vertices[] = { make_pair(200, 50), make_pair(250, 100), make_pair(200, 150), make_pair(100, 150), make_pair(50, 100), make_pair(100, 50) }; // Make sure that the vertices // are put in a clockwise order int n = sizeof(vertices) / sizeof(vertices[0]); pair<int, int> line[] = { make_pair(10, 10), make_pair(450, 200) }; pair<int, int>* temp1 = CyrusBeck(vertices, line, n); pair<int, int> temp2[2]; temp2[0] = line[0]; temp2[1] = line[1]; // To allow clipping and unclipping // of the line by just pressing a key bool trigger = false; while (window.isOpen()) { window.clear(); Event event; if (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (event.type == Event::KeyPressed) trigger = !trigger; } drawPolygon(&window, vertices, n); // Using the trigger value to clip // and unclip a line if (trigger) { line[0] = temp1[0]; line[1] = temp1[1]; } else { line[0] = temp2[0]; line[1] = temp2[1]; } drawline(&window, line[0], line[1]); window.display(); } return 0;}", "e": 16268, "s": 10304, "text": null }, { "code": null, "e": 16276, "s": 16268, "text": "Output:" }, { "code": null, "e": 16297, "s": 16276, "text": "(102, 50) (240, 109)" }, { "code": null, "e": 16314, "s": 16297, "text": "Before Clipping:" }, { "code": null, "e": 16330, "s": 16314, "text": "After Clipping:" }, { "code": null, "e": 16348, "s": 16330, "text": "computer-graphics" }, { "code": null, "e": 16359, "s": 16348, "text": "Algorithms" }, { "code": null, "e": 16369, "s": 16359, "text": "Geometric" }, { "code": null, "e": 16379, "s": 16369, "text": "Geometric" }, { "code": null, "e": 16390, "s": 16379, "text": "Algorithms" } ]
Queue element() method in Java
26 Sep, 2018 The element() method of Queue Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the queue. This method differs from peek() only in that it throws an exception if this queue is empty. Syntax: E element() Returns: This method returns the head of the Queue. Exception: The function throws NoSuchElementException when the queue is empty and the function is called. Below programs illustrate element() method of Queue: Program 1: With the help of LinkedList. // Java Program Demonstrate element()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.element()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Program 2: With the help of ArrayDeque. // Java Program Demonstrate element()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.element()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Program 3: With the help of LinkedBlockingDeque. // Java Program Demonstrate element()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.element()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Program 4: With the help of ConcurrentLinkedDeque. // Java Program Demonstrate element()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.element()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Below programs illustrate exceptions thrown by this method: Program 5: To show NoSuchElementException. // Java Program Demonstrate element()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.element()); Q.clear(); // print queue System.out.println("Queue: " + Q); try { // Queue is empty now hence exception System.out.println("Queue's head: " + Q.element()); } catch (Exception e) { System.out.println("Exception: " + e); } }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Queue: [] Exception: java.util.NoSuchElementException Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#element– Java - util package java-basics Java-Collections Java-Functions java-queue Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2018" }, { "code": null, "e": 209, "s": 28, "text": "The element() method of Queue Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the queue." }, { "code": null, "e": 301, "s": 209, "text": "This method differs from peek() only in that it throws an exception if this queue is empty." }, { "code": null, "e": 309, "s": 301, "text": "Syntax:" }, { "code": null, "e": 321, "s": 309, "text": "E element()" }, { "code": null, "e": 373, "s": 321, "text": "Returns: This method returns the head of the Queue." }, { "code": null, "e": 479, "s": 373, "text": "Exception: The function throws NoSuchElementException when the queue is empty and the function is called." }, { "code": null, "e": 532, "s": 479, "text": "Below programs illustrate element() method of Queue:" }, { "code": null, "e": 572, "s": 532, "text": "Program 1: With the help of LinkedList." }, { "code": "// Java Program Demonstrate element()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.element()); }}", "e": 1139, "s": 572, "text": null }, { "code": null, "e": 1208, "s": 1139, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 1248, "s": 1208, "text": "Program 2: With the help of ArrayDeque." }, { "code": "// Java Program Demonstrate element()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.element()); }}", "e": 1815, "s": 1248, "text": null }, { "code": null, "e": 1884, "s": 1815, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 1933, "s": 1884, "text": "Program 3: With the help of LinkedBlockingDeque." }, { "code": "// Java Program Demonstrate element()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.element()); }}", "e": 2557, "s": 1933, "text": null }, { "code": null, "e": 2626, "s": 2557, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 2677, "s": 2626, "text": "Program 4: With the help of ConcurrentLinkedDeque." }, { "code": "// Java Program Demonstrate element()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.element()); }}", "e": 3305, "s": 2677, "text": null }, { "code": null, "e": 3374, "s": 3305, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 3434, "s": 3374, "text": "Below programs illustrate exceptions thrown by this method:" }, { "code": null, "e": 3477, "s": 3434, "text": "Program 5: To show NoSuchElementException." }, { "code": "// Java Program Demonstrate element()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.element()); Q.clear(); // print queue System.out.println(\"Queue: \" + Q); try { // Queue is empty now hence exception System.out.println(\"Queue's head: \" + Q.element()); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 4354, "s": 3477, "text": null }, { "code": null, "e": 4477, "s": 4354, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\nQueue: []\nException: java.util.NoSuchElementException\n" }, { "code": null, "e": 4560, "s": 4477, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#element–" }, { "code": null, "e": 4580, "s": 4560, "text": "Java - util package" }, { "code": null, "e": 4592, "s": 4580, "text": "java-basics" }, { "code": null, "e": 4609, "s": 4592, "text": "Java-Collections" }, { "code": null, "e": 4624, "s": 4609, "text": "Java-Functions" }, { "code": null, "e": 4635, "s": 4624, "text": "java-queue" }, { "code": null, "e": 4640, "s": 4635, "text": "Java" }, { "code": null, "e": 4645, "s": 4640, "text": "Java" }, { "code": null, "e": 4662, "s": 4645, "text": "Java-Collections" } ]
What is the main difference between int.Parse() and Convert.ToInt32 in C#?
Convert a string representation of number to an integer, using the int.Parse or Convert.ToInt32 method in C#. If the string cannot be converted, then the int.Parse or Convert.ToInt32 method returns an exception Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, and it throws an ArgumentNullException error. Live Demo class Program { static void Main() { int res; string myStr = "5000"; res = int.Parse(myStr); Console.WriteLine("Converting String is a numeric representation: " + res); Console.ReadLine(); } } Converting String is a numeric representation: 5000 Live Demo class Program { static void Main() { int res; string myStr = null; res = Convert.ToInt32(myStr); Console.WriteLine("Converting String is a numeric representation: " + res); Console.ReadLine(); } } Converting String is a numeric representation: 0 Live Demo class Program { static void Main() { int res; string myStr = null; res = int.Parse(myStr); Console.WriteLine("Converting String is a numeric representation: " + res); Console.ReadLine(); } } Unhandled exception. System.ArgumentNullException: Value cannot be null.
[ { "code": null, "e": 1398, "s": 1187, "text": "Convert a string representation of number to an integer, using the int.Parse or Convert.ToInt32 method in C#. If the string cannot be converted, then the int.Parse or Convert.ToInt32 method returns an exception" }, { "code": null, "e": 1544, "s": 1398, "text": "Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, and it throws an ArgumentNullException error." }, { "code": null, "e": 1555, "s": 1544, "text": " Live Demo" }, { "code": null, "e": 1784, "s": 1555, "text": "class Program {\n static void Main() {\n int res;\n string myStr = \"5000\";\n res = int.Parse(myStr);\n Console.WriteLine(\"Converting String is a numeric representation: \" + res);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 1836, "s": 1784, "text": "Converting String is a numeric representation: 5000" }, { "code": null, "e": 1847, "s": 1836, "text": " Live Demo" }, { "code": null, "e": 2080, "s": 1847, "text": "class Program {\n static void Main() {\n int res;\n string myStr = null;\n res = Convert.ToInt32(myStr);\n Console.WriteLine(\"Converting String is a numeric representation: \" + res);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2129, "s": 2080, "text": "Converting String is a numeric representation: 0" }, { "code": null, "e": 2140, "s": 2129, "text": " Live Demo" }, { "code": null, "e": 2367, "s": 2140, "text": "class Program {\n static void Main() {\n int res;\n string myStr = null;\n res = int.Parse(myStr);\n Console.WriteLine(\"Converting String is a numeric representation: \" + res);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2440, "s": 2367, "text": "Unhandled exception. System.ArgumentNullException: Value cannot be null." } ]
Set the width of a button with CSS
To set the button width, use the CSS width property. You can try to run the following code to set the width of a button − Live Demo <!DOCTYPE html> <html> <head> <style> .btn { background-color: yellow; color: black; width: 120px; text-align: center; font-size: 15px; padding: 20px; border-radius: 15px; border: 3px dashed blue; } </style> </head> <body> <h2>Result</h2> <p>Click below for result:</p> <button class = "btn">Result</button> </body> </html>
[ { "code": null, "e": 1240, "s": 1187, "text": "To set the button width, use the CSS width property." }, { "code": null, "e": 1309, "s": 1240, "text": "You can try to run the following code to set the width of a button −" }, { "code": null, "e": 1319, "s": 1309, "text": "Live Demo" }, { "code": null, "e": 1799, "s": 1319, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .btn {\n background-color: yellow;\n color: black;\n width: 120px;\n text-align: center;\n font-size: 15px;\n padding: 20px;\n border-radius: 15px;\n border: 3px dashed blue;\n }\n </style>\n </head>\n <body>\n <h2>Result</h2>\n <p>Click below for result:</p>\n <button class = \"btn\">Result</button>\n </body>\n</html>" } ]
Partition of a set into K subsets with equal sum
11 Jul, 2022 Given an integer array of N elements, the task is to divide this array into K non-empty subsets such that the sum of elements in every subset is same. All elements of this array should be part of exactly one partition. Examples: Input : arr = [2, 1, 4, 5, 6], K = 3 Output : Yes we can divide above array into 3 parts with equal sum as [[2, 4], [1, 5], [6]] Input : arr = [2, 1, 5, 5, 6], K = 3 Output : No It is not possible to divide above array into 3 parts with equal sum We can solve this problem recursively, we keep an array for sum of each partition and a boolean array to check whether an element is already taken into some partition or not. First we need to check some base cases, If K is 1, then we already have our answer, complete array is only subset with same sum. If N < K, then it is not possible to divide array into subsets with equal sum, because we can’t divide the array into more than N parts. If sum of array is not divisible by K, then it is not possible to divide the array. We will proceed only if k divides sum. Our goal reduces to divide array into K parts where sum of each part should be array_sum/K In below code a recursive method is written which tries to add array element into some subset. If sum of this subset reaches required sum, we iterate for next part recursively, otherwise we backtrack for different set of elements. If number of subsets whose sum reaches the required sum is (K-1), we flag that it is possible to partition array into K parts with equal sum, because remaining elements already have a sum equal to required sum. C++ Java Python3 C# Javascript // C++ program to check whether an array can be// partitioned into K subsets of equal sum#include <bits/stdc++.h>using namespace std; // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */bool isKPartitionPossibleRec(int arr[], int subsetSum[], bool taken[], int subset, int K, int N, int curIdx, int limitIdx){ if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; bool nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumbool isKPartitionPossible(int arr[], int N, int K){ // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int subsetSum[K]; bool taken[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver code to test above methodsint main(){ int arr[] = {2, 1, 4, 5, 3, 3}; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; if (isKPartitionPossible(arr, N, K)) cout << "Partitions into equal sum is possible.\n"; else cout << "Partitions into equal sum is not possible.\n";} // Java program to check whether an array can be// partitioned into K subsets of equal sumclass GFG{ // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */static boolean isKPartitionPossibleRec(int arr[], int subsetSum[], boolean taken[], int subset, int K, int N, int curIdx, int limitIdx){ if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; boolean nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumstatic boolean isKPartitionPossible(int arr[], int N, int K){ // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int []subsetSum = new int[K]; boolean []taken = new boolean[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver codepublic static void main(String[] args){ int arr[] = {2, 1, 4, 5, 3, 3}; int N = arr.length; int K = 3; if (isKPartitionPossible(arr, N, K)) System.out.println("Partitions into equal sum is possible."); else System.out.println("Partitions into equal sum is not possible.");}} // This code is contributed by Princi Singh # Python3 program to check whether an array can be# partitioned into K subsets of equal sum # Recursive Utility method to check K equal sum# subsetition of array """*array - given input arraysubsetSum array - sum to store each subset of the arraytaken -boolean array to check whether elementis taken into sum partition or notK - number of partitions neededN - total number of element in arraycurIdx - current subsetSum indexlimitIdx - lastIdx from where array element shouldbe taken """ def isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, limitIdx): if subsetSum[curIdx] == subset: """ current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'""" if (curIdx == K - 2): return True # recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1 , N - 1) # start from limitIdx and include # elements into current partition for i in range(limitIdx, -1, -1): # if already taken, continue if (taken[i]): continue tmp = subsetSum[curIdx] + arr[i] # if temp is less than subset, then only # include the element and call recursively if (tmp <= subset): # mark the element and include into # current partition sum taken[i] = True subsetSum[curIdx] += arr[i] nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1) # after recursive call unmark the element and # remove from subsetition sum taken[i] = False subsetSum[curIdx] -= arr[i] if (nxt): return True return False # Method returns True if arr can be# partitioned into K subsets with equal sumdef isKPartitionPossible(arr, N, K): # If K is 1, # then complete array will be our answer if (K == 1): return True # If total number of partitions are more than N, # then division is not possible if (N < K): return False # if array sum is not divisible by K then # we can't divide array into K partitions sum = 0 for i in range(N): sum += arr[i] if (sum % K != 0): return False # the sum of each subset should be subset (= sum / K) subset = sum // K subsetSum = [0] * K taken = [0] * N # Initialize sum of each subset from 0 for i in range(K): subsetSum[i] = 0 # mark all elements as not taken for i in range(N): taken[i] = False # initialize first subset sum as # last element of array and mark that as taken subsetSum[0] = arr[N - 1] taken[N - 1] = True # call recursive method to check # K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1) # Driver Codearr = [2, 1, 4, 5, 3, 3 ]N = len(arr)K = 3if (isKPartitionPossible(arr, N, K)): print("Partitions into equal sum is possible.\n")else: print("Partitions into equal sum is not possible.\n") # This code is contributed by SHUBHAMSINGH8410 // C# program to check whether an array can be// partitioned into K subsets of equal sumusing System; class GFG{ // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */static bool isKPartitionPossibleRec(int []arr, int []subsetSum, bool []taken, int subset, int K, int N, int curIdx, int limitIdx){ if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; bool nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumstatic bool isKPartitionPossible(int []arr, int N, int K){ // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int []subsetSum = new int[K]; bool []taken = new bool[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver codestatic public void Main (){ int []arr = {2, 1, 4, 5, 3, 3}; int N = arr.Length; int K = 3; if (isKPartitionPossible(arr, N, K)) Console.WriteLine("Partitions into equal sum is possible."); else Console.WriteLine("Partitions into equal sum is not possible.");}} // This code is contributed by ajit. <script>// Javascript program to check whether an array can be// partitioned into K subsets of equal sum // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */function isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, limitIdx) { if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (let i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; let tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; let nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumfunction isKPartitionPossible(arr, N, K) { // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions let sum = 0; for (let i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) let subset = sum / K; let subsetSum = new Array(K); let taken = new Array(N); // Initialize sum of each subset from 0 for (let i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (let i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver code to test above methodslet arr = [2, 1, 4, 5, 3, 3];let N = arr.length;let K = 3; if (isKPartitionPossible(arr, N, K)) document.write("Partitions into equal sum is possible");else document.write("Partitions into equal sum is not possible") // This code is contributed by saurabh_jaiswal.</script> Output: Partitions into equal sum is possible. Complexity Analysis: Time Complexity: O(2^(N * K)). Because if we have K trees stacked on top of each other, the new height of the tree is K * n. i.e one subset is not independent from other.Space Complexity: O(N). Extra space is required for visited array.This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ayush0824 princi singh jit_t SHUBHAMSINGH10 _saurabh_jaiswal surinderdawra388 simmytarika5 ritesh2000tiwari Microsoft Backtracking Microsoft Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 283, "s": 52, "text": "Given an integer array of N elements, the task is to divide this array into K non-empty subsets such that the sum of elements in every subset is same. All elements of this array should be part of exactly one partition. Examples: " }, { "code": null, "e": 532, "s": 283, "text": "Input : arr = [2, 1, 4, 5, 6], K = 3\nOutput : Yes\nwe can divide above array into 3 parts with equal\nsum as [[2, 4], [1, 5], [6]]\n\nInput : arr = [2, 1, 5, 5, 6], K = 3\nOutput : No\nIt is not possible to divide above array into 3\nparts with equal sum" }, { "code": null, "e": 1633, "s": 534, "text": "We can solve this problem recursively, we keep an array for sum of each partition and a boolean array to check whether an element is already taken into some partition or not. First we need to check some base cases, If K is 1, then we already have our answer, complete array is only subset with same sum. If N < K, then it is not possible to divide array into subsets with equal sum, because we can’t divide the array into more than N parts. If sum of array is not divisible by K, then it is not possible to divide the array. We will proceed only if k divides sum. Our goal reduces to divide array into K parts where sum of each part should be array_sum/K In below code a recursive method is written which tries to add array element into some subset. If sum of this subset reaches required sum, we iterate for next part recursively, otherwise we backtrack for different set of elements. If number of subsets whose sum reaches the required sum is (K-1), we flag that it is possible to partition array into K parts with equal sum, because remaining elements already have a sum equal to required sum. " }, { "code": null, "e": 1637, "s": 1633, "text": "C++" }, { "code": null, "e": 1642, "s": 1637, "text": "Java" }, { "code": null, "e": 1650, "s": 1642, "text": "Python3" }, { "code": null, "e": 1653, "s": 1650, "text": "C#" }, { "code": null, "e": 1664, "s": 1653, "text": "Javascript" }, { "code": "// C++ program to check whether an array can be// partitioned into K subsets of equal sum#include <bits/stdc++.h>using namespace std; // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */bool isKPartitionPossibleRec(int arr[], int subsetSum[], bool taken[], int subset, int K, int N, int curIdx, int limitIdx){ if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; bool nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumbool isKPartitionPossible(int arr[], int N, int K){ // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int subsetSum[K]; bool taken[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver code to test above methodsint main(){ int arr[] = {2, 1, 4, 5, 3, 3}; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; if (isKPartitionPossible(arr, N, K)) cout << \"Partitions into equal sum is possible.\\n\"; else cout << \"Partitions into equal sum is not possible.\\n\";}", "e": 5314, "s": 1664, "text": null }, { "code": "// Java program to check whether an array can be// partitioned into K subsets of equal sumclass GFG{ // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */static boolean isKPartitionPossibleRec(int arr[], int subsetSum[], boolean taken[], int subset, int K, int N, int curIdx, int limitIdx){ if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; boolean nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumstatic boolean isKPartitionPossible(int arr[], int N, int K){ // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int []subsetSum = new int[K]; boolean []taken = new boolean[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver codepublic static void main(String[] args){ int arr[] = {2, 1, 4, 5, 3, 3}; int N = arr.length; int K = 3; if (isKPartitionPossible(arr, N, K)) System.out.println(\"Partitions into equal sum is possible.\"); else System.out.println(\"Partitions into equal sum is not possible.\");}} // This code is contributed by Princi Singh", "e": 9006, "s": 5314, "text": null }, { "code": "# Python3 program to check whether an array can be# partitioned into K subsets of equal sum # Recursive Utility method to check K equal sum# subsetition of array \"\"\"*array - given input arraysubsetSum array - sum to store each subset of the arraytaken -boolean array to check whether elementis taken into sum partition or notK - number of partitions neededN - total number of element in arraycurIdx - current subsetSum indexlimitIdx - lastIdx from where array element shouldbe taken \"\"\" def isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, limitIdx): if subsetSum[curIdx] == subset: \"\"\" current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'\"\"\" if (curIdx == K - 2): return True # recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1 , N - 1) # start from limitIdx and include # elements into current partition for i in range(limitIdx, -1, -1): # if already taken, continue if (taken[i]): continue tmp = subsetSum[curIdx] + arr[i] # if temp is less than subset, then only # include the element and call recursively if (tmp <= subset): # mark the element and include into # current partition sum taken[i] = True subsetSum[curIdx] += arr[i] nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1) # after recursive call unmark the element and # remove from subsetition sum taken[i] = False subsetSum[curIdx] -= arr[i] if (nxt): return True return False # Method returns True if arr can be# partitioned into K subsets with equal sumdef isKPartitionPossible(arr, N, K): # If K is 1, # then complete array will be our answer if (K == 1): return True # If total number of partitions are more than N, # then division is not possible if (N < K): return False # if array sum is not divisible by K then # we can't divide array into K partitions sum = 0 for i in range(N): sum += arr[i] if (sum % K != 0): return False # the sum of each subset should be subset (= sum / K) subset = sum // K subsetSum = [0] * K taken = [0] * N # Initialize sum of each subset from 0 for i in range(K): subsetSum[i] = 0 # mark all elements as not taken for i in range(N): taken[i] = False # initialize first subset sum as # last element of array and mark that as taken subsetSum[0] = arr[N - 1] taken[N - 1] = True # call recursive method to check # K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1) # Driver Codearr = [2, 1, 4, 5, 3, 3 ]N = len(arr)K = 3if (isKPartitionPossible(arr, N, K)): print(\"Partitions into equal sum is possible.\\n\")else: print(\"Partitions into equal sum is not possible.\\n\") # This code is contributed by SHUBHAMSINGH8410", "e": 12445, "s": 9006, "text": null }, { "code": "// C# program to check whether an array can be// partitioned into K subsets of equal sumusing System; class GFG{ // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */static bool isKPartitionPossibleRec(int []arr, int []subsetSum, bool []taken, int subset, int K, int N, int curIdx, int limitIdx){ if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (int i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; int tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; bool nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumstatic bool isKPartitionPossible(int []arr, int N, int K){ // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) int subset = sum / K; int []subsetSum = new int[K]; bool []taken = new bool[N]; // Initialize sum of each subset from 0 for (int i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (int i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver codestatic public void Main (){ int []arr = {2, 1, 4, 5, 3, 3}; int N = arr.Length; int K = 3; if (isKPartitionPossible(arr, N, K)) Console.WriteLine(\"Partitions into equal sum is possible.\"); else Console.WriteLine(\"Partitions into equal sum is not possible.\");}} // This code is contributed by ajit.", "e": 16099, "s": 12445, "text": null }, { "code": "<script>// Javascript program to check whether an array can be// partitioned into K subsets of equal sum // Recursive Utility method to check K equal sum// subsetition of array/** array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken */function isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, limitIdx) { if (subsetSum[curIdx] == subset) { /* current index (K - 2) represents (K - 1) subsets of equal sum last partition will already remain with sum 'subset'*/ if (curIdx == K - 2) return true; // recursive call for next subsetition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx + 1, N - 1); } // start from limitIdx and include elements into current partition for (let i = limitIdx; i >= 0; i--) { // if already taken, continue if (taken[i]) continue; let tmp = subsetSum[curIdx] + arr[i]; // if temp is less than subset then only include the element // and call recursively if (tmp <= subset) { // mark the element and include into current partition sum taken[i] = true; subsetSum[curIdx] += arr[i]; let nxt = isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, curIdx, i - 1); // after recursive call unmark the element and remove from // subsetition sum taken[i] = false; subsetSum[curIdx] -= arr[i]; if (nxt) return true; } } return false;} // Method returns true if arr can be partitioned into K subsets// with equal sumfunction isKPartitionPossible(arr, N, K) { // If K is 1, then complete array will be our answer if (K == 1) return true; // If total number of partitions are more than N, then // division is not possible if (N < K) return false; // if array sum is not divisible by K then we can't divide // array into K partitions let sum = 0; for (let i = 0; i < N; i++) sum += arr[i]; if (sum % K != 0) return false; // the sum of each subset should be subset (= sum / K) let subset = sum / K; let subsetSum = new Array(K); let taken = new Array(N); // Initialize sum of each subset from 0 for (let i = 0; i < K; i++) subsetSum[i] = 0; // mark all elements as not taken for (let i = 0; i < N; i++) taken[i] = false; // initialize first subset sum as last element of // array and mark that as taken subsetSum[0] = arr[N - 1]; taken[N - 1] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(arr, subsetSum, taken, subset, K, N, 0, N - 1);} // Driver code to test above methodslet arr = [2, 1, 4, 5, 3, 3];let N = arr.length;let K = 3; if (isKPartitionPossible(arr, N, K)) document.write(\"Partitions into equal sum is possible\");else document.write(\"Partitions into equal sum is not possible\") // This code is contributed by saurabh_jaiswal.</script>", "e": 19594, "s": 16099, "text": null }, { "code": null, "e": 19604, "s": 19594, "text": "Output: " }, { "code": null, "e": 19643, "s": 19604, "text": "Partitions into equal sum is possible." }, { "code": null, "e": 19665, "s": 19643, "text": "Complexity Analysis: " }, { "code": null, "e": 20325, "s": 19665, "text": "Time Complexity: O(2^(N * K)). Because if we have K trees stacked on top of each other, the new height of the tree is K * n. i.e one subset is not independent from other.Space Complexity: O(N). Extra space is required for visited array.This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 20335, "s": 20325, "text": "ayush0824" }, { "code": null, "e": 20348, "s": 20335, "text": "princi singh" }, { "code": null, "e": 20354, "s": 20348, "text": "jit_t" }, { "code": null, "e": 20369, "s": 20354, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 20386, "s": 20369, "text": "_saurabh_jaiswal" }, { "code": null, "e": 20403, "s": 20386, "text": "surinderdawra388" }, { "code": null, "e": 20416, "s": 20403, "text": "simmytarika5" }, { "code": null, "e": 20433, "s": 20416, "text": "ritesh2000tiwari" }, { "code": null, "e": 20443, "s": 20433, "text": "Microsoft" }, { "code": null, "e": 20456, "s": 20443, "text": "Backtracking" }, { "code": null, "e": 20466, "s": 20456, "text": "Microsoft" }, { "code": null, "e": 20479, "s": 20466, "text": "Backtracking" } ]
PHP | header() Function
01 Aug, 2021 The header() function is an inbuilt function in PHP which is used to send a raw HTTP header. The HTTP functions are those functions which manipulate information sent to the client or browser by the Web server, before any other output has been sent. The PHP header() function send a HTTP header to a client or browser in raw form. Before HTML, XML, JSON or other output has been sent to a browser or client, a raw data is sent with request (especially HTTP Request) made by the server as header information. HTTP header provide required information about the object sent in the message body more precisely about the request and response. Syntax: void header( $header, $replace = TRUE, $http_response_code ) Parameters: This function accepts three parameters as mentioned above and described below: $header: This parameter hold the header string. There are two types of header calls. The first header starts with string “HTTP/”, which is used to figure out the HTTP status code to send. The second case of header is the “Location:”. It is mandatory parameter. $replace: It is optional parameter. It denotes the header should replace previous or add a second header. The default value is True (will replace). If $replace value is False then it force multiple headers of the same type. $http_response_code: It is an optional parameter. It forces the HTTP response code to the specified value (PHP 4.3 and higher). Return Values: This function doesn’t return any value. Example 1: <?php// PHP program to describes header function // Redirect the browserheader("Location: https://www.geeksforgeeks.org"); // The below code does not get executed // while redirectingexit; ?> Output: This will change location of header, i.e. redirect to the URL Example 2: <?php// PHP program to describes header function // Set a past dateheader("Expires: Sun, 25 Jul 1997 06:02:34 GMT");header("Cache-Control: no-cache");header("Pragma: no-cache");?> <html> <body> <p>Hello World!</p> <!-- PHP program to display header list --> <?php print_r(headers_list()); ?> </body></html> Output: Hello World! Array ( [0] => X-Powered-By: PHP/7.0.33 [1] => Expires: Sun, 25 Jul 1997 06:02:34 GMT [2] => Cache-Control: no-cache [3] => Pragma: no-cache ) The above example helps to prevent caching by sending header information which override browser setting to not-cache. Note: The header() functions is used multiple time in the example as one header is allowed to send at a time (since PHP 4.4) to prevent header injection attacks. Uses: Change page location Set timezone Set caching control Initiate force download Send HTTP Status Reference: http://php.net/manual/en/function.header.php 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. PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? How to get parameters from a URL string in PHP? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Aug, 2021" }, { "code": null, "e": 689, "s": 52, "text": "The header() function is an inbuilt function in PHP which is used to send a raw HTTP header. The HTTP functions are those functions which manipulate information sent to the client or browser by the Web server, before any other output has been sent. The PHP header() function send a HTTP header to a client or browser in raw form. Before HTML, XML, JSON or other output has been sent to a browser or client, a raw data is sent with request (especially HTTP Request) made by the server as header information. HTTP header provide required information about the object sent in the message body more precisely about the request and response." }, { "code": null, "e": 697, "s": 689, "text": "Syntax:" }, { "code": null, "e": 758, "s": 697, "text": "void header( $header, $replace = TRUE, $http_response_code )" }, { "code": null, "e": 849, "s": 758, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 1110, "s": 849, "text": "$header: This parameter hold the header string. There are two types of header calls. The first header starts with string “HTTP/”, which is used to figure out the HTTP status code to send. The second case of header is the “Location:”. It is mandatory parameter." }, { "code": null, "e": 1334, "s": 1110, "text": "$replace: It is optional parameter. It denotes the header should replace previous or add a second header. The default value is True (will replace). If $replace value is False then it force multiple headers of the same type." }, { "code": null, "e": 1462, "s": 1334, "text": "$http_response_code: It is an optional parameter. It forces the HTTP response code to the specified value (PHP 4.3 and higher)." }, { "code": null, "e": 1517, "s": 1462, "text": "Return Values: This function doesn’t return any value." }, { "code": null, "e": 1528, "s": 1517, "text": "Example 1:" }, { "code": "<?php// PHP program to describes header function // Redirect the browserheader(\"Location: https://www.geeksforgeeks.org\"); // The below code does not get executed // while redirectingexit; ?>", "e": 1723, "s": 1528, "text": null }, { "code": null, "e": 1731, "s": 1723, "text": "Output:" }, { "code": null, "e": 1793, "s": 1731, "text": "This will change location of header, i.e. redirect to the URL" }, { "code": null, "e": 1804, "s": 1793, "text": "Example 2:" }, { "code": "<?php// PHP program to describes header function // Set a past dateheader(\"Expires: Sun, 25 Jul 1997 06:02:34 GMT\");header(\"Cache-Control: no-cache\");header(\"Pragma: no-cache\");?> <html> <body> <p>Hello World!</p> <!-- PHP program to display header list --> <?php print_r(headers_list()); ?> </body></html>", "e": 2171, "s": 1804, "text": null }, { "code": null, "e": 2179, "s": 2171, "text": "Output:" }, { "code": null, "e": 2358, "s": 2179, "text": "Hello World!\n\nArray ( \n [0] => X-Powered-By: PHP/7.0.33 \n [1] => Expires: Sun, 25 Jul 1997 06:02:34 GMT \n [2] => Cache-Control: no-cache \n [3] => Pragma: no-cache \n)\n" }, { "code": null, "e": 2476, "s": 2358, "text": "The above example helps to prevent caching by sending header information which override browser setting to not-cache." }, { "code": null, "e": 2638, "s": 2476, "text": "Note: The header() functions is used multiple time in the example as one header is allowed to send at a time (since PHP 4.4) to prevent header injection attacks." }, { "code": null, "e": 2644, "s": 2638, "text": "Uses:" }, { "code": null, "e": 2665, "s": 2644, "text": "Change page location" }, { "code": null, "e": 2678, "s": 2665, "text": "Set timezone" }, { "code": null, "e": 2698, "s": 2678, "text": "Set caching control" }, { "code": null, "e": 2722, "s": 2698, "text": "Initiate force download" }, { "code": null, "e": 2739, "s": 2722, "text": "Send HTTP Status" }, { "code": null, "e": 2795, "s": 2739, "text": "Reference: http://php.net/manual/en/function.header.php" }, { "code": null, "e": 2964, "s": 2795, "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": 2977, "s": 2964, "text": "PHP-function" }, { "code": null, "e": 2981, "s": 2977, "text": "PHP" }, { "code": null, "e": 2998, "s": 2981, "text": "Web Technologies" }, { "code": null, "e": 3002, "s": 2998, "text": "PHP" }, { "code": null, "e": 3100, "s": 3002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3140, "s": 3100, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3185, "s": 3140, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3212, "s": 3185, "text": "Comparing two dates in PHP" }, { "code": null, "e": 3248, "s": 3212, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 3296, "s": 3248, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 3329, "s": 3296, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3391, "s": 3329, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3452, "s": 3391, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3502, "s": 3452, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Flutter – BoxDecoration Widget
22 Jun, 2021 BoxDecoration is a build-in widget in flutter API. At a bare basic level, it describes how a box should be painted on the screen. The shape of the box needs not to be just a rectangle or a square it can circle also. It comes with a ton of properties we can add an image inside, add a radius to the border (if the shape is a rectangle), cast shadow to the box, etc. Below we will see all its properties and an example implementation of the BoxDecoration widget. const BoxDecoration( {Color? color, DecorationImage? image, BoxBorder? border, BorderRadiusGeometry? borderRadius, List<BoxShadow>? boxShadow, Gradient? gradient, BlendMode? backgroundBlendMode, BoxShape shape: BoxShape.rectangle} ) backgroundBlendMode: This property takes in the BlendMode enum as the object to this parameter. It applies a blending effect to the background color or gradient. border: The border parameter takes in the BoxBorder class as the object to draw a border around the box. borderRadius: This property takes in the BorderRadiusGeometry class as the object which in turn adds curves around the border corners if the box shape is a rectangle. boxShadow: This property holds a list of BoxShadow widget as the object. It casts a shadow on the box. color: This property takes in the Color class as the object to give a background color to the BoxDecoration widget. gradient: This property takes in Gradient class as the object to apply a gradient filling inside the box. image: This property adds an image over the background taking in the DecorationImage class as the object. padding: This property takes in the EdgeInsetsGeometry class as the object to add empty space around the content inside the box. shape: This property takes in the BoxShape as the object to decide the shape of the box. Example: Dart import 'package:flutter/material.dart'; //imported material design packagevoid main() { runApp( //Widget tree starts from here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: Container( width: 300, height: 300, //BoxDecoration Widget decoration: BoxDecoration( image: const DecorationImage( image: NetworkImage( 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png'), fit: BoxFit.cover, ), //DecorationImage border: Border.all( color: Colors.green, width: 8, ), //Border.all borderRadius: BorderRadius.circular(15), boxShadow: [ BoxShadow( color: Colors.black, offset: const Offset( 5.0, 5.0, ), //Offset blurRadius: 10.0, spreadRadius: 2.0, ), //BoxShadow BoxShadow( color: Colors.white, offset: const Offset(0.0, 0.0), blurRadius: 0.0, spreadRadius: 0.0, ), //BoxShadow ], ), //BoxDecoration ), //Container ), //Center ), //Scaffold ), //MaterialApp );} Output: Explanation: The parent widget in this app is Center which is holding the entire widget tree of the app body. The Center widget is holding Container widget as the child. The BoxDecoration widget is taken by the decoration property of the Container. The first element drawn inside the box is a NetworkImage with the help of image property. Then we have the border property which had assigned a 4 pixels thick green colored border around the box. And to add curves around the corners of the border we have the boderRadius property adding a curve of 15 px radius on each corner. And at last, we have the boxShadow property which has a list of two BoxShadow class to assign a white color background in the box (beneath the image) and a deep black-colored shadow outside the box. rajeev0719singh android Flutter Flutter-widgets Android Articles Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Android SDK and it's Components Broadcast Receiver in Android With Example Navigation Drawer in Android Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) Time Complexity and Space Complexity
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2021" }, { "code": null, "e": 515, "s": 54, "text": "BoxDecoration is a build-in widget in flutter API. At a bare basic level, it describes how a box should be painted on the screen. The shape of the box needs not to be just a rectangle or a square it can circle also. It comes with a ton of properties we can add an image inside, add a radius to the border (if the shape is a rectangle), cast shadow to the box, etc. Below we will see all its properties and an example implementation of the BoxDecoration widget." }, { "code": null, "e": 749, "s": 515, "text": " const BoxDecoration(\n{Color? color,\nDecorationImage? image,\nBoxBorder? border,\nBorderRadiusGeometry? borderRadius,\nList<BoxShadow>? boxShadow,\nGradient? gradient,\nBlendMode? backgroundBlendMode,\nBoxShape shape: BoxShape.rectangle}\n)" }, { "code": null, "e": 911, "s": 749, "text": "backgroundBlendMode: This property takes in the BlendMode enum as the object to this parameter. It applies a blending effect to the background color or gradient." }, { "code": null, "e": 1016, "s": 911, "text": "border: The border parameter takes in the BoxBorder class as the object to draw a border around the box." }, { "code": null, "e": 1183, "s": 1016, "text": "borderRadius: This property takes in the BorderRadiusGeometry class as the object which in turn adds curves around the border corners if the box shape is a rectangle." }, { "code": null, "e": 1286, "s": 1183, "text": "boxShadow: This property holds a list of BoxShadow widget as the object. It casts a shadow on the box." }, { "code": null, "e": 1402, "s": 1286, "text": "color: This property takes in the Color class as the object to give a background color to the BoxDecoration widget." }, { "code": null, "e": 1508, "s": 1402, "text": "gradient: This property takes in Gradient class as the object to apply a gradient filling inside the box." }, { "code": null, "e": 1614, "s": 1508, "text": "image: This property adds an image over the background taking in the DecorationImage class as the object." }, { "code": null, "e": 1743, "s": 1614, "text": "padding: This property takes in the EdgeInsetsGeometry class as the object to add empty space around the content inside the box." }, { "code": null, "e": 1832, "s": 1743, "text": "shape: This property takes in the BoxShape as the object to decide the shape of the box." }, { "code": null, "e": 1842, "s": 1832, "text": "Example: " }, { "code": null, "e": 1847, "s": 1842, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; //imported material design packagevoid main() { runApp( //Widget tree starts from here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: Container( width: 300, height: 300, //BoxDecoration Widget decoration: BoxDecoration( image: const DecorationImage( image: NetworkImage( 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png'), fit: BoxFit.cover, ), //DecorationImage border: Border.all( color: Colors.green, width: 8, ), //Border.all borderRadius: BorderRadius.circular(15), boxShadow: [ BoxShadow( color: Colors.black, offset: const Offset( 5.0, 5.0, ), //Offset blurRadius: 10.0, spreadRadius: 2.0, ), //BoxShadow BoxShadow( color: Colors.white, offset: const Offset(0.0, 0.0), blurRadius: 0.0, spreadRadius: 0.0, ), //BoxShadow ], ), //BoxDecoration ), //Container ), //Center ), //Scaffold ), //MaterialApp );}", "e": 3398, "s": 1847, "text": null }, { "code": null, "e": 3407, "s": 3398, "text": "Output: " }, { "code": null, "e": 4182, "s": 3407, "text": "Explanation: The parent widget in this app is Center which is holding the entire widget tree of the app body. The Center widget is holding Container widget as the child. The BoxDecoration widget is taken by the decoration property of the Container. The first element drawn inside the box is a NetworkImage with the help of image property. Then we have the border property which had assigned a 4 pixels thick green colored border around the box. And to add curves around the corners of the border we have the boderRadius property adding a curve of 15 px radius on each corner. And at last, we have the boxShadow property which has a list of two BoxShadow class to assign a white color background in the box (beneath the image) and a deep black-colored shadow outside the box." }, { "code": null, "e": 4198, "s": 4182, "text": "rajeev0719singh" }, { "code": null, "e": 4206, "s": 4198, "text": "android" }, { "code": null, "e": 4214, "s": 4206, "text": "Flutter" }, { "code": null, "e": 4230, "s": 4214, "text": "Flutter-widgets" }, { "code": null, "e": 4238, "s": 4230, "text": "Android" }, { "code": null, "e": 4247, "s": 4238, "text": "Articles" }, { "code": null, "e": 4252, "s": 4247, "text": "Dart" }, { "code": null, "e": 4260, "s": 4252, "text": "Flutter" }, { "code": null, "e": 4268, "s": 4260, "text": "Android" }, { "code": null, "e": 4366, "s": 4268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4435, "s": 4366, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 4466, "s": 4435, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 4498, "s": 4466, "text": "Android SDK and it's Components" }, { "code": null, "e": 4541, "s": 4498, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 4570, "s": 4541, "text": "Navigation Drawer in Android" }, { "code": null, "e": 4620, "s": 4570, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 4667, "s": 4620, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 4703, "s": 4667, "text": "find command in Linux with examples" }, { "code": null, "e": 4756, "s": 4703, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" } ]
Using _ (underscore) as Variable Name in Java
25 Nov, 2021 As we do know variables in java or rather in any language is introduced to write a code where it is suggested to give meaningful names to the variables as per their usage in code and especially in object-oriented languages are supposed to be used locally where ever it is possible instead of just using them globally. It is a very essential property of variables that is been checked is enterprising domain as it helps us achieve cleaner and minimalistic code. Case 1: Using underscore as a variable name in Java 8 Although it is supported in Java 8, a mandatory warning is issued if you use _ as an identifier, telling you that “use of ‘_’ as an identifier might not be supported in releases after Java SE 8”. Example: Java // Java Program to Illustrate Usage of Underscore// As a Variable Name // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring underscore as variable // in java 8 only int _ = 10; // Printing the value stored in it System.out.println(_); }} Output: 10 With the advancement in the version of Java, Java 9 has made changes in features of the java language, and eliminating underscore from the legal name is a major change made by Oracle. The use of the variable name _ in any context is never encouraged. The latest versions of Java reserve this name as a keyword and/or give it special semantics. If you use the underscore character (“_”) as an identifier, your source code can no longer be compiled. We will get a compile-time error. Case 2: Using underscore as a variable name in Java 9 Example: Java // Java program to illustrate Usage of Underscore// As Variable Name in Java9 // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring underscore as variable // in java9 and onwards int _ = 10; // Printing the value as stored in underscore System.out.println(_); }} Output: In Java 9, underscore as variable name won’t work altogether. Below source code can no longer be compiled. Below are the following conclusions been drawn from the above examples as illustrated: Using underscore in a variable like first_name is still valid. But using _ alone as a variable name is no more valid.Even if you are using earlier versions of Java, using only underscore as a variable name is just a plain bad style of programming and must be avoided. Using underscore in a variable like first_name is still valid. But using _ alone as a variable name is no more valid. Even if you are using earlier versions of Java, using only underscore as a variable name is just a plain bad style of programming and must be avoided. This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank java-basics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Nov, 2021" }, { "code": null, "e": 515, "s": 53, "text": "As we do know variables in java or rather in any language is introduced to write a code where it is suggested to give meaningful names to the variables as per their usage in code and especially in object-oriented languages are supposed to be used locally where ever it is possible instead of just using them globally. It is a very essential property of variables that is been checked is enterprising domain as it helps us achieve cleaner and minimalistic code. " }, { "code": null, "e": 569, "s": 515, "text": "Case 1: Using underscore as a variable name in Java 8" }, { "code": null, "e": 765, "s": 569, "text": "Although it is supported in Java 8, a mandatory warning is issued if you use _ as an identifier, telling you that “use of ‘_’ as an identifier might not be supported in releases after Java SE 8”." }, { "code": null, "e": 774, "s": 765, "text": "Example:" }, { "code": null, "e": 779, "s": 774, "text": "Java" }, { "code": "// Java Program to Illustrate Usage of Underscore// As a Variable Name // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring underscore as variable // in java 8 only int _ = 10; // Printing the value stored in it System.out.println(_); }}", "e": 1117, "s": 779, "text": null }, { "code": null, "e": 1126, "s": 1117, "text": "Output: " }, { "code": null, "e": 1129, "s": 1126, "text": "10" }, { "code": null, "e": 1611, "s": 1129, "text": "With the advancement in the version of Java, Java 9 has made changes in features of the java language, and eliminating underscore from the legal name is a major change made by Oracle. The use of the variable name _ in any context is never encouraged. The latest versions of Java reserve this name as a keyword and/or give it special semantics. If you use the underscore character (“_”) as an identifier, your source code can no longer be compiled. We will get a compile-time error." }, { "code": null, "e": 1665, "s": 1611, "text": "Case 2: Using underscore as a variable name in Java 9" }, { "code": null, "e": 1674, "s": 1665, "text": "Example:" }, { "code": null, "e": 1679, "s": 1674, "text": "Java" }, { "code": "// Java program to illustrate Usage of Underscore// As Variable Name in Java9 // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring underscore as variable // in java9 and onwards int _ = 10; // Printing the value as stored in underscore System.out.println(_); }}", "e": 2043, "s": 1679, "text": null }, { "code": null, "e": 2158, "s": 2043, "text": "Output: In Java 9, underscore as variable name won’t work altogether. Below source code can no longer be compiled." }, { "code": null, "e": 2246, "s": 2158, "text": "Below are the following conclusions been drawn from the above examples as illustrated: " }, { "code": null, "e": 2514, "s": 2246, "text": "Using underscore in a variable like first_name is still valid. But using _ alone as a variable name is no more valid.Even if you are using earlier versions of Java, using only underscore as a variable name is just a plain bad style of programming and must be avoided." }, { "code": null, "e": 2632, "s": 2514, "text": "Using underscore in a variable like first_name is still valid. But using _ alone as a variable name is no more valid." }, { "code": null, "e": 2783, "s": 2632, "text": "Even if you are using earlier versions of Java, using only underscore as a variable name is just a plain bad style of programming and must be avoided." }, { "code": null, "e": 3206, "s": 2783, "text": "This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3220, "s": 3206, "text": "solankimayank" }, { "code": null, "e": 3232, "s": 3220, "text": "java-basics" }, { "code": null, "e": 3237, "s": 3232, "text": "Java" }, { "code": null, "e": 3242, "s": 3237, "text": "Java" } ]
SQL Query to Convert VARCHAR to INT
28 Oct, 2021 SQL Server’s CAST() and CONVERT() methods can be used to convert VARCHAR to INT. We’ll also look at the more efficient and secure approach to transform values from one data type to another. The CAST() function in SQL Server is used to cast or transform a value or an expression from one data type to another. Syntax : CAST ( expression AS target_type [ ( length ) ] ) Parameters: expression – Any value of any type that will be converted. target_type – Target data type to which the value will be converted. e.g. INT, BIT, SQL_VARIANT, etc. length – Optional parameter that specifies the length of the target_type, default length is 30. Let’s take an example where the CAST() function is used to convert VARCHAR to INT. Query: SELECT CAST('1234' AS INT) AS Result; Output: In SQL Server, the CONVERT() function is used to convert a value of one type to another. Converting anything involves changing its shape or value. Syntax : SELECT CONVERT ( target_type ( length ), expression ) Parameters: target_type – Data type to which the expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc. length – It provides the length of the target_type. Length is not mandatory. The default length is set to 30. expression – expression is anything that will be converted. In the below example, the CONVERT() function is used to convert VARCHAR to INT. Query: SELECT CONVERT(INT,'5678') AS Result; Now Lets us discuss a more efficient approach to convert the values from one data type to another using SQL Server’s TRY_CAST() and TRY_CONVERT() function: The TRY_CAST() function attempts to cast the input value to a value of the given data type. If the cast is successful, it returns the value in the provided data; else, it returns NULL. However, if you request a conversion that is not valid, the TRY_CAST() method will return an error. Syntax : TRY_CAST ( expression AS data_type [ ( length ) ] ) Parameters used: data_type: Valid data type into which the function will cast the expression. expression: Value to be cast. Query: SELECT TRY_CAST('1234' as INT) as Result; Query: SELECT TRY_CAST('1234abc' as INT) as Result; The TRY_CONVERT() method attempts to convert the value supplied to it to the data type specified. If the cast is successful, it returns the value as the given data; else, it returns NULL. If you request a conversion that is explicitly forbidden, the TRY CONVERT() method will return an error. Syntax : TRY_CONVERT ( data_type[(length)], expression [,style]) Parameters used: data_type: Valid data type into which the function will cast the expression. expression: Value to be cast. style: Is a provided integer that specifies how the function will translate the expression. Query: SELECT TRY_CONVERT( INT ,'5678') as Result; Query: SELECT TRY_CONVERT( INT ,'56abc') as Result; Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Oct, 2021" }, { "code": null, "e": 243, "s": 53, "text": "SQL Server’s CAST() and CONVERT() methods can be used to convert VARCHAR to INT. We’ll also look at the more efficient and secure approach to transform values from one data type to another." }, { "code": null, "e": 362, "s": 243, "text": "The CAST() function in SQL Server is used to cast or transform a value or an expression from one data type to another." }, { "code": null, "e": 371, "s": 362, "text": "Syntax :" }, { "code": null, "e": 421, "s": 371, "text": "CAST ( expression AS target_type [ ( length ) ] )" }, { "code": null, "e": 433, "s": 421, "text": "Parameters:" }, { "code": null, "e": 492, "s": 433, "text": "expression – Any value of any type that will be converted." }, { "code": null, "e": 594, "s": 492, "text": "target_type – Target data type to which the value will be converted. e.g. INT, BIT, SQL_VARIANT, etc." }, { "code": null, "e": 690, "s": 594, "text": "length – Optional parameter that specifies the length of the target_type, default length is 30." }, { "code": null, "e": 773, "s": 690, "text": "Let’s take an example where the CAST() function is used to convert VARCHAR to INT." }, { "code": null, "e": 780, "s": 773, "text": "Query:" }, { "code": null, "e": 818, "s": 780, "text": "SELECT CAST('1234' AS INT) AS Result;" }, { "code": null, "e": 826, "s": 818, "text": "Output:" }, { "code": null, "e": 973, "s": 826, "text": "In SQL Server, the CONVERT() function is used to convert a value of one type to another. Converting anything involves changing its shape or value." }, { "code": null, "e": 982, "s": 973, "text": "Syntax :" }, { "code": null, "e": 1038, "s": 982, "text": "SELECT CONVERT ( target_type ( length ), expression ) " }, { "code": null, "e": 1050, "s": 1038, "text": "Parameters:" }, { "code": null, "e": 1150, "s": 1050, "text": "target_type – Data type to which the expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc." }, { "code": null, "e": 1260, "s": 1150, "text": "length – It provides the length of the target_type. Length is not mandatory. The default length is set to 30." }, { "code": null, "e": 1320, "s": 1260, "text": "expression – expression is anything that will be converted." }, { "code": null, "e": 1400, "s": 1320, "text": "In the below example, the CONVERT() function is used to convert VARCHAR to INT." }, { "code": null, "e": 1407, "s": 1400, "text": "Query:" }, { "code": null, "e": 1445, "s": 1407, "text": "SELECT CONVERT(INT,'5678') AS Result;" }, { "code": null, "e": 1602, "s": 1445, "text": "Now Lets us discuss a more efficient approach to convert the values from one data type to another using SQL Server’s TRY_CAST() and TRY_CONVERT() function:" }, { "code": null, "e": 1887, "s": 1602, "text": "The TRY_CAST() function attempts to cast the input value to a value of the given data type. If the cast is successful, it returns the value in the provided data; else, it returns NULL. However, if you request a conversion that is not valid, the TRY_CAST() method will return an error." }, { "code": null, "e": 1896, "s": 1887, "text": "Syntax :" }, { "code": null, "e": 1950, "s": 1896, "text": "TRY_CAST ( expression AS data_type [ ( length ) ] ) " }, { "code": null, "e": 1967, "s": 1950, "text": "Parameters used:" }, { "code": null, "e": 2044, "s": 1967, "text": "data_type: Valid data type into which the function will cast the expression." }, { "code": null, "e": 2074, "s": 2044, "text": "expression: Value to be cast." }, { "code": null, "e": 2081, "s": 2074, "text": "Query:" }, { "code": null, "e": 2123, "s": 2081, "text": "SELECT TRY_CAST('1234' as INT) as Result;" }, { "code": null, "e": 2130, "s": 2123, "text": "Query:" }, { "code": null, "e": 2175, "s": 2130, "text": "SELECT TRY_CAST('1234abc' as INT) as Result;" }, { "code": null, "e": 2468, "s": 2175, "text": "The TRY_CONVERT() method attempts to convert the value supplied to it to the data type specified. If the cast is successful, it returns the value as the given data; else, it returns NULL. If you request a conversion that is explicitly forbidden, the TRY CONVERT() method will return an error." }, { "code": null, "e": 2477, "s": 2468, "text": "Syntax :" }, { "code": null, "e": 2533, "s": 2477, "text": "TRY_CONVERT ( data_type[(length)], expression [,style])" }, { "code": null, "e": 2550, "s": 2533, "text": "Parameters used:" }, { "code": null, "e": 2628, "s": 2550, "text": "data_type: Valid data type into which the function will cast the expression." }, { "code": null, "e": 2659, "s": 2628, "text": "expression: Value to be cast." }, { "code": null, "e": 2751, "s": 2659, "text": "style: Is a provided integer that specifies how the function will translate the expression." }, { "code": null, "e": 2758, "s": 2751, "text": "Query:" }, { "code": null, "e": 2802, "s": 2758, "text": "SELECT TRY_CONVERT( INT ,'5678') as Result;" }, { "code": null, "e": 2809, "s": 2802, "text": "Query:" }, { "code": null, "e": 2854, "s": 2809, "text": "SELECT TRY_CONVERT( INT ,'56abc') as Result;" }, { "code": null, "e": 2861, "s": 2854, "text": "Picked" }, { "code": null, "e": 2871, "s": 2861, "text": "SQL-Query" }, { "code": null, "e": 2882, "s": 2871, "text": "SQL-Server" }, { "code": null, "e": 2886, "s": 2882, "text": "SQL" }, { "code": null, "e": 2890, "s": 2886, "text": "SQL" } ]
Insert a node in Binary Search Tree Iteratively
18 Aug, 2021 A recursive approach to insert a new node in a BST is already discussed in the post: Binary Search Tree | SET 1. In this post, an iterative approach to insert a node in BST is discussed. Insertion of a Key A new key is always inserted at the leaf node. Start searching a key from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.Example: Input:To the given BST insert 40 Output: Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move to right child else to left child. Input:To the given BST insert 600 Output: Explanation:The new node 600 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move to right child else to left child. Solution: Approach: It is to be noted that new keys are always inserted at the leaf node. Start from root and run a loop until a null pointer is reached. Keep the previous pointer of the current node stored. If the current node is null then create and insert the new node there and make it as one of the children of the parent/previous node depending on its value. If the value of current node is less than the new value then move to the right child of current node else move to the left child. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to demonstrate insert operation// in binary search tree#include <bits/stdc++.h>using namespace std; // BST nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data){ Node* temp = new Node; temp->key = data; temp->left = NULL; temp->right = NULL; return temp;} // A utility function to insert a new// Node with given key in BSTNode* insert(Node* root, int key){ // Create a new Node containing // the new element Node* newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted Node* x = root; // Pointer y maintains the trailing // pointer of x Node* y = NULL; while (x != NULL) { y = x; if (key < x->key) x = x->left; else x = x->right; } // If the root is NULL i.e the tree is empty // The new node is the root node if (y == NULL) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y->key) y->left = newnode; // else assign the new node its right child else y->right = newnode; // Returns the pointer where the // new node is inserted return y;} // A utility function to do inorder// traversal of BSTvoid Inorder(Node* root){ if (root == NULL) return; else { Inorder(root->left); cout << root->key << " "; Inorder(root->right); }} // Driver codeint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // Print inorder traversal of the BST Inorder(root); return 0;} // Java program to demonstrate insert operation// in binary search treeimport java.util.*;class solution{ // BST nodestatic class Node { int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int data){ Node temp = new Node(); temp.key = data; temp.left = null; temp.right = null; return temp;} // A utility function to insert a new// Node with given key in BSTstatic Node insert(Node root, int key){ // Create a new Node containing // the new element Node newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted Node x = root; // Pointer y maintains the trailing // pointer of x Node y = null; while (x != null) { y = x; if (key < x.key) x = x.left; else x = x.right; } // If the root is null i.e the tree is empty // The new node is the root node if (y == null) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y.key) y.left = newnode; // else assign the new node its right child else y.right = newnode; // Returns the pointer where the // new node is inserted return y;} // A utility function to do inorder// traversal of BSTstatic void Inorder(Node root){ if (root == null) return; else { Inorder(root.left); System.out.print( root.key +" "); Inorder(root.right); }} // Driver codepublic static void main(String args[]){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // Print inorder traversal of the BST Inorder(root); }}//contributed by Arnab Kundu """Python3 program to demonstrate insertoperation in binary search tree """ # A Binary Tree Node# Utility function to create a# new tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.key= data self.left = None self.right = self.parent = None # A utility function to insert a new# Node with given key in BSTdef insert(root, key): # Create a new Node containing # the new element newnode = newNode(key) # Pointer to start traversing from root # and traverses downward path to search # where the new node to be inserted x = root # Pointer y maintains the trailing # pointer of x y = None while (x != None): y = x if (key < x.key): x = x.left else: x = x.right # If the root is None i.e the tree is # empty. The new node is the root node if (y == None): y = newnode # If the new key is less then the leaf node key # Assign the new node to be its left child elif (key < y.key): y.left = newnode # else assign the new node its # right child else: y.right = newnode # Returns the pointer where the # new node is inserted return y # A utility function to do inorder# traversal of BSTdef Inorder(root) : if (root == None) : return else: Inorder(root.left) print( root.key, end = " " ) Inorder(root.right) # Driver Codeif __name__ == '__main__': """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) # Pr inorder traversal of the BST Inorder(root) # This code is contributed by# SHUBHAMSINGH10 // C# program to demonstrate insert // operation in binary search treeusing System; class GFG{ // BST node class Node { public int key; public Node left, right; }; // Utility function to create a new node static Node newNode(int data) { Node temp = new Node(); temp.key = data; temp.left = null; temp.right = null; return temp; } // A utility function to insert a new // Node with given key in BST static Node insert(Node root, int key) { // Create a new Node containing // the new element Node newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted Node x = root; // Pointer y maintains the trailing // pointer of x Node y = null; while (x != null) { y = x; if (key < x.key) x = x.left; else x = x.right; } // If the root is null i.e the tree is empty // The new node is the root node if (y == null) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y.key) y.left = newnode; // else assign the new node its right child else y.right = newnode; // Returns the pointer where the // new node is inserted return y; } // A utility function to do inorder // traversal of BST static void Inorder(Node root) { if (root == null) return; else { Inorder(root.left); Console.Write( root.key +" "); Inorder(root.right); } } // Driver code public static void Main(String []args) { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // Print inorder traversal of the BST Inorder(root); }} // This code is contributed 29AjayKumar <script> // javascript program to demonstrate insert // operation in binary search tree// BST nodeclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // Utility function to create a new nodefunction newNode(data){ var temp = new Node(); temp.key = data; temp.left = null; temp.right = null; return temp;} // A utility function to insert a new// Node with given key in BSTfunction insert(root, key){ // Create a new Node containing // the new element var newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted var x = root; // Pointer y maintains the trailing // pointer of x var y = null; while (x != null) { y = x; if (key < x.key) x = x.left; else x = x.right; } // If the root is null i.e the tree is empty // The new node is the root node if (y == null) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y.key) y.left = newnode; // else assign the new node its right child else y.right = newnode; // Returns the pointer where the // new node is inserted return y;} // A utility function to do inorder// traversal of BSTfunction Inorder(root){ if (root == null) return; else { Inorder(root.left); document.write( root.key +" "); Inorder(root.right); }} // Driver code/* Let us create following BST 50 / \ 30 70 / \ / \20 40 60 80 */var root = null;root = insert(root, 50);insert(root, 30);insert(root, 20);insert(root, 40);insert(root, 70);insert(root, 60);insert(root, 80);// Print inorder traversal of the BSTInorder(root); // This code is contributed by itsok.</script> 20 30 40 50 60 70 80 Complexity Analysis: Time Complexity : O(h), where h is height of binary search tree. In worst case the height is equal to number of nodes. Space Complexity: O(1), no extra space is required. andrew1234 29AjayKumar SHUBHAMSINGH10 Ongfa itsok saurabh1990aror gabaa406 Data Structures-Tree Traversals Picked Binary Search Tree Tree Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. set vs unordered_set in C++ STL Flatten BST to sorted list | Increasing order Largest BST in a Binary Tree | Set 2 Find median of BST in O(n) time and O(1) space Floor and Ceil from a BST Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Introduction to Data Structures Introduction to Tree Data Structure
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Aug, 2021" }, { "code": null, "e": 241, "s": 53, "text": "A recursive approach to insert a new node in a BST is already discussed in the post: Binary Search Tree | SET 1. In this post, an iterative approach to insert a node in BST is discussed. " }, { "code": null, "e": 260, "s": 241, "text": "Insertion of a Key" }, { "code": null, "e": 452, "s": 260, "text": "A new key is always inserted at the leaf node. Start searching a key from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.Example: " }, { "code": null, "e": 487, "s": 452, "text": "Input:To the given BST insert 40 " }, { "code": null, "e": 497, "s": 487, "text": "Output: " }, { "code": null, "e": 736, "s": 497, "text": "Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move to right child else to left child. Input:To the given BST insert 600 " }, { "code": null, "e": 746, "s": 736, "text": "Output: " }, { "code": null, "e": 952, "s": 746, "text": "Explanation:The new node 600 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move to right child else to left child. " }, { "code": null, "e": 976, "s": 954, "text": "Solution: Approach: " }, { "code": null, "e": 1046, "s": 976, "text": "It is to be noted that new keys are always inserted at the leaf node." }, { "code": null, "e": 1110, "s": 1046, "text": "Start from root and run a loop until a null pointer is reached." }, { "code": null, "e": 1164, "s": 1110, "text": "Keep the previous pointer of the current node stored." }, { "code": null, "e": 1321, "s": 1164, "text": "If the current node is null then create and insert the new node there and make it as one of the children of the parent/previous node depending on its value." }, { "code": null, "e": 1451, "s": 1321, "text": "If the value of current node is less than the new value then move to the right child of current node else move to the left child." }, { "code": null, "e": 1504, "s": 1451, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1508, "s": 1504, "text": "C++" }, { "code": null, "e": 1513, "s": 1508, "text": "Java" }, { "code": null, "e": 1521, "s": 1513, "text": "Python3" }, { "code": null, "e": 1524, "s": 1521, "text": "C#" }, { "code": null, "e": 1535, "s": 1524, "text": "Javascript" }, { "code": "// C++ program to demonstrate insert operation// in binary search tree#include <bits/stdc++.h>using namespace std; // BST nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int data){ Node* temp = new Node; temp->key = data; temp->left = NULL; temp->right = NULL; return temp;} // A utility function to insert a new// Node with given key in BSTNode* insert(Node* root, int key){ // Create a new Node containing // the new element Node* newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted Node* x = root; // Pointer y maintains the trailing // pointer of x Node* y = NULL; while (x != NULL) { y = x; if (key < x->key) x = x->left; else x = x->right; } // If the root is NULL i.e the tree is empty // The new node is the root node if (y == NULL) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y->key) y->left = newnode; // else assign the new node its right child else y->right = newnode; // Returns the pointer where the // new node is inserted return y;} // A utility function to do inorder// traversal of BSTvoid Inorder(Node* root){ if (root == NULL) return; else { Inorder(root->left); cout << root->key << \" \"; Inorder(root->right); }} // Driver codeint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // Print inorder traversal of the BST Inorder(root); return 0;}", "e": 3497, "s": 1535, "text": null }, { "code": "// Java program to demonstrate insert operation// in binary search treeimport java.util.*;class solution{ // BST nodestatic class Node { int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int data){ Node temp = new Node(); temp.key = data; temp.left = null; temp.right = null; return temp;} // A utility function to insert a new// Node with given key in BSTstatic Node insert(Node root, int key){ // Create a new Node containing // the new element Node newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted Node x = root; // Pointer y maintains the trailing // pointer of x Node y = null; while (x != null) { y = x; if (key < x.key) x = x.left; else x = x.right; } // If the root is null i.e the tree is empty // The new node is the root node if (y == null) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y.key) y.left = newnode; // else assign the new node its right child else y.right = newnode; // Returns the pointer where the // new node is inserted return y;} // A utility function to do inorder// traversal of BSTstatic void Inorder(Node root){ if (root == null) return; else { Inorder(root.left); System.out.print( root.key +\" \"); Inorder(root.right); }} // Driver codepublic static void main(String args[]){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // Print inorder traversal of the BST Inorder(root); }}//contributed by Arnab Kundu", "e": 5544, "s": 3497, "text": null }, { "code": "\"\"\"Python3 program to demonstrate insertoperation in binary search tree \"\"\" # A Binary Tree Node# Utility function to create a# new tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.key= data self.left = None self.right = self.parent = None # A utility function to insert a new# Node with given key in BSTdef insert(root, key): # Create a new Node containing # the new element newnode = newNode(key) # Pointer to start traversing from root # and traverses downward path to search # where the new node to be inserted x = root # Pointer y maintains the trailing # pointer of x y = None while (x != None): y = x if (key < x.key): x = x.left else: x = x.right # If the root is None i.e the tree is # empty. The new node is the root node if (y == None): y = newnode # If the new key is less then the leaf node key # Assign the new node to be its left child elif (key < y.key): y.left = newnode # else assign the new node its # right child else: y.right = newnode # Returns the pointer where the # new node is inserted return y # A utility function to do inorder# traversal of BSTdef Inorder(root) : if (root == None) : return else: Inorder(root.left) print( root.key, end = \" \" ) Inorder(root.right) # Driver Codeif __name__ == '__main__': \"\"\" Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 \"\"\" root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) # Pr inorder traversal of the BST Inorder(root) # This code is contributed by# SHUBHAMSINGH10", "e": 7426, "s": 5544, "text": null }, { "code": "// C# program to demonstrate insert // operation in binary search treeusing System; class GFG{ // BST node class Node { public int key; public Node left, right; }; // Utility function to create a new node static Node newNode(int data) { Node temp = new Node(); temp.key = data; temp.left = null; temp.right = null; return temp; } // A utility function to insert a new // Node with given key in BST static Node insert(Node root, int key) { // Create a new Node containing // the new element Node newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted Node x = root; // Pointer y maintains the trailing // pointer of x Node y = null; while (x != null) { y = x; if (key < x.key) x = x.left; else x = x.right; } // If the root is null i.e the tree is empty // The new node is the root node if (y == null) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y.key) y.left = newnode; // else assign the new node its right child else y.right = newnode; // Returns the pointer where the // new node is inserted return y; } // A utility function to do inorder // traversal of BST static void Inorder(Node root) { if (root == null) return; else { Inorder(root.left); Console.Write( root.key +\" \"); Inorder(root.right); } } // Driver code public static void Main(String []args) { /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); // Print inorder traversal of the BST Inorder(root); }} // This code is contributed 29AjayKumar", "e": 9765, "s": 7426, "text": null }, { "code": "<script> // javascript program to demonstrate insert // operation in binary search tree// BST nodeclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // Utility function to create a new nodefunction newNode(data){ var temp = new Node(); temp.key = data; temp.left = null; temp.right = null; return temp;} // A utility function to insert a new// Node with given key in BSTfunction insert(root, key){ // Create a new Node containing // the new element var newnode = newNode(key); // Pointer to start traversing from root and // traverses downward path to search // where the new node to be inserted var x = root; // Pointer y maintains the trailing // pointer of x var y = null; while (x != null) { y = x; if (key < x.key) x = x.left; else x = x.right; } // If the root is null i.e the tree is empty // The new node is the root node if (y == null) y = newnode; // If the new key is less then the leaf node key // Assign the new node to be its left child else if (key < y.key) y.left = newnode; // else assign the new node its right child else y.right = newnode; // Returns the pointer where the // new node is inserted return y;} // A utility function to do inorder// traversal of BSTfunction Inorder(root){ if (root == null) return; else { Inorder(root.left); document.write( root.key +\" \"); Inorder(root.right); }} // Driver code/* Let us create following BST 50 / \\ 30 70 / \\ / \\20 40 60 80 */var root = null;root = insert(root, 50);insert(root, 30);insert(root, 20);insert(root, 40);insert(root, 70);insert(root, 60);insert(root, 80);// Print inorder traversal of the BSTInorder(root); // This code is contributed by itsok.</script>", "e": 11712, "s": 9765, "text": null }, { "code": null, "e": 11733, "s": 11712, "text": "20 30 40 50 60 70 80" }, { "code": null, "e": 11758, "s": 11735, "text": "Complexity Analysis: " }, { "code": null, "e": 11877, "s": 11758, "text": "Time Complexity : O(h), where h is height of binary search tree. In worst case the height is equal to number of nodes." }, { "code": null, "e": 11931, "s": 11879, "text": "Space Complexity: O(1), no extra space is required." }, { "code": null, "e": 11944, "s": 11933, "text": "andrew1234" }, { "code": null, "e": 11956, "s": 11944, "text": "29AjayKumar" }, { "code": null, "e": 11971, "s": 11956, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 11977, "s": 11971, "text": "Ongfa" }, { "code": null, "e": 11983, "s": 11977, "text": "itsok" }, { "code": null, "e": 11999, "s": 11983, "text": "saurabh1990aror" }, { "code": null, "e": 12008, "s": 11999, "text": "gabaa406" }, { "code": null, "e": 12040, "s": 12008, "text": "Data Structures-Tree Traversals" }, { "code": null, "e": 12047, "s": 12040, "text": "Picked" }, { "code": null, "e": 12066, "s": 12047, "text": "Binary Search Tree" }, { "code": null, "e": 12071, "s": 12066, "text": "Tree" }, { "code": null, "e": 12090, "s": 12071, "text": "Binary Search Tree" }, { "code": null, "e": 12095, "s": 12090, "text": "Tree" }, { "code": null, "e": 12193, "s": 12095, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12225, "s": 12193, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 12271, "s": 12225, "text": "Flatten BST to sorted list | Increasing order" }, { "code": null, "e": 12308, "s": 12271, "text": "Largest BST in a Binary Tree | Set 2" }, { "code": null, "e": 12355, "s": 12308, "text": "Find median of BST in O(n) time and O(1) space" }, { "code": null, "e": 12381, "s": 12355, "text": "Floor and Ceil from a BST" }, { "code": null, "e": 12431, "s": 12381, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 12466, "s": 12431, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 12500, "s": 12466, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 12532, "s": 12500, "text": "Introduction to Data Structures" } ]
Java Swing – JPanel With Examples
10 Nov, 2021 JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar. JPanel(): creates a new panel with a flow layoutJPanel(LayoutManager l): creates a new JPanel with specified layoutManagerJPanel(boolean isDoubleBuffered): creates a new JPanel with a specified buffering strategyJPanel(LayoutManager l, boolean isDoubleBuffered): creates a new JPanel with specified layoutManager and a specified buffering strategy JPanel(): creates a new panel with a flow layout JPanel(LayoutManager l): creates a new JPanel with specified layoutManager JPanel(boolean isDoubleBuffered): creates a new JPanel with a specified buffering strategy JPanel(LayoutManager l, boolean isDoubleBuffered): creates a new JPanel with specified layoutManager and a specified buffering strategy add(Component c): Adds a component to a specified containersetLayout(LayoutManager l): sets the layout of the container to the specified layout managerupdateUI(): resets the UI property with a value from the current look and feel.setUI(PanelUI ui): sets the look and feel of an object that renders this component.getUI(): returns the look and feel object that renders this component.paramString(): returns a string representation of this JPanel.getUIClassID(): returns the name of the Look and feel class that renders this component.getAccessibleContext(): gets the AccessibleContext associated with this JPanel. add(Component c): Adds a component to a specified container setLayout(LayoutManager l): sets the layout of the container to the specified layout manager updateUI(): resets the UI property with a value from the current look and feel. setUI(PanelUI ui): sets the look and feel of an object that renders this component. getUI(): returns the look and feel object that renders this component. paramString(): returns a string representation of this JPanel. getUIClassID(): returns the name of the Look and feel class that renders this component. getAccessibleContext(): gets the AccessibleContext associated with this JPanel. Let us take a sample program in order to illustrate the use of JPanel class by appending sequential execution snapshots of outputs justifying the below program sets as follows: Example: Java // Java Program to Create a Simple JPanel// and Adding Components to it // Importing required classesimport java.awt.*;import java.awt.event.*;import javax.swing.*; // Class 1// Helper class extending JFrame classclass solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2; // Label to display text static JLabel l; // Main class public static void main(String[] args) { // Creating a new frame to store text field and // button f = new JFrame("panel"); // Creating a label to display text l = new JLabel("panel label"); // Creating a new buttons b = new JButton("button1"); b1 = new JButton("button2"); b2 = new JButton("button3"); // Creating a panel to add buttons JPanel p = new JPanel(); // Adding buttons and textfield to panel // using add() method p.add(b); p.add(b1); p.add(b2); p.add(l); // setbackground of panel p.setBackground(Color.red); // Adding panel to frame f.add(p); // Setting the size of frame f.setSize(300, 300); f.show(); }} Output: Example 2: Java // Java Program to Create a JPanel with a Border Layout// and Adding Components to It // Importing required classesimport java.awt.*;import java.awt.event.*;import javax.swing.*; // Main class// Extending JFrame classclass solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // Label to display text static JLabel l; // Main driver method public static void main(String[] args) { // Creating a new frame to store text field and // button f = new JFrame("panel"); // Creating a label to display text l = new JLabel("panel label"); // Creating a new buttons b = new JButton("button1"); b1 = new JButton("button2"); b2 = new JButton("button3"); b3 = new JButton("button4"); // Creating a panel to add buttons // and a specific layout JPanel p = new JPanel(new BorderLayout()); // Adding buttons and textfield to panel // using add() method p.add(b, BorderLayout.NORTH); p.add(b1, BorderLayout.SOUTH); p.add(b2, BorderLayout.EAST); p.add(b3, BorderLayout.WEST); p.add(l, BorderLayout.CENTER); // setbackground of panel p.setBackground(Color.red); // Adding panel to frame f.add(p); // Setting the size of frame f.setSize(300, 300); f.show(); }} Output: Example 3: Java // Java Program to Create a JPanel with a Box layout// and Adding components to it // Importing required classesimport java.awt.*;import java.awt.event.*;import javax.swing.*; // Main class// Extending JFrame classclass solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // Label to display text static JLabel l; // Main drive method public static void main(String[] args) { // Creating a new frame to store text field and // button f = new JFrame("panel"); // Creating a label to display text l = new JLabel("panel label"); // Creating a new buttons b = new JButton("button1"); b1 = new JButton("button2"); b2 = new JButton("button3"); b3 = new JButton("button4"); // Creating a panel to add buttons and // textfield and a layout JPanel p = new JPanel(); // Setting box layout p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); // Adding buttons and textfield to panel p.add(b); p.add(b1); p.add(b2); p.add(b3); p.add(l); // Setting background of panel p.setBackground(Color.red); // Adding panel to frame f.add(p); // Setting the size of frame f.setSize(300, 300); f.show(); }} Output: Henceforth, we are successfully able to generate buttons in our panel. Note: In the previous Program, border layout and Box Layout are used. Different other layouts can be used to organize the components in a definite pattern, such as card layout, grid layout, etc. nidhi_biet Akanksha_Rai sweetyty solankimayank java-swing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Nov, 2021" }, { "code": null, "e": 323, "s": 52, "text": "JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar." }, { "code": null, "e": 671, "s": 323, "text": "JPanel(): creates a new panel with a flow layoutJPanel(LayoutManager l): creates a new JPanel with specified layoutManagerJPanel(boolean isDoubleBuffered): creates a new JPanel with a specified buffering strategyJPanel(LayoutManager l, boolean isDoubleBuffered): creates a new JPanel with specified layoutManager and a specified buffering strategy" }, { "code": null, "e": 720, "s": 671, "text": "JPanel(): creates a new panel with a flow layout" }, { "code": null, "e": 795, "s": 720, "text": "JPanel(LayoutManager l): creates a new JPanel with specified layoutManager" }, { "code": null, "e": 886, "s": 795, "text": "JPanel(boolean isDoubleBuffered): creates a new JPanel with a specified buffering strategy" }, { "code": null, "e": 1022, "s": 886, "text": "JPanel(LayoutManager l, boolean isDoubleBuffered): creates a new JPanel with specified layoutManager and a specified buffering strategy" }, { "code": null, "e": 1635, "s": 1022, "text": "add(Component c): Adds a component to a specified containersetLayout(LayoutManager l): sets the layout of the container to the specified layout managerupdateUI(): resets the UI property with a value from the current look and feel.setUI(PanelUI ui): sets the look and feel of an object that renders this component.getUI(): returns the look and feel object that renders this component.paramString(): returns a string representation of this JPanel.getUIClassID(): returns the name of the Look and feel class that renders this component.getAccessibleContext(): gets the AccessibleContext associated with this JPanel." }, { "code": null, "e": 1695, "s": 1635, "text": "add(Component c): Adds a component to a specified container" }, { "code": null, "e": 1788, "s": 1695, "text": "setLayout(LayoutManager l): sets the layout of the container to the specified layout manager" }, { "code": null, "e": 1868, "s": 1788, "text": "updateUI(): resets the UI property with a value from the current look and feel." }, { "code": null, "e": 1952, "s": 1868, "text": "setUI(PanelUI ui): sets the look and feel of an object that renders this component." }, { "code": null, "e": 2023, "s": 1952, "text": "getUI(): returns the look and feel object that renders this component." }, { "code": null, "e": 2086, "s": 2023, "text": "paramString(): returns a string representation of this JPanel." }, { "code": null, "e": 2175, "s": 2086, "text": "getUIClassID(): returns the name of the Look and feel class that renders this component." }, { "code": null, "e": 2255, "s": 2175, "text": "getAccessibleContext(): gets the AccessibleContext associated with this JPanel." }, { "code": null, "e": 2432, "s": 2255, "text": "Let us take a sample program in order to illustrate the use of JPanel class by appending sequential execution snapshots of outputs justifying the below program sets as follows:" }, { "code": null, "e": 2441, "s": 2432, "text": "Example:" }, { "code": null, "e": 2446, "s": 2441, "text": "Java" }, { "code": "// Java Program to Create a Simple JPanel// and Adding Components to it // Importing required classesimport java.awt.*;import java.awt.event.*;import javax.swing.*; // Class 1// Helper class extending JFrame classclass solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2; // Label to display text static JLabel l; // Main class public static void main(String[] args) { // Creating a new frame to store text field and // button f = new JFrame(\"panel\"); // Creating a label to display text l = new JLabel(\"panel label\"); // Creating a new buttons b = new JButton(\"button1\"); b1 = new JButton(\"button2\"); b2 = new JButton(\"button3\"); // Creating a panel to add buttons JPanel p = new JPanel(); // Adding buttons and textfield to panel // using add() method p.add(b); p.add(b1); p.add(b2); p.add(l); // setbackground of panel p.setBackground(Color.red); // Adding panel to frame f.add(p); // Setting the size of frame f.setSize(300, 300); f.show(); }}", "e": 3655, "s": 2446, "text": null }, { "code": null, "e": 3664, "s": 3655, "text": "Output: " }, { "code": null, "e": 3675, "s": 3664, "text": "Example 2:" }, { "code": null, "e": 3680, "s": 3675, "text": "Java" }, { "code": "// Java Program to Create a JPanel with a Border Layout// and Adding Components to It // Importing required classesimport java.awt.*;import java.awt.event.*;import javax.swing.*; // Main class// Extending JFrame classclass solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // Label to display text static JLabel l; // Main driver method public static void main(String[] args) { // Creating a new frame to store text field and // button f = new JFrame(\"panel\"); // Creating a label to display text l = new JLabel(\"panel label\"); // Creating a new buttons b = new JButton(\"button1\"); b1 = new JButton(\"button2\"); b2 = new JButton(\"button3\"); b3 = new JButton(\"button4\"); // Creating a panel to add buttons // and a specific layout JPanel p = new JPanel(new BorderLayout()); // Adding buttons and textfield to panel // using add() method p.add(b, BorderLayout.NORTH); p.add(b1, BorderLayout.SOUTH); p.add(b2, BorderLayout.EAST); p.add(b3, BorderLayout.WEST); p.add(l, BorderLayout.CENTER); // setbackground of panel p.setBackground(Color.red); // Adding panel to frame f.add(p); // Setting the size of frame f.setSize(300, 300); f.show(); }}", "e": 5108, "s": 3680, "text": null }, { "code": null, "e": 5116, "s": 5108, "text": "Output:" }, { "code": null, "e": 5128, "s": 5116, "text": " Example 3:" }, { "code": null, "e": 5133, "s": 5128, "text": "Java" }, { "code": "// Java Program to Create a JPanel with a Box layout// and Adding components to it // Importing required classesimport java.awt.*;import java.awt.event.*;import javax.swing.*; // Main class// Extending JFrame classclass solution extends JFrame { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // Label to display text static JLabel l; // Main drive method public static void main(String[] args) { // Creating a new frame to store text field and // button f = new JFrame(\"panel\"); // Creating a label to display text l = new JLabel(\"panel label\"); // Creating a new buttons b = new JButton(\"button1\"); b1 = new JButton(\"button2\"); b2 = new JButton(\"button3\"); b3 = new JButton(\"button4\"); // Creating a panel to add buttons and // textfield and a layout JPanel p = new JPanel(); // Setting box layout p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); // Adding buttons and textfield to panel p.add(b); p.add(b1); p.add(b2); p.add(b3); p.add(l); // Setting background of panel p.setBackground(Color.red); // Adding panel to frame f.add(p); // Setting the size of frame f.setSize(300, 300); f.show(); }}", "e": 6508, "s": 5133, "text": null }, { "code": null, "e": 6516, "s": 6508, "text": "Output:" }, { "code": null, "e": 6588, "s": 6516, "text": "Henceforth, we are successfully able to generate buttons in our panel. " }, { "code": null, "e": 6784, "s": 6588, "text": "Note: In the previous Program, border layout and Box Layout are used. Different other layouts can be used to organize the components in a definite pattern, such as card layout, grid layout, etc. " }, { "code": null, "e": 6795, "s": 6784, "text": "nidhi_biet" }, { "code": null, "e": 6808, "s": 6795, "text": "Akanksha_Rai" }, { "code": null, "e": 6817, "s": 6808, "text": "sweetyty" }, { "code": null, "e": 6831, "s": 6817, "text": "solankimayank" }, { "code": null, "e": 6842, "s": 6831, "text": "java-swing" }, { "code": null, "e": 6847, "s": 6842, "text": "Java" }, { "code": null, "e": 6852, "s": 6847, "text": "Java" }, { "code": null, "e": 6950, "s": 6852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7001, "s": 6950, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7032, "s": 7001, "text": "How to iterate any Map in Java" }, { "code": null, "e": 7051, "s": 7032, "text": "Interfaces in Java" }, { "code": null, "e": 7081, "s": 7051, "text": "HashMap in Java with Examples" }, { "code": null, "e": 7099, "s": 7081, "text": "ArrayList in Java" }, { "code": null, "e": 7114, "s": 7099, "text": "Stream In Java" }, { "code": null, "e": 7134, "s": 7114, "text": "Collections in Java" }, { "code": null, "e": 7166, "s": 7134, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7190, "s": 7166, "text": "Singleton Class in Java" } ]
DELETE method- Python requests
26 Feb, 2020 Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make DELETE request to a specified URL using requests.delete() method. Before checking out the DELETE method, let’s figure out what a Http DELETE request is – DELETE is a request method supported by HTTP used by the World Wide Web. The DELETE method deletes the specified resource. As with a PUT request, you need to specify a particular resource for this operation. A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.An example URI looks like for delete operation http://www.example.com/articles/12345 Python’s requests module provides in-built method called delete() for making a DELETE request to a specified URI. Syntax – requests.delete(url, params={key: value}, args) Example – Let’s try making a request to httpbin’s APIs for example purposes. import requests # Making a DELETE requestr = requests.delete('https://httpbin.org / delete', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.json()) save this file as request.py and through terminal run, python request.py Output – The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location. Python-requests 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 Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2020" }, { "code": null, "e": 332, "s": 28, "text": "Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make DELETE request to a specified URL using requests.delete() method. Before checking out the DELETE method, let’s figure out what a Http DELETE request is –" }, { "code": null, "e": 836, "s": 332, "text": "DELETE is a request method supported by HTTP used by the World Wide Web. The DELETE method deletes the specified resource. As with a PUT request, you need to specify a particular resource for this operation. A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.An example URI looks like for delete operation" }, { "code": null, "e": 874, "s": 836, "text": "http://www.example.com/articles/12345" }, { "code": null, "e": 988, "s": 874, "text": "Python’s requests module provides in-built method called delete() for making a DELETE request to a specified URI." }, { "code": null, "e": 997, "s": 988, "text": "Syntax –" }, { "code": null, "e": 1046, "s": 997, "text": "requests.delete(url, params={key: value}, args)\n" }, { "code": null, "e": 1056, "s": 1046, "text": "Example –" }, { "code": null, "e": 1123, "s": 1056, "text": "Let’s try making a request to httpbin’s APIs for example purposes." }, { "code": "import requests # Making a DELETE requestr = requests.delete('https://httpbin.org / delete', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.json())", "e": 1354, "s": 1123, "text": null }, { "code": null, "e": 1409, "s": 1354, "text": "save this file as request.py and through terminal run," }, { "code": null, "e": 1427, "s": 1409, "text": "python request.py" }, { "code": null, "e": 1436, "s": 1427, "text": "Output –" }, { "code": null, "e": 1981, "s": 1436, "text": "The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location." }, { "code": null, "e": 1997, "s": 1981, "text": "Python-requests" }, { "code": null, "e": 2004, "s": 1997, "text": "Python" }, { "code": null, "e": 2102, "s": 2004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2134, "s": 2102, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2161, "s": 2134, "text": "Python Classes and Objects" }, { "code": null, "e": 2192, "s": 2161, "text": "Python | os.path.join() method" }, { "code": null, "e": 2215, "s": 2192, "text": "Introduction To PYTHON" }, { "code": null, "e": 2236, "s": 2215, "text": "Python OOPs Concepts" }, { "code": null, "e": 2292, "s": 2236, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2334, "s": 2292, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2376, "s": 2334, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2415, "s": 2376, "text": "Python | Get unique values from a list" } ]
Number of triangles possible with given lengths of sticks which are powers of 2
08 Jun, 2022 Given an array of N integers where arr[i] denotes the number of sticks of length 2i. The task is to find the number of triangles possible with given lengths having area ≥ 0. Note: Every stick can only be used once. Examples: Input: a[] = {1, 2, 2, 2, 2} Output: 3 All possible triangles are: (20, 24, 24), (21, 23, 23), (21, 22, 22). Input: a[] = {3, 3, 3} Output: 3 Approach: The main observation is that the triangles with area ≥ 0 can only be formed if there are three same lengths of sticks or one different and two similar lengths of sticks. Hence greedily iterate from the back and count the number of pairs of same length sticks available which is arr[i] / 2. But if there is a stick remaining, then a pair and a stick is used to form a triangle. In the end, the total number of sticks left is calculated which is 2 * pairs and the number of triangles that can be formed with these remaining sticks will be (2 * pairs) / 3. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the// number of positive area trianglesint countTriangles(int a[], int n){ // To store the count of // total triangles int cnt = 0; // To store the count of pairs of sticks // with equal lengths int pairs = 0; // Back-traverse and count // the number of triangles for (int i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += (2 * pairs) / 3; return cnt;} // Driver codeint main(){ int a[] = { 1, 2, 2, 2, 2 }; int n = sizeof(a) / sizeof(a[0]); cout << countTriangles(a, n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the// number of positive area trianglesstatic int countTriangles(int a[], int n){ // To store the count of // total triangles int cnt = 0; // To store the count of pairs of sticks // with equal lengths int pairs = 0; // Back-traverse and count // the number of triangles for (int i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += (2 * pairs) / 3; return cnt;} // Driver codepublic static void main(String[] args){ int a[] = { 1, 2, 2, 2, 2 }; int n = a.length; System.out.println(countTriangles(a, n));}} // This code is contributed by Code_Mech. # Python3 implementation of the approach # Function to return the# number of positive area trianglesdef countTriangles(a, n): # To store the count of # total triangles cnt = 0 # To store the count of pairs of sticks # with equal lengths pairs = 0 # Back-traverse and count # the number of triangles for i in range(n - 1, -1, -1): # Count the number of pairs pairs += a[i] // 2 # If we have one remaining stick # and we have a pair if (a[i] % 2 == 1 and pairs > 0): # Count 1 triangle cnt += 1 # Reduce one pair pairs -= 1 # Count the remaining triangles # that can be formed cnt += (2 * pairs) // 3 return cnt # Driver codea = [1, 2, 2, 2, 2]n = len(a)print(countTriangles(a, n)) # This code is contributed by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to return the // number of positive area triangles static int countTriangles(int []a, int n) { // To store the count of // total triangles int cnt = 0; // To store the count of pairs of sticks // with equal lengths int pairs = 0; // Back-traverse and count // the number of triangles for (int i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += (2 * pairs) / 3; return cnt; } // Driver code public static void Main() { int []a = { 1, 2, 2, 2, 2 }; int n = a.Length; Console.WriteLine(countTriangles(a, n)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to return the// number of positive area trianglesFunction countTriangles($a, $n){ // To store the count of // total triangles $cnt = 0; // To store the count of pairs of sticks // with equal lengths $pairs = 0; // Back-traverse and count // the number of triangles for ($i = $n - 1; $i >= 0; $i--) { // Count the number of pairs $pairs += $a[$i] / 2; // If we have one remaining stick // and we have a pair if ($a[$i] % 2 == 1 && $pairs > 0) { // Count 1 triangle $cnt += 1; // Reduce one pair $pairs -= 1; } } // Count the remaining triangles // that can be formed $cnt += (int)((2 * $pairs) / 3); return $cnt;} // Driver code$a = array(1, 2, 2, 2, 2 );$n = sizeof($a);echo(countTriangles($a, $n)); // This code is contributed by Code_Mech.?> <script> // Javascript implementation of the approach // Function to return the number// of positive area trianglesfunction countTriangles(a , n){ // To store the count of // total triangles var cnt = 0; // To store the count of pairs // of sticks with equal lengths var pairs = 0; // Back-traverse and count // the number of triangles for(let i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += parseInt((2 * pairs) / 3); return cnt;} // Driver codevar a = [ 1, 2, 2, 2, 2 ];var n = a.length; document.write(countTriangles(a, n)); // This code is contributed by aashish1995 </script> 3 Time Complexity: O(n)Auxiliary Space: O(1) mohit kumar 29 Code_Mech ankthon aashish1995 rishavmahato348 triangle Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find the Number of Permutations that satisfy the given condition in an array Probability of getting K heads in N coin tosses Number of handshakes such that a person shakes hands only once Ways to sum to N using Natural Numbers up to K with repetitions allowed Largest permutation after at most k swaps Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 243, "s": 28, "text": "Given an array of N integers where arr[i] denotes the number of sticks of length 2i. The task is to find the number of triangles possible with given lengths having area ≥ 0. Note: Every stick can only be used once." }, { "code": null, "e": 255, "s": 243, "text": "Examples: " }, { "code": null, "e": 364, "s": 255, "text": "Input: a[] = {1, 2, 2, 2, 2} Output: 3 All possible triangles are: (20, 24, 24), (21, 23, 23), (21, 22, 22)." }, { "code": null, "e": 398, "s": 364, "text": "Input: a[] = {3, 3, 3} Output: 3 " }, { "code": null, "e": 963, "s": 398, "text": "Approach: The main observation is that the triangles with area ≥ 0 can only be formed if there are three same lengths of sticks or one different and two similar lengths of sticks. Hence greedily iterate from the back and count the number of pairs of same length sticks available which is arr[i] / 2. But if there is a stick remaining, then a pair and a stick is used to form a triangle. In the end, the total number of sticks left is calculated which is 2 * pairs and the number of triangles that can be formed with these remaining sticks will be (2 * pairs) / 3. " }, { "code": null, "e": 1016, "s": 963, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1020, "s": 1016, "text": "C++" }, { "code": null, "e": 1025, "s": 1020, "text": "Java" }, { "code": null, "e": 1033, "s": 1025, "text": "Python3" }, { "code": null, "e": 1036, "s": 1033, "text": "C#" }, { "code": null, "e": 1040, "s": 1036, "text": "PHP" }, { "code": null, "e": 1051, "s": 1040, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the// number of positive area trianglesint countTriangles(int a[], int n){ // To store the count of // total triangles int cnt = 0; // To store the count of pairs of sticks // with equal lengths int pairs = 0; // Back-traverse and count // the number of triangles for (int i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += (2 * pairs) / 3; return cnt;} // Driver codeint main(){ int a[] = { 1, 2, 2, 2, 2 }; int n = sizeof(a) / sizeof(a[0]); cout << countTriangles(a, n); return 0;}", "e": 2028, "s": 1051, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the// number of positive area trianglesstatic int countTriangles(int a[], int n){ // To store the count of // total triangles int cnt = 0; // To store the count of pairs of sticks // with equal lengths int pairs = 0; // Back-traverse and count // the number of triangles for (int i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += (2 * pairs) / 3; return cnt;} // Driver codepublic static void main(String[] args){ int a[] = { 1, 2, 2, 2, 2 }; int n = a.length; System.out.println(countTriangles(a, n));}} // This code is contributed by Code_Mech.", "e": 3046, "s": 2028, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the# number of positive area trianglesdef countTriangles(a, n): # To store the count of # total triangles cnt = 0 # To store the count of pairs of sticks # with equal lengths pairs = 0 # Back-traverse and count # the number of triangles for i in range(n - 1, -1, -1): # Count the number of pairs pairs += a[i] // 2 # If we have one remaining stick # and we have a pair if (a[i] % 2 == 1 and pairs > 0): # Count 1 triangle cnt += 1 # Reduce one pair pairs -= 1 # Count the remaining triangles # that can be formed cnt += (2 * pairs) // 3 return cnt # Driver codea = [1, 2, 2, 2, 2]n = len(a)print(countTriangles(a, n)) # This code is contributed by mohit kumar", "e": 3902, "s": 3046, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the // number of positive area triangles static int countTriangles(int []a, int n) { // To store the count of // total triangles int cnt = 0; // To store the count of pairs of sticks // with equal lengths int pairs = 0; // Back-traverse and count // the number of triangles for (int i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += (2 * pairs) / 3; return cnt; } // Driver code public static void Main() { int []a = { 1, 2, 2, 2, 2 }; int n = a.Length; Console.WriteLine(countTriangles(a, n)); }} // This code is contributed by Ryuga", "e": 5105, "s": 3902, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the// number of positive area trianglesFunction countTriangles($a, $n){ // To store the count of // total triangles $cnt = 0; // To store the count of pairs of sticks // with equal lengths $pairs = 0; // Back-traverse and count // the number of triangles for ($i = $n - 1; $i >= 0; $i--) { // Count the number of pairs $pairs += $a[$i] / 2; // If we have one remaining stick // and we have a pair if ($a[$i] % 2 == 1 && $pairs > 0) { // Count 1 triangle $cnt += 1; // Reduce one pair $pairs -= 1; } } // Count the remaining triangles // that can be formed $cnt += (int)((2 * $pairs) / 3); return $cnt;} // Driver code$a = array(1, 2, 2, 2, 2 );$n = sizeof($a);echo(countTriangles($a, $n)); // This code is contributed by Code_Mech.?>", "e": 6050, "s": 5105, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the number// of positive area trianglesfunction countTriangles(a , n){ // To store the count of // total triangles var cnt = 0; // To store the count of pairs // of sticks with equal lengths var pairs = 0; // Back-traverse and count // the number of triangles for(let i = n - 1; i >= 0; i--) { // Count the number of pairs pairs += a[i] / 2; // If we have one remaining stick // and we have a pair if (a[i] % 2 == 1 && pairs > 0) { // Count 1 triangle cnt += 1; // Reduce one pair pairs -= 1; } } // Count the remaining triangles // that can be formed cnt += parseInt((2 * pairs) / 3); return cnt;} // Driver codevar a = [ 1, 2, 2, 2, 2 ];var n = a.length; document.write(countTriangles(a, n)); // This code is contributed by aashish1995 </script>", "e": 7076, "s": 6050, "text": null }, { "code": null, "e": 7078, "s": 7076, "text": "3" }, { "code": null, "e": 7123, "s": 7080, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 7138, "s": 7123, "text": "mohit kumar 29" }, { "code": null, "e": 7148, "s": 7138, "text": "Code_Mech" }, { "code": null, "e": 7156, "s": 7148, "text": "ankthon" }, { "code": null, "e": 7168, "s": 7156, "text": "aashish1995" }, { "code": null, "e": 7184, "s": 7168, "text": "rishavmahato348" }, { "code": null, "e": 7193, "s": 7184, "text": "triangle" }, { "code": null, "e": 7207, "s": 7193, "text": "Combinatorial" }, { "code": null, "e": 7220, "s": 7207, "text": "Mathematical" }, { "code": null, "e": 7233, "s": 7220, "text": "Mathematical" }, { "code": null, "e": 7247, "s": 7233, "text": "Combinatorial" }, { "code": null, "e": 7345, "s": 7247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7422, "s": 7345, "text": "Find the Number of Permutations that satisfy the given condition in an array" }, { "code": null, "e": 7470, "s": 7422, "text": "Probability of getting K heads in N coin tosses" }, { "code": null, "e": 7533, "s": 7470, "text": "Number of handshakes such that a person shakes hands only once" }, { "code": null, "e": 7605, "s": 7533, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 7647, "s": 7605, "text": "Largest permutation after at most k swaps" }, { "code": null, "e": 7677, "s": 7647, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7720, "s": 7677, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7735, "s": 7720, "text": "C++ Data Types" }, { "code": null, "e": 7759, "s": 7735, "text": "Merge two sorted arrays" } ]
Maximum area rectangle by picking four sides from array
16 Mar, 2022 Given an array of n positive integers that represent lengths. Find out the maximum possible area whose four sides are picked from given array. Note that a rectangle can only be formed if there are two pairs of equal values in given array. Examples: Input : arr[] = {2, 1, 2, 5, 4, 4} Output : 8 Explanation : Dimension will be 4 * 2 Input : arr[] = {2, 1, 3, 5, 4, 4} Output : 0 Explanation : No rectangle possible Method 1 (Sorting) The task basically reduces to finding two pairs of equal values in array. If there are more than two pairs, then pick the two pairs with maximum values. A simple solution is to do following. 1) Sort the given array. 2) Traverse array from largest to smallest value and return two pairs with maximum values. C++ Java Python3 C# PHP Javascript // CPP program for finding maximum area possible// of a rectangle#include <bits/stdc++.h>using namespace std; // function for finding max areaint findArea(int arr[], int n){ // sort array in non-increasing order sort(arr, arr + n, greater<int>()); // Initialize two sides of rectangle int dimension[2] = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]);} // driver functionint main(){ int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findArea(arr, n); return 0;} // Java program for finding maximum area// possible of a rectangleimport java.util.Arrays;import java.util.Collections; public class GFG{ // function for finding max area static int findArea(Integer arr[], int n) { // sort array in non-increasing order Arrays.sort(arr, Collections.reverseOrder()); // Initialize two sides of rectangle int[] dimension = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]); } // driver function public static void main(String args[]) { Integer arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = arr.length; System.out.println(findArea(arr, n)); }}// This code is contributed by Sumit Ghosh # Python3 program for finding# maximum area possible of# a rectangle # function for finding# max areadef findArea(arr, n): # sort array in # non-increasing order arr.sort(reverse = True) # Initialize two # sides of rectangle dimension = [0, 0] # traverse through array i = 0 j = 0 while(i < n - 1 and j < 2): # if any element occurs twice # store that as dimension if (arr[i] == arr[i + 1]): dimension[j] = arr[i] j += 1 i += 1 i += 1 # return the product # of dimensions return (dimension[0] * dimension[1]) # Driver codearr = [4, 2, 1, 4, 6, 6, 2, 5]n = len(arr)print(findArea(arr, n)) # This code is contributed# by Smitha // C# program for finding maximum area// possible of a rectangleusing System;using System.Collections; class GFG{// function for finding max areastatic int findArea(int []arr, int n){ // sort array in non-increasing order Array.Sort(arr); Array.Reverse(arr); // Initialize two sides of rectangle int[] dimension = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]);} // Driver Codepublic static void Main(String []args){ int []arr = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = arr.Length; Console.Write(findArea(arr, n));}} // This code is contributed// by PrinciRaj1992 <?php// PHP program for finding maximum area possible// of a rectangle // function for finding max areafunction findArea($arr, $n){ // sort array in non- // increasing order rsort($arr); // Initialize two sides // of rectangle $dimension = array( 0, 0 ); // traverse through array for( $i = 0, $j = 0; $i < $n - 1 && $j < 2; $i++) // if any element occurs twice // store that as dimension if ($arr[$i] == $arr[$i + 1]) $dimension[$j++] = $arr[$i++]; // return the product // of dimensions return ($dimension[0] * $dimension[1]);} // Driver Code $arr = array(4, 2, 1, 4, 6, 6, 2, 5); $n =count($arr); echo findArea($arr, $n); // This code is contributed by anuj_67.?> <script> // Javascript program for finding maximum area possible// of a rectangle // function for finding max areafunction findArea(arr, n){ // sort array in non-increasing order arr.sort((a,b)=>{return b-a;}) // Initialize two sides of rectangle var dimension = [0,0]; // traverse through array for (var i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]);} // driver functionvar arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ];var n = arr.length;document.write( findArea(arr, n)); </script> Output: 24 Time Complexity : O(n Log n) Method 2 (Hashing) The idea is to insert all first occurrences of elements in a hash set. For second occurrences, keep track of maximum two values. C++ Java Python3 C# Javascript // CPP program for finding maximum area possible// of a rectangle#include <bits/stdc++.h>using namespace std; // function for finding max areaint findArea(int arr[], int n){ unordered_set<int> s; // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of arr[i], // simply insert and continue if (s.find(arr[i]) == s.end()) { s.insert(arr[i]); continue; } // If this is second (or more) occurrence, // update first and second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // return the product of dimensions return (first * second);} // driver functionint main(){ int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findArea(arr, n); return 0;} // Java program for finding maximum// area possible of a rectangleimport java.util.HashSet;import java.util.Set; public class GFG{ // function for finding max area static int findArea(int arr[], int n) { //unordered_set<int> s; Set<Integer> s = new HashSet<>(); // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of // arr[i], simply insert and continue if (!s.contains(arr[i])) { s.add(arr[i]); continue; } // If this is second (or more) // occurrence, update first and // second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // return the product of dimensions return (first * second); } // driver function public static void main(String args[]) { int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = arr.length; System.out.println(findArea(arr, n)); }}// This code is contributed by Sumit Ghosh # Python 3 program for finding maximum# area possible of a rectangle # function for finding max areadef findArea(arr, n): s = [] # traverse through array first = 0 second = 0 for i in range(n) : # If this is first occurrence of # arr[i], simply insert and continue if arr[i] not in s: s.append(arr[i]) continue # If this is second (or more) occurrence, # update first and second maximum values. if (arr[i] > first) : second = first first = arr[i] else if (arr[i] > second): second = arr[i] # return the product of dimensions return (first * second) # Driver Codeif __name__ == "__main__": arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ] n = len(arr) print(findArea(arr, n)) # This code is contributed by ita_c using System;using System.Collections.Generic; // c# program for finding maximum // area possible of a rectangle public class GFG{ // function for finding max area public static int findArea(int[] arr, int n) { //unordered_set<int> s; ISet<int> s = new HashSet<int>(); // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of // arr[i], simply insert and continue if (!s.Contains(arr[i])) { s.Add(arr[i]); continue; } // If this is second (or more) // occurrence, update first and // second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) { second = arr[i]; } } // return the product of dimensions return (first * second); } // driver function public static void Main(string[] args) { int[] arr = new int[] {4, 2, 1, 4, 6, 6, 2, 5}; int n = arr.Length; Console.WriteLine(findArea(arr, n)); }} // This code is contributed by Shrikant13 <script> // Javascript program for finding maximum// area possible of a rectangle // Function for finding max areafunction findArea(arr, n){ let s = new Set(); // Traverse through array let first = 0, second = 0; for(let i = 0; i < n; i++) { // If this is first occurrence of // arr[i], simply insert and continue if (!s.has(arr[i])) { s.add(arr[i]); continue; } // If this is second (or more) // occurrence, update first and // second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // Return the product of dimensions return (first * second);} // Driver Codelet arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ];let n = arr.length; document.write(findArea(arr, n)); // This code is contributed by avanitrachhadiya2155 </script> Output: 24 Time Complexity: O(n) This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Smitha Dinesh Semwal shrikanth13 princiraj1992 ukasp rutvik_56 avanitrachhadiya2155 simmytarika5 area-volume-programs Arrays Hash Sorting Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Mar, 2022" }, { "code": null, "e": 293, "s": 54, "text": "Given an array of n positive integers that represent lengths. Find out the maximum possible area whose four sides are picked from given array. Note that a rectangle can only be formed if there are two pairs of equal values in given array." }, { "code": null, "e": 304, "s": 293, "text": "Examples: " }, { "code": null, "e": 471, "s": 304, "text": "Input : arr[] = {2, 1, 2, 5, 4, 4}\nOutput : 8\nExplanation : Dimension will be 4 * 2\n\nInput : arr[] = {2, 1, 3, 5, 4, 4}\nOutput : 0\nExplanation : No rectangle possible" }, { "code": null, "e": 797, "s": 471, "text": "Method 1 (Sorting) The task basically reduces to finding two pairs of equal values in array. If there are more than two pairs, then pick the two pairs with maximum values. A simple solution is to do following. 1) Sort the given array. 2) Traverse array from largest to smallest value and return two pairs with maximum values." }, { "code": null, "e": 801, "s": 797, "text": "C++" }, { "code": null, "e": 806, "s": 801, "text": "Java" }, { "code": null, "e": 814, "s": 806, "text": "Python3" }, { "code": null, "e": 817, "s": 814, "text": "C#" }, { "code": null, "e": 821, "s": 817, "text": "PHP" }, { "code": null, "e": 832, "s": 821, "text": "Javascript" }, { "code": "// CPP program for finding maximum area possible// of a rectangle#include <bits/stdc++.h>using namespace std; // function for finding max areaint findArea(int arr[], int n){ // sort array in non-increasing order sort(arr, arr + n, greater<int>()); // Initialize two sides of rectangle int dimension[2] = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]);} // driver functionint main(){ int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findArea(arr, n); return 0;}", "e": 1623, "s": 832, "text": null }, { "code": "// Java program for finding maximum area// possible of a rectangleimport java.util.Arrays;import java.util.Collections; public class GFG{ // function for finding max area static int findArea(Integer arr[], int n) { // sort array in non-increasing order Arrays.sort(arr, Collections.reverseOrder()); // Initialize two sides of rectangle int[] dimension = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]); } // driver function public static void main(String args[]) { Integer arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = arr.length; System.out.println(findArea(arr, n)); }}// This code is contributed by Sumit Ghosh", "e": 2680, "s": 1623, "text": null }, { "code": "# Python3 program for finding# maximum area possible of# a rectangle # function for finding# max areadef findArea(arr, n): # sort array in # non-increasing order arr.sort(reverse = True) # Initialize two # sides of rectangle dimension = [0, 0] # traverse through array i = 0 j = 0 while(i < n - 1 and j < 2): # if any element occurs twice # store that as dimension if (arr[i] == arr[i + 1]): dimension[j] = arr[i] j += 1 i += 1 i += 1 # return the product # of dimensions return (dimension[0] * dimension[1]) # Driver codearr = [4, 2, 1, 4, 6, 6, 2, 5]n = len(arr)print(findArea(arr, n)) # This code is contributed# by Smitha", "e": 3430, "s": 2680, "text": null }, { "code": "// C# program for finding maximum area// possible of a rectangleusing System;using System.Collections; class GFG{// function for finding max areastatic int findArea(int []arr, int n){ // sort array in non-increasing order Array.Sort(arr); Array.Reverse(arr); // Initialize two sides of rectangle int[] dimension = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]);} // Driver Codepublic static void Main(String []args){ int []arr = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = arr.Length; Console.Write(findArea(arr, n));}} // This code is contributed// by PrinciRaj1992", "e": 4294, "s": 3430, "text": null }, { "code": "<?php// PHP program for finding maximum area possible// of a rectangle // function for finding max areafunction findArea($arr, $n){ // sort array in non- // increasing order rsort($arr); // Initialize two sides // of rectangle $dimension = array( 0, 0 ); // traverse through array for( $i = 0, $j = 0; $i < $n - 1 && $j < 2; $i++) // if any element occurs twice // store that as dimension if ($arr[$i] == $arr[$i + 1]) $dimension[$j++] = $arr[$i++]; // return the product // of dimensions return ($dimension[0] * $dimension[1]);} // Driver Code $arr = array(4, 2, 1, 4, 6, 6, 2, 5); $n =count($arr); echo findArea($arr, $n); // This code is contributed by anuj_67.?>", "e": 5089, "s": 4294, "text": null }, { "code": "<script> // Javascript program for finding maximum area possible// of a rectangle // function for finding max areafunction findArea(arr, n){ // sort array in non-increasing order arr.sort((a,b)=>{return b-a;}) // Initialize two sides of rectangle var dimension = [0,0]; // traverse through array for (var i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]);} // driver functionvar arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ];var n = arr.length;document.write( findArea(arr, n)); </script>", "e": 5798, "s": 5089, "text": null }, { "code": null, "e": 5807, "s": 5798, "text": "Output: " }, { "code": null, "e": 5810, "s": 5807, "text": "24" }, { "code": null, "e": 5988, "s": 5810, "text": "Time Complexity : O(n Log n) Method 2 (Hashing) The idea is to insert all first occurrences of elements in a hash set. For second occurrences, keep track of maximum two values. " }, { "code": null, "e": 5992, "s": 5988, "text": "C++" }, { "code": null, "e": 5997, "s": 5992, "text": "Java" }, { "code": null, "e": 6005, "s": 5997, "text": "Python3" }, { "code": null, "e": 6008, "s": 6005, "text": "C#" }, { "code": null, "e": 6019, "s": 6008, "text": "Javascript" }, { "code": "// CPP program for finding maximum area possible// of a rectangle#include <bits/stdc++.h>using namespace std; // function for finding max areaint findArea(int arr[], int n){ unordered_set<int> s; // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of arr[i], // simply insert and continue if (s.find(arr[i]) == s.end()) { s.insert(arr[i]); continue; } // If this is second (or more) occurrence, // update first and second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // return the product of dimensions return (first * second);} // driver functionint main(){ int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findArea(arr, n); return 0;}", "e": 6975, "s": 6019, "text": null }, { "code": "// Java program for finding maximum// area possible of a rectangleimport java.util.HashSet;import java.util.Set; public class GFG{ // function for finding max area static int findArea(int arr[], int n) { //unordered_set<int> s; Set<Integer> s = new HashSet<>(); // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of // arr[i], simply insert and continue if (!s.contains(arr[i])) { s.add(arr[i]); continue; } // If this is second (or more) // occurrence, update first and // second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // return the product of dimensions return (first * second); } // driver function public static void main(String args[]) { int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = arr.length; System.out.println(findArea(arr, n)); }}// This code is contributed by Sumit Ghosh", "e": 8220, "s": 6975, "text": null }, { "code": "# Python 3 program for finding maximum# area possible of a rectangle # function for finding max areadef findArea(arr, n): s = [] # traverse through array first = 0 second = 0 for i in range(n) : # If this is first occurrence of # arr[i], simply insert and continue if arr[i] not in s: s.append(arr[i]) continue # If this is second (or more) occurrence, # update first and second maximum values. if (arr[i] > first) : second = first first = arr[i] else if (arr[i] > second): second = arr[i] # return the product of dimensions return (first * second) # Driver Codeif __name__ == \"__main__\": arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ] n = len(arr) print(findArea(arr, n)) # This code is contributed by ita_c", "e": 9059, "s": 8220, "text": null }, { "code": "using System;using System.Collections.Generic; // c# program for finding maximum // area possible of a rectangle public class GFG{ // function for finding max area public static int findArea(int[] arr, int n) { //unordered_set<int> s; ISet<int> s = new HashSet<int>(); // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of // arr[i], simply insert and continue if (!s.Contains(arr[i])) { s.Add(arr[i]); continue; } // If this is second (or more) // occurrence, update first and // second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) { second = arr[i]; } } // return the product of dimensions return (first * second); } // driver function public static void Main(string[] args) { int[] arr = new int[] {4, 2, 1, 4, 6, 6, 2, 5}; int n = arr.Length; Console.WriteLine(findArea(arr, n)); }} // This code is contributed by Shrikant13", "e": 10350, "s": 9059, "text": null }, { "code": "<script> // Javascript program for finding maximum// area possible of a rectangle // Function for finding max areafunction findArea(arr, n){ let s = new Set(); // Traverse through array let first = 0, second = 0; for(let i = 0; i < n; i++) { // If this is first occurrence of // arr[i], simply insert and continue if (!s.has(arr[i])) { s.add(arr[i]); continue; } // If this is second (or more) // occurrence, update first and // second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // Return the product of dimensions return (first * second);} // Driver Codelet arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ];let n = arr.length; document.write(findArea(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 11321, "s": 10350, "text": null }, { "code": null, "e": 11330, "s": 11321, "text": "Output: " }, { "code": null, "e": 11333, "s": 11330, "text": "24" }, { "code": null, "e": 11355, "s": 11333, "text": "Time Complexity: O(n)" }, { "code": null, "e": 11791, "s": 11355, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11796, "s": 11791, "text": "vt_m" }, { "code": null, "e": 11817, "s": 11796, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 11829, "s": 11817, "text": "shrikanth13" }, { "code": null, "e": 11843, "s": 11829, "text": "princiraj1992" }, { "code": null, "e": 11849, "s": 11843, "text": "ukasp" }, { "code": null, "e": 11859, "s": 11849, "text": "rutvik_56" }, { "code": null, "e": 11880, "s": 11859, "text": "avanitrachhadiya2155" }, { "code": null, "e": 11893, "s": 11880, "text": "simmytarika5" }, { "code": null, "e": 11914, "s": 11893, "text": "area-volume-programs" }, { "code": null, "e": 11921, "s": 11914, "text": "Arrays" }, { "code": null, "e": 11926, "s": 11921, "text": "Hash" }, { "code": null, "e": 11934, "s": 11926, "text": "Sorting" }, { "code": null, "e": 11941, "s": 11934, "text": "Arrays" }, { "code": null, "e": 11946, "s": 11941, "text": "Hash" }, { "code": null, "e": 11954, "s": 11946, "text": "Sorting" }, { "code": null, "e": 12052, "s": 11954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12084, "s": 12052, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 12098, "s": 12084, "text": "Linear Search" }, { "code": null, "e": 12183, "s": 12098, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 12206, "s": 12183, "text": "Introduction to Arrays" }, { "code": null, "e": 12262, "s": 12206, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 12347, "s": 12262, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 12385, "s": 12347, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 12421, "s": 12385, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 12452, "s": 12421, "text": "Hashing | Set 1 (Introduction)" } ]
Servlets - Environment Setup
A development environment is where you would develop your Servlet, test them and finally run them. Like any other Java program, you need to compile a servlet by using the Java compiler javac and after compilation the servlet application, it would be deployed in a configured environment to test and run.. This development environment setup involves the following steps − This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately. You can download SDK from Oracle's Java site − Java SE Downloads. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:\jdk1.8.0_65, you would put the following line in your C:\autoexec.bat file. set PATH = C:\jdk1.8.0_65\bin;%PATH% set JAVA_HOME = C:\jdk1.8.0_65 Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8.0_65 and you use the C shell, you would put the following into your .cshrc file. setenv PATH /usr/local/jdk1.8.0_65/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.8.0_65 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. A number of Web Servers that support servlets are available in the market. Some web servers are freely downloadable and Tomcat is one of them. Apache Tomcat is an open source software implementation of the Java Servlet and Java Server Pages technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine − Download latest version of Tomcat from https://tomcat.apache.org/. Download latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-8.0.28 on windows, or /usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-8.0.28 on windows, or /usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on windows machine − %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-8.0.28\bin\startup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-8.0.28/bin/startup.sh After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org Tomcat can be stopped by executing the following commands on windows machine − C:\apache-tomcat-8.0.28\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − /usr/local/apache-tomcat-8.0.28/bin/shutdown.sh Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler. If you are running Windows, you need to put the following lines in your C:\autoexec.bat file. set CATALINA = C:\apache-tomcat-8.0.28 set CLASSPATH = %CATALINA%\common\lib\servlet-api.jar;%CLASSPATH% Alternatively, on Windows NT/2000/XP, you could go to My Computer −> Properties −> Advanced −> Environment Variables. Then, you would update the CLASSPATH value and press the OK button. On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file. setenv CATALINA = /usr/local/apache-tomcat-8.0.28 setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH NOTE − Assuming that your development directory is C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH in similar way as you have added above.
[ { "code": null, "e": 2418, "s": 2319, "text": "A development environment is where you would develop your Servlet, test them and finally run them." }, { "code": null, "e": 2624, "s": 2418, "text": "Like any other Java program, you need to compile a servlet by using the Java compiler javac and after compilation the servlet application, it would be deployed in a configured environment to test and run.." }, { "code": null, "e": 2690, "s": 2624, "text": "This development environment setup involves the following steps −" }, { "code": null, "e": 2838, "s": 2690, "text": "This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately." }, { "code": null, "e": 2904, "s": 2838, "text": "You can download SDK from Oracle's Java site − Java SE Downloads." }, { "code": null, "e": 3189, "s": 2904, "text": "Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 3320, "s": 3189, "text": "If you are running Windows and installed the SDK in C:\\jdk1.8.0_65, you would put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 3391, "s": 3320, "text": "set PATH = C:\\jdk1.8.0_65\\bin;%PATH% \nset JAVA_HOME = C:\\jdk1.8.0_65 \n" }, { "code": null, "e": 3597, "s": 3391, "text": "Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button." }, { "code": null, "e": 3755, "s": 3597, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8.0_65 and you use the C shell, you would put the following into your .cshrc file." }, { "code": null, "e": 3842, "s": 3755, "text": "setenv PATH /usr/local/jdk1.8.0_65/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk1.8.0_65\n" }, { "code": null, "e": 4067, "s": 3842, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java." }, { "code": null, "e": 4210, "s": 4067, "text": "A number of Web Servers that support servlets are available in the market. Some web servers are freely downloadable and Tomcat is one of them." }, { "code": null, "e": 4480, "s": 4210, "text": "Apache Tomcat is an open source software implementation of the Java Servlet and Java Server Pages technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine −" }, { "code": null, "e": 4547, "s": 4480, "text": "Download latest version of Tomcat from https://tomcat.apache.org/." }, { "code": null, "e": 4614, "s": 4547, "text": "Download latest version of Tomcat from https://tomcat.apache.org/." }, { "code": null, "e": 4887, "s": 4614, "text": "Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\\apache-tomcat-8.0.28 on windows, or /usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations." }, { "code": null, "e": 5160, "s": 4887, "text": "Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\\apache-tomcat-8.0.28 on windows, or /usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations." }, { "code": null, "e": 5239, "s": 5160, "text": "Tomcat can be started by executing the following commands on windows machine −" }, { "code": null, "e": 5315, "s": 5239, "text": "%CATALINA_HOME%\\bin\\startup.bat\nor\nC:\\apache-tomcat-8.0.28\\bin\\startup.bat\n" }, { "code": null, "e": 5414, "s": 5315, "text": "Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 5495, "s": 5414, "text": "$CATALINA_HOME/bin/startup.sh\nor\n/usr/local/apache-tomcat-8.0.28/bin/startup.sh\n" }, { "code": null, "e": 5678, "s": 5495, "text": "After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result −" }, { "code": null, "e": 5845, "s": 5678, "text": "Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org" }, { "code": null, "e": 5924, "s": 5845, "text": "Tomcat can be stopped by executing the following commands on windows machine −" }, { "code": null, "e": 5963, "s": 5924, "text": "C:\\apache-tomcat-8.0.28\\bin\\shutdown \n" }, { "code": null, "e": 6062, "s": 5963, "text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 6111, "s": 6062, "text": "/usr/local/apache-tomcat-8.0.28/bin/shutdown.sh\n" }, { "code": null, "e": 6234, "s": 6111, "text": "Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler." }, { "code": null, "e": 6328, "s": 6234, "text": "If you are running Windows, you need to put the following lines in your C:\\autoexec.bat file." }, { "code": null, "e": 6436, "s": 6328, "text": "set CATALINA = C:\\apache-tomcat-8.0.28 \nset CLASSPATH = %CATALINA%\\common\\lib\\servlet-api.jar;%CLASSPATH% \n" }, { "code": null, "e": 6623, "s": 6436, "text": "Alternatively, on Windows NT/2000/XP, you could go to My Computer −> Properties −> Advanced −> Environment Variables. Then, you would update the CLASSPATH value and press the OK button. " }, { "code": null, "e": 6742, "s": 6623, "text": "On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file." }, { "code": null, "e": 6858, "s": 6742, "text": "setenv CATALINA = /usr/local/apache-tomcat-8.0.28\nsetenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH\n" } ]
Perl | Count the frequency of words in text
12 Feb, 2019 Counting frequency of all words of a string is a basic operation for any programming language. The frequency of each word of the text can be counted and stored in a hash for further use. In Perl, we can do this by firstly splitting the words of the string into an array. We use the function split / / which splits the string with ‘ ‘. However the blank spaces can be more than one in between two words, therefore /\s+/ is used. Here \s+ denotes one or more occurrence of ‘ ‘. Now we traverse the new array created by splitting of text into words. This time we increment the count of the word while traversing the array. Example: To demonstrate Count the frequency of words in string# Perl program for counting words in a string $actual_text = "GFG GeeksforGeeks GFG" ; # Creating words array by splitting the string@words= split / /, $actual_text; # Traversing the words array and # increasing count of each word by 1foreach $word(@words) { $count{$word}++;} # Printing the word and its actual countforeach $word (sort keys %count) { print $word, " ", $count{$word}, "\n";}Output:GFG 2 GeeksforGeeks 1 # Perl program for counting words in a string $actual_text = "GFG GeeksforGeeks GFG" ; # Creating words array by splitting the string@words= split / /, $actual_text; # Traversing the words array and # increasing count of each word by 1foreach $word(@words) { $count{$word}++;} # Printing the word and its actual countforeach $word (sort keys %count) { print $word, " ", $count{$word}, "\n";} Output: GFG 2 GeeksforGeeks 1 Difference between /\s+/ and / /: The ‘\s+’ can be used for a delimiter with one or many space. However / / just separates words with 1 space. The following code represents the difference if the text has more than one space between two words. Example: To demonstrate the difference between /\s+/ and / / # Perl program for counting words in a string using / / # A text with two spaces rather than one$actual_text = "GeeksforGeeks welcomes you to GeeksforGeeks portal" ; # splitting the word with / /@words= split / /, $actual_text; # Counting the occurrence of each word foreach $word (@words){ $count{$word}++;} foreach $word (sort keys %count){ print $word, " ", $count{$word}, "\n";}Output:1 GeeksforGeeks 2 portal 1 to 1 welcomes 1 you 1 Note: The extra ‘ ‘ is also counted as a word. # Perl program for counting words in a string using / / # A text with two spaces rather than one$actual_text = "GeeksforGeeks welcomes you to GeeksforGeeks portal" ; # splitting the word with / /@words= split / /, $actual_text; # Counting the occurrence of each word foreach $word (@words){ $count{$word}++;} foreach $word (sort keys %count){ print $word, " ", $count{$word}, "\n";} Output: 1 GeeksforGeeks 2 portal 1 to 1 welcomes 1 you 1 Note: The extra ‘ ‘ is also counted as a word. Using the command /\s+/ to split the words: Here space will not count as the separate word. Example: #Perl program for counting words in a string using /\s+/ # Actual string with two spaces$actual_text = "GeeksforGeeks welcomes you to GeeksforGeeks portal" ; #S plitting the text using /\s+/ command@words = split /\s+/, $actual_text; # counting the occurrence of each word foreach $word (@words) { $count{$word}++;} foreach $word (sort keys %count){ print $word, " ", $count{$word}, "\n";}Output:GeeksforGeeks 2 portal 1 to 1 welcomes 1 you 1 Note: The extra ‘ ‘ is not counted as a word. #Perl program for counting words in a string using /\s+/ # Actual string with two spaces$actual_text = "GeeksforGeeks welcomes you to GeeksforGeeks portal" ; #S plitting the text using /\s+/ command@words = split /\s+/, $actual_text; # counting the occurrence of each word foreach $word (@words) { $count{$word}++;} foreach $word (sort keys %count){ print $word, " ", $count{$word}, "\n";} Output: GeeksforGeeks 2 portal 1 to 1 welcomes 1 you 1 Note: The extra ‘ ‘ is not counted as a word. Perl-hashes Perl-String Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 648, "s": 28, "text": "Counting frequency of all words of a string is a basic operation for any programming language. The frequency of each word of the text can be counted and stored in a hash for further use. In Perl, we can do this by firstly splitting the words of the string into an array. We use the function split / / which splits the string with ‘ ‘. However the blank spaces can be more than one in between two words, therefore /\\s+/ is used. Here \\s+ denotes one or more occurrence of ‘ ‘. Now we traverse the new array created by splitting of text into words. This time we increment the count of the word while traversing the array." }, { "code": null, "e": 1142, "s": 648, "text": "Example: To demonstrate Count the frequency of words in string# Perl program for counting words in a string $actual_text = \"GFG GeeksforGeeks GFG\" ; # Creating words array by splitting the string@words= split / /, $actual_text; # Traversing the words array and # increasing count of each word by 1foreach $word(@words) { $count{$word}++;} # Printing the word and its actual countforeach $word (sort keys %count) { print $word, \" \", $count{$word}, \"\\n\";}Output:GFG 2\nGeeksforGeeks 1\n" }, { "code": "# Perl program for counting words in a string $actual_text = \"GFG GeeksforGeeks GFG\" ; # Creating words array by splitting the string@words= split / /, $actual_text; # Traversing the words array and # increasing count of each word by 1foreach $word(@words) { $count{$word}++;} # Printing the word and its actual countforeach $word (sort keys %count) { print $word, \" \", $count{$word}, \"\\n\";}", "e": 1545, "s": 1142, "text": null }, { "code": null, "e": 1553, "s": 1545, "text": "Output:" }, { "code": null, "e": 1576, "s": 1553, "text": "GFG 2\nGeeksforGeeks 1\n" }, { "code": null, "e": 1819, "s": 1576, "text": "Difference between /\\s+/ and / /: The ‘\\s+’ can be used for a delimiter with one or many space. However / / just separates words with 1 space. The following code represents the difference if the text has more than one space between two words." }, { "code": null, "e": 2380, "s": 1819, "text": "Example: To demonstrate the difference between /\\s+/ and / / # Perl program for counting words in a string using / / # A text with two spaces rather than one$actual_text = \"GeeksforGeeks welcomes you to GeeksforGeeks portal\" ; # splitting the word with / /@words= split / /, $actual_text; # Counting the occurrence of each word foreach $word (@words){ $count{$word}++;} foreach $word (sort keys %count){ print $word, \" \", $count{$word}, \"\\n\";}Output:1\nGeeksforGeeks 2\nportal 1\nto 1\nwelcomes 1\nyou 1\nNote: The extra ‘ ‘ is also counted as a word." }, { "code": " # Perl program for counting words in a string using / / # A text with two spaces rather than one$actual_text = \"GeeksforGeeks welcomes you to GeeksforGeeks portal\" ; # splitting the word with / /@words= split / /, $actual_text; # Counting the occurrence of each word foreach $word (@words){ $count{$word}++;} foreach $word (sort keys %count){ print $word, \" \", $count{$word}, \"\\n\";}", "e": 2779, "s": 2380, "text": null }, { "code": null, "e": 2787, "s": 2779, "text": "Output:" }, { "code": null, "e": 2837, "s": 2787, "text": "1\nGeeksforGeeks 2\nportal 1\nto 1\nwelcomes 1\nyou 1\n" }, { "code": null, "e": 2884, "s": 2837, "text": "Note: The extra ‘ ‘ is also counted as a word." }, { "code": null, "e": 2976, "s": 2884, "text": "Using the command /\\s+/ to split the words: Here space will not count as the separate word." }, { "code": null, "e": 3489, "s": 2976, "text": "Example: #Perl program for counting words in a string using /\\s+/ # Actual string with two spaces$actual_text = \"GeeksforGeeks welcomes you to GeeksforGeeks portal\" ; #S plitting the text using /\\s+/ command@words = split /\\s+/, $actual_text; # counting the occurrence of each word foreach $word (@words) { $count{$word}++;} foreach $word (sort keys %count){ print $word, \" \", $count{$word}, \"\\n\";}Output:GeeksforGeeks 2\nportal 1\nto 1\nwelcomes 1\nyou 1\nNote: The extra ‘ ‘ is not counted as a word." }, { "code": " #Perl program for counting words in a string using /\\s+/ # Actual string with two spaces$actual_text = \"GeeksforGeeks welcomes you to GeeksforGeeks portal\" ; #S plitting the text using /\\s+/ command@words = split /\\s+/, $actual_text; # counting the occurrence of each word foreach $word (@words) { $count{$word}++;} foreach $word (sort keys %count){ print $word, \" \", $count{$word}, \"\\n\";}", "e": 3895, "s": 3489, "text": null }, { "code": null, "e": 3903, "s": 3895, "text": "Output:" }, { "code": null, "e": 3951, "s": 3903, "text": "GeeksforGeeks 2\nportal 1\nto 1\nwelcomes 1\nyou 1\n" }, { "code": null, "e": 3997, "s": 3951, "text": "Note: The extra ‘ ‘ is not counted as a word." }, { "code": null, "e": 4009, "s": 3997, "text": "Perl-hashes" }, { "code": null, "e": 4021, "s": 4009, "text": "Perl-String" }, { "code": null, "e": 4026, "s": 4021, "text": "Perl" }, { "code": null, "e": 4031, "s": 4026, "text": "Perl" } ]
Swapping Pairs of Characters in a String in Java
30 Aug, 2020 Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is. Examples: Input: str = “Java” Output: aJva Explanation: The given string contains even number of characters. Therefore, we swap every pair of characters. Input: str = “GeeksForGeeks” Output: eGkeFsroeGkes Explanation: The given string contains odd number of characters. Therefore, we swap every pair of characters and last character remains as it is. 1. Using String.toCharArray() Method Get the string to swap a pair of characters.Check if the string is null or empty then return the string.Converting the given string into a character array.Traverse the character array and swap the characters.Now, print the result. Get the string to swap a pair of characters. Check if the string is null or empty then return the string. Converting the given string into a character array. Traverse the character array and swap the characters. Now, print the result. Java // Java program to swap pair// of characters of a string class GFG { // Function to swap pair of // characters of a string public static String swapPair(String str) { // Checking if string is null // or empty then return str if (str == null || str.isEmpty()) return str; // Converting the given string // into a character array char[] ch = str.toCharArray(); // Traverse the character array for (int i = 0; i < ch.length - 1; i += 2) { // Swapping the characters char temp = ch[i]; ch[i] = ch[i + 1]; ch[i + 1] = temp; } // Converting the result into a // string and return return new String(ch); } // Driver Code public static void main(String args[]) { // Given String str String str = "GeeksForGeeks"; // Print the result System.out.println(swapPair(str)); }} eGkeFsroeGkes 2. Using StringBuffer.append() Method Get the string to swap a pair of characters.Check if the string is null or empty then return the string.Creating a StringBuffer object with a length of the string passed as a parameter.Traverse the string and append the characters in the StringBuffer object in reverse order.Check if the string contains an odd number of characters then append the last character into the StringBuffer object.Now, print the result. Get the string to swap a pair of characters. Check if the string is null or empty then return the string. Creating a StringBuffer object with a length of the string passed as a parameter. Traverse the string and append the characters in the StringBuffer object in reverse order. Check if the string contains an odd number of characters then append the last character into the StringBuffer object. Now, print the result. Java // Java program to swap pair// of characters of a string class GFG { // Function to swap pair of // characters of a string public static String swapPairs(String str) { // Checking if string is null // or empty then return str if (str == null || str.isEmpty()) return str; int len = str.length(); // Creating a StringBuffer object with // length of the string passed as a parameter StringBuffer sb = new StringBuffer(len); // Traverse the string and append // the character in the StringBuffer // object in reverse order for (int i = 0; i < len - 1; i += 2) { sb.append(str.charAt(i + 1)); sb.append(str.charAt(i)); } // Checking if the string has // odd number of characters // then append the last character // into StringBuffer object if (len % 2 != 0) { sb.append(str.charAt(len - 1)); } // Converting the StringBuffer // into the string and return return sb.toString(); } // Driver Code public static void main(String args[]) { // Given String str String str = "GeeksForGeeks"; // Print the result System.out.println(swapPairs(str)); }} eGkeFsroeGkes Java-String-Programs Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue Interface In Java Interfaces in Java Collections in Java ChronoZonedDateTime isAfter() method in Java with Examples Introduction to Java PriorityQueue in Java Constructors in Java How to add an element to an Array in Java? LinkedList in Java Singleton Class in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Aug, 2020" }, { "code": null, "e": 245, "s": 53, "text": "Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is." }, { "code": null, "e": 255, "s": 245, "text": "Examples:" }, { "code": null, "e": 275, "s": 255, "text": "Input: str = “Java”" }, { "code": null, "e": 288, "s": 275, "text": "Output: aJva" }, { "code": null, "e": 399, "s": 288, "text": "Explanation: The given string contains even number of characters. Therefore, we swap every pair of characters." }, { "code": null, "e": 428, "s": 399, "text": "Input: str = “GeeksForGeeks”" }, { "code": null, "e": 450, "s": 428, "text": "Output: eGkeFsroeGkes" }, { "code": null, "e": 596, "s": 450, "text": "Explanation: The given string contains odd number of characters. Therefore, we swap every pair of characters and last character remains as it is." }, { "code": null, "e": 633, "s": 596, "text": "1. Using String.toCharArray() Method" }, { "code": null, "e": 864, "s": 633, "text": "Get the string to swap a pair of characters.Check if the string is null or empty then return the string.Converting the given string into a character array.Traverse the character array and swap the characters.Now, print the result." }, { "code": null, "e": 909, "s": 864, "text": "Get the string to swap a pair of characters." }, { "code": null, "e": 970, "s": 909, "text": "Check if the string is null or empty then return the string." }, { "code": null, "e": 1022, "s": 970, "text": "Converting the given string into a character array." }, { "code": null, "e": 1076, "s": 1022, "text": "Traverse the character array and swap the characters." }, { "code": null, "e": 1099, "s": 1076, "text": "Now, print the result." }, { "code": null, "e": 1104, "s": 1099, "text": "Java" }, { "code": "// Java program to swap pair// of characters of a string class GFG { // Function to swap pair of // characters of a string public static String swapPair(String str) { // Checking if string is null // or empty then return str if (str == null || str.isEmpty()) return str; // Converting the given string // into a character array char[] ch = str.toCharArray(); // Traverse the character array for (int i = 0; i < ch.length - 1; i += 2) { // Swapping the characters char temp = ch[i]; ch[i] = ch[i + 1]; ch[i + 1] = temp; } // Converting the result into a // string and return return new String(ch); } // Driver Code public static void main(String args[]) { // Given String str String str = \"GeeksForGeeks\"; // Print the result System.out.println(swapPair(str)); }}", "e": 2080, "s": 1104, "text": null }, { "code": null, "e": 2097, "s": 2080, "text": "eGkeFsroeGkes\n\n\n" }, { "code": null, "e": 2135, "s": 2097, "text": "2. Using StringBuffer.append() Method" }, { "code": null, "e": 2550, "s": 2135, "text": "Get the string to swap a pair of characters.Check if the string is null or empty then return the string.Creating a StringBuffer object with a length of the string passed as a parameter.Traverse the string and append the characters in the StringBuffer object in reverse order.Check if the string contains an odd number of characters then append the last character into the StringBuffer object.Now, print the result." }, { "code": null, "e": 2595, "s": 2550, "text": "Get the string to swap a pair of characters." }, { "code": null, "e": 2656, "s": 2595, "text": "Check if the string is null or empty then return the string." }, { "code": null, "e": 2738, "s": 2656, "text": "Creating a StringBuffer object with a length of the string passed as a parameter." }, { "code": null, "e": 2829, "s": 2738, "text": "Traverse the string and append the characters in the StringBuffer object in reverse order." }, { "code": null, "e": 2947, "s": 2829, "text": "Check if the string contains an odd number of characters then append the last character into the StringBuffer object." }, { "code": null, "e": 2970, "s": 2947, "text": "Now, print the result." }, { "code": null, "e": 2975, "s": 2970, "text": "Java" }, { "code": "// Java program to swap pair// of characters of a string class GFG { // Function to swap pair of // characters of a string public static String swapPairs(String str) { // Checking if string is null // or empty then return str if (str == null || str.isEmpty()) return str; int len = str.length(); // Creating a StringBuffer object with // length of the string passed as a parameter StringBuffer sb = new StringBuffer(len); // Traverse the string and append // the character in the StringBuffer // object in reverse order for (int i = 0; i < len - 1; i += 2) { sb.append(str.charAt(i + 1)); sb.append(str.charAt(i)); } // Checking if the string has // odd number of characters // then append the last character // into StringBuffer object if (len % 2 != 0) { sb.append(str.charAt(len - 1)); } // Converting the StringBuffer // into the string and return return sb.toString(); } // Driver Code public static void main(String args[]) { // Given String str String str = \"GeeksForGeeks\"; // Print the result System.out.println(swapPairs(str)); }}", "e": 4283, "s": 2975, "text": null }, { "code": null, "e": 4300, "s": 4283, "text": "eGkeFsroeGkes\n\n\n" }, { "code": null, "e": 4321, "s": 4300, "text": "Java-String-Programs" }, { "code": null, "e": 4334, "s": 4321, "text": "Java-Strings" }, { "code": null, "e": 4339, "s": 4334, "text": "Java" }, { "code": null, "e": 4352, "s": 4339, "text": "Java-Strings" }, { "code": null, "e": 4357, "s": 4352, "text": "Java" }, { "code": null, "e": 4455, "s": 4357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4479, "s": 4455, "text": "Queue Interface In Java" }, { "code": null, "e": 4498, "s": 4479, "text": "Interfaces in Java" }, { "code": null, "e": 4518, "s": 4498, "text": "Collections in Java" }, { "code": null, "e": 4577, "s": 4518, "text": "ChronoZonedDateTime isAfter() method in Java with Examples" }, { "code": null, "e": 4598, "s": 4577, "text": "Introduction to Java" }, { "code": null, "e": 4620, "s": 4598, "text": "PriorityQueue in Java" }, { "code": null, "e": 4641, "s": 4620, "text": "Constructors in Java" }, { "code": null, "e": 4684, "s": 4641, "text": "How to add an element to an Array in Java?" }, { "code": null, "e": 4703, "s": 4684, "text": "LinkedList in Java" } ]
Prefix to Postfix Conversion
24 May, 2022 Prefix: An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Example : *+AB-CD (Infix : (A+B) * (C-D) ) Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). Example : AB+CD-* (Infix : (A+B * (C-D) )Given a Prefix expression, convert it into a Postfix expression. Conversion of Prefix expression directly to Postfix without going through the process of converting them first to Infix and then to Postfix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). Examples: Input : Prefix : *+AB-CD Output : Postfix : AB+CD-* Explanation : Prefix to Infix : (A+B) * (C-D) Infix to Postfix : AB+CD-* Input : Prefix : *-A/BC-/AKL Output : Postfix : ABC/-AK/L-* Explanation : Prefix to Infix : (A-(B/C))*((A/K)-L) Infix to Postfix : ABC/-AK/L-* Algorithm for Prefix to Postfix: Read the Prefix expression in reverse order (from right to left) If the symbol is an operand, then push it onto the Stack If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator after them. string = operand1 + operand2 + operator And push the resultant string back to Stack Repeat the above steps until end of Prefix expression. C++ Java Python 3 C# Javascript // CPP Program to convert prefix to postfix#include <iostream>#include <stack>using namespace std; // function to check if character is operator or notbool isOperator(char x){ switch (x) { case '+': case '-': case '/': case '*': return true; } return false;} // Convert prefix to Postfix expressionstring preToPost(string pre_exp){ stack<string> s; // length of expression int length = pre_exp.size(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = op1 + op2 + pre_exp[i]; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, pre_exp[i])); } } // stack contains only the Postfix expression return s.top();} // Driver Codeint main(){ string pre_exp = "*-A/BC-/AKL"; cout << "Postfix : " << preToPost(pre_exp); return 0;} // JavaProgram to convert prefix to postfiximport java.util.*; class GFG { // function to check if character // is operator or not static boolean isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression static String preToPost(String pre_exp) { Stack<String> s = new Stack<String>(); // length of expression int length = pre_exp.length(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp.charAt(i))) { // pop two operands from stack String op1 = s.peek(); s.pop(); String op2 = s.peek(); s.pop(); // concat the operands and operator String temp = op1 + op2 + pre_exp.charAt(i); // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(pre_exp.charAt(i) + ""); } } // stack contains only the Postfix expression return s.peek(); } // Driver Code public static void main(String args[]) { String pre_exp = "*-A/BC-/AKL"; System.out.println("Postfix : " + preToPost(pre_exp)); }} // This code is contributed by Arnab Kundu # Write Python3 code here# -*- coding: utf-8 -*- # Example Inputs = "*-A/BC-/AKL" # Stack for storing operandsstack = [] operators = set(['+', '-', '*', '/', '^']) # Reversing the orders = s[::-1] # iterating through individual tokensfor i in s: # if token is operator if i in operators: # pop 2 elements from stack a = stack.pop() b = stack.pop() # concatenate them as operand1 + # operand2 + operator temp = a+b+i stack.append(temp) # else if operand else: stack.append(i) # printing final outputprint(*stack) // C# Program to convert prefix to postfixusing System;using System.Collections.Generic; class GFG { // function to check if character // is operator or not static bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression static String preToPost(String pre_exp) { Stack<String> s = new Stack<String>(); // length of expression int length = pre_exp.Length; // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack String op1 = s.Peek(); s.Pop(); String op2 = s.Peek(); s.Pop(); // concat the operands and operator String temp = op1 + op2 + pre_exp[i]; // Push String temp back to stack s.Push(temp); } // if symbol is an operand else { // push the operand to the stack s.Push(pre_exp[i] + ""); } } // stack contains only the Postfix expression return s.Peek(); } // Driver Code public static void Main(String[] args) { String pre_exp = "*-A/BC-/AKL"; Console.WriteLine("Postfix : " + preToPost(pre_exp)); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript Program to convert prefix to postfix // function to check if character // is operator or not function isOperator(x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression function preToPost(pre_exp) { let s = []; // length of expression let length = pre_exp.length; // reading from right to left for (let i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack let op1 = s[s.length - 1]; s.pop(); let op2 = s[s.length - 1]; s.pop(); // concat the operands and operator let temp = op1 + op2 + pre_exp[i]; // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(pre_exp[i] + ""); } } // stack contains only the Postfix expression return s[s.length - 1]; } let pre_exp = "*-A/BC-/AKL"; document.write("Postfix : " + preToPost(pre_exp)); // This code is contributed by suresh07.</script> Postfix : ABC/-AK/L-* Time Complexity: O(N), as we are using a loop for traversing the expression. Auxiliary Space: O(N), as we are using stack for extra space. andrew1234 princiraj1992 geekfreek19 ninja456 akshaysingh98088 suresh07 rohitkumarsinghcna expression-evaluation Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2022" }, { "code": null, "e": 261, "s": 52, "text": "Prefix: An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Example : *+AB-CD (Infix : (A+B) * (C-D) )" }, { "code": null, "e": 801, "s": 261, "text": "Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). Example : AB+CD-* (Infix : (A+B * (C-D) )Given a Prefix expression, convert it into a Postfix expression. Conversion of Prefix expression directly to Postfix without going through the process of converting them first to Infix and then to Postfix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). " }, { "code": null, "e": 812, "s": 801, "text": "Examples: " }, { "code": null, "e": 1117, "s": 812, "text": "Input : Prefix : *+AB-CD\nOutput : Postfix : AB+CD-*\nExplanation : Prefix to Infix : (A+B) * (C-D)\n Infix to Postfix : AB+CD-*\n\nInput : Prefix : *-A/BC-/AKL\nOutput : Postfix : ABC/-AK/L-*\nExplanation : Prefix to Infix : (A-(B/C))*((A/K)-L)\n Infix to Postfix : ABC/-AK/L-* " }, { "code": null, "e": 1151, "s": 1117, "text": "Algorithm for Prefix to Postfix: " }, { "code": null, "e": 1216, "s": 1151, "text": "Read the Prefix expression in reverse order (from right to left)" }, { "code": null, "e": 1273, "s": 1216, "text": "If the symbol is an operand, then push it onto the Stack" }, { "code": null, "e": 1503, "s": 1273, "text": "If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator after them. string = operand1 + operand2 + operator And push the resultant string back to Stack" }, { "code": null, "e": 1558, "s": 1503, "text": "Repeat the above steps until end of Prefix expression." }, { "code": null, "e": 1562, "s": 1558, "text": "C++" }, { "code": null, "e": 1567, "s": 1562, "text": "Java" }, { "code": null, "e": 1576, "s": 1567, "text": "Python 3" }, { "code": null, "e": 1579, "s": 1576, "text": "C#" }, { "code": null, "e": 1590, "s": 1579, "text": "Javascript" }, { "code": "// CPP Program to convert prefix to postfix#include <iostream>#include <stack>using namespace std; // function to check if character is operator or notbool isOperator(char x){ switch (x) { case '+': case '-': case '/': case '*': return true; } return false;} // Convert prefix to Postfix expressionstring preToPost(string pre_exp){ stack<string> s; // length of expression int length = pre_exp.size(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = op1 + op2 + pre_exp[i]; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, pre_exp[i])); } } // stack contains only the Postfix expression return s.top();} // Driver Codeint main(){ string pre_exp = \"*-A/BC-/AKL\"; cout << \"Postfix : \" << preToPost(pre_exp); return 0;}", "e": 2859, "s": 1590, "text": null }, { "code": "// JavaProgram to convert prefix to postfiximport java.util.*; class GFG { // function to check if character // is operator or not static boolean isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression static String preToPost(String pre_exp) { Stack<String> s = new Stack<String>(); // length of expression int length = pre_exp.length(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp.charAt(i))) { // pop two operands from stack String op1 = s.peek(); s.pop(); String op2 = s.peek(); s.pop(); // concat the operands and operator String temp = op1 + op2 + pre_exp.charAt(i); // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(pre_exp.charAt(i) + \"\"); } } // stack contains only the Postfix expression return s.peek(); } // Driver Code public static void main(String args[]) { String pre_exp = \"*-A/BC-/AKL\"; System.out.println(\"Postfix : \" + preToPost(pre_exp)); }} // This code is contributed by Arnab Kundu", "e": 4461, "s": 2859, "text": null }, { "code": "# Write Python3 code here# -*- coding: utf-8 -*- # Example Inputs = \"*-A/BC-/AKL\" # Stack for storing operandsstack = [] operators = set(['+', '-', '*', '/', '^']) # Reversing the orders = s[::-1] # iterating through individual tokensfor i in s: # if token is operator if i in operators: # pop 2 elements from stack a = stack.pop() b = stack.pop() # concatenate them as operand1 + # operand2 + operator temp = a+b+i stack.append(temp) # else if operand else: stack.append(i) # printing final outputprint(*stack)", "e": 5045, "s": 4461, "text": null }, { "code": "// C# Program to convert prefix to postfixusing System;using System.Collections.Generic; class GFG { // function to check if character // is operator or not static bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression static String preToPost(String pre_exp) { Stack<String> s = new Stack<String>(); // length of expression int length = pre_exp.Length; // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack String op1 = s.Peek(); s.Pop(); String op2 = s.Peek(); s.Pop(); // concat the operands and operator String temp = op1 + op2 + pre_exp[i]; // Push String temp back to stack s.Push(temp); } // if symbol is an operand else { // push the operand to the stack s.Push(pre_exp[i] + \"\"); } } // stack contains only the Postfix expression return s.Peek(); } // Driver Code public static void Main(String[] args) { String pre_exp = \"*-A/BC-/AKL\"; Console.WriteLine(\"Postfix : \" + preToPost(pre_exp)); }} /* This code contributed by PrinciRaj1992 */", "e": 6648, "s": 5045, "text": null }, { "code": "<script> // Javascript Program to convert prefix to postfix // function to check if character // is operator or not function isOperator(x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression function preToPost(pre_exp) { let s = []; // length of expression let length = pre_exp.length; // reading from right to left for (let i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack let op1 = s[s.length - 1]; s.pop(); let op2 = s[s.length - 1]; s.pop(); // concat the operands and operator let temp = op1 + op2 + pre_exp[i]; // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(pre_exp[i] + \"\"); } } // stack contains only the Postfix expression return s[s.length - 1]; } let pre_exp = \"*-A/BC-/AKL\"; document.write(\"Postfix : \" + preToPost(pre_exp)); // This code is contributed by suresh07.</script>", "e": 8101, "s": 6648, "text": null }, { "code": null, "e": 8123, "s": 8101, "text": "Postfix : ABC/-AK/L-*" }, { "code": null, "e": 8200, "s": 8123, "text": "Time Complexity: O(N), as we are using a loop for traversing the expression." }, { "code": null, "e": 8262, "s": 8200, "text": "Auxiliary Space: O(N), as we are using stack for extra space." }, { "code": null, "e": 8273, "s": 8262, "text": "andrew1234" }, { "code": null, "e": 8287, "s": 8273, "text": "princiraj1992" }, { "code": null, "e": 8299, "s": 8287, "text": "geekfreek19" }, { "code": null, "e": 8308, "s": 8299, "text": "ninja456" }, { "code": null, "e": 8325, "s": 8308, "text": "akshaysingh98088" }, { "code": null, "e": 8334, "s": 8325, "text": "suresh07" }, { "code": null, "e": 8353, "s": 8334, "text": "rohitkumarsinghcna" }, { "code": null, "e": 8375, "s": 8353, "text": "expression-evaluation" }, { "code": null, "e": 8381, "s": 8375, "text": "Stack" }, { "code": null, "e": 8389, "s": 8381, "text": "Strings" }, { "code": null, "e": 8397, "s": 8389, "text": "Strings" }, { "code": null, "e": 8403, "s": 8397, "text": "Stack" } ]
Check if any K ranges overlap at any point
22 Jun, 2022 Given N ranges [L, R] and an integer K, the task is to check if there are any K ranges that overlap at any point. Examples: Input: ranges[][] = {{1, 3}, {2, 4}, {3, 4}, {7, 10}}, K = 3 Output: Yes 3 is a common point among the ranges {1, 3}, {2, 4} and {3, 4}. Input: ranges[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, K = 2 Output: No Approach: The idea is to make a vector of pairs and store the starting point for every range as pair in this vector as (starting point, -1) and the ending point as (ending point, 1). Now, sort the vector then traverse the vector and if the current element is a starting point then push it into a stack and if it is an ending point then pop an element from the stack. If at any instance of time, the size of the stack is greater than or equal to K then print Yes else print No in the end. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Comparator to sort the vector of pairsbool sortby(const pair<int, int>& a, const pair<int, int>& b){ if (a.first != b.first) return a.first < b.first; return (a.second < b.second);} // Function that returns true if any k// segments overlap at any pointbool kOverlap(vector<pair<int, int> > pairs, int k){ // Vector to store the starting point // and the ending point vector<pair<int, int> > vec; for (int i = 0; i < pairs.size(); i++) { // Starting points are marked by -1 // and ending points by +1 vec.push_back({ pairs[i].first, -1 }); vec.push_back({ pairs[i].second, +1 }); } // Sort the vector by first element sort(vec.begin(), vec.end()); // Stack to store the overlaps stack<pair<int, int> > st; for (int i = 0; i < vec.size(); i++) { // Get the current element pair<int, int> cur = vec[i]; // If it is the starting point if (cur.second == -1) { // Push it in the stack st.push(cur); } // It is the ending point else { // Pop an element from stack st.pop(); } // If more than k ranges overlap if (st.size() >= k) { return true; } } return false;} // Driver codeint main(){ vector<pair<int, int> > pairs; pairs.push_back(make_pair(1, 3)); pairs.push_back(make_pair(2, 4)); pairs.push_back(make_pair(3, 5)); pairs.push_back(make_pair(7, 10)); int n = pairs.size(), k = 3; if (kOverlap(pairs, k)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Stack; class GFG{ static class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} // Function that returns true if any k// segments overlap at any pointstatic boolean kOverlap(ArrayList<Pair> pairs, int k){ // Vector to store the starting point // and the ending point ArrayList<Pair> vec = new ArrayList<>(); for(int i = 0; i < pairs.size(); i++) { // Starting points are marked by -1 // and ending points by +1 vec.add(new Pair(pairs.get(i).first, -1)); vec.add(new Pair(pairs.get(i).second, +1)); } // Sort the vector by first element Collections.sort(vec, new Comparator<Pair>() { // Comparator to sort the vector of pairs public int compare(Pair a, Pair b) { if (a.first != b.first) return a.first - b.first; return (a.second - b.second); } }); // Stack to store the overlaps Stack<Pair> st = new Stack<>(); for(int i = 0; i < vec.size(); i++) { // Get the current element Pair cur = vec.get(i); // If it is the starting point if (cur.second == -1) { // Push it in the stack st.push(cur); } // It is the ending point else { // Pop an element from stack st.pop(); } // If more than k ranges overlap if (st.size() >= k) { return true; } } return false;} // Driver codepublic static void main(String[] args){ ArrayList<Pair> pairs = new ArrayList<>(); pairs.add(new Pair(1, 3)); pairs.add(new Pair(2, 4)); pairs.add(new Pair(3, 5)); pairs.add(new Pair(7, 10)); int n = pairs.size(), k = 3; if (kOverlap(pairs, k)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by sanjeev2552 # Python3 implementation of the approach # Function that returns true if any k# segments overlap at any pointdef kOverlap(pairs: list, k): # Vector to store the starting point # and the ending point vec = list() for i in range(len(pairs)): # Starting points are marked by -1 # and ending points by +1 vec.append((pairs[0], -1)) vec.append((pairs[1], 1)) # Sort the vector by first element vec.sort(key = lambda a: a[0]) # Stack to store the overlaps st = list() for i in range(len(vec)): # Get the current element cur = vec[i] # If it is the starting point if cur[1] == -1: # Push it in the stack st.append(cur) # It is the ending point else: # Pop an element from stack st.pop() # If more than k ranges overlap if len(st) >= k: return True return False # Driver Codeif __name__ == "__main__": pairs = list() pairs.append((1, 3)) pairs.append((2, 4)) pairs.append((3, 5)) pairs.append((7, 10)) n = len(pairs) k = 3 if kOverlap(pairs, k): print("Yes") else: print("No") # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic;class GFG{ // Function that returns true if any k// segments overlap at any pointstatic bool kOverlap(List<Tuple<int,int>> pairs, int k){ // Vector to store the starting point // and the ending point List<Tuple<int,int>> vec = new List<Tuple<int,int>>(); for(int i = 0; i < pairs.Count; i++) { // Starting points are marked by -1 // and ending points by +1 vec.Add(new Tuple<int,int>(pairs[i].Item1,-1)); vec.Add(new Tuple<int,int>(pairs[i].Item2,1)); } vec.Sort(); // Stack to store the overlaps Stack st = new Stack(); for(int i = 0; i < vec.Count; i++) { // Get the current element Tuple<int,int> cur = vec[i]; // If it is the starting point if (cur.Item2 == -1) { // Push it in the stack st.Push(cur); } // It is the ending point else { // Pop an element from stack st.Pop(); } // If more than k ranges overlap if (st.Count >= k) { return true; } } return false;} // Driver codepublic static void Main(params string[] args){ List<Tuple<int,int>> pairs = new List<Tuple<int,int>>(); pairs.Add(new Tuple<int,int>(1, 3)); pairs.Add(new Tuple<int,int>(2, 4)); pairs.Add(new Tuple<int,int>(3, 5)); pairs.Add(new Tuple<int,int>(7, 10)); int n = pairs.Count, k = 3; if (kOverlap(pairs, k)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by rutvik_56/ <script> // JavaScript implementation of the approach // Function that returns true if any k// segments overlap at any pointfunction kOverlap(pairs, k){ // Vector to store the starting point // and the ending point var vec = []; for (var i = 0; i < pairs.length; i++) { // Starting points are marked by -1 // and ending points by +1 vec.push([pairs[i][0], -1 ]); vec.push([pairs[i][1], +1 ]); } // Sort the vector by first element vec.sort((a,b)=>{ if(a[0]!=b[0]) return a[0]-b[0] return a[1]-b[1] }); // Stack to store the overlaps var st = []; for (var i = 0; i < vec.length; i++) { // Get the current element var cur = vec[i]; // If it is the starting point if (cur[1] == -1) { // Push it in the stack st.push(cur); } // It is the ending point else { // Pop an element from stack st.pop(); } // If more than k ranges overlap if (st.length >= k) { return true; } } return false;} // Driver codevar pairs = [];pairs.push([1, 3]);pairs.push([2, 4]);pairs.push([3, 5]);pairs.push([7, 10]);var n = pairs.length, k = 3;if (kOverlap(pairs, k)) document.write( "Yes");else document.write( "No"); </script> Yes Time Complexity: O(N*logN), as we sort an array of size N. Where N is the number of pairs in the array.Auxiliary Space: O(N), as we are using extra space for the array vec and stack st. Where N is the number of pairs in the array. Akanksha_Rai sanjeev2552 rutvik_56 itsok rohitsingh57 cpp-stack-functions Technical Scripter 2019 Searching Stack Technical Scripter Searching Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 142, "s": 28, "text": "Given N ranges [L, R] and an integer K, the task is to check if there are any K ranges that overlap at any point." }, { "code": null, "e": 153, "s": 142, "text": "Examples: " }, { "code": null, "e": 290, "s": 153, "text": "Input: ranges[][] = {{1, 3}, {2, 4}, {3, 4}, {7, 10}}, K = 3 Output: Yes 3 is a common point among the ranges {1, 3}, {2, 4} and {3, 4}." }, { "code": null, "e": 362, "s": 290, "text": "Input: ranges[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, K = 2 Output: No " }, { "code": null, "e": 850, "s": 362, "text": "Approach: The idea is to make a vector of pairs and store the starting point for every range as pair in this vector as (starting point, -1) and the ending point as (ending point, 1). Now, sort the vector then traverse the vector and if the current element is a starting point then push it into a stack and if it is an ending point then pop an element from the stack. If at any instance of time, the size of the stack is greater than or equal to K then print Yes else print No in the end." }, { "code": null, "e": 903, "s": 850, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 907, "s": 903, "text": "C++" }, { "code": null, "e": 912, "s": 907, "text": "Java" }, { "code": null, "e": 920, "s": 912, "text": "Python3" }, { "code": null, "e": 923, "s": 920, "text": "C#" }, { "code": null, "e": 934, "s": 923, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Comparator to sort the vector of pairsbool sortby(const pair<int, int>& a, const pair<int, int>& b){ if (a.first != b.first) return a.first < b.first; return (a.second < b.second);} // Function that returns true if any k// segments overlap at any pointbool kOverlap(vector<pair<int, int> > pairs, int k){ // Vector to store the starting point // and the ending point vector<pair<int, int> > vec; for (int i = 0; i < pairs.size(); i++) { // Starting points are marked by -1 // and ending points by +1 vec.push_back({ pairs[i].first, -1 }); vec.push_back({ pairs[i].second, +1 }); } // Sort the vector by first element sort(vec.begin(), vec.end()); // Stack to store the overlaps stack<pair<int, int> > st; for (int i = 0; i < vec.size(); i++) { // Get the current element pair<int, int> cur = vec[i]; // If it is the starting point if (cur.second == -1) { // Push it in the stack st.push(cur); } // It is the ending point else { // Pop an element from stack st.pop(); } // If more than k ranges overlap if (st.size() >= k) { return true; } } return false;} // Driver codeint main(){ vector<pair<int, int> > pairs; pairs.push_back(make_pair(1, 3)); pairs.push_back(make_pair(2, 4)); pairs.push_back(make_pair(3, 5)); pairs.push_back(make_pair(7, 10)); int n = pairs.size(), k = 3; if (kOverlap(pairs, k)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 2639, "s": 934, "text": null }, { "code": "// Java implementation of the approachimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Stack; class GFG{ static class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} // Function that returns true if any k// segments overlap at any pointstatic boolean kOverlap(ArrayList<Pair> pairs, int k){ // Vector to store the starting point // and the ending point ArrayList<Pair> vec = new ArrayList<>(); for(int i = 0; i < pairs.size(); i++) { // Starting points are marked by -1 // and ending points by +1 vec.add(new Pair(pairs.get(i).first, -1)); vec.add(new Pair(pairs.get(i).second, +1)); } // Sort the vector by first element Collections.sort(vec, new Comparator<Pair>() { // Comparator to sort the vector of pairs public int compare(Pair a, Pair b) { if (a.first != b.first) return a.first - b.first; return (a.second - b.second); } }); // Stack to store the overlaps Stack<Pair> st = new Stack<>(); for(int i = 0; i < vec.size(); i++) { // Get the current element Pair cur = vec.get(i); // If it is the starting point if (cur.second == -1) { // Push it in the stack st.push(cur); } // It is the ending point else { // Pop an element from stack st.pop(); } // If more than k ranges overlap if (st.size() >= k) { return true; } } return false;} // Driver codepublic static void main(String[] args){ ArrayList<Pair> pairs = new ArrayList<>(); pairs.add(new Pair(1, 3)); pairs.add(new Pair(2, 4)); pairs.add(new Pair(3, 5)); pairs.add(new Pair(7, 10)); int n = pairs.size(), k = 3; if (kOverlap(pairs, k)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by sanjeev2552", "e": 4822, "s": 2639, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if any k# segments overlap at any pointdef kOverlap(pairs: list, k): # Vector to store the starting point # and the ending point vec = list() for i in range(len(pairs)): # Starting points are marked by -1 # and ending points by +1 vec.append((pairs[0], -1)) vec.append((pairs[1], 1)) # Sort the vector by first element vec.sort(key = lambda a: a[0]) # Stack to store the overlaps st = list() for i in range(len(vec)): # Get the current element cur = vec[i] # If it is the starting point if cur[1] == -1: # Push it in the stack st.append(cur) # It is the ending point else: # Pop an element from stack st.pop() # If more than k ranges overlap if len(st) >= k: return True return False # Driver Codeif __name__ == \"__main__\": pairs = list() pairs.append((1, 3)) pairs.append((2, 4)) pairs.append((3, 5)) pairs.append((7, 10)) n = len(pairs) k = 3 if kOverlap(pairs, k): print(\"Yes\") else: print(\"No\") # This code is contributed by# sanjeev2552", "e": 6058, "s": 4822, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic;class GFG{ // Function that returns true if any k// segments overlap at any pointstatic bool kOverlap(List<Tuple<int,int>> pairs, int k){ // Vector to store the starting point // and the ending point List<Tuple<int,int>> vec = new List<Tuple<int,int>>(); for(int i = 0; i < pairs.Count; i++) { // Starting points are marked by -1 // and ending points by +1 vec.Add(new Tuple<int,int>(pairs[i].Item1,-1)); vec.Add(new Tuple<int,int>(pairs[i].Item2,1)); } vec.Sort(); // Stack to store the overlaps Stack st = new Stack(); for(int i = 0; i < vec.Count; i++) { // Get the current element Tuple<int,int> cur = vec[i]; // If it is the starting point if (cur.Item2 == -1) { // Push it in the stack st.Push(cur); } // It is the ending point else { // Pop an element from stack st.Pop(); } // If more than k ranges overlap if (st.Count >= k) { return true; } } return false;} // Driver codepublic static void Main(params string[] args){ List<Tuple<int,int>> pairs = new List<Tuple<int,int>>(); pairs.Add(new Tuple<int,int>(1, 3)); pairs.Add(new Tuple<int,int>(2, 4)); pairs.Add(new Tuple<int,int>(3, 5)); pairs.Add(new Tuple<int,int>(7, 10)); int n = pairs.Count, k = 3; if (kOverlap(pairs, k)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by rutvik_56/", "e": 7787, "s": 6058, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function that returns true if any k// segments overlap at any pointfunction kOverlap(pairs, k){ // Vector to store the starting point // and the ending point var vec = []; for (var i = 0; i < pairs.length; i++) { // Starting points are marked by -1 // and ending points by +1 vec.push([pairs[i][0], -1 ]); vec.push([pairs[i][1], +1 ]); } // Sort the vector by first element vec.sort((a,b)=>{ if(a[0]!=b[0]) return a[0]-b[0] return a[1]-b[1] }); // Stack to store the overlaps var st = []; for (var i = 0; i < vec.length; i++) { // Get the current element var cur = vec[i]; // If it is the starting point if (cur[1] == -1) { // Push it in the stack st.push(cur); } // It is the ending point else { // Pop an element from stack st.pop(); } // If more than k ranges overlap if (st.length >= k) { return true; } } return false;} // Driver codevar pairs = [];pairs.push([1, 3]);pairs.push([2, 4]);pairs.push([3, 5]);pairs.push([7, 10]);var n = pairs.length, k = 3;if (kOverlap(pairs, k)) document.write( \"Yes\");else document.write( \"No\"); </script>", "e": 9127, "s": 7787, "text": null }, { "code": null, "e": 9131, "s": 9127, "text": "Yes" }, { "code": null, "e": 9362, "s": 9131, "text": "Time Complexity: O(N*logN), as we sort an array of size N. Where N is the number of pairs in the array.Auxiliary Space: O(N), as we are using extra space for the array vec and stack st. Where N is the number of pairs in the array." }, { "code": null, "e": 9375, "s": 9362, "text": "Akanksha_Rai" }, { "code": null, "e": 9387, "s": 9375, "text": "sanjeev2552" }, { "code": null, "e": 9397, "s": 9387, "text": "rutvik_56" }, { "code": null, "e": 9403, "s": 9397, "text": "itsok" }, { "code": null, "e": 9416, "s": 9403, "text": "rohitsingh57" }, { "code": null, "e": 9436, "s": 9416, "text": "cpp-stack-functions" }, { "code": null, "e": 9460, "s": 9436, "text": "Technical Scripter 2019" }, { "code": null, "e": 9470, "s": 9460, "text": "Searching" }, { "code": null, "e": 9476, "s": 9470, "text": "Stack" }, { "code": null, "e": 9495, "s": 9476, "text": "Technical Scripter" }, { "code": null, "e": 9505, "s": 9495, "text": "Searching" }, { "code": null, "e": 9511, "s": 9505, "text": "Stack" } ]
How to Solve a Production Planning and Inventory Problem in Python | by Khuyen Tran | Towards Data Science
Imagine you are an owner of a clothing store. The demand for clothes varies from day to day (more people prefer to go shopping on the weekend than on the weekday). The production cost also varies from day to day (it costs more to hire workers to work on the weekend). Your job is to determine how many units of clothes to produce each day. Since you can store your clothes, you might decide to produce as many clothes as possible on the cheapest day. However, it costs $1 to store 1 unit per day, so you also need to take into account that the holding cost increases as the number of units being stored increases. How many products should you produce a day so that the total cost is minimized? You can experiment with different numbers of units to produce per day and choose the one with the lowest cost, but this is time-consuming. Luckily, we can solve this problem using Python and linear programming. Linear programming is a mathematical modeling technique in which a linear function is maximized or minimized when subjected to various constraints. CVXPY is a Python tool that provides interfaces to many linear programming solvers. To install CXVPY, type: pip install cxvpy Let’s identify the input parameters, decision variables, objectives, and constraints of this problem. We want to determine how many units to produce and how many units are stored by the end of day t. Note that the ending inventory variable starts at day 0 since the constraints need to know the inventory at the beginning of day 1. We want to minimize the total cost of 4 days. This includes the production cost and the holding cost. Note that since the inventory cost is $1 per unit per day, the ending inventory cost for day t is: We can rewrite the sum as a matrix multiplication like below: The ending inventory is equal to the sum of the beginning inventory and the production quantity of day t subtracted by the demand in day t: In general, we have: The number of units in inventory at the beginning of day 1 is 0: The daily number of units in inventory cannot be negative: The daily production quantity cannot be negative: Wait, but don’t we also need to include the constraints for the demand? That is not necessary. The daily number of units in the ending inventory is equal to or greater than 0, which indicates that the daily demand is fulfilled. Now we have the input parameters, constraints, and objectives, we’re ready to solve the problem! 1890.0 Awesome! The problem is solved and the value of the objective is 1890. This means the optimal solution results in a total cost of $1890. What is the production quantity for days 1, 2, 3, and 4? [ 75. 250. 0. 60.] Let’s also find the ending inventory for each day: [ 0. 100. 0. 0.] Cool! Based on the results, we will: produce just enough to fulfill the demand of day 1 on day 1 produce enough to fulfill the demand of day 2 and 3 on day 2 produce just enough to fulfill the demand of day 3 on day 3 When using a new tool, we should double-check to make sure it gives us an optimal solution. Let’s double-check the solution CXVPY gives us. To do that, we will first create a function to calculate the total cost based on the production quantity of each day. Then we will experiment with different possible combinations. We want to make sure these combinations satisfy the constraints we wrote above. Since the production cost of the first day is the cheapest, let’s see what the total cost would be if we produce every unit needed for 4 days on the first day. 2070 This solution is less optimal than the objective value we got earlier. The total cost of producing everything on the first day is so high can because of the accumulation of the holding cost. What if we produce some on the first day and some on the second day? 2070 This solution is not better either. Okay. What if we prevent the holding cost altogether and only produce enough for each day? 1990 Nope. This solution is still not good. What if we produce everything on the first day and the last day? 1890 Aha! We found a solution that results in the same objective value. That means there are 2 different solutions that produce the same objective value of 1890. This still means that we cannot find a better objective value than 1890. I hope you are convinced that the solution we find above is the optimal solution. If you are still not convinced, feel free to experiment with other possible combinations. Congratulations! You have just learned how to solve production and inventory problems using CXVPY. I hope this article will give you the motivation to solve similar problems using Python. The problem above might be easy to solve in your head. But as the problem becomes bigger, you will save yourself time by using linear programming. The source code of this article could be found here: github.com 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": 440, "s": 172, "text": "Imagine you are an owner of a clothing store. The demand for clothes varies from day to day (more people prefer to go shopping on the weekend than on the weekday). The production cost also varies from day to day (it costs more to hire workers to work on the weekend)." }, { "code": null, "e": 512, "s": 440, "text": "Your job is to determine how many units of clothes to produce each day." }, { "code": null, "e": 786, "s": 512, "text": "Since you can store your clothes, you might decide to produce as many clothes as possible on the cheapest day. However, it costs $1 to store 1 unit per day, so you also need to take into account that the holding cost increases as the number of units being stored increases." }, { "code": null, "e": 866, "s": 786, "text": "How many products should you produce a day so that the total cost is minimized?" }, { "code": null, "e": 1077, "s": 866, "text": "You can experiment with different numbers of units to produce per day and choose the one with the lowest cost, but this is time-consuming. Luckily, we can solve this problem using Python and linear programming." }, { "code": null, "e": 1225, "s": 1077, "text": "Linear programming is a mathematical modeling technique in which a linear function is maximized or minimized when subjected to various constraints." }, { "code": null, "e": 1333, "s": 1225, "text": "CVXPY is a Python tool that provides interfaces to many linear programming solvers. To install CXVPY, type:" }, { "code": null, "e": 1351, "s": 1333, "text": "pip install cxvpy" }, { "code": null, "e": 1453, "s": 1351, "text": "Let’s identify the input parameters, decision variables, objectives, and constraints of this problem." }, { "code": null, "e": 1551, "s": 1453, "text": "We want to determine how many units to produce and how many units are stored by the end of day t." }, { "code": null, "e": 1683, "s": 1551, "text": "Note that the ending inventory variable starts at day 0 since the constraints need to know the inventory at the beginning of day 1." }, { "code": null, "e": 1785, "s": 1683, "text": "We want to minimize the total cost of 4 days. This includes the production cost and the holding cost." }, { "code": null, "e": 1884, "s": 1785, "text": "Note that since the inventory cost is $1 per unit per day, the ending inventory cost for day t is:" }, { "code": null, "e": 1946, "s": 1884, "text": "We can rewrite the sum as a matrix multiplication like below:" }, { "code": null, "e": 2086, "s": 1946, "text": "The ending inventory is equal to the sum of the beginning inventory and the production quantity of day t subtracted by the demand in day t:" }, { "code": null, "e": 2107, "s": 2086, "text": "In general, we have:" }, { "code": null, "e": 2172, "s": 2107, "text": "The number of units in inventory at the beginning of day 1 is 0:" }, { "code": null, "e": 2231, "s": 2172, "text": "The daily number of units in inventory cannot be negative:" }, { "code": null, "e": 2281, "s": 2231, "text": "The daily production quantity cannot be negative:" }, { "code": null, "e": 2509, "s": 2281, "text": "Wait, but don’t we also need to include the constraints for the demand? That is not necessary. The daily number of units in the ending inventory is equal to or greater than 0, which indicates that the daily demand is fulfilled." }, { "code": null, "e": 2606, "s": 2509, "text": "Now we have the input parameters, constraints, and objectives, we’re ready to solve the problem!" }, { "code": null, "e": 2613, "s": 2606, "text": "1890.0" }, { "code": null, "e": 2750, "s": 2613, "text": "Awesome! The problem is solved and the value of the objective is 1890. This means the optimal solution results in a total cost of $1890." }, { "code": null, "e": 2807, "s": 2750, "text": "What is the production quantity for days 1, 2, 3, and 4?" }, { "code": null, "e": 2829, "s": 2807, "text": "[ 75. 250. 0. 60.]" }, { "code": null, "e": 2880, "s": 2829, "text": "Let’s also find the ending inventory for each day:" }, { "code": null, "e": 2902, "s": 2880, "text": "[ 0. 100. 0. 0.]" }, { "code": null, "e": 2939, "s": 2902, "text": "Cool! Based on the results, we will:" }, { "code": null, "e": 2999, "s": 2939, "text": "produce just enough to fulfill the demand of day 1 on day 1" }, { "code": null, "e": 3060, "s": 2999, "text": "produce enough to fulfill the demand of day 2 and 3 on day 2" }, { "code": null, "e": 3120, "s": 3060, "text": "produce just enough to fulfill the demand of day 3 on day 3" }, { "code": null, "e": 3260, "s": 3120, "text": "When using a new tool, we should double-check to make sure it gives us an optimal solution. Let’s double-check the solution CXVPY gives us." }, { "code": null, "e": 3378, "s": 3260, "text": "To do that, we will first create a function to calculate the total cost based on the production quantity of each day." }, { "code": null, "e": 3520, "s": 3378, "text": "Then we will experiment with different possible combinations. We want to make sure these combinations satisfy the constraints we wrote above." }, { "code": null, "e": 3680, "s": 3520, "text": "Since the production cost of the first day is the cheapest, let’s see what the total cost would be if we produce every unit needed for 4 days on the first day." }, { "code": null, "e": 3685, "s": 3680, "text": "2070" }, { "code": null, "e": 3756, "s": 3685, "text": "This solution is less optimal than the objective value we got earlier." }, { "code": null, "e": 3945, "s": 3756, "text": "The total cost of producing everything on the first day is so high can because of the accumulation of the holding cost. What if we produce some on the first day and some on the second day?" }, { "code": null, "e": 3950, "s": 3945, "text": "2070" }, { "code": null, "e": 3986, "s": 3950, "text": "This solution is not better either." }, { "code": null, "e": 4077, "s": 3986, "text": "Okay. What if we prevent the holding cost altogether and only produce enough for each day?" }, { "code": null, "e": 4082, "s": 4077, "text": "1990" }, { "code": null, "e": 4121, "s": 4082, "text": "Nope. This solution is still not good." }, { "code": null, "e": 4186, "s": 4121, "text": "What if we produce everything on the first day and the last day?" }, { "code": null, "e": 4191, "s": 4186, "text": "1890" }, { "code": null, "e": 4421, "s": 4191, "text": "Aha! We found a solution that results in the same objective value. That means there are 2 different solutions that produce the same objective value of 1890. This still means that we cannot find a better objective value than 1890." }, { "code": null, "e": 4593, "s": 4421, "text": "I hope you are convinced that the solution we find above is the optimal solution. If you are still not convinced, feel free to experiment with other possible combinations." }, { "code": null, "e": 4781, "s": 4593, "text": "Congratulations! You have just learned how to solve production and inventory problems using CXVPY. I hope this article will give you the motivation to solve similar problems using Python." }, { "code": null, "e": 4928, "s": 4781, "text": "The problem above might be easy to solve in your head. But as the problem becomes bigger, you will save yourself time by using linear programming." }, { "code": null, "e": 4981, "s": 4928, "text": "The source code of this article could be found here:" }, { "code": null, "e": 4992, "s": 4981, "text": "github.com" }, { "code": null, "e": 5152, "s": 4992, "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." } ]
Bitcoin Price Prediction Using Time Series Forecasting | by Ayushi Asthana | Towards Data Science
This article is about predicting bitcoin price using time series forecasting. Time series forecasting is quite different from other machine learning models because - 1. It is time dependent. So, the basic assumption of a linear regression model that the observations are independent doesn’t hold in this case. 2. Along with an increasing or decreasing trend, most time series have some form of seasonality trends, i.e. variations specific to a particular time frame. Therefore simple machine learning models cannot be used and hence time series forecasting is a different area of research. In this article time series models like AR( Auto Regressive model), MA (Moving Average model) and ARIMA (Autoregressive Integrated Moving Average model) are used for forecasting the price of bitcoin. The dataset contains the opening and closing prices of bitcoins from April 2013 to August 2017 import pandas as kunfuimport numpy as dragonimport pylab as pimport matplotlib.pyplot as plotfrom collections import Counterimport re#importing packages for the prediction of time-series dataimport statsmodels.api as smimport statsmodels.tsa.api as smtimport statsmodels.formula.api as smffrom sklearn.metrics import mean_squared_error The data is loaded from a csv file into train dataframe. This is how first five rows of our data look like. Using date as index the series is plotted with Date on x axis and closing price on y axis. data = train['Close']Date1 = train['Date']train1 = train[['Date','Close']]# Setting the Date as Indextrain2 = train1.set_index('Date')train2.sort_index(inplace=True)print (type(train2))print (train2.head())plot.plot(train2)plot.xlabel('Date', fontsize=12)plot.ylabel('Price in USD', fontsize=12)plot.title("Closing price distribution of bitcoin", fontsize=15)plot.show() Augmented Dicky Fuller Test: The Augmented Dicky Fuller test is a type of statistical test called a unit root test. The intuition behind a unit root test is that it determines how strongly a time series is defined by a trend. There are no. of unit root tests and ADF is one of the most widely used 1. Null Hypothesis (H0): Null hypothesis of the test is that the time series can be represented by a unit root that is not stationary. 2. Alternative Hypothesis (H1): Alternative Hypothesis of the test is that the time series is stationary. Interpretation of p value 1. p value > 0.05: Accepts the Null Hypothesis (H0), the data has a unit root and is non-stationary. 2. p value < = 0.05: Rejects the Null Hypothesis (H0), the data is stationary. from statsmodels.tsa.stattools import adfullerdef test_stationarity(x): #Determing rolling statistics rolmean = x.rolling(window=22,center=False).mean() rolstd = x.rolling(window=12,center=False).std() #Plot rolling statistics: orig = plot.plot(x, color='blue',label='Original') mean = plot.plot(rolmean, color='red', label='Rolling Mean') std = plot.plot(rolstd, color='black', label = 'Rolling Std') plot.legend(loc='best') plot.title('Rolling Mean & Standard Deviation') plot.show(block=False) #Perform Dickey Fuller test result=adfuller(x) print('ADF Stastistic: %f'%result[0]) print('p-value: %f'%result[1]) pvalue=result[1] for key,value in result[4].items(): if result[0]>value: print("The graph is non stationery") break else: print("The graph is stationery") break; print('Critical values:') for key,value in result[4].items(): print('\t%s: %.3f ' % (key, value)) ts = train2['Close'] test_stationarity(ts) Since the p value is greater than 0.05 the time series is non stationary. Okay so far we tested the series and it is non stationary. So there is some work that needs to be done here. So now we use transformations to make the series stationary. Log transformation is used to unskew highly skewed data. Thus helping in forecasting process. ts_log = dragon.log(ts)plot.plot(ts_log,color="green")plot.show()test_stationarity(ts_log) The series is still non stationary as p value is still greater than 0.05 so we need to make further transformations. So let’s go ahead with differencing. In case of differencing to make the time series stationary the current value is subtracted with the previous values. Due to this the mean is stabilized and hence the chances of stationarity of time series are increased. ts_log_diff = ts_log - ts_log.shift()plot.plot(ts_log_diff)plot.show() ts_log_diff.dropna(inplace=True)test_stationarity(ts_log_diff) As our time series is now stationary asour p value is less than 0.05 therefore we can apply time series forecasting models. Auto regressive model is a time series forecasting model where current values are dependent on past values. # follow lagmodel = ARIMA(ts_log, order=(1,1,0)) results_ARIMA = model.fit(disp=-1) plot.plot(ts_log_diff)plot.plot(results_ARIMA.fittedvalues, color='red')plot.title('RSS: %.7f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2))plot.show() In moving average model the series is dependent on past error terms. # follow errormodel = ARIMA(ts_log, order=(0,1,1)) results_MA = model.fit(disp=-1) plot.plot(ts_log_diff)plot.plot(results_MA.fittedvalues, color='red')plot.title('RSS: %.7f'% sum((results_MA.fittedvalues-ts_log_diff)**2))plot.show() It is a combination of both AR and MA models. It makes the time series stationary by itself through the process of differencing. Therefore differencing need not be done explicitly for ARIMA model from statsmodels.tsa.arima_model import ARIMAmodel = ARIMA(ts_log, order=(2,1,0)) results_ARIMA = model.fit(disp=-1) plot.plot(ts_log_diff)plot.plot(results_ARIMA.fittedvalues, color='red')plot.title('RSS: %.7f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2))plot.show() Thus we see that the RSS (Residual Sum of Squares) error is minimum for ARIMA model. Therefore ARIMA model is the best among the three models because of use of dependence on both lagged values and error terms. Therefore it is further used to calculate the mean square error. Here in the below code snippet the dataset is divided into train and test. For every value in the test test we apply an ARIMA model and then the error is calculated and then after iterating over all values in the test set the mean error between predicted and expected value is calculated. size = int(len(ts_log)-100)# Divide into train and testtrain_arima, test_arima = ts_log[0:size], ts_log[size:len(ts_log)]history = [x for x in train_arima]predictions = list()originals = list()error_list = list()print('Printing Predicted vs Expected Values...')print('\n')# We go over each value in the test set and then apply ARIMA model and calculate the predicted value. We have the expected value in the test set therefore we calculate the error between predicted and expected value for t in range(len(test_arima)): model = ARIMA(history, order=(2, 1, 0)) model_fit = model.fit(disp=-1) output = model_fit.forecast() pred_value = output[0] original_value = test_arima[t] history.append(original_value) pred_value = dragon.exp(pred_value) original_value = dragon.exp(original_value) # Calculating the error error = ((abs(pred_value - original_value)) / original_value) * 100 error_list.append(error) print('predicted = %f, expected = %f, error = %f ' % (pred_value, original_value, error), '%') predictions.append(float(pred_value)) originals.append(float(original_value)) # After iterating over whole test set the overall mean error is calculated. print('\n Mean Error in Predicting Test Case Articles : %f ' % (sum(error_list)/float(len(error_list))), '%')plot.figure(figsize=(8, 6))test_day = [t for t in range(len(test_arima))]labels={'Orginal','Predicted'}plot.plot(test_day, predictions, color= 'green')plot.plot(test_day, originals, color = 'orange')plot.title('Expected Vs Predicted Views Forecasting')plot.xlabel('Day')plot.ylabel('Closing Price')plot.legend(labels)plot.show() predicted = 2513.745189, expected = 2564.060000, error = 1.962310 %predicted = 2566.007269, expected = 2601.640000, error = 1.369626 %predicted = 2604.348629, expected = 2601.990000, error = 0.090647 %predicted = 2605.558976, expected = 2608.560000, error = 0.115045 %predicted = 2613.835793, expected = 2518.660000, error = 3.778827 %predicted = 2523.203681, expected = 2571.340000, error = 1.872032 %predicted = 2580.654927, expected = 2518.440000, error = 2.470376 %predicted = 2521.053567, expected = 2372.560000, error = 6.258791 %predicted = 2379.066829, expected = 2337.790000, error = 1.765635 %predicted = 2348.468544, expected = 2398.840000, error = 2.099826 %predicted = 2405.299995, expected = 2357.900000, error = 2.010263 %predicted = 2359.650935, expected = 2233.340000, error = 5.655697 %predicted = 2239.002236, expected = 1998.860000, error = 12.013960 %predicted = 2006.206534, expected = 1929.820000, error = 3.958221 %predicted = 1942.244784, expected = 2228.410000, error = 12.841677 %predicted = 2238.150016, expected = 2318.880000, error = 3.481421 %predicted = 2307.325788, expected = 2273.430000, error = 1.490954 %predicted = 2272.890197, expected = 2817.600000, error = 19.332404 %predicted = 2829.051277, expected = 2667.760000, error = 6.045944 %predicted = 2646.110662, expected = 2810.120000, error = 5.836382 %predicted = 2822.356853, expected = 2730.400000, error = 3.367889 %predicted = 2730.087031, expected = 2754.860000, error = 0.899246 %predicted = 2763.766195, expected = 2576.480000, error = 7.269072 %predicted = 2580.946838, expected = 2529.450000, error = 2.035891 %predicted = 2541.493507, expected = 2671.780000, error = 4.876393 %predicted = 2679.029936, expected = 2809.010000, error = 4.627255 %predicted = 2808.092238, expected = 2726.450000, error = 2.994452 %predicted = 2726.150588, expected = 2757.180000, error = 1.125404 %predicted = 2766.298163, expected = 2875.340000, error = 3.792311 % Mean Error in Predicting Test Case Articles : 3.593133 % Therefore the original and predicted time series is plotted with mean error of 3.59%.Therefore we were able to use different transformations and models to predict the closing price of bitcoin. Thank you if you read till the last. This is my first article on towards data science and there are many more to come. If you find any mistake or have any suggestions please do comment. If you liked the post please don’t forget to clap ! Thankyou.
[ { "code": null, "e": 338, "s": 172, "text": "This article is about predicting bitcoin price using time series forecasting. Time series forecasting is quite different from other machine learning models because -" }, { "code": null, "e": 482, "s": 338, "text": "1. It is time dependent. So, the basic assumption of a linear regression model that the observations are independent doesn’t hold in this case." }, { "code": null, "e": 639, "s": 482, "text": "2. Along with an increasing or decreasing trend, most time series have some form of seasonality trends, i.e. variations specific to a particular time frame." }, { "code": null, "e": 962, "s": 639, "text": "Therefore simple machine learning models cannot be used and hence time series forecasting is a different area of research. In this article time series models like AR( Auto Regressive model), MA (Moving Average model) and ARIMA (Autoregressive Integrated Moving Average model) are used for forecasting the price of bitcoin." }, { "code": null, "e": 1057, "s": 962, "text": "The dataset contains the opening and closing prices of bitcoins from April 2013 to August 2017" }, { "code": null, "e": 1393, "s": 1057, "text": "import pandas as kunfuimport numpy as dragonimport pylab as pimport matplotlib.pyplot as plotfrom collections import Counterimport re#importing packages for the prediction of time-series dataimport statsmodels.api as smimport statsmodels.tsa.api as smtimport statsmodels.formula.api as smffrom sklearn.metrics import mean_squared_error" }, { "code": null, "e": 1501, "s": 1393, "text": "The data is loaded from a csv file into train dataframe. This is how first five rows of our data look like." }, { "code": null, "e": 1592, "s": 1501, "text": "Using date as index the series is plotted with Date on x axis and closing price on y axis." }, { "code": null, "e": 1963, "s": 1592, "text": "data = train['Close']Date1 = train['Date']train1 = train[['Date','Close']]# Setting the Date as Indextrain2 = train1.set_index('Date')train2.sort_index(inplace=True)print (type(train2))print (train2.head())plot.plot(train2)plot.xlabel('Date', fontsize=12)plot.ylabel('Price in USD', fontsize=12)plot.title(\"Closing price distribution of bitcoin\", fontsize=15)plot.show()" }, { "code": null, "e": 1992, "s": 1963, "text": "Augmented Dicky Fuller Test:" }, { "code": null, "e": 2079, "s": 1992, "text": "The Augmented Dicky Fuller test is a type of statistical test called a unit root test." }, { "code": null, "e": 2189, "s": 2079, "text": "The intuition behind a unit root test is that it determines how strongly a time series is defined by a trend." }, { "code": null, "e": 2261, "s": 2189, "text": "There are no. of unit root tests and ADF is one of the most widely used" }, { "code": null, "e": 2396, "s": 2261, "text": "1. Null Hypothesis (H0): Null hypothesis of the test is that the time series can be represented by a unit root that is not stationary." }, { "code": null, "e": 2502, "s": 2396, "text": "2. Alternative Hypothesis (H1): Alternative Hypothesis of the test is that the time series is stationary." }, { "code": null, "e": 2528, "s": 2502, "text": "Interpretation of p value" }, { "code": null, "e": 2629, "s": 2528, "text": "1. p value > 0.05: Accepts the Null Hypothesis (H0), the data has a unit root and is non-stationary." }, { "code": null, "e": 2708, "s": 2629, "text": "2. p value < = 0.05: Rejects the Null Hypothesis (H0), the data is stationary." }, { "code": null, "e": 3769, "s": 2708, "text": "from statsmodels.tsa.stattools import adfullerdef test_stationarity(x): #Determing rolling statistics rolmean = x.rolling(window=22,center=False).mean() rolstd = x.rolling(window=12,center=False).std() #Plot rolling statistics: orig = plot.plot(x, color='blue',label='Original') mean = plot.plot(rolmean, color='red', label='Rolling Mean') std = plot.plot(rolstd, color='black', label = 'Rolling Std') plot.legend(loc='best') plot.title('Rolling Mean & Standard Deviation') plot.show(block=False) #Perform Dickey Fuller test result=adfuller(x) print('ADF Stastistic: %f'%result[0]) print('p-value: %f'%result[1]) pvalue=result[1] for key,value in result[4].items(): if result[0]>value: print(\"The graph is non stationery\") break else: print(\"The graph is stationery\") break; print('Critical values:') for key,value in result[4].items(): print('\\t%s: %.3f ' % (key, value)) ts = train2['Close'] test_stationarity(ts)" }, { "code": null, "e": 4013, "s": 3769, "text": "Since the p value is greater than 0.05 the time series is non stationary. Okay so far we tested the series and it is non stationary. So there is some work that needs to be done here. So now we use transformations to make the series stationary." }, { "code": null, "e": 4107, "s": 4013, "text": "Log transformation is used to unskew highly skewed data. Thus helping in forecasting process." }, { "code": null, "e": 4198, "s": 4107, "text": "ts_log = dragon.log(ts)plot.plot(ts_log,color=\"green\")plot.show()test_stationarity(ts_log)" }, { "code": null, "e": 4352, "s": 4198, "text": "The series is still non stationary as p value is still greater than 0.05 so we need to make further transformations. So let’s go ahead with differencing." }, { "code": null, "e": 4572, "s": 4352, "text": "In case of differencing to make the time series stationary the current value is subtracted with the previous values. Due to this the mean is stabilized and hence the chances of stationarity of time series are increased." }, { "code": null, "e": 4643, "s": 4572, "text": "ts_log_diff = ts_log - ts_log.shift()plot.plot(ts_log_diff)plot.show()" }, { "code": null, "e": 4706, "s": 4643, "text": "ts_log_diff.dropna(inplace=True)test_stationarity(ts_log_diff)" }, { "code": null, "e": 4830, "s": 4706, "text": "As our time series is now stationary asour p value is less than 0.05 therefore we can apply time series forecasting models." }, { "code": null, "e": 4938, "s": 4830, "text": "Auto regressive model is a time series forecasting model where current values are dependent on past values." }, { "code": null, "e": 5181, "s": 4938, "text": "# follow lagmodel = ARIMA(ts_log, order=(1,1,0)) results_ARIMA = model.fit(disp=-1) plot.plot(ts_log_diff)plot.plot(results_ARIMA.fittedvalues, color='red')plot.title('RSS: %.7f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2))plot.show()" }, { "code": null, "e": 5250, "s": 5181, "text": "In moving average model the series is dependent on past error terms." }, { "code": null, "e": 5486, "s": 5250, "text": "# follow errormodel = ARIMA(ts_log, order=(0,1,1)) results_MA = model.fit(disp=-1) plot.plot(ts_log_diff)plot.plot(results_MA.fittedvalues, color='red')plot.title('RSS: %.7f'% sum((results_MA.fittedvalues-ts_log_diff)**2))plot.show()" }, { "code": null, "e": 5682, "s": 5486, "text": "It is a combination of both AR and MA models. It makes the time series stationary by itself through the process of differencing. Therefore differencing need not be done explicitly for ARIMA model" }, { "code": null, "e": 5958, "s": 5682, "text": "from statsmodels.tsa.arima_model import ARIMAmodel = ARIMA(ts_log, order=(2,1,0)) results_ARIMA = model.fit(disp=-1) plot.plot(ts_log_diff)plot.plot(results_ARIMA.fittedvalues, color='red')plot.title('RSS: %.7f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2))plot.show()" }, { "code": null, "e": 6308, "s": 5958, "text": "Thus we see that the RSS (Residual Sum of Squares) error is minimum for ARIMA model. Therefore ARIMA model is the best among the three models because of use of dependence on both lagged values and error terms. Therefore it is further used to calculate the mean square error. Here in the below code snippet the dataset is divided into train and test." }, { "code": null, "e": 6522, "s": 6308, "text": "For every value in the test test we apply an ARIMA model and then the error is calculated and then after iterating over all values in the test set the mean error between predicted and expected value is calculated." }, { "code": null, "e": 8213, "s": 6522, "text": "size = int(len(ts_log)-100)# Divide into train and testtrain_arima, test_arima = ts_log[0:size], ts_log[size:len(ts_log)]history = [x for x in train_arima]predictions = list()originals = list()error_list = list()print('Printing Predicted vs Expected Values...')print('\\n')# We go over each value in the test set and then apply ARIMA model and calculate the predicted value. We have the expected value in the test set therefore we calculate the error between predicted and expected value for t in range(len(test_arima)): model = ARIMA(history, order=(2, 1, 0)) model_fit = model.fit(disp=-1) output = model_fit.forecast() pred_value = output[0] original_value = test_arima[t] history.append(original_value) pred_value = dragon.exp(pred_value) original_value = dragon.exp(original_value) # Calculating the error error = ((abs(pred_value - original_value)) / original_value) * 100 error_list.append(error) print('predicted = %f, expected = %f, error = %f ' % (pred_value, original_value, error), '%') predictions.append(float(pred_value)) originals.append(float(original_value)) # After iterating over whole test set the overall mean error is calculated. print('\\n Mean Error in Predicting Test Case Articles : %f ' % (sum(error_list)/float(len(error_list))), '%')plot.figure(figsize=(8, 6))test_day = [t for t in range(len(test_arima))]labels={'Orginal','Predicted'}plot.plot(test_day, predictions, color= 'green')plot.plot(test_day, originals, color = 'orange')plot.title('Expected Vs Predicted Views Forecasting')plot.xlabel('Day')plot.ylabel('Closing Price')plot.legend(labels)plot.show()" }, { "code": null, "e": 10160, "s": 8213, "text": "predicted = 2513.745189, expected = 2564.060000, error = 1.962310 %predicted = 2566.007269, expected = 2601.640000, error = 1.369626 %predicted = 2604.348629, expected = 2601.990000, error = 0.090647 %predicted = 2605.558976, expected = 2608.560000, error = 0.115045 %predicted = 2613.835793, expected = 2518.660000, error = 3.778827 %predicted = 2523.203681, expected = 2571.340000, error = 1.872032 %predicted = 2580.654927, expected = 2518.440000, error = 2.470376 %predicted = 2521.053567, expected = 2372.560000, error = 6.258791 %predicted = 2379.066829, expected = 2337.790000, error = 1.765635 %predicted = 2348.468544, expected = 2398.840000, error = 2.099826 %predicted = 2405.299995, expected = 2357.900000, error = 2.010263 %predicted = 2359.650935, expected = 2233.340000, error = 5.655697 %predicted = 2239.002236, expected = 1998.860000, error = 12.013960 %predicted = 2006.206534, expected = 1929.820000, error = 3.958221 %predicted = 1942.244784, expected = 2228.410000, error = 12.841677 %predicted = 2238.150016, expected = 2318.880000, error = 3.481421 %predicted = 2307.325788, expected = 2273.430000, error = 1.490954 %predicted = 2272.890197, expected = 2817.600000, error = 19.332404 %predicted = 2829.051277, expected = 2667.760000, error = 6.045944 %predicted = 2646.110662, expected = 2810.120000, error = 5.836382 %predicted = 2822.356853, expected = 2730.400000, error = 3.367889 %predicted = 2730.087031, expected = 2754.860000, error = 0.899246 %predicted = 2763.766195, expected = 2576.480000, error = 7.269072 %predicted = 2580.946838, expected = 2529.450000, error = 2.035891 %predicted = 2541.493507, expected = 2671.780000, error = 4.876393 %predicted = 2679.029936, expected = 2809.010000, error = 4.627255 %predicted = 2808.092238, expected = 2726.450000, error = 2.994452 %predicted = 2726.150588, expected = 2757.180000, error = 1.125404 %predicted = 2766.298163, expected = 2875.340000, error = 3.792311 %" }, { "code": null, "e": 10217, "s": 10160, "text": "Mean Error in Predicting Test Case Articles : 3.593133 %" }, { "code": null, "e": 10410, "s": 10217, "text": "Therefore the original and predicted time series is plotted with mean error of 3.59%.Therefore we were able to use different transformations and models to predict the closing price of bitcoin." } ]
Shortest Path in a Directed Acyclic Graph
One weighted directed acyclic graph is given. Another source vertex is also provided. Now we have to find the shortest distance from the starting node to all other vertices, in the graph. To detect Smaller distance, we can use another algorithm like Bellman-Ford for the graph with negative weight, for positive weight the Dijkstra’s algorithm is also helpful. Here for Directed Acyclic Graph, we will use the topological sorting technique to reduce complexity. Input: The cost matrix of the graph. 0 5 3 -∞ -∞ -∞ -∞ 0 2 6 -∞ -∞ -∞ -∞ 0 7 4 2 -∞ -∞ -∞ 0 -1 1 -∞ -∞ -∞ -∞ 0 -2 -∞ -∞ -∞ -∞ -∞ 0 Output: Shortest Distance from Source Vertex 1 Infinity 0 2 6 5 3 topoSort(u, visited, stack) Input: starting node u, the visited list to keep track, the stack.Output: Sort the nodes in a topological way. Begin mark u as visited for all vertex v, which is connected with u, do if v is not visited, then topoSort(v, visited, stack) done push u into the stack End shortestPath(start) Input − The starting node.Output − List of the shortest distance of all vertices from the starting node. Begin initially make all nodes as unvisited for each node i, in the graph, do if i is not visited, then topoSort(i, visited, stack) done make distance of all vertices as ∞ dist[start] := 0 while stack is not empty, do pop stack item and take into nextVert if dist[nextVert] ≠∞, then for each vertices v, which is adjacent with nextVert, do if cost[nextVert, v] ≠∞, then if dist[v] > dist[nectVert] + cost[nextVert, v], then dist[v] := dist[nectVert] + cost[nextVert, v] done done for all vertices i in the graph, do if dist[i] = ∞, then display Infinity else display dist[i] done End #include<iostream> #include<stack> #define NODE 6 #define INF 9999 using namespace std; int cost[NODE][NODE] = { {0, 5, 3, INF, INF, INF}, {INF, 0, 2, 6, INF, INF}, {INF, INF, 0, 7, 4, 2}, {INF, INF, INF, 0, -1, 1}, {INF, INF, INF, INF, 0, -2}, {INF, INF, INF, INF, INF, 0} }; void topoSort(int u, bool visited[], stack<int>&stk) { visited[u] = true; //set as the node v is visited for(int v = 0; v<NODE; v++) { if(cost[u][v]) { //for allvertices v adjacent to u if(!visited[v]) topoSort(v, visited, stk); } } stk.push(u); //push starting vertex into the stack } void shortestPath(int start) { stack<int> stk; int dist[NODE]; bool vis[NODE]; for(int i = 0; i<NODE;i++) vis[i] = false; // make all nodes as unvisited at first for(int i = 0; i<NODE; i++) //perform topological sort for vertices if(!vis[i]) topoSort(i, vis, stk); for(int i = 0; i<NODE; i++) dist[i] = INF; //initially all distances are infinity dist[start] = 0; //distance for start vertex is 0 while(!stk.empty()) { //when stack contains element, process in topological order int nextVert = stk.top(); stk.pop(); if(dist[nextVert] != INF) { for(int v = 0; v<NODE; v++) { if(cost[nextVert][v] && cost[nextVert][v] != INF){ if(dist[v] > dist[nextVert] +cost[nextVert][v])dist[v] = dist[nextVert] + cost[nextVert][v]; } } } for(int i = 0; i<NODE; i++) (dist[i] == INF)?cout << "Infinity ":cout << dist[i]<<" "; } main() { int start = 1; cout << "Shortest Distance From Source Vertex "<<start<<endl; shortestPath(start); } Shortest Distance From Source Vertex 1 Infinity 0 2 6 5 3
[ { "code": null, "e": 1250, "s": 1062, "text": "One weighted directed acyclic graph is given. Another source vertex is also provided. Now we have to find the shortest distance from the starting node to all other vertices, in the graph." }, { "code": null, "e": 1524, "s": 1250, "text": "To detect Smaller distance, we can use another algorithm like Bellman-Ford for the graph with negative weight, for positive weight the Dijkstra’s algorithm is also helpful. Here for Directed Acyclic Graph, we will use the topological sorting technique to reduce complexity." }, { "code": null, "e": 1736, "s": 1524, "text": "Input:\nThe cost matrix of the graph.\n0 5 3 -∞ -∞ -∞\n-∞ 0 2 6 -∞ -∞\n-∞ -∞ 0 7 4 2\n-∞ -∞ -∞ 0 -1 1\n-∞ -∞ -∞ -∞ 0 -2\n-∞ -∞ -∞ -∞ -∞ 0\n\nOutput:\nShortest Distance from Source Vertex 1\nInfinity 0 2 6 5 3" }, { "code": null, "e": 1764, "s": 1736, "text": "topoSort(u, visited, stack)" }, { "code": null, "e": 1875, "s": 1764, "text": "Input: starting node u, the visited list to keep track, the stack.Output: Sort the nodes in a topological way." }, { "code": null, "e": 2059, "s": 1875, "text": "Begin\n mark u as visited\n for all vertex v, which is connected with u, do\n if v is not visited, then\n topoSort(v, visited, stack)\n done\n push u into the stack\nEnd" }, { "code": null, "e": 2079, "s": 2059, "text": "shortestPath(start)" }, { "code": null, "e": 2184, "s": 2079, "text": "Input − The starting node.Output − List of the shortest distance of all vertices from the starting node." }, { "code": null, "e": 2919, "s": 2184, "text": "Begin\n initially make all nodes as unvisited\n for each node i, in the graph, do\n if i is not visited, then\n topoSort(i, visited, stack)\n done\n\n make distance of all vertices as ∞\n dist[start] := 0\n while stack is not empty, do\n pop stack item and take into nextVert\n if dist[nextVert] ≠∞, then\n for each vertices v, which is adjacent with nextVert, do\n if cost[nextVert, v] ≠∞, then\n if dist[v] > dist[nectVert] + cost[nextVert, v], then\n dist[v] := dist[nectVert] + cost[nextVert, v]\n done\n done\n\n for all vertices i in the graph, do\n if dist[i] = ∞, then\n display Infinity\n else\n display dist[i]\n done\nEnd" }, { "code": null, "e": 4644, "s": 2919, "text": "#include<iostream>\n#include<stack>\n#define NODE 6\n#define INF 9999\n\nusing namespace std;\n\nint cost[NODE][NODE] = {\n {0, 5, 3, INF, INF, INF},\n {INF, 0, 2, 6, INF, INF},\n {INF, INF, 0, 7, 4, 2},\n {INF, INF, INF, 0, -1, 1},\n {INF, INF, INF, INF, 0, -2},\n {INF, INF, INF, INF, INF, 0}\n};\n\nvoid topoSort(int u, bool visited[], stack<int>&stk) {\n visited[u] = true; //set as the node v is visited\n for(int v = 0; v<NODE; v++) {\n if(cost[u][v]) { //for allvertices v adjacent to u\n if(!visited[v])\n topoSort(v, visited, stk);\n }\n }\n\n stk.push(u); //push starting vertex into the stack\n}\n\nvoid shortestPath(int start) {\n stack<int> stk;\n int dist[NODE];\n\n bool vis[NODE];\n for(int i = 0; i<NODE;i++)\n vis[i] = false; // make all nodes as unvisited at first\n\n for(int i = 0; i<NODE; i++) //perform topological sort for vertices\n if(!vis[i])\n topoSort(i, vis, stk);\n\n for(int i = 0; i<NODE; i++)\n dist[i] = INF; //initially all distances are infinity\n dist[start] = 0; //distance for start vertex is 0\n\n while(!stk.empty()) { //when stack contains element, process in topological order\n int nextVert = stk.top(); stk.pop();\n\n if(dist[nextVert] != INF) {\n for(int v = 0; v<NODE; v++) {\n if(cost[nextVert][v] && cost[nextVert][v] != INF){ if(dist[v] > dist[nextVert] +cost[nextVert][v])dist[v] = dist[nextVert] + cost[nextVert][v];\n }\n }\n }\n for(int i = 0; i<NODE; i++)\n (dist[i] == INF)?cout << \"Infinity \":cout << dist[i]<<\" \";\n}\n\nmain() {\n int start = 1;\n cout << \"Shortest Distance From Source Vertex \"<<start<<endl;\n shortestPath(start);\n}" }, { "code": null, "e": 4702, "s": 4644, "text": "Shortest Distance From Source Vertex 1\nInfinity 0 2 6 5 3" } ]
A brief guide to data imputation with Python and R | by Pavlo Horbonos | Towards Data Science
We all know, that data cleaning is one of the most time-consuming stages in the data analysis process. We need to acquire missing values, check their distribution, figure out the patterns, and make a decision on how to fill the spaces. At this point you should realize, that identification of missing data patterns and correct imputation process will influence further analysis. So, let me introduces a few technics for the common analysis languages: R and Python. Before we start the imputation process, we should acquire the data first and find the patterns or schemes of missing data. In simple words, there are two general types of missing data: MCAR and MNAR. MNAR (missing not at random) is the most serious issue with data. It means, that we need to find the dependencies between missing features, and start the data gathering process. It turns in some kind of analysis step, which involves the work with different data sources, analysis of connections, and search of alternative data. MCAR (missing completely at random) means that there are no deep patterns in missing values, so we can work with that and decide if some rows/features may be removed or imputed. It is something we can deal with but only within empirical borders because there can be too much missing data (in the percentage of total records). So, in illustration purposes we will use the next toy-example: We can see the impact on multiple missing values, numeric, and categorical missing values. R programming language has a great community, which adds a lot of packages and libraries to the R development warehouse. So, that’s not a surprise, that we have the MICE package. It includes a lot of functionality connected with multivariate imputation with chained equations (that is MICE algorithm). You can dive deep into the documentation for details, but I will give the basic example. Firstly, let’s see the pattern of the missing data on our toy-example mentioned above: library(mice)md.pattern(df_test) Mice package has built-in tool md.pattern(), which shows the distribution of missing values and combinations of missing features. You can read more about this tool in my previous article about missing data acquainting with R. Also this function gives us a pretty illustration: Work with a mice-imputer is provided within two stages. At the first stage, we prepare the imputer, and at the second stage, we apply it. Imputation preparation includes prediction methods choice and including/excluding columns from the computation. We just need to rewrite the default imputation method for necessary columns through the $method property. In our case, we used mean (unconditional mean) for first and third columns, pmm (predictive mean matching) for the fifth column, norm (prediction by Bayesian linear regression based on other features) for the fourth column, and logreg (prediction by logistic regression for 2-value variable) for the conditional variable. See more in the documentation for the mice() method and by the command methods(your_mice_instance). We have also excluded the second column from the algorithm. Now we are ready for the second stage: reuse current mice instance as the input value for the real imputer: imputation <- mice(df_test, method=init$method, predictorMatrix=init$predictorMatrix, maxit=10, m = 5, seed=123) One of the main features of the MICE package is generating several imputation sets, which we can use as testing examples in further ML models. So, we will be able to choose the best fitting set. In our example we have m=5, so the algorithm generates 5 imputed datasets. You can read more about the work with generated datasets and their usage in your ML pipeline in this article by the author of the package. The last step is to run the algorithm with the concrete number of the imputed dataset: imputed <- complete(imputation, 2) You can see all generated sets within the $imp property of your mice instance. Though, I have chosen the second of the generated sets: Python has one of the strongest support from the community among the other programming languages. There is the especially great codebase for data science packages. You may find several imputation algorithms in the famous scikit-learn package. This package also supports multivariate imputation, but as the documentation states — it is still in experimental status. So, let’s see a less complicated algorithm: SimpleImputer. Nevertheless, the imputer component of the sklearn package has more cool features like imputation through K-nearest algorithm, so you are free to explore it in the documentation. We will use the same toy-example. Of course, a simple imputation algorithm is not so flexible and gives us less predictive power, but it still handles the task. I will skip the part of missing data checking since it is the same as in the previous example. Nevertheless, you can check some good idioms in my article about missing data in Python. from sklearn.impute import SimpleImputerimpNumeric = SimpleImputer(missing_values=np.nan, strategy='mean')impCategorical = SimpleImputer(missing_values=np.nan, strategy='most_frequent') We have chosen the mean strategy for every numeric column and the most_frequent for the categorical one. You can read more about applied strategies on the documentation page for SingleImputer. You may also notice, that SingeImputer allows to set the value we treat as missing. The further process is much shorter than in R: imputer classes have the same fit-transform procedure as other sklearn components. So, again, we set imputation strategies for every column (except the second): And here is our imputed dataset: You are free to experiment, compare, and choose the best one among R and Python implementations. Data clearing is just the beginning of the analysis process, but mistakes at this stage may become catastrophic for further steps. Make the data clean and see the working code from the article on my Github: github.com Also, make sure, you haven’t missed my other data cleaning articles:
[ { "code": null, "e": 637, "s": 172, "text": "We all know, that data cleaning is one of the most time-consuming stages in the data analysis process. We need to acquire missing values, check their distribution, figure out the patterns, and make a decision on how to fill the spaces. At this point you should realize, that identification of missing data patterns and correct imputation process will influence further analysis. So, let me introduces a few technics for the common analysis languages: R and Python." }, { "code": null, "e": 837, "s": 637, "text": "Before we start the imputation process, we should acquire the data first and find the patterns or schemes of missing data. In simple words, there are two general types of missing data: MCAR and MNAR." }, { "code": null, "e": 1165, "s": 837, "text": "MNAR (missing not at random) is the most serious issue with data. It means, that we need to find the dependencies between missing features, and start the data gathering process. It turns in some kind of analysis step, which involves the work with different data sources, analysis of connections, and search of alternative data." }, { "code": null, "e": 1491, "s": 1165, "text": "MCAR (missing completely at random) means that there are no deep patterns in missing values, so we can work with that and decide if some rows/features may be removed or imputed. It is something we can deal with but only within empirical borders because there can be too much missing data (in the percentage of total records)." }, { "code": null, "e": 1554, "s": 1491, "text": "So, in illustration purposes we will use the next toy-example:" }, { "code": null, "e": 1645, "s": 1554, "text": "We can see the impact on multiple missing values, numeric, and categorical missing values." }, { "code": null, "e": 2036, "s": 1645, "text": "R programming language has a great community, which adds a lot of packages and libraries to the R development warehouse. So, that’s not a surprise, that we have the MICE package. It includes a lot of functionality connected with multivariate imputation with chained equations (that is MICE algorithm). You can dive deep into the documentation for details, but I will give the basic example." }, { "code": null, "e": 2123, "s": 2036, "text": "Firstly, let’s see the pattern of the missing data on our toy-example mentioned above:" }, { "code": null, "e": 2156, "s": 2123, "text": "library(mice)md.pattern(df_test)" }, { "code": null, "e": 2433, "s": 2156, "text": "Mice package has built-in tool md.pattern(), which shows the distribution of missing values and combinations of missing features. You can read more about this tool in my previous article about missing data acquainting with R. Also this function gives us a pretty illustration:" }, { "code": null, "e": 2571, "s": 2433, "text": "Work with a mice-imputer is provided within two stages. At the first stage, we prepare the imputer, and at the second stage, we apply it." }, { "code": null, "e": 3271, "s": 2571, "text": "Imputation preparation includes prediction methods choice and including/excluding columns from the computation. We just need to rewrite the default imputation method for necessary columns through the $method property. In our case, we used mean (unconditional mean) for first and third columns, pmm (predictive mean matching) for the fifth column, norm (prediction by Bayesian linear regression based on other features) for the fourth column, and logreg (prediction by logistic regression for 2-value variable) for the conditional variable. See more in the documentation for the mice() method and by the command methods(your_mice_instance). We have also excluded the second column from the algorithm." }, { "code": null, "e": 3379, "s": 3271, "text": "Now we are ready for the second stage: reuse current mice instance as the input value for the real imputer:" }, { "code": null, "e": 3602, "s": 3379, "text": "imputation <- mice(df_test, method=init$method, predictorMatrix=init$predictorMatrix, maxit=10, m = 5, seed=123)" }, { "code": null, "e": 4011, "s": 3602, "text": "One of the main features of the MICE package is generating several imputation sets, which we can use as testing examples in further ML models. So, we will be able to choose the best fitting set. In our example we have m=5, so the algorithm generates 5 imputed datasets. You can read more about the work with generated datasets and their usage in your ML pipeline in this article by the author of the package." }, { "code": null, "e": 4098, "s": 4011, "text": "The last step is to run the algorithm with the concrete number of the imputed dataset:" }, { "code": null, "e": 4133, "s": 4098, "text": "imputed <- complete(imputation, 2)" }, { "code": null, "e": 4268, "s": 4133, "text": "You can see all generated sets within the $imp property of your mice instance. Though, I have chosen the second of the generated sets:" }, { "code": null, "e": 4511, "s": 4268, "text": "Python has one of the strongest support from the community among the other programming languages. There is the especially great codebase for data science packages. You may find several imputation algorithms in the famous scikit-learn package." }, { "code": null, "e": 4871, "s": 4511, "text": "This package also supports multivariate imputation, but as the documentation states — it is still in experimental status. So, let’s see a less complicated algorithm: SimpleImputer. Nevertheless, the imputer component of the sklearn package has more cool features like imputation through K-nearest algorithm, so you are free to explore it in the documentation." }, { "code": null, "e": 5216, "s": 4871, "text": "We will use the same toy-example. Of course, a simple imputation algorithm is not so flexible and gives us less predictive power, but it still handles the task. I will skip the part of missing data checking since it is the same as in the previous example. Nevertheless, you can check some good idioms in my article about missing data in Python." }, { "code": null, "e": 5433, "s": 5216, "text": "from sklearn.impute import SimpleImputerimpNumeric = SimpleImputer(missing_values=np.nan, strategy='mean')impCategorical = SimpleImputer(missing_values=np.nan, strategy='most_frequent')" }, { "code": null, "e": 5918, "s": 5433, "text": "We have chosen the mean strategy for every numeric column and the most_frequent for the categorical one. You can read more about applied strategies on the documentation page for SingleImputer. You may also notice, that SingeImputer allows to set the value we treat as missing. The further process is much shorter than in R: imputer classes have the same fit-transform procedure as other sklearn components. So, again, we set imputation strategies for every column (except the second):" }, { "code": null, "e": 5951, "s": 5918, "text": "And here is our imputed dataset:" }, { "code": null, "e": 6048, "s": 5951, "text": "You are free to experiment, compare, and choose the best one among R and Python implementations." }, { "code": null, "e": 6255, "s": 6048, "text": "Data clearing is just the beginning of the analysis process, but mistakes at this stage may become catastrophic for further steps. Make the data clean and see the working code from the article on my Github:" }, { "code": null, "e": 6266, "s": 6255, "text": "github.com" } ]
Get the sum of multiple row (not all) values from a MySQL table?
You can use aggregate function SUM() from MySQL for this. Let us first create a table − mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Amount int ); Query OK, 0 rows affected (0.65 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(Amount) values(400); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Amount) values(10); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Amount) values(50); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Amount) values(500); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Amount) values(80); Query OK, 1 row affected (0.09 sec) Following is the query to display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----+--------+ | Id | Amount | +----+--------+ | 1 | 400 | | 2 | 10 | | 3 | 50 | | 4 | 500 | | 5 | 80 | +----+--------+ 5 rows in set (0.00 sec) Here is the query to get the sum of rows (not all) out of MySQL table − mysql> select sum(Amount) from DemoTable where Id in(1,4,5); This will produce the following output − +-------------+ | sum(Amount) | +-------------+ | 980 | +-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1150, "s": 1062, "text": "You can use aggregate function SUM() from MySQL for this. Let us first create a table −" }, { "code": null, "e": 1283, "s": 1150, "text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Amount int\n);\nQuery OK, 0 rows affected (0.65 sec)" }, { "code": null, "e": 1339, "s": 1283, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1766, "s": 1339, "text": "mysql> insert into DemoTable(Amount) values(400);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable(Amount) values(10);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Amount) values(50);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(Amount) values(500);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(Amount) values(80);\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 1852, "s": 1766, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 1883, "s": 1852, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1924, "s": 1883, "text": "This will produce the following output −" }, { "code": null, "e": 2093, "s": 1924, "text": "+----+--------+\n| Id | Amount |\n+----+--------+\n| 1 | 400 |\n| 2 | 10 |\n| 3 | 50 |\n| 4 | 500 |\n| 5 | 80 |\n+----+--------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2165, "s": 2093, "text": "Here is the query to get the sum of rows (not all) out of MySQL table −" }, { "code": null, "e": 2226, "s": 2165, "text": "mysql> select sum(Amount) from DemoTable where Id in(1,4,5);" }, { "code": null, "e": 2267, "s": 2226, "text": "This will produce the following output −" }, { "code": null, "e": 2371, "s": 2267, "text": "+-------------+\n| sum(Amount) |\n+-------------+\n| 980 |\n+-------------+\n1 row in set (0.00 sec)" } ]
C | Arrays | Question 2 - GeeksforGeeks
11 Jan, 2013 Predict the output of below program: #include <stdio.h> int main(){ int arr[5]; // Assume base address of arr is 2000 and size of integer is 32 bit printf("%u %u", arr + 1, &arr + 1); return 0;} (A) 2004 2020(B) 2004 2004(C) 2004 Garbage value(D) The program fails to compile because Address-of operator cannot be used with array nameAnswer: (A)Explanation: Name of array in C gives the address(except in sizeof operator) of the first element. Adding 1 to this address gives the address plus the sizeof type the array has. Applying the Address-of operator before the array name gives the address of the whole array. Adding 1 to this address gives the address plus the sizeof whole array. Arrays C-Arrays C Language C Quiz Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 Output of C programs | Set 64 (Pointers)
[ { "code": null, "e": 23591, "s": 23563, "text": "\n11 Jan, 2013" }, { "code": null, "e": 23628, "s": 23591, "text": "Predict the output of below program:" }, { "code": "#include <stdio.h> int main(){ int arr[5]; // Assume base address of arr is 2000 and size of integer is 32 bit printf(\"%u %u\", arr + 1, &arr + 1); return 0;} ", "e": 23802, "s": 23628, "text": null }, { "code": null, "e": 24295, "s": 23802, "text": "(A) 2004 2020(B) 2004 2004(C) 2004 Garbage value(D) The program fails to compile because Address-of operator cannot be used with array nameAnswer: (A)Explanation: Name of array in C gives the address(except in sizeof operator) of the first element. Adding 1 to this address gives the address plus the sizeof type the array has. Applying the Address-of operator before the array name gives the address of the whole array. Adding 1 to this address gives the address plus the sizeof whole array." }, { "code": null, "e": 24302, "s": 24295, "text": "Arrays" }, { "code": null, "e": 24311, "s": 24302, "text": "C-Arrays" }, { "code": null, "e": 24322, "s": 24311, "text": "C Language" }, { "code": null, "e": 24329, "s": 24322, "text": "C Quiz" }, { "code": null, "e": 24336, "s": 24329, "text": "Arrays" }, { "code": null, "e": 24434, "s": 24336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24443, "s": 24434, "text": "Comments" }, { "code": null, "e": 24456, "s": 24443, "text": "Old Comments" }, { "code": null, "e": 24491, "s": 24456, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 24519, "s": 24491, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 24565, "s": 24519, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 24577, "s": 24565, "text": "fork() in C" }, { "code": null, "e": 24617, "s": 24577, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 24659, "s": 24617, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 24702, "s": 24659, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 24733, "s": 24702, "text": "C | File Handling | Question 1" }, { "code": null, "e": 24755, "s": 24733, "text": "C | Misc | Question 7" } ]
Display two digits day number in Java
To display two-digit day number, use the SimpleDateFormat('dd') as shown below − // displaying two-digit day number f = new SimpleDateFormat("dd"); String strDay = f.format(new Date()); System.out.println("Day Number = "+strDay); Since, we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date. import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; The following is an example. Live Demo import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class Demo { public static void main(String[] args) throws Exception { // displaying current date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s"); System.out.println("Today's date = "+simpleformat.format(cal.getTime())); // current time Format f = new SimpleDateFormat("HH.mm.ss Z"); String strResult = f.format(new Date()); System.out.println("Time = "+strResult); // displaying two-digit day number f = new SimpleDateFormat("dd"); String strDay = f.format(new Date()); System.out.println("Day Number = "+strDay); // displaying hour f = new SimpleDateFormat("H"); String strHour = f.format(new Date()); System.out.println("Current Hour = "+strHour); // displaying minutes f = new SimpleDateFormat("mm"); String strMinute = f.format(new Date()); System.out.println("Current Minutes = "+strMinute); // displaying seconds f = new SimpleDateFormat("ss"); String strSeconds = f.format(new Date()); System.out.println("Current Seconds = "+strSeconds); } } Today's date = 26/November/2018 08:59:48 Time = 08.59.48 +0000 Day Number = 26 Current Hour = 8 Current Minutes = 59 Current Seconds = 48
[ { "code": null, "e": 1143, "s": 1062, "text": "To display two-digit day number, use the SimpleDateFormat('dd') as shown below −" }, { "code": null, "e": 1292, "s": 1143, "text": "// displaying two-digit day number\nf = new SimpleDateFormat(\"dd\");\nString strDay = f.format(new Date());\nSystem.out.println(\"Day Number = \"+strDay);" }, { "code": null, "e": 1437, "s": 1292, "text": "Since, we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date." }, { "code": null, "e": 1520, "s": 1437, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;" }, { "code": null, "e": 1549, "s": 1520, "text": "The following is an example." }, { "code": null, "e": 1560, "s": 1549, "text": " Live Demo" }, { "code": null, "e": 2855, "s": 1560, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy hh:mm:s\");\n System.out.println(\"Today's date = \"+simpleformat.format(cal.getTime()));\n // current time\n Format f = new SimpleDateFormat(\"HH.mm.ss Z\");\n String strResult = f.format(new Date());\n System.out.println(\"Time = \"+strResult);\n // displaying two-digit day number\n f = new SimpleDateFormat(\"dd\");\n String strDay = f.format(new Date());\n System.out.println(\"Day Number = \"+strDay);\n // displaying hour\n f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n }\n}" }, { "code": null, "e": 2993, "s": 2855, "text": "Today's date = 26/November/2018 08:59:48\nTime = 08.59.48 +0000\nDay Number = 26\nCurrent Hour = 8\nCurrent Minutes = 59\nCurrent Seconds = 48" } ]
C++ Program to Implement Hash Tables
A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched. This is a C++ program to Implement Hash Tables. Begin Initialize the table size T_S to some integer value. Create a structure hashTableEntry to declare key k and value v. Create a class hashMapTable: Create a constructor hashMapTable to create the table. Create a hashFunc() function which return key mod T_S. Create a function Insert() to insert element at a key. Create a function SearchKey() to search element at a key. Create a function Remove() to remove element at a key. Call a destructor hashMapTable to destroy the objects created by the constructor. In main, perform switch operation and enter input as per choice. To insert key and values, call insert(). To search element, call SearchKey(). To remove element, call Remove(). End. #include<iostream> #include<cstdlib> #include<string> #include<cstdio> using namespace std; const int T_S = 200; class HashTableEntry { public: int k; int v; HashTableEntry(int k, int v) { this->k= k; this->v = v; } }; class HashMapTable { private: HashTableEntry **t; public: HashMapTable() { t = new HashTableEntry * [T_S]; for (int i = 0; i< T_S; i++) { t[i] = NULL; } } int HashFunc(int k) { return k % T_S; } void Insert(int k, int v) { int h = HashFunc(k); while (t[h] != NULL && t[h]->k != k) { h = HashFunc(h + 1); } if (t[h] != NULL) delete t[h]; t[h] = new HashTableEntry(k, v); } int SearchKey(int k) { int h = HashFunc(k); while (t[h] != NULL && t[h]->k != k) { h = HashFunc(h + 1); } if (t[h] == NULL) return -1; else return t[h]->v; } void Remove(int k) { int h = HashFunc(k); while (t[h] != NULL) { if (t[h]->k == k) break; h = HashFunc(h + 1); } if (t[h] == NULL) { cout<<"No Element found at key "<<k<<endl; return; } else { delete t[h]; } cout<<"Element Deleted"<<endl; } ~HashMapTable() { for (int i = 0; i < T_S; i++) { if (t[i] != NULL) delete t[i]; delete[] t; } } }; int main() { HashMapTable hash; int k, v; int c; while (1) { cout<<"1.Insert element into the table"<<endl; cout<<"2.Search element from the key"<<endl; cout<<"3.Delete element at a key"<<endl; cout<<"4.Exit"<<endl; cout<<"Enter your choice: "; cin>>c; switch(c) { case 1: cout<<"Enter element to be inserted: "; cin>>v; cout<<"Enter key at which element to be inserted: "; cin>>k; hash.Insert(k, v); break; case 2: cout<<"Enter key of the element to be searched: "; cin>>k; if (hash.SearchKey(k) == -1) { cout<<"No element found at key "<<k<<endl; continue; } else { cout<<"Element at key "<<k<<" : "; cout<<hash.SearchKey(k)<<endl; } break; case 3: cout<<"Enter key of the element to be deleted: "; cin>>k; hash.Remove(k); break; case 4: exit(1); default: cout<<"\nEnter correct option\n"; } } return 0; } 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 1 Enter key at which element to be inserted: 1 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 2 Enter key at which element to be inserted: 2 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 4 Enter key at which element to be inserted: 5 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 7 Enter key at which element to be inserted: 6 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 2 Enter key of the element to be searched: 7 No element found at key 7 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 2 Enter key of the element to be searched: 6 Element at key 6 : 7 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 3 Enter key of the element to be deleted: 1 Element Deleted 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 4
[ { "code": null, "e": 1255, "s": 1062, "text": "A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched." }, { "code": null, "e": 1303, "s": 1255, "text": "This is a C++ program to Implement Hash Tables." }, { "code": null, "e": 2036, "s": 1303, "text": "Begin\n Initialize the table size T_S to some integer value.\n Create a structure hashTableEntry to declare key k and value v.\n Create a class hashMapTable:\n Create a constructor hashMapTable to create the table.\n Create a hashFunc() function which return key mod T_S.\n Create a function Insert() to insert element at a key.\n Create a function SearchKey() to search element at a key.\n Create a function Remove() to remove element at a key.\n Call a destructor hashMapTable to destroy the objects created by the constructor.\n In main, perform switch operation and enter input as per choice.\n To insert key and values, call insert().\n To search element, call SearchKey().\n To remove element, call Remove().\nEnd." }, { "code": null, "e": 4837, "s": 2036, "text": "#include<iostream>\n#include<cstdlib>\n#include<string>\n#include<cstdio>\nusing namespace std;\nconst int T_S = 200;\nclass HashTableEntry {\n public:\n int k;\n int v;\n HashTableEntry(int k, int v) {\n this->k= k;\n this->v = v;\n }\n};\nclass HashMapTable {\n private:\n HashTableEntry **t;\n public:\n HashMapTable() {\n t = new HashTableEntry * [T_S];\n for (int i = 0; i< T_S; i++) {\n t[i] = NULL;\n }\n }\n int HashFunc(int k) {\n return k % T_S;\n }\n void Insert(int k, int v) {\n int h = HashFunc(k);\n while (t[h] != NULL && t[h]->k != k) {\n h = HashFunc(h + 1);\n }\n if (t[h] != NULL)\n delete t[h];\n t[h] = new HashTableEntry(k, v);\n }\n int SearchKey(int k) {\n int h = HashFunc(k);\n while (t[h] != NULL && t[h]->k != k) {\n h = HashFunc(h + 1);\n }\n if (t[h] == NULL)\n return -1;\n else\n return t[h]->v;\n }\n void Remove(int k) {\n int h = HashFunc(k);\n while (t[h] != NULL) {\n if (t[h]->k == k)\n break;\n h = HashFunc(h + 1);\n }\n if (t[h] == NULL) {\n cout<<\"No Element found at key \"<<k<<endl;\n return;\n } else {\n delete t[h];\n }\n cout<<\"Element Deleted\"<<endl;\n }\n ~HashMapTable() {\n for (int i = 0; i < T_S; i++) {\n if (t[i] != NULL)\n delete t[i];\n delete[] t;\n }\n }\n};\nint main() {\n HashMapTable hash;\n int k, v;\n int c;\n while (1) {\n cout<<\"1.Insert element into the table\"<<endl;\n cout<<\"2.Search element from the key\"<<endl;\n cout<<\"3.Delete element at a key\"<<endl;\n cout<<\"4.Exit\"<<endl;\n cout<<\"Enter your choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Enter element to be inserted: \";\n cin>>v;\n cout<<\"Enter key at which element to be inserted: \";\n cin>>k;\n hash.Insert(k, v);\n break;\n case 2:\n cout<<\"Enter key of the element to be searched: \";\n cin>>k;\n if (hash.SearchKey(k) == -1) {\n cout<<\"No element found at key \"<<k<<endl;\n continue;\n } else {\n cout<<\"Element at key \"<<k<<\" : \";\n cout<<hash.SearchKey(k)<<endl;\n }\n break;\n case 3:\n cout<<\"Enter key of the element to be deleted: \";\n cin>>k;\n hash.Remove(k);\n break;\n case 4:\n exit(1);\n default:\n cout<<\"\\nEnter correct option\\n\";\n }\n }\n return 0;\n}" }, { "code": null, "e": 6264, "s": 4837, "text": "1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 1\nEnter key at which element to be inserted: 1\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 2\nEnter key at which element to be inserted: 2\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 4\nEnter key at which element to be inserted: 5\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 7\nEnter key at which element to be inserted: 6\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 2\nEnter key of the element to be searched: 7\nNo element found at key 7\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 2\nEnter key of the element to be searched: 6\nElement at key 6 : 7\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 3\nEnter key of the element to be deleted: 1\nElement Deleted\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 4" } ]
How to get an amazing Terminal. In Windows and Linux; including... | by Martin Thoma | Towards Data Science
As a developer with 10+ years of experience, I love using the shell. The commands never change, I can create custom shortcuts, it’s reliable and fast. The defaults are not great, though. After reading this article, you will know how to get an awesome shell + terminal on your system. The shell is what actually executes the command. The terminal is a wrapper that runs the shell. The terminal is where you set the font face, font size, color schemes, support for multiple tabs. Examples for terminal emulators are GNOME terminal, Konsole on KDE, Terminator, and XTerm. On Linux, I recommend keeping the default. On Windows, the Windows Terminal is awesome. On Mac, I’ve heard good things about iTerm 2. The shell stores the history of entered commands, defines how you set environment variables, how you switch the current directory. Examples for shells on Linux are ZSH, Bash, fish. On Windows, the typical shells are PowerShell. You can see which shell you are running by executing echo $0 . On Linux, it’s most likely Bash. Every shell has a prompt. The prompt is what is written before your cursor. It signalizes that you can enter a command and gives useful context information. In the example above, the prompt contains the user name moose , the current computer pc08 , the current working directory ~/GitHub/MartinThoma/flake8-simplify , the active git branch feature/19 and the fact that there are modifications ±. No matter what you take, the font matters. You might want to have a monospace font. And you for sure want a powerline font; trust me with that one. The powerline font gives your shell the possibility to use characters that look like images. It can make the prompt way nicer. I like Ubuntu Mono and Droid Sans Mono: There are also “programming fonts” like Fira Code or Jetbrains Mono. I don’t like them, because they make it harder for me to really know what is written. They look nice, though. First, make sure you have the Windows Terminal installed: www.microsoft.com Launch a terminal and navigate to the settings. It’s this small downwards pointing “arrow”: You should see a JSON file which you can change to fit your taste. I have the following: Download and install all 4 “DejaVu Sans Mono Powerline” fonts. On all systems I know, installing a font is done by double-clicking it. Then a window opens which has an “Install” button. Aminal is a Terminal Emulator written in Go. It can be used on Linux, Windows, and Mac. It allows configuration via a configuration file and includes the color and keyboard shortcuts in it. First, you need to install and configure Go on your system. On Ubuntu, it works like this: $ sudo apt-get install golang libgl1-mesa-dev xorg-dev$ export GOPATH="$HOME/go"$ export GOBIN=$(go env GOPATH)/bin Then you can install and run aminal: $ go get -u github.com/liamg/aminal$ aminal The Gnome terminal can be customized by editing the profile. Here I set the Ubuntu Mono derivate Powerline Regular with a font size of 12. The command is set to zsh as this is my favorite shell. The colors are set to solarized dark (left-to-right, top-line / bottom-line) Background: #2e3436 / #555753 Dark Red: #cc0000 / Light Red: ef2929 Dark Green: #4e9a06 / Light Green: #8ae234 Dark Yellow: #c4a000 / Light Yellow: #fce94f Dark Blue: #3465a4 / Light Blue: #729fcf Dark Purple: #75507b / Light Purple: #ad7fa8 Dark Teal: #06989a / Light Teal: #34e2e2 Dark Gray: #d3d7cf / Light Gray: #eeeeec Install the fish shell: sudo apt-get install fish Change the default shell in your terminal emulator to fish . Within Gnome terminal, it is called “custom command”. Then install “Oh My Fish”: curl -L https://get.oh-my.fish | fish And set the theme to agnoster: omf install agnosteromf theme agnoster For cool features of the fish shell, read Why I Use Fish Shell Over Bash and Zsh by Alec Brunelle. A core part of making the terminal awesome is making common commands short. To do so, you create an alias for a command — a shorter version of the original command. The most common example is changing a directory to go one level up. For example, if you are in /home/user/foo/bar , you want to get to /home/user/foo . In most shells, you have to enter cd .. . I like to abbreviate that to .. . So I have the alias alias ..='cd ..' . The syntax may vary, depending on your shell. For Bash, ZSH, and fish it is alias short='long' For bash, you insert them in ~/.bashrc , for ZSH in ~/.zshrc . In fish, it is different. Here are some aliases I like: # Shorten thingsalias ..='cd ..'alias ...='cd ../../'alias ll='ls -alF'alias la='ls -A'alias l='ls -CF'alias c='clear'# If your terminal supports colors, use them!alias ls='ls --color=auto'alias grep='grep --color=auto'alias fgrep='fgrep --color=auto'alias egrep='egrep --color=auto'alias diff='colordiff'# Works only if you have notify-sendalias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' Make sure you have a reasonable terminal emulator. I suggest Gnome Terminal for Linux, iTerm 2 for Mac, and Windows Terminal for Windows. Install a good powerline font like Ubuntu Mono Powerline. Adjust the font face, font size, and color scheme of your terminal emulator to your preferences. Install a good shell. I suggest fish for Linux and PowerShell for Windows. Adjust the prompt of your shell to your needs. I like the agnoster theme.
[ { "code": null, "e": 456, "s": 172, "text": "As a developer with 10+ years of experience, I love using the shell. The commands never change, I can create custom shortcuts, it’s reliable and fast. The defaults are not great, though. After reading this article, you will know how to get an awesome shell + terminal on your system." }, { "code": null, "e": 552, "s": 456, "text": "The shell is what actually executes the command. The terminal is a wrapper that runs the shell." }, { "code": null, "e": 875, "s": 552, "text": "The terminal is where you set the font face, font size, color schemes, support for multiple tabs. Examples for terminal emulators are GNOME terminal, Konsole on KDE, Terminator, and XTerm. On Linux, I recommend keeping the default. On Windows, the Windows Terminal is awesome. On Mac, I’ve heard good things about iTerm 2." }, { "code": null, "e": 1199, "s": 875, "text": "The shell stores the history of entered commands, defines how you set environment variables, how you switch the current directory. Examples for shells on Linux are ZSH, Bash, fish. On Windows, the typical shells are PowerShell. You can see which shell you are running by executing echo $0 . On Linux, it’s most likely Bash." }, { "code": null, "e": 1595, "s": 1199, "text": "Every shell has a prompt. The prompt is what is written before your cursor. It signalizes that you can enter a command and gives useful context information. In the example above, the prompt contains the user name moose , the current computer pc08 , the current working directory ~/GitHub/MartinThoma/flake8-simplify , the active git branch feature/19 and the fact that there are modifications ±." }, { "code": null, "e": 1870, "s": 1595, "text": "No matter what you take, the font matters. You might want to have a monospace font. And you for sure want a powerline font; trust me with that one. The powerline font gives your shell the possibility to use characters that look like images. It can make the prompt way nicer." }, { "code": null, "e": 1910, "s": 1870, "text": "I like Ubuntu Mono and Droid Sans Mono:" }, { "code": null, "e": 2089, "s": 1910, "text": "There are also “programming fonts” like Fira Code or Jetbrains Mono. I don’t like them, because they make it harder for me to really know what is written. They look nice, though." }, { "code": null, "e": 2147, "s": 2089, "text": "First, make sure you have the Windows Terminal installed:" }, { "code": null, "e": 2165, "s": 2147, "text": "www.microsoft.com" }, { "code": null, "e": 2257, "s": 2165, "text": "Launch a terminal and navigate to the settings. It’s this small downwards pointing “arrow”:" }, { "code": null, "e": 2346, "s": 2257, "text": "You should see a JSON file which you can change to fit your taste. I have the following:" }, { "code": null, "e": 2532, "s": 2346, "text": "Download and install all 4 “DejaVu Sans Mono Powerline” fonts. On all systems I know, installing a font is done by double-clicking it. Then a window opens which has an “Install” button." }, { "code": null, "e": 2722, "s": 2532, "text": "Aminal is a Terminal Emulator written in Go. It can be used on Linux, Windows, and Mac. It allows configuration via a configuration file and includes the color and keyboard shortcuts in it." }, { "code": null, "e": 2813, "s": 2722, "text": "First, you need to install and configure Go on your system. On Ubuntu, it works like this:" }, { "code": null, "e": 2929, "s": 2813, "text": "$ sudo apt-get install golang libgl1-mesa-dev xorg-dev$ export GOPATH=\"$HOME/go\"$ export GOBIN=$(go env GOPATH)/bin" }, { "code": null, "e": 2966, "s": 2929, "text": "Then you can install and run aminal:" }, { "code": null, "e": 3010, "s": 2966, "text": "$ go get -u github.com/liamg/aminal$ aminal" }, { "code": null, "e": 3149, "s": 3010, "text": "The Gnome terminal can be customized by editing the profile. Here I set the Ubuntu Mono derivate Powerline Regular with a font size of 12." }, { "code": null, "e": 3205, "s": 3149, "text": "The command is set to zsh as this is my favorite shell." }, { "code": null, "e": 3282, "s": 3205, "text": "The colors are set to solarized dark (left-to-right, top-line / bottom-line)" }, { "code": null, "e": 3312, "s": 3282, "text": "Background: #2e3436 / #555753" }, { "code": null, "e": 3350, "s": 3312, "text": "Dark Red: #cc0000 / Light Red: ef2929" }, { "code": null, "e": 3393, "s": 3350, "text": "Dark Green: #4e9a06 / Light Green: #8ae234" }, { "code": null, "e": 3438, "s": 3393, "text": "Dark Yellow: #c4a000 / Light Yellow: #fce94f" }, { "code": null, "e": 3479, "s": 3438, "text": "Dark Blue: #3465a4 / Light Blue: #729fcf" }, { "code": null, "e": 3524, "s": 3479, "text": "Dark Purple: #75507b / Light Purple: #ad7fa8" }, { "code": null, "e": 3565, "s": 3524, "text": "Dark Teal: #06989a / Light Teal: #34e2e2" }, { "code": null, "e": 3606, "s": 3565, "text": "Dark Gray: #d3d7cf / Light Gray: #eeeeec" }, { "code": null, "e": 3630, "s": 3606, "text": "Install the fish shell:" }, { "code": null, "e": 3656, "s": 3630, "text": "sudo apt-get install fish" }, { "code": null, "e": 3771, "s": 3656, "text": "Change the default shell in your terminal emulator to fish . Within Gnome terminal, it is called “custom command”." }, { "code": null, "e": 3798, "s": 3771, "text": "Then install “Oh My Fish”:" }, { "code": null, "e": 3836, "s": 3798, "text": "curl -L https://get.oh-my.fish | fish" }, { "code": null, "e": 3867, "s": 3836, "text": "And set the theme to agnoster:" }, { "code": null, "e": 3906, "s": 3867, "text": "omf install agnosteromf theme agnoster" }, { "code": null, "e": 4005, "s": 3906, "text": "For cool features of the fish shell, read Why I Use Fish Shell Over Bash and Zsh by Alec Brunelle." }, { "code": null, "e": 4513, "s": 4005, "text": "A core part of making the terminal awesome is making common commands short. To do so, you create an alias for a command — a shorter version of the original command. The most common example is changing a directory to go one level up. For example, if you are in /home/user/foo/bar , you want to get to /home/user/foo . In most shells, you have to enter cd .. . I like to abbreviate that to .. . So I have the alias alias ..='cd ..' . The syntax may vary, depending on your shell. For Bash, ZSH, and fish it is" }, { "code": null, "e": 4532, "s": 4513, "text": "alias short='long'" }, { "code": null, "e": 4621, "s": 4532, "text": "For bash, you insert them in ~/.bashrc , for ZSH in ~/.zshrc . In fish, it is different." }, { "code": null, "e": 4651, "s": 4621, "text": "Here are some aliases I like:" }, { "code": null, "e": 5157, "s": 4651, "text": "# Shorten thingsalias ..='cd ..'alias ...='cd ../../'alias ll='ls -alF'alias la='ls -A'alias l='ls -CF'alias c='clear'# If your terminal supports colors, use them!alias ls='ls --color=auto'alias grep='grep --color=auto'alias fgrep='fgrep --color=auto'alias egrep='egrep --color=auto'alias diff='colordiff'# Works only if you have notify-sendalias alert='notify-send --urgency=low -i \"$([ $? = 0 ] && echo terminal || echo error)\" \"$(history|tail -n1|sed -e '\\''s/^\\s*[0-9]\\+\\s*//;s/[;&|]\\s*alert$//'\\'')\"'" }, { "code": null, "e": 5295, "s": 5157, "text": "Make sure you have a reasonable terminal emulator. I suggest Gnome Terminal for Linux, iTerm 2 for Mac, and Windows Terminal for Windows." }, { "code": null, "e": 5353, "s": 5295, "text": "Install a good powerline font like Ubuntu Mono Powerline." }, { "code": null, "e": 5450, "s": 5353, "text": "Adjust the font face, font size, and color scheme of your terminal emulator to your preferences." }, { "code": null, "e": 5525, "s": 5450, "text": "Install a good shell. I suggest fish for Linux and PowerShell for Windows." } ]
p5.js | min() function - GeeksforGeeks
09 Apr, 2019 The min() function in p5.js is used to get the minimum value from the sequence of numbers. Syntax: min(a, b) or min(arr) Parameters: The min(a, b) function accepts two parameters which are two different number and compared to get minimum value among them. The min(arr) function accepts a single parameter array. Return Value: It returns the minimum value among the different numbers. Below program illustrates the min() function in p5.js: Example: This example uses min() function to get the minimum value. function setup() { // Create Canvas of size 270*80 createCanvas(350, 130); } function draw() { // Set the background color background(220); // Call to min() function let u = min(1, 3); let v = min(1, 1); let w = min(5, 9); let x = min(2, 3.9); let y = min(1.5, 3.2); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting minimum value text("Minimum value between (1, 3) is: " + u, 50, 30); text("Minimum value between (1, 1) is: " + v, 50, 50); text("Minimum value between (5, 9) is: " + w, 50, 70); text("Minimum value between (2, 3.9) is: " + x, 50, 90); text("Minimum value between (1.5, 3.2) is: " + y, 50, 110); } Output: Reference: https://p5js.org/reference/#/p5/min JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25382, "s": 25354, "text": "\n09 Apr, 2019" }, { "code": null, "e": 25473, "s": 25382, "text": "The min() function in p5.js is used to get the minimum value from the sequence of numbers." }, { "code": null, "e": 25481, "s": 25473, "text": "Syntax:" }, { "code": null, "e": 25491, "s": 25481, "text": "min(a, b)" }, { "code": null, "e": 25494, "s": 25491, "text": "or" }, { "code": null, "e": 25503, "s": 25494, "text": "min(arr)" }, { "code": null, "e": 25694, "s": 25503, "text": "Parameters: The min(a, b) function accepts two parameters which are two different number and compared to get minimum value among them. The min(arr) function accepts a single parameter array." }, { "code": null, "e": 25766, "s": 25694, "text": "Return Value: It returns the minimum value among the different numbers." }, { "code": null, "e": 25821, "s": 25766, "text": "Below program illustrates the min() function in p5.js:" }, { "code": null, "e": 25889, "s": 25821, "text": "Example: This example uses min() function to get the minimum value." }, { "code": "function setup() { // Create Canvas of size 270*80 createCanvas(350, 130); } function draw() { // Set the background color background(220); // Call to min() function let u = min(1, 3); let v = min(1, 1); let w = min(5, 9); let x = min(2, 3.9); let y = min(1.5, 3.2); // Set the size of text textSize(16); // Set the text color fill(color('red')); // Getting minimum value text(\"Minimum value between (1, 3) is: \" + u, 50, 30); text(\"Minimum value between (1, 1) is: \" + v, 50, 50); text(\"Minimum value between (5, 9) is: \" + w, 50, 70); text(\"Minimum value between (2, 3.9) is: \" + x, 50, 90); text(\"Minimum value between (1.5, 3.2) is: \" + y, 50, 110); } ", "e": 26663, "s": 25889, "text": null }, { "code": null, "e": 26671, "s": 26663, "text": "Output:" }, { "code": null, "e": 26718, "s": 26671, "text": "Reference: https://p5js.org/reference/#/p5/min" }, { "code": null, "e": 26735, "s": 26718, "text": "JavaScript-p5.js" }, { "code": null, "e": 26746, "s": 26735, "text": "JavaScript" }, { "code": null, "e": 26763, "s": 26746, "text": "Web Technologies" }, { "code": null, "e": 26861, "s": 26763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26870, "s": 26861, "text": "Comments" }, { "code": null, "e": 26883, "s": 26870, "text": "Old Comments" }, { "code": null, "e": 26944, "s": 26883, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26985, "s": 26944, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27039, "s": 26985, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27101, "s": 27039, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27158, "s": 27101, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27200, "s": 27158, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27233, "s": 27200, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27276, "s": 27233, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27338, "s": 27276, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Count number of bits to be flipped to convert A to B | Set-2 - GeeksforGeeks
17 Nov, 2021 Given two integers A and B, the task is to count the number of bits needed to be flipped to convert A to B.Examples: Input: A = 10, B = 7 Output: 3 binary(10) = 1010 binary(7) = 0111 1010 0111 3 bits need to be flipped.Input: A = 8, B = 7 Output: 4 Approach: An approach to solve this problem has already been discussed here. Here, the count of bits that need to be flipped can be found by matching all the bits in both the integers one by one. If the bit under consideration differs then increment the count.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of bits// to be flipped to convert a to bint countBits(int a, int b){ // To store the required count int count = 0; // Loop until both of them become zero while (a || b) { // Store the last bits in a // as well as b int last_bit_a = a & 1; int last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver codeint main(){ int a = 10, b = 7; cout << countBits(a, b); return 0;} // Java implementation of the approachimport java.util.*;class GFG{ // Function to return the count of bits// to be flipped to convert a to bstatic int countBits(int a, int b){ // To store the required count int count = 0; // Loop until both of them become zero while (a > 0 || b > 0) { // Store the last bits in a // as well as b int last_bit_a = a & 1; int last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver codepublic static void main(String[] args){ int a = 10, b = 7; System.out.println(countBits(a, b));}} // This code is contributed by Princi Singh # Python3 implementation of the approach # Function to return the count of bits# to be flipped to convert a to bdef countBits(a, b): # To store the required count count = 0 # Loop until both of them become zero while (a or b): # Store the last bits in a # as well as b last_bit_a = a & 1 last_bit_b = b & 1 # If the current bit is not same # in both the integers if (last_bit_a != last_bit_b): count += 1 # Right shift both the integers by 1 a = a >> 1 b = b >> 1 # Return the count return count # Driver codea = 10b = 7 print(countBits(a, b)) # This code is contributed by Mohit Kumar // C# implementation of the above approachusing System; class GFG{ // Function to return the count of bits// to be flipped to convert a to bstatic int countBits(int a, int b){ // To store the required count int count = 0; // Loop until both of them become zero while (a > 0 || b > 0) { // Store the last bits in a // as well as b int last_bit_a = a & 1; int last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver codepublic static void Main(String[] args){ int a = 10, b = 7; Console.WriteLine(countBits(a, b));}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Function to return the count of bits// to be flipped to convert a to bfunction countBits(a, b){ // To store the required count var count = 0; // Loop until both of them become zero while (a || b) { // Store the last bits in a // as well as b var last_bit_a = a & 1; var last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver code var a = 10, b = 7; document.write(countBits(a, b)); </script> 3 Time Complexity: O(min(log a, log b)) Auxiliary Space: O(1) mohit kumar 29 princi singh princiraj1992 bgangwar59 subhammahato348 Numbers Bit Magic Bit Magic Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Set, Clear and Toggle a given bit of a number in C Program to find parity Hamming code Implementation in C/C++ Check whether K-th bit is set or not Write an Efficient Method to Check if a Number is Multiple of 3 Implementation of Bit Stuffing and Bit Destuffing Builtin functions of GCC compiler Find XOR of all elements in an Array Swap bits in a given number Count total bits in a number
[ { "code": null, "e": 25013, "s": 24985, "text": "\n17 Nov, 2021" }, { "code": null, "e": 25132, "s": 25013, "text": "Given two integers A and B, the task is to count the number of bits needed to be flipped to convert A to B.Examples: " }, { "code": null, "e": 25266, "s": 25132, "text": "Input: A = 10, B = 7 Output: 3 binary(10) = 1010 binary(7) = 0111 1010 0111 3 bits need to be flipped.Input: A = 8, B = 7 Output: 4 " }, { "code": null, "e": 25581, "s": 25268, "text": "Approach: An approach to solve this problem has already been discussed here. Here, the count of bits that need to be flipped can be found by matching all the bits in both the integers one by one. If the bit under consideration differs then increment the count.Below is the implementation of the above approach: " }, { "code": null, "e": 25585, "s": 25581, "text": "C++" }, { "code": null, "e": 25590, "s": 25585, "text": "Java" }, { "code": null, "e": 25598, "s": 25590, "text": "Python3" }, { "code": null, "e": 25601, "s": 25598, "text": "C#" }, { "code": null, "e": 25612, "s": 25601, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of bits// to be flipped to convert a to bint countBits(int a, int b){ // To store the required count int count = 0; // Loop until both of them become zero while (a || b) { // Store the last bits in a // as well as b int last_bit_a = a & 1; int last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver codeint main(){ int a = 10, b = 7; cout << countBits(a, b); return 0;}", "e": 26386, "s": 25612, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ // Function to return the count of bits// to be flipped to convert a to bstatic int countBits(int a, int b){ // To store the required count int count = 0; // Loop until both of them become zero while (a > 0 || b > 0) { // Store the last bits in a // as well as b int last_bit_a = a & 1; int last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver codepublic static void main(String[] args){ int a = 10, b = 7; System.out.println(countBits(a, b));}} // This code is contributed by Princi Singh", "e": 27235, "s": 26386, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of bits# to be flipped to convert a to bdef countBits(a, b): # To store the required count count = 0 # Loop until both of them become zero while (a or b): # Store the last bits in a # as well as b last_bit_a = a & 1 last_bit_b = b & 1 # If the current bit is not same # in both the integers if (last_bit_a != last_bit_b): count += 1 # Right shift both the integers by 1 a = a >> 1 b = b >> 1 # Return the count return count # Driver codea = 10b = 7 print(countBits(a, b)) # This code is contributed by Mohit Kumar", "e": 27926, "s": 27235, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the count of bits// to be flipped to convert a to bstatic int countBits(int a, int b){ // To store the required count int count = 0; // Loop until both of them become zero while (a > 0 || b > 0) { // Store the last bits in a // as well as b int last_bit_a = a & 1; int last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver codepublic static void Main(String[] args){ int a = 10, b = 7; Console.WriteLine(countBits(a, b));}} // This code is contributed by PrinciRaj1992", "e": 28774, "s": 27926, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count of bits// to be flipped to convert a to bfunction countBits(a, b){ // To store the required count var count = 0; // Loop until both of them become zero while (a || b) { // Store the last bits in a // as well as b var last_bit_a = a & 1; var last_bit_b = b & 1; // If the current bit is not same // in both the integers if (last_bit_a != last_bit_b) count++; // Right shift both the integers by 1 a = a >> 1; b = b >> 1; } // Return the count return count;} // Driver code var a = 10, b = 7; document.write(countBits(a, b)); </script>", "e": 29508, "s": 28774, "text": null }, { "code": null, "e": 29510, "s": 29508, "text": "3" }, { "code": null, "e": 29550, "s": 29512, "text": "Time Complexity: O(min(log a, log b))" }, { "code": null, "e": 29572, "s": 29550, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29587, "s": 29572, "text": "mohit kumar 29" }, { "code": null, "e": 29600, "s": 29587, "text": "princi singh" }, { "code": null, "e": 29614, "s": 29600, "text": "princiraj1992" }, { "code": null, "e": 29625, "s": 29614, "text": "bgangwar59" }, { "code": null, "e": 29641, "s": 29625, "text": "subhammahato348" }, { "code": null, "e": 29649, "s": 29641, "text": "Numbers" }, { "code": null, "e": 29659, "s": 29649, "text": "Bit Magic" }, { "code": null, "e": 29669, "s": 29659, "text": "Bit Magic" }, { "code": null, "e": 29677, "s": 29669, "text": "Numbers" }, { "code": null, "e": 29775, "s": 29677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29784, "s": 29775, "text": "Comments" }, { "code": null, "e": 29797, "s": 29784, "text": "Old Comments" }, { "code": null, "e": 29848, "s": 29797, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 29871, "s": 29848, "text": "Program to find parity" }, { "code": null, "e": 29908, "s": 29871, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 29945, "s": 29908, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 30009, "s": 29945, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 30059, "s": 30009, "text": "Implementation of Bit Stuffing and Bit Destuffing" }, { "code": null, "e": 30093, "s": 30059, "text": "Builtin functions of GCC compiler" }, { "code": null, "e": 30130, "s": 30093, "text": "Find XOR of all elements in an Array" }, { "code": null, "e": 30158, "s": 30130, "text": "Swap bits in a given number" } ]
Partition of a set into K subsets with equal sum using BitMask and DP - GeeksforGeeks
11 Aug, 2021 Given an integer array arr[] of consisting of N integers, the task is check if it is possible to divide the given array into K non-empty subsets of equal sum such that every array element is part of a single subset.Examples: Input: arr[] = {2, 1, 4, 5, 6}, K = 3 Output: Yes Explanation: Possible subsets of given array are {2, 4}, (1, 5} and {6}Input: arr[] = {2, 1, 5, 5, 6}, K = 3 Output: No For the recursive approach, refer to Partition of a set into K subsets with equal sum.Approach: Follow the steps below to solve the problem: The idea is to use mask to determine the current state. The current state will tell us about the subset already formed ( which numbers are already selected ). For example: arr[] = [2, 1, 4, 3, 5, 6, 2], mask = (1100101), which means that { 2, 1, 5, 2 } are already chosen in the current mask. For any current state mask, the jth element will be added to it based on the following two conditions: The jth bit is not set in the mask (mask&(1<<j) == 0)sum (mask) + arr[j] <= target ( where target = (Sum of array elements) / K) The jth bit is not set in the mask (mask&(1<<j) == 0) sum (mask) + arr[j] <= target ( where target = (Sum of array elements) / K) Maintain a table dp[] such that dp[i] store the sum of elements in mask i. So, the dp transitions will be: dp[i | (1 << j)] = (dp[i] + arr[j]) % target Illustration: arr [ ] = [4, 3, 2, 3, 5, 2, 1], K = 4, tar = 5 dp[“1100101”] implies that { 4, 3, 5, 1 } are chosen Hence, Sum = 4 + 3 + 5 + 1 = 13, 13 % 5 = 3. Hence, dp[“1100101”] = 3If dp[“11111...1111”] == 0 then that means we can find the solution. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to check if the// given array can be partitioned// into K subsets with equal sum#include <bits/stdc++.h>using namespace std; // Function to check whether// K required partitions// are possible or notbool isKPartitionPossible(int arr[], int N, int K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset int target = sum / K; // Initialize dp array with -1 int dp[(1 << 15)]; for (int i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for (int mask = 0; mask < (1 << N); mask++) { // if current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for (int i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (!(mask & (1 << i)) && dp[mask] + arr[i] <= target) { // transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 5, 3, 3 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; if (isKPartitionPossible(arr, N, K)) { cout << "Partitions into equal "; cout << "sum is possible.\n"; } else { cout << "Partitions into equal "; cout << "sum is not possible.\n"; }} // Java program to check if the// given array can be partitioned// into K subsets with equal sumimport java.util.*; class GFG{ // Function to check whether// K required partitions// are possible or notstatic boolean isKPartitionPossible(int arr[], int N, int K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; int sum = 0; for(int i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset int target = sum / K; // Initialize dp array with -1 int []dp = new int[(1 << 15)]; for(int i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for(int mask = 0; mask < (1 << N); mask++) { // if current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for(int i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (((mask & (1 << i)) == 0) && dp[mask] + arr[i] <= target) { // Transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 1, 4, 5, 3, 3 }; int N = arr.length; int K = 3; if (isKPartitionPossible(arr, N, K)) { System.out.print("Partitions into equal "); System.out.print("sum is possible.\n"); } else { System.out.print("Partitions into equal "); System.out.print("sum is not possible.\n"); }}} // This code is contributed by Amit Katiyar # Python3 program to check if the# given array can be partitioned# into K subsets with equal sum # Function to check whether# K required partitions# are possible or notdef isKPartitionPossible(arr, N, K): if (K == 1): # Return true as the # entire array is the # answer return True # If total number of # partitions exceeds # size of the array if (N < K): return False sum = 0 for i in range(N): sum += arr[i] # If the array sum is not # divisible by K if (sum % K != 0): # No such partitions are # possible return False # Required sum of # each subset target = sum / K # Initialize dp array with -1 dp = [0 for i in range(1 << 15)] for i in range((1 << N)): dp[i] = -1 # Sum of empty subset # is zero dp[0] = 0 # Iterate over all subsets/masks for mask in range((1 << N)): # If current mask is invalid, # continue if (dp[mask] == -1): continue # Iterate over all array elements for i in range(N): # Check if the current element # can be added to the current # subset/mask if ((mask & (1 << i) == 0) and dp[mask] + arr[i] <= target): # Transition dp[mask | (1 << i)] = ((dp[mask] + arr[i]) % target) if (dp[(1 << N) - 1] == 0): return True else: return False # Driver Codeif __name__ == '__main__': arr = [ 2, 1, 4, 5, 3, 3 ] N = len(arr) K = 3 if (isKPartitionPossible(arr, N, K)): print("Partitions into equal "\ "sum is possible.") else: print("Partitions into equal sum "\ "is not possible.") # This code is contributed by Surendra_Gangwar // C# program to check if the// given array can be partitioned// into K subsets with equal sumusing System; class GFG{ // Function to check whether// K required partitions// are possible or notstatic bool isKPartitionPossible(int []arr, int N, int K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; int sum = 0; for(int i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset int target = sum / K; // Initialize dp array with -1 int []dp = new int[(1 << 15)]; for(int i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for(int mask = 0; mask < (1 << N); mask++) { // If current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for(int i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (((mask & (1 << i)) == 0) && dp[mask] + arr[i] <= target) { // Transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Codepublic static void Main(String[] args){ int []arr = { 2, 1, 4, 5, 3, 3 }; int N = arr.Length; int K = 3; if (isKPartitionPossible(arr, N, K)) { Console.Write("Partitions into equal "); Console.Write("sum is possible.\n"); } else { Console.Write("Partitions into equal "); Console.Write("sum is not possible.\n"); }}} // This code is contributed by Amit Katiyar <script> // JavaScript program to check if the// given array can be partitioned// into K subsets with equal sum // Function to check whether// K required partitions// are possible or notfunction isKPartitionPossible(arr, N, K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; let sum = 0; for(let i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset let target = sum / K; // Initialize dp array with -1 let dp = Array.from({length: (1 << 15)}, (_, i) => 0); for(let i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for(let mask = 0; mask < (1 << N); mask++) { // if current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for(let i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (((mask & (1 << i)) == 0) && dp[mask] + arr[i] <= target) { // Transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Code let arr = [ 2, 1, 4, 5, 3, 3 ]; let N = arr.length; let K = 3; if (isKPartitionPossible(arr, N, K)) { document.write("Partitions into equal "); document.write("sum is possible.\n"); } else { document.write("Partitions into equal "); document.write("sum is not possible.\n"); } </script> Output: Partitions into equal sum is possible. Time Complexity: O (N * 2 N) Auxiliary Space: O (2 N) SURENDRA_GANGWAR amit143katiyar splevel62 singghakshay Constructive Algorithms subset Arrays Bit Magic Dynamic Programming Mathematical Recursion Arrays Dynamic Programming Mathematical Recursion Bit Magic subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24924, "s": 24896, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25151, "s": 24924, "text": "Given an integer array arr[] of consisting of N integers, the task is check if it is possible to divide the given array into K non-empty subsets of equal sum such that every array element is part of a single subset.Examples: " }, { "code": null, "e": 25323, "s": 25151, "text": "Input: arr[] = {2, 1, 4, 5, 6}, K = 3 Output: Yes Explanation: Possible subsets of given array are {2, 4}, (1, 5} and {6}Input: arr[] = {2, 1, 5, 5, 6}, K = 3 Output: No " }, { "code": null, "e": 25468, "s": 25325, "text": "For the recursive approach, refer to Partition of a set into K subsets with equal sum.Approach: Follow the steps below to solve the problem: " }, { "code": null, "e": 25761, "s": 25468, "text": "The idea is to use mask to determine the current state. The current state will tell us about the subset already formed ( which numbers are already selected ). For example: arr[] = [2, 1, 4, 3, 5, 6, 2], mask = (1100101), which means that { 2, 1, 5, 2 } are already chosen in the current mask." }, { "code": null, "e": 25866, "s": 25761, "text": "For any current state mask, the jth element will be added to it based on the following two conditions: " }, { "code": null, "e": 25995, "s": 25866, "text": "The jth bit is not set in the mask (mask&(1<<j) == 0)sum (mask) + arr[j] <= target ( where target = (Sum of array elements) / K)" }, { "code": null, "e": 26049, "s": 25995, "text": "The jth bit is not set in the mask (mask&(1<<j) == 0)" }, { "code": null, "e": 26125, "s": 26049, "text": "sum (mask) + arr[j] <= target ( where target = (Sum of array elements) / K)" }, { "code": null, "e": 26233, "s": 26125, "text": "Maintain a table dp[] such that dp[i] store the sum of elements in mask i. So, the dp transitions will be: " }, { "code": null, "e": 26533, "s": 26233, "text": "dp[i | (1 << j)] = (dp[i] + arr[j]) % target Illustration: arr [ ] = [4, 3, 2, 3, 5, 2, 1], K = 4, tar = 5 dp[“1100101”] implies that { 4, 3, 5, 1 } are chosen Hence, Sum = 4 + 3 + 5 + 1 = 13, 13 % 5 = 3. Hence, dp[“1100101”] = 3If dp[“11111...1111”] == 0 then that means we can find the solution. " }, { "code": null, "e": 26582, "s": 26533, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 26586, "s": 26582, "text": "C++" }, { "code": null, "e": 26591, "s": 26586, "text": "Java" }, { "code": null, "e": 26599, "s": 26591, "text": "Python3" }, { "code": null, "e": 26602, "s": 26599, "text": "C#" }, { "code": null, "e": 26613, "s": 26602, "text": "Javascript" }, { "code": "// C++ program to check if the// given array can be partitioned// into K subsets with equal sum#include <bits/stdc++.h>using namespace std; // Function to check whether// K required partitions// are possible or notbool isKPartitionPossible(int arr[], int N, int K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; int sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset int target = sum / K; // Initialize dp array with -1 int dp[(1 << 15)]; for (int i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for (int mask = 0; mask < (1 << N); mask++) { // if current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for (int i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (!(mask & (1 << i)) && dp[mask] + arr[i] <= target) { // transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 5, 3, 3 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; if (isKPartitionPossible(arr, N, K)) { cout << \"Partitions into equal \"; cout << \"sum is possible.\\n\"; } else { cout << \"Partitions into equal \"; cout << \"sum is not possible.\\n\"; }}", "e": 28687, "s": 26613, "text": null }, { "code": "// Java program to check if the// given array can be partitioned// into K subsets with equal sumimport java.util.*; class GFG{ // Function to check whether// K required partitions// are possible or notstatic boolean isKPartitionPossible(int arr[], int N, int K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; int sum = 0; for(int i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset int target = sum / K; // Initialize dp array with -1 int []dp = new int[(1 << 15)]; for(int i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for(int mask = 0; mask < (1 << N); mask++) { // if current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for(int i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (((mask & (1 << i)) == 0) && dp[mask] + arr[i] <= target) { // Transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 1, 4, 5, 3, 3 }; int N = arr.length; int K = 3; if (isKPartitionPossible(arr, N, K)) { System.out.print(\"Partitions into equal \"); System.out.print(\"sum is possible.\\n\"); } else { System.out.print(\"Partitions into equal \"); System.out.print(\"sum is not possible.\\n\"); }}} // This code is contributed by Amit Katiyar", "e": 30899, "s": 28687, "text": null }, { "code": "# Python3 program to check if the# given array can be partitioned# into K subsets with equal sum # Function to check whether# K required partitions# are possible or notdef isKPartitionPossible(arr, N, K): if (K == 1): # Return true as the # entire array is the # answer return True # If total number of # partitions exceeds # size of the array if (N < K): return False sum = 0 for i in range(N): sum += arr[i] # If the array sum is not # divisible by K if (sum % K != 0): # No such partitions are # possible return False # Required sum of # each subset target = sum / K # Initialize dp array with -1 dp = [0 for i in range(1 << 15)] for i in range((1 << N)): dp[i] = -1 # Sum of empty subset # is zero dp[0] = 0 # Iterate over all subsets/masks for mask in range((1 << N)): # If current mask is invalid, # continue if (dp[mask] == -1): continue # Iterate over all array elements for i in range(N): # Check if the current element # can be added to the current # subset/mask if ((mask & (1 << i) == 0) and dp[mask] + arr[i] <= target): # Transition dp[mask | (1 << i)] = ((dp[mask] + arr[i]) % target) if (dp[(1 << N) - 1] == 0): return True else: return False # Driver Codeif __name__ == '__main__': arr = [ 2, 1, 4, 5, 3, 3 ] N = len(arr) K = 3 if (isKPartitionPossible(arr, N, K)): print(\"Partitions into equal \"\\ \"sum is possible.\") else: print(\"Partitions into equal sum \"\\ \"is not possible.\") # This code is contributed by Surendra_Gangwar", "e": 32847, "s": 30899, "text": null }, { "code": "// C# program to check if the// given array can be partitioned// into K subsets with equal sumusing System; class GFG{ // Function to check whether// K required partitions// are possible or notstatic bool isKPartitionPossible(int []arr, int N, int K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; int sum = 0; for(int i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset int target = sum / K; // Initialize dp array with -1 int []dp = new int[(1 << 15)]; for(int i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for(int mask = 0; mask < (1 << N); mask++) { // If current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for(int i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (((mask & (1 << i)) == 0) && dp[mask] + arr[i] <= target) { // Transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Codepublic static void Main(String[] args){ int []arr = { 2, 1, 4, 5, 3, 3 }; int N = arr.Length; int K = 3; if (isKPartitionPossible(arr, N, K)) { Console.Write(\"Partitions into equal \"); Console.Write(\"sum is possible.\\n\"); } else { Console.Write(\"Partitions into equal \"); Console.Write(\"sum is not possible.\\n\"); }}} // This code is contributed by Amit Katiyar", "e": 35039, "s": 32847, "text": null }, { "code": "<script> // JavaScript program to check if the// given array can be partitioned// into K subsets with equal sum // Function to check whether// K required partitions// are possible or notfunction isKPartitionPossible(arr, N, K){ if (K == 1) // Return true as the // entire array is the // answer return true; // If total number of // partitions exceeds // size of the array if (N < K) return false; let sum = 0; for(let i = 0; i < N; i++) sum += arr[i]; // If the array sum is not // divisible by K if (sum % K != 0) // No such partitions are // possible return false; // Required sum of // each subset let target = sum / K; // Initialize dp array with -1 let dp = Array.from({length: (1 << 15)}, (_, i) => 0); for(let i = 0; i < (1 << N); i++) dp[i] = -1; // Sum of empty subset // is zero dp[0] = 0; // Iterate over all subsets/masks for(let mask = 0; mask < (1 << N); mask++) { // if current mask is invalid, continue if (dp[mask] == -1) continue; // Iterate over all array elements for(let i = 0; i < N; i++) { // Check if the current element // can be added to the current // subset/mask if (((mask & (1 << i)) == 0) && dp[mask] + arr[i] <= target) { // Transition dp[mask | (1 << i)] = (dp[mask] + arr[i]) % target; } } } if (dp[(1 << N) - 1] == 0) return true; else return false;} // Driver Code let arr = [ 2, 1, 4, 5, 3, 3 ]; let N = arr.length; let K = 3; if (isKPartitionPossible(arr, N, K)) { document.write(\"Partitions into equal \"); document.write(\"sum is possible.\\n\"); } else { document.write(\"Partitions into equal \"); document.write(\"sum is not possible.\\n\"); } </script>", "e": 37163, "s": 35039, "text": null }, { "code": null, "e": 37173, "s": 37163, "text": "Output: " }, { "code": null, "e": 37212, "s": 37173, "text": "Partitions into equal sum is possible." }, { "code": null, "e": 37267, "s": 37212, "text": "Time Complexity: O (N * 2 N) Auxiliary Space: O (2 N) " }, { "code": null, "e": 37284, "s": 37267, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 37299, "s": 37284, "text": "amit143katiyar" }, { "code": null, "e": 37309, "s": 37299, "text": "splevel62" }, { "code": null, "e": 37322, "s": 37309, "text": "singghakshay" }, { "code": null, "e": 37346, "s": 37322, "text": "Constructive Algorithms" }, { "code": null, "e": 37353, "s": 37346, "text": "subset" }, { "code": null, "e": 37360, "s": 37353, "text": "Arrays" }, { "code": null, "e": 37370, "s": 37360, "text": "Bit Magic" }, { "code": null, "e": 37390, "s": 37370, "text": "Dynamic Programming" }, { "code": null, "e": 37403, "s": 37390, "text": "Mathematical" }, { "code": null, "e": 37413, "s": 37403, "text": "Recursion" }, { "code": null, "e": 37420, "s": 37413, "text": "Arrays" }, { "code": null, "e": 37440, "s": 37420, "text": "Dynamic Programming" }, { "code": null, "e": 37453, "s": 37440, "text": "Mathematical" }, { "code": null, "e": 37463, "s": 37453, "text": "Recursion" }, { "code": null, "e": 37473, "s": 37463, "text": "Bit Magic" }, { "code": null, "e": 37480, "s": 37473, "text": "subset" }, { "code": null, "e": 37578, "s": 37480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37587, "s": 37578, "text": "Comments" }, { "code": null, "e": 37600, "s": 37587, "text": "Old Comments" }, { "code": null, "e": 37648, "s": 37600, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37692, "s": 37648, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37724, "s": 37692, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37747, "s": 37724, "text": "Introduction to Arrays" }, { "code": null, "e": 37761, "s": 37747, "text": "Linear Search" }, { "code": null, "e": 37788, "s": 37761, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 37834, "s": 37788, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 37902, "s": 37834, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 37948, "s": 37902, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
java.time.LocalDateTime.parse() Method Example
The java.time.LocalDateTime.parse(CharSequence text) method obtains an instance of LocalDateTime from a text string such as 2017-02-03T10:15:30. Following is the declaration for java.time.LocalDateTime.parse(CharSequence text) method. public static LocalDateTime parse(CharSequence text) text − the text to parse such as "2017-02-03T10:15:30", not null. the local date, not null. DateTimeParseException − if the text cannot be parsed. The following example shows the usage of java.time.LocalDateTime.parse(CharSequence text) method. package com.tutorialspoint; import java.time.LocalDateTime; public class LocalDateTimeDemo { public static void main(String[] args) { LocalDateTime date = LocalDateTime.parse("2017-02-03T10:15:30"); System.out.println(date); } } Let us compile and run the above program, this will produce the following result − 2017-02-03T10:15:30 Print Add Notes Bookmark this page
[ { "code": null, "e": 2060, "s": 1915, "text": "The java.time.LocalDateTime.parse(CharSequence text) method obtains an instance of LocalDateTime from a text string such as 2017-02-03T10:15:30." }, { "code": null, "e": 2150, "s": 2060, "text": "Following is the declaration for java.time.LocalDateTime.parse(CharSequence text) method." }, { "code": null, "e": 2204, "s": 2150, "text": "public static LocalDateTime parse(CharSequence text)\n" }, { "code": null, "e": 2270, "s": 2204, "text": "text − the text to parse such as \"2017-02-03T10:15:30\", not null." }, { "code": null, "e": 2296, "s": 2270, "text": "the local date, not null." }, { "code": null, "e": 2351, "s": 2296, "text": "DateTimeParseException − if the text cannot be parsed." }, { "code": null, "e": 2449, "s": 2351, "text": "The following example shows the usage of java.time.LocalDateTime.parse(CharSequence text) method." }, { "code": null, "e": 2702, "s": 2449, "text": "package com.tutorialspoint;\n\nimport java.time.LocalDateTime;\n\npublic class LocalDateTimeDemo {\n public static void main(String[] args) {\n \n LocalDateTime date = LocalDateTime.parse(\"2017-02-03T10:15:30\");\n System.out.println(date); \n }\n}" }, { "code": null, "e": 2785, "s": 2702, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 2806, "s": 2785, "text": "2017-02-03T10:15:30\n" }, { "code": null, "e": 2813, "s": 2806, "text": " Print" }, { "code": null, "e": 2824, "s": 2813, "text": " Add Notes" } ]
Android SQLite Database in Kotlin - GeeksforGeeks
16 Sep, 2021 Android comes with an inbuilt implementation of a database package, which is SQLite, an open-source SQL database that stores data in form of text in devices. In this article, we will look at the implementation of Android SQLite in Kotlin. SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process library and its code is publicly available. It is free for use for any purpose, commercial or private. It is basically an embedded SQL database engine. Ordinary disk files can be easily read and write by SQLite because it does not have any separate server like SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format. We will be building a simple application that will be storing data using SQLite and we will also implement methods to retrieve the data. Below is a sample video to show what we will be doing. 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 Kotlin as the programming language. Step 2: Giving permission to access the storage in the AndroidManifest.xml file Navigate to app > AndroidManifest.xml and add the below code to it. XML <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> Step 3: Working with the activity_main.xml file Navigate to app > res > layout > activity_main.xml. Add the below code to your file. Below is the code for activity_main.xml. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!-- Edit text to enter name --> <EditText android:id="@+id/enterName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name" android:textSize="22sp" android:layout_margin="20sp"/> <!-- Edit text to enter age --> <EditText android:id="@+id/enterAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20sp" android:textSize="22sp" android:hint="Enter Age"/> <!-- Button to add Name --> <Button android:id="@+id/addName" android:layout_width="150sp" android:layout_gravity="center" android:background="@color/colorPrimary" android:text="Add Name" android:textColor="#ffffff" android:textSize="20sp" android:layout_height="wrap_content" android:layout_marginTop="20sp"/> <!-- Button to print Name --> <Button android:id="@+id/printName" android:layout_width="150sp" android:layout_gravity="center" android:background="@color/colorPrimary" android:text="Print Name" android:textColor="#ffffff" android:textSize="20sp" android:layout_height="wrap_content" android:layout_marginTop="20sp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- Text view to get all name --> <TextView android:id="@+id/Name" android:textAlignment="center" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20sp" android:text="Name\n\n" android:textSize="22sp" android:padding="10sp" android:textColor="#000000"/> <!-- Text view to get all ages --> <TextView android:layout_weight="1" android:id="@+id/Age" android:textAlignment="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20sp" android:text="Age\n\n" android:textSize="22sp" android:padding="10sp" android:textColor="#000000"/> </LinearLayout> </LinearLayout> Step 4: Creating a new class for SQLite operations Navigate to app > java > your project’s package name > Right-click on it > New > Kotlin class and name it as DBHelper and add the below code to it. To make the code more understandable, comments are added. Kotlin package com.release.gfg1 import android.content.ContentValuesimport android.content.Contextimport android.database.Cursorimport android.database.sqlite.SQLiteDatabaseimport android.database.sqlite.SQLiteOpenHelper class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) { // below is the method for creating a database by a sqlite query override fun onCreate(db: SQLiteDatabase) { // below is a sqlite query, where column names // along with their data types is given val query = ("CREATE TABLE " + TABLE_NAME + " (" + ID_COL + " INTEGER PRIMARY KEY, " + NAME_COl + " TEXT," + AGE_COL + " TEXT" + ")") // we are calling sqlite // method for executing our query db.execSQL(query) } override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) { // this method is to check if table already exists db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME) onCreate(db) } // This method is for adding data in our database fun addName(name : String, age : String ){ // below we are creating // a content values variable val values = ContentValues() // we are inserting our values // in the form of key-value pair values.put(NAME_COl, name) values.put(AGE_COL, age) // here we are creating a // writable variable of // our database as we want to // insert value in our database val db = this.writableDatabase // all values are inserted into database db.insert(TABLE_NAME, null, values) // at last we are // closing our database db.close() } // below method is to get // all data from our database fun getName(): Cursor? { // here we are creating a readable // variable of our database // as we want to read value from it val db = this.readableDatabase // below code returns a cursor to // read data from the database return db.rawQuery("SELECT * FROM " + TABLE_NAME, null) } companion object{ // here we have defined variables for our database // below is variable for database name private val DATABASE_NAME = "GEEKS_FOR_GEEKS" // below is the variable for database version private val DATABASE_VERSION = 1 // below is the variable for table name val TABLE_NAME = "gfg_table" // below is the variable for id column val ID_COL = "id" // below is the variable for name column val NAME_COl = "name" // below is the variable for age column val AGE_COL = "age" }} Step 5: Working with MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin package com.release.gfg1 import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // below code is to add on click // listener to our add name button addName.setOnClickListener{ // below we have created // a new DBHelper class, // and passed context to it val db = DBHelper(this, null) // creating variables for values // in name and age edit texts val name = enterName.text.toString() val age = enterAge.text.toString() // calling method to add // name to our database db.addName(name, age) // Toast to message on the screen Toast.makeText(this, name + " added to database", Toast.LENGTH_LONG).show() // at last, clearing edit texts enterName.text.clear() enterAge.text.clear() } // below code is to add on click // listener to our print name button printName.setOnClickListener{ // creating a DBHelper class // and passing context to it val db = DBHelper(this, null) // below is the variable for cursor // we have called method to get // all names from our database // and add to name text view val cursor = db.getName() // moving the cursor to first position and // appending value in the text view cursor!!.moveToFirst() Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n") Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n") // moving our cursor to next // position and appending values while(cursor.moveToNext()){ Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n") Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n") } // at last we close our cursor cursor.close() } }} Now run your app and see the output. Output: singghakshay anikakapoor ruhelaa48 Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example How to Change the Background Color After Clicking the Button in Android? Android Listview in Java with Example Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Android Menus MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25142, "s": 25114, "text": "\n16 Sep, 2021" }, { "code": null, "e": 25382, "s": 25142, "text": "Android comes with an inbuilt implementation of a database package, which is SQLite, an open-source SQL database that stores data in form of text in devices. In this article, we will look at the implementation of Android SQLite in Kotlin. " }, { "code": null, "e": 26033, "s": 25382, "text": "SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process library and its code is publicly available. It is free for use for any purpose, commercial or private. It is basically an embedded SQL database engine. Ordinary disk files can be easily read and write by SQLite because it does not have any separate server like SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format." }, { "code": null, "e": 26225, "s": 26033, "text": "We will be building a simple application that will be storing data using SQLite and we will also implement methods to retrieve the data. Below is a sample video to show what we will be doing." }, { "code": null, "e": 26254, "s": 26225, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26418, "s": 26254, "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 Kotlin as the programming language." }, { "code": null, "e": 26498, "s": 26418, "text": "Step 2: Giving permission to access the storage in the AndroidManifest.xml file" }, { "code": null, "e": 26566, "s": 26498, "text": "Navigate to app > AndroidManifest.xml and add the below code to it." }, { "code": null, "e": 26570, "s": 26566, "text": "XML" }, { "code": "<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />", "e": 26646, "s": 26570, "text": null }, { "code": null, "e": 26694, "s": 26646, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26820, "s": 26694, "text": "Navigate to app > res > layout > activity_main.xml. Add the below code to your file. Below is the code for activity_main.xml." }, { "code": null, "e": 26824, "s": 26820, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!-- Edit text to enter name --> <EditText android:id=\"@+id/enterName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter Name\" android:textSize=\"22sp\" android:layout_margin=\"20sp\"/> <!-- Edit text to enter age --> <EditText android:id=\"@+id/enterAge\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20sp\" android:textSize=\"22sp\" android:hint=\"Enter Age\"/> <!-- Button to add Name --> <Button android:id=\"@+id/addName\" android:layout_width=\"150sp\" android:layout_gravity=\"center\" android:background=\"@color/colorPrimary\" android:text=\"Add Name\" android:textColor=\"#ffffff\" android:textSize=\"20sp\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20sp\"/> <!-- Button to print Name --> <Button android:id=\"@+id/printName\" android:layout_width=\"150sp\" android:layout_gravity=\"center\" android:background=\"@color/colorPrimary\" android:text=\"Print Name\" android:textColor=\"#ffffff\" android:textSize=\"20sp\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20sp\"/> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!-- Text view to get all name --> <TextView android:id=\"@+id/Name\" android:textAlignment=\"center\" android:layout_weight=\"1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20sp\" android:text=\"Name\\n\\n\" android:textSize=\"22sp\" android:padding=\"10sp\" android:textColor=\"#000000\"/> <!-- Text view to get all ages --> <TextView android:layout_weight=\"1\" android:id=\"@+id/Age\" android:textAlignment=\"center\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20sp\" android:text=\"Age\\n\\n\" android:textSize=\"22sp\" android:padding=\"10sp\" android:textColor=\"#000000\"/> </LinearLayout> </LinearLayout>", "e": 29551, "s": 26824, "text": null }, { "code": null, "e": 29602, "s": 29551, "text": "Step 4: Creating a new class for SQLite operations" }, { "code": null, "e": 29808, "s": 29602, "text": "Navigate to app > java > your project’s package name > Right-click on it > New > Kotlin class and name it as DBHelper and add the below code to it. To make the code more understandable, comments are added." }, { "code": null, "e": 29815, "s": 29808, "text": "Kotlin" }, { "code": "package com.release.gfg1 import android.content.ContentValuesimport android.content.Contextimport android.database.Cursorimport android.database.sqlite.SQLiteDatabaseimport android.database.sqlite.SQLiteOpenHelper class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) { // below is the method for creating a database by a sqlite query override fun onCreate(db: SQLiteDatabase) { // below is a sqlite query, where column names // along with their data types is given val query = (\"CREATE TABLE \" + TABLE_NAME + \" (\" + ID_COL + \" INTEGER PRIMARY KEY, \" + NAME_COl + \" TEXT,\" + AGE_COL + \" TEXT\" + \")\") // we are calling sqlite // method for executing our query db.execSQL(query) } override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) { // this method is to check if table already exists db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME) onCreate(db) } // This method is for adding data in our database fun addName(name : String, age : String ){ // below we are creating // a content values variable val values = ContentValues() // we are inserting our values // in the form of key-value pair values.put(NAME_COl, name) values.put(AGE_COL, age) // here we are creating a // writable variable of // our database as we want to // insert value in our database val db = this.writableDatabase // all values are inserted into database db.insert(TABLE_NAME, null, values) // at last we are // closing our database db.close() } // below method is to get // all data from our database fun getName(): Cursor? { // here we are creating a readable // variable of our database // as we want to read value from it val db = this.readableDatabase // below code returns a cursor to // read data from the database return db.rawQuery(\"SELECT * FROM \" + TABLE_NAME, null) } companion object{ // here we have defined variables for our database // below is variable for database name private val DATABASE_NAME = \"GEEKS_FOR_GEEKS\" // below is the variable for database version private val DATABASE_VERSION = 1 // below is the variable for table name val TABLE_NAME = \"gfg_table\" // below is the variable for id column val ID_COL = \"id\" // below is the variable for name column val NAME_COl = \"name\" // below is the variable for age column val AGE_COL = \"age\" }}", "e": 32579, "s": 29815, "text": null }, { "code": null, "e": 32621, "s": 32579, "text": "Step 5: Working with MainActivity.kt file" }, { "code": null, "e": 32807, "s": 32621, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32814, "s": 32807, "text": "Kotlin" }, { "code": "package com.release.gfg1 import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // below code is to add on click // listener to our add name button addName.setOnClickListener{ // below we have created // a new DBHelper class, // and passed context to it val db = DBHelper(this, null) // creating variables for values // in name and age edit texts val name = enterName.text.toString() val age = enterAge.text.toString() // calling method to add // name to our database db.addName(name, age) // Toast to message on the screen Toast.makeText(this, name + \" added to database\", Toast.LENGTH_LONG).show() // at last, clearing edit texts enterName.text.clear() enterAge.text.clear() } // below code is to add on click // listener to our print name button printName.setOnClickListener{ // creating a DBHelper class // and passing context to it val db = DBHelper(this, null) // below is the variable for cursor // we have called method to get // all names from our database // and add to name text view val cursor = db.getName() // moving the cursor to first position and // appending value in the text view cursor!!.moveToFirst() Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + \"\\n\") Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + \"\\n\") // moving our cursor to next // position and appending values while(cursor.moveToNext()){ Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + \"\\n\") Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + \"\\n\") } // at last we close our cursor cursor.close() } }}", "e": 35164, "s": 32814, "text": null }, { "code": null, "e": 35201, "s": 35164, "text": "Now run your app and see the output." }, { "code": null, "e": 35209, "s": 35201, "text": "Output:" }, { "code": null, "e": 35222, "s": 35209, "text": "singghakshay" }, { "code": null, "e": 35234, "s": 35222, "text": "anikakapoor" }, { "code": null, "e": 35244, "s": 35234, "text": "ruhelaa48" }, { "code": null, "e": 35251, "s": 35244, "text": "Picked" }, { "code": null, "e": 35259, "s": 35251, "text": "Android" }, { "code": null, "e": 35266, "s": 35259, "text": "Kotlin" }, { "code": null, "e": 35274, "s": 35266, "text": "Android" }, { "code": null, "e": 35372, "s": 35274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35381, "s": 35372, "text": "Comments" }, { "code": null, "e": 35394, "s": 35381, "text": "Old Comments" }, { "code": null, "e": 35433, "s": 35394, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35475, "s": 35433, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35508, "s": 35475, "text": "GridView in Android with Example" }, { "code": null, "e": 35581, "s": 35508, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 35619, "s": 35581, "text": "Android Listview in Java with Example" }, { "code": null, "e": 35638, "s": 35619, "text": "Android UI Layouts" }, { "code": null, "e": 35651, "s": 35638, "text": "Kotlin Array" }, { "code": null, "e": 35693, "s": 35651, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35707, "s": 35693, "text": "Android Menus" } ]
Pandas Hacks: read_clipboard(). Well, it’s not a hack, but it saves you... | by Adrian Mark Perea | Towards Data Science
We’ve all been there: we’re reading an interesting piece of data on Kaggle, StackOverflow, or some obscure website on the second page of Google (yikes!), and it had enough shimmer to pique our curiosity to lure us to playing with it, because we (cool data science people) are just suckers for them sweet data insights. We ready our Jupyter notebooks, import our favorite EDA libraries, and prepare ourselves to explore our brand new data set. But wait — we hesitate. We realize that we have to go through all the trouble of downloading the data, saving it into the right folder, and importing the data set with the right folder path (oh the woes of a data scientist)! Simply put, no one has that kind of time. Well, we do, but if we were being honest with ourselves, small hurdles like these are usually what make us decide whether we go through with something or not. Luckily, there’s pandas.read_clipboard() to help us. The pandas.read_clipboard() method is as simple as it sounds: it reads copy-pasted tabular data and parses it into a Data Frame. For instance, try running the method after copying the following Data Frame: Voila! It was that easy. No more needless saving of random csv files in your computer. Now you can just copy your data and begin mining in a matter of seconds! What a wonderful time to be a data scientist. Under the hood, the pandas.read_clipboard() method passes the data you have copied into the pandas.read_csv() method, which makes this method that much more powerful. This means that you don’t have to limit yourself to already-clean data. Whatever you can read through read_csv, you can read through read_clipboard. Take, for example, the following csv file from Kaggle’s Titanic data set with the headers removed: 1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S4,1,1,"Futrelle, Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S5,0,3,"Allen, Mr. William Henry",male,35,0,0,373450,8.05,,S6,0,3,"Moran, Mr. James",male,,0,0,330877,8.4583,,Q7,0,1,"McCarthy, Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S8,0,3,"Palsson, Master. Gosta Leonard",male,2,3,1,349909,21.075,,S9,1,3,"Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)",female,27,0,2,347742,11.1333,,S10,1,2,"Nasser, Mrs. Nicholas (Adele Achem)",female,14,1,0,237736,30.0708,,C11,1,3,"Sandstrom, Miss. Marguerite Rut",female,4,1,1,PP 9549,16.7,G6,S12,1,1,"Bonnell, Miss. Elizabeth",female,58,0,0,113783,26.55,C103,S13,0,3,"Saundercock, Mr. William Henry",male,20,0,0,A/5. 2151,8.05,,S14,0,3,"Andersson, Mr. Anders Johan",male,39,1,5,347082,31.275,,S15,0,3,"Vestrom, Miss. Hulda Amanda Adolfina",female,14,0,0,350406,7.8542,,S16,1,2,"Hewlett, Mrs. (Mary D Kingcome) ",female,55,0,0,248706,16,,S17,0,3,"Rice, Master. Eugene",male,2,4,1,382652,29.125,,Q18,1,2,"Williams, Mr. Charles Eugene",male,,0,0,244373,13,,S19,0,3,"Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele)",female,31,1,0,345763,18,,S20,1,3,"Masselmani, Mrs. Fatima",female,,0,0,2649,7.225,,C21,0,2,"Fynney, Mr. Joseph J",male,35,0,0,239865,26,,S22,1,2,"Beesley, Mr. Lawrence",male,34,0,0,248698,13,D56,S23,1,3,"McGowan, Miss. Anna ""Annie""",female,15,0,0,330923,8.0292,,Q24,1,1,"Sloper, Mr. William Thompson",male,28,0,0,113788,35.5,A6,S25,0,3,"Palsson, Miss. Torborg Danira",female,8,3,1,349909,21.075,,S26,1,3,"Asplund, Mrs. Carl Oscar (Selma Augusta Emilia Johansson)",female,38,1,5,347077,31.3875,,S27,0,3,"Emir, Mr. Farred Chehab",male,,0,0,2631,7.225,,C28,0,1,"Fortune, Mr. Charles Alexander",male,19,3,2,19950,263,C23 C25 C27,S If you copy this and run read_clipboard, you will notice that the data from the first row will be used as headers. Just like we would when using read_csv, we can pass header=None and names=col_names keyword arguments to read_clipboard in order to fix the problem and supply headers while we’re at it. After copying the csv file above, run the following code: import pandas as pdcolumns = [ 'PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked',]pd.read_clipboard(header=None, names=columns) You can see from the image above that the first row was no longer used for the header, and our headers are now properly named. Nice. There is one caveat in using pd.read_clipboard() : it does not work for notebooks running on the cloud or WSL (sobs in binary). So for those who are working on Jupyter notebooks remotely, I’m sorry to say that you have to stick with using read_csv for now. Aside from that, it is a useful way to quickly get your hands on data and wrangle right away. It’s a wonderful addition to any data scientist’s arsenal. Part-time Data Scientist, part-time Tech Writer, full-time Nerd. I find joy in teaching Machine Learning and Programming in manageable, byte-sized pieces. Yes, I’m also hilarious. Coffee addict. Sucker for data visualization. Willing to give my 1’s and 0’s for the next best Tree Map. Follow me on Twitter and LinkedIn.
[ { "code": null, "e": 615, "s": 172, "text": "We’ve all been there: we’re reading an interesting piece of data on Kaggle, StackOverflow, or some obscure website on the second page of Google (yikes!), and it had enough shimmer to pique our curiosity to lure us to playing with it, because we (cool data science people) are just suckers for them sweet data insights. We ready our Jupyter notebooks, import our favorite EDA libraries, and prepare ourselves to explore our brand new data set." }, { "code": null, "e": 1094, "s": 615, "text": "But wait — we hesitate. We realize that we have to go through all the trouble of downloading the data, saving it into the right folder, and importing the data set with the right folder path (oh the woes of a data scientist)! Simply put, no one has that kind of time. Well, we do, but if we were being honest with ourselves, small hurdles like these are usually what make us decide whether we go through with something or not. Luckily, there’s pandas.read_clipboard() to help us." }, { "code": null, "e": 1300, "s": 1094, "text": "The pandas.read_clipboard() method is as simple as it sounds: it reads copy-pasted tabular data and parses it into a Data Frame. For instance, try running the method after copying the following Data Frame:" }, { "code": null, "e": 1506, "s": 1300, "text": "Voila! It was that easy. No more needless saving of random csv files in your computer. Now you can just copy your data and begin mining in a matter of seconds! What a wonderful time to be a data scientist." }, { "code": null, "e": 1921, "s": 1506, "text": "Under the hood, the pandas.read_clipboard() method passes the data you have copied into the pandas.read_csv() method, which makes this method that much more powerful. This means that you don’t have to limit yourself to already-clean data. Whatever you can read through read_csv, you can read through read_clipboard. Take, for example, the following csv file from Kaggle’s Titanic data set with the headers removed:" }, { "code": null, "e": 3864, "s": 1921, "text": "1,0,3,\"Braund, Mr. Owen Harris\",male,22,1,0,A/5 21171,7.25,,S2,1,1,\"Cumings, Mrs. John Bradley (Florence Briggs Thayer)\",female,38,1,0,PC 17599,71.2833,C85,C3,1,3,\"Heikkinen, Miss. Laina\",female,26,0,0,STON/O2. 3101282,7.925,,S4,1,1,\"Futrelle, Mrs. Jacques Heath (Lily May Peel)\",female,35,1,0,113803,53.1,C123,S5,0,3,\"Allen, Mr. William Henry\",male,35,0,0,373450,8.05,,S6,0,3,\"Moran, Mr. James\",male,,0,0,330877,8.4583,,Q7,0,1,\"McCarthy, Mr. Timothy J\",male,54,0,0,17463,51.8625,E46,S8,0,3,\"Palsson, Master. Gosta Leonard\",male,2,3,1,349909,21.075,,S9,1,3,\"Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)\",female,27,0,2,347742,11.1333,,S10,1,2,\"Nasser, Mrs. Nicholas (Adele Achem)\",female,14,1,0,237736,30.0708,,C11,1,3,\"Sandstrom, Miss. Marguerite Rut\",female,4,1,1,PP 9549,16.7,G6,S12,1,1,\"Bonnell, Miss. Elizabeth\",female,58,0,0,113783,26.55,C103,S13,0,3,\"Saundercock, Mr. William Henry\",male,20,0,0,A/5. 2151,8.05,,S14,0,3,\"Andersson, Mr. Anders Johan\",male,39,1,5,347082,31.275,,S15,0,3,\"Vestrom, Miss. Hulda Amanda Adolfina\",female,14,0,0,350406,7.8542,,S16,1,2,\"Hewlett, Mrs. (Mary D Kingcome) \",female,55,0,0,248706,16,,S17,0,3,\"Rice, Master. Eugene\",male,2,4,1,382652,29.125,,Q18,1,2,\"Williams, Mr. Charles Eugene\",male,,0,0,244373,13,,S19,0,3,\"Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele)\",female,31,1,0,345763,18,,S20,1,3,\"Masselmani, Mrs. Fatima\",female,,0,0,2649,7.225,,C21,0,2,\"Fynney, Mr. Joseph J\",male,35,0,0,239865,26,,S22,1,2,\"Beesley, Mr. Lawrence\",male,34,0,0,248698,13,D56,S23,1,3,\"McGowan, Miss. Anna \"\"Annie\"\"\",female,15,0,0,330923,8.0292,,Q24,1,1,\"Sloper, Mr. William Thompson\",male,28,0,0,113788,35.5,A6,S25,0,3,\"Palsson, Miss. Torborg Danira\",female,8,3,1,349909,21.075,,S26,1,3,\"Asplund, Mrs. Carl Oscar (Selma Augusta Emilia Johansson)\",female,38,1,5,347077,31.3875,,S27,0,3,\"Emir, Mr. Farred Chehab\",male,,0,0,2631,7.225,,C28,0,1,\"Fortune, Mr. Charles Alexander\",male,19,3,2,19950,263,C23 C25 C27,S" }, { "code": null, "e": 3979, "s": 3864, "text": "If you copy this and run read_clipboard, you will notice that the data from the first row will be used as headers." }, { "code": null, "e": 4223, "s": 3979, "text": "Just like we would when using read_csv, we can pass header=None and names=col_names keyword arguments to read_clipboard in order to fix the problem and supply headers while we’re at it. After copying the csv file above, run the following code:" }, { "code": null, "e": 4425, "s": 4223, "text": "import pandas as pdcolumns = [ 'PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked',]pd.read_clipboard(header=None, names=columns)" }, { "code": null, "e": 4558, "s": 4425, "text": "You can see from the image above that the first row was no longer used for the header, and our headers are now properly named. Nice." }, { "code": null, "e": 4815, "s": 4558, "text": "There is one caveat in using pd.read_clipboard() : it does not work for notebooks running on the cloud or WSL (sobs in binary). So for those who are working on Jupyter notebooks remotely, I’m sorry to say that you have to stick with using read_csv for now." }, { "code": null, "e": 4968, "s": 4815, "text": "Aside from that, it is a useful way to quickly get your hands on data and wrangle right away. It’s a wonderful addition to any data scientist’s arsenal." }, { "code": null, "e": 5253, "s": 4968, "text": "Part-time Data Scientist, part-time Tech Writer, full-time Nerd. I find joy in teaching Machine Learning and Programming in manageable, byte-sized pieces. Yes, I’m also hilarious. Coffee addict. Sucker for data visualization. Willing to give my 1’s and 0’s for the next best Tree Map." } ]
Solidity - Variable Scope
Scope of local variables is limited to function in which they are defined but State variables can have three types of scopes. Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated. Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated. Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this. Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this. Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it. Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it. pragma solidity ^0.5.0; contract C { uint public data = 30; uint internal iData= 10; function x() public returns (uint) { data = 3; // internal access return data; } } contract Caller { C c = new C(); function f() public view returns (uint) { return c.data(); //external access } } contract D is C { function y() public returns (uint) { iData = 3; // internal access return iData; } function getResult() public view returns(uint){ uint a = 1; // local variable uint b = 2; uint result = a + b; return storedData; //access the state variable } } 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2681, "s": 2555, "text": "Scope of local variables is limited to function in which they are defined but State variables can have three types of scopes." }, { "code": null, "e": 2837, "s": 2681, "text": "Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated." }, { "code": null, "e": 2993, "s": 2837, "text": "Public − Public state variables can be accessed internally as well as via messages. For a public state variable, an automatic getter function is generated." }, { "code": null, "e": 3136, "s": 2993, "text": "Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this." }, { "code": null, "e": 3279, "s": 3136, "text": "Internal − Internal state variables can be accessed only internally from the current contract or contract deriving from it without using this." }, { "code": null, "e": 3425, "s": 3279, "text": "Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it." }, { "code": null, "e": 3571, "s": 3425, "text": "Private − Private state variables can be accessed only internally from the current contract they are defined not in the derived contract from it." }, { "code": null, "e": 4207, "s": 3571, "text": "pragma solidity ^0.5.0;\ncontract C {\n uint public data = 30;\n uint internal iData= 10;\n \n function x() public returns (uint) {\n data = 3; // internal access\n return data;\n }\n}\ncontract Caller {\n C c = new C();\n function f() public view returns (uint) {\n return c.data(); //external access\n }\n}\ncontract D is C {\n function y() public returns (uint) {\n iData = 3; // internal access\n return iData;\n }\n function getResult() public view returns(uint){\n uint a = 1; // local variable\n uint b = 2;\n uint result = a + b;\n return storedData; //access the state variable\n }\n}" }, { "code": null, "e": 4242, "s": 4207, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4259, "s": 4242, "text": " Abhilash Nelson" }, { "code": null, "e": 4294, "s": 4259, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4311, "s": 4294, "text": " Frahaan Hussain" }, { "code": null, "e": 4346, "s": 4311, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4360, "s": 4346, "text": " Swapnil Kole" }, { "code": null, "e": 4367, "s": 4360, "text": " Print" }, { "code": null, "e": 4378, "s": 4367, "text": " Add Notes" } ]
Interactive climate data visualizations with Python & Plotly | by JP Hwang | Towards Data Science
Bar graphs (or column graphs to be exact) are very, very effective forms of data visualisation. They’re perceptually great, and usually don’t require as much explanation as some of the more unusual plots so. Subplot are not often talked about, but they can be very powerful and effective. Used in a certain way, they can allow us to lay out data in 4 dimensions, as two-dimensional charts can be a two-dimensional grid. Sometimes, they just allow us to nicely lay out multiple graphs in one figure. I have recently been looking at temperature data from the Bureau of Meteorology in Australia. The BOM a great deal of high-quality data, with temperature observations that go back as far as 1910 in many weather stations. Here, I will share how to create plots like these using Python and Plotly / Plotly Express, using this temperature data set. As usual, I included the code for this in my GitLab repo here (climate_data directory), so please feel free to download it and play with it / improve upon it. The original data comes from the BOM’s ACORN-SAT dataset. This is a high-quality dataset, and I didn’t have to do much pre-processing at all. Nonetheless, the data set is relatively large with daily observations from over a hundred sites for a hundred years — so I provide a processed dataset file in the git repo. I assume you’re familiar with python. But even if you’re relatively new, this tutorial shouldn’t be too tricky. Feel free to reach out on twitter or here if you’re not sure about something. You’ll need plotly and pandas. Install them (in your virtual environment) with a simple pip install [PACKAGE NAME]. The dataset includes data from multiple weather observation stations. To get a feel for the data, let’s load it, take a quick look, and then plot just one station’s worth of data. As usual, load the data with: import pandas as pdflat_avg_df = pd.read_csv('climate_data/srcdata/flat_avg_data.csv', index_col=0) The index_col parameter specifies to pandas which column is to be used as the index. Loading CSV files without this parameter can lead to duplication of index columns, resulting in outputs like this. Notice the duplicated index column, where the index column has been saved as ‘Unnamed: 0’. Other than that, the columns should be straightforward. avg_temp_C shows the annual average temperature, rel_avg_temp_C is a relative figure vs the median value for the site, and I also included the site name string, year and datatype. datatype is either tmax or tmin, indicating whether it related to the daily maximum or minimum temperature. For now, let’s just plot the tmax data from one site. We are going to filter the dataframe based on the site name (to simple_df), and pass it to Plotly Express. import plotly.express as pxsimple_df = flat_avg_df[(flat_avg_df.site_name == 'ALBANY AIRPORT') & (flat_avg_df.datatype == 'tmax')]fig = px.bar(simple_df, x='year', y='rel_avg_temp_C', color='rel_avg_temp_C')fig.show() Just like that, we can see the annual relative temperatures measured at Albany Airport. It shows an increasing trend since the measurements began in 1910. But is this occurring everywhere? What if we picked multiple locations? How does that look? Subplots allow you to include multiple plots in one figure. Plotly allows creation of subplots with either Plotly Express or classic Plotly. As you might expect, Plotly Express is quicker and easier to use, albeit with less control. Let’s get started with that. Plotly Express’ subplot functions are based on its facet_row and facet_col parameters, allowing creation of subplots using these categorical variables. Let’s put data from different sites onto rows, and tmin / tmax values onto columns. Running len(flat_avg_df.site_name.unique()), it tells us that there are 112 unique names — that’s probably too many rows to look at for now. I’m going to just pick the first 5 names, and plot the data like so: site_names = flat_avg_df.site_name.unique()short_df = flat_avg_df[flat_avg_df.site_name.isin(site_names[:5])]fig = px.bar(short_df, x='year', y='rel_avg_temp_C', color='rel_avg_temp_C', facet_row='site_name', facet_col='datatype')fig.show() Isn’t that fantastically efficient! X-axes are shared and nicely aligned, which allows us to quickly see which data points are missing. For example, data in the bottom right figure (from Scone Airport) probably only begins in 1963. Our Y-axis scales and colour contour scales are also uniform for easy comparisons. Sure, it’s visually a little messy — but remember, we created this in just 4 lines of code. We can clean it up, but we won’t do that just now. I want to highlight how quickly we can visualise, and compare qualities and properties the datasets as well as the data itself. One limitation of this method is that subplot rows and columns need to be correlated to a particular categorical variable. To plot data from ten different sites using Plotly Express, I could create a new column, say called subplot_cols, assign values (like 1 or 2), based on which plots would be put onto a column, and pass the parameter facet_col=’subplot_cols'. I would also have to do the same thing with rows. This is fine, but it’s really a workaround rather than using the feature as intended. After all, Plotly Express is for exploratory analysis and for very well-organised data. It’s not the most flexible of tools. So, let’s look next at generating subplots with regular Plotly, which will give us more flexibility. The very minimum syntax for creating subplots in Plotly is as follows: fig = make_subplots(rows=n_rows, cols=n_rows) # Create subplot grid# Add subplot trace & assign to each gridfig.add_trace( go.Bar( x=[X_DATA], y=[X_DATA], ), row=[SUBPLOT_ROW], col=[SUBPLOT_ROW],) You will see that the add_trace function needs to be repeated for each subplot used. Preferably, traces are added using loops, rather than manually. Especially as the number of subplots grow in size. Let’s start small. We’ll create a 2 by 2 subplot grid, and plot data from the first four stations (by station name), only plotting the ‘tmax’ values. We saw earlier that not some stations were clearly missing data from some years. It didn’t matter above as Plotly Express took care of dealing with the missing data by omission, but here we cannot do that. We are going to be passing a list or an array as the Y values, and skipping over values will (at best) lead to misalignment in data. As we are dealing with relative values, let’s fill in the missing data with zeroes. (It’s debatable whether this is the optimal thing to do, but we can discuss that on another day.) We have to remember to do this as we pass the data to the plot. So, let’s loop over each subplot, each loop a) collecting the Y data (temperature) for the years to be plotted, and pass that data from within the loop to plotly. It’s relatively straightforward — take a look at this code snippet: Here, I create a list of names (site_names) & a list of years (year_list). I sort the year list, and then loop over the number of subplots (4), with an inner loop going over the year, and when there is no data for that year, I simply specify a value of zero. Finally, I use the data to add a simple trace to our figure, using the .add_trace method. I’ve parameterised the row & column number (the +1 at the end ensures that the numbers start at 1 and 1, rather than 0 and 0). So, unfortunately I’d say that this looks significantly worse. We have plotted the same data, in the same format, but the colours are now meaningless, trace names are gone, and we’ve used about 25 lines of code. D’oh. But let’s keep going — it gets better, I promise. Simply adding subplot titles, marker specifications, adding common y-axis parameters and updating the layout to hide the meaningless legends does wonders: fig = make_subplots( rows=2, cols=2, subplot_titles=site_names)go.Bar( ... marker=dict(color=temp_vals, colorscale='RdYlBu_r'),),fig.update_yaxes(tickvals=[-2, 0, 2], range=[-2.5, 2.5], fixedrange=True)fig.update_layout(showlegend=False) Next, let’s just extend this concept and build our next chart, with as many subplots as we’d like. The modifications look lengthy, but they’re really not. What I’ve done is to: parameterise the number of rows & columns (subplot_rows = ...) in our subplot (so that I can change it easily) parameterise the height & width of the figure (height=120 * subplot_rows, width=230 * subplot_cols), to keep subplot sizes consistent, rather than shrinking or enlarging as the number of rows or columns change. order the station names (names_by_obs = ...)by number of observations, so we can prioritise plotting the ones with most data reduce spacing between subplots (horizontal_spacing=...), and reduce font sizes (font=dict(...). Edit: An earlier version of this writeup used the below code to set the title — as I was not aware that there was a method to access these at : for i in fig['layout']['annotations']: i['font'] = dict(size=10, color='#404040') Instead, you can use this: fig.update_annotations(patch=dict(font=dict(size=10, color='#404040'))) If you *do* need to access any of these properties manually, though, the fig object allows you to do that quite easily, which is great. This is going to blow your mind. I assume that you still have the main dataframe loaded in memory. Okay. Ready? Just run this bit of code: fig = px.bar(flat_avg_df, x='year', y='rel_avg_temp_C', color='rel_avg_temp_C')fig.show() I was just giddy when I saw this plot. Yes, it’s not perfect. But in just two lines of code, I am able to visualise the entire annual dataset, showing aggregate yearly trends in temperature variations, from 112 stations. Just for comparison, I did recreate this in regular Plotly and it took something like 30–40 lines of code, mostly in wrangling data and formatting. (I didn’t include it here.) In this graph, I am stacking the tmax and tmin values, which is not ideal. Let’s separate them. Also, since we are plotting temperatures, let’s stick to red=hot and blue=cold convention, ensuring that the midpoint of the color scale is at zero. (You’ll notice above that zero doesn’t quite line up with the midpoint of the scale) Honestly, I am incredibly happy with how this looks. But there’s a couple of big issues — I am stacking up temperatures to numbers that don’t make any sense, and while Plotly Express deals with missing data, some of these stacks are made up of more observations than others, which skews the output. Data visualisation isn’t just about making pretty pictures, it’s about communicating information to readers. We can do better; let’s normalise the temperatures to indicate a reasonable value, like the sums of hot/cold variations across weather observations stations, in each year. I created a new column in the dataframe, where the temperature value is divided by the number of samples from that year: Once that’s been completed, we can simply plot it the same as before, with the only change being y=’norm_rel_avg_temp_C’. You can see that the figures towards the left side of the image (further in the past) have been scaled up to account for the fact that there are fewer samples. As a final touch, we include formatting elements — figure title, axis title, legend title, and annotation. The legend is resized with a border, and scaled down. This is the result: Nice, isn’t it? I’m pretty happy with the results. Here is the interactive version. Bar plots are very important tools in a data visualisation toolbox. Bar plots allow easy comparisons of values, grouping values together when needed, and are easily understood for their familiarity. Subplots are not as critical, but has high utility. Anyone who’s ever looked at pairplots can attest to this. I personally also find that I often have data that is best visualised divided up, and often want to use subplots. Plotly Express’ feature allowing subplot generation by features save a lot of time, as it reduces effort required in visualising effects of certain categorical variables. Regular Plotly’s subplots features is more powerful — if also more verbose. It allows things like manipulating grid sizes with Plotly’s subplots, so if you are interested in further customised subplot layouts, you may wish to explore that option. I hope the above was useful showing you the kinds of good looking visualisations that can be easily created using Plotly / Plotly Express. Try playing with the parameters — with the number of columns, rows, colormaps, font sizes, whatever. I find that I learn a lot that way. As ever, hit me up if you have any questions or comments. If you liked this, say 👋 / follow on twitter, or follow for updates. I also wrote these articles about producing interactive maps with Plotly, and visualising basketball data.
[ { "code": null, "e": 671, "s": 172, "text": "Bar graphs (or column graphs to be exact) are very, very effective forms of data visualisation. They’re perceptually great, and usually don’t require as much explanation as some of the more unusual plots so. Subplot are not often talked about, but they can be very powerful and effective. Used in a certain way, they can allow us to lay out data in 4 dimensions, as two-dimensional charts can be a two-dimensional grid. Sometimes, they just allow us to nicely lay out multiple graphs in one figure." }, { "code": null, "e": 892, "s": 671, "text": "I have recently been looking at temperature data from the Bureau of Meteorology in Australia. The BOM a great deal of high-quality data, with temperature observations that go back as far as 1910 in many weather stations." }, { "code": null, "e": 1017, "s": 892, "text": "Here, I will share how to create plots like these using Python and Plotly / Plotly Express, using this temperature data set." }, { "code": null, "e": 1176, "s": 1017, "text": "As usual, I included the code for this in my GitLab repo here (climate_data directory), so please feel free to download it and play with it / improve upon it." }, { "code": null, "e": 1491, "s": 1176, "text": "The original data comes from the BOM’s ACORN-SAT dataset. This is a high-quality dataset, and I didn’t have to do much pre-processing at all. Nonetheless, the data set is relatively large with daily observations from over a hundred sites for a hundred years — so I provide a processed dataset file in the git repo." }, { "code": null, "e": 1681, "s": 1491, "text": "I assume you’re familiar with python. But even if you’re relatively new, this tutorial shouldn’t be too tricky. Feel free to reach out on twitter or here if you’re not sure about something." }, { "code": null, "e": 1797, "s": 1681, "text": "You’ll need plotly and pandas. Install them (in your virtual environment) with a simple pip install [PACKAGE NAME]." }, { "code": null, "e": 1977, "s": 1797, "text": "The dataset includes data from multiple weather observation stations. To get a feel for the data, let’s load it, take a quick look, and then plot just one station’s worth of data." }, { "code": null, "e": 2007, "s": 1977, "text": "As usual, load the data with:" }, { "code": null, "e": 2107, "s": 2007, "text": "import pandas as pdflat_avg_df = pd.read_csv('climate_data/srcdata/flat_avg_data.csv', index_col=0)" }, { "code": null, "e": 2192, "s": 2107, "text": "The index_col parameter specifies to pandas which column is to be used as the index." }, { "code": null, "e": 2398, "s": 2192, "text": "Loading CSV files without this parameter can lead to duplication of index columns, resulting in outputs like this. Notice the duplicated index column, where the index column has been saved as ‘Unnamed: 0’." }, { "code": null, "e": 2742, "s": 2398, "text": "Other than that, the columns should be straightforward. avg_temp_C shows the annual average temperature, rel_avg_temp_C is a relative figure vs the median value for the site, and I also included the site name string, year and datatype. datatype is either tmax or tmin, indicating whether it related to the daily maximum or minimum temperature." }, { "code": null, "e": 2903, "s": 2742, "text": "For now, let’s just plot the tmax data from one site. We are going to filter the dataframe based on the site name (to simple_df), and pass it to Plotly Express." }, { "code": null, "e": 3121, "s": 2903, "text": "import plotly.express as pxsimple_df = flat_avg_df[(flat_avg_df.site_name == 'ALBANY AIRPORT') & (flat_avg_df.datatype == 'tmax')]fig = px.bar(simple_df, x='year', y='rel_avg_temp_C', color='rel_avg_temp_C')fig.show()" }, { "code": null, "e": 3209, "s": 3121, "text": "Just like that, we can see the annual relative temperatures measured at Albany Airport." }, { "code": null, "e": 3368, "s": 3209, "text": "It shows an increasing trend since the measurements began in 1910. But is this occurring everywhere? What if we picked multiple locations? How does that look?" }, { "code": null, "e": 3509, "s": 3368, "text": "Subplots allow you to include multiple plots in one figure. Plotly allows creation of subplots with either Plotly Express or classic Plotly." }, { "code": null, "e": 3630, "s": 3509, "text": "As you might expect, Plotly Express is quicker and easier to use, albeit with less control. Let’s get started with that." }, { "code": null, "e": 3866, "s": 3630, "text": "Plotly Express’ subplot functions are based on its facet_row and facet_col parameters, allowing creation of subplots using these categorical variables. Let’s put data from different sites onto rows, and tmin / tmax values onto columns." }, { "code": null, "e": 4076, "s": 3866, "text": "Running len(flat_avg_df.site_name.unique()), it tells us that there are 112 unique names — that’s probably too many rows to look at for now. I’m going to just pick the first 5 names, and plot the data like so:" }, { "code": null, "e": 4317, "s": 4076, "text": "site_names = flat_avg_df.site_name.unique()short_df = flat_avg_df[flat_avg_df.site_name.isin(site_names[:5])]fig = px.bar(short_df, x='year', y='rel_avg_temp_C', color='rel_avg_temp_C', facet_row='site_name', facet_col='datatype')fig.show()" }, { "code": null, "e": 4353, "s": 4317, "text": "Isn’t that fantastically efficient!" }, { "code": null, "e": 4632, "s": 4353, "text": "X-axes are shared and nicely aligned, which allows us to quickly see which data points are missing. For example, data in the bottom right figure (from Scone Airport) probably only begins in 1963. Our Y-axis scales and colour contour scales are also uniform for easy comparisons." }, { "code": null, "e": 4903, "s": 4632, "text": "Sure, it’s visually a little messy — but remember, we created this in just 4 lines of code. We can clean it up, but we won’t do that just now. I want to highlight how quickly we can visualise, and compare qualities and properties the datasets as well as the data itself." }, { "code": null, "e": 5317, "s": 4903, "text": "One limitation of this method is that subplot rows and columns need to be correlated to a particular categorical variable. To plot data from ten different sites using Plotly Express, I could create a new column, say called subplot_cols, assign values (like 1 or 2), based on which plots would be put onto a column, and pass the parameter facet_col=’subplot_cols'. I would also have to do the same thing with rows." }, { "code": null, "e": 5528, "s": 5317, "text": "This is fine, but it’s really a workaround rather than using the feature as intended. After all, Plotly Express is for exploratory analysis and for very well-organised data. It’s not the most flexible of tools." }, { "code": null, "e": 5629, "s": 5528, "text": "So, let’s look next at generating subplots with regular Plotly, which will give us more flexibility." }, { "code": null, "e": 5700, "s": 5629, "text": "The very minimum syntax for creating subplots in Plotly is as follows:" }, { "code": null, "e": 5921, "s": 5700, "text": "fig = make_subplots(rows=n_rows, cols=n_rows) # Create subplot grid# Add subplot trace & assign to each gridfig.add_trace( go.Bar( x=[X_DATA], y=[X_DATA], ), row=[SUBPLOT_ROW], col=[SUBPLOT_ROW],)" }, { "code": null, "e": 6121, "s": 5921, "text": "You will see that the add_trace function needs to be repeated for each subplot used. Preferably, traces are added using loops, rather than manually. Especially as the number of subplots grow in size." }, { "code": null, "e": 6271, "s": 6121, "text": "Let’s start small. We’ll create a 2 by 2 subplot grid, and plot data from the first four stations (by station name), only plotting the ‘tmax’ values." }, { "code": null, "e": 6610, "s": 6271, "text": "We saw earlier that not some stations were clearly missing data from some years. It didn’t matter above as Plotly Express took care of dealing with the missing data by omission, but here we cannot do that. We are going to be passing a list or an array as the Y values, and skipping over values will (at best) lead to misalignment in data." }, { "code": null, "e": 6856, "s": 6610, "text": "As we are dealing with relative values, let’s fill in the missing data with zeroes. (It’s debatable whether this is the optimal thing to do, but we can discuss that on another day.) We have to remember to do this as we pass the data to the plot." }, { "code": null, "e": 7087, "s": 6856, "text": "So, let’s loop over each subplot, each loop a) collecting the Y data (temperature) for the years to be plotted, and pass that data from within the loop to plotly. It’s relatively straightforward — take a look at this code snippet:" }, { "code": null, "e": 7346, "s": 7087, "text": "Here, I create a list of names (site_names) & a list of years (year_list). I sort the year list, and then loop over the number of subplots (4), with an inner loop going over the year, and when there is no data for that year, I simply specify a value of zero." }, { "code": null, "e": 7563, "s": 7346, "text": "Finally, I use the data to add a simple trace to our figure, using the .add_trace method. I’ve parameterised the row & column number (the +1 at the end ensures that the numbers start at 1 and 1, rather than 0 and 0)." }, { "code": null, "e": 7781, "s": 7563, "text": "So, unfortunately I’d say that this looks significantly worse. We have plotted the same data, in the same format, but the colours are now meaningless, trace names are gone, and we’ve used about 25 lines of code. D’oh." }, { "code": null, "e": 7831, "s": 7781, "text": "But let’s keep going — it gets better, I promise." }, { "code": null, "e": 7986, "s": 7831, "text": "Simply adding subplot titles, marker specifications, adding common y-axis parameters and updating the layout to hide the meaningless legends does wonders:" }, { "code": null, "e": 8236, "s": 7986, "text": "fig = make_subplots( rows=2, cols=2, subplot_titles=site_names)go.Bar( ... marker=dict(color=temp_vals, colorscale='RdYlBu_r'),),fig.update_yaxes(tickvals=[-2, 0, 2], range=[-2.5, 2.5], fixedrange=True)fig.update_layout(showlegend=False)" }, { "code": null, "e": 8335, "s": 8236, "text": "Next, let’s just extend this concept and build our next chart, with as many subplots as we’d like." }, { "code": null, "e": 8413, "s": 8335, "text": "The modifications look lengthy, but they’re really not. What I’ve done is to:" }, { "code": null, "e": 8524, "s": 8413, "text": "parameterise the number of rows & columns (subplot_rows = ...) in our subplot (so that I can change it easily)" }, { "code": null, "e": 8735, "s": 8524, "text": "parameterise the height & width of the figure (height=120 * subplot_rows, width=230 * subplot_cols), to keep subplot sizes consistent, rather than shrinking or enlarging as the number of rows or columns change." }, { "code": null, "e": 8860, "s": 8735, "text": "order the station names (names_by_obs = ...)by number of observations, so we can prioritise plotting the ones with most data" }, { "code": null, "e": 8922, "s": 8860, "text": "reduce spacing between subplots (horizontal_spacing=...), and" }, { "code": null, "e": 8957, "s": 8922, "text": "reduce font sizes (font=dict(...)." }, { "code": null, "e": 9101, "s": 8957, "text": "Edit: An earlier version of this writeup used the below code to set the title — as I was not aware that there was a method to access these at :" }, { "code": null, "e": 9186, "s": 9101, "text": "for i in fig['layout']['annotations']: i['font'] = dict(size=10, color='#404040')" }, { "code": null, "e": 9213, "s": 9186, "text": "Instead, you can use this:" }, { "code": null, "e": 9285, "s": 9213, "text": "fig.update_annotations(patch=dict(font=dict(size=10, color='#404040')))" }, { "code": null, "e": 9421, "s": 9285, "text": "If you *do* need to access any of these properties manually, though, the fig object allows you to do that quite easily, which is great." }, { "code": null, "e": 9560, "s": 9421, "text": "This is going to blow your mind. I assume that you still have the main dataframe loaded in memory. Okay. Ready? Just run this bit of code:" }, { "code": null, "e": 9650, "s": 9560, "text": "fig = px.bar(flat_avg_df, x='year', y='rel_avg_temp_C', color='rel_avg_temp_C')fig.show()" }, { "code": null, "e": 9871, "s": 9650, "text": "I was just giddy when I saw this plot. Yes, it’s not perfect. But in just two lines of code, I am able to visualise the entire annual dataset, showing aggregate yearly trends in temperature variations, from 112 stations." }, { "code": null, "e": 10047, "s": 9871, "text": "Just for comparison, I did recreate this in regular Plotly and it took something like 30–40 lines of code, mostly in wrangling data and formatting. (I didn’t include it here.)" }, { "code": null, "e": 10377, "s": 10047, "text": "In this graph, I am stacking the tmax and tmin values, which is not ideal. Let’s separate them. Also, since we are plotting temperatures, let’s stick to red=hot and blue=cold convention, ensuring that the midpoint of the color scale is at zero. (You’ll notice above that zero doesn’t quite line up with the midpoint of the scale)" }, { "code": null, "e": 10676, "s": 10377, "text": "Honestly, I am incredibly happy with how this looks. But there’s a couple of big issues — I am stacking up temperatures to numbers that don’t make any sense, and while Plotly Express deals with missing data, some of these stacks are made up of more observations than others, which skews the output." }, { "code": null, "e": 10957, "s": 10676, "text": "Data visualisation isn’t just about making pretty pictures, it’s about communicating information to readers. We can do better; let’s normalise the temperatures to indicate a reasonable value, like the sums of hot/cold variations across weather observations stations, in each year." }, { "code": null, "e": 11078, "s": 10957, "text": "I created a new column in the dataframe, where the temperature value is divided by the number of samples from that year:" }, { "code": null, "e": 11200, "s": 11078, "text": "Once that’s been completed, we can simply plot it the same as before, with the only change being y=’norm_rel_avg_temp_C’." }, { "code": null, "e": 11360, "s": 11200, "text": "You can see that the figures towards the left side of the image (further in the past) have been scaled up to account for the fact that there are fewer samples." }, { "code": null, "e": 11541, "s": 11360, "text": "As a final touch, we include formatting elements — figure title, axis title, legend title, and annotation. The legend is resized with a border, and scaled down. This is the result:" }, { "code": null, "e": 11625, "s": 11541, "text": "Nice, isn’t it? I’m pretty happy with the results. Here is the interactive version." }, { "code": null, "e": 11824, "s": 11625, "text": "Bar plots are very important tools in a data visualisation toolbox. Bar plots allow easy comparisons of values, grouping values together when needed, and are easily understood for their familiarity." }, { "code": null, "e": 12219, "s": 11824, "text": "Subplots are not as critical, but has high utility. Anyone who’s ever looked at pairplots can attest to this. I personally also find that I often have data that is best visualised divided up, and often want to use subplots. Plotly Express’ feature allowing subplot generation by features save a lot of time, as it reduces effort required in visualising effects of certain categorical variables." }, { "code": null, "e": 12466, "s": 12219, "text": "Regular Plotly’s subplots features is more powerful — if also more verbose. It allows things like manipulating grid sizes with Plotly’s subplots, so if you are interested in further customised subplot layouts, you may wish to explore that option." }, { "code": null, "e": 12742, "s": 12466, "text": "I hope the above was useful showing you the kinds of good looking visualisations that can be easily created using Plotly / Plotly Express. Try playing with the parameters — with the number of columns, rows, colormaps, font sizes, whatever. I find that I learn a lot that way." }, { "code": null, "e": 12800, "s": 12742, "text": "As ever, hit me up if you have any questions or comments." } ]
How to print div content using jQuery?
Let’s say we have the following button − <input type='button' id='buttonId' value='Press Me To print the data'> On click of the above button, call the function() with on() − $('#buttonId').on('click', function () { displayTheData(); }) The above function is using the html() to display the following div − <div id='printThisDivIdOnButtonClick'> <p>I am inside the div tag...</p> </div> Following is the complete code to print div content − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <body> <div id='printThisDivIdOnButtonClick'> <p>I am inside the div tag...</p> </div> <p>I am not inside the div tag...</p> <input type='button' id='buttonId' value='Press Me To print the data'> <div id="printTheDivisionValue"></div> </body> <script> $('#buttonId').on('click', function () { displayTheData(); }) function displayTheData() { $(document).ready(function () { $("#printTheDivisionValue").html($("#printThisDivIdOnButtonClick").html()); }); } </script> </html> To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor. The output is as follows − Now click the button, you will get the following output. The output is as follows −
[ { "code": null, "e": 1103, "s": 1062, "text": "Let’s say we have the following button −" }, { "code": null, "e": 1174, "s": 1103, "text": "<input type='button' id='buttonId' value='Press Me To print the data'>" }, { "code": null, "e": 1236, "s": 1174, "text": "On click of the above button, call the function() with on() −" }, { "code": null, "e": 1301, "s": 1236, "text": "$('#buttonId').on('click', function () {\n displayTheData();\n})" }, { "code": null, "e": 1371, "s": 1301, "text": "The above function is using the html() to display the following div −" }, { "code": null, "e": 1454, "s": 1371, "text": "<div id='printThisDivIdOnButtonClick'>\n <p>I am inside the div tag...</p>\n</div>" }, { "code": null, "e": 1508, "s": 1454, "text": "Following is the complete code to print div content −" }, { "code": null, "e": 1519, "s": 1508, "text": " Live Demo" }, { "code": null, "e": 2563, "s": 1519, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n<body>\n <div id='printThisDivIdOnButtonClick'>\n <p>I am inside the div tag...</p>\n </div>\n <p>I am not inside the div tag...</p>\n <input type='button' id='buttonId' value='Press Me To print the data'>\n <div id=\"printTheDivisionValue\"></div>\n</body>\n<script>\n $('#buttonId').on('click', function () {\n displayTheData();\n })\n function displayTheData() {\n $(document).ready(function () {\n $(\"#printTheDivisionValue\").html($(\"#printThisDivIdOnButtonClick\").html());\n });\n }\n</script>\n</html>" }, { "code": null, "e": 2724, "s": 2563, "text": "To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2751, "s": 2724, "text": "The output is as follows −" }, { "code": null, "e": 2808, "s": 2751, "text": "Now click the button, you will get the following output." }, { "code": null, "e": 2835, "s": 2808, "text": "The output is as follows −" } ]
Built-in Functions in AWK - GeeksforGeeks
23 Feb, 2018 AWK has lots of built-in functions for numeric, string, input, and output operations. Awk has the following two types of high level built-in function categories: Built-in functions for numeric operations. Built-in functions for string operations. Prerequisite – AWK command in Unix/Linux Built-in functions for Numeric operations 1. Awk int(n) function: int() function gives us the integer part of the given argument. This produces the lowest integer part of given n. n is any number with or without floating point. If you the whole number as an argument, this function returns the same. Examples:Input : $ awk 'BEGIN{print int(3.534);print int(4);print int(-5.223);print int(-5);}' Output : 3 4 -5 -5 Input : $ awk 'BEGIN{print int(3.534);print int(4);print int(-5.223);print int(-5);}' Output : 3 4 -5 -5 2. awk log(n) function: log() function provides natural logarithmic(with base e) of given amount n. log() returns logarithmic value only when n is positive number. If we give any invalid number(even negative), it throws an error. Examples:Input : $ awk 'BEGIN{print log(3.534);print log(4);print log(0);print log(-5);print log(-1);}' Output : 1.26243 1.38629 -inf awk: cmd. line:1: warning: log: received negative argument -5 nan awk: cmd. line:1: warning: log: received negative argument -1 nan Input : $ awk 'BEGIN{print log(3.534);print log(4);print log(0);print log(-5);print log(-1);}' Output : 1.26243 1.38629 -inf awk: cmd. line:1: warning: log: received negative argument -5 nan awk: cmd. line:1: warning: log: received negative argument -1 nan Explanation: Returns -inf when given zero and gives nan error when negative number is given. 3. awk sqrt(n) function: sqrt() function gives the positive root for the given integer n. This function also accepts the positive number. Examples:Input : $ awk 'BEGIN{print sqrt(16);print sqrt(0);print sqrt(-12);}' Output : 4 0 awk: cmd. line:1: warning: sqrt: called with negative argument -12 -nan Input : $ awk 'BEGIN{print sqrt(16);print sqrt(0);print sqrt(-12);}' Output : 4 0 awk: cmd. line:1: warning: sqrt: called with negative argument -12 -nan Explanation: It returns nan error if we give negative number as argument. 4. awk sin(n) function: sin() function gives sine value of n, with n in radians. Examples:Input : $ awk 'BEGIN{print sin(-60);print sin(90);print sin(45);}' Output :0.304811 0.893997 0.850904 Input : $ awk 'BEGIN{print sin(-60);print sin(90);print sin(45);}' Output :0.304811 0.893997 0.850904 5. awk cos(n) function: cos() function gives cosine value of n, with n in radians. Examples:Input : $ awk 'BEGIN{print cos(-60);print cos(90);print cos(45);}' Output :-0.952413 -0.448074 0.525322 Input : $ awk 'BEGIN{print cos(-60);print cos(90);print cos(45);}' Output :-0.952413 -0.448074 0.525322 Built-in Functions for String Operations 1. awk index(str1, str2) Function: This searches the string str1 for the first occurrences of the string str2, and returns the position in characters where that occurrence begins in the string str1. String indices in awk starts from 1. Example:Input: awk 'BEGIN{print index("Graphic", "ph"); print index("University", "abc")}' Output: 4 0 Input: awk 'BEGIN{print index("Graphic", "ph"); print index("University", "abc")}' Output: 4 0 Explanation: Returns 0 if str2 is not found in str1. 2. awk length(string) Function: The length() function calculates the length of a string. Example:Input: $ awk 'BEGIN{print length("Graphic Era University")}' Output: 22 Input: $ awk 'BEGIN{print length("Graphic Era University")}' Output: 22 Explanation: Length of the string also includes spaces. 3. awk substr(s, p, n) Function: The length() function is used to extract substring function from a string. Returns substring of string s at beginning position p up to a maximum length of n. If n is not supplied, the rest of the string from p is used. Example:Input: $ awk 'BEGIN{print substr("Graphic Era University", 9)}' Output: Era University Input: $ awk 'BEGIN{print substr("Graphic Era University", 9, 8)}' Output: Era Univ Input: $ awk 'BEGIN{print substr("Graphic Era University", 9)}' Output: Era University Input: $ awk 'BEGIN{print substr("Graphic Era University", 9, 8)}' Output: Era Univ 4. awk tolower(s) Function: Translate all uppercase characters in string s to lowercase and returns the new string. Example:Input: $ awk 'BEGIN{print tolower("GEEKSFORGEEKS")}' Output: geeksforgeeks Input: $ awk 'BEGIN{print tolower("GEEKSFORGEEKS")}' Output: geeksforgeeks 5. awk toupper(s) Function: Translate all lowercase characters in string s to uppercase and returns the new string. Example:Input: $ awk 'BEGIN{print toupper("geeksforgeeks")}' Output: GEEKSFORGEEKS Input: $ awk 'BEGIN{print toupper("geeksforgeeks")}' Output: GEEKSFORGEEKS 6. awk split(string, array, fieldsep) Function: This divides string into pieces separated by fieldsep, and stores the pieces in array. The first piece is stored in array[1], the second piece in array[2], and so forth. The string value of the third argument, fieldsep, describe where to split string. Example:Input: $ awk 'BEGIN{string="My Nationality Is Indian"; fieldsep=" "; n=split(string, array, fieldsep); for(i=1; i<=n; i++){printf("%s\n", array[i]);}}' Output: My Nationality Is Indian Input: $ awk 'BEGIN{string="My Nationality Is Indian"; fieldsep=" "; n=split(string, array, fieldsep); for(i=1; i<=n; i++){printf("%s\n", array[i]);}}' Output: My Nationality Is Indian Explanation: The above script breaks up the sentence into words, using a space as the character separating the words. linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n23 Feb, 2018" }, { "code": null, "e": 24568, "s": 24406, "text": "AWK has lots of built-in functions for numeric, string, input, and output operations. Awk has the following two types of high level built-in function categories:" }, { "code": null, "e": 24611, "s": 24568, "text": "Built-in functions for numeric operations." }, { "code": null, "e": 24653, "s": 24611, "text": "Built-in functions for string operations." }, { "code": null, "e": 24694, "s": 24653, "text": "Prerequisite – AWK command in Unix/Linux" }, { "code": null, "e": 24736, "s": 24694, "text": "Built-in functions for Numeric operations" }, { "code": null, "e": 24994, "s": 24736, "text": "1. Awk int(n) function: int() function gives us the integer part of the given argument. This produces the lowest integer part of given n. n is any number with or without floating point. If you the whole number as an argument, this function returns the same." }, { "code": null, "e": 25136, "s": 24994, "text": "Examples:Input : $ awk 'BEGIN{print int(3.534);print int(4);print int(-5.223);print int(-5);}'\nOutput : 3\n 4\n -5\n -5\n" }, { "code": null, "e": 25269, "s": 25136, "text": "Input : $ awk 'BEGIN{print int(3.534);print int(4);print int(-5.223);print int(-5);}'\nOutput : 3\n 4\n -5\n -5\n" }, { "code": null, "e": 25499, "s": 25269, "text": "2. awk log(n) function: log() function provides natural logarithmic(with base e) of given amount n. log() returns logarithmic value only when n is positive number. If we give any invalid number(even negative), it throws an error." }, { "code": null, "e": 25820, "s": 25499, "text": "Examples:Input : $ awk 'BEGIN{print log(3.534);print log(4);print log(0);print log(-5);print log(-1);}'\nOutput : 1.26243\n 1.38629\n -inf\n awk: cmd. line:1: warning: log: received negative argument -5\n nan\n awk: cmd. line:1: warning: log: received negative argument -1\n nan\n" }, { "code": null, "e": 26132, "s": 25820, "text": "Input : $ awk 'BEGIN{print log(3.534);print log(4);print log(0);print log(-5);print log(-1);}'\nOutput : 1.26243\n 1.38629\n -inf\n awk: cmd. line:1: warning: log: received negative argument -5\n nan\n awk: cmd. line:1: warning: log: received negative argument -1\n nan\n" }, { "code": null, "e": 26225, "s": 26132, "text": "Explanation: Returns -inf when given zero and gives nan error when negative number is given." }, { "code": null, "e": 26363, "s": 26225, "text": "3. awk sqrt(n) function: sqrt() function gives the positive root for the given integer n. This function also accepts the positive number." }, { "code": null, "e": 26554, "s": 26363, "text": "Examples:Input : $ awk 'BEGIN{print sqrt(16);print sqrt(0);print sqrt(-12);}'\nOutput : 4\n 0\n awk: cmd. line:1: warning: sqrt: called with negative argument -12\n -nan\n" }, { "code": null, "e": 26736, "s": 26554, "text": "Input : $ awk 'BEGIN{print sqrt(16);print sqrt(0);print sqrt(-12);}'\nOutput : 4\n 0\n awk: cmd. line:1: warning: sqrt: called with negative argument -12\n -nan\n" }, { "code": null, "e": 26810, "s": 26736, "text": "Explanation: It returns nan error if we give negative number as argument." }, { "code": null, "e": 26891, "s": 26810, "text": "4. awk sin(n) function: sin() function gives sine value of n, with n in radians." }, { "code": null, "e": 27019, "s": 26891, "text": "Examples:Input : $ awk 'BEGIN{print sin(-60);print sin(90);print sin(45);}'\nOutput :0.304811\n 0.893997\n 0.850904\n" }, { "code": null, "e": 27138, "s": 27019, "text": "Input : $ awk 'BEGIN{print sin(-60);print sin(90);print sin(45);}'\nOutput :0.304811\n 0.893997\n 0.850904\n" }, { "code": null, "e": 27221, "s": 27138, "text": "5. awk cos(n) function: cos() function gives cosine value of n, with n in radians." }, { "code": null, "e": 27352, "s": 27221, "text": "Examples:Input : $ awk 'BEGIN{print cos(-60);print cos(90);print cos(45);}'\nOutput :-0.952413\n -0.448074\n 0.525322\n" }, { "code": null, "e": 27474, "s": 27352, "text": "Input : $ awk 'BEGIN{print cos(-60);print cos(90);print cos(45);}'\nOutput :-0.952413\n -0.448074\n 0.525322\n" }, { "code": null, "e": 27515, "s": 27474, "text": "Built-in Functions for String Operations" }, { "code": null, "e": 27751, "s": 27515, "text": "1. awk index(str1, str2) Function: This searches the string str1 for the first occurrences of the string str2, and returns the position in characters where that occurrence begins in the string str1. String indices in awk starts from 1." }, { "code": null, "e": 27863, "s": 27751, "text": "Example:Input: awk 'BEGIN{print index(\"Graphic\", \"ph\"); print index(\"University\", \"abc\")}'\nOutput: 4\n 0\n" }, { "code": null, "e": 27967, "s": 27863, "text": "Input: awk 'BEGIN{print index(\"Graphic\", \"ph\"); print index(\"University\", \"abc\")}'\nOutput: 4\n 0\n" }, { "code": null, "e": 28020, "s": 27967, "text": "Explanation: Returns 0 if str2 is not found in str1." }, { "code": null, "e": 28109, "s": 28020, "text": "2. awk length(string) Function: The length() function calculates the length of a string." }, { "code": null, "e": 28191, "s": 28109, "text": "Example:Input: $ awk 'BEGIN{print length(\"Graphic Era University\")}'\nOutput: 22\n\n" }, { "code": null, "e": 28265, "s": 28191, "text": "Input: $ awk 'BEGIN{print length(\"Graphic Era University\")}'\nOutput: 22\n\n" }, { "code": null, "e": 28321, "s": 28265, "text": "Explanation: Length of the string also includes spaces." }, { "code": null, "e": 28573, "s": 28321, "text": "3. awk substr(s, p, n) Function: The length() function is used to extract substring function from a string. Returns substring of string s at beginning position p up to a maximum length of n. If n is not supplied, the rest of the string from p is used." }, { "code": null, "e": 28755, "s": 28573, "text": "Example:Input: $ awk 'BEGIN{print substr(\"Graphic Era University\", 9)}'\nOutput: Era University\n\nInput: $ awk 'BEGIN{print substr(\"Graphic Era University\", 9, 8)}'\nOutput: Era Univ\n\n" }, { "code": null, "e": 28844, "s": 28755, "text": "Input: $ awk 'BEGIN{print substr(\"Graphic Era University\", 9)}'\nOutput: Era University\n\n" }, { "code": null, "e": 28930, "s": 28844, "text": "Input: $ awk 'BEGIN{print substr(\"Graphic Era University\", 9, 8)}'\nOutput: Era Univ\n\n" }, { "code": null, "e": 29046, "s": 28930, "text": "4. awk tolower(s) Function: Translate all uppercase characters in string s to lowercase and returns the new string." }, { "code": null, "e": 29131, "s": 29046, "text": "Example:Input: $ awk 'BEGIN{print tolower(\"GEEKSFORGEEKS\")}'\nOutput: geeksforgeeks\n\n" }, { "code": null, "e": 29208, "s": 29131, "text": "Input: $ awk 'BEGIN{print tolower(\"GEEKSFORGEEKS\")}'\nOutput: geeksforgeeks\n\n" }, { "code": null, "e": 29324, "s": 29208, "text": "5. awk toupper(s) Function: Translate all lowercase characters in string s to uppercase and returns the new string." }, { "code": null, "e": 29409, "s": 29324, "text": "Example:Input: $ awk 'BEGIN{print toupper(\"geeksforgeeks\")}'\nOutput: GEEKSFORGEEKS\n\n" }, { "code": null, "e": 29486, "s": 29409, "text": "Input: $ awk 'BEGIN{print toupper(\"geeksforgeeks\")}'\nOutput: GEEKSFORGEEKS\n\n" }, { "code": null, "e": 29786, "s": 29486, "text": "6. awk split(string, array, fieldsep) Function: This divides string into pieces separated by fieldsep, and stores the pieces in array. The first piece is stored in array[1], the second piece in array[2], and so forth. The string value of the third argument, fieldsep, describe where to split string." }, { "code": null, "e": 30004, "s": 29786, "text": "Example:Input: $ awk 'BEGIN{string=\"My Nationality Is Indian\"; fieldsep=\" \"; n=split(string, array, fieldsep); for(i=1; i<=n; i++){printf(\"%s\\n\", array[i]);}}'\nOutput: My\n Nationality\n Is\n Indian\n" }, { "code": null, "e": 30214, "s": 30004, "text": "Input: $ awk 'BEGIN{string=\"My Nationality Is Indian\"; fieldsep=\" \"; n=split(string, array, fieldsep); for(i=1; i<=n; i++){printf(\"%s\\n\", array[i]);}}'\nOutput: My\n Nationality\n Is\n Indian\n" }, { "code": null, "e": 30332, "s": 30214, "text": "Explanation: The above script breaks up the sentence into words, using a space as the character separating the words." }, { "code": null, "e": 30346, "s": 30332, "text": "linux-command" }, { "code": null, "e": 30357, "s": 30346, "text": "Linux-Unix" }, { "code": null, "e": 30455, "s": 30357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30492, "s": 30455, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 30527, "s": 30492, "text": "scp command in Linux with Examples" }, { "code": null, "e": 30553, "s": 30527, "text": "Thread functions in C/C++" }, { "code": null, "e": 30587, "s": 30553, "text": "mv command in Linux with examples" }, { "code": null, "e": 30624, "s": 30587, "text": "chown command in Linux with Examples" }, { "code": null, "e": 30653, "s": 30624, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 30679, "s": 30653, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30719, "s": 30679, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 30754, "s": 30719, "text": "Basic Operators in Shell Scripting" } ]
Difference between namespace and class - GeeksforGeeks
26 Jan, 2018 Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. In essence, a namespace defines a scope.Following are some points to justify : 1. A namespace is a way of grouping identifiers so that they don’t clash. Using a class implies that you can create an instance of that class, not true with namespaces. 2. You can use using-declarations with namespaces, and that’s not possible with classes unless you derive from them. 3. You can reopen a namespace and add stuff across translation units. You cannot do this with classes.For example:- namespace A {int f1();} namespace A {int f2();} is legal, but: class A { int f1();}; class A { // illegal int f2();}; is not. 4.You can have unnamed namespaces but you can’t have a unnamed class.For example: namespace { // fine // some code....} class { // illegal} 5. If length of a name makes code difficult to read, or is tedious to type in a header file where using directives can’t be used, we can make a namespace alias which serves as an abbreviation for the actual name. For example: #include <iostream> namespace foo { namespace bar { namespace baz { int qux = 42; } }} namespace fbz = foo::bar::baz; int main(){ std::cout << fbz::qux << '\n';} Output : 42 In case of class we have to use typedef. class Car {public: typedef std::vector<Wheel> WheelCollection; WheelCollection wheels;}; cpp-class cpp-namespaces C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Operator Overloading in C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference Between == and .equals() Method in Java
[ { "code": null, "e": 24794, "s": 24766, "text": "\n26 Jan, 2018" }, { "code": null, "e": 25328, "s": 24794, "text": "Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. In essence, a namespace defines a scope.Following are some points to justify :" }, { "code": null, "e": 25497, "s": 25328, "text": "1. A namespace is a way of grouping identifiers so that they don’t clash. Using a class implies that you can create an instance of that class, not true with namespaces." }, { "code": null, "e": 25614, "s": 25497, "text": "2. You can use using-declarations with namespaces, and that’s not possible with classes unless you derive from them." }, { "code": null, "e": 25730, "s": 25614, "text": "3. You can reopen a namespace and add stuff across translation units. You cannot do this with classes.For example:-" }, { "code": "namespace A {int f1();} namespace A {int f2();}", "e": 25779, "s": 25730, "text": null }, { "code": null, "e": 25794, "s": 25779, "text": "is legal, but:" }, { "code": "class A { int f1();}; class A { // illegal int f2();};", "e": 25856, "s": 25794, "text": null }, { "code": null, "e": 25864, "s": 25856, "text": "is not." }, { "code": null, "e": 25946, "s": 25864, "text": "4.You can have unnamed namespaces but you can’t have a unnamed class.For example:" }, { "code": "namespace { // fine // some code....} class { // illegal}", "e": 26006, "s": 25946, "text": null }, { "code": null, "e": 26232, "s": 26006, "text": "5. If length of a name makes code difficult to read, or is tedious to type in a header file where using directives can’t be used, we can make a namespace alias which serves as an abbreviation for the actual name. For example:" }, { "code": "#include <iostream> namespace foo { namespace bar { namespace baz { int qux = 42; } }} namespace fbz = foo::bar::baz; int main(){ std::cout << fbz::qux << '\\n';}", "e": 26431, "s": 26232, "text": null }, { "code": null, "e": 26440, "s": 26431, "text": "Output :" }, { "code": null, "e": 26445, "s": 26440, "text": " 42 " }, { "code": null, "e": 26486, "s": 26445, "text": "In case of class we have to use typedef." }, { "code": "class Car {public: typedef std::vector<Wheel> WheelCollection; WheelCollection wheels;};", "e": 26581, "s": 26486, "text": null }, { "code": null, "e": 26591, "s": 26581, "text": "cpp-class" }, { "code": null, "e": 26606, "s": 26591, "text": "cpp-namespaces" }, { "code": null, "e": 26610, "s": 26606, "text": "C++" }, { "code": null, "e": 26629, "s": 26610, "text": "Difference Between" }, { "code": null, "e": 26633, "s": 26629, "text": "CPP" }, { "code": null, "e": 26731, "s": 26633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26750, "s": 26731, "text": "Inheritance in C++" }, { "code": null, "e": 26793, "s": 26750, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26817, "s": 26793, "text": "C++ Classes and Objects" }, { "code": null, "e": 26844, "s": 26817, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 26872, "s": 26844, "text": "Operator Overloading in C++" }, { "code": null, "e": 26903, "s": 26872, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26943, "s": 26903, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26975, "s": 26943, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27036, "s": 26975, "text": "Difference between var, let and const keywords in JavaScript" } ]
The best way to remove duplicates from an array of objects in JavaScript?
Let’s say the following is our array of objects with duplicates − var studentDetails=[ {studentId:101}, {studentId:104}, {studentId:106}, {studentId:104}, {studentId:110}, {studentId:106}, ] Use the concept of set to remove duplicates as in the below code − var studentDetails=[ {studentId:101}, {studentId:104}, {studentId:106}, {studentId:104}, {studentId:110}, {studentId:106}, ] const distinctValues = new Set const withoutDuplicate = [] for (const tempObj of studentDetails) { if (!distinctValues.has(tempObj.studentId)) { distinctValues.add(tempObj.studentId) withoutDuplicate.push(tempObj) } } console.log(withoutDuplicate); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo158.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo158.js [ { studentId: 101 }, { studentId: 104 }, { studentId: 106 }, { studentId: 110 } ]
[ { "code": null, "e": 1128, "s": 1062, "text": "Let’s say the following is our array of objects with duplicates −" }, { "code": null, "e": 1271, "s": 1128, "text": "var studentDetails=[\n {studentId:101},\n {studentId:104},\n {studentId:106},\n {studentId:104},\n {studentId:110},\n {studentId:106},\n]" }, { "code": null, "e": 1338, "s": 1271, "text": "Use the concept of set to remove duplicates as in the below code −" }, { "code": null, "e": 1748, "s": 1338, "text": "var studentDetails=[\n {studentId:101},\n {studentId:104},\n {studentId:106},\n {studentId:104},\n {studentId:110},\n {studentId:106},\n]\nconst distinctValues = new Set\nconst withoutDuplicate = []\nfor (const tempObj of studentDetails) {\n if (!distinctValues.has(tempObj.studentId)) {\n distinctValues.add(tempObj.studentId)\n withoutDuplicate.push(tempObj)\n }\n}\nconsole.log(withoutDuplicate);" }, { "code": null, "e": 1814, "s": 1748, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1832, "s": 1814, "text": "node fileName.js." }, { "code": null, "e": 1907, "s": 1832, "text": "Here, my file name is demo158.js. This will produce the following output −" }, { "code": null, "e": 2052, "s": 1907, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo158.js\n[\n { studentId: 101 },\n { studentId: 104 },\n { studentId: 106 },\n { studentId: 110 }\n]" } ]
Extending a list in Python (5 different ways) - GeeksforGeeks
11 Oct, 2019 Extending a list in python can be done is following ways:1. Using append() function: We can append at the end of the list by using append() function. For appending any single value to the list or appending a list to the list, the syntax stays the same. But we can only append a single value at a time using append() function # Python program to extend a list using append() a = [10, 12, 13, 17] # appending multiple valuesa.append(20)a.append(22)print(a) Output: [10, 12, 13, 17, 20, 22] 2. Using ‘+’ operator: We can add values by using the “+” operator. We can use [] to add any number of values to the list. Adding multiple values can be done by using ‘, ‘ values. # Python program to extend a list using '+' a = [10, 12, 13, 17] # Appending single valuea = a + [20] # append more then one valuesa = a + [30, 40]print(a) Output: [10, 12, 13, 17, 20, 30, 40] 3. Using slicing: Using slicing in python, single or multiple values can be added to a list. a[:0] = [x, y, z...] Here a is the list in which the values(x, y, z..) are to be added. In this method the values are appended to the front of the list. # Python program to extend a list using 'slicing' # appending multiple value a =[10, 12, 13, 17] # add 1 numbera[:0] = [30] # add two numbersa[:0] = [40, 50]print(a) Output: [40, 50, 30, 10, 12, 13, 17] 4.Using chain(): Using chain() iterator function, we can extend a list by the syntax: list(chain(a, [x, y, z..])) Here a is the list in which the values(x, y, z..) are to be added. In this method the values are appended to the end of the list. # python program to extend a list using # "chain" iterator functionsfrom itertools import * a = [10, 20, 30] # extend a listprint(list(chain(a, [40, 50, 60]))) Output: [10, 20, 30, 40, 50, 60] 5. Using Extend # Python program to extend a list using extend() a = [10, 12, 13, 17] b = [30, 40] a.extend(b) print(a) Output: [10, 12, 13, 17, 30, 40] Akanksha_Rai python-list Python python-list 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 How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python sum() function in Python
[ { "code": null, "e": 24388, "s": 24360, "text": "\n11 Oct, 2019" }, { "code": null, "e": 24713, "s": 24388, "text": "Extending a list in python can be done is following ways:1. Using append() function: We can append at the end of the list by using append() function. For appending any single value to the list or appending a list to the list, the syntax stays the same. But we can only append a single value at a time using append() function" }, { "code": "# Python program to extend a list using append() a = [10, 12, 13, 17] # appending multiple valuesa.append(20)a.append(22)print(a)", "e": 24846, "s": 24713, "text": null }, { "code": null, "e": 24854, "s": 24846, "text": "Output:" }, { "code": null, "e": 24880, "s": 24854, "text": "[10, 12, 13, 17, 20, 22]\n" }, { "code": null, "e": 25060, "s": 24880, "text": "2. Using ‘+’ operator: We can add values by using the “+” operator. We can use [] to add any number of values to the list. Adding multiple values can be done by using ‘, ‘ values." }, { "code": "# Python program to extend a list using '+' a = [10, 12, 13, 17] # Appending single valuea = a + [20] # append more then one valuesa = a + [30, 40]print(a)", "e": 25221, "s": 25060, "text": null }, { "code": null, "e": 25229, "s": 25221, "text": "Output:" }, { "code": null, "e": 25259, "s": 25229, "text": "[10, 12, 13, 17, 20, 30, 40]\n" }, { "code": null, "e": 25352, "s": 25259, "text": "3. Using slicing: Using slicing in python, single or multiple values can be added to a list." }, { "code": null, "e": 25373, "s": 25352, "text": "a[:0] = [x, y, z...]" }, { "code": null, "e": 25505, "s": 25373, "text": "Here a is the list in which the values(x, y, z..) are to be added. In this method the values are appended to the front of the list." }, { "code": "# Python program to extend a list using 'slicing' # appending multiple value a =[10, 12, 13, 17] # add 1 numbera[:0] = [30] # add two numbersa[:0] = [40, 50]print(a)", "e": 25676, "s": 25505, "text": null }, { "code": null, "e": 25684, "s": 25676, "text": "Output:" }, { "code": null, "e": 25714, "s": 25684, "text": "[40, 50, 30, 10, 12, 13, 17]\n" }, { "code": null, "e": 25800, "s": 25714, "text": "4.Using chain(): Using chain() iterator function, we can extend a list by the syntax:" }, { "code": null, "e": 25828, "s": 25800, "text": "list(chain(a, [x, y, z..]))" }, { "code": null, "e": 25958, "s": 25828, "text": "Here a is the list in which the values(x, y, z..) are to be added. In this method the values are appended to the end of the list." }, { "code": "# python program to extend a list using # \"chain\" iterator functionsfrom itertools import * a = [10, 20, 30] # extend a listprint(list(chain(a, [40, 50, 60])))", "e": 26120, "s": 25958, "text": null }, { "code": null, "e": 26128, "s": 26120, "text": "Output:" }, { "code": null, "e": 26154, "s": 26128, "text": "[10, 20, 30, 40, 50, 60]\n" }, { "code": null, "e": 26170, "s": 26154, "text": "5. Using Extend" }, { "code": "# Python program to extend a list using extend() a = [10, 12, 13, 17] b = [30, 40] a.extend(b) print(a)", "e": 26278, "s": 26170, "text": null }, { "code": null, "e": 26286, "s": 26278, "text": "Output:" }, { "code": null, "e": 26312, "s": 26286, "text": "[10, 12, 13, 17, 30, 40]\n" }, { "code": null, "e": 26325, "s": 26312, "text": "Akanksha_Rai" }, { "code": null, "e": 26337, "s": 26325, "text": "python-list" }, { "code": null, "e": 26344, "s": 26337, "text": "Python" }, { "code": null, "e": 26356, "s": 26344, "text": "python-list" }, { "code": null, "e": 26454, "s": 26356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26463, "s": 26454, "text": "Comments" }, { "code": null, "e": 26476, "s": 26463, "text": "Old Comments" }, { "code": null, "e": 26494, "s": 26476, "text": "Python Dictionary" }, { "code": null, "e": 26529, "s": 26494, "text": "Read a file line by line in Python" }, { "code": null, "e": 26561, "s": 26529, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26603, "s": 26561, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26629, "s": 26603, "text": "Python String | replace()" }, { "code": null, "e": 26672, "s": 26629, "text": "Python program to convert a list to string" }, { "code": null, "e": 26709, "s": 26672, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26753, "s": 26709, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26782, "s": 26753, "text": "*args and **kwargs in Python" } ]
OpenCV Python Program to analyze an image using Histogram - GeeksforGeeks
15 Feb, 2018 In this article, image analysis using Matplotlib and OpenCV is discussed. Let’s first understand how to experiment image data with various styles and how to represent with Histogram.Prerequisites: OpenCV matplotlib Importing image data import matplotlib.pyplot as plt #importing matplotlib The image should be used in a PNG file as matplotlib supports only PNG images. Here, It’s a 24-bit RGB PNG image (8 bits for each of R, G, B) used in this example. Each inner list represents a pixel. Here, with an RGB image, there are 3 values. For RGB images, matplotlib supports float32 and uint8 data types. img = plt.imread('flower.png') #reads image data In Matplotlib, this is performed using the imshow() function. Here we have grabbed the plot object. All about Histogram Histogram is considered as a graph or plot which is related to frequency of pixels in an Gray Scale Imagewith pixel values (ranging from 0 to 255). Grayscale image is an image in which the value of each pixel is a single sample, that is, it carries only intensity information where pixel value varies from 0 to 255. Images of this sort, also known as black-and-white, are composed exclusively of shades of gray, varying from black at the weakest intensity to white at the strongest where Pixel can be considered as a every point in an image.How GrayScale Image looks like:It quantifies the number of pixels for each intensity value considered. Before going through Histogram, lets have a rough idea from this given example.Here, we get intuition about contrast, brightness, intensity distribution etc of that image. As we can see the image and its histogram which is drawn for grayscale image, not color image.Left region of histogram shows the amount of darker pixels in image and right region shows the amount of brighter pixels. Histogram creation using numpy array To create a histogram of our image data, we use the hist() function. plt.hist(n_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k') #calculating histogram In our histogram, it looks like there’s distribution of intensity all over image Black and White pixels as grayscale image. From the histogram, we can conclude that dark region is more than brighter region. Now, we will deal with an image which consist of intensity distribution of pixels where pixel value varies. First, we need to calculate histogram using OpenCV in-built function. Histogram Calculation Here, we use cv2.calcHist()(in-built function in OpenCV) to find the histogram. cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) images : it is the source image of type uint8 or float32 represented as “[img]”.channels : it is the index of channel for which we calculate histogram. For grayscale image, its value is [0] andcolor image, you can pass [0], [1] or [2] to calculate histogram of blue, green or red channel respectively.mask : mask image. To find histogram of full image, it is given as “None”.histSize : this represents our BIN count. For full scale, we pass [256].ranges : this is our RANGE. Normally, it is [0,256]. For example: # load an image in grayscale modeimg = cv2.imread('ex.jpg',0) # calculate frequency of pixels in range 0-255histg = cv2.calcHist([img],[0],None,[256],[0,256]) Then, we need to plot histogram to show the characteristics of an image. Plotting Histograms Analysis using Matplotlib: # importing required libraries of opencvimport cv2 # importing library for plottingfrom matplotlib import pyplot as plt # reads an input imageimg = cv2.imread('ex.jpg',0) # find frequency of pixels in range 0-255histr = cv2.calcHist([img],[0],None,[256],[0,256]) # show the plotting graph of an imageplt.plot(histr)plt.show() Input:Output:Illustration shows that each number of pixels of an image lie upon range of 0 to 255. In the second example, it directly finds the histogram and plot it. We need not use calcHist(). See the code below: import cv2from matplotlib import pyplot as pltimg = cv2.imread('ex.jpg',0) # alternative way to find histogram of an imageplt.hist(img.ravel(),256,[0,256])plt.show() Output: Thus, we conclude that image can be represented as a Histogram to conceive the idea of intensity distribution over an image and further its tranquility. References: http://docs.opencv.org/2.4/doc/tutorials/imgproc/table_of_content_imgproc/table_of_content_imgproc.html#table-of-content-imgproc http://www.cambridgeincolour.com/tutorials/histograms1.htm This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. OpenCV Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Twitter Sentiment Analysis using Python Snake Game in C Java Swing | Simple User Registration Form Banking Transaction System using Java Simple registration form using Python Tkinter 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": 24109, "s": 24081, "text": "\n15 Feb, 2018" }, { "code": null, "e": 24306, "s": 24109, "text": "In this article, image analysis using Matplotlib and OpenCV is discussed. Let’s first understand how to experiment image data with various styles and how to represent with Histogram.Prerequisites:" }, { "code": null, "e": 24313, "s": 24306, "text": "OpenCV" }, { "code": null, "e": 24324, "s": 24313, "text": "matplotlib" }, { "code": null, "e": 24345, "s": 24324, "text": "Importing image data" }, { "code": null, "e": 24399, "s": 24345, "text": "import matplotlib.pyplot as plt #importing matplotlib" }, { "code": null, "e": 24710, "s": 24399, "text": "The image should be used in a PNG file as matplotlib supports only PNG images. Here, It’s a 24-bit RGB PNG image (8 bits for each of R, G, B) used in this example. Each inner list represents a pixel. Here, with an RGB image, there are 3 values. For RGB images, matplotlib supports float32 and uint8 data types." }, { "code": null, "e": 24759, "s": 24710, "text": "img = plt.imread('flower.png') #reads image data" }, { "code": null, "e": 24859, "s": 24759, "text": "In Matplotlib, this is performed using the imshow() function. Here we have grabbed the plot object." }, { "code": null, "e": 24879, "s": 24859, "text": "All about Histogram" }, { "code": null, "e": 25911, "s": 24879, "text": "Histogram is considered as a graph or plot which is related to frequency of pixels in an Gray Scale Imagewith pixel values (ranging from 0 to 255). Grayscale image is an image in which the value of each pixel is a single sample, that is, it carries only intensity information where pixel value varies from 0 to 255. Images of this sort, also known as black-and-white, are composed exclusively of shades of gray, varying from black at the weakest intensity to white at the strongest where Pixel can be considered as a every point in an image.How GrayScale Image looks like:It quantifies the number of pixels for each intensity value considered. Before going through Histogram, lets have a rough idea from this given example.Here, we get intuition about contrast, brightness, intensity distribution etc of that image. As we can see the image and its histogram which is drawn for grayscale image, not color image.Left region of histogram shows the amount of darker pixels in image and right region shows the amount of brighter pixels." }, { "code": null, "e": 25948, "s": 25911, "text": "Histogram creation using numpy array" }, { "code": null, "e": 26017, "s": 25948, "text": "To create a histogram of our image data, we use the hist() function." }, { "code": null, "e": 26108, "s": 26017, "text": "plt.hist(n_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k') #calculating histogram" }, { "code": null, "e": 26232, "s": 26108, "text": "In our histogram, it looks like there’s distribution of intensity all over image Black and White pixels as grayscale image." }, { "code": null, "e": 26315, "s": 26232, "text": "From the histogram, we can conclude that dark region is more than brighter region." }, { "code": null, "e": 26494, "s": 26315, "text": "Now, we will deal with an image which consist of intensity distribution of pixels where pixel value varies. First, we need to calculate histogram using OpenCV in-built function." }, { "code": null, "e": 26516, "s": 26494, "text": "Histogram Calculation" }, { "code": null, "e": 26596, "s": 26516, "text": "Here, we use cv2.calcHist()(in-built function in OpenCV) to find the histogram." }, { "code": null, "e": 26673, "s": 26596, "text": "cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])" }, { "code": null, "e": 27173, "s": 26673, "text": "images : it is the source image of type uint8 or float32 represented as “[img]”.channels : it is the index of channel for which we calculate histogram. For grayscale image, its value is [0] andcolor image, you can pass [0], [1] or [2] to calculate histogram of blue, green or red channel respectively.mask : mask image. To find histogram of full image, it is given as “None”.histSize : this represents our BIN count. For full scale, we pass [256].ranges : this is our RANGE. Normally, it is [0,256]." }, { "code": null, "e": 27186, "s": 27173, "text": "For example:" }, { "code": "# load an image in grayscale modeimg = cv2.imread('ex.jpg',0) # calculate frequency of pixels in range 0-255histg = cv2.calcHist([img],[0],None,[256],[0,256]) ", "e": 27347, "s": 27186, "text": null }, { "code": null, "e": 27420, "s": 27347, "text": "Then, we need to plot histogram to show the characteristics of an image." }, { "code": null, "e": 27440, "s": 27420, "text": "Plotting Histograms" }, { "code": null, "e": 27467, "s": 27440, "text": "Analysis using Matplotlib:" }, { "code": "# importing required libraries of opencvimport cv2 # importing library for plottingfrom matplotlib import pyplot as plt # reads an input imageimg = cv2.imread('ex.jpg',0) # find frequency of pixels in range 0-255histr = cv2.calcHist([img],[0],None,[256],[0,256]) # show the plotting graph of an imageplt.plot(histr)plt.show()", "e": 27797, "s": 27467, "text": null }, { "code": null, "e": 28012, "s": 27797, "text": "Input:Output:Illustration shows that each number of pixels of an image lie upon range of 0 to 255. In the second example, it directly finds the histogram and plot it. We need not use calcHist(). See the code below:" }, { "code": "import cv2from matplotlib import pyplot as pltimg = cv2.imread('ex.jpg',0) # alternative way to find histogram of an imageplt.hist(img.ravel(),256,[0,256])plt.show()", "e": 28179, "s": 28012, "text": null }, { "code": null, "e": 28187, "s": 28179, "text": "Output:" }, { "code": null, "e": 28340, "s": 28187, "text": "Thus, we conclude that image can be represented as a Histogram to conceive the idea of intensity distribution over an image and further its tranquility." }, { "code": null, "e": 28352, "s": 28340, "text": "References:" }, { "code": null, "e": 28481, "s": 28352, "text": "http://docs.opencv.org/2.4/doc/tutorials/imgproc/table_of_content_imgproc/table_of_content_imgproc.html#table-of-content-imgproc" }, { "code": null, "e": 28540, "s": 28481, "text": "http://www.cambridgeincolour.com/tutorials/histograms1.htm" }, { "code": null, "e": 28840, "s": 28540, "text": "This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28965, "s": 28840, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28972, "s": 28965, "text": "OpenCV" }, { "code": null, "e": 28980, "s": 28972, "text": "Project" }, { "code": null, "e": 28987, "s": 28980, "text": "Python" }, { "code": null, "e": 29085, "s": 28987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29094, "s": 29085, "text": "Comments" }, { "code": null, "e": 29107, "s": 29094, "text": "Old Comments" }, { "code": null, "e": 29147, "s": 29107, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 29163, "s": 29147, "text": "Snake Game in C" }, { "code": null, "e": 29206, "s": 29163, "text": "Java Swing | Simple User Registration Form" }, { "code": null, "e": 29244, "s": 29206, "text": "Banking Transaction System using Java" }, { "code": null, "e": 29290, "s": 29244, "text": "Simple registration form using Python Tkinter" }, { "code": null, "e": 29318, "s": 29290, "text": "Read JSON file using Python" }, { "code": null, "e": 29368, "s": 29318, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29390, "s": 29368, "text": "Python map() function" } ]
Is it possible to sum two fields in MongoDB using the Aggregation framework?
Yes, it is possible using the $project operator. Let us first create a collection with documents > db.sumTwoFieldsDemo.insertOne({"FirstValue":150,"SecondValue":350}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b4bfe15e86fd1496b38cd") } > db.sumTwoFieldsDemo.insertOne({"FirstValue":450,"SecondValue":1550}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b4c1215e86fd1496b38ce") } > db.sumTwoFieldsDemo.insertOne({"FirstValue":2560,"SecondValue":2440}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b4c2715e86fd1496b38cf") } Following is the query to display all documents from a collection with the help of find() method > db.sumTwoFieldsDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9b4bfe15e86fd1496b38cd"), "FirstValue" : 150, "SecondValue" : 350 } { "_id" : ObjectId("5c9b4c1215e86fd1496b38ce"), "FirstValue" : 450, "SecondValue" : 1550 } { "_id" : ObjectId("5c9b4c2715e86fd1496b38cf"), "FirstValue" : 2560, "SecondValue" : 2440 } Following is the query to sum 2 fields in MongoDB using the $project operator > db.sumTwoFieldsDemo.aggregate( ... { "$project" : ... { ... 'First' : '$FirstValue', ... 'Second' : '$SecondValue', ... 'TotalValueOfBothFields' : { '$add' : [ '$FirstValue', '$SecondValue' ] }, ... } ... } ... ); This will produce the following output { "_id" : ObjectId("5c9b4bfe15e86fd1496b38cd"), "First" : 150, "Second" : 350, "TotalValueOfBothFields" : 500 } { "_id" : ObjectId("5c9b4c1215e86fd1496b38ce"), "First" : 450, "Second" : 1550, "TotalValueOfBothFields" : 2000 } { "_id" : ObjectId("5c9b4c2715e86fd1496b38cf"), "First" : 2560, "Second" : 2440, "TotalValueOfBothFields" : 5000 }
[ { "code": null, "e": 1159, "s": 1062, "text": "Yes, it is possible using the $project operator. Let us first create a collection with documents" }, { "code": null, "e": 1630, "s": 1159, "text": "> db.sumTwoFieldsDemo.insertOne({\"FirstValue\":150,\"SecondValue\":350});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b4bfe15e86fd1496b38cd\")\n}\n> db.sumTwoFieldsDemo.insertOne({\"FirstValue\":450,\"SecondValue\":1550});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b4c1215e86fd1496b38ce\")\n}\n> db.sumTwoFieldsDemo.insertOne({\"FirstValue\":2560,\"SecondValue\":2440});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b4c2715e86fd1496b38cf\")\n}" }, { "code": null, "e": 1727, "s": 1630, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1766, "s": 1727, "text": "> db.sumTwoFieldsDemo.find().pretty();" }, { "code": null, "e": 1805, "s": 1766, "text": "This will produce the following output" }, { "code": null, "e": 2105, "s": 1805, "text": "{\n \"_id\" : ObjectId(\"5c9b4bfe15e86fd1496b38cd\"),\n \"FirstValue\" : 150,\n \"SecondValue\" : 350\n}\n{\n \"_id\" : ObjectId(\"5c9b4c1215e86fd1496b38ce\"),\n \"FirstValue\" : 450,\n \"SecondValue\" : 1550\n}\n{\n \"_id\" : ObjectId(\"5c9b4c2715e86fd1496b38cf\"),\n \"FirstValue\" : 2560,\n \"SecondValue\" : 2440\n}" }, { "code": null, "e": 2183, "s": 2105, "text": "Following is the query to sum 2 fields in MongoDB using the $project operator" }, { "code": null, "e": 2444, "s": 2183, "text": "> db.sumTwoFieldsDemo.aggregate(\n... { \"$project\" :\n... {\n... 'First' : '$FirstValue',\n... 'Second' : '$SecondValue',\n... 'TotalValueOfBothFields' : { '$add' : [ '$FirstValue', '$SecondValue' ] },\n... }\n... }\n... );" }, { "code": null, "e": 2483, "s": 2444, "text": "This will produce the following output" }, { "code": null, "e": 2824, "s": 2483, "text": "{ \"_id\" : ObjectId(\"5c9b4bfe15e86fd1496b38cd\"), \"First\" : 150, \"Second\" : 350, \"TotalValueOfBothFields\" : 500 }\n{ \"_id\" : ObjectId(\"5c9b4c1215e86fd1496b38ce\"), \"First\" : 450, \"Second\" : 1550, \"TotalValueOfBothFields\" : 2000 }\n{ \"_id\" : ObjectId(\"5c9b4c2715e86fd1496b38cf\"), \"First\" : 2560, \"Second\" : 2440, \"TotalValueOfBothFields\" : 5000 }" } ]
PySpark - Serializers
Serialization is used for performance tuning on Apache Spark. All data that is sent over the network or written to the disk or persisted in the memory should be serialized. Serialization plays an important role in costly operations. PySpark supports custom serializers for performance tuning. The following two serializers are supported by PySpark − Serializes objects using Python’s Marshal Serializer. This serializer is faster than PickleSerializer, but supports fewer datatypes. class pyspark.MarshalSerializer Serializes objects using Python’s Pickle Serializer. This serializer supports nearly any Python object, but may not be as fast as more specialized serializers. class pyspark.PickleSerializer Let us see an example on PySpark serialization. Here, we serialize the data using MarshalSerializer. --------------------------------------serializing.py------------------------------------- from pyspark.context import SparkContext from pyspark.serializers import MarshalSerializer sc = SparkContext("local", "serialization app", serializer = MarshalSerializer()) print(sc.parallelize(list(range(1000))).map(lambda x: 2 * x).take(10)) sc.stop() --------------------------------------serializing.py------------------------------------- Command − The command is as follows − $SPARK_HOME/bin/spark-submit serializing.py Output − The output of the above command is − [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Print Add Notes Bookmark this page
[ { "code": null, "e": 2038, "s": 1805, "text": "Serialization is used for performance tuning on Apache Spark. All data that is sent over the network or written to the disk or persisted in the memory should be serialized. Serialization plays an important role in costly operations." }, { "code": null, "e": 2155, "s": 2038, "text": "PySpark supports custom serializers for performance tuning. The following two serializers are supported by PySpark −" }, { "code": null, "e": 2288, "s": 2155, "text": "Serializes objects using Python’s Marshal Serializer. This serializer is faster than PickleSerializer, but supports fewer datatypes." }, { "code": null, "e": 2321, "s": 2288, "text": "class pyspark.MarshalSerializer\n" }, { "code": null, "e": 2481, "s": 2321, "text": "Serializes objects using Python’s Pickle Serializer. This serializer supports nearly any Python object, but may not be as fast as more specialized serializers." }, { "code": null, "e": 2513, "s": 2481, "text": "class pyspark.PickleSerializer\n" }, { "code": null, "e": 2614, "s": 2513, "text": "Let us see an example on PySpark serialization. Here, we serialize the data using MarshalSerializer." }, { "code": null, "e": 3049, "s": 2614, "text": "--------------------------------------serializing.py-------------------------------------\nfrom pyspark.context import SparkContext\nfrom pyspark.serializers import MarshalSerializer\nsc = SparkContext(\"local\", \"serialization app\", serializer = MarshalSerializer())\nprint(sc.parallelize(list(range(1000))).map(lambda x: 2 * x).take(10))\nsc.stop()\n--------------------------------------serializing.py-------------------------------------\n" }, { "code": null, "e": 3087, "s": 3049, "text": "Command − The command is as follows −" }, { "code": null, "e": 3132, "s": 3087, "text": "$SPARK_HOME/bin/spark-submit serializing.py\n" }, { "code": null, "e": 3178, "s": 3132, "text": "Output − The output of the above command is −" }, { "code": null, "e": 3215, "s": 3178, "text": "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n" }, { "code": null, "e": 3222, "s": 3215, "text": " Print" }, { "code": null, "e": 3233, "s": 3222, "text": " Add Notes" } ]
How to Restrict User to Enter Date Manually in Date Field using AngularJS ? - GeeksforGeeks
17 Dec, 2020 In this article, we will see how to restrict the user to enter the date manually in the date field. Approach: First, we need to write the code for input, and we need to give its type as the date in the HTML file. Then in-order to restrict the user to enter date manually we can use onkeydown event. In the onkeydownevent we need to return false so that we can restrict the user to enter the date manually. In order to achieve the above objective, we need to write and function and return false in the ts file. As we restricted the user to enter the date normally, the user can only enter the date from the calendar. After completing the above steps save and run the project in order to see the output. Code Implementation: app.component.html: HTML <h1> Restricting the user to enter date manually in date field</h1> <label for="vote">Select a date:</label> <input type="date" id="vote" name="vote" (keydown)="disableDate()"> app.component.ts: Javascript import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { disableDate(){ return false; } } app.module.ts: Javascript import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { } 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-Function HTML-Misc Picked AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to create module with Routing in Angular 9 ? How to setup 404 page in angular routing ? 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": 24718, "s": 24690, "text": "\n17 Dec, 2020" }, { "code": null, "e": 24818, "s": 24718, "text": "In this article, we will see how to restrict the user to enter the date manually in the date field." }, { "code": null, "e": 24828, "s": 24818, "text": "Approach:" }, { "code": null, "e": 24931, "s": 24828, "text": "First, we need to write the code for input, and we need to give its type as the date in the HTML file." }, { "code": null, "e": 25017, "s": 24931, "text": "Then in-order to restrict the user to enter date manually we can use onkeydown event." }, { "code": null, "e": 25124, "s": 25017, "text": "In the onkeydownevent we need to return false so that we can restrict the user to enter the date manually." }, { "code": null, "e": 25228, "s": 25124, "text": "In order to achieve the above objective, we need to write and function and return false in the ts file." }, { "code": null, "e": 25334, "s": 25228, "text": "As we restricted the user to enter the date normally, the user can only enter the date from the calendar." }, { "code": null, "e": 25420, "s": 25334, "text": "After completing the above steps save and run the project in order to see the output." }, { "code": null, "e": 25441, "s": 25420, "text": "Code Implementation:" }, { "code": null, "e": 25461, "s": 25441, "text": "app.component.html:" }, { "code": null, "e": 25466, "s": 25461, "text": "HTML" }, { "code": "<h1> Restricting the user to enter date manually in date field</h1> <label for=\"vote\">Select a date:</label> <input type=\"date\" id=\"vote\" name=\"vote\" (keydown)=\"disableDate()\">", "e": 25656, "s": 25466, "text": null }, { "code": null, "e": 25674, "s": 25656, "text": "app.component.ts:" }, { "code": null, "e": 25685, "s": 25674, "text": "Javascript" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { disableDate(){ return false; } }", "e": 25916, "s": 25685, "text": null }, { "code": null, "e": 25931, "s": 25916, "text": "app.module.ts:" }, { "code": null, "e": 25942, "s": 25931, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }", "e": 26289, "s": 25942, "text": null }, { "code": null, "e": 26297, "s": 26289, "text": "Output:" }, { "code": null, "e": 26434, "s": 26297, "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": 26453, "s": 26434, "text": "AngularJS-Function" }, { "code": null, "e": 26463, "s": 26453, "text": "HTML-Misc" }, { "code": null, "e": 26470, "s": 26463, "text": "Picked" }, { "code": null, "e": 26480, "s": 26470, "text": "AngularJS" }, { "code": null, "e": 26485, "s": 26480, "text": "HTML" }, { "code": null, "e": 26502, "s": 26485, "text": "Web Technologies" }, { "code": null, "e": 26507, "s": 26502, "text": "HTML" }, { "code": null, "e": 26605, "s": 26507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26614, "s": 26605, "text": "Comments" }, { "code": null, "e": 26627, "s": 26614, "text": "Old Comments" }, { "code": null, "e": 26662, "s": 26627, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 26715, "s": 26662, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 26739, "s": 26715, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 26788, "s": 26739, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 26831, "s": 26788, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 26893, "s": 26831, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26943, "s": 26893, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27003, "s": 26943, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27051, "s": 27003, "text": "How to update Node.js and NPM to next version ?" } ]
How to read an external JSON file in JavaScript
Suppose we have a JSON file config.json that contains the following data − { "secret": "sfsaad7898fdsfsdf^*($%^*$", "connectionString": "mongodb+srv://username:[email protected]/events?retryWrites=tr ue&w=majority", "localConnectionString": "mongodb+srv://username:[email protected]/eventsLocal?retryWrit es=true&w=majority", "frontendClient": "https://helloworld.com", "localFrontendClient": "http://localhost:3000" } And in the same directory (folder), we have a JavaScript file index.js. Our task is to access the content of the json file through the JavaScript file. We can use the require module to access the json file if we are running our JavaScript file in NodeJS environment. The code for this will be − const configData = require('./config.json'); console.log(typeof configData); console.log(configData); If we want to access the json file while running JavaScript in browser, we can use the ES6 import syntax to do that. The code for this will be − <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>READ JSON FILE</title> </head> <body> <p id='main'></p> <script type="module" src="./index.js"></script> </body> </html> import configData from './config.json'; document.getElementById('main').innerHTML = JSON.stringify(configData); And the output will be − { secret: 'sfsaad7898fdsfsdf^*($%^*$', connectionString: 'mongodb+srv://username:[email protected]/events?retryWrites=tr ue&w=majority', localConnectionString: 'mongodb+srv://username:[email protected]/eventsLocal?retryWrit es=true&w=majority', frontendClient: 'https://helloworld.com', localFrontendClient: 'http://localhost:3000' }
[ { "code": null, "e": 1137, "s": 1062, "text": "Suppose we have a JSON file config.json that contains the following data −" }, { "code": null, "e": 1544, "s": 1137, "text": "{\n \"secret\": \"sfsaad7898fdsfsdf^*($%^*$\",\n \"connectionString\":\n \"mongodb+srv://username:[email protected]/events?retryWrites=tr\n ue&w=majority\",\n \"localConnectionString\":\n \"mongodb+srv://username:[email protected]/eventsLocal?retryWrit\n es=true&w=majority\",\n \"frontendClient\": \"https://helloworld.com\",\n \"localFrontendClient\": \"http://localhost:3000\"\n}" }, { "code": null, "e": 1616, "s": 1544, "text": "And in the same directory (folder), we have a JavaScript file index.js." }, { "code": null, "e": 1696, "s": 1616, "text": "Our task is to access the content of the json file through the JavaScript file." }, { "code": null, "e": 1811, "s": 1696, "text": "We can use the require module to access the json file if we are running our JavaScript file in NodeJS environment." }, { "code": null, "e": 1839, "s": 1811, "text": "The code for this will be −" }, { "code": null, "e": 1941, "s": 1839, "text": "const configData = require('./config.json');\nconsole.log(typeof configData);\nconsole.log(configData);" }, { "code": null, "e": 2058, "s": 1941, "text": "If we want to access the json file while running JavaScript in browser, we can use the ES6 import syntax to do that." }, { "code": null, "e": 2086, "s": 2058, "text": "The code for this will be −" }, { "code": null, "e": 2348, "s": 2086, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>READ JSON FILE</title>\n</head>\n<body>\n<p id='main'></p>\n<script type=\"module\" src=\"./index.js\"></script>\n</body>\n</html>" }, { "code": null, "e": 2460, "s": 2348, "text": "import configData from './config.json';\ndocument.getElementById('main').innerHTML = JSON.stringify(configData);" }, { "code": null, "e": 2485, "s": 2460, "text": "And the output will be −" }, { "code": null, "e": 2882, "s": 2485, "text": "{\n secret: 'sfsaad7898fdsfsdf^*($%^*$',\n connectionString:\n 'mongodb+srv://username:[email protected]/events?retryWrites=tr\n ue&w=majority',\n localConnectionString:\n 'mongodb+srv://username:[email protected]/eventsLocal?retryWrit\n es=true&w=majority',\n frontendClient: 'https://helloworld.com',\n localFrontendClient: 'http://localhost:3000'\n}" } ]
What are the SAM Interfaces in Java?
An interface having only one abstract method is known as a functional interface and also named as Single Abstract Method Interfaces (SAM Interfaces). One abstract method means that either a default method or an abstract method whose implementation is available by default is allowed. The instances of SAM interfaces are java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator and java.util.concurrent.Callable. The SAM interfaces can be implemented using lambda expressions or method references. @FunctionalInterface public interface Changeable { public void change(T o); } @FunctionalInterface interface MyInterface { String reverse(String n); } public class LambdaReverseTest { public static void main( String[] args ) { MyInterface myInterface = (str) -> { // Lambda Expression String result = ""; for(int i = str.length()-1; i >= 0 ; i--) result += str.charAt(i); return result; }; System.out.println("The reverse of string is: " + myInterface.reverse("TutorialsPoint")); } } The reverse of string is: tnioPslairotuT
[ { "code": null, "e": 1574, "s": 1062, "text": "An interface having only one abstract method is known as a functional interface and also named as Single Abstract Method Interfaces (SAM Interfaces). One abstract method means that either a default method or an abstract method whose implementation is available by default is allowed. The instances of SAM interfaces are java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator and java.util.concurrent.Callable. The SAM interfaces can be implemented using lambda expressions or method references." }, { "code": null, "e": 1653, "s": 1574, "text": "@FunctionalInterface\npublic interface Changeable {\n public void change(T o);\n}" }, { "code": null, "e": 2125, "s": 1653, "text": "@FunctionalInterface\ninterface MyInterface {\n String reverse(String n);\n}\npublic class LambdaReverseTest {\n public static void main( String[] args ) {\n MyInterface myInterface = (str) -> { // Lambda Expression\n String result = \"\";\n for(int i = str.length()-1; i >= 0 ; i--)\n result += str.charAt(i);\n return result;\n };\n System.out.println(\"The reverse of string is: \" + myInterface.reverse(\"TutorialsPoint\"));\n }\n}" }, { "code": null, "e": 2166, "s": 2125, "text": "The reverse of string is: tnioPslairotuT" } ]
GATE | GATE-CS-2007 | Question 37 - GeeksforGeeks
19 Nov, 2018 Consider a pipelined processor with the following four stages: IF: Instruction Fetch ID: Instruction Decode and Operand Fetch EX: Execute WB: Write Back The IF, ID and WB stages take one clock cycle each to complete the operation. The number of clock cycles for the EX stage dependson the instruction. The ADD and SUB instructions need 1 clock cycle and the MUL instruction needs 3 clock cycles in the EX stage. Operand forwarding is used in the pipelined processor. What is the number of clock cycles taken to complete the following sequence of instructions? ADD R2, R1, R0 R2 <- R0 + R1 MUL R4, R3, R2 R4 <- R3 * R2 SUB R6, R5, R4 R6 <- R5 - R4 (A) 7(B) 8(C) 10(D) 14Answer: (B)Explanation: Explanation: Order of instruction cycle phases IF” ID” EX” WB” We have 3 instructions. which represents wait in pipeline due to result dependently. This is the table shows the cycle phases and number of cycles require for given instruction. No. of cycles required=8 So (B) is correct option.Quiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2000 | Question 41 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25689, "s": 25661, "text": "\n19 Nov, 2018" }, { "code": null, "e": 25752, "s": 25689, "text": "Consider a pipelined processor with the following four stages:" }, { "code": null, "e": 25842, "s": 25752, "text": "IF: Instruction Fetch\nID: Instruction Decode and Operand Fetch\nEX: Execute\nWB: Write Back" }, { "code": null, "e": 26249, "s": 25842, "text": "The IF, ID and WB stages take one clock cycle each to complete the operation. The number of clock cycles for the EX stage dependson the instruction. The ADD and SUB instructions need 1 clock cycle and the MUL instruction needs 3 clock cycles in the EX stage. Operand forwarding is used in the pipelined processor. What is the number of clock cycles taken to complete the following sequence of instructions?" }, { "code": null, "e": 26357, "s": 26249, "text": "ADD R2, R1, R0 R2 <- R0 + R1\nMUL R4, R3, R2 R4 <- R3 * R2\nSUB R6, R5, R4 R6 <- R5 - R4 \n" }, { "code": null, "e": 26416, "s": 26357, "text": "(A) 7(B) 8(C) 10(D) 14Answer: (B)Explanation: Explanation:" }, { "code": null, "e": 26450, "s": 26416, "text": "Order of instruction cycle phases" }, { "code": null, "e": 26469, "s": 26450, "text": "IF” ID” EX” WB”" }, { "code": null, "e": 26555, "s": 26469, "text": "We have 3 instructions. which represents wait in pipeline due to result dependently." }, { "code": null, "e": 26650, "s": 26557, "text": "This is the table shows the cycle phases and number of cycles require for given instruction." }, { "code": null, "e": 26675, "s": 26650, "text": "No. of cycles required=8" }, { "code": null, "e": 26722, "s": 26675, "text": "So (B) is correct option.Quiz of this Question" }, { "code": null, "e": 26735, "s": 26722, "text": "GATE-CS-2007" }, { "code": null, "e": 26753, "s": 26735, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 26758, "s": 26753, "text": "GATE" }, { "code": null, "e": 26856, "s": 26758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26890, "s": 26856, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26924, "s": 26890, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26957, "s": 26924, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26993, "s": 26957, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27027, "s": 26993, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27063, "s": 27027, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27097, "s": 27063, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27131, "s": 27097, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27165, "s": 27131, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to concatenate MySQL distinct query results into a string?
Use group_concat() function from MySQL to concatenate. Let us first create a table − mysql> create table DemoTable -> ( -> Subject varchar(10) -> ); Query OK, 0 rows affected (0.43 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('C'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('C++'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('C++'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('MySQL'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement: mysql> select *from DemoTable; This will produce the following output − +---------+ | Subject | +---------+ | C | | C++ | | C++ | | MongoDB | | MySQL | | MongoDB | | MongoDB | | Java | | Java | +---------+ 9 rows in set (0.00 sec) Following is the query to concatenate SQL distinct query results into a string − mysql> select group_concat(tbl.sub) from (select Subject sub from DemoTable group by Subject ) tbl; This will produce the following output − +--------------------------+ | group_concat(tbl.sub) | +--------------------------+ | C,C++,MongoDB,MySQL,Java | +--------------------------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1147, "s": 1062, "text": "Use group_concat() function from MySQL to concatenate. Let us first create a table −" }, { "code": null, "e": 1257, "s": 1147, "text": "mysql> create table DemoTable\n -> (\n -> Subject varchar(10)\n -> );\nQuery OK, 0 rows affected (0.43 sec)" }, { "code": null, "e": 1313, "s": 1257, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2115, "s": 1313, "text": "mysql> insert into DemoTable values('C');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable values('C++');\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into DemoTable values('C++');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable values('MongoDB');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable values('MySQL');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('MongoDB');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('MongoDB');\nQuery OK, 1 row affected (0.34 sec)\n\nmysql> insert into DemoTable values('Java');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into DemoTable values('Java');\nQuery OK, 1 row affected (0.10 sec)\n\nDisplay all records from the table using select statement:" }, { "code": null, "e": 2146, "s": 2115, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2187, "s": 2146, "text": "This will produce the following output −" }, { "code": null, "e": 2368, "s": 2187, "text": "+---------+\n| Subject |\n+---------+\n| C |\n| C++ |\n| C++ |\n| MongoDB |\n| MySQL |\n| MongoDB |\n| MongoDB |\n| Java |\n| Java |\n+---------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2449, "s": 2368, "text": "Following is the query to concatenate SQL distinct query results into a string −" }, { "code": null, "e": 2549, "s": 2449, "text": "mysql> select group_concat(tbl.sub) from (select Subject sub from DemoTable group by Subject ) tbl;" }, { "code": null, "e": 2590, "s": 2549, "text": "This will produce the following output −" }, { "code": null, "e": 2759, "s": 2590, "text": "+--------------------------+\n| group_concat(tbl.sub) |\n+--------------------------+\n| C,C++,MongoDB,MySQL,Java |\n+--------------------------+\n1 row in set (0.04 sec)" } ]
Dimensionality Reduction (PCA) Explained | by Vatsal | Towards Data Science
Table of Contents Introduction What is Dimensionality Reduction? Linear Combination Feature Engineering & Feature Selection Data PCA- Intuition- Mathematical Breakdown - Advantages- Disadvantages- Implementation Summary Resources Introduction Dimensionality reduction is a popular method in machine learning commonly used by data scientists. This article will focus on a very popular unsupervised learning approach to dimensionality reduction, principle component analysis (PCA). Consider this to be an introductory article with the scope of providing an intuitive understanding of what dimensionality reduction is, how PCA works and how to implement it in Python. Before jumping into dimensionality reduction, let’s first define what a dimension is. Given a matrix A, the dimension of the matrix is the number of rows by the number of columns. If A has 3 rows and 5 columns, A would be a 3x5 matrix. A = [1, 2, 3] --> 1 row, 3 columnsThe dimension of A is 1x3 Now in the most simplest of terms, dimensionality reduction is exactly what it sounds like, you’re reducing the dimension of a matrix to something smaller than it currently is. Given a square (n by n) matrix A, the goal would be to reduce the dimension of this matrix to be smaller than n x n. Current Dimension of A : nReduced Dimension of A : n - x, where x is some positive integer You might ask why someone would you want to do this, the most common application would be for data visualization purposes. It’s quite difficult to visualize something graphically which is in a dimension space greater than 3. Through dimensionality reduction, you’ll be able to transform your dataset of 1000s of rows and columns into one small enough to visualize in 3 / 2 / 1 dimensions. Without doing a massive deep dive into the mathematics behind linear algebra, the simplest way to reduce the dimension of matrix A is to multiply it by a vector / matrix X such that the product equals to b. The formula would be Ax=B , this formula will have a solution if and only if B is a linear combination of the columns of A. Example The goal is to reduce the matrix 4x4 dimension matrix A to a matrix of 4x2 dimensions. The values below are from a random example.A = [[1,2,3,4], x = [[1,2], [3,4,5,6], [3,4], [4,5,6,7], [0,1], [5,6,7,8]] [4,0]]Ax = [[23,13], [39,27], [47,34], [55,41]]The output B now has a dimension of 4x2. Given a dataset of various features, you can reduce the number of features through feature engineering and feature selection. This in it’s self is intuitively reducing the dimensions of the original dataset you were working with. Assuming you have a DataFrame with the following columns : Feature 1 | Feature 2 | Feature 3 | Feature 4 | Feature 5 and you found that you can combine a set of features without losing information about those features by doing some arithmetic. Then the new feature would replace the pairs of features it was produced from. The process of creating new features through some means of preprocessing is known as feature engineering, and the process of selecting specific features for the purposes of training a model is known as feature selection. ExampleFeature 1 + Feature 2 = Feature 6Now your new features are : Feature 3 | Feature 4 | Feature 5 | Feature 6 I’ll show you how to implement PCA through sklearn using NBA data. You can download the data directly from my GitHub repository here or download it from it’s original source from Kaggle here PCA is a highly used unsupervised learning technique to reduce the dimension of a large dataset. It transforms the large set of variables into smaller components which contains majority of the information in the large one. Reducing the size of dataset would naturally result in the loss of information and would impact the accuracy of a model, this downside is offset by the ease of use for exploration, visualization and analysis purposes. Suppose we are looking at a data set associated to a collection of athletes with all of their associated stats. Each of those stats measure various characteristics associated to the athlete, things like height, weight, wingspan, efficiency, points, rebounds, blocks, turnovers, etc. This would essentially yield us a large dataset of various characteristics associated to each of our players, however, many of the characteristics might be related to one another and thus redundant information. PCA aims to create new characteristics which summarize the initial characteristics we had. Through finding linear combinations of the old characteristics, PCA can construct new characteristics whilst trying to minimize information loss. For example, a new characteristic might be computed as the average number of points of a player subtracted by the average number of turnovers per game. It does this by identifying characteristics which strongly differ across players. Mathematical Breakdown Mathematically PCA can be broken down into 4 simple steps. Identify the centre of the data & reposition the data and centre to the origin- This can be accomplished by taking the average of each column and subtracting the original data by that averageCalculate the covariance matrix of the centred matrixCalculate the eigenvector of the covariance matrixProject the eigenvectors onto the covariance matrix through the dot product Identify the centre of the data & reposition the data and centre to the origin- This can be accomplished by taking the average of each column and subtracting the original data by that average Calculate the covariance matrix of the centred matrix Calculate the eigenvector of the covariance matrix Project the eigenvectors onto the covariance matrix through the dot product Mathematically, it is a projection of a higher-dimensional object in a lower-dimensional vector space. Removes correlated features Allows for easier visualization Helps reducing overfitting Variables become less interpretable Information loss Data standardization Note : You may need to change the path on line 11 associated to where you saved the data. Dimensionality reduction is a commonly used method in machine learning, there are many ways to approach reducing the dimensions of your data from feature engineering and feature selection to the implementation of unsupervised learning algorithms like PCA. PCA aims to create new characteristics which summarize the initial characteristics of a dataset through identifying linear combinations. https://builtin.com/data-science/step-step-explanation-principal-component-analysis https://machinelearningmastery.com/calculate-principal-component-analysis-scratch-python/ https://datascience.stackexchange.com/questions/60351/intuition-behind-the-pca-algorithm https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues https://www.i2tutorials.com/what-are-the-pros-and-cons-of-the-pca/ Thank you for reading through my article, if you liked this article, here are some others I’ve written which you might be interested in.
[ { "code": null, "e": 190, "s": 172, "text": "Table of Contents" }, { "code": null, "e": 203, "s": 190, "text": "Introduction" }, { "code": null, "e": 237, "s": 203, "text": "What is Dimensionality Reduction?" }, { "code": null, "e": 256, "s": 237, "text": "Linear Combination" }, { "code": null, "e": 296, "s": 256, "text": "Feature Engineering & Feature Selection" }, { "code": null, "e": 301, "s": 296, "text": "Data" }, { "code": null, "e": 384, "s": 301, "text": "PCA- Intuition- Mathematical Breakdown - Advantages- Disadvantages- Implementation" }, { "code": null, "e": 392, "s": 384, "text": "Summary" }, { "code": null, "e": 402, "s": 392, "text": "Resources" }, { "code": null, "e": 415, "s": 402, "text": "Introduction" }, { "code": null, "e": 837, "s": 415, "text": "Dimensionality reduction is a popular method in machine learning commonly used by data scientists. This article will focus on a very popular unsupervised learning approach to dimensionality reduction, principle component analysis (PCA). Consider this to be an introductory article with the scope of providing an intuitive understanding of what dimensionality reduction is, how PCA works and how to implement it in Python." }, { "code": null, "e": 1073, "s": 837, "text": "Before jumping into dimensionality reduction, let’s first define what a dimension is. Given a matrix A, the dimension of the matrix is the number of rows by the number of columns. If A has 3 rows and 5 columns, A would be a 3x5 matrix." }, { "code": null, "e": 1135, "s": 1073, "text": "A = [1, 2, 3] --> 1 row, 3 columnsThe dimension of A is 1x3" }, { "code": null, "e": 1429, "s": 1135, "text": "Now in the most simplest of terms, dimensionality reduction is exactly what it sounds like, you’re reducing the dimension of a matrix to something smaller than it currently is. Given a square (n by n) matrix A, the goal would be to reduce the dimension of this matrix to be smaller than n x n." }, { "code": null, "e": 1520, "s": 1429, "text": "Current Dimension of A : nReduced Dimension of A : n - x, where x is some positive integer" }, { "code": null, "e": 1909, "s": 1520, "text": "You might ask why someone would you want to do this, the most common application would be for data visualization purposes. It’s quite difficult to visualize something graphically which is in a dimension space greater than 3. Through dimensionality reduction, you’ll be able to transform your dataset of 1000s of rows and columns into one small enough to visualize in 3 / 2 / 1 dimensions." }, { "code": null, "e": 2240, "s": 1909, "text": "Without doing a massive deep dive into the mathematics behind linear algebra, the simplest way to reduce the dimension of matrix A is to multiply it by a vector / matrix X such that the product equals to b. The formula would be Ax=B , this formula will have a solution if and only if B is a linear combination of the columns of A." }, { "code": null, "e": 2248, "s": 2240, "text": "Example" }, { "code": null, "e": 2603, "s": 2248, "text": "The goal is to reduce the matrix 4x4 dimension matrix A to a matrix of 4x2 dimensions. The values below are from a random example.A = [[1,2,3,4], x = [[1,2], [3,4,5,6], [3,4], [4,5,6,7], [0,1], [5,6,7,8]] [4,0]]Ax = [[23,13], [39,27], [47,34], [55,41]]The output B now has a dimension of 4x2." }, { "code": null, "e": 2892, "s": 2603, "text": "Given a dataset of various features, you can reduce the number of features through feature engineering and feature selection. This in it’s self is intuitively reducing the dimensions of the original dataset you were working with. Assuming you have a DataFrame with the following columns :" }, { "code": null, "e": 3377, "s": 2892, "text": "Feature 1 | Feature 2 | Feature 3 | Feature 4 | Feature 5 and you found that you can combine a set of features without losing information about those features by doing some arithmetic. Then the new feature would replace the pairs of features it was produced from. The process of creating new features through some means of preprocessing is known as feature engineering, and the process of selecting specific features for the purposes of training a model is known as feature selection." }, { "code": null, "e": 3491, "s": 3377, "text": "ExampleFeature 1 + Feature 2 = Feature 6Now your new features are : Feature 3 | Feature 4 | Feature 5 | Feature 6" }, { "code": null, "e": 3682, "s": 3491, "text": "I’ll show you how to implement PCA through sklearn using NBA data. You can download the data directly from my GitHub repository here or download it from it’s original source from Kaggle here" }, { "code": null, "e": 4123, "s": 3682, "text": "PCA is a highly used unsupervised learning technique to reduce the dimension of a large dataset. It transforms the large set of variables into smaller components which contains majority of the information in the large one. Reducing the size of dataset would naturally result in the loss of information and would impact the accuracy of a model, this downside is offset by the ease of use for exploration, visualization and analysis purposes." }, { "code": null, "e": 4617, "s": 4123, "text": "Suppose we are looking at a data set associated to a collection of athletes with all of their associated stats. Each of those stats measure various characteristics associated to the athlete, things like height, weight, wingspan, efficiency, points, rebounds, blocks, turnovers, etc. This would essentially yield us a large dataset of various characteristics associated to each of our players, however, many of the characteristics might be related to one another and thus redundant information." }, { "code": null, "e": 5088, "s": 4617, "text": "PCA aims to create new characteristics which summarize the initial characteristics we had. Through finding linear combinations of the old characteristics, PCA can construct new characteristics whilst trying to minimize information loss. For example, a new characteristic might be computed as the average number of points of a player subtracted by the average number of turnovers per game. It does this by identifying characteristics which strongly differ across players." }, { "code": null, "e": 5111, "s": 5088, "text": "Mathematical Breakdown" }, { "code": null, "e": 5170, "s": 5111, "text": "Mathematically PCA can be broken down into 4 simple steps." }, { "code": null, "e": 5540, "s": 5170, "text": "Identify the centre of the data & reposition the data and centre to the origin- This can be accomplished by taking the average of each column and subtracting the original data by that averageCalculate the covariance matrix of the centred matrixCalculate the eigenvector of the covariance matrixProject the eigenvectors onto the covariance matrix through the dot product" }, { "code": null, "e": 5732, "s": 5540, "text": "Identify the centre of the data & reposition the data and centre to the origin- This can be accomplished by taking the average of each column and subtracting the original data by that average" }, { "code": null, "e": 5786, "s": 5732, "text": "Calculate the covariance matrix of the centred matrix" }, { "code": null, "e": 5837, "s": 5786, "text": "Calculate the eigenvector of the covariance matrix" }, { "code": null, "e": 5913, "s": 5837, "text": "Project the eigenvectors onto the covariance matrix through the dot product" }, { "code": null, "e": 6016, "s": 5913, "text": "Mathematically, it is a projection of a higher-dimensional object in a lower-dimensional vector space." }, { "code": null, "e": 6044, "s": 6016, "text": "Removes correlated features" }, { "code": null, "e": 6076, "s": 6044, "text": "Allows for easier visualization" }, { "code": null, "e": 6103, "s": 6076, "text": "Helps reducing overfitting" }, { "code": null, "e": 6139, "s": 6103, "text": "Variables become less interpretable" }, { "code": null, "e": 6156, "s": 6139, "text": "Information loss" }, { "code": null, "e": 6177, "s": 6156, "text": "Data standardization" }, { "code": null, "e": 6267, "s": 6177, "text": "Note : You may need to change the path on line 11 associated to where you saved the data." }, { "code": null, "e": 6660, "s": 6267, "text": "Dimensionality reduction is a commonly used method in machine learning, there are many ways to approach reducing the dimensions of your data from feature engineering and feature selection to the implementation of unsupervised learning algorithms like PCA. PCA aims to create new characteristics which summarize the initial characteristics of a dataset through identifying linear combinations." }, { "code": null, "e": 6744, "s": 6660, "text": "https://builtin.com/data-science/step-step-explanation-principal-component-analysis" }, { "code": null, "e": 6834, "s": 6744, "text": "https://machinelearningmastery.com/calculate-principal-component-analysis-scratch-python/" }, { "code": null, "e": 6923, "s": 6834, "text": "https://datascience.stackexchange.com/questions/60351/intuition-behind-the-pca-algorithm" }, { "code": null, "e": 7040, "s": 6923, "text": "https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues" }, { "code": null, "e": 7107, "s": 7040, "text": "https://www.i2tutorials.com/what-are-the-pros-and-cons-of-the-pca/" } ]
Openpyxl - Adding Image - GeeksforGeeks
07 Jan, 2022 Openpyxl is a Python library for manipulating excel documents of the format (xlsx/xlsm/xltx/xltm) created in different variants of Microsoft Excel. The Genesis of the library happened due to lack of a native library to read/write natively from Python the Office Open XML format. Openpyxl provides python with data set processing capabilities and allows creating different types of database files. One of the stark features offered by the library is allowing the user to define an image inside a cell of the sheet (worksheet). This opens the room for incorporating visual data inside our worksheet, allowing for more comprehensive and explicit results. To install the openpyxl library execute the following command in the command-line: pip install openpyxl For the purpose of importing images inside our worksheet, we would be using a method found inside the openpyxl library under the name of openpyxl.drawing.image.Image. The method is a wrapper over PIL.Image method found in PIL (pillow) library. Due to which it is necessary for the PIL (pillow) library to be installed in order to use this method. Test Image (test.png): Below is the implementation – Python3 import openpyxl # It is not required for one to create a workbook on # filesystem, therefore creating a virtual workbook wrkb = openpyxl.Workbook() # Number of sheets in the workbook (1 sheet in our case)ws = wrkb.worksheets[0] # Adding a row of data to the worksheet (used to# distinguish previous excel data from the image)ws.append([10, 2010, "Geeks", 4, "life"]) # A wrapper over PIL.Image, used to provide image# inclusion properties to openpyxl libraryimg = openpyxl.drawing.image.Image('test.png') # The Coordinates where the image would be pasted# (an image could span several rows and columns# depending on it's size)img.anchor = 'A2' # Adding the image to the worksheet# (with attributes like position)ws.add_image(img) # Saving the workbook created under the name of out.xlsxwb.save('out.xlsx') Output (out.xlsx):- ExplanationThe above code first creates a workbook and saves in the variable wrkb (abbreviation for workbook). wrkb.worksheet[0] specifies the lists of sheets in the book. Since we only want one sheet, we specified 0 as an argument. ws.append() is used to add data to our worksheet. In our case we are adding a row of data 10, 2010, "Geeks", 4, "life" to our worksheet. openpyxl.drawing.image.Image('test.png') specifies the path of the image that would be added inside the worksheet (test.png in our case). img.anchor = 'A2' is used to specify the coordinates at which the image is to be pasted/added.By default the image would be added from cell A1 (anchor A1) or the first cell of our workbook. This position could be changed by specifying a cell coordinates in img.anchor attribute. ws.add_image() adds the image inside the worksheet. This is a method used to finalize the image changes that we want. All other attributes like anchor, would be supplied before this function. wrkb.save() is used to save our worksheet. A path (relative/absolute) is required as an argument, along with any extension included in the path (if not explicitly provided). abhishek0719kadiyan Picked Python Openpyxl-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n07 Jan, 2022" }, { "code": null, "e": 25926, "s": 25647, "text": "Openpyxl is a Python library for manipulating excel documents of the format (xlsx/xlsm/xltx/xltm) created in different variants of Microsoft Excel. The Genesis of the library happened due to lack of a native library to read/write natively from Python the Office Open XML format." }, { "code": null, "e": 26299, "s": 25926, "text": "Openpyxl provides python with data set processing capabilities and allows creating different types of database files. One of the stark features offered by the library is allowing the user to define an image inside a cell of the sheet (worksheet). This opens the room for incorporating visual data inside our worksheet, allowing for more comprehensive and explicit results." }, { "code": null, "e": 26382, "s": 26299, "text": "To install the openpyxl library execute the following command in the command-line:" }, { "code": null, "e": 26403, "s": 26382, "text": "pip install openpyxl" }, { "code": null, "e": 26750, "s": 26403, "text": "For the purpose of importing images inside our worksheet, we would be using a method found inside the openpyxl library under the name of openpyxl.drawing.image.Image. The method is a wrapper over PIL.Image method found in PIL (pillow) library. Due to which it is necessary for the PIL (pillow) library to be installed in order to use this method." }, { "code": null, "e": 26773, "s": 26750, "text": "Test Image (test.png):" }, { "code": null, "e": 26803, "s": 26773, "text": "Below is the implementation –" }, { "code": null, "e": 26811, "s": 26803, "text": "Python3" }, { "code": "import openpyxl # It is not required for one to create a workbook on # filesystem, therefore creating a virtual workbook wrkb = openpyxl.Workbook() # Number of sheets in the workbook (1 sheet in our case)ws = wrkb.worksheets[0] # Adding a row of data to the worksheet (used to# distinguish previous excel data from the image)ws.append([10, 2010, \"Geeks\", 4, \"life\"]) # A wrapper over PIL.Image, used to provide image# inclusion properties to openpyxl libraryimg = openpyxl.drawing.image.Image('test.png') # The Coordinates where the image would be pasted# (an image could span several rows and columns# depending on it's size)img.anchor = 'A2' # Adding the image to the worksheet# (with attributes like position)ws.add_image(img) # Saving the workbook created under the name of out.xlsxwb.save('out.xlsx')", "e": 27625, "s": 26811, "text": null }, { "code": null, "e": 27645, "s": 27625, "text": "Output (out.xlsx):-" }, { "code": null, "e": 28798, "s": 27645, "text": "ExplanationThe above code first creates a workbook and saves in the variable wrkb (abbreviation for workbook). wrkb.worksheet[0] specifies the lists of sheets in the book. Since we only want one sheet, we specified 0 as an argument. ws.append() is used to add data to our worksheet. In our case we are adding a row of data 10, 2010, \"Geeks\", 4, \"life\" to our worksheet. openpyxl.drawing.image.Image('test.png') specifies the path of the image that would be added inside the worksheet (test.png in our case). img.anchor = 'A2' is used to specify the coordinates at which the image is to be pasted/added.By default the image would be added from cell A1 (anchor A1) or the first cell of our workbook. This position could be changed by specifying a cell coordinates in img.anchor attribute. ws.add_image() adds the image inside the worksheet. This is a method used to finalize the image changes that we want. All other attributes like anchor, would be supplied before this function. wrkb.save() is used to save our worksheet. A path (relative/absolute) is required as an argument, along with any extension included in the path (if not explicitly provided)." }, { "code": null, "e": 28818, "s": 28798, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28825, "s": 28818, "text": "Picked" }, { "code": null, "e": 28848, "s": 28825, "text": "Python Openpyxl-module" }, { "code": null, "e": 28855, "s": 28848, "text": "Python" }, { "code": null, "e": 28953, "s": 28855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28985, "s": 28953, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29027, "s": 28985, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29069, "s": 29027, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29125, "s": 29069, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29152, "s": 29125, "text": "Python Classes and Objects" }, { "code": null, "e": 29183, "s": 29152, "text": "Python | os.path.join() method" }, { "code": null, "e": 29219, "s": 29183, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 29248, "s": 29219, "text": "Create a directory in Python" }, { "code": null, "e": 29270, "s": 29248, "text": "Defaultdict in Python" } ]
Is name a reserved word in MySQL?
No, name is not a reserved word in MySQL, you can use without backtick symbol. If you are working on a reserved word then use backtick symbol. Let us first create a table − mysql> create table name ( name varchar(10) ); Query OK, 0 rows affected (0.78 sec) Now you can insert some records in the table using insert command − mysql> insert into name values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into name values('Carol'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select *from name; +-------+ | name | +-------+ | John | | Carol | +-------+ 2 rows in set (0.00 sec) If you have a reserved word then you need to use backtick symbol. Let us now create a table with table name as reserved word “select” − mysql> create table `select` ( `select` int ); Query OK, 0 rows affected (0.70 sec) Above we have used a backtick symbol, since we are considering the table name as reserved word. Now you can insert some records in the table using insert command − mysql> insert into `select` values(1); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select `select` from `select`; +--------+ | select | +--------+ | 1 | +--------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1235, "s": 1062, "text": "No, name is not a reserved word in MySQL, you can use without backtick symbol. If you are working on a reserved word then use backtick symbol. Let us first create a table −" }, { "code": null, "e": 1328, "s": 1235, "text": "mysql> create table name\n (\n name varchar(10)\n );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1396, "s": 1328, "text": "Now you can insert some records in the table using insert command −" }, { "code": null, "e": 1549, "s": 1396, "text": "mysql> insert into name values('John');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into name values('Carol');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1609, "s": 1549, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1635, "s": 1609, "text": "mysql> select *from name;" }, { "code": null, "e": 1720, "s": 1635, "text": "+-------+\n| name |\n+-------+\n| John |\n| Carol |\n+-------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 1856, "s": 1720, "text": "If you have a reserved word then you need to use backtick symbol. Let us now create a table with table name as reserved word “select” −" }, { "code": null, "e": 1949, "s": 1856, "text": "mysql> create table `select`\n (\n `select` int\n );\nQuery OK, 0 rows affected (0.70 sec)" }, { "code": null, "e": 2113, "s": 1949, "text": "Above we have used a backtick symbol, since we are considering the table name as reserved word. Now you can insert some records in the table using insert command −" }, { "code": null, "e": 2188, "s": 2113, "text": "mysql> insert into `select` values(1);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2248, "s": 2188, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2286, "s": 2248, "text": "mysql> select `select` from `select`;" }, { "code": null, "e": 2365, "s": 2286, "text": "+--------+\n| select |\n+--------+\n| 1 |\n+--------+\n1 row in set (0.00 sec)" } ]
adduser command in Linux with Examples - GeeksforGeeks
22 Jun, 2020 adduser command in Linux is used to add a new user to your current Linux machine. This command allows you to modify the configurations of the user which is to be created. It is similar to the useradd command in Linux. The adduser command is much interactive as compared to useradd command. To install adduser tool use the following commands as per your Linux distribution. In case of Debian/Ubuntu $sudo apt-get install adduser In case of CentOS/RedHat $sudo yum install adduser In case of Fedora OS $sudo dnf install adduser 1. To add a new user adduser username This command will add a new user to your Linux system. It will ask for some details and after entering those details a new user account would be created. 2. To add a user with a different shell. sudo adduser username --shell /bin/sh This command will change the default shell for the new user to /bin/sh. 3. To add a new user with a different configuration file. adduser username --conf custom_config.conf This command will take the configurations from the custom_config file and will create the new as per custom_config filename configurations. 4. To add a user with different home directory. adduser username --home /home/manav/ This command will add the new user with /home/manav as the default directory. 5. To get the version of the adduser command. adduser --version This command will print the version details of the adduser command. 6. To display the help section of the adduser command adduser -h This command will display the help section of the adduser command. linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples 'crontab' in Linux with Examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++ Tail command in Linux with examples
[ { "code": null, "e": 24145, "s": 24117, "text": "\n22 Jun, 2020" }, { "code": null, "e": 24435, "s": 24145, "text": "adduser command in Linux is used to add a new user to your current Linux machine. This command allows you to modify the configurations of the user which is to be created. It is similar to the useradd command in Linux. The adduser command is much interactive as compared to useradd command." }, { "code": null, "e": 24518, "s": 24435, "text": "To install adduser tool use the following commands as per your Linux distribution." }, { "code": null, "e": 24543, "s": 24518, "text": "In case of Debian/Ubuntu" }, { "code": null, "e": 24573, "s": 24543, "text": "$sudo apt-get install adduser" }, { "code": null, "e": 24598, "s": 24573, "text": "In case of CentOS/RedHat" }, { "code": null, "e": 24624, "s": 24598, "text": "$sudo yum install adduser" }, { "code": null, "e": 24645, "s": 24624, "text": "In case of Fedora OS" }, { "code": null, "e": 24671, "s": 24645, "text": "$sudo dnf install adduser" }, { "code": null, "e": 24692, "s": 24671, "text": "1. To add a new user" }, { "code": null, "e": 24709, "s": 24692, "text": "adduser username" }, { "code": null, "e": 24863, "s": 24709, "text": "This command will add a new user to your Linux system. It will ask for some details and after entering those details a new user account would be created." }, { "code": null, "e": 24904, "s": 24863, "text": "2. To add a user with a different shell." }, { "code": null, "e": 24942, "s": 24904, "text": "sudo adduser username --shell /bin/sh" }, { "code": null, "e": 25014, "s": 24942, "text": "This command will change the default shell for the new user to /bin/sh." }, { "code": null, "e": 25072, "s": 25014, "text": "3. To add a new user with a different configuration file." }, { "code": null, "e": 25115, "s": 25072, "text": "adduser username --conf custom_config.conf" }, { "code": null, "e": 25255, "s": 25115, "text": "This command will take the configurations from the custom_config file and will create the new as per custom_config filename configurations." }, { "code": null, "e": 25303, "s": 25255, "text": "4. To add a user with different home directory." }, { "code": null, "e": 25340, "s": 25303, "text": "adduser username --home /home/manav/" }, { "code": null, "e": 25418, "s": 25340, "text": "This command will add the new user with /home/manav as the default directory." }, { "code": null, "e": 25464, "s": 25418, "text": "5. To get the version of the adduser command." }, { "code": null, "e": 25482, "s": 25464, "text": "adduser --version" }, { "code": null, "e": 25550, "s": 25482, "text": "This command will print the version details of the adduser command." }, { "code": null, "e": 25604, "s": 25550, "text": "6. To display the help section of the adduser command" }, { "code": null, "e": 25615, "s": 25604, "text": "adduser -h" }, { "code": null, "e": 25682, "s": 25615, "text": "This command will display the help section of the adduser command." }, { "code": null, "e": 25696, "s": 25682, "text": "linux-command" }, { "code": null, "e": 25707, "s": 25696, "text": "Linux-Unix" }, { "code": null, "e": 25805, "s": 25707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25814, "s": 25805, "text": "Comments" }, { "code": null, "e": 25827, "s": 25814, "text": "Old Comments" }, { "code": null, "e": 25862, "s": 25827, "text": "tar command in Linux with examples" }, { "code": null, "e": 25900, "s": 25862, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 25936, "s": 25900, "text": "diff command in Linux with examples" }, { "code": null, "e": 25974, "s": 25936, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 26009, "s": 25974, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26042, "s": 26009, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 26079, "s": 26042, "text": "touch command in Linux with Examples" }, { "code": null, "e": 26115, "s": 26079, "text": "echo command in Linux with Examples" }, { "code": null, "e": 26134, "s": 26115, "text": "Compiling with g++" } ]
Movies Data Science — Pull & Analyze IMDb data using Python | by Jean L | Towards Data Science
IMDb (Internet Movie Database) is one of the most recognized names for its comprehensive online database collection of movies, films, TV series and so on. As of today (July 2020), you’ll see through the following data pull that IMDb database has approximately 7 million titles. In this article, I will use Python in Jupyter Notebook to demonstrate where to pull the data, how to quickly interpret the data and answer some interesting questions including - What kind of data does the IMDb database cover? - What kind of ratings do people give in general? Is it really a normal distribution? Which movies get the best ratings? - Based on the movies that I like, which ones should I also check out? IMDb has made essential susbsets of its database available for non-commercial use of the public and its customers on the IMDb website, where you can also find all relevant details described in the corresponding IMDb data dictionary. In this analysis I focus on mainly 2 datasets (title.basics and title.ratings) which offers 9 and 3 features respectively that include the title ID, name, type, adult movie flag, genre, ratings and the number of votes a title has received. basics_tsv_file =”C:\\Users\....\Downloads\\basics.tsv”basics = pd.read_csv(basics_tsv_file, sep=’\t’,low_memory=False)ratings_tsv_file = "C:\\Users\....\Downloads\\ratings.tsv"ratings = pd.read_csv(ratings_tsv_file, sep='\t',low_memory=False)data = pd.merge(basics, ratings, on ="tconst") As you pull the two datasets by unique IMDb Title IDs (tconst), you’ll notice that the two datasets are 7x different in size: title.basics has 7 million titles, but title.ratings has only 1 million titles But as you merge the two datasets, you’ll see that the number of titles did not decreased after merge. This implied that all the titles included in title.ratings are actually a subset of the titles in title.basics; this is good news as it means that all titles with ratings have basic information in place. Here I’m not getting into details but I’m working on another piece where I will apply Principle Component Analysis, one of the most useful unsupervised machine learning technique, to see deep dive what kind of movies tend to not have ratings data. With that, the merged dataset as shown below has 1 million titles and 11 dimensions, where various analysis tools can be applied on: Pareto 80/20 Rule for the Top Types (TV Episodes, Movies and Short Films) For the Tiles Types, Pareto 80/20 rule is definitely true here. There are in total 10 different Title Types, where the top ones with the highest number of titles are TV Episodes (accounting for almost half of the titles), followed by Movies and Short Films. These top three types in total account for over 80% of the total number of titles. On the other hand,the bottom 3 types with the least number of titles (TV short, TV special and TV mini series) in total account for less than 10% of the total number of titles. The Top Genres are Comedy, Drama and Documentary among the Overly Complicated Classifications For the Tiles Genres, IMDb has a long list of almost 2,000 different genres. And as you can see, the distribution of genres has a long tail where only the top 3 Genres (Comedy, Drama and Documentary) take a share for more than 5% but all other genres account for nothing more than 3%. Note that the long tail may be resulted from an overly complicated classification among different genres. For example, while “Comedy” accounts for 9%, there are lots of similar but slightly different genres such as “Comedy, Drama” (2%), “Comedy, short” (2%), or even “Adventure, Animation, Comedy” (1%) etc etc, each taking up some of the shares that could’ve been classified as “Comedy”. Not to mention how one movie can be strictly classified as “Adventure, Animation, Comedy” instead of simply “Action, Adventure, Animation” or “Comedy.” Not many X-Rated Movies in the IMDb database IMDb has a “isAdult” factor which is a boolean (0/1) variable in the basic dataset that flags out 18+ Adult Movies. As from the above pie chart, there are minimal number of Adult Movies in the IMDb database, accounting for only 1.8% of the total number of titles. (*Note to transform the dtype from object to boolean before doing the analysis as the default dtype can be misleading for further analysis) Average rating is around 7 out 10. People are generous in terms of giving ratings! Here’s a box-and-whisker diagram that helps describe the differences in Ratings distribution among and within each Title Type. First, it is interesting to see that instead of a normal Gaussian distribution, overall the Ratings are very skewed to the right. Instead of having a medium rating of 5, the typical medium average rating is around 7. Ratings for TV Episodes are much higher than Movies Also, among the ten Title Types, Ratings for TV Episodes are overall higher with less variation compared to Movies, which brings up an interesting question: is it really because the quality of TV Episodes is significantly better than Movies in general? Do people tend to hold a higher standard and be more critical on Movies? These are yet to be answered but for sure if you see a TV Episode with Ratings of 7, it is likely just an average series. On the other hand, make sure to check out a movie with Ratings of 7! This concludes my initial data exploration of the IMDb data, which covered most of the questions I had in mind as I started this analysis. As a next step, I’m working some further analysis to see how my last question on which other movies may interest me more, and will share with you once available. You can find the complete code here at GitHub in Python Jupyter Notebook. I hope you enjoyed and learned something interesting from the article. If you have any questions or thoughts on what may be fun digging further, please feel free to clap and comment. Thanks!
[ { "code": null, "e": 626, "s": 172, "text": "IMDb (Internet Movie Database) is one of the most recognized names for its comprehensive online database collection of movies, films, TV series and so on. As of today (July 2020), you’ll see through the following data pull that IMDb database has approximately 7 million titles. In this article, I will use Python in Jupyter Notebook to demonstrate where to pull the data, how to quickly interpret the data and answer some interesting questions including" }, { "code": null, "e": 676, "s": 626, "text": "- What kind of data does the IMDb database cover?" }, { "code": null, "e": 797, "s": 676, "text": "- What kind of ratings do people give in general? Is it really a normal distribution? Which movies get the best ratings?" }, { "code": null, "e": 868, "s": 797, "text": "- Based on the movies that I like, which ones should I also check out?" }, { "code": null, "e": 1341, "s": 868, "text": "IMDb has made essential susbsets of its database available for non-commercial use of the public and its customers on the IMDb website, where you can also find all relevant details described in the corresponding IMDb data dictionary. In this analysis I focus on mainly 2 datasets (title.basics and title.ratings) which offers 9 and 3 features respectively that include the title ID, name, type, adult movie flag, genre, ratings and the number of votes a title has received." }, { "code": null, "e": 1631, "s": 1341, "text": "basics_tsv_file =”C:\\\\Users\\....\\Downloads\\\\basics.tsv”basics = pd.read_csv(basics_tsv_file, sep=’\\t’,low_memory=False)ratings_tsv_file = \"C:\\\\Users\\....\\Downloads\\\\ratings.tsv\"ratings = pd.read_csv(ratings_tsv_file, sep='\\t',low_memory=False)data = pd.merge(basics, ratings, on =\"tconst\")" }, { "code": null, "e": 1757, "s": 1631, "text": "As you pull the two datasets by unique IMDb Title IDs (tconst), you’ll notice that the two datasets are 7x different in size:" }, { "code": null, "e": 1796, "s": 1757, "text": "title.basics has 7 million titles, but" }, { "code": null, "e": 1836, "s": 1796, "text": "title.ratings has only 1 million titles" }, { "code": null, "e": 2391, "s": 1836, "text": "But as you merge the two datasets, you’ll see that the number of titles did not decreased after merge. This implied that all the titles included in title.ratings are actually a subset of the titles in title.basics; this is good news as it means that all titles with ratings have basic information in place. Here I’m not getting into details but I’m working on another piece where I will apply Principle Component Analysis, one of the most useful unsupervised machine learning technique, to see deep dive what kind of movies tend to not have ratings data." }, { "code": null, "e": 2524, "s": 2391, "text": "With that, the merged dataset as shown below has 1 million titles and 11 dimensions, where various analysis tools can be applied on:" }, { "code": null, "e": 2598, "s": 2524, "text": "Pareto 80/20 Rule for the Top Types (TV Episodes, Movies and Short Films)" }, { "code": null, "e": 3116, "s": 2598, "text": "For the Tiles Types, Pareto 80/20 rule is definitely true here. There are in total 10 different Title Types, where the top ones with the highest number of titles are TV Episodes (accounting for almost half of the titles), followed by Movies and Short Films. These top three types in total account for over 80% of the total number of titles. On the other hand,the bottom 3 types with the least number of titles (TV short, TV special and TV mini series) in total account for less than 10% of the total number of titles." }, { "code": null, "e": 3210, "s": 3116, "text": "The Top Genres are Comedy, Drama and Documentary among the Overly Complicated Classifications" }, { "code": null, "e": 3495, "s": 3210, "text": "For the Tiles Genres, IMDb has a long list of almost 2,000 different genres. And as you can see, the distribution of genres has a long tail where only the top 3 Genres (Comedy, Drama and Documentary) take a share for more than 5% but all other genres account for nothing more than 3%." }, { "code": null, "e": 4036, "s": 3495, "text": "Note that the long tail may be resulted from an overly complicated classification among different genres. For example, while “Comedy” accounts for 9%, there are lots of similar but slightly different genres such as “Comedy, Drama” (2%), “Comedy, short” (2%), or even “Adventure, Animation, Comedy” (1%) etc etc, each taking up some of the shares that could’ve been classified as “Comedy”. Not to mention how one movie can be strictly classified as “Adventure, Animation, Comedy” instead of simply “Action, Adventure, Animation” or “Comedy.”" }, { "code": null, "e": 4081, "s": 4036, "text": "Not many X-Rated Movies in the IMDb database" }, { "code": null, "e": 4345, "s": 4081, "text": "IMDb has a “isAdult” factor which is a boolean (0/1) variable in the basic dataset that flags out 18+ Adult Movies. As from the above pie chart, there are minimal number of Adult Movies in the IMDb database, accounting for only 1.8% of the total number of titles." }, { "code": null, "e": 4485, "s": 4345, "text": "(*Note to transform the dtype from object to boolean before doing the analysis as the default dtype can be misleading for further analysis)" }, { "code": null, "e": 4568, "s": 4485, "text": "Average rating is around 7 out 10. People are generous in terms of giving ratings!" }, { "code": null, "e": 4912, "s": 4568, "text": "Here’s a box-and-whisker diagram that helps describe the differences in Ratings distribution among and within each Title Type. First, it is interesting to see that instead of a normal Gaussian distribution, overall the Ratings are very skewed to the right. Instead of having a medium rating of 5, the typical medium average rating is around 7." }, { "code": null, "e": 4964, "s": 4912, "text": "Ratings for TV Episodes are much higher than Movies" }, { "code": null, "e": 5481, "s": 4964, "text": "Also, among the ten Title Types, Ratings for TV Episodes are overall higher with less variation compared to Movies, which brings up an interesting question: is it really because the quality of TV Episodes is significantly better than Movies in general? Do people tend to hold a higher standard and be more critical on Movies? These are yet to be answered but for sure if you see a TV Episode with Ratings of 7, it is likely just an average series. On the other hand, make sure to check out a movie with Ratings of 7!" }, { "code": null, "e": 5782, "s": 5481, "text": "This concludes my initial data exploration of the IMDb data, which covered most of the questions I had in mind as I started this analysis. As a next step, I’m working some further analysis to see how my last question on which other movies may interest me more, and will share with you once available." }, { "code": null, "e": 5856, "s": 5782, "text": "You can find the complete code here at GitHub in Python Jupyter Notebook." } ]
How to find and replace within a text file using Python?
The following code does the replacement in the given text file. After the replacement, the text is written to a new text file 'bar.txt' f1 = open('foo.txt', 'r') f2 = open('bar.txt', 'w') for line in f1: print line f2.write(line.replace('Poetry', 'Prose')) f2 = open('bar.txt', 'r') for line in f2: print line, f1.close() f2.close() This gives the output Poetry is often considered the oldest form of literature. Poetry today is usually written down, but is still sometimes performed. Prose is often considered the oldest form of literature. Prose today is usually written down, but is still sometimes performed.
[ { "code": null, "e": 1127, "s": 1062, "text": "The following code does the replacement in the given text file. " }, { "code": null, "e": 1199, "s": 1127, "text": "After the replacement, the text is written to a new text file 'bar.txt'" }, { "code": null, "e": 1407, "s": 1199, "text": "f1 = open('foo.txt', 'r')\nf2 = open('bar.txt', 'w')\nfor line in f1:\n print line\n f2.write(line.replace('Poetry', 'Prose'))\nf2 = open('bar.txt', 'r')\nfor line in f2:\n print line,\nf1.close()\nf2.close()" }, { "code": null, "e": 1429, "s": 1407, "text": "This gives the output" }, { "code": null, "e": 1688, "s": 1429, "text": "Poetry is often considered the oldest form of literature. Poetry today is usually\n written down, but is still sometimes performed.\nProse is often considered the oldest form of literature. Prose today is usually\nwritten down, but is still sometimes performed." } ]
String with additive sequence
05 Jul, 2022 Given a string, the task is to find whether it contains an additive sequence or not. A string contains an additive sequence if its digits can make a sequence of numbers in which every number is addition of previous two numbers. A valid string should contain at least three digit to make one additive sequence. Examples: Input : s = “235813” Output : true 2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13 Input : s = “199100199” Output : true 1 + 99 = 100, 99 + 100 = 199 Input : s = “12345678” Output : false This problem can be solved recursively, note that number of digits in added value can’t be smaller than digits in any of its operand that is why we will loop till (length of string)/2 for first number and (length of string – first number’s length)/ 2 for second number to ignore invalid result. Next thing to note is, first and second number can’t start with 0, which is checked in below code by isValid method. When we call recursively, we check that sum of first and second number is exactly equal to rest of string. If yes then direct return the result else check that sum string is prefix of rest of string or not, If yes then call recursively with second number, sum string and rest of string after removing sum string from rest of string and if sum string is not prefix of rest of string then no solution in available. Below is C++ implementation. CPP // C++ program to check whether a string// makes an additive sequence or not#include <bits/stdc++.h>using namespace std; // Checks whether num is valid or not, by// checking first character and sizebool isValid(string num){ if (num.size() > 1 && num[0] == '0') return false; return true;} // returns int value at pos string, if pos is// out of bound then returns 0int val(string a, int pos){ if (pos >= a.length()) return 0; // converting character to integer return (a[pos] - '0');} // add two number in string form and return// result as a stringstring addString(string a, string b){ string sum = ""; int i = a.length() - 1; int j = b.length() - 1; int carry = 0; // loop until both string get processed while (i >= 0 || j >= 0) { int t = val(a, i) + val(b, j) + carry; sum += (t % 10 + '0'); carry = t / 10; i--; j--; } if (carry) sum += (carry + '0'); reverse(sum.begin(), sum.end()); return sum;} // Recursive method to check c = a + bbool checkAddition(list<string>& res, string a, string b, string c){ // both first and second number should be valid if (!isValid(a) || !isValid(b)) return false; string sum = addString(a, b); // if sum is same as c then direct return if (sum == c) { res.push_back(sum); return true; } /* if sum size is greater than c, then no possible sequence further OR if c is not prefix of sum string, then no possible sequence further */ if (c.size() <= sum.size() || sum != c.substr(0, sum.size())) return false; else { res.push_back(sum); // next recursive call will have b as first // number, sum as second number and string // c as third number after removing prefix // sum string from c return checkAddition(res, b, sum, c.substr(sum.size())); }} // Method returns additive sequence from string as// a listlist<string> additiveSequence(string num){ list<string> res; int l = num.length(); // loop until l/2 only, because if first // number is larger,then no possible sequence // later for (int i = 1; i <= l/2; i++) { for (int j = 1; j <= (l - i)/2; j++) { if (checkAddition(res, num.substr(0, i), num.substr(i, j), num.substr(i + j))) { // adding first and second number at // front of result list res.push_front(num.substr(i, j)); res.push_front(num.substr(0, i)); return res; } } } // If code execution reaches here, then string // doesn't have any additive sequence res.clear(); return res;} // Method to print result listvoid printResult(list<string> res){ for (auto it = res.begin(); it != res.end(); it++) cout << *it << " "; cout << endl;} // Driver code to test above methodsint main(){ string num = "235813"; list<string> res = additiveSequence(num); printResult(res); num = "199100199"; res = additiveSequence(num); printResult(res); return 0;} 2 3 5 8 13 1 99 100 199 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. simmytarika5 hardikkoriintern Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all subsequences of a string Recursive Practice Problems with Solutions Reverse a stack using recursion Write a program to reverse digits of a number Write a program to reverse an array or string Reverse a string in Java C++ Data Types Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 363, "s": 52, "text": "Given a string, the task is to find whether it contains an additive sequence or not. A string contains an additive sequence if its digits can make a sequence of numbers in which every number is addition of previous two numbers. A valid string should contain at least three digit to make one additive sequence. " }, { "code": null, "e": 374, "s": 363, "text": "Examples: " }, { "code": null, "e": 549, "s": 374, "text": "Input : s = “235813”\nOutput : true\n2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13\n\nInput : s = “199100199”\nOutput : true\n1 + 99 = 100, 99 + 100 = 199\n\nInput : s = “12345678”\nOutput : false" }, { "code": null, "e": 845, "s": 549, "text": "This problem can be solved recursively, note that number of digits in added value can’t be smaller than digits in any of its operand that is why we will loop till (length of string)/2 for first number and (length of string – first number’s length)/ 2 for second number to ignore invalid result. " }, { "code": null, "e": 1376, "s": 845, "text": "Next thing to note is, first and second number can’t start with 0, which is checked in below code by isValid method. When we call recursively, we check that sum of first and second number is exactly equal to rest of string. If yes then direct return the result else check that sum string is prefix of rest of string or not, If yes then call recursively with second number, sum string and rest of string after removing sum string from rest of string and if sum string is not prefix of rest of string then no solution in available. " }, { "code": null, "e": 1405, "s": 1376, "text": "Below is C++ implementation." }, { "code": null, "e": 1409, "s": 1405, "text": "CPP" }, { "code": "// C++ program to check whether a string// makes an additive sequence or not#include <bits/stdc++.h>using namespace std; // Checks whether num is valid or not, by// checking first character and sizebool isValid(string num){ if (num.size() > 1 && num[0] == '0') return false; return true;} // returns int value at pos string, if pos is// out of bound then returns 0int val(string a, int pos){ if (pos >= a.length()) return 0; // converting character to integer return (a[pos] - '0');} // add two number in string form and return// result as a stringstring addString(string a, string b){ string sum = \"\"; int i = a.length() - 1; int j = b.length() - 1; int carry = 0; // loop until both string get processed while (i >= 0 || j >= 0) { int t = val(a, i) + val(b, j) + carry; sum += (t % 10 + '0'); carry = t / 10; i--; j--; } if (carry) sum += (carry + '0'); reverse(sum.begin(), sum.end()); return sum;} // Recursive method to check c = a + bbool checkAddition(list<string>& res, string a, string b, string c){ // both first and second number should be valid if (!isValid(a) || !isValid(b)) return false; string sum = addString(a, b); // if sum is same as c then direct return if (sum == c) { res.push_back(sum); return true; } /* if sum size is greater than c, then no possible sequence further OR if c is not prefix of sum string, then no possible sequence further */ if (c.size() <= sum.size() || sum != c.substr(0, sum.size())) return false; else { res.push_back(sum); // next recursive call will have b as first // number, sum as second number and string // c as third number after removing prefix // sum string from c return checkAddition(res, b, sum, c.substr(sum.size())); }} // Method returns additive sequence from string as// a listlist<string> additiveSequence(string num){ list<string> res; int l = num.length(); // loop until l/2 only, because if first // number is larger,then no possible sequence // later for (int i = 1; i <= l/2; i++) { for (int j = 1; j <= (l - i)/2; j++) { if (checkAddition(res, num.substr(0, i), num.substr(i, j), num.substr(i + j))) { // adding first and second number at // front of result list res.push_front(num.substr(i, j)); res.push_front(num.substr(0, i)); return res; } } } // If code execution reaches here, then string // doesn't have any additive sequence res.clear(); return res;} // Method to print result listvoid printResult(list<string> res){ for (auto it = res.begin(); it != res.end(); it++) cout << *it << \" \"; cout << endl;} // Driver code to test above methodsint main(){ string num = \"235813\"; list<string> res = additiveSequence(num); printResult(res); num = \"199100199\"; res = additiveSequence(num); printResult(res); return 0;}", "e": 4677, "s": 1409, "text": null }, { "code": null, "e": 4704, "s": 4677, "text": "2 3 5 8 13 \n1 99 100 199 \n" }, { "code": null, "e": 5003, "s": 4704, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5016, "s": 5003, "text": "simmytarika5" }, { "code": null, "e": 5033, "s": 5016, "text": "hardikkoriintern" }, { "code": null, "e": 5043, "s": 5033, "text": "Recursion" }, { "code": null, "e": 5051, "s": 5043, "text": "Strings" }, { "code": null, "e": 5059, "s": 5051, "text": "Strings" }, { "code": null, "e": 5069, "s": 5059, "text": "Recursion" }, { "code": null, "e": 5167, "s": 5069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5195, "s": 5167, "text": "Backtracking | Introduction" }, { "code": null, "e": 5230, "s": 5195, "text": "Print all subsequences of a string" }, { "code": null, "e": 5273, "s": 5230, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 5305, "s": 5273, "text": "Reverse a stack using recursion" }, { "code": null, "e": 5351, "s": 5305, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 5397, "s": 5351, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 5422, "s": 5397, "text": "Reverse a string in Java" }, { "code": null, "e": 5437, "s": 5422, "text": "C++ Data Types" }, { "code": null, "e": 5482, "s": 5437, "text": "Different Methods to Reverse a String in C++" } ]
Sum of subsets of all the subsets of an array | O(N)
22 Jun, 2022 Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 d) {1, 1} : 4 All the possible subsets of this subset will be {}, {1}, {1} and {1, 1}, Sum = 0 + 1 + 1 + 2 = 4 Thus, ans = 0 + 1 + 1 + 4 = 6Input: arr[] = {1, 4, 2, 12} Output: 513 Approach: In this article, an approach with O(N) time complexity to solve the given problem will be discussed. The key is observing the number of times an element will repeat in all the subsets.Let’s magnify the view. It is known that every element will appear 2(N – 1) times in the sum of subsets. Now, let’s magnify the view even further and see how the count varies with the subset size.There are N – 1CK – 1 subsets of size K for every index that include it. Contribution of an element for a subset of size K will be equal to 2(K – 1) times its value. Thus, total contribution of an element for all the subsets of length K will be equal to N – 1CK – 1 * 2(K – 1) Total contribution among all the subsets will be equal to: N – 1CN – 1 * 2(N – 1) + N – 1CN – 2 * 2(N – 2 + N – 1CN – 3 * 2(N – 3) + ... + N – 1C0 * 20. Now, the contribution of each element in the final answer is known. So, multiply it to the sum of all the elements of the array which will give the required answer.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define maxN 10 // To store factorial valuesint fact[maxN]; // Function to return ncrint ncr(int n, int r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumint findSum(int* arr, int n){ // Initialising factorial fact[0] = 1; for (int i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier int mul = 0; // Finding the value of multipler // according to the formula for (int i = 0; i <= n - 1; i++) mul += (int)pow(2, i) * ncr(n - 1, i); // To store the final answer int ans = 0; // Calculate the final answer for (int i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver codeint main(){ int arr[] = { 1, 1 }; int n = sizeof(arr) / sizeof(int); cout << findSum(arr, n); return 0;} // Java implementation of the approachclass GFG{static int maxN = 10; // To store factorial valuesstatic int []fact = new int[maxN]; // Function to return ncrstatic int ncr(int n, int r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumstatic int findSum(int[] arr, int n){ // Initialising factorial fact[0] = 1; for (int i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier int mul = 0; // Finding the value of multipler // according to the formula for (int i = 0; i <= n - 1; i++) mul += (int)Math.pow(2, i) * ncr(n - 1, i); // To store the final answer int ans = 0; // Calculate the final answer for (int i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver codepublic static void main(String []args){ int arr[] = { 1, 1 }; int n = arr.length; System.out.println(findSum(arr, n));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approachmaxN = 10 # To store factorial valuesfact = [0]*maxN; # Function to return ncrdef ncr(n, r) : return (fact[n] // fact[r]) // fact[n - r]; # Function to return the required sumdef findSum(arr, n) : # Initialising factorial fact[0] = 1; for i in range(1, n) : fact[i] = i * fact[i - 1]; # Multiplier mul = 0; # Finding the value of multipler # according to the formula for i in range(n) : mul += (2 ** i) * ncr(n - 1, i); # To store the final answer ans = 0; # Calculate the final answer for i in range(n) : ans += mul * arr[i]; return ans; # Driver codeif __name__ == "__main__" : arr = [ 1, 1 ]; n = len(arr); print(findSum(arr, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{static int maxN = 10; // To store factorial valuesstatic int []fact = new int[maxN]; // Function to return ncrstatic int ncr(int n, int r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumstatic int findSum(int[] arr, int n){ // Initialising factorial fact[0] = 1; for (int i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier int mul = 0; // Finding the value of multipler // according to the formula for (int i = 0; i <= n - 1; i++) mul += (int)Math.Pow(2, i) * ncr(n - 1, i); // To store the final answer int ans = 0; // Calculate the final answer for (int i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver codepublic static void Main(String []args){ int []arr = { 1, 1 }; int n = arr.Length; Console.WriteLine(findSum(arr, n));}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // To store factorial valueslet fact = new Array(10); // Function to return ncrfunction ncr(n, r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumfunction findSum(arr, n){ // Initialising factorial fact[0] = 1; for (let i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier let mul = 0; // Finding the value of multipler // according to the formula for (let i = 0; i <= n - 1; i++) mul += Math.pow(2, i) * ncr(n - 1, i); // To store the final answer let ans = 0; // Calculate the final answer for (let i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver code let arr = [ 1, 1 ]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by Mayank Tyagi </script> 6 Time Complexity : O(Nlogn) ,where N is the number of elements in an array. Space Complexity : O(N) ,to store the factorial of numbers from 1 to N ankthon Rajput-Ji 29AjayKumar mayanktyagi1709 sagartomar9927 adityapatil12 subset Arrays Backtracking Combinatorial Arrays subset Combinatorial Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) N Queen Problem | Backtracking-3 The Knight's tour problem | Backtracking-1 Rat in a Maze | Backtracking-2 Backtracking | Introduction
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 177, "s": 52, "text": "Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: " }, { "code": null, "e": 658, "s": 177, "text": "Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 d) {1, 1} : 4 All the possible subsets of this subset will be {}, {1}, {1} and {1, 1}, Sum = 0 + 1 + 1 + 2 = 4 Thus, ans = 0 + 1 + 1 + 4 = 6Input: arr[] = {1, 4, 2, 12} Output: 513 " }, { "code": null, "e": 1388, "s": 660, "text": "Approach: In this article, an approach with O(N) time complexity to solve the given problem will be discussed. The key is observing the number of times an element will repeat in all the subsets.Let’s magnify the view. It is known that every element will appear 2(N – 1) times in the sum of subsets. Now, let’s magnify the view even further and see how the count varies with the subset size.There are N – 1CK – 1 subsets of size K for every index that include it. Contribution of an element for a subset of size K will be equal to 2(K – 1) times its value. Thus, total contribution of an element for all the subsets of length K will be equal to N – 1CK – 1 * 2(K – 1) Total contribution among all the subsets will be equal to: " }, { "code": null, "e": 1484, "s": 1388, "text": "N – 1CN – 1 * 2(N – 1) + N – 1CN – 2 * 2(N – 2 + N – 1CN – 3 * 2(N – 3) + ... + N – 1C0 * 20. " }, { "code": null, "e": 1701, "s": 1484, "text": "Now, the contribution of each element in the final answer is known. So, multiply it to the sum of all the elements of the array which will give the required answer.Below is the implementation of the above approach: " }, { "code": null, "e": 1705, "s": 1701, "text": "C++" }, { "code": null, "e": 1710, "s": 1705, "text": "Java" }, { "code": null, "e": 1718, "s": 1710, "text": "Python3" }, { "code": null, "e": 1721, "s": 1718, "text": "C#" }, { "code": null, "e": 1732, "s": 1721, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define maxN 10 // To store factorial valuesint fact[maxN]; // Function to return ncrint ncr(int n, int r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumint findSum(int* arr, int n){ // Initialising factorial fact[0] = 1; for (int i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier int mul = 0; // Finding the value of multipler // according to the formula for (int i = 0; i <= n - 1; i++) mul += (int)pow(2, i) * ncr(n - 1, i); // To store the final answer int ans = 0; // Calculate the final answer for (int i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver codeint main(){ int arr[] = { 1, 1 }; int n = sizeof(arr) / sizeof(int); cout << findSum(arr, n); return 0;}", "e": 2622, "s": 1732, "text": null }, { "code": "// Java implementation of the approachclass GFG{static int maxN = 10; // To store factorial valuesstatic int []fact = new int[maxN]; // Function to return ncrstatic int ncr(int n, int r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumstatic int findSum(int[] arr, int n){ // Initialising factorial fact[0] = 1; for (int i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier int mul = 0; // Finding the value of multipler // according to the formula for (int i = 0; i <= n - 1; i++) mul += (int)Math.pow(2, i) * ncr(n - 1, i); // To store the final answer int ans = 0; // Calculate the final answer for (int i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver codepublic static void main(String []args){ int arr[] = { 1, 1 }; int n = arr.length; System.out.println(findSum(arr, n));}} // This code is contributed by Rajput-Ji", "e": 3577, "s": 2622, "text": null }, { "code": "# Python3 implementation of the approachmaxN = 10 # To store factorial valuesfact = [0]*maxN; # Function to return ncrdef ncr(n, r) : return (fact[n] // fact[r]) // fact[n - r]; # Function to return the required sumdef findSum(arr, n) : # Initialising factorial fact[0] = 1; for i in range(1, n) : fact[i] = i * fact[i - 1]; # Multiplier mul = 0; # Finding the value of multipler # according to the formula for i in range(n) : mul += (2 ** i) * ncr(n - 1, i); # To store the final answer ans = 0; # Calculate the final answer for i in range(n) : ans += mul * arr[i]; return ans; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 1 ]; n = len(arr); print(findSum(arr, n)); # This code is contributed by AnkitRai01", "e": 4373, "s": 3577, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int maxN = 10; // To store factorial valuesstatic int []fact = new int[maxN]; // Function to return ncrstatic int ncr(int n, int r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumstatic int findSum(int[] arr, int n){ // Initialising factorial fact[0] = 1; for (int i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier int mul = 0; // Finding the value of multipler // according to the formula for (int i = 0; i <= n - 1; i++) mul += (int)Math.Pow(2, i) * ncr(n - 1, i); // To store the final answer int ans = 0; // Calculate the final answer for (int i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver codepublic static void Main(String []args){ int []arr = { 1, 1 }; int n = arr.Length; Console.WriteLine(findSum(arr, n));}} // This code is contributed by 29AjayKumar", "e": 5345, "s": 4373, "text": null }, { "code": "<script> // JavaScript implementation of the approach // To store factorial valueslet fact = new Array(10); // Function to return ncrfunction ncr(n, r){ return (fact[n] / fact[r]) / fact[n - r];} // Function to return the required sumfunction findSum(arr, n){ // Initialising factorial fact[0] = 1; for (let i = 1; i < n; i++) fact[i] = i * fact[i - 1]; // Multiplier let mul = 0; // Finding the value of multipler // according to the formula for (let i = 0; i <= n - 1; i++) mul += Math.pow(2, i) * ncr(n - 1, i); // To store the final answer let ans = 0; // Calculate the final answer for (let i = 0; i < n; i++) ans += mul * arr[i]; return ans;} // Driver code let arr = [ 1, 1 ]; let n = arr.length; document.write(findSum(arr, n)); // This code is contributed by Mayank Tyagi </script>", "e": 6216, "s": 5345, "text": null }, { "code": null, "e": 6218, "s": 6216, "text": "6" }, { "code": null, "e": 6295, "s": 6220, "text": "Time Complexity : O(Nlogn) ,where N is the number of elements in an array." }, { "code": null, "e": 6366, "s": 6295, "text": "Space Complexity : O(N) ,to store the factorial of numbers from 1 to N" }, { "code": null, "e": 6374, "s": 6366, "text": "ankthon" }, { "code": null, "e": 6384, "s": 6374, "text": "Rajput-Ji" }, { "code": null, "e": 6396, "s": 6384, "text": "29AjayKumar" }, { "code": null, "e": 6412, "s": 6396, "text": "mayanktyagi1709" }, { "code": null, "e": 6427, "s": 6412, "text": "sagartomar9927" }, { "code": null, "e": 6441, "s": 6427, "text": "adityapatil12" }, { "code": null, "e": 6448, "s": 6441, "text": "subset" }, { "code": null, "e": 6455, "s": 6448, "text": "Arrays" }, { "code": null, "e": 6468, "s": 6455, "text": "Backtracking" }, { "code": null, "e": 6482, "s": 6468, "text": "Combinatorial" }, { "code": null, "e": 6489, "s": 6482, "text": "Arrays" }, { "code": null, "e": 6496, "s": 6489, "text": "subset" }, { "code": null, "e": 6510, "s": 6496, "text": "Combinatorial" }, { "code": null, "e": 6523, "s": 6510, "text": "Backtracking" }, { "code": null, "e": 6621, "s": 6523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6689, "s": 6621, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6733, "s": 6689, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 6765, "s": 6733, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6813, "s": 6765, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 6827, "s": 6813, "text": "Linear Search" }, { "code": null, "e": 6912, "s": 6827, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 6945, "s": 6912, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 6988, "s": 6945, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7019, "s": 6988, "text": "Rat in a Maze | Backtracking-2" } ]
Screen Mirroring of Android Smartphone using Raspberry Pi
17 Jan, 2022 Raspberry Pi consists series of small single-board computers. It was developed in the United Kingdom by the Raspberry Pi foundation in association with Broadcom. The first Raspberry Pi model was launched in 2012 and by the time it became popular because of its wide applications in many fields like many used Raspberry Pi to learn programming skills, build hardware projects, do home automation, and even use them in industrial applications. Raspberry Pi is a very cheap computer that runs Linux but also provides a set of GPIO(general purpose input/output)pins that allow you to control electronic components for physical computing and explore the internet of things(IoT). Here is the list of different models of Raspberry Pi: Cortex-A72 (ARM v8) 64-bit 1 GB,2 GB, 4 GB(LPDDR4) Cortex-A72 (ARM v8) 64-bit Cortex-A72 (ARM v8) 64-bit RP2040 dual-core Arm Cortex-M0+ Now, let’s move to our project based on the screen mirroring of an android phone with the help of Raspberry Pi. Screen Mirroring or casting allows you to mirror your mobile device content to your TV screen. One needs at least Raspberry Pi 2 model for mirroring your mobile device to your tv screen. Raspberry Pi 2(or above model, excluding Pi Pico) HDMI cableMouseKeyboardSD card(8GB at least)Data Cable(Depending upon your smartphone charging port)Output Screen(TV screen, Computer screen or any other screen) HDMI cable Mouse Keyboard SD card(8GB at least) Data Cable(Depending upon your smartphone charging port) Output Screen(TV screen, Computer screen or any other screen) Before moving forward, one should install Raspberry Pi OS(previously called Raspbian) an official supported operating system for Raspberry Pi. So, now here are connections one should make before moving further: Connect one end of the HDMI cable to the output screen and the other to Raspberry Pi.Connect mouse and keyboard to the Raspberry Pi ports.For internet connection connect with an Ethernet cable or with WiFi.For providing power to Raspberry Pi connect it with a type-C or type-B data cable(depending upon the Raspberry Pi model). Connect one end of the HDMI cable to the output screen and the other to Raspberry Pi. Connect mouse and keyboard to the Raspberry Pi ports. For internet connection connect with an Ethernet cable or with WiFi. For providing power to Raspberry Pi connect it with a type-C or type-B data cable(depending upon the Raspberry Pi model). Now it begins, after installing OS and making connections follow the given below steps carefully: For installing scrcpy we have to install PiKiss on our Raspberry Pi. Step 1: Open terminal(Ctrl+Alt+T) on Raspberry Pi and type the following command and hit enter: $ curl -sSL https://git.io/JfAPE | bash Step 2: Open File Explorer->Pi(folder)->PiKiss. Under PiKiss Folder go-to tools and on top click on ‘Open Current Folder in Terminal’. Step 3: Check if new scripts are available on remote and update them automatically, but If you want to get the latest version manually, just enter into the directory with cd PiKISS and use the below command: $ git pull Step 4: Open the drop-down menu and click on ‘System Tools followed by Open PiKISS. Step 5: The given window will pop up and scroll down to select scrcpy and press enter. Step 6: Again open the drop-down menu and click on System tools followed by scrcpy. Step 7: Now, connect the android smartphone to raspberry pi and enable the developer option on your android smartphone by tapping 4-7 times on your android smartphones’ build number(If you are unable to enable the developer option, then search how to enable developer option for any particular device. After getting on developer option,enable USB debugging on android smartphone. (Click ‘OK’ on popup message if it displays on after enabling USB debugging). On connecting your android smartphone to Raspberry Pi, it will show the ‘USB Debugging’ popup window, click on ‘Allow‘. Step 8: At last, again enable scrcpy by simply click on Scrcpy under System Tools. It will mirror your android device on your output screen. simmytarika5 Android TechTips Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jan, 2022" }, { "code": null, "e": 494, "s": 52, "text": "Raspberry Pi consists series of small single-board computers. It was developed in the United Kingdom by the Raspberry Pi foundation in association with Broadcom. The first Raspberry Pi model was launched in 2012 and by the time it became popular because of its wide applications in many fields like many used Raspberry Pi to learn programming skills, build hardware projects, do home automation, and even use them in industrial applications." }, { "code": null, "e": 726, "s": 494, "text": "Raspberry Pi is a very cheap computer that runs Linux but also provides a set of GPIO(general purpose input/output)pins that allow you to control electronic components for physical computing and explore the internet of things(IoT)." }, { "code": null, "e": 780, "s": 726, "text": "Here is the list of different models of Raspberry Pi:" }, { "code": null, "e": 801, "s": 780, "text": "Cortex-A72 (ARM v8) " }, { "code": null, "e": 808, "s": 801, "text": "64-bit" }, { "code": null, "e": 819, "s": 808, "text": "1 GB,2 GB," }, { "code": null, "e": 832, "s": 819, "text": "4 GB(LPDDR4)" }, { "code": null, "e": 852, "s": 832, "text": "Cortex-A72 (ARM v8)" }, { "code": null, "e": 860, "s": 852, "text": " 64-bit" }, { "code": null, "e": 881, "s": 860, "text": "Cortex-A72 (ARM v8) " }, { "code": null, "e": 888, "s": 881, "text": "64-bit" }, { "code": null, "e": 905, "s": 888, "text": "RP2040 dual-core" }, { "code": null, "e": 921, "s": 905, "text": " Arm Cortex-M0+" }, { "code": null, "e": 1033, "s": 921, "text": "Now, let’s move to our project based on the screen mirroring of an android phone with the help of Raspberry Pi." }, { "code": null, "e": 1220, "s": 1033, "text": "Screen Mirroring or casting allows you to mirror your mobile device content to your TV screen. One needs at least Raspberry Pi 2 model for mirroring your mobile device to your tv screen." }, { "code": null, "e": 1270, "s": 1220, "text": "Raspberry Pi 2(or above model, excluding Pi Pico)" }, { "code": null, "e": 1432, "s": 1270, "text": "HDMI cableMouseKeyboardSD card(8GB at least)Data Cable(Depending upon your smartphone charging port)Output Screen(TV screen, Computer screen or any other screen)" }, { "code": null, "e": 1443, "s": 1432, "text": "HDMI cable" }, { "code": null, "e": 1449, "s": 1443, "text": "Mouse" }, { "code": null, "e": 1458, "s": 1449, "text": "Keyboard" }, { "code": null, "e": 1480, "s": 1458, "text": "SD card(8GB at least)" }, { "code": null, "e": 1537, "s": 1480, "text": "Data Cable(Depending upon your smartphone charging port)" }, { "code": null, "e": 1599, "s": 1537, "text": "Output Screen(TV screen, Computer screen or any other screen)" }, { "code": null, "e": 1742, "s": 1599, "text": "Before moving forward, one should install Raspberry Pi OS(previously called Raspbian) an official supported operating system for Raspberry Pi." }, { "code": null, "e": 1810, "s": 1742, "text": "So, now here are connections one should make before moving further:" }, { "code": null, "e": 2138, "s": 1810, "text": "Connect one end of the HDMI cable to the output screen and the other to Raspberry Pi.Connect mouse and keyboard to the Raspberry Pi ports.For internet connection connect with an Ethernet cable or with WiFi.For providing power to Raspberry Pi connect it with a type-C or type-B data cable(depending upon the Raspberry Pi model)." }, { "code": null, "e": 2224, "s": 2138, "text": "Connect one end of the HDMI cable to the output screen and the other to Raspberry Pi." }, { "code": null, "e": 2278, "s": 2224, "text": "Connect mouse and keyboard to the Raspberry Pi ports." }, { "code": null, "e": 2347, "s": 2278, "text": "For internet connection connect with an Ethernet cable or with WiFi." }, { "code": null, "e": 2469, "s": 2347, "text": "For providing power to Raspberry Pi connect it with a type-C or type-B data cable(depending upon the Raspberry Pi model)." }, { "code": null, "e": 2567, "s": 2469, "text": "Now it begins, after installing OS and making connections follow the given below steps carefully:" }, { "code": null, "e": 2636, "s": 2567, "text": "For installing scrcpy we have to install PiKiss on our Raspberry Pi." }, { "code": null, "e": 2732, "s": 2636, "text": "Step 1: Open terminal(Ctrl+Alt+T) on Raspberry Pi and type the following command and hit enter:" }, { "code": null, "e": 2773, "s": 2732, "text": " $ curl -sSL https://git.io/JfAPE | bash" }, { "code": null, "e": 2915, "s": 2780, "text": "Step 2: Open File Explorer->Pi(folder)->PiKiss. Under PiKiss Folder go-to tools and on top click on ‘Open Current Folder in Terminal’." }, { "code": null, "e": 3124, "s": 2915, "text": "Step 3: Check if new scripts are available on remote and update them automatically, but If you want to get the latest version manually, just enter into the directory with cd PiKISS and use the below command: " }, { "code": null, "e": 3135, "s": 3124, "text": "$ git pull" }, { "code": null, "e": 3219, "s": 3135, "text": "Step 4: Open the drop-down menu and click on ‘System Tools followed by Open PiKISS." }, { "code": null, "e": 3306, "s": 3219, "text": "Step 5: The given window will pop up and scroll down to select scrcpy and press enter." }, { "code": null, "e": 3390, "s": 3306, "text": "Step 6: Again open the drop-down menu and click on System tools followed by scrcpy." }, { "code": null, "e": 3968, "s": 3390, "text": "Step 7: Now, connect the android smartphone to raspberry pi and enable the developer option on your android smartphone by tapping 4-7 times on your android smartphones’ build number(If you are unable to enable the developer option, then search how to enable developer option for any particular device. After getting on developer option,enable USB debugging on android smartphone. (Click ‘OK’ on popup message if it displays on after enabling USB debugging). On connecting your android smartphone to Raspberry Pi, it will show the ‘USB Debugging’ popup window, click on ‘Allow‘." }, { "code": null, "e": 4051, "s": 3968, "text": "Step 8: At last, again enable scrcpy by simply click on Scrcpy under System Tools." }, { "code": null, "e": 4109, "s": 4051, "text": "It will mirror your android device on your output screen." }, { "code": null, "e": 4122, "s": 4109, "text": "simmytarika5" }, { "code": null, "e": 4130, "s": 4122, "text": "Android" }, { "code": null, "e": 4139, "s": 4130, "text": "TechTips" }, { "code": null, "e": 4147, "s": 4139, "text": "Android" }, { "code": null, "e": 4245, "s": 4147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4314, "s": 4245, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 4346, "s": 4314, "text": "Android SDK and it's Components" }, { "code": null, "e": 4395, "s": 4346, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 4434, "s": 4395, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4476, "s": 4434, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 4529, "s": 4476, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 4555, "s": 4529, "text": "Docker - COPY Instruction" }, { "code": null, "e": 4590, "s": 4555, "text": "Setting up the environment in Java" }, { "code": null, "e": 4631, "s": 4590, "text": "How to Run a Python Script using Docker?" } ]
numpy.sum() in Python
03 Apr, 2020 numpy.sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis. Parameters :arr : input array.axis : axis along which we want to calculate the sum value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : Different array in which we want to place the result. The array must have same dimensions as expected output. Default is None.initial : [scalar, optional] Starting value of the sum. Return : Sum of the array elements (a scalar value if axis is none) or array with sum values along the specified axis. Code #1: # Python Program illustrating # numpy.sum() methodimport numpy as np # 1D array arr = [20, 2, .2, 10, 4] print("\nSum of arr : ", np.sum(arr)) print("Sum of arr(uint8) : ", np.sum(arr, dtype = np.uint8)) print("Sum of arr(float32) : ", np.sum(arr, dtype = np.float32)) print ("\nIs np.sum(arr).dtype == np.uint : ", np.sum(arr).dtype == np.uint) print ("Is np.sum(arr).dtype == np.float : ", np.sum(arr).dtype == np.float) Output: Sum of arr : 36.2 Sum of arr(uint8) : 36 Sum of arr(float32) : 36.2 Is np.sum(arr).dtype == np.uint : False Is np.sum(arr).dtype == np.uint : True Code #2: # Python Program illustrating # numpy.sum() methodimport numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]] print("\nSum of arr : ", np.sum(arr)) print("Sum of arr(uint8) : ", np.sum(arr, dtype = np.uint8)) print("Sum of arr(float32) : ", np.sum(arr, dtype = np.float32)) print ("\nIs np.sum(arr).dtype == np.uint : ", np.sum(arr).dtype == np.uint) print ("Is np.sum(arr).dtype == np.uint : ", np.sum(arr).dtype == np.float) Output: Sum of arr : 279 Sum of arr(uint8) : 23 Sum of arr(float32) : 279.0 Is np.sum(arr).dtype == np.uint : False Is np.sum(arr).dtype == np.uint : False Code #3: # Python Program illustrating # numpy.sum() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]] print("\nSum of arr : ", np.sum(arr)) print("Sum of arr(axis = 0) : ", np.sum(arr, axis = 0)) print("Sum of arr(axis = 1) : ", np.sum(arr, axis = 1)) print("\nSum of arr (keepdimension is True): \n", np.sum(arr, axis = 1, keepdims = True)) Output: Sum of arr : 279 Sum of arr(axis = 0) : [52 25 93 42 67] Sum of arr(axis = 1) : [120 75 84] Sum of arr (keepdimension is True): [[120] [ 75] [ 84]] HenryMoore Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Apr, 2020" }, { "code": null, "e": 136, "s": 28, "text": "numpy.sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis." }, { "code": null, "e": 559, "s": 136, "text": "Parameters :arr : input array.axis : axis along which we want to calculate the sum value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : Different array in which we want to place the result. The array must have same dimensions as expected output. Default is None.initial : [scalar, optional] Starting value of the sum." }, { "code": null, "e": 678, "s": 559, "text": "Return : Sum of the array elements (a scalar value if axis is none) or array with sum values along the specified axis." }, { "code": null, "e": 687, "s": 678, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.sum() methodimport numpy as np # 1D array arr = [20, 2, .2, 10, 4] print(\"\\nSum of arr : \", np.sum(arr)) print(\"Sum of arr(uint8) : \", np.sum(arr, dtype = np.uint8)) print(\"Sum of arr(float32) : \", np.sum(arr, dtype = np.float32)) print (\"\\nIs np.sum(arr).dtype == np.uint : \", np.sum(arr).dtype == np.uint) print (\"Is np.sum(arr).dtype == np.float : \", np.sum(arr).dtype == np.float) ", "e": 1143, "s": 687, "text": null }, { "code": null, "e": 1151, "s": 1143, "text": "Output:" }, { "code": null, "e": 1305, "s": 1151, "text": "Sum of arr : 36.2\nSum of arr(uint8) : 36\nSum of arr(float32) : 36.2\n\nIs np.sum(arr).dtype == np.uint : False\nIs np.sum(arr).dtype == np.uint : True\n" }, { "code": null, "e": 1315, "s": 1305, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.sum() methodimport numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]] print(\"\\nSum of arr : \", np.sum(arr)) print(\"Sum of arr(uint8) : \", np.sum(arr, dtype = np.uint8)) print(\"Sum of arr(float32) : \", np.sum(arr, dtype = np.float32)) print (\"\\nIs np.sum(arr).dtype == np.uint : \", np.sum(arr).dtype == np.uint) print (\"Is np.sum(arr).dtype == np.uint : \", np.sum(arr).dtype == np.float) ", "e": 1848, "s": 1315, "text": null }, { "code": null, "e": 1856, "s": 1848, "text": "Output:" }, { "code": null, "e": 2011, "s": 1856, "text": "Sum of arr : 279\nSum of arr(uint8) : 23\nSum of arr(float32) : 279.0\n\nIs np.sum(arr).dtype == np.uint : False\nIs np.sum(arr).dtype == np.uint : False\n" }, { "code": null, "e": 2021, "s": 2011, "text": " Code #3:" }, { "code": "# Python Program illustrating # numpy.sum() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]] print(\"\\nSum of arr : \", np.sum(arr)) print(\"Sum of arr(axis = 0) : \", np.sum(arr, axis = 0)) print(\"Sum of arr(axis = 1) : \", np.sum(arr, axis = 1)) print(\"\\nSum of arr (keepdimension is True): \\n\", np.sum(arr, axis = 1, keepdims = True))", "e": 2453, "s": 2021, "text": null }, { "code": null, "e": 2461, "s": 2453, "text": "Output:" }, { "code": null, "e": 2619, "s": 2461, "text": "Sum of arr : 279\nSum of arr(axis = 0) : [52 25 93 42 67]\nSum of arr(axis = 1) : [120 75 84]\n\nSum of arr (keepdimension is True): \n [[120]\n [ 75]\n [ 84]]" }, { "code": null, "e": 2630, "s": 2619, "text": "HenryMoore" }, { "code": null, "e": 2665, "s": 2630, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 2678, "s": 2665, "text": "Python-numpy" }, { "code": null, "e": 2685, "s": 2678, "text": "Python" }, { "code": null, "e": 2783, "s": 2685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2801, "s": 2783, "text": "Python Dictionary" }, { "code": null, "e": 2843, "s": 2801, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2865, "s": 2843, "text": "Enumerate() in Python" }, { "code": null, "e": 2900, "s": 2865, "text": "Read a file line by line in Python" }, { "code": null, "e": 2926, "s": 2900, "text": "Python String | replace()" }, { "code": null, "e": 2958, "s": 2926, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2987, "s": 2958, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3014, "s": 2987, "text": "Python Classes and Objects" }, { "code": null, "e": 3044, "s": 3014, "text": "Iterate over a list in Python" } ]
Number of square matrices with all 1s
26 Apr, 2021 Given an N*M matrix containing only 0s and 1s, the task is to count the number of square submatrices containing all 1s.Examples: Input: arr[][] = {{0, 1, 1, 1}, {1, 1, 1, 1}, {0, 1, 1, 1}} Output: 15 Explanation: There are 10 squares of side length 1. There are 4 squares of side length 2. There is 1 square of side length 3. Total number of squares = 10 + 4 + 1 = 15.Input: arr[][] = {{1, 0, 1}, {1, 1, 0}, {1, 1, 0}} Output: 7 Approach: This problem can be solved using Dynamic Programming. Let the array arr[i][j] store the number of square matrices ending at (i, j)The recurrence relation to find the number of squares ending at (i, j) can be given by:If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1Else if arr[i][j] is 0: arr[i][j] = 0Calculate the sum of the array which is equal to the number of square submatrices with all 1s. Let the array arr[i][j] store the number of square matrices ending at (i, j) The recurrence relation to find the number of squares ending at (i, j) can be given by:If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1Else if arr[i][j] is 0: arr[i][j] = 0 If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1 arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1 Else if arr[i][j] is 0: arr[i][j] = 0 arr[i][j] = 0 Calculate the sum of the array which is equal to the number of square submatrices with all 1s. Below is the implementation of the above approach: CPP Java Python C# Javascript // C++ program to return the number of// square submatrices with all 1s#include <bits/stdc++.h>using namespace std; #define n 3#define m 3 // Function to return the number of// square submatrices with all 1sint countSquareMatrices(int a[][m], int N, int M){ // Initialize count variable int count = 0; for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i][j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i][j] = min(min(a[i - 1][j], a[i][j - 1]), a[i - 1][j - 1]) + 1; } } // Calculate the sum of the array for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) count += a[i][j]; return count;} // Driver codeint main(){ int arr[][m] = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } }; cout << countSquareMatrices(arr, n, m); return 0;} // Java program to return the number of// square submatrices with all 1sclass GFG{ final static int n = 3; final static int m = 3; // Function to return the number of // square submatrices with all 1s static int countSquareMatrices(int a[][], int N, int M) { // Initialize count variable int count = 0; for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i][j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i][j] = Math.min(Math.min(a[i - 1][j], a[i][j - 1]), a[i - 1][j - 1]) + 1; } } // Calculate the sum of the array for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) count += a[i][j]; return count; } // Driver code public static void main (String[] args) { int arr[][] = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } }; System.out.println(countSquareMatrices(arr, n, m)); }} // This code is contributed by AnkitRai01 # Python3 program to return the number of# square submatrices with all 1sn = 3m = 3 # Function to return the number of# square submatrices with all 1sdef countSquareMatrices(a, N, M): # Initialize count variable count = 0 for i in range(1, N): for j in range(1, M): # If a[i][j] is equal to 0 if (a[i][j] == 0): continue # Calculate number of # square submatrices # ending at (i, j) a[i][j] = min([a[i - 1][j], a[i][j - 1], a[i - 1][j - 1]])+1 # Calculate the sum of the array for i in range(N): for j in range(M): count += a[i][j] return count # Driver code arr = [ [ 1, 0, 1], [ 1, 1, 0 ], [ 1, 1, 0 ] ] print(countSquareMatrices(arr, n, m)) # This code is contributed by mohit kumar 29 // C# program to return the number of// square submatrices with all 1susing System; class GFG{ static int n = 3; static int m = 3; // Function to return the number of // square submatrices with all 1s static int countSquareMatrices(int [,]a, int N, int M) { // Initialize count variable int count = 0; for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i, j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i, j] = Math.Min(Math.Min(a[i - 1, j], a[i, j - 1]), a[i - 1, j - 1]) + 1; } } // Calculate the sum of the array for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) count += a[i, j]; return count; } // Driver code public static void Main() { int [,]arr = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } }; Console.WriteLine(countSquareMatrices(arr, n, m)); }} // This code is contributed by AnkitRai01 <script> // Javascript program to return the number of// square submatrices with all 1s var n = 3var m = 3 // Function to return the number of// square submatrices with all 1sfunction countSquareMatrices(a, N, M){ // Initialize count variable var count = 0; for (var i = 1; i < N; i++) { for (var j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i][j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i][j] = Math.min(Math.min(a[i - 1][j], a[i][j - 1]), a[i - 1][j - 1]) + 1; } } // Calculate the sum of the array for (var i = 0; i < N; i++) for (var j = 0; j < M; j++) count += a[i][j]; return count;} // Driver codevar arr = [ [ 1, 0, 1 ], [ 1, 1, 0 ], [ 1, 1, 0 ] ];document.write( countSquareMatrices(arr, n, m)); </script> Output : 7 Time Complexity: O(N*M)Auxiliary Space: O(1) mohit kumar 29 ankthon subhammahato348 rutvik_56 Dynamic Programming Matrix Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Count number of binary strings without consecutive 1's Find if a string is interleaved of two other strings | DP-33 Optimal Substructure Property in Dynamic Programming | DP-2 Maximum sum such that no two elements are adjacent Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 The Celebrity Problem
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Apr, 2021" }, { "code": null, "e": 182, "s": 52, "text": "Given an N*M matrix containing only 0s and 1s, the task is to count the number of square submatrices containing all 1s.Examples: " }, { "code": null, "e": 483, "s": 182, "text": "Input: arr[][] = {{0, 1, 1, 1}, {1, 1, 1, 1}, {0, 1, 1, 1}} Output: 15 Explanation: There are 10 squares of side length 1. There are 4 squares of side length 2. There is 1 square of side length 3. Total number of squares = 10 + 4 + 1 = 15.Input: arr[][] = {{1, 0, 1}, {1, 1, 0}, {1, 1, 0}} Output: 7 " }, { "code": null, "e": 549, "s": 483, "text": "Approach: This problem can be solved using Dynamic Programming. " }, { "code": null, "e": 928, "s": 549, "text": "Let the array arr[i][j] store the number of square matrices ending at (i, j)The recurrence relation to find the number of squares ending at (i, j) can be given by:If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1Else if arr[i][j] is 0: arr[i][j] = 0Calculate the sum of the array which is equal to the number of square submatrices with all 1s." }, { "code": null, "e": 1005, "s": 928, "text": "Let the array arr[i][j] store the number of square matrices ending at (i, j)" }, { "code": null, "e": 1214, "s": 1005, "text": "The recurrence relation to find the number of squares ending at (i, j) can be given by:If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1Else if arr[i][j] is 0: arr[i][j] = 0" }, { "code": null, "e": 1299, "s": 1214, "text": "If arr[i][j] is 1:arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1" }, { "code": null, "e": 1366, "s": 1299, "text": "arr[i][j] = min( min(arr[i-1][j], arr[i][j-1]), arr[i-1][j-1]) + 1" }, { "code": null, "e": 1404, "s": 1366, "text": "Else if arr[i][j] is 0: arr[i][j] = 0" }, { "code": null, "e": 1418, "s": 1404, "text": "arr[i][j] = 0" }, { "code": null, "e": 1513, "s": 1418, "text": "Calculate the sum of the array which is equal to the number of square submatrices with all 1s." }, { "code": null, "e": 1566, "s": 1513, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1570, "s": 1566, "text": "CPP" }, { "code": null, "e": 1575, "s": 1570, "text": "Java" }, { "code": null, "e": 1582, "s": 1575, "text": "Python" }, { "code": null, "e": 1585, "s": 1582, "text": "C#" }, { "code": null, "e": 1596, "s": 1585, "text": "Javascript" }, { "code": "// C++ program to return the number of// square submatrices with all 1s#include <bits/stdc++.h>using namespace std; #define n 3#define m 3 // Function to return the number of// square submatrices with all 1sint countSquareMatrices(int a[][m], int N, int M){ // Initialize count variable int count = 0; for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i][j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i][j] = min(min(a[i - 1][j], a[i][j - 1]), a[i - 1][j - 1]) + 1; } } // Calculate the sum of the array for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) count += a[i][j]; return count;} // Driver codeint main(){ int arr[][m] = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } }; cout << countSquareMatrices(arr, n, m); return 0;}", "e": 2695, "s": 1596, "text": null }, { "code": "// Java program to return the number of// square submatrices with all 1sclass GFG{ final static int n = 3; final static int m = 3; // Function to return the number of // square submatrices with all 1s static int countSquareMatrices(int a[][], int N, int M) { // Initialize count variable int count = 0; for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i][j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i][j] = Math.min(Math.min(a[i - 1][j], a[i][j - 1]), a[i - 1][j - 1]) + 1; } } // Calculate the sum of the array for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) count += a[i][j]; return count; } // Driver code public static void main (String[] args) { int arr[][] = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } }; System.out.println(countSquareMatrices(arr, n, m)); }} // This code is contributed by AnkitRai01", "e": 3979, "s": 2695, "text": null }, { "code": "# Python3 program to return the number of# square submatrices with all 1sn = 3m = 3 # Function to return the number of# square submatrices with all 1sdef countSquareMatrices(a, N, M): # Initialize count variable count = 0 for i in range(1, N): for j in range(1, M): # If a[i][j] is equal to 0 if (a[i][j] == 0): continue # Calculate number of # square submatrices # ending at (i, j) a[i][j] = min([a[i - 1][j], a[i][j - 1], a[i - 1][j - 1]])+1 # Calculate the sum of the array for i in range(N): for j in range(M): count += a[i][j] return count # Driver code arr = [ [ 1, 0, 1], [ 1, 1, 0 ], [ 1, 1, 0 ] ] print(countSquareMatrices(arr, n, m)) # This code is contributed by mohit kumar 29", "e": 4841, "s": 3979, "text": null }, { "code": "// C# program to return the number of// square submatrices with all 1susing System; class GFG{ static int n = 3; static int m = 3; // Function to return the number of // square submatrices with all 1s static int countSquareMatrices(int [,]a, int N, int M) { // Initialize count variable int count = 0; for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i, j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i, j] = Math.Min(Math.Min(a[i - 1, j], a[i, j - 1]), a[i - 1, j - 1]) + 1; } } // Calculate the sum of the array for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) count += a[i, j]; return count; } // Driver code public static void Main() { int [,]arr = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } }; Console.WriteLine(countSquareMatrices(arr, n, m)); }} // This code is contributed by AnkitRai01", "e": 6108, "s": 4841, "text": null }, { "code": "<script> // Javascript program to return the number of// square submatrices with all 1s var n = 3var m = 3 // Function to return the number of// square submatrices with all 1sfunction countSquareMatrices(a, N, M){ // Initialize count variable var count = 0; for (var i = 1; i < N; i++) { for (var j = 1; j < M; j++) { // If a[i][j] is equal to 0 if (a[i][j] == 0) continue; // Calculate number of // square submatrices // ending at (i, j) a[i][j] = Math.min(Math.min(a[i - 1][j], a[i][j - 1]), a[i - 1][j - 1]) + 1; } } // Calculate the sum of the array for (var i = 0; i < N; i++) for (var j = 0; j < M; j++) count += a[i][j]; return count;} // Driver codevar arr = [ [ 1, 0, 1 ], [ 1, 1, 0 ], [ 1, 1, 0 ] ];document.write( countSquareMatrices(arr, n, m)); </script>", "e": 7121, "s": 6108, "text": null }, { "code": null, "e": 7131, "s": 7121, "text": "Output : " }, { "code": null, "e": 7133, "s": 7131, "text": "7" }, { "code": null, "e": 7178, "s": 7133, "text": "Time Complexity: O(N*M)Auxiliary Space: O(1)" }, { "code": null, "e": 7193, "s": 7178, "text": "mohit kumar 29" }, { "code": null, "e": 7201, "s": 7193, "text": "ankthon" }, { "code": null, "e": 7217, "s": 7201, "text": "subhammahato348" }, { "code": null, "e": 7227, "s": 7217, "text": "rutvik_56" }, { "code": null, "e": 7247, "s": 7227, "text": "Dynamic Programming" }, { "code": null, "e": 7254, "s": 7247, "text": "Matrix" }, { "code": null, "e": 7274, "s": 7254, "text": "Dynamic Programming" }, { "code": null, "e": 7281, "s": 7274, "text": "Matrix" }, { "code": null, "e": 7379, "s": 7281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7447, "s": 7379, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 7502, "s": 7447, "text": "Count number of binary strings without consecutive 1's" }, { "code": null, "e": 7563, "s": 7502, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 7623, "s": 7563, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 7674, "s": 7623, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 7710, "s": 7674, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 7754, "s": 7710, "text": "Program to find largest element in an array" }, { "code": null, "e": 7785, "s": 7754, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 7809, "s": 7785, "text": "Sudoku | Backtracking-7" } ]
Reading Rows from a CSV File in Python
20 Dec, 2021 CSV stands for Comma Separated Values. This file format is a delimited text file that uses a comma as a delimiter to separate the text present in it. Or in other words, CSV files are used to store data in tabular form. As per the name suggested, this file contains the data which is separated by a comma and every line of a file is considered a record. We can create the CSV file either from notepad or using excel. Example: Geeks,for,geeks one,of,the, top,learning,platform We can create a CSV file using the following ways: 1. Using Notepad: We can create a CSV file using Notepad. In the Notepad, open a new file in which separate the values by comma and save the file with .csv extension. 2. Using Excel: We can also create a CSV file using Excel. In Excel, open a new file in which specify each value in a different cell and save it with filetype CSV. To read data row-wise from a CSV file in Python, we can use reader and DictReader which are present in the CSV module allows us to fetch data row-wise. Using reader we can iterate between rows of a CSV file as a list of values. It iterates over all rows in a CSV file and fetches data in each row as a list. reader() method is present in CSV library. So to use this reader method, first we need to import the CSV library. reader object accepts a single parameter called fileObject (a variable that holds the CSV file). Syntax: csv.reader(fileobject) Steps to read CSV file: Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method. with open('filename') as fileObject While loading the file by specifying path along with filename, if you got any unicode error then append r before path of filename with open(r'path/filename') as fileObject Step 2: Create a reader object by passing the above-created file object to the reader function. reader_obj = csv.reader(file_obj) Step 3: Use for loop on reader object to get each row. Example: Consider a CSV file named “samplecsv.csv”. This file contains the following data: Id,Name,Rating 1,Akhil,4 2,Babu,3 3,Nikhil,5 Python3 # Python program to read CSV file line by line# import necessary packagesimport csv # Open file with open('samplecsv.csv') as file_obj: # Create reader object by passing the file # object to reader method reader_obj = csv.reader(file_obj) # Iterate over each row in the csv # file using reader object for row in reader_obj: print(row) Output: ['Id', 'Name', 'Rating'] ['1', 'Akhil', '4'] ['2', 'Babu', '3'] ['3', 'Nikhil', '5'] Reading CSV file without header Everything is fine with the above example but if we don’t want column names to fetch or we can say we don’t want to read the header of the file, then we use the next() method on the file object before creating the reader object so that it skips the headings. Python3 # Python program to read CSV file without header # Import necessary packagesimport csv # Open filewith open('samplecsv.csv') as file_obj: # Skips the heading # Using next() method heading = next(file_obj) # Create reader object by passing the file # object to reader method reader_obj = csv.reader(file_obj) # Iterate over each row in the csv file # using reader object for row in reader_obj: print(row) Output: ['1', 'Akhil', '4'] ['2', 'Babu', '3'] ['3', 'Nikhil', '5'] Explanation: The above code is almost the same as the code in the above example but a slight change is we use the next function here that helps us to skip the column names while accessing data from a CSV file i.e. first row. If column names are required then we access them from the heading object i.e. return the result of the next method. When using a reader() method we can iterate over a CSV file as a list but using the DictReader class object we can iterate over a CSV file row by row as a dictionary. This DictReader method is present in the csv library. So to use it first we need to import the csv library. DictReader() accepts a single parameter called fileObject (a variable that holds the csv file). Syntax csv.DictReader(fileobject) Steps to read CSV file: Step 1: Load the CSV file using the open method in a file object. with open('filename') as fileObject Step 2: Create a reader object with the help of DictReader method using fileobject. reader_obj = csv.DictReader(file_obj) This reader object is also known as an iterator can be used to fetch row-wise data. Step 3: Use for loop on reader object to get each row. Example: Python3 # Python3 program to read CSV file using DictReader # Import necessary packagesimport csv # Open filewith open('samplecsv.csv') as file_obj: # Create reader object by passing the file # object to DictReader method reader_obj = csv.DictReader(file_obj) # Iterate over each row in the csv file # using reader object for row in reader_obj: print(row) Output: OrderedDict([('Id', '1'), ('Name', 'Akhil'), ('Rating', '4')]) OrderedDict([('Id', '2'), ('Name', 'Babu'), ('Rating', '3')]) OrderedDict([('Id', '3'), ('Name', 'Nikhil'), ('Rating', '5')]) Explanation: In the code, first we loaded the CSV file named samplecsv.csv and then created a reader_object that can be iterated to fetch each row. The returned result is in the form of Key-Value pair indicates it as a dictionary. So using DictReader we read data row by row as a Dictionary. Picked Class 12 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Dec, 2021" }, { "code": null, "e": 470, "s": 53, "text": "CSV stands for Comma Separated Values. This file format is a delimited text file that uses a comma as a delimiter to separate the text present in it. Or in other words, CSV files are used to store data in tabular form. As per the name suggested, this file contains the data which is separated by a comma and every line of a file is considered a record. We can create the CSV file either from notepad or using excel. " }, { "code": null, "e": 479, "s": 470, "text": "Example:" }, { "code": null, "e": 529, "s": 479, "text": "Geeks,for,geeks\none,of,the,\ntop,learning,platform" }, { "code": null, "e": 580, "s": 529, "text": "We can create a CSV file using the following ways:" }, { "code": null, "e": 747, "s": 580, "text": "1. Using Notepad: We can create a CSV file using Notepad. In the Notepad, open a new file in which separate the values by comma and save the file with .csv extension." }, { "code": null, "e": 911, "s": 747, "text": "2. Using Excel: We can also create a CSV file using Excel. In Excel, open a new file in which specify each value in a different cell and save it with filetype CSV." }, { "code": null, "e": 1063, "s": 911, "text": "To read data row-wise from a CSV file in Python, we can use reader and DictReader which are present in the CSV module allows us to fetch data row-wise." }, { "code": null, "e": 1431, "s": 1063, "text": "Using reader we can iterate between rows of a CSV file as a list of values. It iterates over all rows in a CSV file and fetches data in each row as a list. reader() method is present in CSV library. So to use this reader method, first we need to import the CSV library. reader object accepts a single parameter called fileObject (a variable that holds the CSV file). " }, { "code": null, "e": 1439, "s": 1431, "text": "Syntax:" }, { "code": null, "e": 1462, "s": 1439, "text": "csv.reader(fileobject)" }, { "code": null, "e": 1486, "s": 1462, "text": "Steps to read CSV file:" }, { "code": null, "e": 1636, "s": 1486, "text": "Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method." }, { "code": null, "e": 1672, "s": 1636, "text": "with open('filename') as fileObject" }, { "code": null, "e": 1802, "s": 1672, "text": "While loading the file by specifying path along with filename, if you got any unicode error then append r before path of filename" }, { "code": null, "e": 1845, "s": 1802, "text": "with open(r'path/filename') as fileObject " }, { "code": null, "e": 1941, "s": 1845, "text": "Step 2: Create a reader object by passing the above-created file object to the reader function." }, { "code": null, "e": 1975, "s": 1941, "text": "reader_obj = csv.reader(file_obj)" }, { "code": null, "e": 2030, "s": 1975, "text": "Step 3: Use for loop on reader object to get each row." }, { "code": null, "e": 2039, "s": 2030, "text": "Example:" }, { "code": null, "e": 2121, "s": 2039, "text": "Consider a CSV file named “samplecsv.csv”. This file contains the following data:" }, { "code": null, "e": 2166, "s": 2121, "text": "Id,Name,Rating\n1,Akhil,4\n2,Babu,3\n3,Nikhil,5" }, { "code": null, "e": 2174, "s": 2166, "text": "Python3" }, { "code": "# Python program to read CSV file line by line# import necessary packagesimport csv # Open file with open('samplecsv.csv') as file_obj: # Create reader object by passing the file # object to reader method reader_obj = csv.reader(file_obj) # Iterate over each row in the csv # file using reader object for row in reader_obj: print(row)", "e": 2549, "s": 2174, "text": null }, { "code": null, "e": 2557, "s": 2549, "text": "Output:" }, { "code": null, "e": 2642, "s": 2557, "text": "['Id', 'Name', 'Rating']\n['1', 'Akhil', '4']\n['2', 'Babu', '3']\n['3', 'Nikhil', '5']" }, { "code": null, "e": 2674, "s": 2642, "text": "Reading CSV file without header" }, { "code": null, "e": 2933, "s": 2674, "text": "Everything is fine with the above example but if we don’t want column names to fetch or we can say we don’t want to read the header of the file, then we use the next() method on the file object before creating the reader object so that it skips the headings." }, { "code": null, "e": 2941, "s": 2933, "text": "Python3" }, { "code": "# Python program to read CSV file without header # Import necessary packagesimport csv # Open filewith open('samplecsv.csv') as file_obj: # Skips the heading # Using next() method heading = next(file_obj) # Create reader object by passing the file # object to reader method reader_obj = csv.reader(file_obj) # Iterate over each row in the csv file # using reader object for row in reader_obj: print(row)", "e": 3401, "s": 2941, "text": null }, { "code": null, "e": 3409, "s": 3401, "text": "Output:" }, { "code": null, "e": 3469, "s": 3409, "text": "['1', 'Akhil', '4']\n['2', 'Babu', '3']\n['3', 'Nikhil', '5']" }, { "code": null, "e": 3810, "s": 3469, "text": "Explanation: The above code is almost the same as the code in the above example but a slight change is we use the next function here that helps us to skip the column names while accessing data from a CSV file i.e. first row. If column names are required then we access them from the heading object i.e. return the result of the next method." }, { "code": null, "e": 4182, "s": 3810, "text": "When using a reader() method we can iterate over a CSV file as a list but using the DictReader class object we can iterate over a CSV file row by row as a dictionary. This DictReader method is present in the csv library. So to use it first we need to import the csv library. DictReader() accepts a single parameter called fileObject (a variable that holds the csv file). " }, { "code": null, "e": 4189, "s": 4182, "text": "Syntax" }, { "code": null, "e": 4216, "s": 4189, "text": "csv.DictReader(fileobject)" }, { "code": null, "e": 4240, "s": 4216, "text": "Steps to read CSV file:" }, { "code": null, "e": 4306, "s": 4240, "text": "Step 1: Load the CSV file using the open method in a file object." }, { "code": null, "e": 4342, "s": 4306, "text": "with open('filename') as fileObject" }, { "code": null, "e": 4426, "s": 4342, "text": "Step 2: Create a reader object with the help of DictReader method using fileobject." }, { "code": null, "e": 4464, "s": 4426, "text": "reader_obj = csv.DictReader(file_obj)" }, { "code": null, "e": 4548, "s": 4464, "text": "This reader object is also known as an iterator can be used to fetch row-wise data." }, { "code": null, "e": 4603, "s": 4548, "text": "Step 3: Use for loop on reader object to get each row." }, { "code": null, "e": 4612, "s": 4603, "text": "Example:" }, { "code": null, "e": 4620, "s": 4612, "text": "Python3" }, { "code": "# Python3 program to read CSV file using DictReader # Import necessary packagesimport csv # Open filewith open('samplecsv.csv') as file_obj: # Create reader object by passing the file # object to DictReader method reader_obj = csv.DictReader(file_obj) # Iterate over each row in the csv file # using reader object for row in reader_obj: print(row)", "e": 5007, "s": 4620, "text": null }, { "code": null, "e": 5015, "s": 5007, "text": "Output:" }, { "code": null, "e": 5204, "s": 5015, "text": "OrderedDict([('Id', '1'), ('Name', 'Akhil'), ('Rating', '4')])\nOrderedDict([('Id', '2'), ('Name', 'Babu'), ('Rating', '3')])\nOrderedDict([('Id', '3'), ('Name', 'Nikhil'), ('Rating', '5')])" }, { "code": null, "e": 5496, "s": 5204, "text": "Explanation: In the code, first we loaded the CSV file named samplecsv.csv and then created a reader_object that can be iterated to fetch each row. The returned result is in the form of Key-Value pair indicates it as a dictionary. So using DictReader we read data row by row as a Dictionary." }, { "code": null, "e": 5503, "s": 5496, "text": "Picked" }, { "code": null, "e": 5512, "s": 5503, "text": "Class 12" }, { "code": null, "e": 5528, "s": 5512, "text": "School Learning" }, { "code": null, "e": 5547, "s": 5528, "text": "School Programming" } ]
ML | Feature Scaling – Part 2
05 Jul, 2021 Feature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data pre-processing to handle highly varying magnitudes or values or units. If feature scaling is not done, then a machine learning algorithm tends to weigh greater values, higher and consider smaller values as the lower values, regardless of the unit of the values. Example: If an algorithm is not using the feature scaling method then it can consider the value 3000 meters to be greater than 5 km but that’s actually not true and in this case, the algorithm will give wrong predictions. So, we use Feature Scaling to bring all values to the same magnitudes and thus, tackle this issue. Techniques to perform Feature ScalingConsider the two most important ones: Min-Max Normalization: This technique re-scales a feature or observation value with distribution value between 0 and 1. Standardization: It is a very effective technique which re-scales a feature value so that it has distribution with 0 mean value and variance equals to 1. Download the dataset:Go to the link and download Data_for_Feature_Scaling.csv Code: Python code explaining the working of Feature Scaling on the data # Python code explaining How to# perform Feature Scaling """ PART 1 Importing Libraries """ import numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Sklearn library from sklearn import preprocessing """ PART 2 Importing Data """ data_set = pd.read_csv('C:\\Users\\dell\\Desktop\\Data_for_Feature_Scaling.csv')data_set.head() # here Features - Age and Salary columns # are taken using slicing# to handle values with varying magnitudex = data_set.iloc[:, 1:3].valuesprint ("\nOriginal data values : \n", x) """ PART 4 Handling the missing values """ from sklearn import preprocessing """ MIN MAX SCALER """ min_max_scaler = preprocessing.MinMaxScaler(feature_range =(0, 1)) # Scaled featurex_after_min_max_scaler = min_max_scaler.fit_transform(x) print ("\nAfter min max Scaling : \n", x_after_min_max_scaler) """ Standardisation """ Standardisation = preprocessing.StandardScaler() # Scaled featurex_after_Standardisation = Standardisation.fit_transform(x) print ("\nAfter Standardisation : \n", x_after_Standardisation) Output : Country Age Salary Purchased 0 France 44 72000 0 1 Spain 27 48000 1 2 Germany 30 54000 0 3 Spain 38 61000 0 4 Germany 40 1000 1 Original data values : [[ 44 72000] [ 27 48000] [ 30 54000] [ 38 61000] [ 40 1000] [ 35 58000] [ 78 52000] [ 48 79000] [ 50 83000] [ 37 67000]] After min max Scaling : [[ 0.33333333 0.86585366] [ 0. 0.57317073] [ 0.05882353 0.64634146] [ 0.21568627 0.73170732] [ 0.25490196 0. ] [ 0.15686275 0.69512195] [ 1. 0.62195122] [ 0.41176471 0.95121951] [ 0.45098039 1. ] [ 0.19607843 0.80487805]] After Standardisation : [[ 0.09536935 0.66527061] [-1.15176827 -0.43586695] [-0.93168516 -0.16058256] [-0.34479687 0.16058256] [-0.1980748 -2.59226136] [-0.56487998 0.02294037] [ 2.58964459 -0.25234403] [ 0.38881349 0.98643574] [ 0.53553557 1.16995867] [-0.41815791 0.43586695]] Vijay Sirra Advanced Computer Subject Machine Learning Mathematical Python Mathematical Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Docker - COPY Instruction ML | Monte Carlo Tree Search (MCTS) Getting started with Machine Learning Markov Decision Process Agents in Artificial Intelligence Search Algorithms in AI Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Getting started with Machine Learning
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2021" }, { "code": null, "e": 455, "s": 52, "text": "Feature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data pre-processing to handle highly varying magnitudes or values or units. If feature scaling is not done, then a machine learning algorithm tends to weigh greater values, higher and consider smaller values as the lower values, regardless of the unit of the values." }, { "code": null, "e": 776, "s": 455, "text": "Example: If an algorithm is not using the feature scaling method then it can consider the value 3000 meters to be greater than 5 km but that’s actually not true and in this case, the algorithm will give wrong predictions. So, we use Feature Scaling to bring all values to the same magnitudes and thus, tackle this issue." }, { "code": null, "e": 851, "s": 776, "text": "Techniques to perform Feature ScalingConsider the two most important ones:" }, { "code": null, "e": 971, "s": 851, "text": "Min-Max Normalization: This technique re-scales a feature or observation value with distribution value between 0 and 1." }, { "code": null, "e": 1125, "s": 971, "text": "Standardization: It is a very effective technique which re-scales a feature value so that it has distribution with 0 mean value and variance equals to 1." }, { "code": null, "e": 1203, "s": 1125, "text": "Download the dataset:Go to the link and download Data_for_Feature_Scaling.csv" }, { "code": null, "e": 1275, "s": 1203, "text": "Code: Python code explaining the working of Feature Scaling on the data" }, { "code": "# Python code explaining How to# perform Feature Scaling \"\"\" PART 1 Importing Libraries \"\"\" import numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Sklearn library from sklearn import preprocessing \"\"\" PART 2 Importing Data \"\"\" data_set = pd.read_csv('C:\\\\Users\\\\dell\\\\Desktop\\\\Data_for_Feature_Scaling.csv')data_set.head() # here Features - Age and Salary columns # are taken using slicing# to handle values with varying magnitudex = data_set.iloc[:, 1:3].valuesprint (\"\\nOriginal data values : \\n\", x) \"\"\" PART 4 Handling the missing values \"\"\" from sklearn import preprocessing \"\"\" MIN MAX SCALER \"\"\" min_max_scaler = preprocessing.MinMaxScaler(feature_range =(0, 1)) # Scaled featurex_after_min_max_scaler = min_max_scaler.fit_transform(x) print (\"\\nAfter min max Scaling : \\n\", x_after_min_max_scaler) \"\"\" Standardisation \"\"\" Standardisation = preprocessing.StandardScaler() # Scaled featurex_after_Standardisation = Standardisation.fit_transform(x) print (\"\\nAfter Standardisation : \\n\", x_after_Standardisation)", "e": 2342, "s": 1275, "text": null }, { "code": null, "e": 2351, "s": 2342, "text": "Output :" }, { "code": null, "e": 3335, "s": 2351, "text": " Country Age Salary Purchased\n0 France 44 72000 0\n1 Spain 27 48000 1\n2 Germany 30 54000 0\n3 Spain 38 61000 0\n4 Germany 40 1000 1\n\nOriginal data values : \n [[ 44 72000]\n [ 27 48000]\n [ 30 54000]\n [ 38 61000]\n [ 40 1000]\n [ 35 58000]\n [ 78 52000]\n [ 48 79000]\n [ 50 83000]\n [ 37 67000]]\n\nAfter min max Scaling : \n [[ 0.33333333 0.86585366]\n [ 0. 0.57317073]\n [ 0.05882353 0.64634146]\n [ 0.21568627 0.73170732]\n [ 0.25490196 0. ]\n [ 0.15686275 0.69512195]\n [ 1. 0.62195122]\n [ 0.41176471 0.95121951]\n [ 0.45098039 1. ]\n [ 0.19607843 0.80487805]]\n\nAfter Standardisation : \n [[ 0.09536935 0.66527061]\n [-1.15176827 -0.43586695]\n [-0.93168516 -0.16058256]\n [-0.34479687 0.16058256]\n [-0.1980748 -2.59226136]\n [-0.56487998 0.02294037]\n [ 2.58964459 -0.25234403]\n [ 0.38881349 0.98643574]\n [ 0.53553557 1.16995867]\n [-0.41815791 0.43586695]]\n" }, { "code": null, "e": 3347, "s": 3335, "text": "Vijay Sirra" }, { "code": null, "e": 3373, "s": 3347, "text": "Advanced Computer Subject" }, { "code": null, "e": 3390, "s": 3373, "text": "Machine Learning" }, { "code": null, "e": 3403, "s": 3390, "text": "Mathematical" }, { "code": null, "e": 3410, "s": 3403, "text": "Python" }, { "code": null, "e": 3423, "s": 3410, "text": "Mathematical" }, { "code": null, "e": 3440, "s": 3423, "text": "Machine Learning" }, { "code": null, "e": 3538, "s": 3440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3561, "s": 3538, "text": "System Design Tutorial" }, { "code": null, "e": 3587, "s": 3561, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3623, "s": 3587, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3661, "s": 3623, "text": "Getting started with Machine Learning" }, { "code": null, "e": 3685, "s": 3661, "text": "Markov Decision Process" }, { "code": null, "e": 3719, "s": 3685, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 3743, "s": 3719, "text": "Search Algorithms in AI" }, { "code": null, "e": 3784, "s": 3743, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3820, "s": 3784, "text": "ML | Monte Carlo Tree Search (MCTS)" } ]
PyQt5 – QCommandLinkButton Class
26 Jun, 2020 QCommandLinkButton is a control widget that was introduced by Windows Vista. Its intended use is similar to that of a radio button in that it is used to choose between a set of mutually exclusive options. The appearance of it is generally similar to that of a flat push button, but it allows for a descriptive text in addition to the normal button text. By default it will also carry an arrow icon, indicating that pressing the control will open another window or page or do something. Below is how the command link button looks like Example :We will create a window having a label and the command link button and when the command link button pressed the counter will increment in the label Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # counter value self.n = 0 # creating label label = QLabel("Counter", self) # setting label geometry label.setGeometry(100, 100, 100, 40) # creating a command link button cl_button = QCommandLinkButton("Next", self) # setting geometry cl_button.setGeometry(200, 100, 200, 40) # adding action to the button cl_button.clicked.connect(lambda: increment(self.n)) # method for incrementing the counter def increment(n): # increment self.n = n + 1 # setting text to the label label.setText(str(self.n)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QCommandLinkButton Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2020" }, { "code": null, "e": 562, "s": 28, "text": "QCommandLinkButton is a control widget that was introduced by Windows Vista. Its intended use is similar to that of a radio button in that it is used to choose between a set of mutually exclusive options. The appearance of it is generally similar to that of a flat push button, but it allows for a descriptive text in addition to the normal button text. By default it will also carry an arrow icon, indicating that pressing the control will open another window or page or do something. Below is how the command link button looks like" }, { "code": null, "e": 719, "s": 562, "text": "Example :We will create a window having a label and the command link button and when the command link button pressed the counter will increment in the label" }, { "code": null, "e": 747, "s": 719, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # counter value self.n = 0 # creating label label = QLabel(\"Counter\", self) # setting label geometry label.setGeometry(100, 100, 100, 40) # creating a command link button cl_button = QCommandLinkButton(\"Next\", self) # setting geometry cl_button.setGeometry(200, 100, 200, 40) # adding action to the button cl_button.clicked.connect(lambda: increment(self.n)) # method for incrementing the counter def increment(n): # increment self.n = n + 1 # setting text to the label label.setText(str(self.n)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2084, "s": 747, "text": null }, { "code": null, "e": 2093, "s": 2084, "text": "Output :" }, { "code": null, "e": 2124, "s": 2093, "text": "Python PyQt-QCommandLinkButton" }, { "code": null, "e": 2135, "s": 2124, "text": "Python-gui" }, { "code": null, "e": 2147, "s": 2135, "text": "Python-PyQt" }, { "code": null, "e": 2154, "s": 2147, "text": "Python" }, { "code": null, "e": 2252, "s": 2154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2284, "s": 2252, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2311, "s": 2284, "text": "Python Classes and Objects" }, { "code": null, "e": 2332, "s": 2311, "text": "Python OOPs Concepts" }, { "code": null, "e": 2355, "s": 2332, "text": "Introduction To PYTHON" }, { "code": null, "e": 2411, "s": 2355, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2442, "s": 2411, "text": "Python | os.path.join() method" }, { "code": null, "e": 2484, "s": 2442, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2526, "s": 2484, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2565, "s": 2526, "text": "Python | Get unique values from a list" } ]
PHP | filter_input_array() Function
18 Jul, 2019 The filter_input_array() function is an inbuilt function in PHP which is used to get external variables (e.g. from form input) and filters them if it is specified. This function is similar to filter_input() function but the only difference is filter_input() filters a single value but in filter_input_array() filters the whole array according to options provided. It is useful for retrieving/filtering many values instead of calling filter_input() many times. This is new in PHP only works in PHP 5.2 or latter version of PHP. Syntax: mixed filter_input_array( $type_of_data, $definition, $add_empty_parameter ) Parameters: This function accepts three parameters as mentioned above and described below: type_of_data: It is required parameter. It holds the input type of the data to check. The available options are:INPUT_GETINPUT_POSTINPUT_COOKIEINPUT_SERVERINPUT_ENV INPUT_GET INPUT_POST INPUT_COOKIE INPUT_SERVER INPUT_ENV definition: It is optional parameter. It specifies an array of filter arguments or parameters. A valid array key as a variable name and a valid value as a filter name or ID, or an array specifying the filter, flags, and options. This parameter can also be a single filter name/ID just like filter_input() then all values in the input array are filtered by the specified filter. add_empty_parameter: It is optional parameter. It is a Boolean parameter. It adds missing keys as NULL to the return value when it sets to True. Its default value is True. Return Value: It returns an array containing the values of the variables on success and on failure, it returns False. If the input array designated by type is not populated, the function returns NULL if the FILTER_NULL_ON_FAILURE flag is not given, otherwise, it returns False. For other failures, False is returned. Below programs illustrate the filter_input_array() function in PHP: program 1: <?php $filters = array( "name" => array( "filter" => FILTER_CALLBACK, "flags" => FILTER_FORCE_ARRAY, "options" => "ucwords" ), "age" => array( "filter" => FILTER_VALIDATE_INT, "options" => array( "min_range" => 1, "max_range" => 120 ) ), "email"=> FILTER_VALIDATE_EMAIL,); print_r(filter_input_array(INPUT_GET, $filters)); ?> Output: Note: This example may not give the expected result on online IDE as it doesn’t support the passing of parameters in GET or POST method. So, try to run it in some PHP hosting server or localhost and pass the values of the parameter either by GET or POST method. Program 2:Data came from POST method: $_POST = array( 'product_id' => '234<A>', 'component' => array('10'), 'version' => '<2.8.9', 'array2' => array('45', '1'), 'scalar_data' => '2', ); <?php// PHP program to uses filter_input_array() Function error_reporting(E_ALL | E_STRICT); $args = array( 'id' => FILTER_SANITIZE_ENCODED, 'array1' => array( 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY, 'options' => array( 'min_range' => 1, 'max_range' => 10 ) ), 'version' => FILTER_SANITIZE_ENCODED, 'noparameter' => FILTER_VALIDATE_INT, 'scalar_data' => array( 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_SCALAR, ), 'array2' => array( 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY, )); $allinputs = filter_input_array(INPUT_GET, $args); var_dump($allinputs);echo "\n"; ?> Output: Note: This example may not give the expected result on online IDE as it doesn’t support the passing of parameters in GET or POST method. So, try to run it in some PHP hosting server or localhost and pass the values of the parameter either by GET or POST method. References: http://php.net/manual/en/function.filter-input-array.php PHP-function PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2019" }, { "code": null, "e": 555, "s": 28, "text": "The filter_input_array() function is an inbuilt function in PHP which is used to get external variables (e.g. from form input) and filters them if it is specified. This function is similar to filter_input() function but the only difference is filter_input() filters a single value but in filter_input_array() filters the whole array according to options provided. It is useful for retrieving/filtering many values instead of calling filter_input() many times. This is new in PHP only works in PHP 5.2 or latter version of PHP." }, { "code": null, "e": 563, "s": 555, "text": "Syntax:" }, { "code": null, "e": 640, "s": 563, "text": "mixed filter_input_array( $type_of_data, $definition, $add_empty_parameter )" }, { "code": null, "e": 731, "s": 640, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 896, "s": 731, "text": "type_of_data: It is required parameter. It holds the input type of the data to check. The available options are:INPUT_GETINPUT_POSTINPUT_COOKIEINPUT_SERVERINPUT_ENV" }, { "code": null, "e": 906, "s": 896, "text": "INPUT_GET" }, { "code": null, "e": 917, "s": 906, "text": "INPUT_POST" }, { "code": null, "e": 930, "s": 917, "text": "INPUT_COOKIE" }, { "code": null, "e": 943, "s": 930, "text": "INPUT_SERVER" }, { "code": null, "e": 953, "s": 943, "text": "INPUT_ENV" }, { "code": null, "e": 1331, "s": 953, "text": "definition: It is optional parameter. It specifies an array of filter arguments or parameters. A valid array key as a variable name and a valid value as a filter name or ID, or an array specifying the filter, flags, and options. This parameter can also be a single filter name/ID just like filter_input() then all values in the input array are filtered by the specified filter." }, { "code": null, "e": 1503, "s": 1331, "text": "add_empty_parameter: It is optional parameter. It is a Boolean parameter. It adds missing keys as NULL to the return value when it sets to True. Its default value is True." }, { "code": null, "e": 1820, "s": 1503, "text": "Return Value: It returns an array containing the values of the variables on success and on failure, it returns False. If the input array designated by type is not populated, the function returns NULL if the FILTER_NULL_ON_FAILURE flag is not given, otherwise, it returns False. For other failures, False is returned." }, { "code": null, "e": 1888, "s": 1820, "text": "Below programs illustrate the filter_input_array() function in PHP:" }, { "code": null, "e": 1899, "s": 1888, "text": "program 1:" }, { "code": "<?php $filters = array( \"name\" => array( \"filter\" => FILTER_CALLBACK, \"flags\" => FILTER_FORCE_ARRAY, \"options\" => \"ucwords\" ), \"age\" => array( \"filter\" => FILTER_VALIDATE_INT, \"options\" => array( \"min_range\" => 1, \"max_range\" => 120 ) ), \"email\"=> FILTER_VALIDATE_EMAIL,); print_r(filter_input_array(INPUT_GET, $filters)); ?>", "e": 2307, "s": 1899, "text": null }, { "code": null, "e": 2315, "s": 2307, "text": "Output:" }, { "code": null, "e": 2577, "s": 2315, "text": "Note: This example may not give the expected result on online IDE as it doesn’t support the passing of parameters in GET or POST method. So, try to run it in some PHP hosting server or localhost and pass the values of the parameter either by GET or POST method." }, { "code": null, "e": 2615, "s": 2577, "text": "Program 2:Data came from POST method:" }, { "code": null, "e": 2789, "s": 2615, "text": "$_POST = array(\n 'product_id' => '234<A>',\n 'component' => array('10'),\n 'version' => '<2.8.9',\n 'array2' => array('45', '1'),\n 'scalar_data' => '2',\n);\n" }, { "code": "<?php// PHP program to uses filter_input_array() Function error_reporting(E_ALL | E_STRICT); $args = array( 'id' => FILTER_SANITIZE_ENCODED, 'array1' => array( 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY, 'options' => array( 'min_range' => 1, 'max_range' => 10 ) ), 'version' => FILTER_SANITIZE_ENCODED, 'noparameter' => FILTER_VALIDATE_INT, 'scalar_data' => array( 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_SCALAR, ), 'array2' => array( 'filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY, )); $allinputs = filter_input_array(INPUT_GET, $args); var_dump($allinputs);echo \"\\n\"; ?>", "e": 3538, "s": 2789, "text": null }, { "code": null, "e": 3546, "s": 3538, "text": "Output:" }, { "code": null, "e": 3808, "s": 3546, "text": "Note: This example may not give the expected result on online IDE as it doesn’t support the passing of parameters in GET or POST method. So, try to run it in some PHP hosting server or localhost and pass the values of the parameter either by GET or POST method." }, { "code": null, "e": 3877, "s": 3808, "text": "References: http://php.net/manual/en/function.filter-input-array.php" }, { "code": null, "e": 3890, "s": 3877, "text": "PHP-function" }, { "code": null, "e": 3894, "s": 3890, "text": "PHP" }, { "code": null, "e": 3907, "s": 3894, "text": "PHP Programs" }, { "code": null, "e": 3924, "s": 3907, "text": "Web Technologies" }, { "code": null, "e": 3928, "s": 3924, "text": "PHP" } ]
Find the Nth row in Pascal’s Triangle
02 Jun, 2022 Given a non-negative integer N, the task is to find the Nth row of Pascal’s Triangle. Note: The row index starts from 0. Pascal’s Triangle: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Examples: Input: N = 3 Output: 1, 3, 3, 1 Explanation: The elements in the 3rd row are 1 3 3 1. Input: N = 0 Output: 1 Naive Approach: The simplest approach to solve the problem is to use Recursion. Find the row of the previous index first using recursion and then calculate the values of the current row with the help of the previous one. Repeat this process up to the Nth row. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the Nth// index row in Pascal's triangle#include <bits/stdc++.h>using namespace std; // Function to find the elements// of rowIndex in Pascal's Trianglevector<int> getRow(int rowIndex){ vector<int> currow; // 1st element of every row is 1 currow.push_back(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row vector<int> prev = getRow(rowIndex - 1); for(int i = 1; i < prev.size(); i++) { // Generate the elements // of the current row // by the help of the // previous row int curr = prev[i - 1] + prev[i]; currow.push_back(curr); } currow.push_back(1); // Return the row return currow;} // Driver Code int main(){ int n = 3; vector<int> arr = getRow(n); for(int i = 0; i < arr.size(); i++) { if (i == arr.size() - 1) cout << arr[i]; else cout << arr[i] << ", "; } return 0;} // This code is contributed by divyesh072019 // Java Program to find the Nth// index row in Pascal's triangleimport java.util.ArrayList;public class geeks { // Function to find the elements // of rowIndex in Pascal's Triangle public static ArrayList<Integer> getRow( int rowIndex) { ArrayList<Integer> currow = new ArrayList<Integer>(); // 1st element of every row is 1 currow.add(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row ArrayList<Integer> prev = getRow(rowIndex - 1); for (int i = 1; i < prev.size(); i++) { // Generate the elements // of the current row // by the help of the // previous row int curr = prev.get(i - 1) + prev.get(i); currow.add(curr); } currow.add(1); // Return the row return currow; } // Driver Program public static void main(String[] args) { int n = 3; ArrayList<Integer> arr = getRow(n); for (int i = 0; i < arr.size(); i++) { if (i == arr.size() - 1) System.out.print(arr.get(i)); else System.out.print(arr.get(i) + ", "); } }} # Python3 program to find the Nth# index row in Pascal's triangle # Function to find the elements# of rowIndex in Pascal's Triangledef getRow(rowIndex) : currow = [] # 1st element of every row is 1 currow.append(1) # Check if the row that has to # be returned is the first row if (rowIndex == 0) : return currow # Generate the previous row prev = getRow(rowIndex - 1) for i in range(1, len(prev)) : # Generate the elements # of the current row # by the help of the # previous row curr = prev[i - 1] + prev[i] currow.append(curr) currow.append(1) # Return the row return currow n = 3arr = getRow(n) for i in range(len(arr)) : if (i == (len(arr) - 1)) : print(arr[i]) else : print(arr[i] , end = ", ") # This code is contributed by divyeshrabadiya07 // C# program to find the Nth// index row in Pascal's triangleusing System;using System.Collections.Generic; class GFG{ // Function to find the elements// of rowIndex in Pascal's Trianglepublic static List<int> getRow(int rowIndex){ List<int> currow = new List<int>(); // 1st element of every row is 1 currow.Add(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row List<int> prev = getRow(rowIndex - 1); for(int i = 1; i < prev.Count; i++) { // Generate the elements // of the current row // by the help of the // previous row int curr = prev[i - 1] + prev[i]; currow.Add(curr); } currow.Add(1); // Return the row return currow;} // Driver codepublic static void Main(String[] args){ int n = 3; List<int> arr = getRow(n); for(int i = 0; i < arr.Count; i++) { if (i == arr.Count - 1) Console.Write(arr[i]); else Console.Write(arr[i] + ", "); }}} // This code is contributed by 29AjayKumar <script> // Javascript program to find the Nth // index row in Pascal's triangle // Function to find the elements // of rowIndex in Pascal's Triangle function getRow(rowIndex) { let currow = []; // 1st element of every row is 1 currow.push(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row let prev = getRow(rowIndex - 1); for(let i = 1; i < prev.length; i++) { // Generate the elements // of the current row // by the help of the // previous row let curr = prev[i - 1] + prev[i]; currow.push(curr); } currow.push(1); // Return the row return currow; } let n = 3; let arr = getRow(n); for(let i = 0; i < arr.length; i++) { if (i == arr.length - 1) document.write(arr[i]); else document.write(arr[i] + ", "); } </script> 1, 3, 3, 1 Time Complexity: O(N2)Space Complexity: O(N) Efficient Approach: Follow the steps below to optimize the above approach: Unlike the above approach, we will just generate only the numbers of the Nth row. We can observe that the Nth row of the Pascals triangle consists of following sequence: NC0, NC1, ......, NCN - 1, NCN Since, NC0 = 1, the following values of the sequence can be generated by the following equation: NCr = (NCr - 1 * (N - r + 1)) / r where 1 ≤ r ≤ N Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Print the N-th row of the// Pascal's Trianglevoid generateNthrow(int N){ // nC0 = 1 int prev = 1; cout << prev; for (int i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r int curr = (prev * (N - i + 1)) / i; cout << ", " << curr; prev = curr; }} // Driver Programint main(){ int N = 5; generateNthrow(N); return 0;} // Java program to implement the above approachimport java.io.*; class GFG{ // Print the N-th row of the// Pascal's Trianglestatic void generateNthrow(int N){ // nC0 = 1 int prev = 1; System.out.print(prev); for(int i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r int curr = (prev * (N - i + 1)) / i; System.out.print(", " + curr); prev = curr; }} // Driver codepublic static void main (String[] args){ int N = 5; generateNthrow(N);}} // This code is contributed by shubhamsingh10 # Python3 program to implement the above approach # Print the N-th row of the# Pascal's Triangledef generateNthRow (N): # nC0 = 1 prev = 1 print(prev, end = '') for i in range(1, N + 1): # nCr = (nCr-1 * (n - r + 1))/r curr = (prev * (N - i + 1)) // i print(",", curr, end = '') prev = curr # Driver codeN = 5 # Function callinggenerateNthRow(N) # This code is contributed by himanshu77 // C# program to implement the above approachusing System;using System.Collections.Generic;class GFG{ // Print the N-th row of the// Pascal's Trianglestatic void generateNthrow(int N){ // nC0 = 1 int prev = 1; Console.Write(prev); for(int i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r int curr = (prev * (N - i + 1)) / i; Console.Write(", " + curr); prev = curr; }} // Driver codepublic static void Main(String[] args){ int N = 5; generateNthrow(N);}} // This code is contributed by 29AjayKumar <script> // Javascript program to implement the above approach // Print the N-th row of the // Pascal's Triangle function generateNthrow(N) { // nC0 = 1 let prev = 1; document.write(prev); for(let i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r let curr = (prev * (N - i + 1)) / i; document.write(", " + curr); prev = curr; } } let N = 5; generateNthrow(N); // This code is contributed by suresh07.</script> 1, 5, 10, 10, 5, 1 Time Complexity: O(N) Auxiliary Space: O(1) SHUBHAMSINGH10 himanshu77 29AjayKumar divyesh072019 divyeshrabadiya07 mukesh07 suresh07 tausifsiddiqui pattern-printing Permutation and Combination series Competitive Programming Mathematical Recursion Mathematical pattern-printing Recursion series 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 Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2022" }, { "code": null, "e": 139, "s": 52, "text": "Given a non-negative integer N, the task is to find the Nth row of Pascal’s Triangle. " }, { "code": null, "e": 175, "s": 139, "text": "Note: The row index starts from 0. " }, { "code": null, "e": 226, "s": 175, "text": "Pascal’s Triangle: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 " }, { "code": null, "e": 237, "s": 226, "text": "Examples: " }, { "code": null, "e": 323, "s": 237, "text": "Input: N = 3 Output: 1, 3, 3, 1 Explanation: The elements in the 3rd row are 1 3 3 1." }, { "code": null, "e": 347, "s": 323, "text": "Input: N = 0 Output: 1 " }, { "code": null, "e": 607, "s": 347, "text": "Naive Approach: The simplest approach to solve the problem is to use Recursion. Find the row of the previous index first using recursion and then calculate the values of the current row with the help of the previous one. Repeat this process up to the Nth row." }, { "code": null, "e": 660, "s": 607, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 664, "s": 660, "text": "C++" }, { "code": null, "e": 669, "s": 664, "text": "Java" }, { "code": null, "e": 677, "s": 669, "text": "Python3" }, { "code": null, "e": 680, "s": 677, "text": "C#" }, { "code": null, "e": 691, "s": 680, "text": "Javascript" }, { "code": "// C++ program to find the Nth// index row in Pascal's triangle#include <bits/stdc++.h>using namespace std; // Function to find the elements// of rowIndex in Pascal's Trianglevector<int> getRow(int rowIndex){ vector<int> currow; // 1st element of every row is 1 currow.push_back(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row vector<int> prev = getRow(rowIndex - 1); for(int i = 1; i < prev.size(); i++) { // Generate the elements // of the current row // by the help of the // previous row int curr = prev[i - 1] + prev[i]; currow.push_back(curr); } currow.push_back(1); // Return the row return currow;} // Driver Code int main(){ int n = 3; vector<int> arr = getRow(n); for(int i = 0; i < arr.size(); i++) { if (i == arr.size() - 1) cout << arr[i]; else cout << arr[i] << \", \"; } return 0;} // This code is contributed by divyesh072019", "e": 1802, "s": 691, "text": null }, { "code": "// Java Program to find the Nth// index row in Pascal's triangleimport java.util.ArrayList;public class geeks { // Function to find the elements // of rowIndex in Pascal's Triangle public static ArrayList<Integer> getRow( int rowIndex) { ArrayList<Integer> currow = new ArrayList<Integer>(); // 1st element of every row is 1 currow.add(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row ArrayList<Integer> prev = getRow(rowIndex - 1); for (int i = 1; i < prev.size(); i++) { // Generate the elements // of the current row // by the help of the // previous row int curr = prev.get(i - 1) + prev.get(i); currow.add(curr); } currow.add(1); // Return the row return currow; } // Driver Program public static void main(String[] args) { int n = 3; ArrayList<Integer> arr = getRow(n); for (int i = 0; i < arr.size(); i++) { if (i == arr.size() - 1) System.out.print(arr.get(i)); else System.out.print(arr.get(i) + \", \"); } }}", "e": 3205, "s": 1802, "text": null }, { "code": "# Python3 program to find the Nth# index row in Pascal's triangle # Function to find the elements# of rowIndex in Pascal's Triangledef getRow(rowIndex) : currow = [] # 1st element of every row is 1 currow.append(1) # Check if the row that has to # be returned is the first row if (rowIndex == 0) : return currow # Generate the previous row prev = getRow(rowIndex - 1) for i in range(1, len(prev)) : # Generate the elements # of the current row # by the help of the # previous row curr = prev[i - 1] + prev[i] currow.append(curr) currow.append(1) # Return the row return currow n = 3arr = getRow(n) for i in range(len(arr)) : if (i == (len(arr) - 1)) : print(arr[i]) else : print(arr[i] , end = \", \") # This code is contributed by divyeshrabadiya07", "e": 4096, "s": 3205, "text": null }, { "code": "// C# program to find the Nth// index row in Pascal's triangleusing System;using System.Collections.Generic; class GFG{ // Function to find the elements// of rowIndex in Pascal's Trianglepublic static List<int> getRow(int rowIndex){ List<int> currow = new List<int>(); // 1st element of every row is 1 currow.Add(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row List<int> prev = getRow(rowIndex - 1); for(int i = 1; i < prev.Count; i++) { // Generate the elements // of the current row // by the help of the // previous row int curr = prev[i - 1] + prev[i]; currow.Add(curr); } currow.Add(1); // Return the row return currow;} // Driver codepublic static void Main(String[] args){ int n = 3; List<int> arr = getRow(n); for(int i = 0; i < arr.Count; i++) { if (i == arr.Count - 1) Console.Write(arr[i]); else Console.Write(arr[i] + \", \"); }}} // This code is contributed by 29AjayKumar", "e": 5233, "s": 4096, "text": null }, { "code": "<script> // Javascript program to find the Nth // index row in Pascal's triangle // Function to find the elements // of rowIndex in Pascal's Triangle function getRow(rowIndex) { let currow = []; // 1st element of every row is 1 currow.push(1); // Check if the row that has to // be returned is the first row if (rowIndex == 0) { return currow; } // Generate the previous row let prev = getRow(rowIndex - 1); for(let i = 1; i < prev.length; i++) { // Generate the elements // of the current row // by the help of the // previous row let curr = prev[i - 1] + prev[i]; currow.push(curr); } currow.push(1); // Return the row return currow; } let n = 3; let arr = getRow(n); for(let i = 0; i < arr.length; i++) { if (i == arr.length - 1) document.write(arr[i]); else document.write(arr[i] + \", \"); } </script>", "e": 6317, "s": 5233, "text": null }, { "code": null, "e": 6328, "s": 6317, "text": "1, 3, 3, 1" }, { "code": null, "e": 6375, "s": 6330, "text": "Time Complexity: O(N2)Space Complexity: O(N)" }, { "code": null, "e": 6450, "s": 6375, "text": "Efficient Approach: Follow the steps below to optimize the above approach:" }, { "code": null, "e": 6532, "s": 6450, "text": "Unlike the above approach, we will just generate only the numbers of the Nth row." }, { "code": null, "e": 6620, "s": 6532, "text": "We can observe that the Nth row of the Pascals triangle consists of following sequence:" }, { "code": null, "e": 6651, "s": 6620, "text": "NC0, NC1, ......, NCN - 1, NCN" }, { "code": null, "e": 6748, "s": 6651, "text": "Since, NC0 = 1, the following values of the sequence can be generated by the following equation:" }, { "code": null, "e": 6798, "s": 6748, "text": "NCr = (NCr - 1 * (N - r + 1)) / r where 1 ≤ r ≤ N" }, { "code": null, "e": 6849, "s": 6798, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 6853, "s": 6849, "text": "C++" }, { "code": null, "e": 6858, "s": 6853, "text": "Java" }, { "code": null, "e": 6866, "s": 6858, "text": "Python3" }, { "code": null, "e": 6869, "s": 6866, "text": "C#" }, { "code": null, "e": 6880, "s": 6869, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Print the N-th row of the// Pascal's Trianglevoid generateNthrow(int N){ // nC0 = 1 int prev = 1; cout << prev; for (int i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r int curr = (prev * (N - i + 1)) / i; cout << \", \" << curr; prev = curr; }} // Driver Programint main(){ int N = 5; generateNthrow(N); return 0;}", "e": 7351, "s": 6880, "text": null }, { "code": "// Java program to implement the above approachimport java.io.*; class GFG{ // Print the N-th row of the// Pascal's Trianglestatic void generateNthrow(int N){ // nC0 = 1 int prev = 1; System.out.print(prev); for(int i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r int curr = (prev * (N - i + 1)) / i; System.out.print(\", \" + curr); prev = curr; }} // Driver codepublic static void main (String[] args){ int N = 5; generateNthrow(N);}} // This code is contributed by shubhamsingh10", "e": 7906, "s": 7351, "text": null }, { "code": "# Python3 program to implement the above approach # Print the N-th row of the# Pascal's Triangledef generateNthRow (N): # nC0 = 1 prev = 1 print(prev, end = '') for i in range(1, N + 1): # nCr = (nCr-1 * (n - r + 1))/r curr = (prev * (N - i + 1)) // i print(\",\", curr, end = '') prev = curr # Driver codeN = 5 # Function callinggenerateNthRow(N) # This code is contributed by himanshu77", "e": 8336, "s": 7906, "text": null }, { "code": "// C# program to implement the above approachusing System;using System.Collections.Generic;class GFG{ // Print the N-th row of the// Pascal's Trianglestatic void generateNthrow(int N){ // nC0 = 1 int prev = 1; Console.Write(prev); for(int i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r int curr = (prev * (N - i + 1)) / i; Console.Write(\", \" + curr); prev = curr; }} // Driver codepublic static void Main(String[] args){ int N = 5; generateNthrow(N);}} // This code is contributed by 29AjayKumar", "e": 8911, "s": 8336, "text": null }, { "code": "<script> // Javascript program to implement the above approach // Print the N-th row of the // Pascal's Triangle function generateNthrow(N) { // nC0 = 1 let prev = 1; document.write(prev); for(let i = 1; i <= N; i++) { // nCr = (nCr-1 * (n - r + 1))/r let curr = (prev * (N - i + 1)) / i; document.write(\", \" + curr); prev = curr; } } let N = 5; generateNthrow(N); // This code is contributed by suresh07.</script>", "e": 9449, "s": 8911, "text": null }, { "code": null, "e": 9468, "s": 9449, "text": "1, 5, 10, 10, 5, 1" }, { "code": null, "e": 9515, "s": 9470, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 9530, "s": 9515, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 9541, "s": 9530, "text": "himanshu77" }, { "code": null, "e": 9553, "s": 9541, "text": "29AjayKumar" }, { "code": null, "e": 9567, "s": 9553, "text": "divyesh072019" }, { "code": null, "e": 9585, "s": 9567, "text": "divyeshrabadiya07" }, { "code": null, "e": 9594, "s": 9585, "text": "mukesh07" }, { "code": null, "e": 9603, "s": 9594, "text": "suresh07" }, { "code": null, "e": 9618, "s": 9603, "text": "tausifsiddiqui" }, { "code": null, "e": 9635, "s": 9618, "text": "pattern-printing" }, { "code": null, "e": 9663, "s": 9635, "text": "Permutation and Combination" }, { "code": null, "e": 9670, "s": 9663, "text": "series" }, { "code": null, "e": 9694, "s": 9670, "text": "Competitive Programming" }, { "code": null, "e": 9707, "s": 9694, "text": "Mathematical" }, { "code": null, "e": 9717, "s": 9707, "text": "Recursion" }, { "code": null, "e": 9730, "s": 9717, "text": "Mathematical" }, { "code": null, "e": 9747, "s": 9730, "text": "pattern-printing" }, { "code": null, "e": 9757, "s": 9747, "text": "Recursion" }, { "code": null, "e": 9764, "s": 9757, "text": "series" }, { "code": null, "e": 9862, "s": 9764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9896, "s": 9862, "text": "Most important type of Algorithms" }, { "code": null, "e": 9934, "s": 9896, "text": "The Ultimate Beginner's Guide For DSA" }, { "code": null, "e": 9974, "s": 9934, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 10009, "s": 9974, "text": "Equal Sum and XOR of three Numbers" }, { "code": null, "e": 10068, "s": 10009, "text": "C++: Methods of code shortening in competitive programming" }, { "code": null, "e": 10098, "s": 10068, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 10141, "s": 10098, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 10201, "s": 10141, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 10216, "s": 10201, "text": "C++ Data Types" } ]
How to create a responsive Modal Sign-Up form for a Website?
14 Aug, 2020 Follow the steps to create a responsive sign up form using CSS.Step 1:Adding HTML Use a “form” element to process the input.Then add inputs (with a matching label) for each fieldStep 2:Adding CSS Add the required CSS to design the login page try to keep the design as simple as possible.Input: html <!DOCTYPE html><html><style> /*add full-width input fields*/ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 2px solid #ccc; box-sizing: border-box; } /* set a style for all buttons*/ button { background-color: Green; color: white; padding: 15px 20px; margin: 8px 0; cursor: pointer; width: 100%; } /*set styles for the cancel button*/ .cancelbtn { padding: 15px 20px; background-color: #FF2E00; } /*float cancel and signup buttons and add an equal width*/ .cancelbtn, .signupbtn { float: left; width: 50%; } /*add padding to container elements*/ .container { padding: 16px; } /*clear floats*/ .clearfix::after { content: ""; clear: both; display: table; } /*styles for cancel button and signup button on extra small screens*/ @media screen and (max-width: 300px) { .cancelbtn, .signupbtn { width: 100%; } }</style> <body> <h2>Signup Form</h2> <!--Step 1:Adding HTML--> <form action="/action_page.php" style="border:1px solid #ccc"> <div class="container"> <label><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <label><b>Repeat Password</b></label> <input type="password" placeholder="Repeat Password" name="psw-repeat" required> <input type="checkbox" checked="checked"> Remember me <p>To create an account you have to agree our <a href="#">Terms & Privacy</a>.</p> <div class="clearfix"> <button type="button" class="cancelbtn">Cancel</button> <button type="submit" class="signupbtn">Sign Up</button> </div> </div> </form> </body> </html> Output: Follow the steps to create a responsive Modal Sign Up pageStep 1: Adding HTML. Use a “form” element to process the input. Then add inputs (with a matching label) for each field.Step 2:Adding CSS. Using the same CSS as the above example with certain Modal modifications:Input: html <!DOCTYPE html><html><style> /*add full-width input fields*/ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 2px solid #ccc; box-sizing: border-box; } /* set a style for all buttons*/ button { background-color: green; color: white; padding: 14px 20px; margin: 8px 0; cursor: pointer; width: 100%; } /*set styles for the cancel button*/ .cancelbtn { padding: 14px 20px; background-color: #FF2E00; } /*float cancel and signup buttons and add an equal width*/ .cancelbtn, .signupbtn { float: left; width: 50% } /*add padding to container elements*/ .container { padding: 16px; } /*define the modal’s background*/ .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); padding-top: 60px; } /*define the modal-content background*/ .modal-content { background-color: #fefefe; margin: 5% auto 15% auto; border: 1px solid #888; width: 80%; } /*define the close button*/ .close { position: absolute; right: 35px; top: 15px; color: #000; font-size: 40px; font-weight: bold; } /*define the close hover and focus effects*/ .close:hover, .close:focus { color: red; cursor: pointer; } .clearfix::after { content: ""; clear: both; display: table; } @media screen and (max-width: 300px) { .cancelbtn, .signupbtn { width: 100%; } }</style> <body> <h2>Modal Signup Form</h2> <!--Step 1:Adding HTML--> <button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Sign Up</button> <div id="id01" class="modal"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span> <form class="modal-content animate" action="/action_page.php"> <div class="container"> <label><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <label><b>Repeat Password</b></label> <input type="password" placeholder="Repeat Password" name="psw-repeat" required> <input type="checkbox"> Remember me <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p> <div class="clearfix"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button> <button type="submit" class="signupbtn">Sign Up</button> </div> </div> </form> </div> <!--close the modal by just clicking outside of the modal--> <script> var modal = document.getElementById('id01'); window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> </html> Output: iamdhavalparmar HTML-Misc javascript-form HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Aug, 2020" }, { "code": null, "e": 350, "s": 54, "text": "Follow the steps to create a responsive sign up form using CSS.Step 1:Adding HTML Use a “form” element to process the input.Then add inputs (with a matching label) for each fieldStep 2:Adding CSS Add the required CSS to design the login page try to keep the design as simple as possible.Input: " }, { "code": null, "e": 355, "s": 350, "text": "html" }, { "code": "<!DOCTYPE html><html><style> /*add full-width input fields*/ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 2px solid #ccc; box-sizing: border-box; } /* set a style for all buttons*/ button { background-color: Green; color: white; padding: 15px 20px; margin: 8px 0; cursor: pointer; width: 100%; } /*set styles for the cancel button*/ .cancelbtn { padding: 15px 20px; background-color: #FF2E00; } /*float cancel and signup buttons and add an equal width*/ .cancelbtn, .signupbtn { float: left; width: 50%; } /*add padding to container elements*/ .container { padding: 16px; } /*clear floats*/ .clearfix::after { content: \"\"; clear: both; display: table; } /*styles for cancel button and signup button on extra small screens*/ @media screen and (max-width: 300px) { .cancelbtn, .signupbtn { width: 100%; } }</style> <body> <h2>Signup Form</h2> <!--Step 1:Adding HTML--> <form action=\"/action_page.php\" style=\"border:1px solid #ccc\"> <div class=\"container\"> <label><b>Email</b></label> <input type=\"text\" placeholder=\"Enter Email\" name=\"email\" required> <label><b>Password</b></label> <input type=\"password\" placeholder=\"Enter Password\" name=\"psw\" required> <label><b>Repeat Password</b></label> <input type=\"password\" placeholder=\"Repeat Password\" name=\"psw-repeat\" required> <input type=\"checkbox\" checked=\"checked\"> Remember me <p>To create an account you have to agree our <a href=\"#\">Terms & Privacy</a>.</p> <div class=\"clearfix\"> <button type=\"button\" class=\"cancelbtn\">Cancel</button> <button type=\"submit\" class=\"signupbtn\">Sign Up</button> </div> </div> </form> </body> </html>", "e": 2465, "s": 355, "text": null }, { "code": null, "e": 2475, "s": 2465, "text": "Output: " }, { "code": null, "e": 2753, "s": 2475, "text": "Follow the steps to create a responsive Modal Sign Up pageStep 1: Adding HTML. Use a “form” element to process the input. Then add inputs (with a matching label) for each field.Step 2:Adding CSS. Using the same CSS as the above example with certain Modal modifications:Input: " }, { "code": null, "e": 2758, "s": 2753, "text": "html" }, { "code": "<!DOCTYPE html><html><style> /*add full-width input fields*/ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 2px solid #ccc; box-sizing: border-box; } /* set a style for all buttons*/ button { background-color: green; color: white; padding: 14px 20px; margin: 8px 0; cursor: pointer; width: 100%; } /*set styles for the cancel button*/ .cancelbtn { padding: 14px 20px; background-color: #FF2E00; } /*float cancel and signup buttons and add an equal width*/ .cancelbtn, .signupbtn { float: left; width: 50% } /*add padding to container elements*/ .container { padding: 16px; } /*define the modal’s background*/ .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); padding-top: 60px; } /*define the modal-content background*/ .modal-content { background-color: #fefefe; margin: 5% auto 15% auto; border: 1px solid #888; width: 80%; } /*define the close button*/ .close { position: absolute; right: 35px; top: 15px; color: #000; font-size: 40px; font-weight: bold; } /*define the close hover and focus effects*/ .close:hover, .close:focus { color: red; cursor: pointer; } .clearfix::after { content: \"\"; clear: both; display: table; } @media screen and (max-width: 300px) { .cancelbtn, .signupbtn { width: 100%; } }</style> <body> <h2>Modal Signup Form</h2> <!--Step 1:Adding HTML--> <button onclick=\"document.getElementById('id01').style.display='block'\" style=\"width:auto;\">Sign Up</button> <div id=\"id01\" class=\"modal\"> <span onclick=\"document.getElementById('id01').style.display='none'\" class=\"close\" title=\"Close Modal\">×</span> <form class=\"modal-content animate\" action=\"/action_page.php\"> <div class=\"container\"> <label><b>Email</b></label> <input type=\"text\" placeholder=\"Enter Email\" name=\"email\" required> <label><b>Password</b></label> <input type=\"password\" placeholder=\"Enter Password\" name=\"psw\" required> <label><b>Repeat Password</b></label> <input type=\"password\" placeholder=\"Repeat Password\" name=\"psw-repeat\" required> <input type=\"checkbox\"> Remember me <p>By creating an account you agree to our <a href=\"#\">Terms & Privacy</a>.</p> <div class=\"clearfix\"> <button type=\"button\" onclick=\"document.getElementById('id01').style.display='none'\" class=\"cancelbtn\">Cancel</button> <button type=\"submit\" class=\"signupbtn\">Sign Up</button> </div> </div> </form> </div> <!--close the modal by just clicking outside of the modal--> <script> var modal = document.getElementById('id01'); window.onclick = function(event) { if (event.target == modal) { modal.style.display = \"none\"; } } </script> </body> </html>", "e": 6266, "s": 2758, "text": null }, { "code": null, "e": 6275, "s": 6266, "text": "Output: " }, { "code": null, "e": 6295, "s": 6279, "text": "iamdhavalparmar" }, { "code": null, "e": 6305, "s": 6295, "text": "HTML-Misc" }, { "code": null, "e": 6321, "s": 6305, "text": "javascript-form" }, { "code": null, "e": 6326, "s": 6321, "text": "HTML" }, { "code": null, "e": 6343, "s": 6326, "text": "Web Technologies" }, { "code": null, "e": 6348, "s": 6343, "text": "HTML" } ]
C Program for Tower of Hanoi
16 Jun, 2022 Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. C #include <stdio.h> // C recursive function to solve tower of hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod){ if (n == 1) { printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); return; } towerOfHanoi(n-1, from_rod, aux_rod, to_rod); printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); towerOfHanoi(n-1, aux_rod, to_rod, from_rod);} int main(){ int n = 4; // Number of disks towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods return 0;} Output: Move disk 1 from rod A to rod B Move disk 2 from rod A to rod C Move disk 1 from rod B to rod C Move disk 3 from rod A to rod B Move disk 1 from rod C to rod A Move disk 2 from rod C to rod B Move disk 1 from rod A to rod B Move disk 4 from rod A to rod C Move disk 1 from rod B to rod C Move disk 2 from rod B to rod A Move disk 1 from rod C to rod A Move disk 3 from rod B to rod C Move disk 1 from rod A to rod B Move disk 2 from rod A to rod C Move disk 1 from rod B to rod C Time Complexity: O(2n) Auxiliary Space: O(n) Please refer complete article on Program for Tower of Hanoi for more details! chandramauliguptach C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File How to return multiple values from a function in C or C++? C++ Program to check Prime Number Producer Consumer Problem in C C Program to Swap two Numbers How to Append a Character to a String in C C program to sort an array in ascending order Program to find Prime Numbers Between given Interval Set, Clear and Toggle a given bit of a number in C
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 486, "s": 28, "text": "Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. " }, { "code": null, "e": 488, "s": 486, "text": "C" }, { "code": "#include <stdio.h> // C recursive function to solve tower of hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod){ if (n == 1) { printf(\"\\n Move disk 1 from rod %c to rod %c\", from_rod, to_rod); return; } towerOfHanoi(n-1, from_rod, aux_rod, to_rod); printf(\"\\n Move disk %d from rod %c to rod %c\", n, from_rod, to_rod); towerOfHanoi(n-1, aux_rod, to_rod, from_rod);} int main(){ int n = 4; // Number of disks towerOfHanoi(n, \\'A\\', \\'C\\', \\'B\\'); // A, B and C are names of rods return 0;}", "e": 1047, "s": 488, "text": null }, { "code": null, "e": 1055, "s": 1047, "text": "Output:" }, { "code": null, "e": 1550, "s": 1055, "text": " Move disk 1 from rod A to rod B\n Move disk 2 from rod A to rod C\n Move disk 1 from rod B to rod C\n Move disk 3 from rod A to rod B\n Move disk 1 from rod C to rod A\n Move disk 2 from rod C to rod B\n Move disk 1 from rod A to rod B\n Move disk 4 from rod A to rod C\n Move disk 1 from rod B to rod C\n Move disk 2 from rod B to rod A\n Move disk 1 from rod C to rod A\n Move disk 3 from rod B to rod C\n Move disk 1 from rod A to rod B\n Move disk 2 from rod A to rod C\n Move disk 1 from rod B to rod C" }, { "code": null, "e": 1573, "s": 1550, "text": "Time Complexity: O(2n)" }, { "code": null, "e": 1595, "s": 1573, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 1673, "s": 1595, "text": "Please refer complete article on Program for Tower of Hanoi for more details!" }, { "code": null, "e": 1693, "s": 1673, "text": "chandramauliguptach" }, { "code": null, "e": 1704, "s": 1693, "text": "C Programs" }, { "code": null, "e": 1802, "s": 1704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1837, "s": 1802, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 1878, "s": 1837, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 1937, "s": 1878, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 1971, "s": 1937, "text": "C++ Program to check Prime Number" }, { "code": null, "e": 2002, "s": 1971, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 2032, "s": 2002, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 2075, "s": 2032, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 2121, "s": 2075, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 2174, "s": 2121, "text": "Program to find Prime Numbers Between given Interval" } ]
Getting screen’s height and width using Tkinter | Python
14 Sep, 2021 Tkinter provides some methods with the help of which we can get the current screen height and width.Following methods can be used to decide height and width : winfo_screenheight() // Returns screen height in pixels winfo_screenmmheight() // Returns screen height in mm winfo_screenwidth() // Returns screen width in pixels winfo_screenmmwidth() // Returns screen width in mm Code #1: Getting height and width in pixels. Python3 # importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # getting screen's height in pixelsheight = root.winfo_screenheight() # getting screen's width in pixelswidth = root.winfo_screenwidth() print("\n width x height = %d x %d (in pixels)\n" %(width, height))# infinite loopmainloop() Output: Code #2: Getting height and width in mm. Python3 # importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # getting screen's height in mmheight = root.winfo_screenmmheight() # getting screen's width in mmwidth = root.winfo_screenmmwidth() print("\n width x height = %d x %d (in mm)\n" %(width, height))# infinite loopmainloop() Output: gopikumarkaushik9065 Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 188, "s": 28, "text": "Tkinter provides some methods with the help of which we can get the current screen height and width.Following methods can be used to decide height and width : " }, { "code": null, "e": 407, "s": 188, "text": "winfo_screenheight() // Returns screen height in pixels\n\nwinfo_screenmmheight() // Returns screen height in mm\n\nwinfo_screenwidth() // Returns screen width in pixels\n\nwinfo_screenmmwidth() // Returns screen width in mm" }, { "code": null, "e": 456, "s": 407, "text": " Code #1: Getting height and width in pixels. " }, { "code": null, "e": 464, "s": 456, "text": "Python3" }, { "code": "# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # getting screen's height in pixelsheight = root.winfo_screenheight() # getting screen's width in pixelswidth = root.winfo_screenwidth() print(\"\\n width x height = %d x %d (in pixels)\\n\" %(width, height))# infinite loopmainloop()", "e": 805, "s": 464, "text": null }, { "code": null, "e": 815, "s": 805, "text": "Output: " }, { "code": null, "e": 860, "s": 815, "text": " Code #2: Getting height and width in mm. " }, { "code": null, "e": 868, "s": 860, "text": "Python3" }, { "code": "# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # getting screen's height in mmheight = root.winfo_screenmmheight() # getting screen's width in mmwidth = root.winfo_screenmmwidth() print(\"\\n width x height = %d x %d (in mm)\\n\" %(width, height))# infinite loopmainloop()", "e": 1201, "s": 868, "text": null }, { "code": null, "e": 1211, "s": 1201, "text": "Output: " }, { "code": null, "e": 1234, "s": 1213, "text": "gopikumarkaushik9065" }, { "code": null, "e": 1245, "s": 1234, "text": "Python-gui" }, { "code": null, "e": 1260, "s": 1245, "text": "Python-tkinter" }, { "code": null, "e": 1267, "s": 1260, "text": "Python" }, { "code": null, "e": 1365, "s": 1267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1383, "s": 1365, "text": "Python Dictionary" }, { "code": null, "e": 1425, "s": 1383, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1460, "s": 1425, "text": "Read a file line by line in Python" }, { "code": null, "e": 1486, "s": 1460, "text": "Python String | replace()" }, { "code": null, "e": 1518, "s": 1486, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1547, "s": 1518, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1574, "s": 1547, "text": "Python Classes and Objects" }, { "code": null, "e": 1610, "s": 1574, "text": "Convert integer to string in Python" }, { "code": null, "e": 1641, "s": 1610, "text": "Python | os.path.join() method" } ]
Data Structures | Heap | Question 12
28 Jun, 2021 The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given order into a Max Heap. The resultant Max Heap is. (A) a(B) b(C) c(D) dAnswer: (A)Explanation: 32, 15, 20, 30, 12, 25, 16 After insertion of 32, 15 and 20 32 / \ 15 20 After insertion of 30 32 / \ 15 20 / 30 Max Heap property is violated, so 30 is swapped with 15 32 / \ 30 20 / 15 After insertion of 12 32 / \ 30 20 / \ 15 12 After insertion of 25 32 / \ 30 20 / \ / 15 12 25 Max Heap property is violated, so 25 is swapped with 20 32 / \ 30 25 / \ / 15 12 20 After insertion of 16 32 / \ 30 25 / \ / \ 15 12 20 16 Quiz of this Question Data Structures Data Structures-Heap Heap Quizzes Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 155, "s": 28, "text": "The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given order into a Max Heap. The resultant Max Heap is." }, { "code": null, "e": 199, "s": 155, "text": "(A) a(B) b(C) c(D) dAnswer: (A)Explanation:" }, { "code": null, "e": 936, "s": 199, "text": "32, 15, 20, 30, 12, 25, 16 \n\nAfter insertion of 32, 15 and 20\n 32\n / \\\n 15 20\n \nAfter insertion of 30\n 32\n / \\\n 15 20\n /\n 30\nMax Heap property is violated, so 30 is swapped with 15\n 32\n / \\\n 30 20\n /\n 15\n\nAfter insertion of 12\n 32\n / \\\n 30 20\n / \\\n 15 12\n\nAfter insertion of 25\n 32\n / \\\n 30 20\n / \\ /\n 15 12 25\nMax Heap property is violated, so 25 is swapped with 20\n 32\n / \\\n 30 25\n / \\ /\n 15 12 20\n\n\nAfter insertion of 16\n 32\n / \\\n 30 25\n / \\ / \\\n 15 12 20 16 \n" }, { "code": null, "e": 958, "s": 936, "text": "Quiz of this Question" }, { "code": null, "e": 974, "s": 958, "text": "Data Structures" }, { "code": null, "e": 995, "s": 974, "text": "Data Structures-Heap" }, { "code": null, "e": 1008, "s": 995, "text": "Heap Quizzes" }, { "code": null, "e": 1024, "s": 1008, "text": "Data Structures" }, { "code": null, "e": 1040, "s": 1024, "text": "Data Structures" } ]
Swap every two bits in bytes
22 May, 2022 Swap all the pair of bits in a byte. Before swapping: 11-10-11-01 After swapping: 11-01-11-10Examples: Input : 00000010 Output : 00000001 Input : 00000100 Output : 00001000 Approach: x = ((x & 0x55555555) >> 1) | ((x & 0xAAAAAAAA) <> 1 extracts the high bit position and shifts it to the low bit position. Similarly the expression (x & 0xAAAAAAAA) << 1 extracts the low bit from each pair and shifts it to the high bit position. The two parts are then combined using bitwise-OR. x= 00011010 ((x & 0xAAAAAAAA) >> 1) = 00001010 >> 1 = 00000101 ((x & 0x55555555) << 1) = 00010000 <> 1) | ((x & 0x55555555) << 1) = 00100101 Below is the implementation of the above idea: C++ Java Python3 C# PHP Javascript // C++ program to swap every two bits in a byte.#include<bits/stdc++.h>using namespace std; unsigned int swapBitsInPair(unsigned int x){ // Extracting the high bit shift it to lowbit // Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); } /* Driver function to test above function */int main(){ unsigned int x = 4; cout << swapBitsInPair(x); return 0;} // This code is contributed by Kasina Dheeraj. // Java program to swap every// two bits in a byte.import java.util.*; class GFG{ static int swapBitsInPair( int x) { // Extracting the high bit shift it to lowbit // Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); } // Driver Function public static void main(String[] args) { int x = 4; System.out.print(swapBitsInPair(x)); }} // This code is contributed by Gitanjali. # Python program to swap every# two bits in a byte. import math def swapBitsInPair( x): # Extracting the high bit shift it to lowbit # Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) or ((x & 0x55555555) << 1) # driver Functionx = 4;print(swapBitsInPair(x)) # This code is contributed by Gitanjali. // C# program to swap every two bits in a byte.using System; public class GFG{ static uint swapBitsInPair(uint x) { // Extracting the high bit shift it to lowbit // Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); } // Driver function to test above function static public void Main () { uint x = 4; Console.WriteLine(swapBitsInPair(x)); }} // This code is contributed by vt_m. <?php// PHP program to swap every// two bits in a byte. function swapBitsInPair($x){ // Extracting the high bit // shift it to lowbit // Extracting the low bit // shift it to highbit return (($x & 0xAAAAAAAA) >> 1) | (($x & 0x55555555) << 1);} // Driver Code $x = 4; echo swapBitsInPair($x); // This code is contributed by mits?> <script> // java script program to swap every// two bits in a byte. function swapBitsInPair(x){ // Extracting the high bit // shift it to lowbit // Extracting the low bit // shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1);} // Driver Code let x = 4; document.write( swapBitsInPair(x)); // This code is contributed by sravan kumar</script> Output: 8 Time Complexity: O(1) Space Complexity: O(1) Reference: https://stackoverflow.com/questions/4788799/swap-every-pair-of-bits-in-byte This article is contributed by Saumya and improved by Kasina Dheeraj .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar sravankumar8128 dheerukd2002 Cisco Bit Magic Cisco Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) Divide two integers without using multiplication, division and mod operator Bit Fields in C Add two numbers without using arithmetic operators Find the element that appears once C++ bitset and its application Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2 Count total set bits in all numbers from 1 to n Set, Clear and Toggle a given bit of a number in C Position of rightmost set bit
[ { "code": null, "e": 54, "s": 26, "text": "\n22 May, 2022" }, { "code": null, "e": 159, "s": 54, "text": "Swap all the pair of bits in a byte. Before swapping: 11-10-11-01 After swapping: 11-01-11-10Examples: " }, { "code": null, "e": 232, "s": 159, "text": "Input : 00000010\nOutput : 00000001\n\nInput : 00000100\nOutput : 00001000" }, { "code": null, "e": 542, "s": 234, "text": "Approach: x = ((x & 0x55555555) >> 1) | ((x & 0xAAAAAAAA) <> 1 extracts the high bit position and shifts it to the low bit position. Similarly the expression (x & 0xAAAAAAAA) << 1 extracts the low bit from each pair and shifts it to the high bit position. The two parts are then combined using bitwise-OR. " }, { "code": null, "e": 707, "s": 542, "text": "x= 00011010\n((x & 0xAAAAAAAA) >> 1) = 00001010 >> 1\n = 00000101\n((x & 0x55555555) << 1) = 00010000 <> 1) | ((x & 0x55555555) << 1) = 00100101" }, { "code": null, "e": 756, "s": 707, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 760, "s": 756, "text": "C++" }, { "code": null, "e": 765, "s": 760, "text": "Java" }, { "code": null, "e": 773, "s": 765, "text": "Python3" }, { "code": null, "e": 776, "s": 773, "text": "C#" }, { "code": null, "e": 780, "s": 776, "text": "PHP" }, { "code": null, "e": 791, "s": 780, "text": "Javascript" }, { "code": "// C++ program to swap every two bits in a byte.#include<bits/stdc++.h>using namespace std; unsigned int swapBitsInPair(unsigned int x){ // Extracting the high bit shift it to lowbit // Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); } /* Driver function to test above function */int main(){ unsigned int x = 4; cout << swapBitsInPair(x); return 0;} // This code is contributed by Kasina Dheeraj.", "e": 1275, "s": 791, "text": null }, { "code": "// Java program to swap every// two bits in a byte.import java.util.*; class GFG{ static int swapBitsInPair( int x) { // Extracting the high bit shift it to lowbit // Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); } // Driver Function public static void main(String[] args) { int x = 4; System.out.print(swapBitsInPair(x)); }} // This code is contributed by Gitanjali.", "e": 1762, "s": 1275, "text": null }, { "code": "# Python program to swap every# two bits in a byte. import math def swapBitsInPair( x): # Extracting the high bit shift it to lowbit # Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) or ((x & 0x55555555) << 1) # driver Functionx = 4;print(swapBitsInPair(x)) # This code is contributed by Gitanjali.", "e": 2097, "s": 1762, "text": null }, { "code": "// C# program to swap every two bits in a byte.using System; public class GFG{ static uint swapBitsInPair(uint x) { // Extracting the high bit shift it to lowbit // Extracting the low bit shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); } // Driver function to test above function static public void Main () { uint x = 4; Console.WriteLine(swapBitsInPair(x)); }} // This code is contributed by vt_m.", "e": 2618, "s": 2097, "text": null }, { "code": "<?php// PHP program to swap every// two bits in a byte. function swapBitsInPair($x){ // Extracting the high bit // shift it to lowbit // Extracting the low bit // shift it to highbit return (($x & 0xAAAAAAAA) >> 1) | (($x & 0x55555555) << 1);} // Driver Code $x = 4; echo swapBitsInPair($x); // This code is contributed by mits?>", "e": 2988, "s": 2618, "text": null }, { "code": "<script> // java script program to swap every// two bits in a byte. function swapBitsInPair(x){ // Extracting the high bit // shift it to lowbit // Extracting the low bit // shift it to highbit return ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1);} // Driver Code let x = 4; document.write( swapBitsInPair(x)); // This code is contributed by sravan kumar</script>", "e": 3396, "s": 2988, "text": null }, { "code": null, "e": 3406, "s": 3396, "text": "Output: " }, { "code": null, "e": 3408, "s": 3406, "text": "8" }, { "code": null, "e": 3430, "s": 3408, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3453, "s": 3430, "text": "Space Complexity: O(1)" }, { "code": null, "e": 3540, "s": 3453, "text": "Reference: https://stackoverflow.com/questions/4788799/swap-every-pair-of-bits-in-byte" }, { "code": null, "e": 3865, "s": 3540, "text": "This article is contributed by Saumya and improved by Kasina Dheeraj .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3991, "s": 3865, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4004, "s": 3991, "text": "Mithun Kumar" }, { "code": null, "e": 4020, "s": 4004, "text": "sravankumar8128" }, { "code": null, "e": 4033, "s": 4020, "text": "dheerukd2002" }, { "code": null, "e": 4039, "s": 4033, "text": "Cisco" }, { "code": null, "e": 4049, "s": 4039, "text": "Bit Magic" }, { "code": null, "e": 4055, "s": 4049, "text": "Cisco" }, { "code": null, "e": 4065, "s": 4055, "text": "Bit Magic" }, { "code": null, "e": 4163, "s": 4065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4201, "s": 4163, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 4277, "s": 4201, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 4293, "s": 4277, "text": "Bit Fields in C" }, { "code": null, "e": 4344, "s": 4293, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 4379, "s": 4344, "text": "Find the element that appears once" }, { "code": null, "e": 4410, "s": 4379, "text": "C++ bitset and its application" }, { "code": null, "e": 4498, "s": 4410, "text": "Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2" }, { "code": null, "e": 4546, "s": 4498, "text": "Count total set bits in all numbers from 1 to n" }, { "code": null, "e": 4597, "s": 4546, "text": "Set, Clear and Toggle a given bit of a number in C" } ]