title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java Regex - Character Class [a-zA-Z] Match
The character class [a-zA-Z] matches any character from a to z or A to Z. The following example shows the usage of character class matching. package com.tutorialspoint; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CharacterClassDemo { private static final String REGEX = "[a-zA-Z]"; private static final String INPUT = "dbcabca124ADCbc"; public static void main(String[] args) { // create a pattern Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); while(matcher.find()) { //Prints the start index of the match. System.out.println("Match String start(): "+matcher.start()); } } } Let us compile and run the above program, this will produce the following result − Match String start(): 0 Match String start(): 1 Match String start(): 2 Match String start(): 3 Match String start(): 4 Match String start(): 5 Match String start(): 6 Match String start(): 10 Match String start(): 11 Match String start(): 12 Match String start(): 13 Match String start(): 14 Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 2124, "text": "The character class [a-zA-Z] matches any character from a to z or A to Z." }, { "code": null, "e": 2265, "s": 2198, "text": "The following example shows the usage of character class matching." }, { "code": null, "e": 2873, "s": 2265, "text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CharacterClassDemo {\n private static final String REGEX = \"[a-zA-Z]\";\n private static final String INPUT = \"dbcabca124ADCbc\";\n\n public static void main(String[] args) {\n // create a pattern\n Pattern pattern = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT); \n\n while(matcher.find()) {\n //Prints the start index of the match.\n System.out.println(\"Match String start(): \"+matcher.start());\n }\n }\n}" }, { "code": null, "e": 2956, "s": 2873, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3250, "s": 2956, "text": "Match String start(): 0\nMatch String start(): 1\nMatch String start(): 2\nMatch String start(): 3\nMatch String start(): 4\nMatch String start(): 5\nMatch String start(): 6\nMatch String start(): 10\nMatch String start(): 11\nMatch String start(): 12\nMatch String start(): 13\nMatch String start(): 14\n" }, { "code": null, "e": 3257, "s": 3250, "text": " Print" }, { "code": null, "e": 3268, "s": 3257, "text": " Add Notes" } ]
Building a Facial Recognition Model using PCA & SVM Algorithms | by Mahnoor Javed | Towards Data Science
In this article, we will learn to use Principal Component Analysis and Support Vector Machines for building a facial recognition model. First, let us understand what PCA and SVM are: Principal Component Analysis (PCA) is a machine learning algorithm that is widely used in exploratory data analysis and for making predictive models. It is commonly used for dimensionality reduction by projecting each data point onto only the first few principal components to obtain lower-dimensional data while preserving as much of the data’s variation as possible. Matt Brems’s article provides a comprehensive in-depth of the algorithm. For now, let us understand the algorithm in easier terms: Suppose we have a problem at hand for which we are collecting data. Our dataset results in several variables, many features, all of which affect the results in different aspects. We may choose to eliminate certain features, but that would mean losing information, and we don't want that, right? So another method of reducing the number of features (reducing data dimensionality) is to create new features by extracting the important information and dropping the least important ones. In this way, our information will not be lost and we will have reduced features, and there will be fewer chances of overfitting our model. Support Vector Machine (SVM) is a supervised machine learning model used for two-group classification problems. After giving an SVM model set of labeled training data for each category, they’re able to categorize new test data. SVM classifies data based on the plane that maximizes the margin. The SVM decision boundary is straight. SVM is a really good algorithm for image classification. Experimental results show that SVMs achieve significantly higher search accuracy than traditional query refinement schemes after just three to four rounds of relevance feedback. This is also true for image segmentation systems, including those using a modified version SVM that uses the privileged approach. Marco Peixeiro’s article explains the need to have a maximal margin hyperplane to classify the data. Give it a read, you’ll understand SVMs better! Faces are high dimensionality data consisting of a number of pixels. Data in high dimensionality is difficult to process and cannot be visualized using simple techniques like scatterplots for 2-dimensional data. What we will do is to use PCA to reduce the high dimensionality of data and then feed it into the SVM classifier to classify the pictures. Let us jump to the coding segment! The following code example is taken from the sklearn documentation on eigenfaces. We will go through the code step by step to understand its intricacies and results. First off, we will import the required libraries and modules. An in-depth discussion of why we are importing them will follow when their needs arise. import pylab as plimport numpy as npfrom matplotlib import pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import fetch_lfw_peoplefrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrixfrom sklearn.decomposition import PCA as RandomizedPCAfrom sklearn.svm import SVC Next, we will download the data into the disk and load it as NumPy arrays using fetch_lfw_people from sklearn.datasets: lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) The lfw dataset consists of a database of face photographs designed for studying the problem of unconstrained face recognition. The data set contains more than 13,000 images of faces collected from the web. Each face has been labeled with the name of the person pictured. 1680 of the people pictured have two or more distinct photos in the data set. The images are in grayscale (pixel values = 0 — 255). Next, we will introspect the image arrays to find the shape of the pictures. We will use the NumPy shape attribute that returns a tuple with each index having the number of corresponding elements. n_samples, h, w = lfw_people.images.shapenp.random.seed(42) As can be seen from the variable explorer, we have 1288 samples (pictures) with a height of 50 px and a width of 37 px (50 x 37 = 1850 features) We will use the data arrays in the lfw_people utils.Bunch directly and store it in X. We will use this data in our further processing. X = lfw_people.datan_features = X.shape[1] The data in X has 1288 samples and 1850 features for each sample. Next, we will define the labels which are the id of the person to whom the picture belongs. y = lfw_people.targettarget_names = lfw_people.target_namesn_classes = target_names.shape[0] Here, y represents the target which is the label of each picture. The label is further defined by the target_names variable which consists of the 7 names of the people to be identified. target is a 1288x1 NumPy array that contains the values 0–6 of the name the 1288 pictures corresponds to. So if the id 0 has a target value of 5, it would refer to “Hugo Chavez”, as depicted in the target_names: Hence, y is the target in numerical form, target_names is any of the target/labels by the name, and n_classes is the variable that stores the number of classes we have, in our case, we have 7: Ariel SharonColin PowellDonald RumsfeldGeorge W BushGerhard SchröderHugo ChavezTony Blair Ariel Sharon Colin Powell Donald Rumsfeld George W Bush Gerhard Schröder Hugo Chavez Tony Blair Let us print out the variables: print("Total dataset size:")print("n_samples: %d", n_samples)print("n_features: %d", n_features)print("n_classes: %d", n_classes) So, we have 1288 samples (pictures), a total of 1850 features for each sample (50px x 37px) and 7 classes (the people). Next, we will use the train_test_split module from sklearn.model_selection and split the data (X-features and y-labels)into training data and testing data, with 25% of the data used for testing and the remaining 75% to train the model. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) Here are the variables X-train, X_test, y_train & y_test: Now, we will use PCA from sklearn.decomposition to select the top components to train the model. We have already imported PCA as RandomizedPCA in the first block of code. In our case, we have a total of 966 features in the training set X_train , and we will reduce them to 50 using PCA (dimensionality reduction): n_components = 50pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train) This process takes less than a second, which can be verified using the time function (let us skip that for now). Now we will reshape our PCA components and define eigenfaces, which is the name given to a set of eigenvectors when used in the computer vision problem of human face recognition: eigenfaces = pca.components_.reshape((n_components, h, w)) As the screenshot shows, the eigenfaces is a 50 x 50 x 37 NumPy array. The first 50 corresponds to the number of features, the n_components that we initialized a while back, and into which our PCA algorithm reduced to. The image dimensions in the eigenfaces are 50 x 37. Next, we will use PCA’s transform on both X_train and X_test to reduce the dimensionality. X_train_pca = pca.transform(X_train)X_test_pca = pca.transform(X_test) As can be seen in the screenshot above, the dimensionality of both X_train and X_test were reduced through the PCA algorithm. Each had the features reduced from 1850 to 50 (as we defined in the algorithm). Once we’re done with dimensionality reduction, we will now move towards classification. First, we will train the SVM Classification model. We will use GridSearchCV, a library function that is an approach to hyperparameter tuning. It will methodically build and evaluate a model for each combination of algorithm parameters specified in a grid, and return the best estimator in clf.best_estimator. The parameters are given in the param_grid: print("Fitting the classifier to the training set")param_grid = { 'C': [1e3, 5e3, 1e4, 5e4, 1e5], 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)clf = clf.fit(X_train_pca, y_train)print("Best estimator found by grid search:")print(clf.best_estimator_) The best classifier for our data is SVC with the following parameters: SVC(C=1000, class_weight = ‘balanced’, gamma=0.01) Let us now predict the people's names on the test data. We will use the classifier which we found from GridSearchCV and which we had already fit on the training data. print("Predicting the people names on the testing set")y_pred = clf.predict(X_test_pca) Once the predictions are made, let us print the Classification Report which will display the precision, recall, F1-score, and support scores for the model. This gives a deeper intuition of the classifier’s behavior. print(classification_report(y_test, y_pred, target_names=target_names)) Let us print the Confusion Matrix as well: print(confusion_matrix(y_test, y_pred, labels=range(n_classes))) The Confusion Matrix prints the values of True Positives, False Positives, and False Negatives and gives an overview of how the classifier is. In the above example, Finally, we will plot both the portraits of the people as well as the eigenfaces! We will define 2 functions: title to plot the result of the prediction on a portion of the test set, and plot_gallery to evaluate the prediction by plotting them: def title(y_pred, y_test, target_names, i): pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1] true_name = target_names[y_test[i]].rsplit(' ', 1)[-1] return 'predicted: %s\ntrue: %s' % (pred_name, true_name)def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1) plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) plt.title(titles[i], size=12) plt.xticks(()) plt.yticks(()) Let us now plot the results of the prediction on a portion of the test set: prediction_titles = [title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])]plot_gallery(X_test, prediction_titles, h, w) Let us now plot the eigenfaces. We will use the eigenfaces variable which we defined in the code block above. eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]plot_gallery(eigenfaces, eigenface_titles, h, w)plt.show() Lastly, let us plot the accuracy of the PCA + SVM Model for Facial Recognition: from sklearn.metrics import accuracy_scorescore = accuracy_score(y_test, y_pred)print(score) We get an accuracy score of 0.81! While it’s not a perfect score, and there is a lot of room for improvement, facial recognition with PCA and SVM gives us a starting point for further powerful algorithms! In this article, we built a facial recognition model using PCA and SVM. The Principal Component Analysis algorithm was used to reduce the dimensions of the data we had; images having a number of pixel values! then we used SVM for classification by finding the best estimator by hyperparameter tuning. We were able to classify the portraits and got an accuracy score of 0.81. What can we do to improve accuracy? I’ll leave that to you 😃
[ { "code": null, "e": 308, "s": 172, "text": "In this article, we will learn to use Principal Component Analysis and Support Vector Machines for building a facial recognition model." }, { "code": null, "e": 355, "s": 308, "text": "First, let us understand what PCA and SVM are:" }, { "code": null, "e": 724, "s": 355, "text": "Principal Component Analysis (PCA) is a machine learning algorithm that is widely used in exploratory data analysis and for making predictive models. It is commonly used for dimensionality reduction by projecting each data point onto only the first few principal components to obtain lower-dimensional data while preserving as much of the data’s variation as possible." }, { "code": null, "e": 855, "s": 724, "text": "Matt Brems’s article provides a comprehensive in-depth of the algorithm. For now, let us understand the algorithm in easier terms:" }, { "code": null, "e": 1150, "s": 855, "text": "Suppose we have a problem at hand for which we are collecting data. Our dataset results in several variables, many features, all of which affect the results in different aspects. We may choose to eliminate certain features, but that would mean losing information, and we don't want that, right?" }, { "code": null, "e": 1478, "s": 1150, "text": "So another method of reducing the number of features (reducing data dimensionality) is to create new features by extracting the important information and dropping the least important ones. In this way, our information will not be lost and we will have reduced features, and there will be fewer chances of overfitting our model." }, { "code": null, "e": 1706, "s": 1478, "text": "Support Vector Machine (SVM) is a supervised machine learning model used for two-group classification problems. After giving an SVM model set of labeled training data for each category, they’re able to categorize new test data." }, { "code": null, "e": 2176, "s": 1706, "text": "SVM classifies data based on the plane that maximizes the margin. The SVM decision boundary is straight. SVM is a really good algorithm for image classification. Experimental results show that SVMs achieve significantly higher search accuracy than traditional query refinement schemes after just three to four rounds of relevance feedback. This is also true for image segmentation systems, including those using a modified version SVM that uses the privileged approach." }, { "code": null, "e": 2324, "s": 2176, "text": "Marco Peixeiro’s article explains the need to have a maximal margin hyperplane to classify the data. Give it a read, you’ll understand SVMs better!" }, { "code": null, "e": 2536, "s": 2324, "text": "Faces are high dimensionality data consisting of a number of pixels. Data in high dimensionality is difficult to process and cannot be visualized using simple techniques like scatterplots for 2-dimensional data." }, { "code": null, "e": 2675, "s": 2536, "text": "What we will do is to use PCA to reduce the high dimensionality of data and then feed it into the SVM classifier to classify the pictures." }, { "code": null, "e": 2710, "s": 2675, "text": "Let us jump to the coding segment!" }, { "code": null, "e": 2876, "s": 2710, "text": "The following code example is taken from the sklearn documentation on eigenfaces. We will go through the code step by step to understand its intricacies and results." }, { "code": null, "e": 3026, "s": 2876, "text": "First off, we will import the required libraries and modules. An in-depth discussion of why we are importing them will follow when their needs arise." }, { "code": null, "e": 3418, "s": 3026, "text": "import pylab as plimport numpy as npfrom matplotlib import pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import fetch_lfw_peoplefrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrixfrom sklearn.decomposition import PCA as RandomizedPCAfrom sklearn.svm import SVC" }, { "code": null, "e": 3538, "s": 3418, "text": "Next, we will download the data into the disk and load it as NumPy arrays using fetch_lfw_people from sklearn.datasets:" }, { "code": null, "e": 3605, "s": 3538, "text": "lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)" }, { "code": null, "e": 3955, "s": 3605, "text": "The lfw dataset consists of a database of face photographs designed for studying the problem of unconstrained face recognition. The data set contains more than 13,000 images of faces collected from the web. Each face has been labeled with the name of the person pictured. 1680 of the people pictured have two or more distinct photos in the data set." }, { "code": null, "e": 4009, "s": 3955, "text": "The images are in grayscale (pixel values = 0 — 255)." }, { "code": null, "e": 4206, "s": 4009, "text": "Next, we will introspect the image arrays to find the shape of the pictures. We will use the NumPy shape attribute that returns a tuple with each index having the number of corresponding elements." }, { "code": null, "e": 4266, "s": 4206, "text": "n_samples, h, w = lfw_people.images.shapenp.random.seed(42)" }, { "code": null, "e": 4411, "s": 4266, "text": "As can be seen from the variable explorer, we have 1288 samples (pictures) with a height of 50 px and a width of 37 px (50 x 37 = 1850 features)" }, { "code": null, "e": 4546, "s": 4411, "text": "We will use the data arrays in the lfw_people utils.Bunch directly and store it in X. We will use this data in our further processing." }, { "code": null, "e": 4589, "s": 4546, "text": "X = lfw_people.datan_features = X.shape[1]" }, { "code": null, "e": 4655, "s": 4589, "text": "The data in X has 1288 samples and 1850 features for each sample." }, { "code": null, "e": 4747, "s": 4655, "text": "Next, we will define the labels which are the id of the person to whom the picture belongs." }, { "code": null, "e": 4840, "s": 4747, "text": "y = lfw_people.targettarget_names = lfw_people.target_namesn_classes = target_names.shape[0]" }, { "code": null, "e": 5026, "s": 4840, "text": "Here, y represents the target which is the label of each picture. The label is further defined by the target_names variable which consists of the 7 names of the people to be identified." }, { "code": null, "e": 5238, "s": 5026, "text": "target is a 1288x1 NumPy array that contains the values 0–6 of the name the 1288 pictures corresponds to. So if the id 0 has a target value of 5, it would refer to “Hugo Chavez”, as depicted in the target_names:" }, { "code": null, "e": 5431, "s": 5238, "text": "Hence, y is the target in numerical form, target_names is any of the target/labels by the name, and n_classes is the variable that stores the number of classes we have, in our case, we have 7:" }, { "code": null, "e": 5522, "s": 5431, "text": "Ariel SharonColin PowellDonald RumsfeldGeorge W BushGerhard SchröderHugo ChavezTony Blair" }, { "code": null, "e": 5535, "s": 5522, "text": "Ariel Sharon" }, { "code": null, "e": 5548, "s": 5535, "text": "Colin Powell" }, { "code": null, "e": 5564, "s": 5548, "text": "Donald Rumsfeld" }, { "code": null, "e": 5578, "s": 5564, "text": "George W Bush" }, { "code": null, "e": 5596, "s": 5578, "text": "Gerhard Schröder" }, { "code": null, "e": 5608, "s": 5596, "text": "Hugo Chavez" }, { "code": null, "e": 5619, "s": 5608, "text": "Tony Blair" }, { "code": null, "e": 5651, "s": 5619, "text": "Let us print out the variables:" }, { "code": null, "e": 5781, "s": 5651, "text": "print(\"Total dataset size:\")print(\"n_samples: %d\", n_samples)print(\"n_features: %d\", n_features)print(\"n_classes: %d\", n_classes)" }, { "code": null, "e": 5901, "s": 5781, "text": "So, we have 1288 samples (pictures), a total of 1850 features for each sample (50px x 37px) and 7 classes (the people)." }, { "code": null, "e": 6137, "s": 5901, "text": "Next, we will use the train_test_split module from sklearn.model_selection and split the data (X-features and y-labels)into training data and testing data, with 25% of the data used for testing and the remaining 75% to train the model." }, { "code": null, "e": 6228, "s": 6137, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)" }, { "code": null, "e": 6286, "s": 6228, "text": "Here are the variables X-train, X_test, y_train & y_test:" }, { "code": null, "e": 6457, "s": 6286, "text": "Now, we will use PCA from sklearn.decomposition to select the top components to train the model. We have already imported PCA as RandomizedPCA in the first block of code." }, { "code": null, "e": 6600, "s": 6457, "text": "In our case, we have a total of 966 features in the training set X_train , and we will reduce them to 50 using PCA (dimensionality reduction):" }, { "code": null, "e": 6690, "s": 6600, "text": "n_components = 50pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train)" }, { "code": null, "e": 6803, "s": 6690, "text": "This process takes less than a second, which can be verified using the time function (let us skip that for now)." }, { "code": null, "e": 6982, "s": 6803, "text": "Now we will reshape our PCA components and define eigenfaces, which is the name given to a set of eigenvectors when used in the computer vision problem of human face recognition:" }, { "code": null, "e": 7041, "s": 6982, "text": "eigenfaces = pca.components_.reshape((n_components, h, w))" }, { "code": null, "e": 7312, "s": 7041, "text": "As the screenshot shows, the eigenfaces is a 50 x 50 x 37 NumPy array. The first 50 corresponds to the number of features, the n_components that we initialized a while back, and into which our PCA algorithm reduced to. The image dimensions in the eigenfaces are 50 x 37." }, { "code": null, "e": 7403, "s": 7312, "text": "Next, we will use PCA’s transform on both X_train and X_test to reduce the dimensionality." }, { "code": null, "e": 7474, "s": 7403, "text": "X_train_pca = pca.transform(X_train)X_test_pca = pca.transform(X_test)" }, { "code": null, "e": 7680, "s": 7474, "text": "As can be seen in the screenshot above, the dimensionality of both X_train and X_test were reduced through the PCA algorithm. Each had the features reduced from 1850 to 50 (as we defined in the algorithm)." }, { "code": null, "e": 7819, "s": 7680, "text": "Once we’re done with dimensionality reduction, we will now move towards classification. First, we will train the SVM Classification model." }, { "code": null, "e": 8121, "s": 7819, "text": "We will use GridSearchCV, a library function that is an approach to hyperparameter tuning. It will methodically build and evaluate a model for each combination of algorithm parameters specified in a grid, and return the best estimator in clf.best_estimator. The parameters are given in the param_grid:" }, { "code": null, "e": 8479, "s": 8121, "text": "print(\"Fitting the classifier to the training set\")param_grid = { 'C': [1e3, 5e3, 1e4, 5e4, 1e5], 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)clf = clf.fit(X_train_pca, y_train)print(\"Best estimator found by grid search:\")print(clf.best_estimator_)" }, { "code": null, "e": 8550, "s": 8479, "text": "The best classifier for our data is SVC with the following parameters:" }, { "code": null, "e": 8601, "s": 8550, "text": "SVC(C=1000, class_weight = ‘balanced’, gamma=0.01)" }, { "code": null, "e": 8768, "s": 8601, "text": "Let us now predict the people's names on the test data. We will use the classifier which we found from GridSearchCV and which we had already fit on the training data." }, { "code": null, "e": 8856, "s": 8768, "text": "print(\"Predicting the people names on the testing set\")y_pred = clf.predict(X_test_pca)" }, { "code": null, "e": 9072, "s": 8856, "text": "Once the predictions are made, let us print the Classification Report which will display the precision, recall, F1-score, and support scores for the model. This gives a deeper intuition of the classifier’s behavior." }, { "code": null, "e": 9144, "s": 9072, "text": "print(classification_report(y_test, y_pred, target_names=target_names))" }, { "code": null, "e": 9187, "s": 9144, "text": "Let us print the Confusion Matrix as well:" }, { "code": null, "e": 9252, "s": 9187, "text": "print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))" }, { "code": null, "e": 9417, "s": 9252, "text": "The Confusion Matrix prints the values of True Positives, False Positives, and False Negatives and gives an overview of how the classifier is. In the above example," }, { "code": null, "e": 9662, "s": 9417, "text": "Finally, we will plot both the portraits of the people as well as the eigenfaces! We will define 2 functions: title to plot the result of the prediction on a portion of the test set, and plot_gallery to evaluate the prediction by plotting them:" }, { "code": null, "e": 10344, "s": 9662, "text": "def title(y_pred, y_test, target_names, i): pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1] true_name = target_names[y_test[i]].rsplit(' ', 1)[-1] return 'predicted: %s\\ntrue: %s' % (pred_name, true_name)def plot_gallery(images, titles, h, w, n_row=3, n_col=4): \"\"\"Helper function to plot a gallery of portraits\"\"\" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1) plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) plt.title(titles[i], size=12) plt.xticks(()) plt.yticks(())" }, { "code": null, "e": 10420, "s": 10344, "text": "Let us now plot the results of the prediction on a portion of the test set:" }, { "code": null, "e": 10582, "s": 10420, "text": "prediction_titles = [title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])]plot_gallery(X_test, prediction_titles, h, w)" }, { "code": null, "e": 10692, "s": 10582, "text": "Let us now plot the eigenfaces. We will use the eigenfaces variable which we defined in the code block above." }, { "code": null, "e": 10826, "s": 10692, "text": "eigenface_titles = [\"eigenface %d\" % i for i in range(eigenfaces.shape[0])]plot_gallery(eigenfaces, eigenface_titles, h, w)plt.show()" }, { "code": null, "e": 10906, "s": 10826, "text": "Lastly, let us plot the accuracy of the PCA + SVM Model for Facial Recognition:" }, { "code": null, "e": 10999, "s": 10906, "text": "from sklearn.metrics import accuracy_scorescore = accuracy_score(y_test, y_pred)print(score)" }, { "code": null, "e": 11204, "s": 10999, "text": "We get an accuracy score of 0.81! While it’s not a perfect score, and there is a lot of room for improvement, facial recognition with PCA and SVM gives us a starting point for further powerful algorithms!" }, { "code": null, "e": 11579, "s": 11204, "text": "In this article, we built a facial recognition model using PCA and SVM. The Principal Component Analysis algorithm was used to reduce the dimensions of the data we had; images having a number of pixel values! then we used SVM for classification by finding the best estimator by hyperparameter tuning. We were able to classify the portraits and got an accuracy score of 0.81." }, { "code": null, "e": 11615, "s": 11579, "text": "What can we do to improve accuracy?" } ]
How do we use re.finditer() method in Python regular expression?
According to Python docs, re.finditer(pattern, string, flags=0) Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. The following code shows the use of re.finditer() method in Python regex import re s1 = 'Blue Berries' pattern = 'Blue Berries' for match in re.finditer(pattern, s1): s = match.start() e = match.end() print 'String match "%s" at %d:%d' % (s1[s:e], s, e) Strings match "Blue Berries" at 0:12
[ { "code": null, "e": 1088, "s": 1062, "text": "According to Python docs," }, { "code": null, "e": 1126, "s": 1088, "text": "re.finditer(pattern, string, flags=0)" }, { "code": null, "e": 1365, "s": 1126, "text": " Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. " }, { "code": null, "e": 1438, "s": 1365, "text": "The following code shows the use of re.finditer() method in Python regex" }, { "code": null, "e": 1631, "s": 1438, "text": "import re\ns1 = 'Blue Berries'\npattern = 'Blue Berries'\nfor match in re.finditer(pattern, s1):\n s = match.start()\n e = match.end()\n print 'String match \"%s\" at %d:%d' % (s1[s:e], s, e)" }, { "code": null, "e": 1670, "s": 1631, "text": "Strings match \"Blue Berries\" at 0:12\n\n" } ]
Flutter - Battery Level and State - GeeksforGeeks
30 Nov, 2021 In this article, we will see how to fetch Battery level and its state using flutter. To fetch Battery level(percentage) and its state we use a package called battery plus package. Battery level – we see how much percent battery is remaining in mobile. Battery State – we see whether the state of the battery is charging, discharging or it’s full. Now we will practically see how to fetch battery level and check the state of the battery – Step 1: Add dependencies to your pubspec.yaml file Dart dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 battery_plus: Step 2: Now, once we have added the dependencies into our flutter project, we need to import battery_plus.dart class. Dart import 'dart:async'; import 'package:flutter/material.dart';import 'package:battery_plus/battery_plus.dart'; Step 3: To use the battery_plus class we need to create an instance of the Battery class. We had created a variable called percentage and we have kept its initial value to 0. Step 4: Now we have created the method getBatteryPercentage() to check the battery percentage. In that method, we had initialized a variable level that stores the current value of the battery percentage. Then we had assigned the value to the percentage variable. Variable level returns a future type, so we had used async and await. Now we had created an init state and inside the init state we had called the getBatteryPercentage() method. Dart class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; @override void initState() { super.initState(); // calling the method to display battery percentage getBatteryPerentage(); } // method created to display battery percent void getBatteryPerentage() async { final level = await battery.batteryLevel; percentage = level; setState(() {}); } Step 5: In the build method we had created an Appbar in green color with text on it. Then we had created a column and inside that, we had displayed the battery percentage. Dart @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks', style: TextStyle(color: Colors.white),), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children:[ // Displaying battery percentage Text('Battery Percentage: $percentage', style: const TextStyle(fontSize: 24),) ], ), ), ); } Output: Step 6: To get the latest update of our battery percentage again and again. We have used Timer. This timer will show the latest battery status after every 5 seconds. We can increase the timer or decrease it as per our need Dart class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; late Timer timer; @override void initState() { super.initState(); // calling the method to get battery state getBatteryState(); // We have used timer to get the current status of // battery percentage after every 5 seconds Timer.periodic(const Duration(seconds: 5), (timer) { getBatteryPerentage(); }); } // method created to display battery percent void getBatteryPerentage() async { final level = await battery.batteryLevel; percentage = level; setState(() {}); } Step 7: Now to get the status of our battery state whether the battery is in charging mode, discharging mode, or full. We had created a battery state of enum type and initially we had set the state to full. and as we go inside the Battery state to check its properties we see that the battery state is of enum class and has 4 types of features defined that help us know the current state of our battery. Dart class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; late Timer timer; // created a Batterystate of enum type BatteryState batteryState = BatteryState.full; late StreamSubscription streamSubscription; This batterystate class contains 4 types of features that will help us to know the state of the battery. Dart // Indicates the current battery state.enum BatteryState { // The battery is completely full of energy. full, // The battery is currently storing energy. charging, // The battery is currently losing energy. discharging, // The state of the battery is unknown. unknown} Step 8: Next we had created a getBatteryState() method. This method is created to check the current state of our battery and then update display it to the user. We had used here listen to the method that will store the current state of our battery and then we assign it to batteryState. Dart // method to know the state of the battery void getBatteryState() { streamSubscription = battery.onBatteryStateChanged.listen((state) { batteryState = state; setState(() {}); }); } Then had called the method inside the initState() Dart @override void initState() { super.initState(); // calling the method to get battery state getBatteryState(); Timer.periodic(const Duration(seconds: 5), (timer) { getBatteryPerentage(); }); } Step 9: At the final step we had created a custom widget called BatteryBuild() which accepts the battery state. In this widget, we had added different states of battery using switch case. Then called the custom widget BatteryBuild() in the build method Dart // Custom widget to add different states of battery// ignore: non_constant_identifier_names Widget BatteryBuild(BatteryState state) { switch (state) { case BatteryState.full: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_full, size: 200, color: Colors.green, )), ); case BatteryState.charging: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_charging_full, size: 200, color: Colors.blue, )), ); case BatteryState.discharging: default: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_alert, size: 200, color: Colors.red, )), ); } } Full source code: Dart import 'dart:async'; import 'package:flutter/material.dart';import 'package:battery_plus/battery_plus.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, }) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; late Timer timer; // created a Batterystate of enum type BatteryState batteryState = BatteryState.full; late StreamSubscription streamSubscription; @override void initState() { super.initState(); // calling the method to get battery state getBatteryState(); // calling the method to get battery percentage Timer.periodic(const Duration(seconds: 5), (timer) { getBatteryPerentage(); }); } // method created to display battery percent void getBatteryPerentage() async { final level = await battery.batteryLevel; percentage = level; setState(() {}); } // method to know the state of the battery void getBatteryState() { streamSubscription = battery.onBatteryStateChanged.listen((state) { batteryState = state; setState(() {}); }); } // Custom widget to add different states of battery// ignore: non_constant_identifier_names Widget BatteryBuild(BatteryState state) { switch (state) { // first case is for battery full state // then it will show green in color case BatteryState.full: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_full, size: 200, color: Colors.green, )), ); // Second case is when battery is charging // then it will show blue in color case BatteryState.charging: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_charging_full, size: 200, color: Colors.blue, )), ); // third case is when the battery is // discharged then it will show red in color case BatteryState.discharging: default: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_alert, size: 200, color: Colors.red, )), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks', style: TextStyle(color: Colors.white),), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children:[ // calling the custom widget BatteryBuild(batteryState), // Displaying battery percentage Text('Battery Percentage: $percentage', style: const TextStyle(fontSize: 24),) ], ), ), ); }} Output: Explanation – In step 9 we created a custom widget where we coded that if the mobile battery is charging then show us the battery in blue color. So currently my phone is not fully charged that’s why we saw the battery in blue color. If our battery would have been 100% then the color would have changed to green If our battery would have been 0% then it would have been in red color. For more clarification see the below image. Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25371, "s": 25343, "text": "\n30 Nov, 2021" }, { "code": null, "e": 25551, "s": 25371, "text": "In this article, we will see how to fetch Battery level and its state using flutter. To fetch Battery level(percentage) and its state we use a package called battery plus package." }, { "code": null, "e": 25623, "s": 25551, "text": "Battery level – we see how much percent battery is remaining in mobile." }, { "code": null, "e": 25718, "s": 25623, "text": "Battery State – we see whether the state of the battery is charging, discharging or it’s full." }, { "code": null, "e": 25811, "s": 25718, "text": "Now we will practically see how to fetch battery level and check the state of the battery – " }, { "code": null, "e": 25863, "s": 25811, "text": "Step 1: Add dependencies to your pubspec.yaml file " }, { "code": null, "e": 25868, "s": 25863, "text": "Dart" }, { "code": "dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 battery_plus:", "e": 25949, "s": 25868, "text": null }, { "code": null, "e": 26067, "s": 25949, "text": "Step 2: Now, once we have added the dependencies into our flutter project, we need to import battery_plus.dart class." }, { "code": null, "e": 26072, "s": 26067, "text": "Dart" }, { "code": "import 'dart:async'; import 'package:flutter/material.dart';import 'package:battery_plus/battery_plus.dart';", "e": 26182, "s": 26072, "text": null }, { "code": null, "e": 26357, "s": 26182, "text": "Step 3: To use the battery_plus class we need to create an instance of the Battery class. We had created a variable called percentage and we have kept its initial value to 0." }, { "code": null, "e": 26799, "s": 26357, "text": "Step 4: Now we have created the method getBatteryPercentage() to check the battery percentage. In that method, we had initialized a variable level that stores the current value of the battery percentage. Then we had assigned the value to the percentage variable. Variable level returns a future type, so we had used async and await. Now we had created an init state and inside the init state we had called the getBatteryPercentage() method." }, { "code": null, "e": 26804, "s": 26799, "text": "Dart" }, { "code": "class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; @override void initState() { super.initState(); // calling the method to display battery percentage getBatteryPerentage(); } // method created to display battery percent void getBatteryPerentage() async { final level = await battery.batteryLevel; percentage = level; setState(() {}); }", "e": 27362, "s": 26804, "text": null }, { "code": null, "e": 27534, "s": 27362, "text": "Step 5: In the build method we had created an Appbar in green color with text on it. Then we had created a column and inside that, we had displayed the battery percentage." }, { "code": null, "e": 27539, "s": 27534, "text": "Dart" }, { "code": "@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks', style: TextStyle(color: Colors.white),), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children:[ // Displaying battery percentage Text('Battery Percentage: $percentage', style: const TextStyle(fontSize: 24),) ], ), ), ); }", "e": 28117, "s": 27539, "text": null }, { "code": null, "e": 28125, "s": 28117, "text": "Output:" }, { "code": null, "e": 28349, "s": 28125, "text": "Step 6: To get the latest update of our battery percentage again and again. We have used Timer. This timer will show the latest battery status after every 5 seconds. We can increase the timer or decrease it as per our need" }, { "code": null, "e": 28354, "s": 28349, "text": "Dart" }, { "code": "class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; late Timer timer; @override void initState() { super.initState(); // calling the method to get battery state getBatteryState(); // We have used timer to get the current status of // battery percentage after every 5 seconds Timer.periodic(const Duration(seconds: 5), (timer) { getBatteryPerentage(); }); } // method created to display battery percent void getBatteryPerentage() async { final level = await battery.batteryLevel; percentage = level; setState(() {}); }", "e": 29170, "s": 28354, "text": null }, { "code": null, "e": 29574, "s": 29170, "text": "Step 7: Now to get the status of our battery state whether the battery is in charging mode, discharging mode, or full. We had created a battery state of enum type and initially we had set the state to full. and as we go inside the Battery state to check its properties we see that the battery state is of enum class and has 4 types of features defined that help us know the current state of our battery." }, { "code": null, "e": 29579, "s": 29574, "text": "Dart" }, { "code": "class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; late Timer timer; // created a Batterystate of enum type BatteryState batteryState = BatteryState.full; late StreamSubscription streamSubscription; ", "e": 29880, "s": 29579, "text": null }, { "code": null, "e": 29985, "s": 29880, "text": "This batterystate class contains 4 types of features that will help us to know the state of the battery." }, { "code": null, "e": 29990, "s": 29985, "text": "Dart" }, { "code": "// Indicates the current battery state.enum BatteryState { // The battery is completely full of energy. full, // The battery is currently storing energy. charging, // The battery is currently losing energy. discharging, // The state of the battery is unknown. unknown}", "e": 30273, "s": 29990, "text": null }, { "code": null, "e": 30560, "s": 30273, "text": "Step 8: Next we had created a getBatteryState() method. This method is created to check the current state of our battery and then update display it to the user. We had used here listen to the method that will store the current state of our battery and then we assign it to batteryState." }, { "code": null, "e": 30565, "s": 30560, "text": "Dart" }, { "code": "// method to know the state of the battery void getBatteryState() { streamSubscription = battery.onBatteryStateChanged.listen((state) { batteryState = state; setState(() {}); }); }", "e": 30766, "s": 30565, "text": null }, { "code": null, "e": 30823, "s": 30766, "text": " Then had called the method inside the initState() " }, { "code": null, "e": 30828, "s": 30823, "text": "Dart" }, { "code": "@override void initState() { super.initState(); // calling the method to get battery state getBatteryState(); Timer.periodic(const Duration(seconds: 5), (timer) { getBatteryPerentage(); }); }", "e": 31163, "s": 30828, "text": null }, { "code": null, "e": 31416, "s": 31163, "text": "Step 9: At the final step we had created a custom widget called BatteryBuild() which accepts the battery state. In this widget, we had added different states of battery using switch case. Then called the custom widget BatteryBuild() in the build method" }, { "code": null, "e": 31421, "s": 31416, "text": "Dart" }, { "code": "// Custom widget to add different states of battery// ignore: non_constant_identifier_names Widget BatteryBuild(BatteryState state) { switch (state) { case BatteryState.full: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_full, size: 200, color: Colors.green, )), ); case BatteryState.charging: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_charging_full, size: 200, color: Colors.blue, )), ); case BatteryState.discharging: default: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_alert, size: 200, color: Colors.red, )), ); } }", "e": 32633, "s": 31421, "text": null }, { "code": null, "e": 32651, "s": 32633, "text": "Full source code:" }, { "code": null, "e": 32656, "s": 32651, "text": "Dart" }, { "code": "import 'dart:async'; import 'package:flutter/material.dart';import 'package:battery_plus/battery_plus.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, }) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { var battery = Battery(); int percentage = 0; late Timer timer; // created a Batterystate of enum type BatteryState batteryState = BatteryState.full; late StreamSubscription streamSubscription; @override void initState() { super.initState(); // calling the method to get battery state getBatteryState(); // calling the method to get battery percentage Timer.periodic(const Duration(seconds: 5), (timer) { getBatteryPerentage(); }); } // method created to display battery percent void getBatteryPerentage() async { final level = await battery.batteryLevel; percentage = level; setState(() {}); } // method to know the state of the battery void getBatteryState() { streamSubscription = battery.onBatteryStateChanged.listen((state) { batteryState = state; setState(() {}); }); } // Custom widget to add different states of battery// ignore: non_constant_identifier_names Widget BatteryBuild(BatteryState state) { switch (state) { // first case is for battery full state // then it will show green in color case BatteryState.full: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_full, size: 200, color: Colors.green, )), ); // Second case is when battery is charging // then it will show blue in color case BatteryState.charging: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_charging_full, size: 200, color: Colors.blue, )), ); // third case is when the battery is // discharged then it will show red in color case BatteryState.discharging: default: // ignore: sized_box_for_whitespace return Container( width: 200, height: 200, // ignore: prefer_const_constructors child: (Icon( Icons.battery_alert, size: 200, color: Colors.red, )), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks', style: TextStyle(color: Colors.white),), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children:[ // calling the custom widget BatteryBuild(batteryState), // Displaying battery percentage Text('Battery Percentage: $percentage', style: const TextStyle(fontSize: 24),) ], ), ), ); }}", "e": 36604, "s": 32656, "text": null }, { "code": null, "e": 36612, "s": 36604, "text": "Output:" }, { "code": null, "e": 36627, "s": 36612, "text": "Explanation – " }, { "code": null, "e": 36846, "s": 36627, "text": "In step 9 we created a custom widget where we coded that if the mobile battery is charging then show us the battery in blue color. So currently my phone is not fully charged that’s why we saw the battery in blue color." }, { "code": null, "e": 36925, "s": 36846, "text": "If our battery would have been 100% then the color would have changed to green" }, { "code": null, "e": 37041, "s": 36925, "text": "If our battery would have been 0% then it would have been in red color. For more clarification see the below image." }, { "code": null, "e": 37049, "s": 37041, "text": "Flutter" }, { "code": null, "e": 37071, "s": 37049, "text": "Flutter UI-components" }, { "code": null, "e": 37076, "s": 37071, "text": "Dart" }, { "code": null, "e": 37084, "s": 37076, "text": "Flutter" }, { "code": null, "e": 37182, "s": 37084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37221, "s": 37182, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 37247, "s": 37221, "text": "ListView Class in Flutter" }, { "code": null, "e": 37273, "s": 37247, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 37296, "s": 37273, "text": "Flutter - Stack Widget" }, { "code": null, "e": 37314, "s": 37296, "text": "Flutter - Dialogs" }, { "code": null, "e": 37353, "s": 37314, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 37370, "s": 37353, "text": "Flutter Tutorial" }, { "code": null, "e": 37396, "s": 37370, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 37419, "s": 37396, "text": "Flutter - Stack Widget" } ]
C# | Get the first node of the LinkedList<T> - GeeksforGeeks
01 Feb, 2019 LinkedList<T>.First property is used to get the first node of the LinkedList<T>. Syntax: public System.Collections.Generic.LinkedListNode First { get; } Return Value: The first LinkedListNode<T> of the LinkedList<T>. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to get the first// node of the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("Geeks"); myList.AddLast("for"); myList.AddLast("Data Structures"); myList.AddLast("Noida"); // To get the first node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.First.Value); else Console.WriteLine("LinkedList is empty"); }} Output: Geeks Example 2: // C# code to get the first// node of the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // To get the first node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.First.Value); else Console.WriteLine("LinkedList is empty"); }} Output: LinkedList is empty Note: LinkedList accepts null as a valid Value for reference types and allows duplicate values. If the LinkedList is empty, the First and Last properties contain null. Retrieving the value of this property is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.first?view=netframework-4.7.2 CSharp-Generic-Namespace CSharp-LinkedList C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Replace() Method C# | Class and Object C# | Constructors Introduction to .NET Framework C# | Data Types HashSet in C# with Examples
[ { "code": null, "e": 25847, "s": 25819, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25928, "s": 25847, "text": "LinkedList<T>.First property is used to get the first node of the LinkedList<T>." }, { "code": null, "e": 25936, "s": 25928, "text": "Syntax:" }, { "code": null, "e": 26001, "s": 25936, "text": "public System.Collections.Generic.LinkedListNode First { get; }\n" }, { "code": null, "e": 26065, "s": 26001, "text": "Return Value: The first LinkedListNode<T> of the LinkedList<T>." }, { "code": null, "e": 26145, "s": 26065, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 26156, "s": 26145, "text": "Example 1:" }, { "code": "// C# code to get the first// node of the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"Geeks\"); myList.AddLast(\"for\"); myList.AddLast(\"Data Structures\"); myList.AddLast(\"Noida\"); // To get the first node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.First.Value); else Console.WriteLine(\"LinkedList is empty\"); }}", "e": 26828, "s": 26156, "text": null }, { "code": null, "e": 26836, "s": 26828, "text": "Output:" }, { "code": null, "e": 26843, "s": 26836, "text": "Geeks\n" }, { "code": null, "e": 26854, "s": 26843, "text": "Example 2:" }, { "code": "// C# code to get the first// node of the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // To get the first node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.First.Value); else Console.WriteLine(\"LinkedList is empty\"); }}", "e": 27346, "s": 26854, "text": null }, { "code": null, "e": 27354, "s": 27346, "text": "Output:" }, { "code": null, "e": 27375, "s": 27354, "text": "LinkedList is empty\n" }, { "code": null, "e": 27381, "s": 27375, "text": "Note:" }, { "code": null, "e": 27471, "s": 27381, "text": "LinkedList accepts null as a valid Value for reference types and allows duplicate values." }, { "code": null, "e": 27543, "s": 27471, "text": "If the LinkedList is empty, the First and Last properties contain null." }, { "code": null, "e": 27603, "s": 27543, "text": "Retrieving the value of this property is an O(1) operation." }, { "code": null, "e": 27614, "s": 27603, "text": "Reference:" }, { "code": null, "e": 27728, "s": 27614, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.first?view=netframework-4.7.2" }, { "code": null, "e": 27753, "s": 27728, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27771, "s": 27753, "text": "CSharp-LinkedList" }, { "code": null, "e": 27774, "s": 27771, "text": "C#" }, { "code": null, "e": 27872, "s": 27774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27887, "s": 27872, "text": "C# | Delegates" }, { "code": null, "e": 27909, "s": 27887, "text": "C# | Abstract Classes" }, { "code": null, "e": 27955, "s": 27909, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27978, "s": 27955, "text": "Extension Method in C#" }, { "code": null, "e": 28000, "s": 27978, "text": "C# | Replace() Method" }, { "code": null, "e": 28022, "s": 28000, "text": "C# | Class and Object" }, { "code": null, "e": 28040, "s": 28022, "text": "C# | Constructors" }, { "code": null, "e": 28071, "s": 28040, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28087, "s": 28071, "text": "C# | Data Types" } ]
Common mistakes to be avoided in Competitive Programming in C++ | Beginners - GeeksforGeeks
Common mistakes to be avoided in Competitive Programming in C++ | Beginners C++ tricks for competitive programming (for C++ 11) Writing C/C++ code efficiently in Competitive programming Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota) What are the default values of static variables in C? Understanding “volatile” qualifier in C | Set 2 (Examples) Const Qualifier in C Initialization of static variables in C Understanding “register” keyword in C Understanding “extern” keyword in C Storage Classes in C Static Variables in C Memory Layout of C Programs How to deallocate memory without using free() in C? Difference Between malloc() and calloc() with Examples Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() How to dynamically allocate a 2D array in C? How to pass a 2D array as a parameter in C? Multidimensional Arrays in C / C++ 2D Vector In C++ With User Defined Size Vector of Vectors in C++ STL with Examples Vector in C++ STL The C++ Standard Template Library (STL) Sort in C++ Standard Template Library (STL) Arrays in C/C++ std::sort() in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Common mistakes to be avoided in Competitive Programming in C++ | Beginners C++ tricks for competitive programming (for C++ 11) Writing C/C++ code efficiently in Competitive programming Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota) What are the default values of static variables in C? Understanding “volatile” qualifier in C | Set 2 (Examples) Const Qualifier in C Initialization of static variables in C Understanding “register” keyword in C Understanding “extern” keyword in C Storage Classes in C Static Variables in C Memory Layout of C Programs How to deallocate memory without using free() in C? Difference Between malloc() and calloc() with Examples Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() How to dynamically allocate a 2D array in C? How to pass a 2D array as a parameter in C? Multidimensional Arrays in C / C++ 2D Vector In C++ With User Defined Size Vector of Vectors in C++ STL with Examples Vector in C++ STL The C++ Standard Template Library (STL) Sort in C++ Standard Template Library (STL) Arrays in C/C++ std::sort() in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Difficulty Level : Medium Not using of 1LL or 1ll when needed// A program shows problem if we// don't use 1ll or 1LL#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0;}Output: -727379968 You might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long.// C++ program to show that use of 1ll// fixes the problem in above code.#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; long long int z = 1LL*x*y; cout << z; return 0;}Output: 1000000000000 Here is another place where this trick can help you.// Another problematic code that doesn't // use 1LL or 1ll#include <iostream>using namespace std; int main(){ // we should use 1LL or 1ll here // instead of 1. The correct statement // is "long long int z = 1LL << 40;" long long int z = 1 << 40; cout << z; return 0;}Output: 0 Not using cin.ignore() with getline// A program that shows problem if we// don't use cin.ignore()#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; for(int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << " "; cout << s << endl; } return 0;}Input: 4 a b c d e f g h Output: 0 3 a b 3 c d 3 e f So what is the problem here?This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream: "4\n"A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline).Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.cin.ignore(n, delim);This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.// C++ program to show that use of cin.ignore()// fixes the problem in above code.#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; cin.ignore(1, '\n'); for (int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << " "; cout << s << endl; } return 0;}Input: 4 a b c d e f g h Output: 3 a b 3 c d 3 e f 3 g h But what if we don’t know how many lines of input are going to be there? We can use this then:// C++ program to handle cases when we// don't know how many lines of input // are going to be there#include <iostream>using namespace std;int main(){ string s; while (getline(cin, s)) { if (s.empty()) break; cout << s << endl; } return 0;}Input: a b c d e f g h Output: a b c d e f g h A problem when taking remainders: In a lot of problems, you have to print your solution modulo some large prime (for example 10^9 + 7).// Below program shows problem if we// don't use don't take remainders// properly.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; z = (z + x*y)%mod; // not good practice cout << z; return 0;}Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this:// Program to demonstrate proper// ways of taking remainders.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; // good practice z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod; cout << z; return 0;}This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.Why does this work?Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod.cin and cout might cause TLE: In a lot of programs, the cause of TLE is generally based on your algorithm. For example, if n = 10^6 and your algorithm runs in O(n^2) then this won’t pass a 1 second Time Limit. But say, you have found an algorithm that runs in O(n) for n = 10^6. This should pass the 1 second Time Limit.What if this is failing?One possible reason is that you are using cin and cout for I/O over multiple test cases.You can use scanf or printf for the same. You can also use some custom Fast I/O function for the same based on something like getchar() and putchar().scanf and printf are faster than cin and cout. See this for more details.Custom Fast I/O functions:// C++ program to demonstrate fast input and output // use long long x = fast_input(); to read in xinline long long int fast_input(void){ char t; long long int x=0; long long int neg=0; t = getchar(); while ((t<48 || t>57) && t!='-') t = getchar(); if (t == '-') //handle negative input { neg = 1; t = getchar(); } while (t>=48 && t<=57) { x = (x<<3) + (x<<1) + t - 48; // x<<3 means 8*x and x<<1 means 2*x so we // have x = 10*x+(t - 48) t = getchar(); } if (neg) x = -x; return x;} // use fast_output(x, 0); to print x and a newline// use fast_output(x, 1); to print x and a ' ' after// the xinline void fast_output(long long int x, int mode){ char a[20]; long long int i=0, j; a[0] = '0'; if (x < 0) { putchar('-'); x = -x; } if (x==0) putchar('0'); while (x) { // convert each digit to character and // store in char array a[i++] = x%10 + 48; x /= 10; } // print each character from the array for (j=i-1; j>=0; j--) putchar(a[j]); if (mode == 0) putchar('\n'); else putchar(' ');} Not using of 1LL or 1ll when needed// A program shows problem if we// don't use 1ll or 1LL#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0;}Output: -727379968 You might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long.// C++ program to show that use of 1ll// fixes the problem in above code.#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; long long int z = 1LL*x*y; cout << z; return 0;}Output: 1000000000000 Here is another place where this trick can help you.// Another problematic code that doesn't // use 1LL or 1ll#include <iostream>using namespace std; int main(){ // we should use 1LL or 1ll here // instead of 1. The correct statement // is "long long int z = 1LL << 40;" long long int z = 1 << 40; cout << z; return 0;}Output: 0 // A program shows problem if we// don't use 1ll or 1LL#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0;} Output: -727379968 You might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long. // C++ program to show that use of 1ll// fixes the problem in above code.#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; long long int z = 1LL*x*y; cout << z; return 0;} Output: 1000000000000 Here is another place where this trick can help you. // Another problematic code that doesn't // use 1LL or 1ll#include <iostream>using namespace std; int main(){ // we should use 1LL or 1ll here // instead of 1. The correct statement // is "long long int z = 1LL << 40;" long long int z = 1 << 40; cout << z; return 0;} Output: 0 Not using cin.ignore() with getline// A program that shows problem if we// don't use cin.ignore()#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; for(int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << " "; cout << s << endl; } return 0;}Input: 4 a b c d e f g h Output: 0 3 a b 3 c d 3 e f So what is the problem here?This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream: "4\n"A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline).Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.cin.ignore(n, delim);This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.// C++ program to show that use of cin.ignore()// fixes the problem in above code.#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; cin.ignore(1, '\n'); for (int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << " "; cout << s << endl; } return 0;}Input: 4 a b c d e f g h Output: 3 a b 3 c d 3 e f 3 g h But what if we don’t know how many lines of input are going to be there? We can use this then:// C++ program to handle cases when we// don't know how many lines of input // are going to be there#include <iostream>using namespace std;int main(){ string s; while (getline(cin, s)) { if (s.empty()) break; cout << s << endl; } return 0;}Input: a b c d e f g h Output: a b c d e f g h // A program that shows problem if we// don't use cin.ignore()#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; for(int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << " "; cout << s << endl; } return 0;} Input: 4 a b c d e f g h Output: 0 3 a b 3 c d 3 e f So what is the problem here?This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream: "4\n" A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline). Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.cin.ignore(n, delim);This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. // C++ program to show that use of cin.ignore()// fixes the problem in above code.#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; cin.ignore(1, '\n'); for (int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << " "; cout << s << endl; } return 0;} Input: 4 a b c d e f g h Output: 3 a b 3 c d 3 e f 3 g h But what if we don’t know how many lines of input are going to be there? We can use this then: // C++ program to handle cases when we// don't know how many lines of input // are going to be there#include <iostream>using namespace std;int main(){ string s; while (getline(cin, s)) { if (s.empty()) break; cout << s << endl; } return 0;} Input: a b c d e f g h Output: a b c d e f g h A problem when taking remainders: In a lot of problems, you have to print your solution modulo some large prime (for example 10^9 + 7).// Below program shows problem if we// don't use don't take remainders// properly.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; z = (z + x*y)%mod; // not good practice cout << z; return 0;}Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this:// Program to demonstrate proper// ways of taking remainders.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; // good practice z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod; cout << z; return 0;}This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.Why does this work?Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod. // Below program shows problem if we// don't use don't take remainders// properly.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; z = (z + x*y)%mod; // not good practice cout << z; return 0;} Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this: // Program to demonstrate proper// ways of taking remainders.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; // good practice z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod; cout << z; return 0;} This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.Why does this work?Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod. cin and cout might cause TLE: In a lot of programs, the cause of TLE is generally based on your algorithm. For example, if n = 10^6 and your algorithm runs in O(n^2) then this won’t pass a 1 second Time Limit. But say, you have found an algorithm that runs in O(n) for n = 10^6. This should pass the 1 second Time Limit.What if this is failing?One possible reason is that you are using cin and cout for I/O over multiple test cases.You can use scanf or printf for the same. You can also use some custom Fast I/O function for the same based on something like getchar() and putchar().scanf and printf are faster than cin and cout. See this for more details.Custom Fast I/O functions:// C++ program to demonstrate fast input and output // use long long x = fast_input(); to read in xinline long long int fast_input(void){ char t; long long int x=0; long long int neg=0; t = getchar(); while ((t<48 || t>57) && t!='-') t = getchar(); if (t == '-') //handle negative input { neg = 1; t = getchar(); } while (t>=48 && t<=57) { x = (x<<3) + (x<<1) + t - 48; // x<<3 means 8*x and x<<1 means 2*x so we // have x = 10*x+(t - 48) t = getchar(); } if (neg) x = -x; return x;} // use fast_output(x, 0); to print x and a newline// use fast_output(x, 1); to print x and a ' ' after// the xinline void fast_output(long long int x, int mode){ char a[20]; long long int i=0, j; a[0] = '0'; if (x < 0) { putchar('-'); x = -x; } if (x==0) putchar('0'); while (x) { // convert each digit to character and // store in char array a[i++] = x%10 + 48; x /= 10; } // print each character from the array for (j=i-1; j>=0; j--) putchar(a[j]); if (mode == 0) putchar('\n'); else putchar(' ');} scanf and printf are faster than cin and cout. See this for more details. Custom Fast I/O functions: // C++ program to demonstrate fast input and output // use long long x = fast_input(); to read in xinline long long int fast_input(void){ char t; long long int x=0; long long int neg=0; t = getchar(); while ((t<48 || t>57) && t!='-') t = getchar(); if (t == '-') //handle negative input { neg = 1; t = getchar(); } while (t>=48 && t<=57) { x = (x<<3) + (x<<1) + t - 48; // x<<3 means 8*x and x<<1 means 2*x so we // have x = 10*x+(t - 48) t = getchar(); } if (neg) x = -x; return x;} // use fast_output(x, 0); to print x and a newline// use fast_output(x, 1); to print x and a ' ' after// the xinline void fast_output(long long int x, int mode){ char a[20]; long long int i=0, j; a[0] = '0'; if (x < 0) { putchar('-'); x = -x; } if (x==0) putchar('0'); while (x) { // convert each digit to character and // store in char array a[i++] = x%10 + 48; x /= 10; } // print each character from the array for (j=i-1; j>=0; j--) putchar(a[j]); if (mode == 0) putchar('\n'); else putchar(' ');} Related Articles :A Better Way To Approach Competitive ProgrammingC++ tricks for competitive programming (for C++ 11)Writing C/C++ code efficiently in Competitive programming This article is contributed by Hemang Sarkar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C++ Competitive Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Virtual Function in C++ C++ Classes and Objects Bitwise Operators in C/C++ Templates in C++ with Examples Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS
[ { "code": null, "e": 24114, "s": 24038, "text": "Common mistakes to be avoided in Competitive Programming in C++ | Beginners" }, { "code": null, "e": 24166, "s": 24114, "text": "C++ tricks for competitive programming (for C++ 11)" }, { "code": null, "e": 24224, "s": 24166, "text": "Writing C/C++ code efficiently in Competitive programming" }, { "code": null, "e": 24295, "s": 24224, "text": "Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota)" }, { "code": null, "e": 24349, "s": 24295, "text": "What are the default values of static variables in C?" }, { "code": null, "e": 24408, "s": 24349, "text": "Understanding “volatile” qualifier in C | Set 2 (Examples)" }, { "code": null, "e": 24429, "s": 24408, "text": "Const Qualifier in C" }, { "code": null, "e": 24469, "s": 24429, "text": "Initialization of static variables in C" }, { "code": null, "e": 24507, "s": 24469, "text": "Understanding “register” keyword in C" }, { "code": null, "e": 24543, "s": 24507, "text": "Understanding “extern” keyword in C" }, { "code": null, "e": 24564, "s": 24543, "text": "Storage Classes in C" }, { "code": null, "e": 24586, "s": 24564, "text": "Static Variables in C" }, { "code": null, "e": 24614, "s": 24586, "text": "Memory Layout of C Programs" }, { "code": null, "e": 24666, "s": 24614, "text": "How to deallocate memory without using free() in C?" }, { "code": null, "e": 24721, "s": 24666, "text": "Difference Between malloc() and calloc() with Examples" }, { "code": null, "e": 24799, "s": 24721, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 24844, "s": 24799, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 24888, "s": 24844, "text": "How to pass a 2D array as a parameter in C?" }, { "code": null, "e": 24923, "s": 24888, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 24963, "s": 24923, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 25006, "s": 24963, "text": "Vector of Vectors in C++ STL with Examples" }, { "code": null, "e": 25024, "s": 25006, "text": "Vector in C++ STL" }, { "code": null, "e": 25064, "s": 25024, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 25108, "s": 25064, "text": "Sort in C++ Standard Template Library (STL)" }, { "code": null, "e": 25124, "s": 25108, "text": "Arrays in C/C++" }, { "code": null, "e": 25147, "s": 25124, "text": "std::sort() in C++ STL" }, { "code": null, "e": 25193, "s": 25147, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 25236, "s": 25193, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 25312, "s": 25236, "text": "Common mistakes to be avoided in Competitive Programming in C++ | Beginners" }, { "code": null, "e": 25364, "s": 25312, "text": "C++ tricks for competitive programming (for C++ 11)" }, { "code": null, "e": 25422, "s": 25364, "text": "Writing C/C++ code efficiently in Competitive programming" }, { "code": null, "e": 25493, "s": 25422, "text": "Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota)" }, { "code": null, "e": 25547, "s": 25493, "text": "What are the default values of static variables in C?" }, { "code": null, "e": 25606, "s": 25547, "text": "Understanding “volatile” qualifier in C | Set 2 (Examples)" }, { "code": null, "e": 25627, "s": 25606, "text": "Const Qualifier in C" }, { "code": null, "e": 25667, "s": 25627, "text": "Initialization of static variables in C" }, { "code": null, "e": 25705, "s": 25667, "text": "Understanding “register” keyword in C" }, { "code": null, "e": 25741, "s": 25705, "text": "Understanding “extern” keyword in C" }, { "code": null, "e": 25762, "s": 25741, "text": "Storage Classes in C" }, { "code": null, "e": 25784, "s": 25762, "text": "Static Variables in C" }, { "code": null, "e": 25812, "s": 25784, "text": "Memory Layout of C Programs" }, { "code": null, "e": 25864, "s": 25812, "text": "How to deallocate memory without using free() in C?" }, { "code": null, "e": 25919, "s": 25864, "text": "Difference Between malloc() and calloc() with Examples" }, { "code": null, "e": 25997, "s": 25919, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 26042, "s": 25997, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 26086, "s": 26042, "text": "How to pass a 2D array as a parameter in C?" }, { "code": null, "e": 26121, "s": 26086, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26161, "s": 26121, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 26204, "s": 26161, "text": "Vector of Vectors in C++ STL with Examples" }, { "code": null, "e": 26222, "s": 26204, "text": "Vector in C++ STL" }, { "code": null, "e": 26262, "s": 26222, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 26306, "s": 26262, "text": "Sort in C++ Standard Template Library (STL)" }, { "code": null, "e": 26322, "s": 26306, "text": "Arrays in C/C++" }, { "code": null, "e": 26345, "s": 26322, "text": "std::sort() in C++ STL" }, { "code": null, "e": 26391, "s": 26345, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26434, "s": 26391, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26460, "s": 26434, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 33384, "s": 26460, "text": "Not using of 1LL or 1ll when needed// A program shows problem if we// don't use 1ll or 1LL#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0;}Output: -727379968\nYou might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long.// C++ program to show that use of 1ll// fixes the problem in above code.#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; long long int z = 1LL*x*y; cout << z; return 0;}Output: 1000000000000\nHere is another place where this trick can help you.// Another problematic code that doesn't // use 1LL or 1ll#include <iostream>using namespace std; int main(){ // we should use 1LL or 1ll here // instead of 1. The correct statement // is \"long long int z = 1LL << 40;\" long long int z = 1 << 40; cout << z; return 0;}Output: 0\nNot using cin.ignore() with getline// A program that shows problem if we// don't use cin.ignore()#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; for(int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << \" \"; cout << s << endl; } return 0;}Input:\n4\na b\nc d\ne f\ng h\nOutput:\n0 \n3 a b\n3 c d\n3 e f\nSo what is the problem here?This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream: \"4\\n\"A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline).Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.cin.ignore(n, delim);This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.// C++ program to show that use of cin.ignore()// fixes the problem in above code.#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; cin.ignore(1, '\\n'); for (int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << \" \"; cout << s << endl; } return 0;}Input:\n4\na b\nc d\ne f\ng h\nOutput:\n3 a b\n3 c d\n3 e f\n3 g h\nBut what if we don’t know how many lines of input are going to be there? We can use this then:// C++ program to handle cases when we// don't know how many lines of input // are going to be there#include <iostream>using namespace std;int main(){ string s; while (getline(cin, s)) { if (s.empty()) break; cout << s << endl; } return 0;}Input:\na b\nc d\ne f\ng h\n\nOutput:\na b\nc d\ne f\ng h\nA problem when taking remainders: In a lot of problems, you have to print your solution modulo some large prime (for example 10^9 + 7).// Below program shows problem if we// don't use don't take remainders// properly.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; z = (z + x*y)%mod; // not good practice cout << z; return 0;}Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this:// Program to demonstrate proper// ways of taking remainders.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; // good practice z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod; cout << z; return 0;}This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.Why does this work?Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod.cin and cout might cause TLE: In a lot of programs, the cause of TLE is generally based on your algorithm. For example, if n = 10^6 and your algorithm runs in O(n^2) then this won’t pass a 1 second Time Limit. But say, you have found an algorithm that runs in O(n) for n = 10^6. This should pass the 1 second Time Limit.What if this is failing?One possible reason is that you are using cin and cout for I/O over multiple test cases.You can use scanf or printf for the same. You can also use some custom Fast I/O function for the same based on something like getchar() and putchar().scanf and printf are faster than cin and cout. See this for more details.Custom Fast I/O functions:// C++ program to demonstrate fast input and output // use long long x = fast_input(); to read in xinline long long int fast_input(void){ char t; long long int x=0; long long int neg=0; t = getchar(); while ((t<48 || t>57) && t!='-') t = getchar(); if (t == '-') //handle negative input { neg = 1; t = getchar(); } while (t>=48 && t<=57) { x = (x<<3) + (x<<1) + t - 48; // x<<3 means 8*x and x<<1 means 2*x so we // have x = 10*x+(t - 48) t = getchar(); } if (neg) x = -x; return x;} // use fast_output(x, 0); to print x and a newline// use fast_output(x, 1); to print x and a ' ' after// the xinline void fast_output(long long int x, int mode){ char a[20]; long long int i=0, j; a[0] = '0'; if (x < 0) { putchar('-'); x = -x; } if (x==0) putchar('0'); while (x) { // convert each digit to character and // store in char array a[i++] = x%10 + 48; x /= 10; } // print each character from the array for (j=i-1; j>=0; j--) putchar(a[j]); if (mode == 0) putchar('\\n'); else putchar(' ');}" }, { "code": null, "e": 34803, "s": 33384, "text": "Not using of 1LL or 1ll when needed// A program shows problem if we// don't use 1ll or 1LL#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0;}Output: -727379968\nYou might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long.// C++ program to show that use of 1ll// fixes the problem in above code.#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; long long int z = 1LL*x*y; cout << z; return 0;}Output: 1000000000000\nHere is another place where this trick can help you.// Another problematic code that doesn't // use 1LL or 1ll#include <iostream>using namespace std; int main(){ // we should use 1LL or 1ll here // instead of 1. The correct statement // is \"long long int z = 1LL << 40;\" long long int z = 1 << 40; cout << z; return 0;}Output: 0\n" }, { "code": "// A program shows problem if we// don't use 1ll or 1LL#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0;}", "e": 35067, "s": 34803, "text": null }, { "code": null, "e": 35087, "s": 35067, "text": "Output: -727379968\n" }, { "code": null, "e": 35594, "s": 35087, "text": "You might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long." }, { "code": "// C++ program to show that use of 1ll// fixes the problem in above code.#include <iostream>using namespace std;int main(){ int x = 1000000; int y = 1000000; long long int z = 1LL*x*y; cout << z; return 0;}", "e": 35820, "s": 35594, "text": null }, { "code": null, "e": 35843, "s": 35820, "text": "Output: 1000000000000\n" }, { "code": null, "e": 35896, "s": 35843, "text": "Here is another place where this trick can help you." }, { "code": "// Another problematic code that doesn't // use 1LL or 1ll#include <iostream>using namespace std; int main(){ // we should use 1LL or 1ll here // instead of 1. The correct statement // is \"long long int z = 1LL << 40;\" long long int z = 1 << 40; cout << z; return 0;}", "e": 36183, "s": 35896, "text": null }, { "code": null, "e": 36194, "s": 36183, "text": "Output: 0\n" }, { "code": null, "e": 38719, "s": 36194, "text": "Not using cin.ignore() with getline// A program that shows problem if we// don't use cin.ignore()#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; for(int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << \" \"; cout << s << endl; } return 0;}Input:\n4\na b\nc d\ne f\ng h\nOutput:\n0 \n3 a b\n3 c d\n3 e f\nSo what is the problem here?This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream: \"4\\n\"A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline).Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.cin.ignore(n, delim);This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.// C++ program to show that use of cin.ignore()// fixes the problem in above code.#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; cin.ignore(1, '\\n'); for (int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << \" \"; cout << s << endl; } return 0;}Input:\n4\na b\nc d\ne f\ng h\nOutput:\n3 a b\n3 c d\n3 e f\n3 g h\nBut what if we don’t know how many lines of input are going to be there? We can use this then:// C++ program to handle cases when we// don't know how many lines of input // are going to be there#include <iostream>using namespace std;int main(){ string s; while (getline(cin, s)) { if (s.empty()) break; cout << s << endl; } return 0;}Input:\na b\nc d\ne f\ng h\n\nOutput:\na b\nc d\ne f\ng h\n" }, { "code": "// A program that shows problem if we// don't use cin.ignore()#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; for(int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << \" \"; cout << s << endl; } return 0;}", "e": 39006, "s": 38719, "text": null }, { "code": null, "e": 39061, "s": 39006, "text": "Input:\n4\na b\nc d\ne f\ng h\nOutput:\n0 \n3 a b\n3 c d\n3 e f\n" }, { "code": null, "e": 39359, "s": 39061, "text": "So what is the problem here?This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream:" }, { "code": null, "e": 39369, "s": 39359, "text": " \"4\\n\"" }, { "code": null, "e": 39947, "s": 39369, "text": "A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline)." }, { "code": null, "e": 40404, "s": 39947, "text": "Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.cin.ignore(n, delim);This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim." }, { "code": "// C++ program to show that use of cin.ignore()// fixes the problem in above code.#include <iostream>using namespace std; int main(){ int n; cin >> n; string s; cin.ignore(1, '\\n'); for (int i = 0; i<n; ++i) { getline(cin, s); cout << s.length() << \" \"; cout << s << endl; } return 0;}", "e": 40736, "s": 40404, "text": null }, { "code": null, "e": 40794, "s": 40736, "text": "Input:\n4\na b\nc d\ne f\ng h\nOutput:\n3 a b\n3 c d\n3 e f\n3 g h\n" }, { "code": null, "e": 40889, "s": 40794, "text": "But what if we don’t know how many lines of input are going to be there? We can use this then:" }, { "code": "// C++ program to handle cases when we// don't know how many lines of input // are going to be there#include <iostream>using namespace std;int main(){ string s; while (getline(cin, s)) { if (s.empty()) break; cout << s << endl; } return 0;}", "e": 41170, "s": 40889, "text": null }, { "code": null, "e": 41219, "s": 41170, "text": "Input:\na b\nc d\ne f\ng h\n\nOutput:\na b\nc d\ne f\ng h\n" }, { "code": null, "e": 42326, "s": 41219, "text": "A problem when taking remainders: In a lot of problems, you have to print your solution modulo some large prime (for example 10^9 + 7).// Below program shows problem if we// don't use don't take remainders// properly.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; z = (z + x*y)%mod; // not good practice cout << z; return 0;}Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this:// Program to demonstrate proper// ways of taking remainders.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; // good practice z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod; cout << z; return 0;}This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.Why does this work?Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod." }, { "code": "// Below program shows problem if we// don't use don't take remainders// properly.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; z = (z + x*y)%mod; // not good practice cout << z; return 0;}", "e": 42603, "s": 42326, "text": null }, { "code": null, "e": 42712, "s": 42603, "text": "Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this:" }, { "code": "// Program to demonstrate proper// ways of taking remainders.#include <iostream>#define mod 1000000007using namespace std; int main(){ long long int x, y, z; cin >> x >> y >> z; // good practice z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod; cout << z; return 0;}", "e": 42995, "s": 42712, "text": null }, { "code": null, "e": 43301, "s": 42995, "text": "This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.Why does this work?Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod." }, { "code": null, "e": 45177, "s": 43301, "text": "cin and cout might cause TLE: In a lot of programs, the cause of TLE is generally based on your algorithm. For example, if n = 10^6 and your algorithm runs in O(n^2) then this won’t pass a 1 second Time Limit. But say, you have found an algorithm that runs in O(n) for n = 10^6. This should pass the 1 second Time Limit.What if this is failing?One possible reason is that you are using cin and cout for I/O over multiple test cases.You can use scanf or printf for the same. You can also use some custom Fast I/O function for the same based on something like getchar() and putchar().scanf and printf are faster than cin and cout. See this for more details.Custom Fast I/O functions:// C++ program to demonstrate fast input and output // use long long x = fast_input(); to read in xinline long long int fast_input(void){ char t; long long int x=0; long long int neg=0; t = getchar(); while ((t<48 || t>57) && t!='-') t = getchar(); if (t == '-') //handle negative input { neg = 1; t = getchar(); } while (t>=48 && t<=57) { x = (x<<3) + (x<<1) + t - 48; // x<<3 means 8*x and x<<1 means 2*x so we // have x = 10*x+(t - 48) t = getchar(); } if (neg) x = -x; return x;} // use fast_output(x, 0); to print x and a newline// use fast_output(x, 1); to print x and a ' ' after// the xinline void fast_output(long long int x, int mode){ char a[20]; long long int i=0, j; a[0] = '0'; if (x < 0) { putchar('-'); x = -x; } if (x==0) putchar('0'); while (x) { // convert each digit to character and // store in char array a[i++] = x%10 + 48; x /= 10; } // print each character from the array for (j=i-1; j>=0; j--) putchar(a[j]); if (mode == 0) putchar('\\n'); else putchar(' ');}" }, { "code": null, "e": 45251, "s": 45177, "text": "scanf and printf are faster than cin and cout. See this for more details." }, { "code": null, "e": 45278, "s": 45251, "text": "Custom Fast I/O functions:" }, { "code": "// C++ program to demonstrate fast input and output // use long long x = fast_input(); to read in xinline long long int fast_input(void){ char t; long long int x=0; long long int neg=0; t = getchar(); while ((t<48 || t>57) && t!='-') t = getchar(); if (t == '-') //handle negative input { neg = 1; t = getchar(); } while (t>=48 && t<=57) { x = (x<<3) + (x<<1) + t - 48; // x<<3 means 8*x and x<<1 means 2*x so we // have x = 10*x+(t - 48) t = getchar(); } if (neg) x = -x; return x;} // use fast_output(x, 0); to print x and a newline// use fast_output(x, 1); to print x and a ' ' after// the xinline void fast_output(long long int x, int mode){ char a[20]; long long int i=0, j; a[0] = '0'; if (x < 0) { putchar('-'); x = -x; } if (x==0) putchar('0'); while (x) { // convert each digit to character and // store in char array a[i++] = x%10 + 48; x /= 10; } // print each character from the array for (j=i-1; j>=0; j--) putchar(a[j]); if (mode == 0) putchar('\\n'); else putchar(' ');}", "e": 46473, "s": 45278, "text": null }, { "code": null, "e": 46648, "s": 46473, "text": "Related Articles :A Better Way To Approach Competitive ProgrammingC++ tricks for competitive programming (for C++ 11)Writing C/C++ code efficiently in Competitive programming" }, { "code": null, "e": 46949, "s": 46648, "text": "This article is contributed by Hemang Sarkar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 47074, "s": 46949, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 47078, "s": 47074, "text": "C++" }, { "code": null, "e": 47102, "s": 47078, "text": "Competitive Programming" }, { "code": null, "e": 47106, "s": 47102, "text": "CPP" }, { "code": null, "e": 47204, "s": 47106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47223, "s": 47204, "text": "Inheritance in C++" }, { "code": null, "e": 47247, "s": 47223, "text": "Virtual Function in C++" }, { "code": null, "e": 47271, "s": 47247, "text": "C++ Classes and Objects" }, { "code": null, "e": 47298, "s": 47271, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 47329, "s": 47298, "text": "Templates in C++ with Examples" }, { "code": null, "e": 47372, "s": 47329, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 47415, "s": 47372, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 47456, "s": 47415, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 47534, "s": 47456, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Reverse a number using stack in C++
We are given an integer number Num as input. The goal is to find the reverse of the number using stack. Stack:- A stack is a data structure in C++ which stores data in LIFO ( Last in First Out) manner. Major operations of stack are-: Declaration-: stack <int> stck; //stck is now a stack variable. Finding Top using top(). Function stck.top() returns reference of top element in the stck Finding Top using top(). Function stck.top() returns reference of top element in the stck Removing Top using pop(). Function removes topmost element from the stck Removing Top using pop(). Function removes topmost element from the stck Adding element to top using push(). Function stck.push( value ) adds item value in stack. Value should be of type stck. Adding element to top using push(). Function stck.push( value ) adds item value in stack. Value should be of type stck. Check if staxk is empty using empty(). Function stck.empty() returns true if stack is empty. Check if staxk is empty using empty(). Function stck.empty() returns true if stack is empty. Input − Num = 33267 Output − Reverse of number is: 76233 Explanation− First we will push all elements to stack 7 - 6 - 2 - 3 - 3 ← top 7 * 10000 + 6 * 1000 + 2*100 + 3*10 + 3*1 ← = 70000 + 6000 + 200 + 30 + 3 ← = 76233 Input − Num = 111000 Output − Reverse of number is: 111 Explanation − First we will push all elements to stack 0 - 0 - 0 - 1 - 1 - 1 ← top 0 * 100000 + 0 * 10000 + 0*1000 + 1*100 + 1*10 + 1*1 ← = 0 + 0 + 0 + 100 + 10 + 1 ← = 111 In this approach we will first take remainders of input number and push to stack and reduce number by 10 until number becomes 0. In this way stack will be filled with top as first digit. Take the input number Num. Take the input number Num. Take empty stack for integers using stack<int> stck. Take empty stack for integers using stack<int> stck. Function pushDigts(int num1) takes num1 and adds it to stack with first digit on top. Function pushDigts(int num1) takes num1 and adds it to stack with first digit on top. Take rem as variable. Take rem as variable. Using a while loop check if num1 is non-zero, if true then set rem=num1%10. Using a while loop check if num1 is non-zero, if true then set rem=num1%10. Push rem to stack. Push rem to stack. Reduce num1 by 10 for 2nd digit and so on. Reduce num1 by 10 for 2nd digit and so on. Now reverse the number using elements of stack with function revrseNum(). Now reverse the number using elements of stack with function revrseNum(). Take variables revrs, topp, temp, i. Take variables revrs, topp, temp, i. While the stack is not empty While the stack is not empty Take the topmost element as topp=stck.top(). Take the topmost element as topp=stck.top(). Reduce stack using stck.pop(). Reduce stack using stck.pop(). Set temp=topp*i. Set temp=topp*i. Add temp to revrs. Add temp to revrs. Increase i by i*10 in multiples of 100. Increase i by i*10 in multiples of 100. At the end return the reverse of the input num as revrs. At the end return the reverse of the input num as revrs. Print result obtained inside main. Print result obtained inside main. #include <bits/stdc++.h> using namespace std; stack <int> stck; void pushDigts(int num1){ int rem; while (num1 > 0){ rem=num1 % 10; stck.push(rem); num1 = num1 / 10; } } int revrseNum(){ int revrs = 0; int i = 1; int temp; int topp; while (!stck.empty()){ topp=stck.top(); stck.pop(); temp=topp*i; revrs = revrs + temp; i *= 10; } return revrs; } int main(){ int Num = 43556; pushDigts(Num); cout<<"Reverse of number is: "<<revrseNum(); return 0; } If we run the above code it will generate the following Output Reverse of number is: 65534
[ { "code": null, "e": 1166, "s": 1062, "text": "We are given an integer number Num as input. The goal is to find the reverse of the number using stack." }, { "code": null, "e": 1296, "s": 1166, "text": "Stack:- A stack is a data structure in C++ which stores data in LIFO ( Last in First Out) manner. Major operations of stack are-:" }, { "code": null, "e": 1360, "s": 1296, "text": "Declaration-: stack <int> stck; //stck is now a stack variable." }, { "code": null, "e": 1450, "s": 1360, "text": "Finding Top using top(). Function stck.top() returns reference of top element in the stck" }, { "code": null, "e": 1540, "s": 1450, "text": "Finding Top using top(). Function stck.top() returns reference of top element in the stck" }, { "code": null, "e": 1613, "s": 1540, "text": "Removing Top using pop(). Function removes topmost element from the stck" }, { "code": null, "e": 1686, "s": 1613, "text": "Removing Top using pop(). Function removes topmost element from the stck" }, { "code": null, "e": 1806, "s": 1686, "text": "Adding element to top using push(). Function stck.push( value ) adds item value in stack. Value should be of type stck." }, { "code": null, "e": 1926, "s": 1806, "text": "Adding element to top using push(). Function stck.push( value ) adds item value in stack. Value should be of type stck." }, { "code": null, "e": 2019, "s": 1926, "text": "Check if staxk is empty using empty(). Function stck.empty() returns true if stack is empty." }, { "code": null, "e": 2112, "s": 2019, "text": "Check if staxk is empty using empty(). Function stck.empty() returns true if stack is empty." }, { "code": null, "e": 2132, "s": 2112, "text": "Input − Num = 33267" }, { "code": null, "e": 2169, "s": 2132, "text": "Output − Reverse of number is: 76233" }, { "code": null, "e": 2182, "s": 2169, "text": "Explanation−" }, { "code": null, "e": 2223, "s": 2182, "text": "First we will push all elements to stack" }, { "code": null, "e": 2247, "s": 2223, "text": "7 - 6 - 2 - 3 - 3 ← top" }, { "code": null, "e": 2291, "s": 2247, "text": "7 * 10000 + 6 * 1000 + 2*100 + 3*10 + 3*1 ←" }, { "code": null, "e": 2323, "s": 2291, "text": "= 70000 + 6000 + 200 + 30 + 3 ←" }, { "code": null, "e": 2331, "s": 2323, "text": "= 76233" }, { "code": null, "e": 2352, "s": 2331, "text": "Input − Num = 111000" }, { "code": null, "e": 2387, "s": 2352, "text": "Output − Reverse of number is: 111" }, { "code": null, "e": 2401, "s": 2387, "text": "Explanation −" }, { "code": null, "e": 2442, "s": 2401, "text": "First we will push all elements to stack" }, { "code": null, "e": 2470, "s": 2442, "text": "0 - 0 - 0 - 1 - 1 - 1 ← top" }, { "code": null, "e": 2525, "s": 2470, "text": "0 * 100000 + 0 * 10000 + 0*1000 + 1*100 + 1*10 + 1*1 ←" }, { "code": null, "e": 2554, "s": 2525, "text": "= 0 + 0 + 0 + 100 + 10 + 1 ←" }, { "code": null, "e": 2560, "s": 2554, "text": "= 111" }, { "code": null, "e": 2747, "s": 2560, "text": "In this approach we will first take remainders of input number and push to stack and reduce number by 10 until number becomes 0. In this way stack will be filled with top as first digit." }, { "code": null, "e": 2774, "s": 2747, "text": "Take the input number Num." }, { "code": null, "e": 2801, "s": 2774, "text": "Take the input number Num." }, { "code": null, "e": 2854, "s": 2801, "text": "Take empty stack for integers using stack<int> stck." }, { "code": null, "e": 2907, "s": 2854, "text": "Take empty stack for integers using stack<int> stck." }, { "code": null, "e": 2993, "s": 2907, "text": "Function pushDigts(int num1) takes num1 and adds it to stack with first digit on top." }, { "code": null, "e": 3079, "s": 2993, "text": "Function pushDigts(int num1) takes num1 and adds it to stack with first digit on top." }, { "code": null, "e": 3101, "s": 3079, "text": "Take rem as variable." }, { "code": null, "e": 3123, "s": 3101, "text": "Take rem as variable." }, { "code": null, "e": 3199, "s": 3123, "text": "Using a while loop check if num1 is non-zero, if true then set rem=num1%10." }, { "code": null, "e": 3275, "s": 3199, "text": "Using a while loop check if num1 is non-zero, if true then set rem=num1%10." }, { "code": null, "e": 3294, "s": 3275, "text": "Push rem to stack." }, { "code": null, "e": 3313, "s": 3294, "text": "Push rem to stack." }, { "code": null, "e": 3356, "s": 3313, "text": "Reduce num1 by 10 for 2nd digit and so on." }, { "code": null, "e": 3399, "s": 3356, "text": "Reduce num1 by 10 for 2nd digit and so on." }, { "code": null, "e": 3473, "s": 3399, "text": "Now reverse the number using elements of stack with function revrseNum()." }, { "code": null, "e": 3547, "s": 3473, "text": "Now reverse the number using elements of stack with function revrseNum()." }, { "code": null, "e": 3584, "s": 3547, "text": "Take variables revrs, topp, temp, i." }, { "code": null, "e": 3621, "s": 3584, "text": "Take variables revrs, topp, temp, i." }, { "code": null, "e": 3650, "s": 3621, "text": "While the stack is not empty" }, { "code": null, "e": 3679, "s": 3650, "text": "While the stack is not empty" }, { "code": null, "e": 3724, "s": 3679, "text": "Take the topmost element as topp=stck.top()." }, { "code": null, "e": 3769, "s": 3724, "text": "Take the topmost element as topp=stck.top()." }, { "code": null, "e": 3800, "s": 3769, "text": "Reduce stack using stck.pop()." }, { "code": null, "e": 3831, "s": 3800, "text": "Reduce stack using stck.pop()." }, { "code": null, "e": 3848, "s": 3831, "text": "Set temp=topp*i." }, { "code": null, "e": 3865, "s": 3848, "text": "Set temp=topp*i." }, { "code": null, "e": 3884, "s": 3865, "text": "Add temp to revrs." }, { "code": null, "e": 3903, "s": 3884, "text": "Add temp to revrs." }, { "code": null, "e": 3943, "s": 3903, "text": "Increase i by i*10 in multiples of 100." }, { "code": null, "e": 3983, "s": 3943, "text": "Increase i by i*10 in multiples of 100." }, { "code": null, "e": 4040, "s": 3983, "text": "At the end return the reverse of the input num as revrs." }, { "code": null, "e": 4097, "s": 4040, "text": "At the end return the reverse of the input num as revrs." }, { "code": null, "e": 4132, "s": 4097, "text": "Print result obtained inside main." }, { "code": null, "e": 4167, "s": 4132, "text": "Print result obtained inside main." }, { "code": null, "e": 4706, "s": 4167, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstack <int> stck;\nvoid pushDigts(int num1){\n int rem;\n while (num1 > 0){\n rem=num1 % 10;\n stck.push(rem);\n num1 = num1 / 10;\n }\n}\nint revrseNum(){\n int revrs = 0;\n int i = 1;\n int temp;\n int topp;\n while (!stck.empty()){\n topp=stck.top();\n stck.pop();\n temp=topp*i;\n revrs = revrs + temp;\n i *= 10;\n }\n return revrs;\n}\nint main(){\n int Num = 43556;\n pushDigts(Num);\n cout<<\"Reverse of number is: \"<<revrseNum();\n return 0;\n}" }, { "code": null, "e": 4769, "s": 4706, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 4797, "s": 4769, "text": "Reverse of number is: 65534" } ]
Java Interface
Another way to achieve abstraction in Java, is with interfaces. An interface is a completely "abstract class" that is used to group related methods with empty bodies: // interface interface Animal { public void animalSound(); // interface method (does not have a body) public void run(); // interface method (does not have a body) } To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class: // Interface interface Animal { public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) } // Pig "implements" the Animal interface class Pig implements Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); } public void sleep() { // The body of sleep() is provided here System.out.println("Zzz"); } } class Main { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } } Try it Yourself » Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) Interface methods do not have a body - the body is provided by the "implement" class On implementation of an interface, you must override all of its methods Interface methods are by default abstract and public Interface attributes are by default public, static and final An interface cannot contain a constructor (as it cannot be used to create objects) 1) To achieve security - hide certain details and only show the important details of an object (interface). 2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below). To implement multiple interfaces, separate them with a comma: interface FirstInterface { public void myMethod(); // interface method } interface SecondInterface { public void myOtherMethod(); // interface method } class DemoClass implements FirstInterface, SecondInterface { public void myMethod() { System.out.println("Some text.."); } public void myOtherMethod() { System.out.println("Some other text..."); } } class Main { public static void main(String[] args) { DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); } } Try it Yourself » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 64, "s": 0, "text": "Another way to achieve abstraction in Java, is with interfaces." }, { "code": null, "e": 168, "s": 64, "text": "An interface is a completely \"abstract class\" \nthat is used to group related methods with empty bodies:" }, { "code": null, "e": 341, "s": 168, "text": "// interface\ninterface Animal {\n public void animalSound(); // interface method (does not have a body)\n public void run(); // interface method (does not have a body)\n}\n \n" }, { "code": null, "e": 574, "s": 341, "text": "To access the interface methods, the interface must be \"implemented\" \n(kinda like inherited) by another class with the implements \nkeyword (instead of extends). The body of the \ninterface method is provided by the \"implement\" class:" }, { "code": null, "e": 1219, "s": 574, "text": "// Interface\ninterface Animal {\n public void animalSound(); // interface method (does not have a body)\n public void sleep(); // interface method (does not have a body)\n}\n\n// Pig \"implements\" the Animal interface\nclass Pig implements Animal {\n public void animalSound() {\n // The body of animalSound() is provided here\n System.out.println(\"The pig says: wee wee\");\n }\n public void sleep() {\n // The body of sleep() is provided here\n System.out.println(\"Zzz\");\n }\n}\n\nclass Main {\n public static void main(String[] args) {\n Pig myPig = new Pig(); // Create a Pig object\n myPig.animalSound();\n myPig.sleep();\n }\n}\n \n \n" }, { "code": null, "e": 1239, "s": 1219, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1398, "s": 1239, "text": "Like abstract classes, interfaces cannot be used to create objects (in the example above, \nit is not possible to create an \"Animal\" object in the MyMainClass)" }, { "code": null, "e": 1484, "s": 1398, "text": "Interface methods do not have a body - the \nbody is provided by the \"implement\" class" }, { "code": null, "e": 1556, "s": 1484, "text": "On implementation of an interface, you must override all of its methods" }, { "code": null, "e": 1612, "s": 1556, "text": "Interface methods are by default abstract and \n public" }, { "code": null, "e": 1676, "s": 1612, "text": "Interface attributes are by default public, \n static and final" }, { "code": null, "e": 1759, "s": 1676, "text": "An interface cannot contain a constructor (as it cannot be used to create objects)" }, { "code": null, "e": 1868, "s": 1759, "text": "1) To achieve security - hide certain details and only show the important \ndetails of an object (interface)." }, { "code": null, "e": 2155, "s": 1868, "text": "2) Java does not support \"multiple inheritance\" (a class can only inherit from one superclass). However, it can be achieved \n with interfaces, because the class can implement multiple interfaces.\n Note: To implement multiple interfaces, separate them with a comma (see example below)." }, { "code": null, "e": 2217, "s": 2155, "text": "To implement multiple interfaces, separate them with a comma:" }, { "code": null, "e": 2744, "s": 2217, "text": "interface FirstInterface {\n public void myMethod(); // interface method\n}\n\ninterface SecondInterface {\n public void myOtherMethod(); // interface method\n}\n\nclass DemoClass implements FirstInterface, SecondInterface {\n public void myMethod() {\n System.out.println(\"Some text..\");\n }\n public void myOtherMethod() {\n System.out.println(\"Some other text...\");\n }\n}\n\nclass Main {\n public static void main(String[] args) {\n DemoClass myObj = new DemoClass();\n myObj.myMethod();\n myObj.myOtherMethod();\n }\n}\n \n" }, { "code": null, "e": 2764, "s": 2744, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2797, "s": 2764, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2839, "s": 2797, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2946, "s": 2839, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2965, "s": 2946, "text": "help@w3schools.com" } ]
Recursive Selection Sort - GeeksforGeeks
29 Apr, 2022 The Selection Sort algorithm sorts maintain two parts. The first part that is already sortedThe second part is yet to be sorted. The first part that is already sorted The second part is yet to be sorted. The algorithm works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the end of the sorted part. arr[] = 64 25 12 22 11 // Find the minimum element in arr[0...4] // and place it at beginning 11 25 12 22 64 // Find the minimum element in arr[1...4] // and place it at beginning of arr[1...4] 11 12 25 22 64 // Find the minimum element in arr[2...4] // and place it at beginning of arr[2...4] 11 12 22 25 64 // Find the minimum element in arr[3...4] // and place it at beginning of arr[3...4] 11 12 22 25 64 We have already discussed Iterative Selection Sort. In this article recursive approach is discussed. The idea of a recursive solution is to one by one increment sorted part and recursively call for the remaining (yet to be sorted) part. C++ Java Python3 C# // Recursive C++ program to sort an array// using selection sort#include <iostream>using namespace std; // Return minimum indexint minIndex(int a[], int i, int j){ if (i == j) return i; // Find minimum of remaining elements int k = minIndex(a, i + 1, j); // Return minimum of current and remaining. return (a[i] < a[k])? i : k;} // Recursive selection sort. n is size of a[] and index// is index of starting element.void recurSelectionSort(int a[], int n, int index = 0){ // Return when starting and size are same if (index == n) return; // calling minimum index function for minimum index int k = minIndex(a, index, n-1); // Swapping when index and minimum index are not same if (k != index) swap(a[k], a[index]); // Recursively calling selection sort function recurSelectionSort(a, n, index + 1);} // Driver codeint main(){ int arr[] = {3, 1, 5, 2, 7, 0}; int n = sizeof(arr)/sizeof(arr[0]); // Calling function recurSelectionSort(arr, n); //printing sorted array for (int i = 0; i<n ; i++) cout << arr[i] << " "; cout << endl; return 0;} // Recursive Java program to sort an array// using selection sort class Test{ // Return minimum index static int minIndex(int a[], int i, int j) { if (i == j) return i; // Find minimum of remaining elements int k = minIndex(a, i + 1, j); // Return minimum of current and remaining. return (a[i] < a[k])? i : k; } // Recursive selection sort. n is size of a[] and index // is index of starting element. static void recurSelectionSort(int a[], int n, int index) { // Return when starting and size are same if (index == n) return; // calling minimum index function for minimum index int k = minIndex(a, index, n-1); // Swapping when index nd minimum index are not same if (k != index){ // swap int temp = a[k]; a[k] = a[index]; a[index] = temp; } // Recursively calling selection sort function recurSelectionSort(a, n, index + 1); } // Driver method public static void main(String args[]) { int arr[] = {3, 1, 5, 2, 7, 0}; // Calling function recurSelectionSort(arr, arr.length, 0); //printing sorted array for (int i = 0; i< arr.length; i++) System.out.print(arr[i] + " "); }} # Recursive Python3 code to sort# an array using selection sort # Return minimum indexdef minIndex( a , i , j ): if i == j: return i # Find minimum of remaining elements k = minIndex(a, i + 1, j) # Return minimum of current # and remaining. return (i if a[i] < a[k] else k) # Recursive selection sort. n is# size of a[] and index is index of# starting element.def recurSelectionSort(a, n, index = 0): # Return when starting and # size are same if index == n: return -1 # calling minimum index function # for minimum index k = minIndex(a, index, n-1) # Swapping when index and minimum # index are not same if k != index: a[k], a[index] = a[index], a[k] # Recursively calling selection # sort function recurSelectionSort(a, n, index + 1) # Driver codearr = [3, 1, 5, 2, 7, 0]n = len(arr) # Calling functionrecurSelectionSort(arr, n) # printing sorted arrayfor i in arr: print(i, end = ' ') # This code is contributed by "Sharad_Bhardwaj". // Recursive C# program to sort an array// using selection sortusing System; class GFG{ // Return minimum index static int minIndex(int []a, int i, int j) { if (i == j) return i; // Find minimum of remaining elements int k = minIndex(a, i + 1, j); // Return minimum of current and remaining. return (a[i] < a[k])? i : k; } // Recursive selection sort. n is size of // a[] and index is index of starting element. static void recurSelectionSort(int []a, int n, int index) { // Return when starting and size are same if (index == n) return; // calling minimum index function // for minimum index int k = minIndex(a, index, n - 1); // Swapping when index and minimum index // are not same if (k != index) { // swap int temp = a[k]; a[k] = a[index]; a[index] = temp; } // Recursively calling selection sort function recurSelectionSort(a, n, index + 1); } // Driver Code public static void Main(String []args) { int []arr = {3, 1, 5, 2, 7, 0}; // Calling function recurSelectionSort(arr, arr.Length, 0); //printing sorted array for (int i = 0; i< arr.Length; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Princi Singh Output: 0 1 2 3 5 7 This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princi singh amandeepkaur93031 princebansal07 Medlife Sorting Medlife Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Quick Sort vs Merge Sort Stability in sorting algorithms Quickselect Algorithm Segregate 0s and 1s in an array Chocolate Distribution Problem Sorting in Java QuickSort using Random Pivoting Sort a nearly sorted (or K sorted) array Binary Insertion Sort
[ { "code": null, "e": 24078, "s": 24050, "text": "\n29 Apr, 2022" }, { "code": null, "e": 24134, "s": 24078, "text": "The Selection Sort algorithm sorts maintain two parts. " }, { "code": null, "e": 24208, "s": 24134, "text": "The first part that is already sortedThe second part is yet to be sorted." }, { "code": null, "e": 24246, "s": 24208, "text": "The first part that is already sorted" }, { "code": null, "e": 24283, "s": 24246, "text": "The second part is yet to be sorted." }, { "code": null, "e": 24446, "s": 24283, "text": "The algorithm works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the end of the sorted part. " }, { "code": null, "e": 24860, "s": 24446, "text": "arr[] = 64 25 12 22 11\n\n// Find the minimum element in arr[0...4]\n// and place it at beginning\n11 25 12 22 64\n\n// Find the minimum element in arr[1...4]\n// and place it at beginning of arr[1...4]\n11 12 25 22 64\n\n// Find the minimum element in arr[2...4]\n// and place it at beginning of arr[2...4]\n11 12 22 25 64\n\n// Find the minimum element in arr[3...4]\n// and place it at beginning of arr[3...4]\n11 12 22 25 64 " }, { "code": null, "e": 25097, "s": 24860, "text": "We have already discussed Iterative Selection Sort. In this article recursive approach is discussed. The idea of a recursive solution is to one by one increment sorted part and recursively call for the remaining (yet to be sorted) part." }, { "code": null, "e": 25101, "s": 25097, "text": "C++" }, { "code": null, "e": 25106, "s": 25101, "text": "Java" }, { "code": null, "e": 25114, "s": 25106, "text": "Python3" }, { "code": null, "e": 25117, "s": 25114, "text": "C#" }, { "code": "// Recursive C++ program to sort an array// using selection sort#include <iostream>using namespace std; // Return minimum indexint minIndex(int a[], int i, int j){ if (i == j) return i; // Find minimum of remaining elements int k = minIndex(a, i + 1, j); // Return minimum of current and remaining. return (a[i] < a[k])? i : k;} // Recursive selection sort. n is size of a[] and index// is index of starting element.void recurSelectionSort(int a[], int n, int index = 0){ // Return when starting and size are same if (index == n) return; // calling minimum index function for minimum index int k = minIndex(a, index, n-1); // Swapping when index and minimum index are not same if (k != index) swap(a[k], a[index]); // Recursively calling selection sort function recurSelectionSort(a, n, index + 1);} // Driver codeint main(){ int arr[] = {3, 1, 5, 2, 7, 0}; int n = sizeof(arr)/sizeof(arr[0]); // Calling function recurSelectionSort(arr, n); //printing sorted array for (int i = 0; i<n ; i++) cout << arr[i] << \" \"; cout << endl; return 0;}", "e": 26254, "s": 25117, "text": null }, { "code": "// Recursive Java program to sort an array// using selection sort class Test{ // Return minimum index static int minIndex(int a[], int i, int j) { if (i == j) return i; // Find minimum of remaining elements int k = minIndex(a, i + 1, j); // Return minimum of current and remaining. return (a[i] < a[k])? i : k; } // Recursive selection sort. n is size of a[] and index // is index of starting element. static void recurSelectionSort(int a[], int n, int index) { // Return when starting and size are same if (index == n) return; // calling minimum index function for minimum index int k = minIndex(a, index, n-1); // Swapping when index nd minimum index are not same if (k != index){ // swap int temp = a[k]; a[k] = a[index]; a[index] = temp; } // Recursively calling selection sort function recurSelectionSort(a, n, index + 1); } // Driver method public static void main(String args[]) { int arr[] = {3, 1, 5, 2, 7, 0}; // Calling function recurSelectionSort(arr, arr.length, 0); //printing sorted array for (int i = 0; i< arr.length; i++) System.out.print(arr[i] + \" \"); }}", "e": 27636, "s": 26254, "text": null }, { "code": "# Recursive Python3 code to sort# an array using selection sort # Return minimum indexdef minIndex( a , i , j ): if i == j: return i # Find minimum of remaining elements k = minIndex(a, i + 1, j) # Return minimum of current # and remaining. return (i if a[i] < a[k] else k) # Recursive selection sort. n is# size of a[] and index is index of# starting element.def recurSelectionSort(a, n, index = 0): # Return when starting and # size are same if index == n: return -1 # calling minimum index function # for minimum index k = minIndex(a, index, n-1) # Swapping when index and minimum # index are not same if k != index: a[k], a[index] = a[index], a[k] # Recursively calling selection # sort function recurSelectionSort(a, n, index + 1) # Driver codearr = [3, 1, 5, 2, 7, 0]n = len(arr) # Calling functionrecurSelectionSort(arr, n) # printing sorted arrayfor i in arr: print(i, end = ' ') # This code is contributed by \"Sharad_Bhardwaj\".", "e": 28701, "s": 27636, "text": null }, { "code": "// Recursive C# program to sort an array// using selection sortusing System; class GFG{ // Return minimum index static int minIndex(int []a, int i, int j) { if (i == j) return i; // Find minimum of remaining elements int k = minIndex(a, i + 1, j); // Return minimum of current and remaining. return (a[i] < a[k])? i : k; } // Recursive selection sort. n is size of // a[] and index is index of starting element. static void recurSelectionSort(int []a, int n, int index) { // Return when starting and size are same if (index == n) return; // calling minimum index function // for minimum index int k = minIndex(a, index, n - 1); // Swapping when index and minimum index // are not same if (k != index) { // swap int temp = a[k]; a[k] = a[index]; a[index] = temp; } // Recursively calling selection sort function recurSelectionSort(a, n, index + 1); } // Driver Code public static void Main(String []args) { int []arr = {3, 1, 5, 2, 7, 0}; // Calling function recurSelectionSort(arr, arr.Length, 0); //printing sorted array for (int i = 0; i< arr.Length; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Princi Singh", "e": 30193, "s": 28701, "text": null }, { "code": null, "e": 30203, "s": 30193, "text": "Output: " }, { "code": null, "e": 30216, "s": 30203, "text": "0 1 2 3 5 7 " }, { "code": null, "e": 30642, "s": 30216, "text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30655, "s": 30642, "text": "princi singh" }, { "code": null, "e": 30673, "s": 30655, "text": "amandeepkaur93031" }, { "code": null, "e": 30688, "s": 30673, "text": "princebansal07" }, { "code": null, "e": 30696, "s": 30688, "text": "Medlife" }, { "code": null, "e": 30704, "s": 30696, "text": "Sorting" }, { "code": null, "e": 30712, "s": 30704, "text": "Medlife" }, { "code": null, "e": 30720, "s": 30712, "text": "Sorting" }, { "code": null, "e": 30818, "s": 30720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30844, "s": 30818, "text": "C++ Program for QuickSort" }, { "code": null, "e": 30869, "s": 30844, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 30901, "s": 30869, "text": "Stability in sorting algorithms" }, { "code": null, "e": 30923, "s": 30901, "text": "Quickselect Algorithm" }, { "code": null, "e": 30955, "s": 30923, "text": "Segregate 0s and 1s in an array" }, { "code": null, "e": 30986, "s": 30955, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31002, "s": 30986, "text": "Sorting in Java" }, { "code": null, "e": 31034, "s": 31002, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 31075, "s": 31034, "text": "Sort a nearly sorted (or K sorted) array" } ]
Lodash _.isNumber() Function - GeeksforGeeks
25 Nov, 2021 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.isNumber() method is used to find whether the given value parameter is number or not. If the given value is a number then it returns True value otherwise, it returns False. Syntax: _.isNumber(value) Parameters: This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value to check. value: This parameter holds the value to check. Return Value: This method returns true if the value is a number, else false. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.isNumber() method console.log(_.isNumber(10)); console.log(_.isNumber('GeeksforGeeks')); console.log(_.isNumber(15.675)); Output: true false true Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.isNumber() // method console.log(_.isNumber(true));console.log(_.isNumber(Number.MIN_VALUE)); console.log(_.isNumber(Infinity));console.log(_.isNumber('3')); Output: false true true false JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Node.js | fs.writeFileSync() Method Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 24978, "s": 24950, "text": "\n25 Nov, 2021" }, { "code": null, "e": 25118, "s": 24978, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 25297, "s": 25118, "text": "The _.isNumber() method is used to find whether the given value parameter is number or not. If the given value is a number then it returns True value otherwise, it returns False." }, { "code": null, "e": 25305, "s": 25297, "text": "Syntax:" }, { "code": null, "e": 25323, "s": 25305, "text": "_.isNumber(value)" }, { "code": null, "e": 25414, "s": 25323, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 25462, "s": 25414, "text": "value: This parameter holds the value to check." }, { "code": null, "e": 25510, "s": 25462, "text": "value: This parameter holds the value to check." }, { "code": null, "e": 25587, "s": 25510, "text": "Return Value: This method returns true if the value is a number, else false." }, { "code": null, "e": 25684, "s": 25587, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file." }, { "code": null, "e": 25695, "s": 25684, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNumber() method console.log(_.isNumber(10)); console.log(_.isNumber('GeeksforGeeks')); console.log(_.isNumber(15.675));", "e": 25899, "s": 25695, "text": null }, { "code": null, "e": 25907, "s": 25899, "text": "Output:" }, { "code": null, "e": 25923, "s": 25907, "text": "true\nfalse\ntrue" }, { "code": null, "e": 25936, "s": 25923, "text": "Example 2: " }, { "code": null, "e": 25947, "s": 25936, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isNumber() // method console.log(_.isNumber(true));console.log(_.isNumber(Number.MIN_VALUE)); console.log(_.isNumber(Infinity));console.log(_.isNumber('3'));", "e": 26188, "s": 25947, "text": null }, { "code": null, "e": 26196, "s": 26188, "text": "Output:" }, { "code": null, "e": 26218, "s": 26196, "text": "false\ntrue\ntrue\nfalse" }, { "code": null, "e": 26236, "s": 26218, "text": "JavaScript-Lodash" }, { "code": null, "e": 26247, "s": 26236, "text": "JavaScript" }, { "code": null, "e": 26264, "s": 26247, "text": "Web Technologies" }, { "code": null, "e": 26362, "s": 26264, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26407, "s": 26362, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26468, "s": 26407, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26540, "s": 26468, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26581, "s": 26540, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26617, "s": 26581, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 26659, "s": 26617, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26692, "s": 26659, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26735, "s": 26692, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26785, "s": 26735, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MySQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database. The column parameters specify the names of the columns of the table. The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.). Tip: For an overview of the available data types, go to our complete Data Types Reference. The following example creates a table called "Persons" that contains five columns: PersonID, LastName, FirstName, Address, and City: The PersonID column is of type int and will hold an integer. The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters. The empty "Persons" table will now look like this: Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement. A copy of an existing table can also be created using CREATE TABLE. The new table gets the same column definitions. All columns or specific columns can be selected. If you create a new table using an existing table, the new table will be filled with the existing values from the old table. The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table): Write the correct SQL statement to create a new table called Persons. ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 72, "s": 0, "text": "The CREATE TABLE statement is used to create a new table in a database." }, { "code": null, "e": 141, "s": 72, "text": "The column parameters specify the names of the columns of the table." }, { "code": null, "e": 248, "s": 141, "text": "The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.)." }, { "code": null, "e": 339, "s": 248, "text": "Tip: For an overview of the available data types, go to our complete Data Types Reference." }, { "code": null, "e": 473, "s": 339, "text": "The following example creates a table called \"Persons\" that contains five columns: PersonID, LastName, FirstName, \nAddress, and City:" }, { "code": null, "e": 534, "s": 473, "text": "The PersonID column is of type int and will hold an integer." }, { "code": null, "e": 691, "s": 534, "text": "The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields \nis 255 characters." }, { "code": null, "e": 742, "s": 691, "text": "The empty \"Persons\" table will now look like this:" }, { "code": null, "e": 838, "s": 742, "text": "Tip: The empty \"Persons\" table can now be filled with data with the \nSQL INSERT INTO statement." }, { "code": null, "e": 906, "s": 838, "text": "A copy of an existing table can also be created using CREATE TABLE." }, { "code": null, "e": 1003, "s": 906, "text": "The new table gets the same column definitions. All columns or specific columns can be selected." }, { "code": null, "e": 1128, "s": 1003, "text": "If you create a new table using an existing table, the new table will be filled with the existing values from the old table." }, { "code": null, "e": 1232, "s": 1128, "text": "The following SQL creates a new table called \"TestTables\" (which is \na copy of the \"Customers\" table): " }, { "code": null, "e": 1302, "s": 1232, "text": "Write the correct SQL statement to create a new table called Persons." }, { "code": null, "e": 1421, "s": 1302, "text": " (\n PersonID int,\n LastName varchar(255),\n FirstName varchar(255),\n Address varchar(255),\n City varchar(255) \n);\n" }, { "code": null, "e": 1440, "s": 1421, "text": "Start the Exercise" }, { "code": null, "e": 1473, "s": 1440, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1515, "s": 1473, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1622, "s": 1515, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1641, "s": 1622, "text": "help@w3schools.com" } ]
SQL Tryit Editor v1.6
SELECT * FROM Orders WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31'; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 21, "s": 0, "text": "SELECT * FROM Orders" }, { "code": null, "e": 76, "s": 21, "text": "WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';" }, { "code": null, "e": 78, "s": 76, "text": "​" }, { "code": null, "e": 141, "s": 78, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 201, "s": 141, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 269, "s": 201, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 307, "s": 269, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 392, "s": 307, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 566, "s": 392, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 617, "s": 566, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 685, "s": 617, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 856, "s": 685, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 956, "s": 856, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1016, "s": 956, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
atd command in Linux with examples - GeeksforGeeks
04 Apr, 2019 atd is a job scheduler daemon that runs jobs scheduled for later execution. These jobs are one-time task(not recurring) at a specific time scheduled using ‘at’ or ‘batch’ utility. Syntax: atd [-l load_avg] [-b batch_interval] [-d] [-f] [-s] Options: -l : Specifies a limiting load factor, over which batch jobs should not be run, instead of the compile-time choice of 1.5. -b : Specify the minimum interval in seconds between the start of two batch jobs (60 default). -d : Debug; print error messages to standard error instead of using syslog(3). This option also implies -f. -f : Run atd in the foreground. -s : Process the at/batch queue only once. This is primarily of use for compatibility with old versions of at; atd -s is equivalent to the old atrun command. Starting atd: To start atd in the current session, use below command:$ service atd start $ service atd start To start atd automatically at boot time, use below command:$ chkconfig atd on $ chkconfig atd on While using ‘at’ utility, the following issue can be seen:It means that atd is not running and needs to be started. It means that atd is not running and needs to be started. Stopping atd: To stop atd in the current session, use below command:$ service atd stop $ service atd stop To disable atd from starting at boot time, use below command:$ chkconfig atd off $ chkconfig atd off Restarting atd: To restart atd, use below command. $ service atd restart Checking atd status: To determine if atd is running or not, use below command: $ service atd status If atd is running, status will be “active”: If atd is not running, status will be “inactive”:Example: Example: linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24040, "s": 24012, "text": "\n04 Apr, 2019" }, { "code": null, "e": 24220, "s": 24040, "text": "atd is a job scheduler daemon that runs jobs scheduled for later execution. These jobs are one-time task(not recurring) at a specific time scheduled using ‘at’ or ‘batch’ utility." }, { "code": null, "e": 24228, "s": 24220, "text": "Syntax:" }, { "code": null, "e": 24281, "s": 24228, "text": "atd [-l load_avg] [-b batch_interval] [-d] [-f] [-s]" }, { "code": null, "e": 24290, "s": 24281, "text": "Options:" }, { "code": null, "e": 24413, "s": 24290, "text": "-l : Specifies a limiting load factor, over which batch jobs should not be run, instead of the compile-time choice of 1.5." }, { "code": null, "e": 24508, "s": 24413, "text": "-b : Specify the minimum interval in seconds between the start of two batch jobs (60 default)." }, { "code": null, "e": 24616, "s": 24508, "text": "-d : Debug; print error messages to standard error instead of using syslog(3). This option also implies -f." }, { "code": null, "e": 24648, "s": 24616, "text": "-f : Run atd in the foreground." }, { "code": null, "e": 24806, "s": 24648, "text": "-s : Process the at/batch queue only once. This is primarily of use for compatibility with old versions of at; atd -s is equivalent to the old atrun command." }, { "code": null, "e": 24820, "s": 24806, "text": "Starting atd:" }, { "code": null, "e": 24896, "s": 24820, "text": "To start atd in the current session, use below command:$ service atd start " }, { "code": null, "e": 24917, "s": 24896, "text": "$ service atd start " }, { "code": null, "e": 24996, "s": 24917, "text": "To start atd automatically at boot time, use below command:$ chkconfig atd on " }, { "code": null, "e": 25016, "s": 24996, "text": "$ chkconfig atd on " }, { "code": null, "e": 25132, "s": 25016, "text": "While using ‘at’ utility, the following issue can be seen:It means that atd is not running and needs to be started." }, { "code": null, "e": 25190, "s": 25132, "text": "It means that atd is not running and needs to be started." }, { "code": null, "e": 25204, "s": 25190, "text": "Stopping atd:" }, { "code": null, "e": 25278, "s": 25204, "text": "To stop atd in the current session, use below command:$ service atd stop " }, { "code": null, "e": 25298, "s": 25278, "text": "$ service atd stop " }, { "code": null, "e": 25380, "s": 25298, "text": "To disable atd from starting at boot time, use below command:$ chkconfig atd off " }, { "code": null, "e": 25401, "s": 25380, "text": "$ chkconfig atd off " }, { "code": null, "e": 25452, "s": 25401, "text": "Restarting atd: To restart atd, use below command." }, { "code": null, "e": 25475, "s": 25452, "text": "$ service atd restart " }, { "code": null, "e": 25554, "s": 25475, "text": "Checking atd status: To determine if atd is running or not, use below command:" }, { "code": null, "e": 25576, "s": 25554, "text": "$ service atd status " }, { "code": null, "e": 25620, "s": 25576, "text": "If atd is running, status will be “active”:" }, { "code": null, "e": 25678, "s": 25620, "text": "If atd is not running, status will be “inactive”:Example:" }, { "code": null, "e": 25687, "s": 25678, "text": "Example:" }, { "code": null, "e": 25701, "s": 25687, "text": "linux-command" }, { "code": null, "e": 25721, "s": 25701, "text": "Linux-misc-commands" }, { "code": null, "e": 25728, "s": 25721, "text": "Picked" }, { "code": null, "e": 25739, "s": 25728, "text": "Linux-Unix" }, { "code": null, "e": 25837, "s": 25739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25846, "s": 25837, "text": "Comments" }, { "code": null, "e": 25859, "s": 25846, "text": "Old Comments" }, { "code": null, "e": 25894, "s": 25859, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25931, "s": 25894, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25965, "s": 25931, "text": "mv command in Linux with examples" }, { "code": null, "e": 25991, "s": 25965, "text": "Thread functions in C/C++" }, { "code": null, "e": 26017, "s": 25991, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26054, "s": 26017, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26094, "s": 26054, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26123, "s": 26094, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26165, "s": 26123, "text": "Named Pipe or FIFO with example C program" } ]
Data Visualization: How to choose the right chart [Part 1] | by XuanKhanh Nguyen | Towards Data Science
According to the World Economic Forum, the world produces 2.5 quintillion bytes of data every day. With so much data, it’s become increasingly difficult to manage and make sense of it all. It would be impossible for any person to wade through data line-by-line and see distinct patterns and make observations. Data visualization is one of the data science processes; that is, a framework for approaching data science tasks. After data is collected, processed, and modeled, the relationships need to be visualized for the conclusions. We use data visualization as a technique to communicate insights from data through visual representation. Our main goal is to distill large datasets into visual graphics to allow for a straightforward understanding of complex relationships within the data. So now, we know data visualization can provide insight that traditional descriptive statistics cannot. Our big question is how to choose the right chart for the data? This note will give us an overview of the different chart types. For each type of chart, we will introduce a short description. We then discuss when to use it and when we should avoid using it. Next, we will look at some Python code for implementation. I only present the primary principle; the full version will be provided at the end of this article. I hope this note is interesting enough to pick up the slack. Let’s hop to it. Before making a chart, it’s essential to understand why we need one. Graphs, plots, maps, and diagrams help people understand complex data, find patterns, identify trends, and tell stories. Think about the message we want to share with our audience. Here, I group the charts by their data visualization functions, that is, what we want our charts to communicate with our audience. While each chart’s allocation into specific functions isn’t a perfect system, it still works as a useful guide for selecting a chart based on our analysis or communication needs. The first part of this note will introduce us to different charts to display the connection between variables, the trend over time, and the relative order of variables within category(ies) 1. Scatter plot using Matplotlib2. Marginal Histogram3. Scatter plot using Seaborn4. Pair Plot in Seaborn5. Heat Map 6. Line Chart7. Area Chart8. Stack Area Chart9. Area Chart Unstacked 10. Vertical Bar Chart11. Horizontal Bar Chart12. Multi-set Bar Chart13. Stack Bar Chart14. Lollipop Chart The second part of this note will introduce us to different chart types use to compare variables and their distribution. 15. Histogram16. Density Curve with Histogram17. Density Plot18. Box Plot19. Strip Plot20. Violin Plot21. Population Pyramid 22. Bubble Chart23. Bullet Chart24. Pie Chart25. Net Pie Chart26. Donut Chart27. TreeMap28. Diverging Bar29. Choropleth Map30. Bubble Map We use a relationship method to display a connection or correlation between two or more variables. When assessing a relationship between data sets, we are trying to understand how two or more data sets combine and interact with each other. This relationship is called correlation, and it can be positive or negative, meaning that the variables considered might be supportive or working against each other. A scatter plot is a type of chart that is often used in statistics and data science. It consists of multiple data points plotted across two axes. Each variable depicted in a scatter plot would have various observations. It can be an advantageous chart type whenever we see any relationship between the two data sets. We use a scatter plot to identify the data’s relationship with each variable (i.e., correlation or trend patterns.) It also helps in detecting outliers in the plot. In machine learning, scatter plots are often used in regression, where x and y are continuous variables. They are also used in clustering scatters or outlier detection. Scatter plots are not suitable if we are interested in observing time patterns. A scatter plot is used with numerical data or numbers. So, if we have categories such as three divisions, five products, etc., a scatter plot would not reveal much. We use the Iris dataset for visualization. plt.scatter(iris_df['sepal length (cm)'], iris_df['sepal width (cm)'])plt.title('Scatterplot of Distribution of Sepal Length and Sepal Width', fontsize=15)plt.xlabel('sepal length (cm)')plt.ylabel('sepal width (cm)') Marginal histograms are histograms added to the margin of each axis of a scatter plot for analyzing the distribution of each measure. We use a marginal histogram to assess the relationship between two variables and examine their distributions. Putting marginal histograms in scatter plots or adding marginal bars on highlighted tables makes the visualization interactive, informative, and impressive. # A seaborn jointplot shows bivariate scatterplots and univariate histograms in the same figurep = sns.jointplot(iris_df['sepal length (cm)'], iris_df['sepal width (cm)'], height=10) Our goal here is to produce a legend to understand the differences between groups. We will use seaborn’s FacetGrid to color the scatterplot by species. sns.FacetGrid(iris_df, hue=’species’, size=10) \ .map(plt.scatter, ‘sepal length (cm)’, ‘sepal width (cm)’) \ .add_legend()plt.title(‘Scatterplot with Seaborn’, fontsize=15) Another useful seaborn plot is pairplot, which shows the bivariate relationship between each pair of features. From the pair plot, we’ll see that the Iris-setosa species is separated from the other two across all feature combinations. sns.pairplot(iris_df.drop(“target”, axis=1), hue=”species”, height=3) A heatmap is a graphical representation of data that uses a system of color-coding to represent different values. Heatmaps are useful for cross-examining multivariate data, through placing variables in rows and columns and coloring cells within the table. All the rows are one category (labels displayed on the left side), and all the columns are another category (labels displayed on the bottom). The individual rows and columns are divided into the subcategories, which all match each other in a matrix. The cells within the table either contain color-coded categorical data or numerical data based on a color scale. Data in a cell demonstrates the relationship between two variables in the connecting row and column. Heatmaps are useful for showing variance across multiple variables, revealing any patterns, displaying whether any variables are similar, and detecting any correlations between them. Heatmap can be super useful when we want to see which intersections of the categorical values have a higher concentration of the data than others. Heatmaps are better suited to displaying a more generalized view of numerical data. It is harder to accurately tell the differences between color shades and extract specific data points (unless we include the cells’ raw data). Heatmaps can also show the changes in data over time if one of the rows or columns is set to time intervals. An example of this would be to use a heatmap to compare the temperature changes across the year in the city(ies), to see the hottest or coldest places. So the rows contain each month, the columns indicate hours, and the cells would have the temperature values. We use the World Happiness Report dataset from Kaggle. I cleaned the data and combined all files into the happiness_rank.csv file. You can download and clean the data or download the final result here. I recommend you check out my data cleaning codes on Github. sns.heatmap(happy[usecols].corr(),linewidths=0.25, vmax=0.7,square=True,cmap="Blues", linecolor='w',annot=True,annot_kws={"size":8}, mask=mask, cbar_kws={"shrink": .9}) Sometimes it isn’t enough to know that a relationship exists between variables; in some cases, better analysis is possible if we can also visualize when the relationship took place. Because relationships are denoted with links between variables, the date/time appears as a link property. This visualization method shows data over the period to find trends or changes over time. Line charts are used to display quantitative values over a continuous interval or period. Line charts are drawn by first plotting data points on a cartesian coordinate grid and then connecting them. Typically, the y-axis has a quantitative value, while the x-axis is a timescale or a sequence of intervals. The direction of the lines on the graph works as an excellent metaphor for the data: an upward slope indicates increasing values, and a downward slope indicates where values have decreased. The line’s journey across the graph can create patterns that reveal trends in a dataset. Line charts are most frequently used to show trends and analyze how the data has changed over time. Line charts are best for continuous data as it connects many variables that all belong to the same category. When grouped with other lines or other data series, individual lines can be compared. However, we should avoid using more than four lines per graph, as this makes the chart more cluttered and harder to read. A solution to this is to split our chart into multiples subplots. Suppose we have a dataset containing information about Medium members. We want to see the trend of articles that have been read in 2019. plt.plot(data['Month'], data['All Views'], color='#4870a0', marker='o') The idea of an area chart is based on the line chart. The colored region shows us the development of a variable over time. Area charts are ideal for clearly illustrating the magnitude of change between two or more data points. For example, the happiness score has six generating divisions; we would like to see each of these divisions’ contributions. Moreover, if we are interested in the portion generated by each division and not that much of the total amount of the division self, we can use a 100% stacked area chart. This will show each division’s percentage contribution over time. Area charts are not the best choice if we want to present fluctuating values, like the stock market or price changes. Here, we want to present an accumulative number of external views over time. plt.stackplot(data['Month'], data['External Views'], colors='#7289da', alpha=0.8) The idea of a stack area chart is based on the simple area charts. It displays the value of several groups on the same graphic. Values of each group are displayed on top of each other. The entire graph represents the total of all data plotted over time. The stacked area chart type is a powerful chart as it allows grouping of data and seeing trends over a selected date range. Stacked area charts use the areas to convey whole numbers, so they do not work for negative values. Stacked area charts are colorful and fun, but we should use them with caution because they can quickly become a mess. We shouldn’t stack together more than five categories. plt.stackplot(data['Month'], data['Internal Views'], data['External Views'], alpha=0.75, colors=['#7289da','#f29fa9'], labels=['Internal Views', 'External Views']) Unlike a stack area chart, an area chart unstacked shows the overlap of several groups on the same graphic. x = data['Internal Views']y = data['External Views']# plot the dataax.plot(x, color='#49a7c3', alpha=0.3, label='Internal Views')ax.plot(y, color='#f04747', alpha=0.3, label='External Views')# fill the areas between the plots and the x axis# this can create overlapping areas between linesax.fill_between(x.index, 0, x, color='blue', alpha=0.2)ax.fill_between(x.index, 0, y, color='red', alpha=0.2) A visualization method displays the relative order of data values. Bar charts are among the most frequently used chart types. As the name suggests, a bar chart is composed of a series of bars illustrating a variable’s development. There are four types of bar charts: horizontal bar chart, verticle bar chart, group bar chart, and stacked bar chart. Bar charts are great when we want to track the development of one or two variables over time. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value. A simple bar chart isn’t suitable when we have a single period breakdown of a variable. For example, if I want to portray the main business lines that contributed to a company’s revenues, I wouldn’t use a bar chart. Instead, I would create a pie chart or one of its variations. Vertical bar charts (column chart) are distinguished from histograms, as they do not display continuous developments over an interval. Vertical bar chart’s discrete data is categorical and therefore answers the question of “how many?” in each category. Vertical bar charts are typically used to compare several items in a specific range of values. So it is ideal for comparing a single category of data between individual sub-items, for example, corresponding revenue between regions. We use mpg_ggplot2 data frame. It is a rectangular collection of variables (in the columns) and observations (in the rows). mpg contains observations collected by the US Environmental Protection Agency on 38 popular models of car. Here, we want to compare car models. plt.bar(value_count.index, value_count.values, color='#49a7c3') Horizontal bar charts represent the data horizontally. The data categories are shown on the y-axis, and the data values are shown on the x-axis. The length of each bar is equal to the value corresponding to the data category, and all bars go across from left to right. plt.barh(value_count.index, value_count.values, color='#b28eb2') Also known as a Grouped Bar Chart or Clustered Bar Chart. This variation of a bar chart is used when two or more data series are plotted side-by-side and grouped under categories, all on the same axis. We use multi-set bar charts to compare grouped variables or categories to other groups with those same variables or category types. The downside of group bar charts is that they become harder to read the more bars we have in one group. ax = views.plot.bar(rot=0,color='#E6E9ED',width=1, figsize=(14,8))ax = df.plot.bar(rot=0, ax=ax, color=['#7289da', '#dd546e', '#99aab5', '#f3c366'], width=0.8, figsize=(14,8)) Unlike a multi-set bar chart that displays their bars side-by-side, stacked bar charts segment their bars. Stacked bar charts are used to show how a broader category is divided into smaller categories and what the relationship of each part has on the total amount. Stacked bar charts place each value for the segment after the previous one. The total value of the bar is all the segment values added together. It is ideal for comparing the total amounts across each group/segmented bar. One major flaw of Stacked bar charts is that they become harder to read the more segments each bar has. Also, comparing each component to each other is difficult, as they are not aligned on a common baseline. rect1 = plt.bar(data['Month'] ,data['Internal Views'], width=0.5, color='lightblue')rect2 = plt.bar(data['Month'], data['External Views'], width=0.5, color='#1f77b4') Lollipop chart serves a similar purpose as an ordered bar chart in a visually pleasing way. We use lollipop charts to show the relationship between a numerical variable and another numerical or categorical variable. The lollipop chart is often claimed to be useful compared to a standard bar chart if we are dealing with a large number of values and when values are all high, such as in the 80–90% range (out of 100%). Then a broad set of tall columns can be visually aggressive. If our data has unsorted bars of very similar length — it is harder to compare the sizes of two very identical lollipops than standard bars. Python Implementation (markerline, stemlines, baseline) = plt.stem(value_count.index, value_count.values) That’s it for the first part. The code is available on Github. We will continue with distributions and comparisons on part two. So far, we know that data visualization is a quick, easy way to convey concepts universally — and we can experiment with different scenarios by making slight adjustments. There are dozens of tools for data visualization and data analysis — these range from simple — zero codings required (Tableau) to complex — coding required (JaveScript). Not every tool is right for every person looking to learn visualization techniques, and not every tool can scale to industry or enterprise purposes. My favorite professor told me that “Good data visualization theory and skills will transcend specific tools and products.” When we learn this skill, focus on best practices, and explore our style when it comes to visualizations and dashboards. Data visualization isn’t going away anytime soon, so it’s essential to build a foundation of analysis and storytelling, and exploration that you can carry with regardless of the tools or software you end up using. If you want to dig deeper into this particular topic, here are some excellent places to start. Information is BeautifulVisualizing dataData Visualization CatalogueColor HexMatplotlib Cheat SheetHow to make a heatmap with Seaborn in Python? Information is Beautiful Visualizing data Data Visualization Catalogue Color Hex Matplotlib Cheat Sheet How to make a heatmap with Seaborn in Python?
[ { "code": null, "e": 481, "s": 171, "text": "According to the World Economic Forum, the world produces 2.5 quintillion bytes of data every day. With so much data, it’s become increasingly difficult to manage and make sense of it all. It would be impossible for any person to wade through data line-by-line and see distinct patterns and make observations." }, { "code": null, "e": 705, "s": 481, "text": "Data visualization is one of the data science processes; that is, a framework for approaching data science tasks. After data is collected, processed, and modeled, the relationships need to be visualized for the conclusions." }, { "code": null, "e": 962, "s": 705, "text": "We use data visualization as a technique to communicate insights from data through visual representation. Our main goal is to distill large datasets into visual graphics to allow for a straightforward understanding of complex relationships within the data." }, { "code": null, "e": 1129, "s": 962, "text": "So now, we know data visualization can provide insight that traditional descriptive statistics cannot. Our big question is how to choose the right chart for the data?" }, { "code": null, "e": 1482, "s": 1129, "text": "This note will give us an overview of the different chart types. For each type of chart, we will introduce a short description. We then discuss when to use it and when we should avoid using it. Next, we will look at some Python code for implementation. I only present the primary principle; the full version will be provided at the end of this article." }, { "code": null, "e": 1560, "s": 1482, "text": "I hope this note is interesting enough to pick up the slack. Let’s hop to it." }, { "code": null, "e": 2120, "s": 1560, "text": "Before making a chart, it’s essential to understand why we need one. Graphs, plots, maps, and diagrams help people understand complex data, find patterns, identify trends, and tell stories. Think about the message we want to share with our audience. Here, I group the charts by their data visualization functions, that is, what we want our charts to communicate with our audience. While each chart’s allocation into specific functions isn’t a perfect system, it still works as a useful guide for selecting a chart based on our analysis or communication needs." }, { "code": null, "e": 2309, "s": 2120, "text": "The first part of this note will introduce us to different charts to display the connection between variables, the trend over time, and the relative order of variables within category(ies)" }, { "code": null, "e": 2426, "s": 2309, "text": "1. Scatter plot using Matplotlib2. Marginal Histogram3. Scatter plot using Seaborn4. Pair Plot in Seaborn5. Heat Map" }, { "code": null, "e": 2495, "s": 2426, "text": "6. Line Chart7. Area Chart8. Stack Area Chart9. Area Chart Unstacked" }, { "code": null, "e": 2602, "s": 2495, "text": "10. Vertical Bar Chart11. Horizontal Bar Chart12. Multi-set Bar Chart13. Stack Bar Chart14. Lollipop Chart" }, { "code": null, "e": 2723, "s": 2602, "text": "The second part of this note will introduce us to different chart types use to compare variables and their distribution." }, { "code": null, "e": 2848, "s": 2723, "text": "15. Histogram16. Density Curve with Histogram17. Density Plot18. Box Plot19. Strip Plot20. Violin Plot21. Population Pyramid" }, { "code": null, "e": 2986, "s": 2848, "text": "22. Bubble Chart23. Bullet Chart24. Pie Chart25. Net Pie Chart26. Donut Chart27. TreeMap28. Diverging Bar29. Choropleth Map30. Bubble Map" }, { "code": null, "e": 3085, "s": 2986, "text": "We use a relationship method to display a connection or correlation between two or more variables." }, { "code": null, "e": 3226, "s": 3085, "text": "When assessing a relationship between data sets, we are trying to understand how two or more data sets combine and interact with each other." }, { "code": null, "e": 3392, "s": 3226, "text": "This relationship is called correlation, and it can be positive or negative, meaning that the variables considered might be supportive or working against each other." }, { "code": null, "e": 3709, "s": 3392, "text": "A scatter plot is a type of chart that is often used in statistics and data science. It consists of multiple data points plotted across two axes. Each variable depicted in a scatter plot would have various observations. It can be an advantageous chart type whenever we see any relationship between the two data sets." }, { "code": null, "e": 3874, "s": 3709, "text": "We use a scatter plot to identify the data’s relationship with each variable (i.e., correlation or trend patterns.) It also helps in detecting outliers in the plot." }, { "code": null, "e": 4043, "s": 3874, "text": "In machine learning, scatter plots are often used in regression, where x and y are continuous variables. They are also used in clustering scatters or outlier detection." }, { "code": null, "e": 4123, "s": 4043, "text": "Scatter plots are not suitable if we are interested in observing time patterns." }, { "code": null, "e": 4288, "s": 4123, "text": "A scatter plot is used with numerical data or numbers. So, if we have categories such as three divisions, five products, etc., a scatter plot would not reveal much." }, { "code": null, "e": 4331, "s": 4288, "text": "We use the Iris dataset for visualization." }, { "code": null, "e": 4548, "s": 4331, "text": "plt.scatter(iris_df['sepal length (cm)'], iris_df['sepal width (cm)'])plt.title('Scatterplot of Distribution of Sepal Length and Sepal Width', fontsize=15)plt.xlabel('sepal length (cm)')plt.ylabel('sepal width (cm)')" }, { "code": null, "e": 4682, "s": 4548, "text": "Marginal histograms are histograms added to the margin of each axis of a scatter plot for analyzing the distribution of each measure." }, { "code": null, "e": 4949, "s": 4682, "text": "We use a marginal histogram to assess the relationship between two variables and examine their distributions. Putting marginal histograms in scatter plots or adding marginal bars on highlighted tables makes the visualization interactive, informative, and impressive." }, { "code": null, "e": 5132, "s": 4949, "text": "# A seaborn jointplot shows bivariate scatterplots and univariate histograms in the same figurep = sns.jointplot(iris_df['sepal length (cm)'], iris_df['sepal width (cm)'], height=10)" }, { "code": null, "e": 5284, "s": 5132, "text": "Our goal here is to produce a legend to understand the differences between groups. We will use seaborn’s FacetGrid to color the scatterplot by species." }, { "code": null, "e": 5458, "s": 5284, "text": "sns.FacetGrid(iris_df, hue=’species’, size=10) \\ .map(plt.scatter, ‘sepal length (cm)’, ‘sepal width (cm)’) \\ .add_legend()plt.title(‘Scatterplot with Seaborn’, fontsize=15)" }, { "code": null, "e": 5693, "s": 5458, "text": "Another useful seaborn plot is pairplot, which shows the bivariate relationship between each pair of features. From the pair plot, we’ll see that the Iris-setosa species is separated from the other two across all feature combinations." }, { "code": null, "e": 5763, "s": 5693, "text": "sns.pairplot(iris_df.drop(“target”, axis=1), hue=”species”, height=3)" }, { "code": null, "e": 6019, "s": 5763, "text": "A heatmap is a graphical representation of data that uses a system of color-coding to represent different values. Heatmaps are useful for cross-examining multivariate data, through placing variables in rows and columns and coloring cells within the table." }, { "code": null, "e": 6483, "s": 6019, "text": "All the rows are one category (labels displayed on the left side), and all the columns are another category (labels displayed on the bottom). The individual rows and columns are divided into the subcategories, which all match each other in a matrix. The cells within the table either contain color-coded categorical data or numerical data based on a color scale. Data in a cell demonstrates the relationship between two variables in the connecting row and column." }, { "code": null, "e": 6666, "s": 6483, "text": "Heatmaps are useful for showing variance across multiple variables, revealing any patterns, displaying whether any variables are similar, and detecting any correlations between them." }, { "code": null, "e": 6813, "s": 6666, "text": "Heatmap can be super useful when we want to see which intersections of the categorical values have a higher concentration of the data than others." }, { "code": null, "e": 7040, "s": 6813, "text": "Heatmaps are better suited to displaying a more generalized view of numerical data. It is harder to accurately tell the differences between color shades and extract specific data points (unless we include the cells’ raw data)." }, { "code": null, "e": 7410, "s": 7040, "text": "Heatmaps can also show the changes in data over time if one of the rows or columns is set to time intervals. An example of this would be to use a heatmap to compare the temperature changes across the year in the city(ies), to see the hottest or coldest places. So the rows contain each month, the columns indicate hours, and the cells would have the temperature values." }, { "code": null, "e": 7672, "s": 7410, "text": "We use the World Happiness Report dataset from Kaggle. I cleaned the data and combined all files into the happiness_rank.csv file. You can download and clean the data or download the final result here. I recommend you check out my data cleaning codes on Github." }, { "code": null, "e": 7877, "s": 7672, "text": "sns.heatmap(happy[usecols].corr(),linewidths=0.25, vmax=0.7,square=True,cmap=\"Blues\", linecolor='w',annot=True,annot_kws={\"size\":8}, mask=mask, cbar_kws={\"shrink\": .9})" }, { "code": null, "e": 8255, "s": 7877, "text": "Sometimes it isn’t enough to know that a relationship exists between variables; in some cases, better analysis is possible if we can also visualize when the relationship took place. Because relationships are denoted with links between variables, the date/time appears as a link property. This visualization method shows data over the period to find trends or changes over time." }, { "code": null, "e": 8345, "s": 8255, "text": "Line charts are used to display quantitative values over a continuous interval or period." }, { "code": null, "e": 8841, "s": 8345, "text": "Line charts are drawn by first plotting data points on a cartesian coordinate grid and then connecting them. Typically, the y-axis has a quantitative value, while the x-axis is a timescale or a sequence of intervals. The direction of the lines on the graph works as an excellent metaphor for the data: an upward slope indicates increasing values, and a downward slope indicates where values have decreased. The line’s journey across the graph can create patterns that reveal trends in a dataset." }, { "code": null, "e": 8941, "s": 8841, "text": "Line charts are most frequently used to show trends and analyze how the data has changed over time." }, { "code": null, "e": 9050, "s": 8941, "text": "Line charts are best for continuous data as it connects many variables that all belong to the same category." }, { "code": null, "e": 9324, "s": 9050, "text": "When grouped with other lines or other data series, individual lines can be compared. However, we should avoid using more than four lines per graph, as this makes the chart more cluttered and harder to read. A solution to this is to split our chart into multiples subplots." }, { "code": null, "e": 9461, "s": 9324, "text": "Suppose we have a dataset containing information about Medium members. We want to see the trend of articles that have been read in 2019." }, { "code": null, "e": 9533, "s": 9461, "text": "plt.plot(data['Month'], data['All Views'], color='#4870a0', marker='o')" }, { "code": null, "e": 9656, "s": 9533, "text": "The idea of an area chart is based on the line chart. The colored region shows us the development of a variable over time." }, { "code": null, "e": 9884, "s": 9656, "text": "Area charts are ideal for clearly illustrating the magnitude of change between two or more data points. For example, the happiness score has six generating divisions; we would like to see each of these divisions’ contributions." }, { "code": null, "e": 10121, "s": 9884, "text": "Moreover, if we are interested in the portion generated by each division and not that much of the total amount of the division self, we can use a 100% stacked area chart. This will show each division’s percentage contribution over time." }, { "code": null, "e": 10239, "s": 10121, "text": "Area charts are not the best choice if we want to present fluctuating values, like the stock market or price changes." }, { "code": null, "e": 10316, "s": 10239, "text": "Here, we want to present an accumulative number of external views over time." }, { "code": null, "e": 10398, "s": 10316, "text": "plt.stackplot(data['Month'], data['External Views'], colors='#7289da', alpha=0.8)" }, { "code": null, "e": 10652, "s": 10398, "text": "The idea of a stack area chart is based on the simple area charts. It displays the value of several groups on the same graphic. Values of each group are displayed on top of each other. The entire graph represents the total of all data plotted over time." }, { "code": null, "e": 10776, "s": 10652, "text": "The stacked area chart type is a powerful chart as it allows grouping of data and seeing trends over a selected date range." }, { "code": null, "e": 10876, "s": 10776, "text": "Stacked area charts use the areas to convey whole numbers, so they do not work for negative values." }, { "code": null, "e": 11049, "s": 10876, "text": "Stacked area charts are colorful and fun, but we should use them with caution because they can quickly become a mess. We shouldn’t stack together more than five categories." }, { "code": null, "e": 11250, "s": 11049, "text": "plt.stackplot(data['Month'], data['Internal Views'], data['External Views'], alpha=0.75, colors=['#7289da','#f29fa9'], labels=['Internal Views', 'External Views'])" }, { "code": null, "e": 11358, "s": 11250, "text": "Unlike a stack area chart, an area chart unstacked shows the overlap of several groups on the same graphic." }, { "code": null, "e": 11757, "s": 11358, "text": "x = data['Internal Views']y = data['External Views']# plot the dataax.plot(x, color='#49a7c3', alpha=0.3, label='Internal Views')ax.plot(y, color='#f04747', alpha=0.3, label='External Views')# fill the areas between the plots and the x axis# this can create overlapping areas between linesax.fill_between(x.index, 0, x, color='blue', alpha=0.2)ax.fill_between(x.index, 0, y, color='red', alpha=0.2)" }, { "code": null, "e": 11824, "s": 11757, "text": "A visualization method displays the relative order of data values." }, { "code": null, "e": 11988, "s": 11824, "text": "Bar charts are among the most frequently used chart types. As the name suggests, a bar chart is composed of a series of bars illustrating a variable’s development." }, { "code": null, "e": 12106, "s": 11988, "text": "There are four types of bar charts: horizontal bar chart, verticle bar chart, group bar chart, and stacked bar chart." }, { "code": null, "e": 12316, "s": 12106, "text": "Bar charts are great when we want to track the development of one or two variables over time. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value." }, { "code": null, "e": 12594, "s": 12316, "text": "A simple bar chart isn’t suitable when we have a single period breakdown of a variable. For example, if I want to portray the main business lines that contributed to a company’s revenues, I wouldn’t use a bar chart. Instead, I would create a pie chart or one of its variations." }, { "code": null, "e": 12847, "s": 12594, "text": "Vertical bar charts (column chart) are distinguished from histograms, as they do not display continuous developments over an interval. Vertical bar chart’s discrete data is categorical and therefore answers the question of “how many?” in each category." }, { "code": null, "e": 13079, "s": 12847, "text": "Vertical bar charts are typically used to compare several items in a specific range of values. So it is ideal for comparing a single category of data between individual sub-items, for example, corresponding revenue between regions." }, { "code": null, "e": 13310, "s": 13079, "text": "We use mpg_ggplot2 data frame. It is a rectangular collection of variables (in the columns) and observations (in the rows). mpg contains observations collected by the US Environmental Protection Agency on 38 popular models of car." }, { "code": null, "e": 13347, "s": 13310, "text": "Here, we want to compare car models." }, { "code": null, "e": 13411, "s": 13347, "text": "plt.bar(value_count.index, value_count.values, color='#49a7c3')" }, { "code": null, "e": 13680, "s": 13411, "text": "Horizontal bar charts represent the data horizontally. The data categories are shown on the y-axis, and the data values are shown on the x-axis. The length of each bar is equal to the value corresponding to the data category, and all bars go across from left to right." }, { "code": null, "e": 13745, "s": 13680, "text": "plt.barh(value_count.index, value_count.values, color='#b28eb2')" }, { "code": null, "e": 13803, "s": 13745, "text": "Also known as a Grouped Bar Chart or Clustered Bar Chart." }, { "code": null, "e": 13947, "s": 13803, "text": "This variation of a bar chart is used when two or more data series are plotted side-by-side and grouped under categories, all on the same axis." }, { "code": null, "e": 14079, "s": 13947, "text": "We use multi-set bar charts to compare grouped variables or categories to other groups with those same variables or category types." }, { "code": null, "e": 14183, "s": 14079, "text": "The downside of group bar charts is that they become harder to read the more bars we have in one group." }, { "code": null, "e": 14376, "s": 14183, "text": "ax = views.plot.bar(rot=0,color='#E6E9ED',width=1, figsize=(14,8))ax = df.plot.bar(rot=0, ax=ax, color=['#7289da', '#dd546e', '#99aab5', '#f3c366'], width=0.8, figsize=(14,8))" }, { "code": null, "e": 14641, "s": 14376, "text": "Unlike a multi-set bar chart that displays their bars side-by-side, stacked bar charts segment their bars. Stacked bar charts are used to show how a broader category is divided into smaller categories and what the relationship of each part has on the total amount." }, { "code": null, "e": 14863, "s": 14641, "text": "Stacked bar charts place each value for the segment after the previous one. The total value of the bar is all the segment values added together. It is ideal for comparing the total amounts across each group/segmented bar." }, { "code": null, "e": 15072, "s": 14863, "text": "One major flaw of Stacked bar charts is that they become harder to read the more segments each bar has. Also, comparing each component to each other is difficult, as they are not aligned on a common baseline." }, { "code": null, "e": 15269, "s": 15072, "text": "rect1 = plt.bar(data['Month'] ,data['Internal Views'], width=0.5, color='lightblue')rect2 = plt.bar(data['Month'], data['External Views'], width=0.5, color='#1f77b4')" }, { "code": null, "e": 15485, "s": 15269, "text": "Lollipop chart serves a similar purpose as an ordered bar chart in a visually pleasing way. We use lollipop charts to show the relationship between a numerical variable and another numerical or categorical variable." }, { "code": null, "e": 15749, "s": 15485, "text": "The lollipop chart is often claimed to be useful compared to a standard bar chart if we are dealing with a large number of values and when values are all high, such as in the 80–90% range (out of 100%). Then a broad set of tall columns can be visually aggressive." }, { "code": null, "e": 15890, "s": 15749, "text": "If our data has unsorted bars of very similar length — it is harder to compare the sizes of two very identical lollipops than standard bars." }, { "code": null, "e": 15912, "s": 15890, "text": "Python Implementation" }, { "code": null, "e": 15996, "s": 15912, "text": "(markerline, stemlines, baseline) = plt.stem(value_count.index, value_count.values)" }, { "code": null, "e": 16124, "s": 15996, "text": "That’s it for the first part. The code is available on Github. We will continue with distributions and comparisons on part two." }, { "code": null, "e": 16295, "s": 16124, "text": "So far, we know that data visualization is a quick, easy way to convey concepts universally — and we can experiment with different scenarios by making slight adjustments." }, { "code": null, "e": 16614, "s": 16295, "text": "There are dozens of tools for data visualization and data analysis — these range from simple — zero codings required (Tableau) to complex — coding required (JaveScript). Not every tool is right for every person looking to learn visualization techniques, and not every tool can scale to industry or enterprise purposes." }, { "code": null, "e": 17072, "s": 16614, "text": "My favorite professor told me that “Good data visualization theory and skills will transcend specific tools and products.” When we learn this skill, focus on best practices, and explore our style when it comes to visualizations and dashboards. Data visualization isn’t going away anytime soon, so it’s essential to build a foundation of analysis and storytelling, and exploration that you can carry with regardless of the tools or software you end up using." }, { "code": null, "e": 17167, "s": 17072, "text": "If you want to dig deeper into this particular topic, here are some excellent places to start." }, { "code": null, "e": 17312, "s": 17167, "text": "Information is BeautifulVisualizing dataData Visualization CatalogueColor HexMatplotlib Cheat SheetHow to make a heatmap with Seaborn in Python?" }, { "code": null, "e": 17337, "s": 17312, "text": "Information is Beautiful" }, { "code": null, "e": 17354, "s": 17337, "text": "Visualizing data" }, { "code": null, "e": 17383, "s": 17354, "text": "Data Visualization Catalogue" }, { "code": null, "e": 17393, "s": 17383, "text": "Color Hex" }, { "code": null, "e": 17416, "s": 17393, "text": "Matplotlib Cheat Sheet" } ]
Production Data Processing with PySpark on AWS EMR | by Brent Lemieux | Towards Data Science
Data Pipelines with PySpark and AWS EMR is a multi-part series. This is part 2 of 2. Check out part 1 if you need a primer on AWS EMR. Getting Started with PySpark on AWS EMRProduction Data Processing with PySpark on AWS EMR (this article) Getting Started with PySpark on AWS EMR Production Data Processing with PySpark on AWS EMR (this article) Apache Spark has been all the rage for large-scale data processing and analytics — for good reason. With Spark, organizations are able to extract a ton of value from their ever-growing piles of data. Because of this, data scientists and engineers who can build Spark applications are highly valued by businesses. This article will show you how to run your Spark application on an Amazon EMR cluster from the command line. Most of the PySpark tutorials out there use Jupyter notebooks to demonstrate Spark’s data processing and machine learning functionality. The reason is simple. When working on a cluster, notebooks make it much easier to test syntax and debug Spark applications by giving you quick feedback and presenting error messages within the UI. Otherwise, you would have to dig through log files to figure out what went wrong — not ideal for learning. Once you’re confident your code works, you may want to integrate your Spark application into your systems. Here, notebooks are much less useful. To run PySpark on a schedule, we need to move our code from a notebook to a Python script and submit that script to a cluster. In this tutorial, I’ll show you how. Submitting Spark applications to a cluster from the command line can be intimidating at first. My goal is to demystify the process. This guide will show you how to use the AWS Command Line Interface to: Create a cluster that can handle datasets much larger than what fits on your local machine.Submit a Spark application to the cluster, that reads data, processes it, and stores the results in an accessible location.Auto-terminate the cluster once the step is complete, so you only pay for the cluster while you’re using it. Create a cluster that can handle datasets much larger than what fits on your local machine. Submit a Spark application to the cluster, that reads data, processes it, and stores the results in an accessible location. Auto-terminate the cluster once the step is complete, so you only pay for the cluster while you’re using it. When developing Spark applications for processing data or running machine learning models, my preference is to start by using a Jupyter notebook for the reasons stated above. Here’s a guide to creating an Amazon EMR cluster and connecting to it with a Jupyter notebook. Once I know my code works, I may want to put the process in play as a scheduled job. I’ll put the code in a script so I can put it on a schedule with Cron or Apache Airflow. IMPORTANT UPDATE: This guide uses AWS CLI version 1 — the commands below will need some adjustment to work with version 2. Create your AWS account if you haven’t already. Install and configure the AWS Command Line Interface. To configure the AWS CLI, you’ll need to add your credentials. You can create credentials by following these instructions. You’ll also need to specify your default region. For this tutorial, we’re using us-west-2. You can use whichever region you want. Just be sure to use the same region for all of your resources. For this example, we’ll load Amazon book review data from S3, perform basic processing, and calculate some aggregates. We’ll then write our aggregated data frame back to S3. The example is simple, but this is a common workflow for Spark. Read the data from a source (S3 in this example).Process the data or execute a model workflow with Spark ML.Write the results somewhere accessible to our systems (another S3 bucket in this example). Read the data from a source (S3 in this example). Process the data or execute a model workflow with Spark ML. Write the results somewhere accessible to our systems (another S3 bucket in this example). If you haven’t already, create an S3 bucket now. Make sure the region you create the bucket in is the same region you use for the rest of this tutorial. I’ll be using region “US West (Oregon)”. Copy the file below. Be sure to edit the output_path in main() to use your S3 bucket. Then upload pyspark_job.py to your bucket. # pyspark_job.pyfrom pyspark.sql import SparkSessionfrom pyspark.sql import functions as Fdef create_spark_session(): """Create spark session.Returns: spark (SparkSession) - spark session connected to AWS EMR cluster """ spark = SparkSession \ .builder \ .config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.0") \ .getOrCreate() return sparkdef process_book_data(spark, input_path, output_path): """Process the book review data and write to S3.Arguments: spark (SparkSession) - spark session connected to AWS EMR cluster input_path (str) - AWS S3 bucket path for source data output_path (str) - AWS S3 bucket for writing processed data """ df = spark.read.parquet(input_path) # Apply some basic filters and aggregate by product_title. book_agg = df.filter(df.verified_purchase == 'Y') \ .groupBy('product_title') \ .agg({'star_rating': 'avg', 'review_id': 'count'}) \ .filter(F.col('count(review_id)') >= 500) \ .sort(F.desc('avg(star_rating)')) \ .select(F.col('product_title').alias('book_title'), F.col('count(review_id)').alias('review_count'), F.col('avg(star_rating)').alias('review_avg_stars')) # Save the data to your S3 bucket as a .parquet file. book_agg.write.mode('overwrite')\ .save(output_path)def main(): spark = create_spark_session() input_path = ('s3://amazon-reviews-pds/parquet/' + 'product_category=Books/*.parquet') output_path = 's3://spark-tutorial-bwl/book-aggregates' process_book_data(spark, input_path, output_path)if __name__ == '__main__': main() It’s time to create our cluster and submit our application. Once our application finishes, we’ll tell the cluster to terminate. Auto-terminate allows us to pay for the resources only when we need them. Depending on our use case, we may not want to terminate our cluster upon completion. For instance, if you have a web application that relies on Spark for a data processing task, you may want to have a dedicated cluster running at all times. Run the command below. Make sure you replace the bold italicized pieces with your own files. Details on --ec2-attributes and --bootstrap-actions, and all of the other arguments, are included below. aws emr create-cluster --name "Spark cluster with step" \ --release-label emr-5.24.1 \ --applications Name=Spark \ --log-uri s3://your-bucket/logs/ \ --ec2-attributes KeyName=your-key-pair \ --instance-type m5.xlarge \ --instance-count 3 \ --bootstrap-actions Path=s3://your-bucket/emr_bootstrap.sh \ --steps Type=Spark,Name="Spark job",ActionOnFailure=CONTINUE,Args=[--deploy-mode,cluster,--master,yarn,s3://your-bucket/pyspark_job.py] \ --use-default-roles \ --auto-terminate Important aws emr create-cluster arguments: --steps tells your cluster what to do after the cluster starts. Be sure to replace s3://your-bucket/pyspark_job.py in the --steps argument with the S3 path to your Spark application. You can also put your application code on S3 and pass an S3 path. --bootstrap-actions allows you to specify what packages you want to be installed on all of your cluster’s nodes. This step is only necessary if your application uses non-builtin Python packages other than pyspark. To use such packages, create your emr_bootstrap.sh file using the example below as a template, and add it to your S3 bucket. Include --bootstrap-actions Path=s3://your-bucket/emr_bootstrap.sh in the aws emr create-cluster command. #!/bin/bashsudo pip install -U \ matplotlib \ pandas \ spark-nlp --ec2-attributes allows you to specify many different EC2 attributes. Set your key pair using this syntax --ec2-attributes KeyPair=your-key-pair. Note: this is just the name of your key pair, not the file path. You can learn more about creating a key pair file here. --log-uri requires an S3 bucket to store your log files. Other aws emr create-cluster arguments explained: --name gives the cluster you are creating an identifier. --release-label specifies which version of EMR to use. I recommend using the latest version. --applications tells EMR which type of application you will be using on your cluster. To create a Spark cluster, use Name=Spark. --instance-type specifies which type of EC2 instance you want to use for your cluster. --instance-count specifies how many instances you want in your cluster. --use-default-roles tells the cluster to use the default IAM roles for EMR. If this is your first time using EMR, you’ll need to run aws emr create-default-roles before you can use this command. If you’ve created a cluster on EMR in the region you have the AWS CLI configured for, then you should be good to go. --auto-terminate tells the cluster to terminate once the steps specified in --steps finish. Exclude this command if you would like to leave your cluster running — beware that you are paying for your cluster as long as you keep it running. After you execute the aws emr create-cluster command, you should get a response: { "ClusterId": "j-xxxxxxxxxx"} Sign-in to the AWS console and navigate to the EMR dashboard. Your cluster status should be “Starting”. It should take about ten minutes for your cluster to start up, bootstrap, and run your application (if you used my example code). Once the step is complete, you should see the output data in your S3 bucket. That’s it! You now know how to create an Amazon EMR cluster and submit Spark applications to it. This workflow is a crucial component of building production data processing applications with Spark. I hope you’re now feeling more confident working with all of these tools. Once you have your job running smoothly, consider standing up an Airflow environment on Amazon to schedule and monitor your pipelines. Thank you for reading! Please let me know if you liked the article or if you have any critiques. If you found this guide useful, be sure to follow me so you don’t miss my future articles. If you need help with a data project or want to say hi, connect with me on LinkedIn. Cheers!
[ { "code": null, "e": 307, "s": 172, "text": "Data Pipelines with PySpark and AWS EMR is a multi-part series. This is part 2 of 2. Check out part 1 if you need a primer on AWS EMR." }, { "code": null, "e": 412, "s": 307, "text": "Getting Started with PySpark on AWS EMRProduction Data Processing with PySpark on AWS EMR (this article)" }, { "code": null, "e": 452, "s": 412, "text": "Getting Started with PySpark on AWS EMR" }, { "code": null, "e": 518, "s": 452, "text": "Production Data Processing with PySpark on AWS EMR (this article)" }, { "code": null, "e": 940, "s": 518, "text": "Apache Spark has been all the rage for large-scale data processing and analytics — for good reason. With Spark, organizations are able to extract a ton of value from their ever-growing piles of data. Because of this, data scientists and engineers who can build Spark applications are highly valued by businesses. This article will show you how to run your Spark application on an Amazon EMR cluster from the command line." }, { "code": null, "e": 1381, "s": 940, "text": "Most of the PySpark tutorials out there use Jupyter notebooks to demonstrate Spark’s data processing and machine learning functionality. The reason is simple. When working on a cluster, notebooks make it much easier to test syntax and debug Spark applications by giving you quick feedback and presenting error messages within the UI. Otherwise, you would have to dig through log files to figure out what went wrong — not ideal for learning." }, { "code": null, "e": 1690, "s": 1381, "text": "Once you’re confident your code works, you may want to integrate your Spark application into your systems. Here, notebooks are much less useful. To run PySpark on a schedule, we need to move our code from a notebook to a Python script and submit that script to a cluster. In this tutorial, I’ll show you how." }, { "code": null, "e": 1893, "s": 1690, "text": "Submitting Spark applications to a cluster from the command line can be intimidating at first. My goal is to demystify the process. This guide will show you how to use the AWS Command Line Interface to:" }, { "code": null, "e": 2216, "s": 1893, "text": "Create a cluster that can handle datasets much larger than what fits on your local machine.Submit a Spark application to the cluster, that reads data, processes it, and stores the results in an accessible location.Auto-terminate the cluster once the step is complete, so you only pay for the cluster while you’re using it." }, { "code": null, "e": 2308, "s": 2216, "text": "Create a cluster that can handle datasets much larger than what fits on your local machine." }, { "code": null, "e": 2432, "s": 2308, "text": "Submit a Spark application to the cluster, that reads data, processes it, and stores the results in an accessible location." }, { "code": null, "e": 2541, "s": 2432, "text": "Auto-terminate the cluster once the step is complete, so you only pay for the cluster while you’re using it." }, { "code": null, "e": 2811, "s": 2541, "text": "When developing Spark applications for processing data or running machine learning models, my preference is to start by using a Jupyter notebook for the reasons stated above. Here’s a guide to creating an Amazon EMR cluster and connecting to it with a Jupyter notebook." }, { "code": null, "e": 2985, "s": 2811, "text": "Once I know my code works, I may want to put the process in play as a scheduled job. I’ll put the code in a script so I can put it on a schedule with Cron or Apache Airflow." }, { "code": null, "e": 3108, "s": 2985, "text": "IMPORTANT UPDATE: This guide uses AWS CLI version 1 — the commands below will need some adjustment to work with version 2." }, { "code": null, "e": 3526, "s": 3108, "text": "Create your AWS account if you haven’t already. Install and configure the AWS Command Line Interface. To configure the AWS CLI, you’ll need to add your credentials. You can create credentials by following these instructions. You’ll also need to specify your default region. For this tutorial, we’re using us-west-2. You can use whichever region you want. Just be sure to use the same region for all of your resources." }, { "code": null, "e": 3700, "s": 3526, "text": "For this example, we’ll load Amazon book review data from S3, perform basic processing, and calculate some aggregates. We’ll then write our aggregated data frame back to S3." }, { "code": null, "e": 3764, "s": 3700, "text": "The example is simple, but this is a common workflow for Spark." }, { "code": null, "e": 3963, "s": 3764, "text": "Read the data from a source (S3 in this example).Process the data or execute a model workflow with Spark ML.Write the results somewhere accessible to our systems (another S3 bucket in this example)." }, { "code": null, "e": 4013, "s": 3963, "text": "Read the data from a source (S3 in this example)." }, { "code": null, "e": 4073, "s": 4013, "text": "Process the data or execute a model workflow with Spark ML." }, { "code": null, "e": 4164, "s": 4073, "text": "Write the results somewhere accessible to our systems (another S3 bucket in this example)." }, { "code": null, "e": 4487, "s": 4164, "text": "If you haven’t already, create an S3 bucket now. Make sure the region you create the bucket in is the same region you use for the rest of this tutorial. I’ll be using region “US West (Oregon)”. Copy the file below. Be sure to edit the output_path in main() to use your S3 bucket. Then upload pyspark_job.py to your bucket." }, { "code": null, "e": 6199, "s": 4487, "text": "# pyspark_job.pyfrom pyspark.sql import SparkSessionfrom pyspark.sql import functions as Fdef create_spark_session(): \"\"\"Create spark session.Returns: spark (SparkSession) - spark session connected to AWS EMR cluster \"\"\" spark = SparkSession \\ .builder \\ .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\ .getOrCreate() return sparkdef process_book_data(spark, input_path, output_path): \"\"\"Process the book review data and write to S3.Arguments: spark (SparkSession) - spark session connected to AWS EMR cluster input_path (str) - AWS S3 bucket path for source data output_path (str) - AWS S3 bucket for writing processed data \"\"\" df = spark.read.parquet(input_path) # Apply some basic filters and aggregate by product_title. book_agg = df.filter(df.verified_purchase == 'Y') \\ .groupBy('product_title') \\ .agg({'star_rating': 'avg', 'review_id': 'count'}) \\ .filter(F.col('count(review_id)') >= 500) \\ .sort(F.desc('avg(star_rating)')) \\ .select(F.col('product_title').alias('book_title'), F.col('count(review_id)').alias('review_count'), F.col('avg(star_rating)').alias('review_avg_stars')) # Save the data to your S3 bucket as a .parquet file. book_agg.write.mode('overwrite')\\ .save(output_path)def main(): spark = create_spark_session() input_path = ('s3://amazon-reviews-pds/parquet/' + 'product_category=Books/*.parquet') output_path = 's3://spark-tutorial-bwl/book-aggregates' process_book_data(spark, input_path, output_path)if __name__ == '__main__': main()" }, { "code": null, "e": 6401, "s": 6199, "text": "It’s time to create our cluster and submit our application. Once our application finishes, we’ll tell the cluster to terminate. Auto-terminate allows us to pay for the resources only when we need them." }, { "code": null, "e": 6642, "s": 6401, "text": "Depending on our use case, we may not want to terminate our cluster upon completion. For instance, if you have a web application that relies on Spark for a data processing task, you may want to have a dedicated cluster running at all times." }, { "code": null, "e": 6840, "s": 6642, "text": "Run the command below. Make sure you replace the bold italicized pieces with your own files. Details on --ec2-attributes and --bootstrap-actions, and all of the other arguments, are included below." }, { "code": null, "e": 7348, "s": 6840, "text": "aws emr create-cluster --name \"Spark cluster with step\" \\ --release-label emr-5.24.1 \\ --applications Name=Spark \\ --log-uri s3://your-bucket/logs/ \\ --ec2-attributes KeyName=your-key-pair \\ --instance-type m5.xlarge \\ --instance-count 3 \\ --bootstrap-actions Path=s3://your-bucket/emr_bootstrap.sh \\ --steps Type=Spark,Name=\"Spark job\",ActionOnFailure=CONTINUE,Args=[--deploy-mode,cluster,--master,yarn,s3://your-bucket/pyspark_job.py] \\ --use-default-roles \\ --auto-terminate" }, { "code": null, "e": 7392, "s": 7348, "text": "Important aws emr create-cluster arguments:" }, { "code": null, "e": 7641, "s": 7392, "text": "--steps tells your cluster what to do after the cluster starts. Be sure to replace s3://your-bucket/pyspark_job.py in the --steps argument with the S3 path to your Spark application. You can also put your application code on S3 and pass an S3 path." }, { "code": null, "e": 8086, "s": 7641, "text": "--bootstrap-actions allows you to specify what packages you want to be installed on all of your cluster’s nodes. This step is only necessary if your application uses non-builtin Python packages other than pyspark. To use such packages, create your emr_bootstrap.sh file using the example below as a template, and add it to your S3 bucket. Include --bootstrap-actions Path=s3://your-bucket/emr_bootstrap.sh in the aws emr create-cluster command." }, { "code": null, "e": 8160, "s": 8086, "text": "#!/bin/bashsudo pip install -U \\ matplotlib \\ pandas \\ spark-nlp" }, { "code": null, "e": 8427, "s": 8160, "text": "--ec2-attributes allows you to specify many different EC2 attributes. Set your key pair using this syntax --ec2-attributes KeyPair=your-key-pair. Note: this is just the name of your key pair, not the file path. You can learn more about creating a key pair file here." }, { "code": null, "e": 8484, "s": 8427, "text": "--log-uri requires an S3 bucket to store your log files." }, { "code": null, "e": 8534, "s": 8484, "text": "Other aws emr create-cluster arguments explained:" }, { "code": null, "e": 8591, "s": 8534, "text": "--name gives the cluster you are creating an identifier." }, { "code": null, "e": 8684, "s": 8591, "text": "--release-label specifies which version of EMR to use. I recommend using the latest version." }, { "code": null, "e": 8813, "s": 8684, "text": "--applications tells EMR which type of application you will be using on your cluster. To create a Spark cluster, use Name=Spark." }, { "code": null, "e": 8900, "s": 8813, "text": "--instance-type specifies which type of EC2 instance you want to use for your cluster." }, { "code": null, "e": 8972, "s": 8900, "text": "--instance-count specifies how many instances you want in your cluster." }, { "code": null, "e": 9284, "s": 8972, "text": "--use-default-roles tells the cluster to use the default IAM roles for EMR. If this is your first time using EMR, you’ll need to run aws emr create-default-roles before you can use this command. If you’ve created a cluster on EMR in the region you have the AWS CLI configured for, then you should be good to go." }, { "code": null, "e": 9523, "s": 9284, "text": "--auto-terminate tells the cluster to terminate once the steps specified in --steps finish. Exclude this command if you would like to leave your cluster running — beware that you are paying for your cluster as long as you keep it running." }, { "code": null, "e": 9604, "s": 9523, "text": "After you execute the aws emr create-cluster command, you should get a response:" }, { "code": null, "e": 9638, "s": 9604, "text": "{ \"ClusterId\": \"j-xxxxxxxxxx\"}" }, { "code": null, "e": 9949, "s": 9638, "text": "Sign-in to the AWS console and navigate to the EMR dashboard. Your cluster status should be “Starting”. It should take about ten minutes for your cluster to start up, bootstrap, and run your application (if you used my example code). Once the step is complete, you should see the output data in your S3 bucket." }, { "code": null, "e": 9960, "s": 9949, "text": "That’s it!" }, { "code": null, "e": 10221, "s": 9960, "text": "You now know how to create an Amazon EMR cluster and submit Spark applications to it. This workflow is a crucial component of building production data processing applications with Spark. I hope you’re now feeling more confident working with all of these tools." }, { "code": null, "e": 10356, "s": 10221, "text": "Once you have your job running smoothly, consider standing up an Airflow environment on Amazon to schedule and monitor your pipelines." }, { "code": null, "e": 10544, "s": 10356, "text": "Thank you for reading! Please let me know if you liked the article or if you have any critiques. If you found this guide useful, be sure to follow me so you don’t miss my future articles." } ]
Adding Drop Shadow to Images using CSS3
To add drop shadow to image in CSS3, use the drop-shadow value for filter property. It has the following values − h-shadow – To specify a pixel value for the horizontal shadow. v-shadow – To specify a pixel value for the vertical shadow. Negative values place the shadow above the image. blur – To add a blur effect to the shadow. spread - Positive values causes the shadow to expand and negative to shrink. color – To add color to the shadow Live Demo <!DOCTYPE html> <html> <head> <style> img.demo { filter: brightness(120%); filter: contrast(120%); filter: drop-shadow(10px 10px 10px green); } </style> </head> <body> <h1>Learn MySQL</h1> <img src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150"> <h1>Learn MySQL</h1> <img class="demo" src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150"> </body> </html>
[ { "code": null, "e": 1176, "s": 1062, "text": "To add drop shadow to image in CSS3, use the drop-shadow value for filter property. It has the following values −" }, { "code": null, "e": 1239, "s": 1176, "text": "h-shadow – To specify a pixel value for the horizontal shadow." }, { "code": null, "e": 1350, "s": 1239, "text": "v-shadow – To specify a pixel value for the vertical shadow. Negative values place the shadow above the image." }, { "code": null, "e": 1393, "s": 1350, "text": "blur – To add a blur effect to the shadow." }, { "code": null, "e": 1470, "s": 1393, "text": "spread - Positive values causes the shadow to expand and negative to shrink." }, { "code": null, "e": 1505, "s": 1470, "text": "color – To add color to the shadow" }, { "code": null, "e": 1516, "s": 1505, "text": " Live Demo" }, { "code": null, "e": 1990, "s": 1516, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nimg.demo {\n filter: brightness(120%);\n filter: contrast(120%);\n filter: drop-shadow(10px 10px 10px green);\n}\n</style>\n</head>\n<body>\n<h1>Learn MySQL</h1>\n<img src=\"https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg\" alt=\"MySQL\" width=\"160\" height=\"150\">\n<h1>Learn MySQL</h1>\n<img class=\"demo\" src=\"https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg\" alt=\"MySQL\" width=\"160\" height=\"150\">\n</body>\n</html>" } ]
An algorithm to find the best moving average for stock trading | by Gianluca Malato | Towards Data Science
Moving averages are one of the most used tools in stock trading. Many traders actually use only this tool in their investment toolbox. Let’s see what they are and how we can use Python to fine-tune their features. In a time series, a moving average of period N at a certain time t, is the mean value of the N values before t (included). It’s defined for each time instant excluding the first N ones. In this particular case, we are talking about the Simple Moving Average (SMA) because every point of the average has the same weight. There are types of moving averages that weigh every point in a different way, giving more weight to the most recent data. It’s the case of the Exponential Moving Average (EMA) or the Linear Weighted Moving Average (LWMA). In trading, the number of previous time series observations the average is calculated from is called period. So, an SMA with period 20 indicates a moving average of the last 20 periods. As you can see, SMA follows the time series and it’s useful to remove noise from the signal, keeping the relevant information about the trend. Moving averages are often used in time series analysis, for example in ARIMA models and, generally speaking, when we want to compare a time series value to the average value in the past. Moving averages are often used to detect a trend. It’s very common to assume that if the stock price is above its moving average, it will likely continue rising in an uptrend. The longer the period of an SMA, the longer the time horizon of the trend it spots. As you can see, short moving averages are useful to catch short-term movements, while the 200-period SMA is able to detect a long-term trend. Generally speaking, the most used SMA periods in trading are: 20 for swing trading 50 for medium-term trading 200 for long-term trading It’s a general rule of thumb among traders that if a stock price is above its 200-days moving average, the trend is bullish (i.e. the price rises). So they are often looking for stocks whose price is above the 200-periods SMA. In order to find the best period of an SMA, we first need to know how long we are going to keep the stock in our portfolio. If we are swing traders, we may want to keep it for 5–10 business days. If we are position traders, maybe we must raise this threshold to 40–60 days. If we are portfolio traders and use moving averages as a technical filter in our stock screening plan, maybe we can focus on 200–300 days. Choosing the investment period is a discretionary choice of the trader. Once we have determined it, we must try to set a suitable SMA period. We have seen 20, 50 and 200 periods, but are they always good? Well not really. Markets change a lot during the time and they often make traders fine-tune their indicators and moving averages in order to follow volatility burst, black swans and so on. So there isn’t the right choice for the moving average period, but we can build a model that self-adapts to market changes and auto-adjust itself in order to find the best moving average period. The algorithm I propose here is an attempt to find the best moving average according to the investment period we choose. After we choose this period, we’ll try different moving averages length and find the one that maximizes the expected return of our investment (i.e. if we buy at 100 and after the chosen period the price rises to 105, we have a 5% return). The reason of using the average return after N days as an objective function is pretty simple: we want our moving average to give us the best prediction of the trend according to the time we want to keep stocks in our portfolio, so we want to maximize the average return of our investment in such a time. In practice, we’ll do the following: Take some years of daily data of our stock (e.g. 10 years) Split this dataset into training and test sets Apply different moving averages on the training set and, for each one, calculate the average return value after N days when the close price is over the moving average (we don’t consider short positions for this example) Choose the moving average length that maximizes such average return Use this moving average to calculate the average return on the test set Verify that the average return on the test set is statistically similar to the average return achieved on the training set The last point is the most important one because it performs cross-validation that helps us avoid overfitting after the optimization phase. If this check is satisfied, we can use the moving average length we found. For this example, we’ll use different stocks and investment length. The statistical significance of the mean values will be done using Welch’s test. First of all, we must install yfinance library. It’s very useful for downloading stock data. !pip install yfinance Then we can import some useful packages: import yfinanceimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import ttest_ind Let’s assume we want to keep the SPY ETF on S&P 500 index for 2 days and that we want to analyze 10 years of data. n_forward = 2name = 'SPY'start_date = "2010-01-01"end_date = "2020-06-15" Now we can download our data and calculate the return after 2 days. ticker = yfinance.Ticker(name)data = ticker.history(interval="1d",start=start_date,end=end_date)data['Forward Close'] = data['Close'].shift(-n_forward)data['Forward Return'] = (data['Forward Close'] - data['Close'])/data['Close'] Now we can perform the optimization for searching the best moving average. We’ll do a for loop that spans among 20-period moving average and 500-period moving average. For each period we split our dataset in training and test sets, then we’ll look only ad those days when the close price is above the SMA and calculate the forward return. Finally, we’ll calculate the average forward return in training and test sets, comparing them using a Welch’s test. result = []train_size = 0.6for sma_length in range(20,500): data['SMA'] = data['Close'].rolling(sma_length).mean() data['input'] = [int(x) for x in data['Close'] > data['SMA']] df = data.dropna() training = df.head(int(train_size * df.shape[0])) test = df.tail(int((1 - train_size) * df.shape[0])) tr_returns = training[training['input'] == 1]['Forward Return'] test_returns = test[test['input'] == 1]['Forward Return'] mean_forward_return_training = tr_returns.mean() mean_forward_return_test = test_returns.mean() pvalue = ttest_ind(tr_returns,test_returns,equal_var=False)[1] result.append({ 'sma_length':sma_length, 'training_forward_return': mean_forward_return_training, 'test_forward_return': mean_forward_return_test, 'p-value':pvalue }) We’ll sort all the results by training average future returns in order to get the optimal moving average. result.sort(key = lambda x : -x['training_forward_return']) The first item, which has the best score, is: As you can see, the p-value is higher than 5%, so we can assume that the average return in the test set is comparable with the average return in the training set, so we haven’t suffered overfitting. Let’s see the price chart according to the best moving average we’ve found (which is the 479-period moving average). It’s clear that the price is very often above the SMA. Now, let’s see what happens if we set n_forward = 40 (that is, we keep our position opened for 40 days). The best moving average produces these results: As you can see, the p-value is lower than 5%, so we can assume that the training phase has introduced some kind of overfitting, so we can’t use this SMA in the real world. Another reason could be that volatility has changed too much and the market needs to stabilize before making us invest in it. Finally, let’s see what happens with a Gold-based ETF (ticker: GLD) with 40-days investment. p-value is quite high, so there’s no overfitting. The best moving average period is 136, as we can see in the chart below. In this article, we’ve seen a simple algorithm to find the best Simple Moving Average for stock and ETF trading. It can be easily applied every trading day in order to find, day by day, the best moving average. In this way, a trader can easily adapt to market changes and to volatility fluctuations. All the calculations shown in this article can be found on GitHub here: https://github.com/gianlucamalato/machinelearning/blob/master/Find_the_best_moving_average.ipynb. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 386, "s": 172, "text": "Moving averages are one of the most used tools in stock trading. Many traders actually use only this tool in their investment toolbox. Let’s see what they are and how we can use Python to fine-tune their features." }, { "code": null, "e": 928, "s": 386, "text": "In a time series, a moving average of period N at a certain time t, is the mean value of the N values before t (included). It’s defined for each time instant excluding the first N ones. In this particular case, we are talking about the Simple Moving Average (SMA) because every point of the average has the same weight. There are types of moving averages that weigh every point in a different way, giving more weight to the most recent data. It’s the case of the Exponential Moving Average (EMA) or the Linear Weighted Moving Average (LWMA)." }, { "code": null, "e": 1114, "s": 928, "text": "In trading, the number of previous time series observations the average is calculated from is called period. So, an SMA with period 20 indicates a moving average of the last 20 periods." }, { "code": null, "e": 1257, "s": 1114, "text": "As you can see, SMA follows the time series and it’s useful to remove noise from the signal, keeping the relevant information about the trend." }, { "code": null, "e": 1444, "s": 1257, "text": "Moving averages are often used in time series analysis, for example in ARIMA models and, generally speaking, when we want to compare a time series value to the average value in the past." }, { "code": null, "e": 1620, "s": 1444, "text": "Moving averages are often used to detect a trend. It’s very common to assume that if the stock price is above its moving average, it will likely continue rising in an uptrend." }, { "code": null, "e": 1704, "s": 1620, "text": "The longer the period of an SMA, the longer the time horizon of the trend it spots." }, { "code": null, "e": 1846, "s": 1704, "text": "As you can see, short moving averages are useful to catch short-term movements, while the 200-period SMA is able to detect a long-term trend." }, { "code": null, "e": 1908, "s": 1846, "text": "Generally speaking, the most used SMA periods in trading are:" }, { "code": null, "e": 1929, "s": 1908, "text": "20 for swing trading" }, { "code": null, "e": 1956, "s": 1929, "text": "50 for medium-term trading" }, { "code": null, "e": 1982, "s": 1956, "text": "200 for long-term trading" }, { "code": null, "e": 2209, "s": 1982, "text": "It’s a general rule of thumb among traders that if a stock price is above its 200-days moving average, the trend is bullish (i.e. the price rises). So they are often looking for stocks whose price is above the 200-periods SMA." }, { "code": null, "e": 2622, "s": 2209, "text": "In order to find the best period of an SMA, we first need to know how long we are going to keep the stock in our portfolio. If we are swing traders, we may want to keep it for 5–10 business days. If we are position traders, maybe we must raise this threshold to 40–60 days. If we are portfolio traders and use moving averages as a technical filter in our stock screening plan, maybe we can focus on 200–300 days." }, { "code": null, "e": 2844, "s": 2622, "text": "Choosing the investment period is a discretionary choice of the trader. Once we have determined it, we must try to set a suitable SMA period. We have seen 20, 50 and 200 periods, but are they always good? Well not really." }, { "code": null, "e": 3211, "s": 2844, "text": "Markets change a lot during the time and they often make traders fine-tune their indicators and moving averages in order to follow volatility burst, black swans and so on. So there isn’t the right choice for the moving average period, but we can build a model that self-adapts to market changes and auto-adjust itself in order to find the best moving average period." }, { "code": null, "e": 3571, "s": 3211, "text": "The algorithm I propose here is an attempt to find the best moving average according to the investment period we choose. After we choose this period, we’ll try different moving averages length and find the one that maximizes the expected return of our investment (i.e. if we buy at 100 and after the chosen period the price rises to 105, we have a 5% return)." }, { "code": null, "e": 3876, "s": 3571, "text": "The reason of using the average return after N days as an objective function is pretty simple: we want our moving average to give us the best prediction of the trend according to the time we want to keep stocks in our portfolio, so we want to maximize the average return of our investment in such a time." }, { "code": null, "e": 3913, "s": 3876, "text": "In practice, we’ll do the following:" }, { "code": null, "e": 3972, "s": 3913, "text": "Take some years of daily data of our stock (e.g. 10 years)" }, { "code": null, "e": 4019, "s": 3972, "text": "Split this dataset into training and test sets" }, { "code": null, "e": 4239, "s": 4019, "text": "Apply different moving averages on the training set and, for each one, calculate the average return value after N days when the close price is over the moving average (we don’t consider short positions for this example)" }, { "code": null, "e": 4307, "s": 4239, "text": "Choose the moving average length that maximizes such average return" }, { "code": null, "e": 4379, "s": 4307, "text": "Use this moving average to calculate the average return on the test set" }, { "code": null, "e": 4502, "s": 4379, "text": "Verify that the average return on the test set is statistically similar to the average return achieved on the training set" }, { "code": null, "e": 4717, "s": 4502, "text": "The last point is the most important one because it performs cross-validation that helps us avoid overfitting after the optimization phase. If this check is satisfied, we can use the moving average length we found." }, { "code": null, "e": 4866, "s": 4717, "text": "For this example, we’ll use different stocks and investment length. The statistical significance of the mean values will be done using Welch’s test." }, { "code": null, "e": 4959, "s": 4866, "text": "First of all, we must install yfinance library. It’s very useful for downloading stock data." }, { "code": null, "e": 4981, "s": 4959, "text": "!pip install yfinance" }, { "code": null, "e": 5022, "s": 4981, "text": "Then we can import some useful packages:" }, { "code": null, "e": 5139, "s": 5022, "text": "import yfinanceimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import ttest_ind" }, { "code": null, "e": 5254, "s": 5139, "text": "Let’s assume we want to keep the SPY ETF on S&P 500 index for 2 days and that we want to analyze 10 years of data." }, { "code": null, "e": 5328, "s": 5254, "text": "n_forward = 2name = 'SPY'start_date = \"2010-01-01\"end_date = \"2020-06-15\"" }, { "code": null, "e": 5396, "s": 5328, "text": "Now we can download our data and calculate the return after 2 days." }, { "code": null, "e": 5626, "s": 5396, "text": "ticker = yfinance.Ticker(name)data = ticker.history(interval=\"1d\",start=start_date,end=end_date)data['Forward Close'] = data['Close'].shift(-n_forward)data['Forward Return'] = (data['Forward Close'] - data['Close'])/data['Close']" }, { "code": null, "e": 6081, "s": 5626, "text": "Now we can perform the optimization for searching the best moving average. We’ll do a for loop that spans among 20-period moving average and 500-period moving average. For each period we split our dataset in training and test sets, then we’ll look only ad those days when the close price is above the SMA and calculate the forward return. Finally, we’ll calculate the average forward return in training and test sets, comparing them using a Welch’s test." }, { "code": null, "e": 6866, "s": 6081, "text": "result = []train_size = 0.6for sma_length in range(20,500): data['SMA'] = data['Close'].rolling(sma_length).mean() data['input'] = [int(x) for x in data['Close'] > data['SMA']] df = data.dropna() training = df.head(int(train_size * df.shape[0])) test = df.tail(int((1 - train_size) * df.shape[0])) tr_returns = training[training['input'] == 1]['Forward Return'] test_returns = test[test['input'] == 1]['Forward Return'] mean_forward_return_training = tr_returns.mean() mean_forward_return_test = test_returns.mean() pvalue = ttest_ind(tr_returns,test_returns,equal_var=False)[1] result.append({ 'sma_length':sma_length, 'training_forward_return': mean_forward_return_training, 'test_forward_return': mean_forward_return_test, 'p-value':pvalue })" }, { "code": null, "e": 6972, "s": 6866, "text": "We’ll sort all the results by training average future returns in order to get the optimal moving average." }, { "code": null, "e": 7032, "s": 6972, "text": "result.sort(key = lambda x : -x['training_forward_return'])" }, { "code": null, "e": 7078, "s": 7032, "text": "The first item, which has the best score, is:" }, { "code": null, "e": 7277, "s": 7078, "text": "As you can see, the p-value is higher than 5%, so we can assume that the average return in the test set is comparable with the average return in the training set, so we haven’t suffered overfitting." }, { "code": null, "e": 7394, "s": 7277, "text": "Let’s see the price chart according to the best moving average we’ve found (which is the 479-period moving average)." }, { "code": null, "e": 7449, "s": 7394, "text": "It’s clear that the price is very often above the SMA." }, { "code": null, "e": 7554, "s": 7449, "text": "Now, let’s see what happens if we set n_forward = 40 (that is, we keep our position opened for 40 days)." }, { "code": null, "e": 7602, "s": 7554, "text": "The best moving average produces these results:" }, { "code": null, "e": 7900, "s": 7602, "text": "As you can see, the p-value is lower than 5%, so we can assume that the training phase has introduced some kind of overfitting, so we can’t use this SMA in the real world. Another reason could be that volatility has changed too much and the market needs to stabilize before making us invest in it." }, { "code": null, "e": 7993, "s": 7900, "text": "Finally, let’s see what happens with a Gold-based ETF (ticker: GLD) with 40-days investment." }, { "code": null, "e": 8043, "s": 7993, "text": "p-value is quite high, so there’s no overfitting." }, { "code": null, "e": 8116, "s": 8043, "text": "The best moving average period is 136, as we can see in the chart below." }, { "code": null, "e": 8416, "s": 8116, "text": "In this article, we’ve seen a simple algorithm to find the best Simple Moving Average for stock and ETF trading. It can be easily applied every trading day in order to find, day by day, the best moving average. In this way, a trader can easily adapt to market changes and to volatility fluctuations." }, { "code": null, "e": 8586, "s": 8416, "text": "All the calculations shown in this article can be found on GitHub here: https://github.com/gianlucamalato/machinelearning/blob/master/Find_the_best_moving_average.ipynb." } ]
du Command in LINUX - GeeksforGeeks
15 May, 2019 While working on LINUX, there might come a situation when you want to transfer a set of files or the entire directory. In such a case, you might wanna know the disk space consumed by that particular directory or set of files. As you are dealing with LINUX, there exists a command line utility for this also which is du command that estimates and displays the disk space used by files. So, in simple words du command-line utility helps you to find out the disk usage of set of files or a directory. Here’s the syntax of du command : //syntax of du command du [OPTION]... [FILE]... or du [OPTION]... --files0-from=F where OPTION refers to the options compatible with du command and FILE refers to the filename of which you wanna know the disk space occupied. Using du command Suppose there are two files say kt.txt and pt.txt and you want to know the disk usage of these files, then you can simply use du command by specifying the file names along with it as: //using du command $du kt.txt pt.txt 8 kt.txt 4 pt.txt /* the first column displayed the file's disk usage */ So, as shown above du displayed the disk space used by the corresponding files. Now, the displayed values are actually in the units of the first available SIZE from – -block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables and if not in this format then units are default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). Don’t get puzzled from the above paragraph. We can simply use -h option to force du to produce the output in the human readable format. Options for du command -a, – -all option : This option produces counts as output for all files, not for just directories. – -apparent-size option : This prints the apparent sizes for the files and not the disk usage which can be larger due to holes in files (sparse), internal fragmentation and indirect blocks but in real the apparent size is smaller. -c, – -total option : This displays a grand total. -B, – -block-size=SIZE option : This option causes the size to scale by SIZE like -BM prints the size in Megabytes. -b, – -bytes option : This option is equivalent to – -apparent-size – -block-size=1. -D, – -dereference-args option : This option is used to dereference only the symbolic links listed on the command line. -H option : This option is equivalent to the above -D option. – -files0-from=F option : This is used to summarize disk usage of the NUL-terminated file names specified in the file F and if the file F is “-” then read names from the standard input. -h, – -human-readable option : This prints the sizes in human readable format i.e in rounding values and using abbreviations like 1 K and this is the most often used option with du. – -si option: This is much similar to the -h option but uses power of 1000 and not of 1024. -k option : its equivalent to – -block-size=1K. -l, – -count-links option : This count sizes many times if files are hard-linked. -m option : This is equivalent to – – block-size=1M. -L, – -dereference option : This option dereferences all symbolic links. -P, – -no-dereference option : This option tells du not to follow any symbolic links which is by default setting. -0, –null option : This ends each output line with 0 byte rather than a newline. -S, – -separate-dirs option : This causes the output not to include the size of subdirectories. -s, – -summarize option : This option will allow to display a total only for each argument. -x, – -one-file-system option : This will cause du to skip directories on different file systems. -X, – -exclude-from=FILE option : Exclude files that match any pattern given in FILE. – -exclude=PATTERN option : It will exclude files that match PATTERN. -d, – -max-depth=N option : Print the total for a directory (or file, with –all) only if it is N or fewer levels below the command line argument; –max-depth=0 is the same as –summarize. – -time option : This will show the time of the last modification of any file in the directory, or any of its subdirectories. – -time=WORD option : This shows time as WORD instead of modification time :atime, access, use, ctime or status. – -time-style=STYLE option : this shows time using STYLE: full-iso, long-iso, iso, or +FORMAT (FORMAT is interpreted like the format of date). – -help option : This will display a help message and exit. – -version option : This will display version info and exit. Examples of using du command 1. Using -h option : As mentioned above, -h option is used to produce the output in human readable format. //using -h with du $du -h kt.txt pt.txt 8.0K kt.txt 4.0K pt.txt /*now the output is in human readable format i.e in Kilobytes */ 2. Using du to show disk usage of a directory : Now, if you will pass a directory name say kartik as an argument to du it will show the disk usage info of the input directory kartik and its sub-directories (if any). /*using du to display disk usage of a directory and its sub-directories */ $du kartik 4 kartik/thakral 24 kartik Above the disk usage info of the directory kartik and its sub-directory thakral is displayed. 3. Using -a option : now, as seen above only the disk usage info of directorykartik and its sub-directory thakral is displayed but what if you also want to know the disk usage info of all the files present under the directory kartik. For this, use -a option. //using -a with du $du -a kartik 8 kartik/kt.txt 4 kartik/pt.txt 4 kartik/pranjal.png 4 kartik/thakral.png 4 kartik/thakral 24 kartik /*so with -a option used all the files (under directory kartik) disk usage info is displayed along with the thakral sub-directory */ 4. Using -c option : This option displays the grand total as shown. //using -c with du $du -c -h kt.txt pt.txt 8.0K kt.txt 4.0K pt.txt 12.0K total /* at the end total is displayed for the disk usage */ 5. Using – -time option : This option is used to display the last modification time in the output of du. //using --time with du $du --time kt.txt 4 2017-11-18 16:00 kt.txt /*so the last modification date and time gets displayed when --time option is used */ 6. Using – -exclude=PATTERN option : In one of the example above, all the files disk usage related info was displayed of directory kartik. Now, suppose you want to know the info of .txt files only and not of .png files, in that case to exclude the .png pattern you can use this option. //using --exclude=PATTERN with du $du --exclude=*.png -a kartik 8 kartik/kt.txt 4 kartik/pt.txt 4 kartik/thakral 24 kartik /*so, in this case .png files info are excluded from the output */ 7. Using – -max-depth=N option : Now, this option allows you to limit the output of du to a particular depth of a directory.Suppose you have a directory named FRIENDS under which you have sub-directories as FRIENDS/college and FRIENDS/school and also under sub-directory college you have another sub-directory as FRIENDS/college/farewell then you can use – -max-depth=N option in this case as: //using --max-depth=N with du $du --max-depth=0 FRIENDS 24 FRIENDS /* in this case you restricted du output only to top=level directory */ Now, for sub-directories college and school you can use : $du --max-depth=1 FRIENDS 16 FRIENDS/college 8 FRIENDS/school 24 FRIENDS Now, for FRIENDS/college/farewell you can use –max-depth=2 as: $du --max-depth=2 FRIENDS 4 FRIENDS/college/farewell 16 FRIENDS/college 8 FRIENDS/school 24 FRIENDS /*so this is how N in --max-depth=N is used for levels */ 8. Using – -files0-from=F option : As mentioned above, this is used to summarize disk usage of the NUL-terminated file names specified in the file F and if the file F is “-” then read names from the standard input.Let’s use this option for taking input from STDIN as: //using --files0from=F with du $pwd /home/kartik $ls kt.txt pt.txt thakral /*now use this option for taking input from STDIN */ $du --files0-from=- kt.txt8 kt.txt pt.txt4 pt.txt /* in this case after giving kt.txt as a input from STDIN there is need to press Ctrl+D twice then the output is shown and same for pt.txt or any other file name given from STDIN */ Applications of du command It can be used to find out the disk space occupied by a particular directory in case of transferring files from one computer to another. du command can be linked with pipes to filters.A filter is usually a specialized program that transforms the data in a meaningful way. There also exists some other ways like df command to find the disk usage but they all lack du ability to show the disk usage of individual directories and files. It can also be used to find out quickly the number of sub-directories present in a directory. Example of using du with filters Let’s take a simple example of using du with sort command so that the output produced by du will be sorted in the increasing order of size of files. $du -a kartik 8 kartik/kt.txt 4 kartik/pt.txt 4 kartik/pranjal.png 4 kartik/thakral.png 4 kartik/thakral 24 kartik /*now using du to produce sorted output */ $du -a kartik | sort -n 4 kartik/pt.txt 4 kartik/pranjal.png 4 kartik/thakral.png 4 kartik/thakral 8 kartik/kt.txt 24 kartik /* now the output displayed is sorted according to the size */ The sort command along with -n option used causes to list the output in numeric order with the file with the smallest size appearing first.In this way du can be used to arrange the output according to the size. That’s all about du command. linux-command Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C ZIP command in Linux with examples Conditional Statements | Shell Script tar command in Linux with examples UDP Server-Client implementation in C curl command in Linux with Examples Cat command in Linux with examples echo command in Linux with Examples Mutex lock for Linux Thread Synchronization Thread functions in C/C++
[ { "code": null, "e": 23950, "s": 23922, "text": "\n15 May, 2019" }, { "code": null, "e": 24335, "s": 23950, "text": "While working on LINUX, there might come a situation when you want to transfer a set of files or the entire directory. In such a case, you might wanna know the disk space consumed by that particular directory or set of files. As you are dealing with LINUX, there exists a command line utility for this also which is du command that estimates and displays the disk space used by files." }, { "code": null, "e": 24448, "s": 24335, "text": "So, in simple words du command-line utility helps you to find out the disk usage of set of files or a directory." }, { "code": null, "e": 24482, "s": 24448, "text": "Here’s the syntax of du command :" }, { "code": null, "e": 24573, "s": 24482, "text": "//syntax of du command\n\ndu [OPTION]... [FILE]...\n or\ndu [OPTION]... --files0-from=F\n" }, { "code": null, "e": 24716, "s": 24573, "text": "where OPTION refers to the options compatible with du command and FILE refers to the filename of which you wanna know the disk space occupied." }, { "code": null, "e": 24733, "s": 24716, "text": "Using du command" }, { "code": null, "e": 24917, "s": 24733, "text": "Suppose there are two files say kt.txt and pt.txt and you want to know the disk usage of these files, then you can simply use du command by specifying the file names along with it as:" }, { "code": null, "e": 25043, "s": 24917, "text": "//using du command\n\n$du kt.txt pt.txt\n8 kt.txt\n4 pt.txt\n\n/* the first column \ndisplayed the file's\ndisk usage */\n" }, { "code": null, "e": 25123, "s": 25043, "text": "So, as shown above du displayed the disk space used by the corresponding files." }, { "code": null, "e": 25392, "s": 25123, "text": "Now, the displayed values are actually in the units of the first available SIZE from – -block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables and if not in this format then units are default to 1024 bytes (or 512 if POSIXLY_CORRECT is set)." }, { "code": null, "e": 25528, "s": 25392, "text": "Don’t get puzzled from the above paragraph. We can simply use -h option to force du to produce the output in the human readable format." }, { "code": null, "e": 25551, "s": 25528, "text": "Options for du command" }, { "code": null, "e": 25650, "s": 25551, "text": "-a, – -all option : This option produces counts as output for all files, not for just directories." }, { "code": null, "e": 25881, "s": 25650, "text": "– -apparent-size option : This prints the apparent sizes for the files and not the disk usage which can be larger due to holes in files (sparse), internal fragmentation and indirect blocks but in real the apparent size is smaller." }, { "code": null, "e": 25932, "s": 25881, "text": "-c, – -total option : This displays a grand total." }, { "code": null, "e": 26048, "s": 25932, "text": "-B, – -block-size=SIZE option : This option causes the size to scale by SIZE like -BM prints the size in Megabytes." }, { "code": null, "e": 26133, "s": 26048, "text": "-b, – -bytes option : This option is equivalent to – -apparent-size – -block-size=1." }, { "code": null, "e": 26253, "s": 26133, "text": "-D, – -dereference-args option : This option is used to dereference only the symbolic links listed on the command line." }, { "code": null, "e": 26315, "s": 26253, "text": "-H option : This option is equivalent to the above -D option." }, { "code": null, "e": 26501, "s": 26315, "text": "– -files0-from=F option : This is used to summarize disk usage of the NUL-terminated file names specified in the file F and if the file F is “-” then read names from the standard input." }, { "code": null, "e": 26683, "s": 26501, "text": "-h, – -human-readable option : This prints the sizes in human readable format i.e in rounding values and using abbreviations like 1 K and this is the most often used option with du." }, { "code": null, "e": 26775, "s": 26683, "text": "– -si option: This is much similar to the -h option but uses power of 1000 and not of 1024." }, { "code": null, "e": 26823, "s": 26775, "text": "-k option : its equivalent to – -block-size=1K." }, { "code": null, "e": 26905, "s": 26823, "text": "-l, – -count-links option : This count sizes many times if files are hard-linked." }, { "code": null, "e": 26958, "s": 26905, "text": "-m option : This is equivalent to – – block-size=1M." }, { "code": null, "e": 27031, "s": 26958, "text": "-L, – -dereference option : This option dereferences all symbolic links." }, { "code": null, "e": 27145, "s": 27031, "text": "-P, – -no-dereference option : This option tells du not to follow any symbolic links which is by default setting." }, { "code": null, "e": 27226, "s": 27145, "text": "-0, –null option : This ends each output line with 0 byte rather than a newline." }, { "code": null, "e": 27322, "s": 27226, "text": "-S, – -separate-dirs option : This causes the output not to include the size of subdirectories." }, { "code": null, "e": 27414, "s": 27322, "text": "-s, – -summarize option : This option will allow to display a total only for each argument." }, { "code": null, "e": 27512, "s": 27414, "text": "-x, – -one-file-system option : This will cause du to skip directories on different file systems." }, { "code": null, "e": 27598, "s": 27512, "text": "-X, – -exclude-from=FILE option : Exclude files that match any pattern given in FILE." }, { "code": null, "e": 27668, "s": 27598, "text": "– -exclude=PATTERN option : It will exclude files that match PATTERN." }, { "code": null, "e": 27854, "s": 27668, "text": "-d, – -max-depth=N option : Print the total for a directory (or file, with –all) only if it is N or fewer levels below the command line argument; –max-depth=0 is the same as –summarize." }, { "code": null, "e": 27980, "s": 27854, "text": "– -time option : This will show the time of the last modification of any file in the directory, or any of its subdirectories." }, { "code": null, "e": 28093, "s": 27980, "text": "– -time=WORD option : This shows time as WORD instead of modification time :atime, access, use, ctime or status." }, { "code": null, "e": 28236, "s": 28093, "text": "– -time-style=STYLE option : this shows time using STYLE: full-iso, long-iso, iso, or +FORMAT (FORMAT is interpreted like the format of date)." }, { "code": null, "e": 28296, "s": 28236, "text": "– -help option : This will display a help message and exit." }, { "code": null, "e": 28357, "s": 28296, "text": "– -version option : This will display version info and exit." }, { "code": null, "e": 28386, "s": 28357, "text": "Examples of using du command" }, { "code": null, "e": 28493, "s": 28386, "text": "1. Using -h option : As mentioned above, -h option is used to produce the output in human readable format." }, { "code": null, "e": 28631, "s": 28493, "text": "//using -h with du\n\n$du -h kt.txt pt.txt\n8.0K kt.txt\n4.0K pt.txt\n\n/*now the output\nis in human readable\nformat i.e in\nKilobytes */\n" }, { "code": null, "e": 28847, "s": 28631, "text": "2. Using du to show disk usage of a directory : Now, if you will pass a directory name say kartik as an argument to du it will show the disk usage info of the input directory kartik and its sub-directories (if any)." }, { "code": null, "e": 28975, "s": 28847, "text": "/*using du to display disk usage \nof a directory and its\nsub-directories */\n\n$du kartik\n4 kartik/thakral\n24 kartik\n\n" }, { "code": null, "e": 29069, "s": 28975, "text": "Above the disk usage info of the directory kartik and its sub-directory thakral is displayed." }, { "code": null, "e": 29328, "s": 29069, "text": "3. Using -a option : now, as seen above only the disk usage info of directorykartik and its sub-directory thakral is displayed but what if you also want to know the disk usage info of all the files present under the directory kartik. For this, use -a option." }, { "code": null, "e": 29634, "s": 29328, "text": "//using -a with du\n\n$du -a kartik\n8 kartik/kt.txt\n4 kartik/pt.txt\n4 kartik/pranjal.png\n4 kartik/thakral.png\n4 kartik/thakral\n24 kartik\n\n/*so with -a option used\nall the files (under directory\nkartik) disk usage info is\ndisplayed along with the \nthakral sub-directory */\n" }, { "code": null, "e": 29702, "s": 29634, "text": "4. Using -c option : This option displays the grand total as shown." }, { "code": null, "e": 29848, "s": 29702, "text": "//using -c with du\n\n$du -c -h kt.txt pt.txt\n8.0K kt.txt\n4.0K pt.txt\n12.0K total\n\n/* at the end\ntotal is displayed \nfor the disk usage */\n" }, { "code": null, "e": 29953, "s": 29848, "text": "5. Using – -time option : This option is used to display the last modification time in the output of du." }, { "code": null, "e": 30122, "s": 29953, "text": "//using --time with du\n\n$du --time kt.txt\n4 2017-11-18 16:00 kt.txt\n\n/*so the last\nmodification date and\ntime gets displayed\nwhen --time \noption is used */\n" }, { "code": null, "e": 30408, "s": 30122, "text": "6. Using – -exclude=PATTERN option : In one of the example above, all the files disk usage related info was displayed of directory kartik. Now, suppose you want to know the info of .txt files only and not of .png files, in that case to exclude the .png pattern you can use this option." }, { "code": null, "e": 30624, "s": 30408, "text": "//using --exclude=PATTERN with du\n\n$du --exclude=*.png -a kartik\n8 kartik/kt.txt\n4 kartik/pt.txt\n4 kartik/thakral\n24 kartik\n\n/*so, in this case\n.png files info are\nexcluded from the output */\n" }, { "code": null, "e": 31018, "s": 30624, "text": "7. Using – -max-depth=N option : Now, this option allows you to limit the output of du to a particular depth of a directory.Suppose you have a directory named FRIENDS under which you have sub-directories as FRIENDS/college and FRIENDS/school and also under sub-directory college you have another sub-directory as FRIENDS/college/farewell then you can use – -max-depth=N option in this case as:" }, { "code": null, "e": 31168, "s": 31018, "text": "//using --max-depth=N with du\n\n$du --max-depth=0 FRIENDS\n24 FRIENDS\n\n\n/* in this case you \nrestricted du output\nonly to top=level\ndirectory */\n" }, { "code": null, "e": 31226, "s": 31168, "text": "Now, for sub-directories college and school you can use :" }, { "code": null, "e": 31317, "s": 31226, "text": "$du --max-depth=1 FRIENDS\n16 FRIENDS/college\n8 FRIENDS/school\n24 FRIENDS\n\n" }, { "code": null, "e": 31380, "s": 31317, "text": "Now, for FRIENDS/college/farewell you can use –max-depth=2 as:" }, { "code": null, "e": 31563, "s": 31380, "text": "$du --max-depth=2 FRIENDS\n4 FRIENDS/college/farewell\n16 FRIENDS/college\n8 FRIENDS/school\n24 FRIENDS\n\n/*so this is how N\nin --max-depth=N \nis used for levels */\n" }, { "code": null, "e": 31831, "s": 31563, "text": "8. Using – -files0-from=F option : As mentioned above, this is used to summarize disk usage of the NUL-terminated file names specified in the file F and if the file F is “-” then read names from the standard input.Let’s use this option for taking input from STDIN as:" }, { "code": null, "e": 32200, "s": 31831, "text": "//using --files0from=F with du\n\n$pwd\n/home/kartik\n\n$ls\nkt.txt pt.txt thakral\n\n/*now use this option for \ntaking input from\nSTDIN */\n\n$du --files0-from=-\nkt.txt8 kt.txt\npt.txt4 pt.txt\n\n/* in this case after \ngiving kt.txt as a input\nfrom STDIN there is need to\npress Ctrl+D twice then the\noutput is shown and same for\npt.txt or any other file name\ngiven from STDIN */\n\n" }, { "code": null, "e": 32227, "s": 32200, "text": "Applications of du command" }, { "code": null, "e": 32364, "s": 32227, "text": "It can be used to find out the disk space occupied by a particular directory in case of transferring files from one computer to another." }, { "code": null, "e": 32499, "s": 32364, "text": "du command can be linked with pipes to filters.A filter is usually a specialized program that transforms the data in a meaningful way." }, { "code": null, "e": 32661, "s": 32499, "text": "There also exists some other ways like df command to find the disk usage but they all lack du ability to show the disk usage of individual directories and files." }, { "code": null, "e": 32755, "s": 32661, "text": "It can also be used to find out quickly the number of sub-directories present in a directory." }, { "code": null, "e": 32788, "s": 32755, "text": "Example of using du with filters" }, { "code": null, "e": 32937, "s": 32788, "text": "Let’s take a simple example of using du with sort command so that the output produced by du will be sorted in the increasing order of size of files." }, { "code": null, "e": 33358, "s": 32937, "text": "\n$du -a kartik\n8 kartik/kt.txt\n4 kartik/pt.txt\n4 kartik/pranjal.png\n4 kartik/thakral.png\n4 kartik/thakral\n24 kartik\n\n/*now using du to produce\nsorted output */\n\n$du -a kartik | sort -n\n4 kartik/pt.txt\n4 kartik/pranjal.png\n4 kartik/thakral.png\n4 kartik/thakral\n8 kartik/kt.txt\n24 kartik\n\n/* now the output displayed\nis sorted according to the size */\n" }, { "code": null, "e": 33569, "s": 33358, "text": "The sort command along with -n option used causes to list the output in numeric order with the file with the smallest size appearing first.In this way du can be used to arrange the output according to the size." }, { "code": null, "e": 33598, "s": 33569, "text": "That’s all about du command." }, { "code": null, "e": 33612, "s": 33598, "text": "linux-command" }, { "code": null, "e": 33632, "s": 33612, "text": "Linux-file-commands" }, { "code": null, "e": 33643, "s": 33632, "text": "Linux-Unix" }, { "code": null, "e": 33741, "s": 33643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33750, "s": 33741, "text": "Comments" }, { "code": null, "e": 33763, "s": 33750, "text": "Old Comments" }, { "code": null, "e": 33801, "s": 33763, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 33836, "s": 33801, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 33874, "s": 33836, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 33909, "s": 33874, "text": "tar command in Linux with examples" }, { "code": null, "e": 33947, "s": 33909, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33983, "s": 33947, "text": "curl command in Linux with Examples" }, { "code": null, "e": 34018, "s": 33983, "text": "Cat command in Linux with examples" }, { "code": null, "e": 34054, "s": 34018, "text": "echo command in Linux with Examples" }, { "code": null, "e": 34098, "s": 34054, "text": "Mutex lock for Linux Thread Synchronization" } ]
AWT TextEvent Class
The object of this class represents the text events.The TextEvent is generated when character is entered in the text fields or text area. The TextEvent instance does not include the characters currently in the text component that generated the event rather we are provided with other methods to retrieve that information. Following is the declaration for java.awt.event.TextEvent class: public class TextEvent extends AWTEvent Following are the fields for java.awt.event.TextEvent class: static int TEXT_FIRST --The first number in the range of ids used for text events. static int TEXT_FIRST --The first number in the range of ids used for text events. static int TEXT_LAST --The last number in the range of ids used for text events. static int TEXT_LAST --The last number in the range of ids used for text events. static int TEXT_VALUE_CHANGED --This event id indicates that object's text changed. static int TEXT_VALUE_CHANGED --This event id indicates that object's text changed. TextEvent(Object source, int id) Constructs a TextEvent object. String paramString() Returns a parameter string identifying this text event. This class inherits methods from the following classes: java.awt.AWTEvent java.awt.AWTEvent java.util.EventObject java.util.EventObject java.lang.Object java.lang.Object 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 2070, "s": 1747, "text": "The object of this class represents the text events.The TextEvent is generated when character is entered in the text fields or text area. The TextEvent instance does not include the characters currently in the text component that generated the event rather we are provided with other methods to retrieve that information." }, { "code": null, "e": 2135, "s": 2070, "text": "Following is the declaration for java.awt.event.TextEvent class:" }, { "code": null, "e": 2178, "s": 2135, "text": "public class TextEvent\n extends AWTEvent" }, { "code": null, "e": 2239, "s": 2178, "text": "Following are the fields for java.awt.event.TextEvent class:" }, { "code": null, "e": 2323, "s": 2239, "text": "static int TEXT_FIRST --The first number in the range of ids used for text events." }, { "code": null, "e": 2407, "s": 2323, "text": "static int TEXT_FIRST --The first number in the range of ids used for text events." }, { "code": null, "e": 2489, "s": 2407, "text": "static int TEXT_LAST --The last number in the range of ids used for text events." }, { "code": null, "e": 2571, "s": 2489, "text": "static int TEXT_LAST --The last number in the range of ids used for text events." }, { "code": null, "e": 2656, "s": 2571, "text": "static int TEXT_VALUE_CHANGED --This event id indicates that object's text changed." }, { "code": null, "e": 2741, "s": 2656, "text": "static int TEXT_VALUE_CHANGED --This event id indicates that object's text changed." }, { "code": null, "e": 2775, "s": 2741, "text": "TextEvent(Object source, int id) " }, { "code": null, "e": 2806, "s": 2775, "text": "Constructs a TextEvent object." }, { "code": null, "e": 2827, "s": 2806, "text": "String\tparamString()" }, { "code": null, "e": 2884, "s": 2827, "text": " Returns a parameter string identifying this text event." }, { "code": null, "e": 2940, "s": 2884, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 2958, "s": 2940, "text": "java.awt.AWTEvent" }, { "code": null, "e": 2976, "s": 2958, "text": "java.awt.AWTEvent" }, { "code": null, "e": 2998, "s": 2976, "text": "java.util.EventObject" }, { "code": null, "e": 3020, "s": 2998, "text": "java.util.EventObject" }, { "code": null, "e": 3037, "s": 3020, "text": "java.lang.Object" }, { "code": null, "e": 3054, "s": 3037, "text": "java.lang.Object" }, { "code": null, "e": 3087, "s": 3054, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 3095, "s": 3087, "text": " EduOLC" }, { "code": null, "e": 3102, "s": 3095, "text": " Print" }, { "code": null, "e": 3113, "s": 3102, "text": " Add Notes" } ]
List assign() function in C++ STL
Given is th e task to show the working of the assign() function in C++. The list::assign() function is a part of the C++ standard template library. It is used to assign the values to a list and also to copy values from one list to another. <list> header file should be included to call this function. The syntax for assigning new values is as follows − List_Name.assign(size,value) The syntax for copying values from one list to another is as follows − First_List.assign(Second_List.begin(),Second_list.end()) The function takes two parameters − First is size, that represents the size of the list and the second one is value, which represents the data value to be stored inside the list. The function has no return value. Input: Lt.assign(3,10) Output: The size of list Lt is 3. The elements of the list Lt are 10 10 10. Explanation − The following example shows how we can assign a list its size and values by using the assign() function. The first value that we will pass inside the list function becomes the size of the list, in this case it is 3 and the second element is the value that is assigned to each position of the list and here it is 10. Input: int array[5] = { 1, 2, 3, 4 } Lt.assign(array,array+3) Output: The size of list Lt is 3. The elements of the list Lt are 1 2 3. Explanation − The following example shows how we can assign values to a list using an array. The total number of elements that we will assign to the list becomes the size of the list. The user has to simply pass the name of the array as the first argument inside the assign() function, and the second argument should be the name of the array, then a “+” sign followed by the number of elements the user wants to assign to the list. In the above case we have written 3, so the first three elements of the array will be assigned to the list. If we write a number that is bigger than the number of elements present in the array, let us say 6, then the program will not show any error instead the size of the list will become 6 and the extra positions in the list will be assigned with the value zero. Approach used in the below program as follows − First create a function ShowList(list<int> L) that will display the elements of the list. Create an iterator, let’s say itr that will contain the initial element of the list to be displayed. Make the loop run till itr reaches the final element of the list. Then inside the main() function create three lists using list<int> let’s say L1, L2 ad L3 so that they accept values of type int and then create an array of type int, let’s say arr[] and assign it some values. Then use the assign() function to assign size and some values to the list L1 and then pass the list L1 into the ShowDisplay() function. Then use the assign() function to copy elements of list L1 into L2 and also pass the list L2 into the ShowList() function. Then use the assign() function to copy elements of the array arr[] into the list L3 and pass the list L3 into the DisplayList() function. Start Step 1-> Declare function DisplayList(list<int> L) for showing list elements Declare iterator itr Loop For itr=L.begin() and itr!=L.end() and itr++ Print *itr End Step 2-> In function main() Declare lists L1,L2,L3 Initialize array arr[] Call L1.assign(size,value) Print L1.size(); Call function DisplayList(L1) to display L1 Call L2.assign(L1.begin(),L1.end()) Print L2.size(); Call function DisplayList(L2) to display L2 Call L3.assign(arr,arr+4) Print L3.size(); Call function DisplayList(L3) to display L3 Stop Live Demo #include<iostream> #include<list> using namespace std; int ShowList(list<int> L) { cout<<"The elements of the list are "; list<int>::iterator itr; for(itr=L.begin(); itr!=L.end(); itr++) { cout<<*itr<<" "; } cout<<"\n"; } int main() { list<int> L1; list<int> L2; list<int> L3; int arr[10] = { 6, 7, 2, 4 }; //assigning size and values to list L1 L1.assign(3,20); cout<<"The size of list L1 is "<<L1.size()<<"\n"; ShowList(L1); //copying the elements of L1 into L3 L2.assign(L1.begin(),L1.end()); cout<<"The size of list is L2 "<<L2.size()<<"\n"; ShowList(L2); //copying the elements of arr[] into list L3 L3.assign(arr,arr+4); cout<<"The size of list is L3 "<<L3.size()<<"\n"; ShowList(L3); return 0; } If we run the above code it will generate the following output − The size of list L1 is 3 The elements of the list are 20 20 20 The size of list L2 is 3 The elements of the list are 20 20 20 The size of list L3 is 4 The elements of the list are 6 7 2 4 Explanation For the list L1 we gave size as 3 and value as 20 in the assign() function which had generated the above output. Then we copied the elements of list L1 into that L2 that gives L2 the same size and value as that of L1 as we can see in the output. Then we used the assign function to copy all the elements of the array arr[] which made the size of L3 equal to 4 and its elements same as the elements of the array as in the output.
[ { "code": null, "e": 1134, "s": 1062, "text": "Given is th e task to show the working of the assign() function in C++." }, { "code": null, "e": 1302, "s": 1134, "text": "The list::assign() function is a part of the C++ standard template library. It is used to assign the values to a list and also to copy values from one list to another." }, { "code": null, "e": 1363, "s": 1302, "text": "<list> header file should be included to call this function." }, { "code": null, "e": 1415, "s": 1363, "text": "The syntax for assigning new values is as follows −" }, { "code": null, "e": 1444, "s": 1415, "text": "List_Name.assign(size,value)" }, { "code": null, "e": 1515, "s": 1444, "text": "The syntax for copying values from one list to another is as follows −" }, { "code": null, "e": 1572, "s": 1515, "text": "First_List.assign(Second_List.begin(),Second_list.end())" }, { "code": null, "e": 1608, "s": 1572, "text": "The function takes two parameters −" }, { "code": null, "e": 1751, "s": 1608, "text": "First is size, that represents the size of the list and the second one is value, which represents the data value to be stored inside the list." }, { "code": null, "e": 1785, "s": 1751, "text": "The function has no return value." }, { "code": null, "e": 1884, "s": 1785, "text": "Input: Lt.assign(3,10)\nOutput: The size of list Lt is 3.\nThe elements of the list Lt are 10 10 10." }, { "code": null, "e": 1898, "s": 1884, "text": "Explanation −" }, { "code": null, "e": 2214, "s": 1898, "text": "The following example shows how we can assign a list its size and values by using the assign() function. The first value that we will pass inside the list function becomes the size of the list, in this case it is 3 and the second element is the value that is assigned to each position of the list and here it is 10." }, { "code": null, "e": 2349, "s": 2214, "text": "Input: int array[5] = { 1, 2, 3, 4 }\nLt.assign(array,array+3)\nOutput: The size of list Lt is 3.\nThe elements of the list Lt are 1 2 3." }, { "code": null, "e": 2363, "s": 2349, "text": "Explanation −" }, { "code": null, "e": 2533, "s": 2363, "text": "The following example shows how we can assign values to a list using an array. The total number of elements that we will assign to the list becomes the size of the list." }, { "code": null, "e": 2781, "s": 2533, "text": "The user has to simply pass the name of the array as the first argument inside the assign() function, and the second argument should be the name of the array, then a “+” sign followed by the number of elements the user wants to assign to the list." }, { "code": null, "e": 2889, "s": 2781, "text": "In the above case we have written 3, so the first three elements of the array will be assigned to the list." }, { "code": null, "e": 3147, "s": 2889, "text": "If we write a number that is bigger than the number of elements present in the array, let us say 6, then the program will not show any error instead the size of the list will become 6 and the extra positions in the list will be assigned with the value zero." }, { "code": null, "e": 3195, "s": 3147, "text": "Approach used in the below program as follows −" }, { "code": null, "e": 3285, "s": 3195, "text": "First create a function ShowList(list<int> L) that will display the elements of the list." }, { "code": null, "e": 3386, "s": 3285, "text": "Create an iterator, let’s say itr that will contain the initial element of the list to be displayed." }, { "code": null, "e": 3452, "s": 3386, "text": "Make the loop run till itr reaches the final element of the list." }, { "code": null, "e": 3662, "s": 3452, "text": "Then inside the main() function create three lists using list<int> let’s say L1, L2 ad L3 so that they accept values of type int and then create an array of type int, let’s say arr[] and assign it some values." }, { "code": null, "e": 3798, "s": 3662, "text": "Then use the assign() function to assign size and some values to the list L1 and then pass the list L1 into the ShowDisplay() function." }, { "code": null, "e": 3921, "s": 3798, "text": "Then use the assign() function to copy elements of list L1 into L2 and also pass the list L2 into the ShowList() function." }, { "code": null, "e": 4059, "s": 3921, "text": "Then use the assign() function to copy elements of the array arr[] into the list L3 and pass the list L3 into the DisplayList() function." }, { "code": null, "e": 4624, "s": 4059, "text": "Start\nStep 1-> Declare function DisplayList(list<int> L) for showing list elements\n Declare iterator itr\n Loop For itr=L.begin() and itr!=L.end() and itr++\n Print *itr\n End\nStep 2-> In function main()\n Declare lists L1,L2,L3\n Initialize array arr[]\n Call L1.assign(size,value)\n Print L1.size();\n Call function DisplayList(L1) to display L1\n Call L2.assign(L1.begin(),L1.end())\n Print L2.size();\n Call function DisplayList(L2) to display L2\n Call L3.assign(arr,arr+4)\n Print L3.size();\n Call function DisplayList(L3) to display L3\nStop" }, { "code": null, "e": 4635, "s": 4624, "text": " Live Demo" }, { "code": null, "e": 5410, "s": 4635, "text": "#include<iostream>\n#include<list>\nusing namespace std;\nint ShowList(list<int> L) {\n cout<<\"The elements of the list are \";\n list<int>::iterator itr;\n for(itr=L.begin(); itr!=L.end(); itr++) {\n cout<<*itr<<\" \";\n }\n cout<<\"\\n\";\n}\nint main() {\n list<int> L1;\n list<int> L2;\n list<int> L3;\n int arr[10] = { 6, 7, 2, 4 };\n //assigning size and values to list L1\n L1.assign(3,20);\n cout<<\"The size of list L1 is \"<<L1.size()<<\"\\n\";\n ShowList(L1);\n //copying the elements of L1 into L3\n L2.assign(L1.begin(),L1.end());\n cout<<\"The size of list is L2 \"<<L2.size()<<\"\\n\";\n ShowList(L2);\n //copying the elements of arr[] into list L3\n L3.assign(arr,arr+4);\n cout<<\"The size of list is L3 \"<<L3.size()<<\"\\n\";\n ShowList(L3);\n return 0;\n}" }, { "code": null, "e": 5475, "s": 5410, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 5663, "s": 5475, "text": "The size of list L1 is 3\nThe elements of the list are 20 20 20\nThe size of list L2 is 3\nThe elements of the list are 20 20 20\nThe size of list L3 is 4\nThe elements of the list are 6 7 2 4" }, { "code": null, "e": 5675, "s": 5663, "text": "Explanation" }, { "code": null, "e": 5788, "s": 5675, "text": "For the list L1 we gave size as 3 and value as 20 in the assign() function which had generated the above output." }, { "code": null, "e": 5921, "s": 5788, "text": "Then we copied the elements of list L1 into that L2 that gives L2 the same size and value as that of L1 as we can see in the output." }, { "code": null, "e": 6104, "s": 5921, "text": "Then we used the assign function to copy all the elements of the array arr[] which made the size of L3 equal to 4 and its elements same as the elements of the array as in the output." } ]
Loop through the Vector elements using an Iterator in Java
An Iterator can be used to loop through the Vector elements. The method hasNext( ) returns true if there are more elements in the Vector and false otherwise. The method next( ) returns the next element in the Vector and throws the exception NoSuchElementException if there is no next element. A program that demonstrates this is given as follows − Live Demo import java.util.Iterator; import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(); vec.add(4); vec.add(1); vec.add(3); vec.add(9); vec.add(6); vec.add(8); System.out.println("The Vector elements are: "); Iterator i = vec.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } } The output of the above program is as follows − The Vector elements are: 4 1 3 9 6 8 Now let us understand the above program. The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows − Vector vec = new Vector(); vec.add(4); vec.add(1); vec.add(3); vec.add(9); vec.add(6); vec.add(8); System.out.println("The Vector elements are: "); Iterator i = vec.iterator(); while (i.hasNext()) { System.out.println(i.next()); }
[ { "code": null, "e": 1355, "s": 1062, "text": "An Iterator can be used to loop through the Vector elements. The method hasNext( ) returns true if there are more elements in the Vector and false otherwise. The method next( ) returns the next element in the Vector and throws the exception NoSuchElementException if there is no next element." }, { "code": null, "e": 1410, "s": 1355, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1421, "s": 1410, "text": " Live Demo" }, { "code": null, "e": 1850, "s": 1421, "text": "import java.util.Iterator;\nimport java.util.Vector;\npublic class Demo {\n public static void main(String args[]) {\n Vector vec = new Vector();\n vec.add(4);\n vec.add(1);\n vec.add(3);\n vec.add(9);\n vec.add(6);\n vec.add(8);\n System.out.println(\"The Vector elements are: \");\n Iterator i = vec.iterator();\n while (i.hasNext()) {\n System.out.println(i.next());\n }\n }\n}" }, { "code": null, "e": 1898, "s": 1850, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1935, "s": 1898, "text": "The Vector elements are:\n4\n1\n3\n9\n6\n8" }, { "code": null, "e": 1976, "s": 1935, "text": "Now let us understand the above program." }, { "code": null, "e": 2213, "s": 1976, "text": "The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2447, "s": 2213, "text": "Vector vec = new Vector();\nvec.add(4);\nvec.add(1);\nvec.add(3);\nvec.add(9);\nvec.add(6);\nvec.add(8);\nSystem.out.println(\"The Vector elements are: \");\nIterator i = vec.iterator();\nwhile (i.hasNext()) {\n System.out.println(i.next());\n}" } ]
Making Docker, Conda and Jupyter play well together | by Borun Chowdhury Ph.D. | Towards Data Science
Docker and Docker-Compose are great utilities that support the microservice paradigm by allowing efficient containerization. Within the python ecosystem the package manager Conda also allows some kind of containerization that is limited to python packages. Conda environments are especially handy for data scientists working in jupyter notebooks that have different (and mutually exclusive) package dependencies. However, due to the peculiar way in which conda environments are setup, getting them working out of the box in Docker, as it were, is not so straightforward. Furthermore, adding kernelspecs for these environments to jupyter is another very useful but complicated step. This article will clearly and concisely explain how to setup Dockerized containers with Jupyter having multiple kernels. To gain from this article you should already know the basics of Docker, Conda and Jupyter. If you don’t and would like to there are excellent tutorials on all three on their websites. I like Docker in the context of data science and machine learning research as it is very easy for me to containerize my whole research setup and move it to the various cloud services that I use (my laptop, my desktop, GCP, a barebones cloud we maintain and AWS). Requiring multiple conda environments and associated jupyter kernels is something one often needs in Data Science and Machine Learning. For instance when dealing with Python 2 and Python 3 code or when transitioning from Tensorflow 1 to Tensorflow 2. One such issue came up recently for me. I work with TensorFlow and PyTorch both for deeplearning and till now I had them both installed in the same conda environment in my docker image. However, turns out that installing tensorflow 2.x breaks tensorboard for pytorch and the “solution” seems to be to not install tensorflow in the same environment as pytorch. To reproduce it just try running the tutorial notebook mentioned in the image above after installing tensorflow 2. So, in this case the solution is either of the following Two dockerized containers with one having tensorflow 2 and the other pytorch.One container with two environments that give two kernels in jupyter. Two dockerized containers with one having tensorflow 2 and the other pytorch. One container with two environments that give two kernels in jupyter. The second one seems more elegant. Nevertheless, the standard way of creating a conda environment and activating it requires an interactive sessions and that is not possible when building a docker image. In this article I quickly describe what needs to be done using a simple example and the actual code can be found in my repository. In fact my repository has the actual code that can be used to run the jupyter notebook mentioned above here but that has a lot of other steps that can distract away from the main topic of this article which is how to make Docker and Conda play well together. So I have also made another toy example here that just helps explain this particular point. The docker file contains the following main steps: Start with Ubuntu Download and install miniconda RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shRUN bash Miniconda3-latest-Linux-x86_64.sh -b -p /minicondaENV PATH=$PATH:/miniconda/condabin:/miniconda/bin Install jupyter in the base environment Create two more environments and add them to jupyter kernel list. This is a non-trivial step as one has to run ipykernel install in the new environment. Usually one would do that by doing conda init and then activate the new environment but this requires starting a new bash shell which we cannot do here. This is thus handled in a different way by running commands in the appropriate shells in the following manner. RUN conda env create -f packages/environment_one.ymlSHELL ["conda","run","-n","one","/bin/bash","-c"]RUN python -m ipykernel install --name kernel_one --display-name "Display Name One"RUN pip install -U -r packages/requirements_one.txt Add a new user and switch to her directory Perform conda init as well as make it so that by default a new bash session opens in a one of the newly created environments. This step is not necessary for the problem we described is worth noting in case we do want the shell to be conda friendly and launch into one of the extra environments SHELL ["/bin/bash","-c"]RUN conda initRUN echo 'conda activate one' >> ~/.bashrc Expose the port on which jupyter notebook will listen and run it. Note that in this example I am running a notebook with no authentication which is only for illustrative purposes. You should always turn on proper authentication. EXPOSE 8888 ENTRYPOINT ["jupyter", "notebook", "--no-browser","--ip=0.0.0.0","--NotebookApp.token=''","--NotebookApp.password=''"] Finally I find it very useful to put all my microservices behind the reverse proxy traefik. This has the additional advantage of being able to turn on SSL on all services without individual configuration. In this toy example there is only one microservice but when we have many it is useful to turn them on with prefixes and here is why I used an entry point instead of command in the dockerfile above. I can now complete the command by asking jupyter to start the notebook server while listening on a different path where traefik will redirect the traffic command: "--NotebookApp.base_url='multiple_conda_environments'" Now the notebook can be accessed on https://myserver.com /multiple_conda_environment where you should replace myserver.com with your hostname. Now when you run try to create a new notebook you should see a choice between the standard python3 and two additional kernels If you go to the actual repository with the full code to run both tensorflow and pytorch you will find that I appropriated the python3 kernel to convert it into a tensorflow kernel and have changed its name to reflect that. This is a better solution if you do not care about the extra default kernel floating around that is not going to be used. Having your jupyter server run as a container is a must for every data scientist as it allows one to seamlessly move their lab, as it were, from one cloud to another. Being able to have multiple kernels in jupyter is likewise a must for every data scientist as well as it allows one to work on multiple projects with mutually exclusive package dependencies. Due to the way standard conda environments and their jupyter kernelspecs are installed, making the two play with each other is not straightforward. In this tutorial and the associated github repository I have explained how to make containerized jupyter installations that support multiple kernels.
[ { "code": null, "e": 585, "s": 172, "text": "Docker and Docker-Compose are great utilities that support the microservice paradigm by allowing efficient containerization. Within the python ecosystem the package manager Conda also allows some kind of containerization that is limited to python packages. Conda environments are especially handy for data scientists working in jupyter notebooks that have different (and mutually exclusive) package dependencies." }, { "code": null, "e": 975, "s": 585, "text": "However, due to the peculiar way in which conda environments are setup, getting them working out of the box in Docker, as it were, is not so straightforward. Furthermore, adding kernelspecs for these environments to jupyter is another very useful but complicated step. This article will clearly and concisely explain how to setup Dockerized containers with Jupyter having multiple kernels." }, { "code": null, "e": 1159, "s": 975, "text": "To gain from this article you should already know the basics of Docker, Conda and Jupyter. If you don’t and would like to there are excellent tutorials on all three on their websites." }, { "code": null, "e": 1422, "s": 1159, "text": "I like Docker in the context of data science and machine learning research as it is very easy for me to containerize my whole research setup and move it to the various cloud services that I use (my laptop, my desktop, GCP, a barebones cloud we maintain and AWS)." }, { "code": null, "e": 1673, "s": 1422, "text": "Requiring multiple conda environments and associated jupyter kernels is something one often needs in Data Science and Machine Learning. For instance when dealing with Python 2 and Python 3 code or when transitioning from Tensorflow 1 to Tensorflow 2." }, { "code": null, "e": 2033, "s": 1673, "text": "One such issue came up recently for me. I work with TensorFlow and PyTorch both for deeplearning and till now I had them both installed in the same conda environment in my docker image. However, turns out that installing tensorflow 2.x breaks tensorboard for pytorch and the “solution” seems to be to not install tensorflow in the same environment as pytorch." }, { "code": null, "e": 2148, "s": 2033, "text": "To reproduce it just try running the tutorial notebook mentioned in the image above after installing tensorflow 2." }, { "code": null, "e": 2205, "s": 2148, "text": "So, in this case the solution is either of the following" }, { "code": null, "e": 2352, "s": 2205, "text": "Two dockerized containers with one having tensorflow 2 and the other pytorch.One container with two environments that give two kernels in jupyter." }, { "code": null, "e": 2430, "s": 2352, "text": "Two dockerized containers with one having tensorflow 2 and the other pytorch." }, { "code": null, "e": 2500, "s": 2430, "text": "One container with two environments that give two kernels in jupyter." }, { "code": null, "e": 2704, "s": 2500, "text": "The second one seems more elegant. Nevertheless, the standard way of creating a conda environment and activating it requires an interactive sessions and that is not possible when building a docker image." }, { "code": null, "e": 3186, "s": 2704, "text": "In this article I quickly describe what needs to be done using a simple example and the actual code can be found in my repository. In fact my repository has the actual code that can be used to run the jupyter notebook mentioned above here but that has a lot of other steps that can distract away from the main topic of this article which is how to make Docker and Conda play well together. So I have also made another toy example here that just helps explain this particular point." }, { "code": null, "e": 3237, "s": 3186, "text": "The docker file contains the following main steps:" }, { "code": null, "e": 3255, "s": 3237, "text": "Start with Ubuntu" }, { "code": null, "e": 3286, "s": 3255, "text": "Download and install miniconda" }, { "code": null, "e": 3473, "s": 3286, "text": "RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shRUN bash Miniconda3-latest-Linux-x86_64.sh -b -p /minicondaENV PATH=$PATH:/miniconda/condabin:/miniconda/bin" }, { "code": null, "e": 3513, "s": 3473, "text": "Install jupyter in the base environment" }, { "code": null, "e": 3930, "s": 3513, "text": "Create two more environments and add them to jupyter kernel list. This is a non-trivial step as one has to run ipykernel install in the new environment. Usually one would do that by doing conda init and then activate the new environment but this requires starting a new bash shell which we cannot do here. This is thus handled in a different way by running commands in the appropriate shells in the following manner." }, { "code": null, "e": 4166, "s": 3930, "text": "RUN conda env create -f packages/environment_one.ymlSHELL [\"conda\",\"run\",\"-n\",\"one\",\"/bin/bash\",\"-c\"]RUN python -m ipykernel install --name kernel_one --display-name \"Display Name One\"RUN pip install -U -r packages/requirements_one.txt" }, { "code": null, "e": 4209, "s": 4166, "text": "Add a new user and switch to her directory" }, { "code": null, "e": 4503, "s": 4209, "text": "Perform conda init as well as make it so that by default a new bash session opens in a one of the newly created environments. This step is not necessary for the problem we described is worth noting in case we do want the shell to be conda friendly and launch into one of the extra environments" }, { "code": null, "e": 4584, "s": 4503, "text": "SHELL [\"/bin/bash\",\"-c\"]RUN conda initRUN echo 'conda activate one' >> ~/.bashrc" }, { "code": null, "e": 4813, "s": 4584, "text": "Expose the port on which jupyter notebook will listen and run it. Note that in this example I am running a notebook with no authentication which is only for illustrative purposes. You should always turn on proper authentication." }, { "code": null, "e": 4986, "s": 4813, "text": "EXPOSE 8888 ENTRYPOINT [\"jupyter\", \"notebook\", \"--no-browser\",\"--ip=0.0.0.0\",\"--NotebookApp.token=''\",\"--NotebookApp.password=''\"]" }, { "code": null, "e": 5543, "s": 4986, "text": "Finally I find it very useful to put all my microservices behind the reverse proxy traefik. This has the additional advantage of being able to turn on SSL on all services without individual configuration. In this toy example there is only one microservice but when we have many it is useful to turn them on with prefixes and here is why I used an entry point instead of command in the dockerfile above. I can now complete the command by asking jupyter to start the notebook server while listening on a different path where traefik will redirect the traffic" }, { "code": null, "e": 5607, "s": 5543, "text": "command: \"--NotebookApp.base_url='multiple_conda_environments'\"" }, { "code": null, "e": 5750, "s": 5607, "text": "Now the notebook can be accessed on https://myserver.com /multiple_conda_environment where you should replace myserver.com with your hostname." }, { "code": null, "e": 5876, "s": 5750, "text": "Now when you run try to create a new notebook you should see a choice between the standard python3 and two additional kernels" }, { "code": null, "e": 6100, "s": 5876, "text": "If you go to the actual repository with the full code to run both tensorflow and pytorch you will find that I appropriated the python3 kernel to convert it into a tensorflow kernel and have changed its name to reflect that." }, { "code": null, "e": 6222, "s": 6100, "text": "This is a better solution if you do not care about the extra default kernel floating around that is not going to be used." }, { "code": null, "e": 6389, "s": 6222, "text": "Having your jupyter server run as a container is a must for every data scientist as it allows one to seamlessly move their lab, as it were, from one cloud to another." }, { "code": null, "e": 6580, "s": 6389, "text": "Being able to have multiple kernels in jupyter is likewise a must for every data scientist as well as it allows one to work on multiple projects with mutually exclusive package dependencies." } ]
bin() in Python - GeeksforGeeks
17 Sep, 2021 Python bin() function returns the binary string of a given integer. Syntax: bin(a) Parameters : a : an integer to convert Return Value : A binary string of an integer or int object. Exceptions : Raises TypeError when a float value is sent in arguments. Python3 # Python code to demonstrate working of# bin() # declare variablenum = 100 # print binary numberprint(bin(num)) Output: 0b1100100 Python3 # Python code to demonstrate working of# bin() # function returning binary stringdef Binary(n): s = bin(n) # removing "0b" prefix s1 = s[2:] return s1 print("The binary representation of 100 (using bin()) is : ", end="")print(Binary(100)) Output: The binary representation of 100 (using bin()) is : 1100100 Here we send the object of the class to the bin methods, and we are using python special methods __index()__ method which always returns positive integer, and it can not be a rising error if the value is not an integer. Python3 # Python code to demonstrate working of# bin()class number: num = 100 def __index__(self): return(self.num) print(bin(number())) Output: 0b1100100 This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kumar_satyam base-conversion Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24678, "s": 24650, "text": "\n17 Sep, 2021" }, { "code": null, "e": 24746, "s": 24678, "text": "Python bin() function returns the binary string of a given integer." }, { "code": null, "e": 24762, "s": 24746, "text": "Syntax: bin(a)" }, { "code": null, "e": 24801, "s": 24762, "text": "Parameters : a : an integer to convert" }, { "code": null, "e": 24861, "s": 24801, "text": "Return Value : A binary string of an integer or int object." }, { "code": null, "e": 24932, "s": 24861, "text": "Exceptions : Raises TypeError when a float value is sent in arguments." }, { "code": null, "e": 24940, "s": 24932, "text": "Python3" }, { "code": "# Python code to demonstrate working of# bin() # declare variablenum = 100 # print binary numberprint(bin(num))", "e": 25052, "s": 24940, "text": null }, { "code": null, "e": 25060, "s": 25052, "text": "Output:" }, { "code": null, "e": 25070, "s": 25060, "text": "0b1100100" }, { "code": null, "e": 25078, "s": 25070, "text": "Python3" }, { "code": "# Python code to demonstrate working of# bin() # function returning binary stringdef Binary(n): s = bin(n) # removing \"0b\" prefix s1 = s[2:] return s1 print(\"The binary representation of 100 (using bin()) is : \", end=\"\")print(Binary(100))", "e": 25330, "s": 25078, "text": null }, { "code": null, "e": 25339, "s": 25330, "text": "Output: " }, { "code": null, "e": 25399, "s": 25339, "text": "The binary representation of 100 (using bin()) is : 1100100" }, { "code": null, "e": 25620, "s": 25399, "text": "Here we send the object of the class to the bin methods, and we are using python special methods __index()__ method which always returns positive integer, and it can not be a rising error if the value is not an integer. " }, { "code": null, "e": 25628, "s": 25620, "text": "Python3" }, { "code": "# Python code to demonstrate working of# bin()class number: num = 100 def __index__(self): return(self.num) print(bin(number()))", "e": 25771, "s": 25628, "text": null }, { "code": null, "e": 25779, "s": 25771, "text": "Output:" }, { "code": null, "e": 25789, "s": 25779, "text": "0b1100100" }, { "code": null, "e": 26086, "s": 25789, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26212, "s": 26086, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 26225, "s": 26212, "text": "kumar_satyam" }, { "code": null, "e": 26241, "s": 26225, "text": "base-conversion" }, { "code": null, "e": 26267, "s": 26241, "text": "Python-Built-in-functions" }, { "code": null, "e": 26274, "s": 26267, "text": "Python" }, { "code": null, "e": 26372, "s": 26274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26390, "s": 26372, "text": "Python Dictionary" }, { "code": null, "e": 26425, "s": 26390, "text": "Read a file line by line in Python" }, { "code": null, "e": 26447, "s": 26425, "text": "Enumerate() in Python" }, { "code": null, "e": 26479, "s": 26447, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26509, "s": 26479, "text": "Iterate over a list in Python" }, { "code": null, "e": 26551, "s": 26509, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26577, "s": 26551, "text": "Python String | replace()" }, { "code": null, "e": 26614, "s": 26577, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26657, "s": 26614, "text": "Python program to convert a list to string" } ]
K-Nearest Neighbours (kNN) Algorithm: Common Questions and Python Implementation | by Chingis Oinar | Towards Data Science
K-Nearest Neighbours is considered to be one of the most intuitive machine learning algorithms since it is simple to understand and explain. Additionally, it is quite convenient to demonstrate how everything goes visually. However, the kNN algorithm is still a common and very useful algorithm to use for a large variety of classification problems. If you are new to machine learning, make sure you test yourself on an understanding of this simple yet wonderful algorithm. There are a lot of useful sources on what it is and how it works, hence I want to go through 5 common or interesting questions you should know in my personal opinion. The k-NN algorithm does more computation on test time rather than train time. That is absolutely true. The idea of the kNN algorithm is to find a k-long list of samples that are close to a sample we want to classify. Therefore, the training phase is basically storing a training set, whereas while the prediction stage the algorithm looks for k-neighbours using that stored data. Why do you need to scale your data for the k-NN algorithm? Imagine a dataset having m number of “examples” and n number of “features”. There is one feature dimension having values exactly between 0 and 1. Meanwhile, there is also a feature dimension that varies from -99999 to 99999. Considering the formula of Euclidean Distance, this will affect the performance by giving higher weightage to variables having a higher magnitude. Read more: Why is scaling required in KNN and K-Means? The k-NN algorithm can be used for imputing the missing value of both categorical and continuous variables. That is true. k-NN can be used as one of many techniques when it comes to handling missing values. A new sample is imputed by determining the samples in the training set “nearest” to it and averages these nearby points to impute. A scikit learn library provides a quick and convenient way to use this technique. Note: NaNs are omitted while distances are calculated. Example: from sklearn.impute import KNNImputer# define imputerimputer = KNNImputer() #default k is 5=> n_neighbors=5# fit on the datasetimputer.fit(X)# transform the datasetXtrans = imputer.transform(X) Thus, missing values will be replaced by the mean value of its “neighbours”. Is Euclidean Distance always the case? Although Euclidean Distance is the most common method used and taught, it is not always the optimal decision. In fact, it is hard to come up with the right metric just by looking at data, so I would suggest trying a set of them. However, there are some special cases. For instance, hamming distance is used in case of a categorical variable. Read more: 3 text distances that every data scientist should know Why should we not use the KNN algorithm for large datasets? Here is an overview of the data flow that occurs in the KNN algorithm: Calculate the distances to all vectors in a training set and store themSort the calculated distancesStore the K nearest vectorsCalculate the most frequent class displayed by K nearest vectors Calculate the distances to all vectors in a training set and store them Sort the calculated distances Store the K nearest vectors Calculate the most frequent class displayed by K nearest vectors Imagine you have a very large dataset. Therefore, it is not only a bad decision to store a large amount of data but it is also computationally costly to keep calculating and sorting all the values. I will break down the implementation into the following stages: Calculate the distances to all vectors in a training set and store themSort the calculated distancesCalculate the most frequent class displayed by K nearest vectors and make a prediction Calculate the distances to all vectors in a training set and store them Sort the calculated distances Calculate the most frequent class displayed by K nearest vectors and make a prediction Calculate the distances to all vectors in a training set and store them It is important to note that there is a large variety of options to choose as a metric; however, I want to use Euclidean Distance as an example. It is the most common metric used to calculate distances among vectors since it is straightforward and easy to explain. The general formula is as follows: Euclidean Distance = sqrt(sum i to N (x1_i — x2_i)2) Thus, let’s summarize it with the following Python code. Note: Don’t forget to import sqrt() from “math” module. Sort the calculated distances Firstly, we need to calculate all the distances between a single test sample and all the samples in our training set. As distances are obtained, we should sort the list of distances and pick the “nearest” k vectors from our training set by looking at how far they are from a test sample. Calculate the most frequent class displayed by K nearest vectors and make a prediction Finally, in order to make a prediction, we should get our k “nearest” neighbours by calling our function I attached above. Thus, the only thing that is left is to count the number of occurrences of each label and pick the most frequent one. Let’s summarize everything by combining all the function into a separate class object. Here is a more generalized version of the code, please take time to look through it. Comparison Let’s compare our implementation with the one provided by scikit learn. I am going to use a simple toy dataset that contains two predictors, which are age and salary. Thus, we want to predict if a customer is willing to purchase our product. I am going to skip preprocessing since it is not what I want to focus on; however, I used a train-test split technique and applied a StandardScaler afterwards. Anyways, if you are interested, I will provide the source code on Github. Finally, I will define both models and fit our data. Please refer to the KNN implementation provided above. I am selecting 5 as our default k value. Note that for the latter model the default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. model=KNN(5) #our model model.fit(X_train,y_train)predictions=model.predict(X_test)#our model's predictionsfrom sklearn.neighbors import KNeighborsClassifierclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)#The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric.classifier.fit(X_train, y_train)y_pred = classifier.predict(X_test) Results The figure attached above shows that both models demonstrated identical performance. The accuracy turned out to be 0.93, which is a pretty good result. The figure attached below is a visualization of our test set results. I am providing a single figure since both models are identical. However, I personally suggest using implementations that are provided already since our implementation is simple and inefficient. Moreover, it is just more convenient not to keep writing the exact same code every time. To sum up, K-Nearest Neighbours is considered to be one of the most intuitive machine learning algorithms since it is simple to understand and explain. Additionally, it is quite convenient to demonstrate how everything goes visually. In this article we answered the following questions: the k-NN algorithm does more computation on test time rather than train time. Why do you need to scale your data for the k-NN algorithm? the k-NN algorithm can be used for imputing the missing value of both categorical and continuous variables. Is Euclidean Distance always the case? Why should we not use KNN algorithm for large datasets? Moreover, I provided a python implementation of the KNN algorithm in order to strengthen your understanding of what happens inside. The full implementation can be found on my Github.
[ { "code": null, "e": 811, "s": 171, "text": "K-Nearest Neighbours is considered to be one of the most intuitive machine learning algorithms since it is simple to understand and explain. Additionally, it is quite convenient to demonstrate how everything goes visually. However, the kNN algorithm is still a common and very useful algorithm to use for a large variety of classification problems. If you are new to machine learning, make sure you test yourself on an understanding of this simple yet wonderful algorithm. There are a lot of useful sources on what it is and how it works, hence I want to go through 5 common or interesting questions you should know in my personal opinion." }, { "code": null, "e": 889, "s": 811, "text": "The k-NN algorithm does more computation on test time rather than train time." }, { "code": null, "e": 1191, "s": 889, "text": "That is absolutely true. The idea of the kNN algorithm is to find a k-long list of samples that are close to a sample we want to classify. Therefore, the training phase is basically storing a training set, whereas while the prediction stage the algorithm looks for k-neighbours using that stored data." }, { "code": null, "e": 1250, "s": 1191, "text": "Why do you need to scale your data for the k-NN algorithm?" }, { "code": null, "e": 1622, "s": 1250, "text": "Imagine a dataset having m number of “examples” and n number of “features”. There is one feature dimension having values exactly between 0 and 1. Meanwhile, there is also a feature dimension that varies from -99999 to 99999. Considering the formula of Euclidean Distance, this will affect the performance by giving higher weightage to variables having a higher magnitude." }, { "code": null, "e": 1677, "s": 1622, "text": "Read more: Why is scaling required in KNN and K-Means?" }, { "code": null, "e": 1785, "s": 1677, "text": "The k-NN algorithm can be used for imputing the missing value of both categorical and continuous variables." }, { "code": null, "e": 2097, "s": 1785, "text": "That is true. k-NN can be used as one of many techniques when it comes to handling missing values. A new sample is imputed by determining the samples in the training set “nearest” to it and averages these nearby points to impute. A scikit learn library provides a quick and convenient way to use this technique." }, { "code": null, "e": 2152, "s": 2097, "text": "Note: NaNs are omitted while distances are calculated." }, { "code": null, "e": 2161, "s": 2152, "text": "Example:" }, { "code": null, "e": 2355, "s": 2161, "text": "from sklearn.impute import KNNImputer# define imputerimputer = KNNImputer() #default k is 5=> n_neighbors=5# fit on the datasetimputer.fit(X)# transform the datasetXtrans = imputer.transform(X)" }, { "code": null, "e": 2432, "s": 2355, "text": "Thus, missing values will be replaced by the mean value of its “neighbours”." }, { "code": null, "e": 2471, "s": 2432, "text": "Is Euclidean Distance always the case?" }, { "code": null, "e": 2813, "s": 2471, "text": "Although Euclidean Distance is the most common method used and taught, it is not always the optimal decision. In fact, it is hard to come up with the right metric just by looking at data, so I would suggest trying a set of them. However, there are some special cases. For instance, hamming distance is used in case of a categorical variable." }, { "code": null, "e": 2879, "s": 2813, "text": "Read more: 3 text distances that every data scientist should know" }, { "code": null, "e": 2939, "s": 2879, "text": "Why should we not use the KNN algorithm for large datasets?" }, { "code": null, "e": 3010, "s": 2939, "text": "Here is an overview of the data flow that occurs in the KNN algorithm:" }, { "code": null, "e": 3202, "s": 3010, "text": "Calculate the distances to all vectors in a training set and store themSort the calculated distancesStore the K nearest vectorsCalculate the most frequent class displayed by K nearest vectors" }, { "code": null, "e": 3274, "s": 3202, "text": "Calculate the distances to all vectors in a training set and store them" }, { "code": null, "e": 3304, "s": 3274, "text": "Sort the calculated distances" }, { "code": null, "e": 3332, "s": 3304, "text": "Store the K nearest vectors" }, { "code": null, "e": 3397, "s": 3332, "text": "Calculate the most frequent class displayed by K nearest vectors" }, { "code": null, "e": 3595, "s": 3397, "text": "Imagine you have a very large dataset. Therefore, it is not only a bad decision to store a large amount of data but it is also computationally costly to keep calculating and sorting all the values." }, { "code": null, "e": 3659, "s": 3595, "text": "I will break down the implementation into the following stages:" }, { "code": null, "e": 3846, "s": 3659, "text": "Calculate the distances to all vectors in a training set and store themSort the calculated distancesCalculate the most frequent class displayed by K nearest vectors and make a prediction" }, { "code": null, "e": 3918, "s": 3846, "text": "Calculate the distances to all vectors in a training set and store them" }, { "code": null, "e": 3948, "s": 3918, "text": "Sort the calculated distances" }, { "code": null, "e": 4035, "s": 3948, "text": "Calculate the most frequent class displayed by K nearest vectors and make a prediction" }, { "code": null, "e": 4107, "s": 4035, "text": "Calculate the distances to all vectors in a training set and store them" }, { "code": null, "e": 4407, "s": 4107, "text": "It is important to note that there is a large variety of options to choose as a metric; however, I want to use Euclidean Distance as an example. It is the most common metric used to calculate distances among vectors since it is straightforward and easy to explain. The general formula is as follows:" }, { "code": null, "e": 4460, "s": 4407, "text": "Euclidean Distance = sqrt(sum i to N (x1_i — x2_i)2)" }, { "code": null, "e": 4573, "s": 4460, "text": "Thus, let’s summarize it with the following Python code. Note: Don’t forget to import sqrt() from “math” module." }, { "code": null, "e": 4603, "s": 4573, "text": "Sort the calculated distances" }, { "code": null, "e": 4891, "s": 4603, "text": "Firstly, we need to calculate all the distances between a single test sample and all the samples in our training set. As distances are obtained, we should sort the list of distances and pick the “nearest” k vectors from our training set by looking at how far they are from a test sample." }, { "code": null, "e": 4978, "s": 4891, "text": "Calculate the most frequent class displayed by K nearest vectors and make a prediction" }, { "code": null, "e": 5219, "s": 4978, "text": "Finally, in order to make a prediction, we should get our k “nearest” neighbours by calling our function I attached above. Thus, the only thing that is left is to count the number of occurrences of each label and pick the most frequent one." }, { "code": null, "e": 5391, "s": 5219, "text": "Let’s summarize everything by combining all the function into a separate class object. Here is a more generalized version of the code, please take time to look through it." }, { "code": null, "e": 5402, "s": 5391, "text": "Comparison" }, { "code": null, "e": 5644, "s": 5402, "text": "Let’s compare our implementation with the one provided by scikit learn. I am going to use a simple toy dataset that contains two predictors, which are age and salary. Thus, we want to predict if a customer is willing to purchase our product." }, { "code": null, "e": 5878, "s": 5644, "text": "I am going to skip preprocessing since it is not what I want to focus on; however, I used a train-test split technique and applied a StandardScaler afterwards. Anyways, if you are interested, I will provide the source code on Github." }, { "code": null, "e": 6152, "s": 5878, "text": "Finally, I will define both models and fit our data. Please refer to the KNN implementation provided above. I am selecting 5 as our default k value. Note that for the latter model the default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric." }, { "code": null, "e": 6550, "s": 6152, "text": "model=KNN(5) #our model model.fit(X_train,y_train)predictions=model.predict(X_test)#our model's predictionsfrom sklearn.neighbors import KNeighborsClassifierclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)#The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric.classifier.fit(X_train, y_train)y_pred = classifier.predict(X_test)" }, { "code": null, "e": 6558, "s": 6550, "text": "Results" }, { "code": null, "e": 7063, "s": 6558, "text": "The figure attached above shows that both models demonstrated identical performance. The accuracy turned out to be 0.93, which is a pretty good result. The figure attached below is a visualization of our test set results. I am providing a single figure since both models are identical. However, I personally suggest using implementations that are provided already since our implementation is simple and inefficient. Moreover, it is just more convenient not to keep writing the exact same code every time." }, { "code": null, "e": 7350, "s": 7063, "text": "To sum up, K-Nearest Neighbours is considered to be one of the most intuitive machine learning algorithms since it is simple to understand and explain. Additionally, it is quite convenient to demonstrate how everything goes visually. In this article we answered the following questions:" }, { "code": null, "e": 7428, "s": 7350, "text": "the k-NN algorithm does more computation on test time rather than train time." }, { "code": null, "e": 7487, "s": 7428, "text": "Why do you need to scale your data for the k-NN algorithm?" }, { "code": null, "e": 7595, "s": 7487, "text": "the k-NN algorithm can be used for imputing the missing value of both categorical and continuous variables." }, { "code": null, "e": 7634, "s": 7595, "text": "Is Euclidean Distance always the case?" }, { "code": null, "e": 7690, "s": 7634, "text": "Why should we not use KNN algorithm for large datasets?" } ]
Best Practices for Airflow Developers | Towards Data Science
Apache Airflow is one of the most popular open-source data orchestration frameworks for building and scheduling batch-based pipelines. To master the art of ETL with Airflow, it is critical to learn how to efficiently develop data pipelines by properly utilizing built-in features, adopting DevOps strategies, and automating testing and monitoring. In this blog post, I will provide several tips and best practices for developing and monitoring data pipelines using Airflow. As always, I will explain the underlying mechanisms of Airflow to help you understand the “why” behind each tip. (New to Airflow? Read the beginner’s guide to Airflow first.) (Looking for more Airflow tips? Check out Apache Airflow Tips and Best Practices.) Macros Airflow has powerful built-in support for Jinja templating, which lets developers use many useful variables/macros, such as execution timestamp and task details, at runtime. An important use case of macros is to ensure your DAGs are idempotent, which I explain in detail in my previous blog post. Since macros allow users to retrieve runtime information at task run level, another great use case of macros is for job alerts, which I will demonstrate with examples in a later section. However, not all operator parameters are templated, so you need to make sure Jinja templating is enabled for the operators that you plan to pass macros to. To check which parameters in an operator take macros as arguments, look for the template_fields attribute in the operator source code. For example, as of today, the most recent version of PythonOperator has three templated parameters: ‘templates_dict’, ‘op_args’, and ‘op_kwargs’: template_fields = ('templates_dict', 'op_args', 'op_kwargs') In order to enable templating for more parameters, simply overwrite thetemplate_fields attribute. Since this attribute is an immutable tuple, make sure to include the original list of templated parameters when you overwrite it. DAG factory Even building the simplest DAG in Airflow still requires writing~30 lines of Python code, in addition to knowledge of Airflow basics. If a large group of non-engineer members in the data organization build and deploy pipelines daily (most of which are very simple workflows with minimal dependency between tasks), then these employees need to invest a lot of time learning to write low-level scripts using the apache-airflow library. In this case, creating a high-level wrapper on top of Airflow’s native Python library (aka a DAG factory) will allow them to build simple data pipelines using fewer lines of code and without having in-depth knowledge of Airflow, which in turn saves time and resources. As an example, below is a DAG factory class that returns a DAG that runs all SQL scripts in a folder at a given schedule: If someone with zero knowledge on Airflow wants to schedule a couple of SQL queries to run daily, now they only need to put those SQL files in a folder and write the 2-line code below: import DagFactorydag = DagFactory('jon_snow_sql_dag', 'Jon Snow', '2020-02-19', '@daily', __file__).sql_dag() The DagFactory here is a very straightforward implementation, but you can enrich it based on your organization’s use cases; for example, adding a data lineage and qualify check, or allowing custom task dependency. How does this work behind the scenes? Though the file that defines DagFactory is present in Airflow’s DAG folder, no actual DAG exists until a DagFactory instance is initialized with parameters in a DAG file. In the example above, only when dag is created in the global namespace, Airflow is able to pick it up, as it only recognizes DAG objects inglobals(). Automated Tests After workflow files are uploaded to Airflow’s DAG folder, the Airflow scheduler will try to quickly compile all the files and validate all DAG definitions, e.g. checking whether there are any loops in task dependencies. Therefore, even if your IDE does not report any compiling errors, Airflow might still reject your DAGs at runtime. To catch Airflow exceptions ahead of time before deployment, you need a pytest function to ensure all DAG files are valid: Option #1: Use importlib # DAG_FOLDER_PATH: the relative path to the DAG folder# DAG_FOLDER_NAME: the name of the DAG folderdef validate_dags_1(): for dag_file in DAG_FOLDER_PATH.iterdir(): if dag_file.is_file() and dag_file.name.endswith('.py'): import_path = f'{DAG_FOLDER_NAME}.{dag_file.name[:-3]}' importlib.import_module(import_path) Option #2: Use DagBag from airflow.models import DagBagdef validate_dags_2(): dagbag = DagBag() assert len(dagbag.import_errors) == 0, f'DAG failures: {dagbag.import_errors}' Continuous Deployment (CD) An important but easy way to boost your team’s Airflow development efficiency is by adopting Continuous Deployment (CD) in your engineering workflow, which means whenever a set of changes is committed to the Airflow repository and passes automated tests (if any), these changes will automatically be deployed to Airflow’s DAG folder. There are a lot of DevOps automation tools that can help you achieve this easily: Jenkins Drone GitHub Actions Real-time failure alerts If there are tons of Airflow DAGs running at high frequency on your Airflow cluster, users would love to get notified whenever a task fails rather than manually checking task status. Luckily, Airflow supports a handy parameter: on_failure_callback, which will trigger a user-provided callback function with a context dictionary full of task run information. For example, below is a callback function that sends a detailed Slack alert upon task failure: To set up the failure alert for a DAG, set callback function in default_args: default_args = { 'owner': 'Xinran Waibel', 'start_date': datetime.datetime(2020, 2, 20), 'on_failure_callback': slack_failure_msg} (TL;DR) Here is a digest of key takeaways from this blog post: Use macros to build idempotent DAGs and provide relevant error information in job alerts. Remember you can use thetemplate_fields attribute to enable templating for any operator parameters. Create a DAG factory to allow users to create DAGs with efficiency. Test DAG definitions using importlib or DagBag so that you can deploy workflows with confidence later. Implement CD for Airflow repository using automation tools like Jenkins. Make good use of on_failure_callback to send real-time failure alerts. Happy learning and see you next time! Want to learn more about Data Engineering? Check out my Data Engineering 101 column on Towards Data Science:
[ { "code": null, "e": 759, "s": 172, "text": "Apache Airflow is one of the most popular open-source data orchestration frameworks for building and scheduling batch-based pipelines. To master the art of ETL with Airflow, it is critical to learn how to efficiently develop data pipelines by properly utilizing built-in features, adopting DevOps strategies, and automating testing and monitoring. In this blog post, I will provide several tips and best practices for developing and monitoring data pipelines using Airflow. As always, I will explain the underlying mechanisms of Airflow to help you understand the “why” behind each tip." }, { "code": null, "e": 821, "s": 759, "text": "(New to Airflow? Read the beginner’s guide to Airflow first.)" }, { "code": null, "e": 904, "s": 821, "text": "(Looking for more Airflow tips? Check out Apache Airflow Tips and Best Practices.)" }, { "code": null, "e": 911, "s": 904, "text": "Macros" }, { "code": null, "e": 1395, "s": 911, "text": "Airflow has powerful built-in support for Jinja templating, which lets developers use many useful variables/macros, such as execution timestamp and task details, at runtime. An important use case of macros is to ensure your DAGs are idempotent, which I explain in detail in my previous blog post. Since macros allow users to retrieve runtime information at task run level, another great use case of macros is for job alerts, which I will demonstrate with examples in a later section." }, { "code": null, "e": 1832, "s": 1395, "text": "However, not all operator parameters are templated, so you need to make sure Jinja templating is enabled for the operators that you plan to pass macros to. To check which parameters in an operator take macros as arguments, look for the template_fields attribute in the operator source code. For example, as of today, the most recent version of PythonOperator has three templated parameters: ‘templates_dict’, ‘op_args’, and ‘op_kwargs’:" }, { "code": null, "e": 1893, "s": 1832, "text": "template_fields = ('templates_dict', 'op_args', 'op_kwargs')" }, { "code": null, "e": 2121, "s": 1893, "text": "In order to enable templating for more parameters, simply overwrite thetemplate_fields attribute. Since this attribute is an immutable tuple, make sure to include the original list of templated parameters when you overwrite it." }, { "code": null, "e": 2133, "s": 2121, "text": "DAG factory" }, { "code": null, "e": 2836, "s": 2133, "text": "Even building the simplest DAG in Airflow still requires writing~30 lines of Python code, in addition to knowledge of Airflow basics. If a large group of non-engineer members in the data organization build and deploy pipelines daily (most of which are very simple workflows with minimal dependency between tasks), then these employees need to invest a lot of time learning to write low-level scripts using the apache-airflow library. In this case, creating a high-level wrapper on top of Airflow’s native Python library (aka a DAG factory) will allow them to build simple data pipelines using fewer lines of code and without having in-depth knowledge of Airflow, which in turn saves time and resources." }, { "code": null, "e": 2958, "s": 2836, "text": "As an example, below is a DAG factory class that returns a DAG that runs all SQL scripts in a folder at a given schedule:" }, { "code": null, "e": 3143, "s": 2958, "text": "If someone with zero knowledge on Airflow wants to schedule a couple of SQL queries to run daily, now they only need to put those SQL files in a folder and write the 2-line code below:" }, { "code": null, "e": 3253, "s": 3143, "text": "import DagFactorydag = DagFactory('jon_snow_sql_dag', 'Jon Snow', '2020-02-19', '@daily', __file__).sql_dag()" }, { "code": null, "e": 3467, "s": 3253, "text": "The DagFactory here is a very straightforward implementation, but you can enrich it based on your organization’s use cases; for example, adding a data lineage and qualify check, or allowing custom task dependency." }, { "code": null, "e": 3826, "s": 3467, "text": "How does this work behind the scenes? Though the file that defines DagFactory is present in Airflow’s DAG folder, no actual DAG exists until a DagFactory instance is initialized with parameters in a DAG file. In the example above, only when dag is created in the global namespace, Airflow is able to pick it up, as it only recognizes DAG objects inglobals()." }, { "code": null, "e": 3842, "s": 3826, "text": "Automated Tests" }, { "code": null, "e": 4301, "s": 3842, "text": "After workflow files are uploaded to Airflow’s DAG folder, the Airflow scheduler will try to quickly compile all the files and validate all DAG definitions, e.g. checking whether there are any loops in task dependencies. Therefore, even if your IDE does not report any compiling errors, Airflow might still reject your DAGs at runtime. To catch Airflow exceptions ahead of time before deployment, you need a pytest function to ensure all DAG files are valid:" }, { "code": null, "e": 4326, "s": 4301, "text": "Option #1: Use importlib" }, { "code": null, "e": 4678, "s": 4326, "text": "# DAG_FOLDER_PATH: the relative path to the DAG folder# DAG_FOLDER_NAME: the name of the DAG folderdef validate_dags_1(): for dag_file in DAG_FOLDER_PATH.iterdir(): if dag_file.is_file() and dag_file.name.endswith('.py'): import_path = f'{DAG_FOLDER_NAME}.{dag_file.name[:-3]}' importlib.import_module(import_path)" }, { "code": null, "e": 4700, "s": 4678, "text": "Option #2: Use DagBag" }, { "code": null, "e": 4855, "s": 4700, "text": "from airflow.models import DagBagdef validate_dags_2(): dagbag = DagBag() assert len(dagbag.import_errors) == 0, f'DAG failures: {dagbag.import_errors}'" }, { "code": null, "e": 4882, "s": 4855, "text": "Continuous Deployment (CD)" }, { "code": null, "e": 5298, "s": 4882, "text": "An important but easy way to boost your team’s Airflow development efficiency is by adopting Continuous Deployment (CD) in your engineering workflow, which means whenever a set of changes is committed to the Airflow repository and passes automated tests (if any), these changes will automatically be deployed to Airflow’s DAG folder. There are a lot of DevOps automation tools that can help you achieve this easily:" }, { "code": null, "e": 5306, "s": 5298, "text": "Jenkins" }, { "code": null, "e": 5312, "s": 5306, "text": "Drone" }, { "code": null, "e": 5327, "s": 5312, "text": "GitHub Actions" }, { "code": null, "e": 5352, "s": 5327, "text": "Real-time failure alerts" }, { "code": null, "e": 5805, "s": 5352, "text": "If there are tons of Airflow DAGs running at high frequency on your Airflow cluster, users would love to get notified whenever a task fails rather than manually checking task status. Luckily, Airflow supports a handy parameter: on_failure_callback, which will trigger a user-provided callback function with a context dictionary full of task run information. For example, below is a callback function that sends a detailed Slack alert upon task failure:" }, { "code": null, "e": 5883, "s": 5805, "text": "To set up the failure alert for a DAG, set callback function in default_args:" }, { "code": null, "e": 6023, "s": 5883, "text": "default_args = { 'owner': 'Xinran Waibel', 'start_date': datetime.datetime(2020, 2, 20), 'on_failure_callback': slack_failure_msg}" }, { "code": null, "e": 6086, "s": 6023, "text": "(TL;DR) Here is a digest of key takeaways from this blog post:" }, { "code": null, "e": 6276, "s": 6086, "text": "Use macros to build idempotent DAGs and provide relevant error information in job alerts. Remember you can use thetemplate_fields attribute to enable templating for any operator parameters." }, { "code": null, "e": 6344, "s": 6276, "text": "Create a DAG factory to allow users to create DAGs with efficiency." }, { "code": null, "e": 6447, "s": 6344, "text": "Test DAG definitions using importlib or DagBag so that you can deploy workflows with confidence later." }, { "code": null, "e": 6520, "s": 6447, "text": "Implement CD for Airflow repository using automation tools like Jenkins." }, { "code": null, "e": 6591, "s": 6520, "text": "Make good use of on_failure_callback to send real-time failure alerts." }, { "code": null, "e": 6629, "s": 6591, "text": "Happy learning and see you next time!" } ]
Minimize Rounding Error to Meet Target in C++
Suppose we have an array of prices P [p1,p2...,pn] and a target value, we have to round each price Pi to Roundi(Pi) so that the rounded array [Round1(P1),Round2(P2)...,Roundn(Pn)] sums to the given target value. Here each operation Roundi(pi) could be either Floor(Pi) or Ceil(Pi). We have to return the string "-1" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which will be (as a string with three places after the decimal) defined as − ∑i−1n|Roundi(????)−???? So if the input is like [“0.700”, “2.800”, “4.900”], and the target is 8. Use floor or ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0 To solve this, we will follow these steps − ret := 0 ret := 0 make one priority queue pq for (double and array) type complex data make one priority queue pq for (double and array) type complex data for i in range 0 to size of pricesx := double value of prices[i]low := floor of xhigh := ceiling of xif low is not highdiff := (high - x) – (x - low)insert diff into pqtarget := target – lowret := ret + (x - low) for i in range 0 to size of prices x := double value of prices[i] x := double value of prices[i] low := floor of x low := floor of x high := ceiling of x high := ceiling of x if low is not highdiff := (high - x) – (x - low)insert diff into pq if low is not high diff := (high - x) – (x - low) diff := (high - x) – (x - low) insert diff into pq insert diff into pq target := target – low target := target – low ret := ret + (x - low) ret := ret + (x - low) if target > size of pq or target < 0, then return “-1” if target > size of pq or target < 0, then return “-1” while target is not 0ret := ret + top of pq, delete from pqddecrease target by 1 while target is not 0 ret := ret + top of pq, delete from pq ret := ret + top of pq, delete from pq d decrease target by 1 decrease target by 1 s := ret as string s := ret as string return substring s by taking number up to three decimal places return substring s by taking number up to three decimal places Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; struct Comparator{ bool operator()(double a, double b) { return !(a < b); } }; class Solution { public: string minimizeError(vector<string>& prices, int target) { double ret = 0; priority_queue < double, vector < double >, Comparator > pq; for(int i = 0; i < prices.size(); i++){ double x = stod(prices[i]); double low = floor(x); double high = ceil(x); if(low != high){ double diff = ((high - x) - (x - low)); pq.push(diff); } target -= low; ret += (x - low); } if(target > pq.size() || target < 0) return "-1"; while(target--){ ret += pq.top(); pq.pop(); } string s = to_string (ret); return s.substr (0, s.find_first_of ('.', 0) + 4); } }; main(){ vector<string> v = {"0.700","2.800","4.900"}; Solution ob; cout << (ob.minimizeError(v, 8)); } ["0.700","2.800","4.900"] 8 "1.000"
[ { "code": null, "e": 1344, "s": 1062, "text": "Suppose we have an array of prices P [p1,p2...,pn] and a target value, we have to round each price Pi to Roundi(Pi) so that the rounded array [Round1(P1),Round2(P2)...,Roundn(Pn)] sums to the given target value. Here each operation Roundi(pi) could be either Floor(Pi) or Ceil(Pi)." }, { "code": null, "e": 1555, "s": 1344, "text": "We have to return the string \"-1\" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which will be (as a string with three places after the decimal) defined as −" }, { "code": null, "e": 1579, "s": 1555, "text": "∑i−1n|Roundi(????)−????" }, { "code": null, "e": 1747, "s": 1579, "text": "So if the input is like [“0.700”, “2.800”, “4.900”], and the target is 8. Use floor or ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0" }, { "code": null, "e": 1791, "s": 1747, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1800, "s": 1791, "text": "ret := 0" }, { "code": null, "e": 1809, "s": 1800, "text": "ret := 0" }, { "code": null, "e": 1877, "s": 1809, "text": "make one priority queue pq for (double and array) type complex data" }, { "code": null, "e": 1945, "s": 1877, "text": "make one priority queue pq for (double and array) type complex data" }, { "code": null, "e": 2158, "s": 1945, "text": "for i in range 0 to size of pricesx := double value of prices[i]low := floor of xhigh := ceiling of xif low is not highdiff := (high - x) – (x - low)insert diff into pqtarget := target – lowret := ret + (x - low)" }, { "code": null, "e": 2193, "s": 2158, "text": "for i in range 0 to size of prices" }, { "code": null, "e": 2224, "s": 2193, "text": "x := double value of prices[i]" }, { "code": null, "e": 2255, "s": 2224, "text": "x := double value of prices[i]" }, { "code": null, "e": 2273, "s": 2255, "text": "low := floor of x" }, { "code": null, "e": 2291, "s": 2273, "text": "low := floor of x" }, { "code": null, "e": 2312, "s": 2291, "text": "high := ceiling of x" }, { "code": null, "e": 2333, "s": 2312, "text": "high := ceiling of x" }, { "code": null, "e": 2401, "s": 2333, "text": "if low is not highdiff := (high - x) – (x - low)insert diff into pq" }, { "code": null, "e": 2420, "s": 2401, "text": "if low is not high" }, { "code": null, "e": 2451, "s": 2420, "text": "diff := (high - x) – (x - low)" }, { "code": null, "e": 2482, "s": 2451, "text": "diff := (high - x) – (x - low)" }, { "code": null, "e": 2502, "s": 2482, "text": "insert diff into pq" }, { "code": null, "e": 2522, "s": 2502, "text": "insert diff into pq" }, { "code": null, "e": 2545, "s": 2522, "text": "target := target – low" }, { "code": null, "e": 2568, "s": 2545, "text": "target := target – low" }, { "code": null, "e": 2591, "s": 2568, "text": "ret := ret + (x - low)" }, { "code": null, "e": 2614, "s": 2591, "text": "ret := ret + (x - low)" }, { "code": null, "e": 2669, "s": 2614, "text": "if target > size of pq or target < 0, then return “-1”" }, { "code": null, "e": 2724, "s": 2669, "text": "if target > size of pq or target < 0, then return “-1”" }, { "code": null, "e": 2805, "s": 2724, "text": "while target is not 0ret := ret + top of pq, delete from pqddecrease target by 1" }, { "code": null, "e": 2827, "s": 2805, "text": "while target is not 0" }, { "code": null, "e": 2866, "s": 2827, "text": "ret := ret + top of pq, delete from pq" }, { "code": null, "e": 2905, "s": 2866, "text": "ret := ret + top of pq, delete from pq" }, { "code": null, "e": 2907, "s": 2905, "text": "d" }, { "code": null, "e": 2928, "s": 2907, "text": "decrease target by 1" }, { "code": null, "e": 2949, "s": 2928, "text": "decrease target by 1" }, { "code": null, "e": 2968, "s": 2949, "text": "s := ret as string" }, { "code": null, "e": 2987, "s": 2968, "text": "s := ret as string" }, { "code": null, "e": 3050, "s": 2987, "text": "return substring s by taking number up to three decimal places" }, { "code": null, "e": 3113, "s": 3050, "text": "return substring s by taking number up to three decimal places" }, { "code": null, "e": 3183, "s": 3113, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3194, "s": 3183, "text": " Live Demo" }, { "code": null, "e": 4175, "s": 3194, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Comparator{\n bool operator()(double a, double b) {\n return !(a < b);\n }\n};\nclass Solution {\n public:\n string minimizeError(vector<string>& prices, int target) {\n double ret = 0;\n priority_queue < double, vector < double >, Comparator > pq;\n for(int i = 0; i < prices.size(); i++){\n double x = stod(prices[i]);\n double low = floor(x);\n double high = ceil(x);\n if(low != high){\n double diff = ((high - x) - (x - low));\n pq.push(diff);\n }\n target -= low;\n ret += (x - low);\n }\n if(target > pq.size() || target < 0) return \"-1\";\n while(target--){\n ret += pq.top();\n pq.pop();\n }\n string s = to_string (ret);\n return s.substr (0, s.find_first_of ('.', 0) + 4);\n }\n};\nmain(){\n vector<string> v = {\"0.700\",\"2.800\",\"4.900\"};\n Solution ob;\n cout << (ob.minimizeError(v, 8));\n}" }, { "code": null, "e": 4203, "s": 4175, "text": "[\"0.700\",\"2.800\",\"4.900\"]\n8" }, { "code": null, "e": 4211, "s": 4203, "text": "\"1.000\"" } ]
Node.js shift() function - GeeksforGeeks
14 Oct, 2021 shift() is an array function from Node.js that is used to delete element from the front of an array. Syntax: array_name.shift() Parameter: This function does not takes any parameter. Return type: The function returns the array after deleting the element. The program below demonstrates the working of the function: Program 1: function shiftDemo(){ arr.shift(); console.log(arr);}var arr=[17, 55, 87, 49, 78];shiftDemo(); Output: [ 55, 87, 49, 78 ] Program 2: function shiftDemo(){ arr.shift(); console.log(arr);}var arr=['a', 'b'];shiftDemo(); Output: [ 'b' ] Program 3: let Lang = ["Python", "C", "Java", "JavaScript"];while ((i = Lang.shift()) !== undefined) { Lang.shift();}console.log(Lang); Output: [] NodeJS-function Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24531, "s": 24503, "text": "\n14 Oct, 2021" }, { "code": null, "e": 24632, "s": 24531, "text": "shift() is an array function from Node.js that is used to delete element from the front of an array." }, { "code": null, "e": 24640, "s": 24632, "text": "Syntax:" }, { "code": null, "e": 24659, "s": 24640, "text": "array_name.shift()" }, { "code": null, "e": 24714, "s": 24659, "text": "Parameter: This function does not takes any parameter." }, { "code": null, "e": 24786, "s": 24714, "text": "Return type: The function returns the array after deleting the element." }, { "code": null, "e": 24846, "s": 24786, "text": "The program below demonstrates the working of the function:" }, { "code": null, "e": 24857, "s": 24846, "text": "Program 1:" }, { "code": "function shiftDemo(){ arr.shift(); console.log(arr);}var arr=[17, 55, 87, 49, 78];shiftDemo();", "e": 24954, "s": 24857, "text": null }, { "code": null, "e": 24962, "s": 24954, "text": "Output:" }, { "code": null, "e": 24981, "s": 24962, "text": "[ 55, 87, 49, 78 ]" }, { "code": null, "e": 24992, "s": 24981, "text": "Program 2:" }, { "code": "function shiftDemo(){ arr.shift(); console.log(arr);}var arr=['a', 'b'];shiftDemo();", "e": 25079, "s": 24992, "text": null }, { "code": null, "e": 25087, "s": 25079, "text": "Output:" }, { "code": null, "e": 25095, "s": 25087, "text": "[ 'b' ]" }, { "code": null, "e": 25106, "s": 25095, "text": "Program 3:" }, { "code": "let Lang = [\"Python\", \"C\", \"Java\", \"JavaScript\"];while ((i = Lang.shift()) !== undefined) { Lang.shift();}console.log(Lang);", "e": 25234, "s": 25106, "text": null }, { "code": null, "e": 25242, "s": 25234, "text": "Output:" }, { "code": null, "e": 25245, "s": 25242, "text": "[]" }, { "code": null, "e": 25261, "s": 25245, "text": "NodeJS-function" }, { "code": null, "e": 25269, "s": 25261, "text": "Node.js" }, { "code": null, "e": 25286, "s": 25269, "text": "Web Technologies" }, { "code": null, "e": 25384, "s": 25286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25393, "s": 25384, "text": "Comments" }, { "code": null, "e": 25406, "s": 25393, "text": "Old Comments" }, { "code": null, "e": 25463, "s": 25406, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 25502, "s": 25463, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 25529, "s": 25502, "text": "Mongoose Populate() Method" }, { "code": null, "e": 25560, "s": 25529, "text": "Express.js req.params Property" }, { "code": null, "e": 25585, "s": 25560, "text": "Mongoose find() Function" }, { "code": null, "e": 25641, "s": 25585, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 25703, "s": 25641, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25746, "s": 25703, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 25796, "s": 25746, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Operator Precedence and Associativity in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. #include <stdio.h> main() { int a = 20; int b = 10; int c = 15; int d = 5; int e; e = (a + b) * c / d; // ( 30 * 15 ) / 5 printf("Value of (a + b) * c / d is : %d\n", e ); e = ((a + b) * c) / d; // (30 * 15 ) / 5 printf("Value of ((a + b) * c) / d is : %d\n" , e ); e = (a + b) * (c / d); // (30) * (15/5) printf("Value of (a + b) * (c / d) is : %d\n", e ); e = a + (b * c) / d; // 20 + (150/5) printf("Value of a + (b * c) / d is : %d\n" , e ); return 0; } Value of (a + b) * c / d is : 90 Value of ((a + b) * c) / d is : 90 Value of (a + b) * (c / d) is : 90 Value of a + (b * c) / d is : 50
[ { "code": null, "e": 1323, "s": 1062, "text": "Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator." }, { "code": null, "e": 1492, "s": 1323, "text": "For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7." }, { "code": null, "e": 1687, "s": 1492, "text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first." }, { "code": null, "e": 2187, "s": 1687, "text": "#include <stdio.h>\nmain() {\n int a = 20;\n int b = 10;\n int c = 15;\n int d = 5;\n int e;\n e = (a + b) * c / d; // ( 30 * 15 ) / 5\n printf(\"Value of (a + b) * c / d is : %d\\n\", e );\n e = ((a + b) * c) / d; // (30 * 15 ) / 5\n printf(\"Value of ((a + b) * c) / d is : %d\\n\" , e );\n e = (a + b) * (c / d); // (30) * (15/5)\n printf(\"Value of (a + b) * (c / d) is : %d\\n\", e );\n e = a + (b * c) / d; // 20 + (150/5)\n printf(\"Value of a + (b * c) / d is : %d\\n\" , e );\n return 0;\n}" }, { "code": null, "e": 2323, "s": 2187, "text": "Value of (a + b) * c / d is : 90\nValue of ((a + b) * c) / d is : 90\nValue of (a + b) * (c / d) is : 90\nValue of a + (b * c) / d is : 50" } ]
Apache Presto - MySQL Connector
The MySQL connector is used to query an external MySQL database. MySQL server installation. Hopefully you have installed mysql server on your machine. To enable mysql properties on Presto server, you must create a file “mysql.properties” in “etc/catalog” directory. Issue the following command to create a mysql.properties file. $ cd etc $ cd catalog $ vi mysql.properties connector.name = mysql connection-url = jdbc:mysql://localhost:3306 connection-user = root connection-password = pwd Save the file and quit the terminal. In the above file, you must enter your mysql password in connection-password field. Open MySQL server and create a database using the following command. create database tutorials Now you have created “tutorials” database in the server. To enable database type, use the command “use tutorials” in the query window. Let’s create a simple table on “tutorials” database. create table author(auth_id int not null, auth_name varchar(50),topic varchar(100)) After creating a table, insert three records using the following query. insert into author values(1,'Doug Cutting','Hadoop') insert into author values(2,’James Gosling','java') insert into author values(3,'Dennis Ritchie’,'C') To retrieve all the records, type the following query. select * from author auth_id auth_name topic 1 Doug Cutting Hadoop 2 James Gosling java 3 Dennis Ritchie C As of now, you have queried data using MySQL server. Let’s connect Mysql storage plugin to Presto server. Type the following command to connect MySql plugin on Presto CLI. ./presto --server localhost:8080 --catalog mysql --schema tutorials You will receive the following response. presto:tutorials> Here “tutorials” refers to schema in mysql server. To list out all the schemas in mysql, type the following query in Presto server. presto:tutorials> show schemas from mysql; Schema -------------------- information_schema performance_schema sys tutorials From this result, we can conclude the first three schemas as predefined and the last one as created by yourself. Following query lists out all the tables in tutorials schema. presto:tutorials> show tables from mysql.tutorials; Table -------- author We have created only one table in this schema. If you have created multiple tables, it will list out all the tables. To describe the table fields, type the following query. presto:tutorials> describe mysql.tutorials.author; Column | Type | Comment -----------+--------------+--------- auth_id | integer | auth_name | varchar(50) | topic | varchar(100) | presto:tutorials> show columns from mysql.tutorials.author; Column | Type | Comment -----------+--------------+--------- auth_id | integer | auth_name | varchar(50) | topic | varchar(100) | To fetch all the records from mysql table, issue the following query. presto:tutorials> select * from mysql.tutorials.author; auth_id | auth_name | topic ---------+----------------+-------- 1 | Doug Cutting | Hadoop 2 | James Gosling | java 3 | Dennis Ritchie | C From this result, you can retrieve mysql server records in Presto. Mysql connector doesn’t support create table query but you can create a table using as command. presto:tutorials> create table mysql.tutorials.sample as select * from mysql.tutorials.author; CREATE TABLE: 3 rows You can’t insert rows directly because this connector has some limitations. It cannot support the following queries − create insert update delete drop To view the records in the newly created table, type the following query. presto:tutorials> select * from mysql.tutorials.sample; auth_id | auth_name | topic ---------+----------------+-------- 1 | Doug Cutting | Hadoop 2 | James Gosling | java 3 | Dennis Ritchie | C 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2071, "s": 2006, "text": "The MySQL connector is used to query an external MySQL database." }, { "code": null, "e": 2098, "s": 2071, "text": "MySQL server installation." }, { "code": null, "e": 2335, "s": 2098, "text": "Hopefully you have installed mysql server on your machine. To enable mysql properties on Presto server, you must create a file “mysql.properties” in “etc/catalog” directory. Issue the following command to create a mysql.properties file." }, { "code": null, "e": 2507, "s": 2335, "text": "$ cd etc \n$ cd catalog \n$ vi mysql.properties \n\nconnector.name = mysql \nconnection-url = jdbc:mysql://localhost:3306 \nconnection-user = root \nconnection-password = pwd \n" }, { "code": null, "e": 2628, "s": 2507, "text": "Save the file and quit the terminal. In the above file, you must enter your mysql password in connection-password field." }, { "code": null, "e": 2697, "s": 2628, "text": "Open MySQL server and create a database using the following command." }, { "code": null, "e": 2723, "s": 2697, "text": "create database tutorials" }, { "code": null, "e": 2858, "s": 2723, "text": "Now you have created “tutorials” database in the server. To enable database type, use the command “use tutorials” in the query window." }, { "code": null, "e": 2911, "s": 2858, "text": "Let’s create a simple table on “tutorials” database." }, { "code": null, "e": 2995, "s": 2911, "text": "create table author(auth_id int not null, auth_name varchar(50),topic varchar(100))" }, { "code": null, "e": 3067, "s": 2995, "text": "After creating a table, insert three records using the following query." }, { "code": null, "e": 3224, "s": 3067, "text": "insert into author values(1,'Doug Cutting','Hadoop') \ninsert into author values(2,’James Gosling','java') \ninsert into author values(3,'Dennis Ritchie’,'C')" }, { "code": null, "e": 3279, "s": 3224, "text": "To retrieve all the records, type the following query." }, { "code": null, "e": 3300, "s": 3279, "text": "select * from author" }, { "code": null, "e": 3432, "s": 3300, "text": "auth_id auth_name topic \n1 Doug Cutting Hadoop \n2 James Gosling java \n3 Dennis Ritchie C \n" }, { "code": null, "e": 3538, "s": 3432, "text": "As of now, you have queried data using MySQL server. Let’s connect Mysql storage plugin to Presto server." }, { "code": null, "e": 3604, "s": 3538, "text": "Type the following command to connect MySql plugin on Presto CLI." }, { "code": null, "e": 3674, "s": 3604, "text": "./presto --server localhost:8080 --catalog mysql --schema tutorials \n" }, { "code": null, "e": 3715, "s": 3674, "text": "You will receive the following response." }, { "code": null, "e": 3735, "s": 3715, "text": "presto:tutorials> \n" }, { "code": null, "e": 3786, "s": 3735, "text": "Here “tutorials” refers to schema in mysql server." }, { "code": null, "e": 3867, "s": 3786, "text": "To list out all the schemas in mysql, type the following query in Presto server." }, { "code": null, "e": 3910, "s": 3867, "text": "presto:tutorials> show schemas from mysql;" }, { "code": null, "e": 4006, "s": 3910, "text": " Schema \n-------------------- \n information_schema \n performance_schema \n sys \n tutorials\n" }, { "code": null, "e": 4119, "s": 4006, "text": "From this result, we can conclude the first three schemas as predefined and the last one as created by yourself." }, { "code": null, "e": 4181, "s": 4119, "text": "Following query lists out all the tables in tutorials schema." }, { "code": null, "e": 4234, "s": 4181, "text": "presto:tutorials> show tables from mysql.tutorials; " }, { "code": null, "e": 4262, "s": 4234, "text": " Table \n-------- \n author\n" }, { "code": null, "e": 4379, "s": 4262, "text": "We have created only one table in this schema. If you have created multiple tables, it will list out all the tables." }, { "code": null, "e": 4435, "s": 4379, "text": "To describe the table fields, type the following query." }, { "code": null, "e": 4486, "s": 4435, "text": "presto:tutorials> describe mysql.tutorials.author;" }, { "code": null, "e": 4648, "s": 4486, "text": " Column | Type | Comment \n-----------+--------------+--------- \n auth_id | integer | \n auth_name | varchar(50) | \n topic | varchar(100) |\n" }, { "code": null, "e": 4709, "s": 4648, "text": "presto:tutorials> show columns from mysql.tutorials.author; " }, { "code": null, "e": 4871, "s": 4709, "text": " Column | Type | Comment \n-----------+--------------+--------- \n auth_id | integer | \n auth_name | varchar(50) | \n topic | varchar(100) |\n" }, { "code": null, "e": 4941, "s": 4871, "text": "To fetch all the records from mysql table, issue the following query." }, { "code": null, "e": 4998, "s": 4941, "text": "presto:tutorials> select * from mysql.tutorials.author; " }, { "code": null, "e": 5171, "s": 4998, "text": "auth_id | auth_name | topic \n---------+----------------+-------- \n 1 | Doug Cutting | Hadoop \n 2 | James Gosling | java \n 3 | Dennis Ritchie | C\n" }, { "code": null, "e": 5238, "s": 5171, "text": "From this result, you can retrieve mysql server records in Presto." }, { "code": null, "e": 5334, "s": 5238, "text": "Mysql connector doesn’t support create table query but you can create a table using as command." }, { "code": null, "e": 5431, "s": 5334, "text": "presto:tutorials> create table mysql.tutorials.sample as \nselect * from mysql.tutorials.author; " }, { "code": null, "e": 5453, "s": 5431, "text": "CREATE TABLE: 3 rows\n" }, { "code": null, "e": 5571, "s": 5453, "text": "You can’t insert rows directly because this connector has some limitations. It cannot support the following queries −" }, { "code": null, "e": 5578, "s": 5571, "text": "create" }, { "code": null, "e": 5585, "s": 5578, "text": "insert" }, { "code": null, "e": 5592, "s": 5585, "text": "update" }, { "code": null, "e": 5599, "s": 5592, "text": "delete" }, { "code": null, "e": 5604, "s": 5599, "text": "drop" }, { "code": null, "e": 5678, "s": 5604, "text": "To view the records in the newly created table, type the following query." }, { "code": null, "e": 5735, "s": 5678, "text": "presto:tutorials> select * from mysql.tutorials.sample; " }, { "code": null, "e": 5908, "s": 5735, "text": "auth_id | auth_name | topic \n---------+----------------+-------- \n 1 | Doug Cutting | Hadoop \n 2 | James Gosling | java \n 3 | Dennis Ritchie | C\n" }, { "code": null, "e": 5943, "s": 5908, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5962, "s": 5943, "text": " Arnab Chakraborty" }, { "code": null, "e": 5997, "s": 5962, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6018, "s": 5997, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 6051, "s": 6018, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6064, "s": 6051, "text": " Nilay Mehta" }, { "code": null, "e": 6099, "s": 6064, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6117, "s": 6099, "text": " Bigdata Engineer" }, { "code": null, "e": 6150, "s": 6117, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6168, "s": 6150, "text": " Bigdata Engineer" }, { "code": null, "e": 6201, "s": 6168, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6219, "s": 6201, "text": " Bigdata Engineer" }, { "code": null, "e": 6226, "s": 6219, "text": " Print" }, { "code": null, "e": 6237, "s": 6226, "text": " Add Notes" } ]
C# Program to Get the Machine Name or Host Name Using Environment Class - GeeksforGeeks
30 Nov, 2021 Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information and time since last system boot in milliseconds information. By just using the predefined MachineName Property we can get the machine name or the hostname using the Environment class. This property is used to find the NetBIOS name of the computer. It also throws InvalidOperationException when this property does not get the name of the computer. Syntax: Environment.MachineName Return: This method returns a string that contains the machine name. Example: C# // C# program to find the name of the machine// Using Environment classusing System; class GFG{ static public void Main(){ // Here we get the machine name // Using the MachineName property // of the Environment class Console.WriteLine("Machine Name is" + Environment.MachineName);}} Output: Machine Name is Check avtarkumar719 CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n30 Nov, 2021" }, { "code": null, "e": 25022, "s": 24302, "text": "Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information and time since last system boot in milliseconds information. By just using the predefined MachineName Property we can get the machine name or the hostname using the Environment class. This property is used to find the NetBIOS name of the computer. It also throws InvalidOperationException when this property does not get the name of the computer." }, { "code": null, "e": 25030, "s": 25022, "text": "Syntax:" }, { "code": null, "e": 25054, "s": 25030, "text": "Environment.MachineName" }, { "code": null, "e": 25123, "s": 25054, "text": "Return: This method returns a string that contains the machine name." }, { "code": null, "e": 25132, "s": 25123, "text": "Example:" }, { "code": null, "e": 25135, "s": 25132, "text": "C#" }, { "code": "// C# program to find the name of the machine// Using Environment classusing System; class GFG{ static public void Main(){ // Here we get the machine name // Using the MachineName property // of the Environment class Console.WriteLine(\"Machine Name is\" + Environment.MachineName);}}", "e": 25435, "s": 25135, "text": null }, { "code": null, "e": 25443, "s": 25435, "text": "Output:" }, { "code": null, "e": 25465, "s": 25443, "text": "Machine Name is Check" }, { "code": null, "e": 25479, "s": 25465, "text": "avtarkumar719" }, { "code": null, "e": 25495, "s": 25479, "text": "CSharp-programs" }, { "code": null, "e": 25502, "s": 25495, "text": "Picked" }, { "code": null, "e": 25505, "s": 25502, "text": "C#" }, { "code": null, "e": 25603, "s": 25505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25621, "s": 25603, "text": "Destructors in C#" }, { "code": null, "e": 25644, "s": 25621, "text": "Extension Method in C#" }, { "code": null, "e": 25672, "s": 25644, "text": "HashSet in C# with Examples" }, { "code": null, "e": 25712, "s": 25672, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 25755, "s": 25712, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 25777, "s": 25755, "text": "Partial Classes in C#" }, { "code": null, "e": 25794, "s": 25777, "text": "C# | Inheritance" }, { "code": null, "e": 25810, "s": 25794, "text": "C# | List Class" }, { "code": null, "e": 25860, "s": 25810, "text": "Difference between Hashtable and Dictionary in C#" } ]
ByteArrayOutputStream write() method in Java with Examples - GeeksforGeeks
28 May, 2020 The write() method of ByteArrayOutputStream class in Java is used in two ways: 1. The write(int) method of ByteArrayOutputStream class in Java is used to write the specified byte to the ByteArrayOutputStream. This specified byte is passed as integer type parameter in this write() method. This write() method writes single byte at a time. Syntax: public void write(int b) Specified By: This method is specified by write() method of OutputStream class. Parameters: This method accepts one parameter b which represents the byte to be written. Return value: The method does not return any value. Exceptions: This method does not throw any exception. Below program illustrates write(int) method in ByteArrayOutputStream class in IO package: Program: // Java program to illustrate// ByteArrayOutputStream write(int) method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Write byte // to byteArrayOutputStream byteArrayOutStr.write(71); byteArrayOutStr.write(69); byteArrayOutStr.write(69); byteArrayOutStr.write(75); byteArrayOutStr.write(83); // Print the byteArrayOutputStream System.out.println( byteArrayOutStr.toString()); }} GEEKS 2. The write(byte[ ], int, int) method of ByteArrayOutputStream class in Java is used to write the given number of bytes from the given byte array starting at given offset of the byte array to theByteArrayOutputStream. This method is different from the above write() method as it can write several bytes at a time. Syntax: public void write(byte[ ] b, int offset, int length) Overrides: This method overrides write() method of OutputStream class. Parameters: This method accepts three parameters: b – It represents the byte array. offset – It represents the starting index in the byte array. length – It represents the number of bytes to be written. Return value: The method does not return any value. Exceptions: This method does not throw any exception. Below program illustrates write(byte[ ], int, int) method in ByteArrayOutputStream class in IO package: Program: // Java program to illustrate// ByteArrayOutputStream// write(byte[ ], int, int) method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf, 8, 5); // Print the byteArrayOutputStream System.out.println( byteArrayOutStr.toString()); }} GEEKS References:1. https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#write(int)2. https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#write(byte%5B%5D, int, int) Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n28 May, 2020" }, { "code": null, "e": 25304, "s": 25225, "text": "The write() method of ByteArrayOutputStream class in Java is used in two ways:" }, { "code": null, "e": 25564, "s": 25304, "text": "1. The write(int) method of ByteArrayOutputStream class in Java is used to write the specified byte to the ByteArrayOutputStream. This specified byte is passed as integer type parameter in this write() method. This write() method writes single byte at a time." }, { "code": null, "e": 25572, "s": 25564, "text": "Syntax:" }, { "code": null, "e": 25598, "s": 25572, "text": "public void write(int b)\n" }, { "code": null, "e": 25678, "s": 25598, "text": "Specified By: This method is specified by write() method of OutputStream class." }, { "code": null, "e": 25767, "s": 25678, "text": "Parameters: This method accepts one parameter b which represents the byte to be written." }, { "code": null, "e": 25819, "s": 25767, "text": "Return value: The method does not return any value." }, { "code": null, "e": 25873, "s": 25819, "text": "Exceptions: This method does not throw any exception." }, { "code": null, "e": 25963, "s": 25873, "text": "Below program illustrates write(int) method in ByteArrayOutputStream class in IO package:" }, { "code": null, "e": 25972, "s": 25963, "text": "Program:" }, { "code": "// Java program to illustrate// ByteArrayOutputStream write(int) method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Write byte // to byteArrayOutputStream byteArrayOutStr.write(71); byteArrayOutStr.write(69); byteArrayOutStr.write(69); byteArrayOutStr.write(75); byteArrayOutStr.write(83); // Print the byteArrayOutputStream System.out.println( byteArrayOutStr.toString()); }}", "e": 26637, "s": 25972, "text": null }, { "code": null, "e": 26644, "s": 26637, "text": "GEEKS\n" }, { "code": null, "e": 26959, "s": 26644, "text": "2. The write(byte[ ], int, int) method of ByteArrayOutputStream class in Java is used to write the given number of bytes from the given byte array starting at given offset of the byte array to theByteArrayOutputStream. This method is different from the above write() method as it can write several bytes at a time." }, { "code": null, "e": 26967, "s": 26959, "text": "Syntax:" }, { "code": null, "e": 27057, "s": 26967, "text": "public void write(byte[ ] b,\n int offset,\n int length)\n" }, { "code": null, "e": 27128, "s": 27057, "text": "Overrides: This method overrides write() method of OutputStream class." }, { "code": null, "e": 27178, "s": 27128, "text": "Parameters: This method accepts three parameters:" }, { "code": null, "e": 27212, "s": 27178, "text": "b – It represents the byte array." }, { "code": null, "e": 27273, "s": 27212, "text": "offset – It represents the starting index in the byte array." }, { "code": null, "e": 27331, "s": 27273, "text": "length – It represents the number of bytes to be written." }, { "code": null, "e": 27383, "s": 27331, "text": "Return value: The method does not return any value." }, { "code": null, "e": 27437, "s": 27383, "text": "Exceptions: This method does not throw any exception." }, { "code": null, "e": 27541, "s": 27437, "text": "Below program illustrates write(byte[ ], int, int) method in ByteArrayOutputStream class in IO package:" }, { "code": null, "e": 27550, "s": 27541, "text": "Program:" }, { "code": "// Java program to illustrate// ByteArrayOutputStream// write(byte[ ], int, int) method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf, 8, 5); // Print the byteArrayOutputStream System.out.println( byteArrayOutStr.toString()); }}", "e": 28248, "s": 27550, "text": null }, { "code": null, "e": 28255, "s": 28248, "text": "GEEKS\n" }, { "code": null, "e": 28466, "s": 28255, "text": "References:1. https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#write(int)2. https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#write(byte%5B%5D, int, int)" }, { "code": null, "e": 28481, "s": 28466, "text": "Java-Functions" }, { "code": null, "e": 28497, "s": 28481, "text": "Java-IO package" }, { "code": null, "e": 28502, "s": 28497, "text": "Java" }, { "code": null, "e": 28507, "s": 28502, "text": "Java" }, { "code": null, "e": 28605, "s": 28507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28620, "s": 28605, "text": "Stream In Java" }, { "code": null, "e": 28641, "s": 28620, "text": "Constructors in Java" }, { "code": null, "e": 28660, "s": 28641, "text": "Exceptions in Java" }, { "code": null, "e": 28690, "s": 28660, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28736, "s": 28690, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28753, "s": 28736, "text": "Generics in Java" }, { "code": null, "e": 28774, "s": 28753, "text": "Introduction to Java" }, { "code": null, "e": 28817, "s": 28774, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28853, "s": 28817, "text": "Internal Working of HashMap in Java" } ]
How to Add JAR file to Classpath in Java? - GeeksforGeeks
07 Aug, 2021 JAR is an abbreviation of JAVA Archive. It is used for aggregating multiple files into a single one, and it is present in a ZIP format. It can also be used as an archiving tool but the main intention to use this file for development is that the Java applets and their components(.class files) can be easily downloaded to a client browser in just one single HTTP request, rather than establishing a new connection for just one thing. This will improve the speed with which applets can be loaded onto a web page and starts their work. It also supports compression, which reduces the file size and the download time will be improved. Methods: JAR file can be added in a classpath in two different ways Using eclipse or any IDEUsing command line Using eclipse or any IDE Using command line Step 1: Right-Click on your project name Step 2: Click on Build Path Step 3: Click on configure build path Step 4: Click on libraries and click on “Add External JARs” Step 5: Select the jar file from the folder where you have saved your jar file Step 6: Click on Apply and Ok. Command 1: By including JAR name in CLASSPATH environment variable CLASSPATH environment variable is not case-sensitive. It can be either Classpath or classpath which is similar to PATH environment variable which we can use to locate Java binaries like javaw and java command. Command 2: By including name of JAR file in -a classpath command-line option This option is viable when we are passing –classpath option while running our java program like java –classpath $(CLASSPATH) Main. In this case, CLASSPATH shell variable contains the list of Jar file which is required by the application. One of the best advantages of using classpath command-line option is that it allows us to use every application to have its own set of JAR classpath. In other cases, it’s not available to all Java program which runs on the same host. Command 3: By including the jar name in the Class-Path option in the manifest When we are running an executable JAR file we always notice that the Class-Path attribute in the file inside the META-INF folder. Therefore, we can say that Class-Path is given the highest priority and it overrides the CLASSPATH environment variable as well as –classpath command-line option. Henceforth, we can deduce that its a good place to include all JAR files required by Java Application. Command 4: By using Java 6 wildcard option to include multiple JAR From Java 1.6+ onwards we can use a wildcard for including all jars in a directory to set classpath or else to provide Java program using classpath command-line option. We can illustrate the Java command example to add multiple JAR into classpath using Java 6 wildcard method as follows, java.exe -classpath D:\lib\*Main In this method, we include all JAR files inside ‘D:\lib’ directory into the classpath. We must ensure that syntax is correct. Some more important points about using Java 6 wildcard to include multiple JAR in classpath are as follows: Use * instead of *.jar Whenever JAR and classfile are present in the same directory then we need to include both of them separately Java -classpath /classes: /lib/* In Java 6 wildcard which includes all JAR, it will not search for JARs in a subdirectory. Wildcard is included in all JAR is not honored in the case when we are running Java program with JAR file and having Class-Path attribute in the manifest file. JAR wildcard is honored when we use –cp or –classpath option Command 5: Adding JAR in ext directory example be it ‘C:\Program Files\Java\jdk1.6.0\jre\lib\ext’ By using the above method we can add multiple JAR in our classpath. JAR from ext directory can be loaded by extension Classloader. It has been given higher priority than application class loader which loads JAR from either CLASSPATH environment variable or else directories specified in –classpath or –cp as5853535 Picked How To Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to Install OpenCV for Python on Windows? How to filter object array based on attributes? Java Tutorial How to Install FFmpeg on Windows? Arrays in Java Split() String method in Java with examples Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples
[ { "code": null, "e": 25681, "s": 25653, "text": "\n07 Aug, 2021" }, { "code": null, "e": 26312, "s": 25681, "text": "JAR is an abbreviation of JAVA Archive. It is used for aggregating multiple files into a single one, and it is present in a ZIP format. It can also be used as an archiving tool but the main intention to use this file for development is that the Java applets and their components(.class files) can be easily downloaded to a client browser in just one single HTTP request, rather than establishing a new connection for just one thing. This will improve the speed with which applets can be loaded onto a web page and starts their work. It also supports compression, which reduces the file size and the download time will be improved." }, { "code": null, "e": 26380, "s": 26312, "text": "Methods: JAR file can be added in a classpath in two different ways" }, { "code": null, "e": 26423, "s": 26380, "text": "Using eclipse or any IDEUsing command line" }, { "code": null, "e": 26448, "s": 26423, "text": "Using eclipse or any IDE" }, { "code": null, "e": 26467, "s": 26448, "text": "Using command line" }, { "code": null, "e": 26508, "s": 26467, "text": "Step 1: Right-Click on your project name" }, { "code": null, "e": 26536, "s": 26508, "text": "Step 2: Click on Build Path" }, { "code": null, "e": 26575, "s": 26536, "text": "Step 3: Click on configure build path" }, { "code": null, "e": 26635, "s": 26575, "text": "Step 4: Click on libraries and click on “Add External JARs”" }, { "code": null, "e": 26714, "s": 26635, "text": "Step 5: Select the jar file from the folder where you have saved your jar file" }, { "code": null, "e": 26745, "s": 26714, "text": "Step 6: Click on Apply and Ok." }, { "code": null, "e": 26812, "s": 26745, "text": "Command 1: By including JAR name in CLASSPATH environment variable" }, { "code": null, "e": 27022, "s": 26812, "text": "CLASSPATH environment variable is not case-sensitive. It can be either Classpath or classpath which is similar to PATH environment variable which we can use to locate Java binaries like javaw and java command." }, { "code": null, "e": 27099, "s": 27022, "text": "Command 2: By including name of JAR file in -a classpath command-line option" }, { "code": null, "e": 27571, "s": 27099, "text": "This option is viable when we are passing –classpath option while running our java program like java –classpath $(CLASSPATH) Main. In this case, CLASSPATH shell variable contains the list of Jar file which is required by the application. One of the best advantages of using classpath command-line option is that it allows us to use every application to have its own set of JAR classpath. In other cases, it’s not available to all Java program which runs on the same host." }, { "code": null, "e": 27649, "s": 27571, "text": "Command 3: By including the jar name in the Class-Path option in the manifest" }, { "code": null, "e": 28045, "s": 27649, "text": "When we are running an executable JAR file we always notice that the Class-Path attribute in the file inside the META-INF folder. Therefore, we can say that Class-Path is given the highest priority and it overrides the CLASSPATH environment variable as well as –classpath command-line option. Henceforth, we can deduce that its a good place to include all JAR files required by Java Application." }, { "code": null, "e": 28112, "s": 28045, "text": "Command 4: By using Java 6 wildcard option to include multiple JAR" }, { "code": null, "e": 28400, "s": 28112, "text": "From Java 1.6+ onwards we can use a wildcard for including all jars in a directory to set classpath or else to provide Java program using classpath command-line option. We can illustrate the Java command example to add multiple JAR into classpath using Java 6 wildcard method as follows," }, { "code": null, "e": 28433, "s": 28400, "text": "java.exe -classpath D:\\lib\\*Main" }, { "code": null, "e": 28667, "s": 28433, "text": "In this method, we include all JAR files inside ‘D:\\lib’ directory into the classpath. We must ensure that syntax is correct. Some more important points about using Java 6 wildcard to include multiple JAR in classpath are as follows:" }, { "code": null, "e": 28690, "s": 28667, "text": "Use * instead of *.jar" }, { "code": null, "e": 28799, "s": 28690, "text": "Whenever JAR and classfile are present in the same directory then we need to include both of them separately" }, { "code": null, "e": 28834, "s": 28799, "text": " Java -classpath /classes: /lib/*" }, { "code": null, "e": 28924, "s": 28834, "text": "In Java 6 wildcard which includes all JAR, it will not search for JARs in a subdirectory." }, { "code": null, "e": 29145, "s": 28924, "text": "Wildcard is included in all JAR is not honored in the case when we are running Java program with JAR file and having Class-Path attribute in the manifest file. JAR wildcard is honored when we use –cp or –classpath option" }, { "code": null, "e": 29243, "s": 29145, "text": "Command 5: Adding JAR in ext directory example be it ‘C:\\Program Files\\Java\\jdk1.6.0\\jre\\lib\\ext’" }, { "code": null, "e": 29548, "s": 29243, "text": "By using the above method we can add multiple JAR in our classpath. JAR from ext directory can be loaded by extension Classloader. It has been given higher priority than application class loader which loads JAR from either CLASSPATH environment variable or else directories specified in –classpath or –cp" }, { "code": null, "e": 29558, "s": 29548, "text": "as5853535" }, { "code": null, "e": 29565, "s": 29558, "text": "Picked" }, { "code": null, "e": 29572, "s": 29565, "text": "How To" }, { "code": null, "e": 29577, "s": 29572, "text": "Java" }, { "code": null, "e": 29582, "s": 29577, "text": "Java" }, { "code": null, "e": 29680, "s": 29582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29707, "s": 29680, "text": "How to Align Text in HTML?" }, { "code": null, "e": 29752, "s": 29707, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 29800, "s": 29752, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 29814, "s": 29800, "text": "Java Tutorial" }, { "code": null, "e": 29848, "s": 29814, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29863, "s": 29848, "text": "Arrays in Java" }, { "code": null, "e": 29907, "s": 29863, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29958, "s": 29907, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29994, "s": 29958, "text": "Arrays.sort() in Java with examples" } ]
Mapping CSV to JavaBeans Using OpenCSV - GeeksforGeeks
17 Jul, 2018 OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping strategy which maps the column id to the java bean property. First add OpenCSV to the project.For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.Mapping CSV to JavaBeansMapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap(); mapping.put("column id ", "javaBeanProperty"); Then add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy(); strategy.setType(JavaBeanObject.class); strategy.setColumnMapping(mapping); Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); CsvToBean csv = new CsvToBean(); Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader); First add OpenCSV to the project.For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path. For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency> For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1' compile group: 'com.opencsv', name: 'opencsv', version: '4.1' You can Download OpenCSV Jar and include in your project class path. Mapping CSV to JavaBeansMapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap(); mapping.put("column id ", "javaBeanProperty"); Then add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy(); strategy.setType(JavaBeanObject.class); strategy.setColumnMapping(mapping); Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); CsvToBean csv = new CsvToBean(); Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader); Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap(); mapping.put("column id ", "javaBeanProperty"); Then add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy(); strategy.setType(JavaBeanObject.class); strategy.setColumnMapping(mapping); Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); CsvToBean csv = new CsvToBean(); Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader); Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap(); mapping.put("column id ", "javaBeanProperty"); Then add all the column id of csv file with their corresponding javabean property. Map mapping = new HashMap(); mapping.put("column id ", "javaBeanProperty"); Then add all the column id of csv file with their corresponding javabean property. Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy(); strategy.setType(JavaBeanObject.class); strategy.setColumnMapping(mapping); HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy(); strategy.setType(JavaBeanObject.class); strategy.setColumnMapping(mapping); Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); CsvToBean csv = new CsvToBean(); String csvFilename = "data.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); CsvToBean csv = new CsvToBean(); Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader); List list = csv.parse(strategy, csvReader); Example: Let’ s convert csv file containing Student data to Student objects having attribute Name, RollNo, Department, Result, Pointer. StudentData.csv: name, rollno, department, result, cgpa amar, 42, cse, pass, 8.6 rohini, 21, ece, fail, 3.2 aman, 23, cse, pass, 8.9 rahul, 45, ee, fail, 4.6 pratik, 65, cse, pass, 7.2 raunak, 23, me, pass, 9.1 suvam, 68, me, pass, 8.2 First create a Student Class with Attributes Name, RollNo, Department, Result, Pointer. Then Create a main class which map csv data to JavaBeans object. Programs: Student.javapublic class Student { private static final long serialVersionUID = 1L; public String Name, RollNo, Department, Result, Pointer; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getRollNo() { return RollNo; } public void setRollNo(String rollNo) { RollNo = rollNo; } public String getDepartment() { return Department; } public void setDepartment(String department) { Department = department; } public String getResult() { return Result; } public void setResult(String result) { Result = result; } public String getPointer() { return Pointer; } public void setPointer(String pointer) { Pointer = pointer; } @Override public String toString() { return "Student [Name=" + Name + ", RollNo=" + RollNo + ", Department = " + Department + ", Result = " + Result + ", Pointer=" + Pointer + "]"; }}csvtobean.javaimport java.io.*;import java.util.*; import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; public class csvtobean { public static void main(String[] args) { // Hashmap to map CSV data to // Bean attributes. Map<String, String> mapping = new HashMap<String, String>(); mapping.put("name", "Name"); mapping.put("rollno", "RollNo"); mapping.put("department", "Department"); mapping.put("result", "Result"); mapping.put("cgpa", "Pointer"); // HeaderColumnNameTranslateMappingStrategy // for Student class HeaderColumnNameTranslateMappingStrategy<Student> strategy = new HeaderColumnNameTranslateMappingStrategy<Student>(); strategy.setType(Student.class); strategy.setColumnMapping(mapping); // Create castobaen and csvreader object CSVReader csvReader = null; try { csvReader = new CSVReader(new FileReader ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } CsvToBean csvToBean = new CsvToBean(); // call the parse method of CsvToBean // pass strategy, csvReader to parse method List<Student> list = csvToBean.parse(strategy, csvReader); // print details of Bean object for (Student e : list) { System.out.println(e); } }} Student.javapublic class Student { private static final long serialVersionUID = 1L; public String Name, RollNo, Department, Result, Pointer; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getRollNo() { return RollNo; } public void setRollNo(String rollNo) { RollNo = rollNo; } public String getDepartment() { return Department; } public void setDepartment(String department) { Department = department; } public String getResult() { return Result; } public void setResult(String result) { Result = result; } public String getPointer() { return Pointer; } public void setPointer(String pointer) { Pointer = pointer; } @Override public String toString() { return "Student [Name=" + Name + ", RollNo=" + RollNo + ", Department = " + Department + ", Result = " + Result + ", Pointer=" + Pointer + "]"; }} public class Student { private static final long serialVersionUID = 1L; public String Name, RollNo, Department, Result, Pointer; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getRollNo() { return RollNo; } public void setRollNo(String rollNo) { RollNo = rollNo; } public String getDepartment() { return Department; } public void setDepartment(String department) { Department = department; } public String getResult() { return Result; } public void setResult(String result) { Result = result; } public String getPointer() { return Pointer; } public void setPointer(String pointer) { Pointer = pointer; } @Override public String toString() { return "Student [Name=" + Name + ", RollNo=" + RollNo + ", Department = " + Department + ", Result = " + Result + ", Pointer=" + Pointer + "]"; }} csvtobean.javaimport java.io.*;import java.util.*; import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; public class csvtobean { public static void main(String[] args) { // Hashmap to map CSV data to // Bean attributes. Map<String, String> mapping = new HashMap<String, String>(); mapping.put("name", "Name"); mapping.put("rollno", "RollNo"); mapping.put("department", "Department"); mapping.put("result", "Result"); mapping.put("cgpa", "Pointer"); // HeaderColumnNameTranslateMappingStrategy // for Student class HeaderColumnNameTranslateMappingStrategy<Student> strategy = new HeaderColumnNameTranslateMappingStrategy<Student>(); strategy.setType(Student.class); strategy.setColumnMapping(mapping); // Create castobaen and csvreader object CSVReader csvReader = null; try { csvReader = new CSVReader(new FileReader ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } CsvToBean csvToBean = new CsvToBean(); // call the parse method of CsvToBean // pass strategy, csvReader to parse method List<Student> list = csvToBean.parse(strategy, csvReader); // print details of Bean object for (Student e : list) { System.out.println(e); } }} import java.io.*;import java.util.*; import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; public class csvtobean { public static void main(String[] args) { // Hashmap to map CSV data to // Bean attributes. Map<String, String> mapping = new HashMap<String, String>(); mapping.put("name", "Name"); mapping.put("rollno", "RollNo"); mapping.put("department", "Department"); mapping.put("result", "Result"); mapping.put("cgpa", "Pointer"); // HeaderColumnNameTranslateMappingStrategy // for Student class HeaderColumnNameTranslateMappingStrategy<Student> strategy = new HeaderColumnNameTranslateMappingStrategy<Student>(); strategy.setType(Student.class); strategy.setColumnMapping(mapping); // Create castobaen and csvreader object CSVReader csvReader = null; try { csvReader = new CSVReader(new FileReader ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } CsvToBean csvToBean = new CsvToBean(); // call the parse method of CsvToBean // pass strategy, csvReader to parse method List<Student> list = csvToBean.parse(strategy, csvReader); // print details of Bean object for (Student e : list) { System.out.println(e); } }} Output: Student [Name=amar, RollNo=42, Department=cse, Result=pass, Pointer=8.6] Student [Name=rohini, RollNo=21, Department=ece, Result=fail, Pointer=3.2] Student [Name=aman, RollNo=23, Department=cse, Result=pass, Pointer=8.9] Student [Name=rahul, RollNo=45, Department=ee, Result=fail, Pointer=4.6] Student [Name=pratik, RollNo=65, Department=cse, Result=pass, Pointer=7.2] Student [Name=raunak, RollNo=23, Department=me, Result=pass, Pointer=9.1] Student [Name=suvam, RollNo=68, Department=me, Result=pass, Pointer=8.2] Reference: OpenCSV Documentation, CsvTOBean Documentation, MappingStrategy CSV 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 HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25830, "s": 25802, "text": "\n17 Jul, 2018" }, { "code": null, "e": 26237, "s": 25830, "text": "OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping strategy which maps the column id to the java bean property." }, { "code": null, "e": 27624, "s": 26237, "text": "First add OpenCSV to the project.For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.Mapping CSV to JavaBeansMapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();\n mapping.put(\"column id \", \"javaBeanProperty\");\nThen add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =\n new HeaderColumnNameTranslateMappingStrategy();\n strategy.setType(JavaBeanObject.class);\n strategy.setColumnMapping(mapping);\nCreate the object of CSVReade and CsvToBean classString csvFilename = \"data.csv\";\nCSVReader csvReader = new CSVReader(new FileReader(csvFilename));\nCsvToBean csv = new CsvToBean();\nCall parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);\n" }, { "code": null, "e": 28031, "s": 27624, "text": "First add OpenCSV to the project.For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path." }, { "code": null, "e": 28225, "s": 28031, "text": "For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>" }, { "code": "<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>", "e": 28347, "s": 28225, "text": null }, { "code": null, "e": 28460, "s": 28347, "text": "For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'" }, { "code": null, "e": 28522, "s": 28460, "text": "compile group: 'com.opencsv', name: 'opencsv', version: '4.1'" }, { "code": null, "e": 28591, "s": 28522, "text": "You can Download OpenCSV Jar and include in your project class path." }, { "code": null, "e": 29572, "s": 28591, "text": "Mapping CSV to JavaBeansMapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();\n mapping.put(\"column id \", \"javaBeanProperty\");\nThen add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =\n new HeaderColumnNameTranslateMappingStrategy();\n strategy.setType(JavaBeanObject.class);\n strategy.setColumnMapping(mapping);\nCreate the object of CSVReade and CsvToBean classString csvFilename = \"data.csv\";\nCSVReader csvReader = new CSVReader(new FileReader(csvFilename));\nCsvToBean csv = new CsvToBean();\nCall parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);\n" }, { "code": null, "e": 30440, "s": 29572, "text": "Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();\n mapping.put(\"column id \", \"javaBeanProperty\");\nThen add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =\n new HeaderColumnNameTranslateMappingStrategy();\n strategy.setType(JavaBeanObject.class);\n strategy.setColumnMapping(mapping);\nCreate the object of CSVReade and CsvToBean classString csvFilename = \"data.csv\";\nCSVReader csvReader = new CSVReader(new FileReader(csvFilename));\nCsvToBean csv = new CsvToBean();\nCall parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);\n" }, { "code": null, "e": 30678, "s": 30440, "text": "Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();\n mapping.put(\"column id \", \"javaBeanProperty\");\nThen add all the column id of csv file with their corresponding javabean property." }, { "code": null, "e": 30764, "s": 30678, "text": "Map mapping = new HashMap();\n mapping.put(\"column id \", \"javaBeanProperty\");\n" }, { "code": null, "e": 30847, "s": 30764, "text": "Then add all the column id of csv file with their corresponding javabean property." }, { "code": null, "e": 31144, "s": 30847, "text": "Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =\n new HeaderColumnNameTranslateMappingStrategy();\n strategy.setType(JavaBeanObject.class);\n strategy.setColumnMapping(mapping);\n" }, { "code": null, "e": 31338, "s": 31144, "text": "HeaderColumnNameTranslateMappingStrategy strategy =\n new HeaderColumnNameTranslateMappingStrategy();\n strategy.setType(JavaBeanObject.class);\n strategy.setColumnMapping(mapping);\n" }, { "code": null, "e": 31520, "s": 31338, "text": "Create the object of CSVReade and CsvToBean classString csvFilename = \"data.csv\";\nCSVReader csvReader = new CSVReader(new FileReader(csvFilename));\nCsvToBean csv = new CsvToBean();\n" }, { "code": null, "e": 31653, "s": 31520, "text": "String csvFilename = \"data.csv\";\nCSVReader csvReader = new CSVReader(new FileReader(csvFilename));\nCsvToBean csv = new CsvToBean();\n" }, { "code": null, "e": 31807, "s": 31653, "text": "Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);\n" }, { "code": null, "e": 31852, "s": 31807, "text": "List list = csv.parse(strategy, csvReader);\n" }, { "code": null, "e": 31988, "s": 31852, "text": "Example: Let’ s convert csv file containing Student data to Student objects having attribute Name, RollNo, Department, Result, Pointer." }, { "code": null, "e": 32226, "s": 31988, "text": "StudentData.csv:\n\nname, rollno, department, result, cgpa\namar, 42, cse, pass, 8.6\nrohini, 21, ece, fail, 3.2\naman, 23, cse, pass, 8.9\nrahul, 45, ee, fail, 4.6\npratik, 65, cse, pass, 7.2\nraunak, 23, me, pass, 9.1\nsuvam, 68, me, pass, 8.2\n" }, { "code": null, "e": 32379, "s": 32226, "text": "First create a Student Class with Attributes Name, RollNo, Department, Result, Pointer. Then Create a main class which map csv data to JavaBeans object." }, { "code": null, "e": 32389, "s": 32379, "text": "Programs:" }, { "code": null, "e": 35114, "s": 32389, "text": "Student.javapublic class Student { private static final long serialVersionUID = 1L; public String Name, RollNo, Department, Result, Pointer; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getRollNo() { return RollNo; } public void setRollNo(String rollNo) { RollNo = rollNo; } public String getDepartment() { return Department; } public void setDepartment(String department) { Department = department; } public String getResult() { return Result; } public void setResult(String result) { Result = result; } public String getPointer() { return Pointer; } public void setPointer(String pointer) { Pointer = pointer; } @Override public String toString() { return \"Student [Name=\" + Name + \", RollNo=\" + RollNo + \", Department = \" + Department + \", Result = \" + Result + \", Pointer=\" + Pointer + \"]\"; }}csvtobean.javaimport java.io.*;import java.util.*; import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; public class csvtobean { public static void main(String[] args) { // Hashmap to map CSV data to // Bean attributes. Map<String, String> mapping = new HashMap<String, String>(); mapping.put(\"name\", \"Name\"); mapping.put(\"rollno\", \"RollNo\"); mapping.put(\"department\", \"Department\"); mapping.put(\"result\", \"Result\"); mapping.put(\"cgpa\", \"Pointer\"); // HeaderColumnNameTranslateMappingStrategy // for Student class HeaderColumnNameTranslateMappingStrategy<Student> strategy = new HeaderColumnNameTranslateMappingStrategy<Student>(); strategy.setType(Student.class); strategy.setColumnMapping(mapping); // Create castobaen and csvreader object CSVReader csvReader = null; try { csvReader = new CSVReader(new FileReader (\"D:\\\\EclipseWorkSpace\\\\CSVOperations\\\\StudentData.csv\")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } CsvToBean csvToBean = new CsvToBean(); // call the parse method of CsvToBean // pass strategy, csvReader to parse method List<Student> list = csvToBean.parse(strategy, csvReader); // print details of Bean object for (Student e : list) { System.out.println(e); } }}" }, { "code": null, "e": 36234, "s": 35114, "text": "Student.javapublic class Student { private static final long serialVersionUID = 1L; public String Name, RollNo, Department, Result, Pointer; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getRollNo() { return RollNo; } public void setRollNo(String rollNo) { RollNo = rollNo; } public String getDepartment() { return Department; } public void setDepartment(String department) { Department = department; } public String getResult() { return Result; } public void setResult(String result) { Result = result; } public String getPointer() { return Pointer; } public void setPointer(String pointer) { Pointer = pointer; } @Override public String toString() { return \"Student [Name=\" + Name + \", RollNo=\" + RollNo + \", Department = \" + Department + \", Result = \" + Result + \", Pointer=\" + Pointer + \"]\"; }}" }, { "code": "public class Student { private static final long serialVersionUID = 1L; public String Name, RollNo, Department, Result, Pointer; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getRollNo() { return RollNo; } public void setRollNo(String rollNo) { RollNo = rollNo; } public String getDepartment() { return Department; } public void setDepartment(String department) { Department = department; } public String getResult() { return Result; } public void setResult(String result) { Result = result; } public String getPointer() { return Pointer; } public void setPointer(String pointer) { Pointer = pointer; } @Override public String toString() { return \"Student [Name=\" + Name + \", RollNo=\" + RollNo + \", Department = \" + Department + \", Result = \" + Result + \", Pointer=\" + Pointer + \"]\"; }}", "e": 37342, "s": 36234, "text": null }, { "code": null, "e": 38948, "s": 37342, "text": "csvtobean.javaimport java.io.*;import java.util.*; import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; public class csvtobean { public static void main(String[] args) { // Hashmap to map CSV data to // Bean attributes. Map<String, String> mapping = new HashMap<String, String>(); mapping.put(\"name\", \"Name\"); mapping.put(\"rollno\", \"RollNo\"); mapping.put(\"department\", \"Department\"); mapping.put(\"result\", \"Result\"); mapping.put(\"cgpa\", \"Pointer\"); // HeaderColumnNameTranslateMappingStrategy // for Student class HeaderColumnNameTranslateMappingStrategy<Student> strategy = new HeaderColumnNameTranslateMappingStrategy<Student>(); strategy.setType(Student.class); strategy.setColumnMapping(mapping); // Create castobaen and csvreader object CSVReader csvReader = null; try { csvReader = new CSVReader(new FileReader (\"D:\\\\EclipseWorkSpace\\\\CSVOperations\\\\StudentData.csv\")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } CsvToBean csvToBean = new CsvToBean(); // call the parse method of CsvToBean // pass strategy, csvReader to parse method List<Student> list = csvToBean.parse(strategy, csvReader); // print details of Bean object for (Student e : list) { System.out.println(e); } }}" }, { "code": "import java.io.*;import java.util.*; import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; public class csvtobean { public static void main(String[] args) { // Hashmap to map CSV data to // Bean attributes. Map<String, String> mapping = new HashMap<String, String>(); mapping.put(\"name\", \"Name\"); mapping.put(\"rollno\", \"RollNo\"); mapping.put(\"department\", \"Department\"); mapping.put(\"result\", \"Result\"); mapping.put(\"cgpa\", \"Pointer\"); // HeaderColumnNameTranslateMappingStrategy // for Student class HeaderColumnNameTranslateMappingStrategy<Student> strategy = new HeaderColumnNameTranslateMappingStrategy<Student>(); strategy.setType(Student.class); strategy.setColumnMapping(mapping); // Create castobaen and csvreader object CSVReader csvReader = null; try { csvReader = new CSVReader(new FileReader (\"D:\\\\EclipseWorkSpace\\\\CSVOperations\\\\StudentData.csv\")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } CsvToBean csvToBean = new CsvToBean(); // call the parse method of CsvToBean // pass strategy, csvReader to parse method List<Student> list = csvToBean.parse(strategy, csvReader); // print details of Bean object for (Student e : list) { System.out.println(e); } }}", "e": 40540, "s": 38948, "text": null }, { "code": null, "e": 40548, "s": 40540, "text": "Output:" }, { "code": null, "e": 41065, "s": 40548, "text": "Student [Name=amar, RollNo=42, Department=cse, Result=pass, Pointer=8.6]\nStudent [Name=rohini, RollNo=21, Department=ece, Result=fail, Pointer=3.2]\nStudent [Name=aman, RollNo=23, Department=cse, Result=pass, Pointer=8.9]\nStudent [Name=rahul, RollNo=45, Department=ee, Result=fail, Pointer=4.6]\nStudent [Name=pratik, RollNo=65, Department=cse, Result=pass, Pointer=7.2]\nStudent [Name=raunak, RollNo=23, Department=me, Result=pass, Pointer=9.1]\nStudent [Name=suvam, RollNo=68, Department=me, Result=pass, Pointer=8.2]\n" }, { "code": null, "e": 41140, "s": 41065, "text": "Reference: OpenCSV Documentation, CsvTOBean Documentation, MappingStrategy" }, { "code": null, "e": 41144, "s": 41140, "text": "CSV" }, { "code": null, "e": 41149, "s": 41144, "text": "Java" }, { "code": null, "e": 41154, "s": 41149, "text": "Java" }, { "code": null, "e": 41252, "s": 41154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41303, "s": 41252, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 41333, "s": 41303, "text": "HashMap in Java with Examples" }, { "code": null, "e": 41348, "s": 41333, "text": "Stream In Java" }, { "code": null, "e": 41367, "s": 41348, "text": "Interfaces in Java" }, { "code": null, "e": 41398, "s": 41367, "text": "How to iterate any Map in Java" }, { "code": null, "e": 41416, "s": 41398, "text": "ArrayList in Java" }, { "code": null, "e": 41448, "s": 41416, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 41468, "s": 41448, "text": "Stack Class in Java" }, { "code": null, "e": 41500, "s": 41468, "text": "Multidimensional Arrays in Java" } ]
Python | Decision tree implementation - GeeksforGeeks
26 Apr, 2022 Prerequisites: Decision Tree, DecisionTreeClassifier, sklearn, numpy, pandas Decision Tree is one of the most powerful and popular algorithm. Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables. In this article, We are going to implement a Decision tree algorithm on the Balance Scale Weight & Distance Database presented on the UCI. Title : Balance Scale Weight & Distance Database Number of Instances : 625 (49 balanced, 288 left, 288 right) Number of Attributes : 4 (numeric) + class name = 5 Attribute Information: Class Name (Target variable): 3L [balance scale tip to the left]B [balance scale be balanced]R [balance scale tip to the right]Left-Weight: 5 (1, 2, 3, 4, 5)Left-Distance: 5 (1, 2, 3, 4, 5)Right-Weight: 5 (1, 2, 3, 4, 5)Right-Distance: 5 (1, 2, 3, 4, 5) Missing Attribute Values: None Class Distribution:46.08 percent are L07.84 percent are B46.08 percent are R You can find more details of the dataset here. Class Name (Target variable): 3L [balance scale tip to the left]B [balance scale be balanced]R [balance scale tip to the right]Left-Weight: 5 (1, 2, 3, 4, 5)Left-Distance: 5 (1, 2, 3, 4, 5)Right-Weight: 5 (1, 2, 3, 4, 5)Right-Distance: 5 (1, 2, 3, 4, 5) Missing Attribute Values: None Class Distribution:46.08 percent are L07.84 percent are B46.08 percent are R You can find more details of the dataset here. Class Name (Target variable): 3L [balance scale tip to the left]B [balance scale be balanced]R [balance scale tip to the right] L [balance scale tip to the left] B [balance scale be balanced] R [balance scale tip to the right] Left-Weight: 5 (1, 2, 3, 4, 5) Left-Distance: 5 (1, 2, 3, 4, 5) Right-Weight: 5 (1, 2, 3, 4, 5) Right-Distance: 5 (1, 2, 3, 4, 5) Missing Attribute Values: None Class Distribution:46.08 percent are L07.84 percent are B46.08 percent are R You can find more details of the dataset here. 46.08 percent are L07.84 percent are B46.08 percent are R 46.08 percent are L 07.84 percent are B 46.08 percent are R sklearn :In python, sklearn is a machine learning package which include a lot of ML algorithms.Here, we are using some of its modules like train_test_split, DecisionTreeClassifier and accuracy_score.NumPy :It is a numeric python module which provides fast maths functions for calculations.It is used to read data in numpy arrays and for manipulation purpose.Pandas :Used to read and write different files.Data manipulation can be done easily with dataframes. sklearn :In python, sklearn is a machine learning package which include a lot of ML algorithms.Here, we are using some of its modules like train_test_split, DecisionTreeClassifier and accuracy_score. In python, sklearn is a machine learning package which include a lot of ML algorithms. Here, we are using some of its modules like train_test_split, DecisionTreeClassifier and accuracy_score. NumPy :It is a numeric python module which provides fast maths functions for calculations.It is used to read data in numpy arrays and for manipulation purpose. It is a numeric python module which provides fast maths functions for calculations. It is used to read data in numpy arrays and for manipulation purpose. Pandas :Used to read and write different files.Data manipulation can be done easily with dataframes. Used to read and write different files. Data manipulation can be done easily with dataframes. In Python, sklearn is the package which contains all the required packages to implement Machine learning algorithm. You can install the sklearn package by following the commands given below.using pip : pip install -U scikit-learn Before using the above command make sure you have scipy and numpy packages installed. If you don’t have pip. You can install it using python get-pip.py using conda : conda install scikit-learn At the beginning, we consider the whole training set as the root. Attributes are assumed to be categorical for information gain and for gini index, attributes are assumed to be continuous. On the basis of attribute values records are distributed recursively. We use statistical methods for ordering attributes as root or internal node.Pseudocode :Find the best attribute and place it on the root node of the tree.Now, split the training set of the dataset into subsets. While making the subset make sure that each subset of training dataset should have the same value for an attribute.Find leaf nodes in all branches by repeating 1 and 2 on each subset.While implementing the decision tree we will go through the following two phases:Building PhasePreprocess the dataset.Split the dataset from train and test using Python sklearn package.Train the classifier.Operational PhaseMake predictions.Calculate the accuracy.Data Import : Find the best attribute and place it on the root node of the tree.Now, split the training set of the dataset into subsets. While making the subset make sure that each subset of training dataset should have the same value for an attribute.Find leaf nodes in all branches by repeating 1 and 2 on each subset. Find the best attribute and place it on the root node of the tree. Now, split the training set of the dataset into subsets. While making the subset make sure that each subset of training dataset should have the same value for an attribute. Find leaf nodes in all branches by repeating 1 and 2 on each subset. While implementing the decision tree we will go through the following two phases: Building PhasePreprocess the dataset.Split the dataset from train and test using Python sklearn package.Train the classifier.Operational PhaseMake predictions.Calculate the accuracy. Building PhasePreprocess the dataset.Split the dataset from train and test using Python sklearn package.Train the classifier. Preprocess the dataset. Split the dataset from train and test using Python sklearn package. Train the classifier. Operational PhaseMake predictions.Calculate the accuracy. Make predictions. Calculate the accuracy. To import and manipulate the data we are using the pandas package provided in python. Here, we are using a URL which is directly fetching the dataset from the UCI site no need to download the dataset. When you try to run this code on your system make sure the system should have an active Internet connection. As the dataset is separated by “,” so we have to pass the sep parameter’s value as “,”. Another thing is notice is that the dataset doesn’t contain the header so we will pass the Header parameter’s value as none. If we will not pass the header parameter then it will consider the first line of the dataset as the header.Data Slicing : Before training the model we have to split the dataset into the training and testing dataset. To split the dataset for training and testing we are using the sklearn module train_test_split First of all we have to separate the target variable from the attributes in the dataset.X = balance_data.values[:, 1:5] Y = balance_data.values[:,0] X = balance_data.values[:, 1:5] Y = balance_data.values[:,0] Above are the lines from the code which separate the dataset. The variable X contains the attributes while the variable Y contains the target variable of the dataset. Next step is to split the dataset for training and testing purpose.X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = 0.3, random_state = 100) X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = 0.3, random_state = 100) Above line split the dataset for training and testing. As we are splitting the dataset in a ratio of 70:30 between training and testing so we are pass test_size parameter’s value as 0.3. random_state variable is a pseudo-random number generator state used for random sampling.Terms used in code :Gini index and information gain both of these methods are used to select from the n attributes of the dataset which attribute would be placed at the root node or the internal node.Gini index: Gini index and information gain both of these methods are used to select from the n attributes of the dataset which attribute would be placed at the root node or the internal node. Gini index: Gini Index is a metric to measure how often a randomly chosen element would be incorrectly identified. It means an attribute with lower gini index should be preferred. Sklearn supports “gini” criteria for Gini Index and by default, it takes “gini” value.Entropy: Entropy: Entropy is the measure of uncertainty of a random variable, it characterizes the impurity of an arbitrary collection of examples. The higher the entropy the more the information content.Information Gain Information Gain The entropy typically changes when we use a node in a decision tree to partition the training instances into smaller subsets. Information gain is a measure of this change in entropy. Sklearn supports “entropy” criteria for Information Gain and if we want to use Information Gain method in sklearn then we have to mention it explicitly.Accuracy score Accuracy score Accuracy score is used to calculate the accuracy of the trained classifier.Confusion Matrix Confusion Matrix Confusion Matrix is used to understand the trained classifier behavior over the test dataset or validate dataset.Recommended: Please try your approach on {IDE} first, before moving on to the solution.Below is the python code for the decision tree.# Run this program on your local python# interpreter, provided you have installed# the required libraries. # Importing the required packagesimport numpy as npimport pandas as pdfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report # Function importing Datasetdef importdata(): balance_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-'+'databases/balance-scale/balance-scale.data', sep= ',', header = None) # Printing the dataswet shape print ("Dataset Length: ", len(balance_data)) print ("Dataset Shape: ", balance_data.shape) # Printing the dataset obseravtions print ("Dataset: ",balance_data.head()) return balance_data # Function to split the datasetdef splitdataset(balance_data): # Separating the target variable X = balance_data.values[:, 1:5] Y = balance_data.values[:, 0] # Splitting the dataset into train and test X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = 0.3, random_state = 100) return X, Y, X_train, X_test, y_train, y_test # Function to perform training with giniIndex.def train_using_gini(X_train, X_test, y_train): # Creating the classifier object clf_gini = DecisionTreeClassifier(criterion = "gini", random_state = 100,max_depth=3, min_samples_leaf=5) # Performing training clf_gini.fit(X_train, y_train) return clf_gini # Function to perform training with entropy.def tarin_using_entropy(X_train, X_test, y_train): # Decision tree with entropy clf_entropy = DecisionTreeClassifier( criterion = "entropy", random_state = 100, max_depth = 3, min_samples_leaf = 5) # Performing training clf_entropy.fit(X_train, y_train) return clf_entropy # Function to make predictionsdef prediction(X_test, clf_object): # Predicton on test with giniIndex y_pred = clf_object.predict(X_test) print("Predicted values:") print(y_pred) return y_pred # Function to calculate accuracydef cal_accuracy(y_test, y_pred): print("Confusion Matrix: ", confusion_matrix(y_test, y_pred)) print ("Accuracy : ", accuracy_score(y_test,y_pred)*100) print("Report : ", classification_report(y_test, y_pred)) # Driver codedef main(): # Building Phase data = importdata() X, Y, X_train, X_test, y_train, y_test = splitdataset(data) clf_gini = train_using_gini(X_train, X_test, y_train) clf_entropy = tarin_using_entropy(X_train, X_test, y_train) # Operational Phase print("Results Using Gini Index:") # Prediction using gini y_pred_gini = prediction(X_test, clf_gini) cal_accuracy(y_test, y_pred_gini) print("Results Using Entropy:") # Prediction using entropy y_pred_entropy = prediction(X_test, clf_entropy) cal_accuracy(y_test, y_pred_entropy) # Calling main functionif __name__=="__main__": main()Data Infomation: Dataset Length: 625 Dataset Shape: (625, 5) Dataset: 0 1 2 3 4 0 B 1 1 1 1 1 R 1 1 1 2 2 R 1 1 1 3 3 R 1 1 1 4 4 R 1 1 1 5 Results Using Gini Index: Predicted values: ['R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'R'] Confusion Matrix: [[ 0 6 7] [ 0 67 18] [ 0 19 71]] Accuracy : 73.4042553191 Report : precision recall f1-score support B 0.00 0.00 0.00 13 L 0.73 0.79 0.76 85 R 0.74 0.79 0.76 90 avg/total 0.68 0.73 0.71 188 Results Using Entropy: Predicted values: ['R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'R' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'R'] Confusion Matrix: [[ 0 6 7] [ 0 63 22] [ 0 20 70]] Accuracy : 70.7446808511 Report : precision recall f1-score support B 0.00 0.00 0.00 13 L 0.71 0.74 0.72 85 R 0.71 0.78 0.74 90 avg / total 0.66 0.71 0.68 188My Personal Notes arrow_drop_upSave Below is the python code for the decision tree. # Run this program on your local python# interpreter, provided you have installed# the required libraries. # Importing the required packagesimport numpy as npimport pandas as pdfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report # Function importing Datasetdef importdata(): balance_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-'+'databases/balance-scale/balance-scale.data', sep= ',', header = None) # Printing the dataswet shape print ("Dataset Length: ", len(balance_data)) print ("Dataset Shape: ", balance_data.shape) # Printing the dataset obseravtions print ("Dataset: ",balance_data.head()) return balance_data # Function to split the datasetdef splitdataset(balance_data): # Separating the target variable X = balance_data.values[:, 1:5] Y = balance_data.values[:, 0] # Splitting the dataset into train and test X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = 0.3, random_state = 100) return X, Y, X_train, X_test, y_train, y_test # Function to perform training with giniIndex.def train_using_gini(X_train, X_test, y_train): # Creating the classifier object clf_gini = DecisionTreeClassifier(criterion = "gini", random_state = 100,max_depth=3, min_samples_leaf=5) # Performing training clf_gini.fit(X_train, y_train) return clf_gini # Function to perform training with entropy.def tarin_using_entropy(X_train, X_test, y_train): # Decision tree with entropy clf_entropy = DecisionTreeClassifier( criterion = "entropy", random_state = 100, max_depth = 3, min_samples_leaf = 5) # Performing training clf_entropy.fit(X_train, y_train) return clf_entropy # Function to make predictionsdef prediction(X_test, clf_object): # Predicton on test with giniIndex y_pred = clf_object.predict(X_test) print("Predicted values:") print(y_pred) return y_pred # Function to calculate accuracydef cal_accuracy(y_test, y_pred): print("Confusion Matrix: ", confusion_matrix(y_test, y_pred)) print ("Accuracy : ", accuracy_score(y_test,y_pred)*100) print("Report : ", classification_report(y_test, y_pred)) # Driver codedef main(): # Building Phase data = importdata() X, Y, X_train, X_test, y_train, y_test = splitdataset(data) clf_gini = train_using_gini(X_train, X_test, y_train) clf_entropy = tarin_using_entropy(X_train, X_test, y_train) # Operational Phase print("Results Using Gini Index:") # Prediction using gini y_pred_gini = prediction(X_test, clf_gini) cal_accuracy(y_test, y_pred_gini) print("Results Using Entropy:") # Prediction using entropy y_pred_entropy = prediction(X_test, clf_entropy) cal_accuracy(y_test, y_pred_entropy) # Calling main functionif __name__=="__main__": main() Data Infomation: Dataset Length: 625 Dataset Shape: (625, 5) Dataset: 0 1 2 3 4 0 B 1 1 1 1 1 R 1 1 1 2 2 R 1 1 1 3 3 R 1 1 1 4 4 R 1 1 1 5 Results Using Gini Index: Predicted values: ['R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'R'] Confusion Matrix: [[ 0 6 7] [ 0 67 18] [ 0 19 71]] Accuracy : 73.4042553191 Report : precision recall f1-score support B 0.00 0.00 0.00 13 L 0.73 0.79 0.76 85 R 0.74 0.79 0.76 90 avg/total 0.68 0.73 0.71 188 Results Using Entropy: Predicted values: ['R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'R' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'R'] Confusion Matrix: [[ 0 6 7] [ 0 63 22] [ 0 20 70]] Accuracy : 70.7446808511 Report : precision recall f1-score support B 0.00 0.00 0.00 13 L 0.71 0.74 0.72 85 R 0.71 0.78 0.74 90 avg / total 0.66 0.71 0.68 188 Data Infomation: Results Using Gini Index: Results Using Entropy: shubham_singh knbarnwal khyatichat23 Advanced Computer Subject Machine Learning Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Copying Files to and from Docker Containers ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction Agents in Artificial Intelligence Activation functions in Neural Networks Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Underfitting and Overfitting
[ { "code": null, "e": 25471, "s": 25443, "text": "\n26 Apr, 2022" }, { "code": null, "e": 25548, "s": 25471, "text": "Prerequisites: Decision Tree, DecisionTreeClassifier, sklearn, numpy, pandas" }, { "code": null, "e": 25767, "s": 25548, "text": "Decision Tree is one of the most powerful and popular algorithm. Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables." }, { "code": null, "e": 25906, "s": 25767, "text": "In this article, We are going to implement a Decision tree algorithm on the Balance Scale Weight & Distance Database presented on the UCI." }, { "code": null, "e": 26516, "s": 25906, "text": "Title : Balance Scale Weight & Distance Database\nNumber of Instances : 625 (49 balanced, 288 left, 288 right)\nNumber of Attributes : 4 (numeric) + class name = 5\nAttribute Information:\nClass Name (Target variable): 3L [balance scale tip to the left]B [balance scale be balanced]R [balance scale tip to the right]Left-Weight: 5 (1, 2, 3, 4, 5)Left-Distance: 5 (1, 2, 3, 4, 5)Right-Weight: 5 (1, 2, 3, 4, 5)Right-Distance: 5 (1, 2, 3, 4, 5)\nMissing Attribute Values: None\nClass Distribution:46.08 percent are L07.84 percent are B46.08 percent are R\nYou can find more details of the dataset here." }, { "code": null, "e": 26925, "s": 26516, "text": "Class Name (Target variable): 3L [balance scale tip to the left]B [balance scale be balanced]R [balance scale tip to the right]Left-Weight: 5 (1, 2, 3, 4, 5)Left-Distance: 5 (1, 2, 3, 4, 5)Right-Weight: 5 (1, 2, 3, 4, 5)Right-Distance: 5 (1, 2, 3, 4, 5)\nMissing Attribute Values: None\nClass Distribution:46.08 percent are L07.84 percent are B46.08 percent are R\nYou can find more details of the dataset here." }, { "code": null, "e": 27053, "s": 26925, "text": "Class Name (Target variable): 3L [balance scale tip to the left]B [balance scale be balanced]R [balance scale tip to the right]" }, { "code": null, "e": 27087, "s": 27053, "text": "L [balance scale tip to the left]" }, { "code": null, "e": 27117, "s": 27087, "text": "B [balance scale be balanced]" }, { "code": null, "e": 27152, "s": 27117, "text": "R [balance scale tip to the right]" }, { "code": null, "e": 27183, "s": 27152, "text": "Left-Weight: 5 (1, 2, 3, 4, 5)" }, { "code": null, "e": 27216, "s": 27183, "text": "Left-Distance: 5 (1, 2, 3, 4, 5)" }, { "code": null, "e": 27248, "s": 27216, "text": "Right-Weight: 5 (1, 2, 3, 4, 5)" }, { "code": null, "e": 27437, "s": 27248, "text": "Right-Distance: 5 (1, 2, 3, 4, 5)\nMissing Attribute Values: None\nClass Distribution:46.08 percent are L07.84 percent are B46.08 percent are R\nYou can find more details of the dataset here." }, { "code": null, "e": 27495, "s": 27437, "text": "46.08 percent are L07.84 percent are B46.08 percent are R" }, { "code": null, "e": 27515, "s": 27495, "text": "46.08 percent are L" }, { "code": null, "e": 27535, "s": 27515, "text": "07.84 percent are B" }, { "code": null, "e": 27555, "s": 27535, "text": "46.08 percent are R" }, { "code": null, "e": 28014, "s": 27555, "text": "sklearn :In python, sklearn is a machine learning package which include a lot of ML algorithms.Here, we are using some of its modules like train_test_split, DecisionTreeClassifier and accuracy_score.NumPy :It is a numeric python module which provides fast maths functions for calculations.It is used to read data in numpy arrays and for manipulation purpose.Pandas :Used to read and write different files.Data manipulation can be done easily with dataframes." }, { "code": null, "e": 28214, "s": 28014, "text": "sklearn :In python, sklearn is a machine learning package which include a lot of ML algorithms.Here, we are using some of its modules like train_test_split, DecisionTreeClassifier and accuracy_score." }, { "code": null, "e": 28301, "s": 28214, "text": "In python, sklearn is a machine learning package which include a lot of ML algorithms." }, { "code": null, "e": 28406, "s": 28301, "text": "Here, we are using some of its modules like train_test_split, DecisionTreeClassifier and accuracy_score." }, { "code": null, "e": 28566, "s": 28406, "text": "NumPy :It is a numeric python module which provides fast maths functions for calculations.It is used to read data in numpy arrays and for manipulation purpose." }, { "code": null, "e": 28650, "s": 28566, "text": "It is a numeric python module which provides fast maths functions for calculations." }, { "code": null, "e": 28720, "s": 28650, "text": "It is used to read data in numpy arrays and for manipulation purpose." }, { "code": null, "e": 28821, "s": 28720, "text": "Pandas :Used to read and write different files.Data manipulation can be done easily with dataframes." }, { "code": null, "e": 28861, "s": 28821, "text": "Used to read and write different files." }, { "code": null, "e": 28915, "s": 28861, "text": "Data manipulation can be done easily with dataframes." }, { "code": null, "e": 29117, "s": 28915, "text": "In Python, sklearn is the package which contains all the required packages to implement Machine learning algorithm. You can install the sklearn package by following the commands given below.using pip :" }, { "code": null, "e": 29145, "s": 29117, "text": "pip install -U scikit-learn" }, { "code": null, "e": 29231, "s": 29145, "text": "Before using the above command make sure you have scipy and numpy packages installed." }, { "code": null, "e": 29279, "s": 29231, "text": "If you don’t have pip. You can install it using" }, { "code": null, "e": 29297, "s": 29279, "text": "python get-pip.py" }, { "code": null, "e": 29311, "s": 29297, "text": "using conda :" }, { "code": null, "e": 29338, "s": 29311, "text": "conda install scikit-learn" }, { "code": null, "e": 29404, "s": 29338, "text": "At the beginning, we consider the whole training set as the root." }, { "code": null, "e": 29527, "s": 29404, "text": "Attributes are assumed to be categorical for information gain and for gini index, attributes are assumed to be continuous." }, { "code": null, "e": 29597, "s": 29527, "text": "On the basis of attribute values records are distributed recursively." }, { "code": null, "e": 30268, "s": 29597, "text": "We use statistical methods for ordering attributes as root or internal node.Pseudocode :Find the best attribute and place it on the root node of the tree.Now, split the training set of the dataset into subsets. While making the subset make sure that each subset of training dataset should have the same value for an attribute.Find leaf nodes in all branches by repeating 1 and 2 on each subset.While implementing the decision tree we will go through the following two phases:Building PhasePreprocess the dataset.Split the dataset from train and test using Python sklearn package.Train the classifier.Operational PhaseMake predictions.Calculate the accuracy.Data Import :" }, { "code": null, "e": 30575, "s": 30268, "text": "Find the best attribute and place it on the root node of the tree.Now, split the training set of the dataset into subsets. While making the subset make sure that each subset of training dataset should have the same value for an attribute.Find leaf nodes in all branches by repeating 1 and 2 on each subset." }, { "code": null, "e": 30642, "s": 30575, "text": "Find the best attribute and place it on the root node of the tree." }, { "code": null, "e": 30815, "s": 30642, "text": "Now, split the training set of the dataset into subsets. While making the subset make sure that each subset of training dataset should have the same value for an attribute." }, { "code": null, "e": 30884, "s": 30815, "text": "Find leaf nodes in all branches by repeating 1 and 2 on each subset." }, { "code": null, "e": 30966, "s": 30884, "text": "While implementing the decision tree we will go through the following two phases:" }, { "code": null, "e": 31149, "s": 30966, "text": "Building PhasePreprocess the dataset.Split the dataset from train and test using Python sklearn package.Train the classifier.Operational PhaseMake predictions.Calculate the accuracy." }, { "code": null, "e": 31275, "s": 31149, "text": "Building PhasePreprocess the dataset.Split the dataset from train and test using Python sklearn package.Train the classifier." }, { "code": null, "e": 31299, "s": 31275, "text": "Preprocess the dataset." }, { "code": null, "e": 31367, "s": 31299, "text": "Split the dataset from train and test using Python sklearn package." }, { "code": null, "e": 31389, "s": 31367, "text": "Train the classifier." }, { "code": null, "e": 31447, "s": 31389, "text": "Operational PhaseMake predictions.Calculate the accuracy." }, { "code": null, "e": 31465, "s": 31447, "text": "Make predictions." }, { "code": null, "e": 31489, "s": 31465, "text": "Calculate the accuracy." }, { "code": null, "e": 31575, "s": 31489, "text": "To import and manipulate the data we are using the pandas package provided in python." }, { "code": null, "e": 31799, "s": 31575, "text": "Here, we are using a URL which is directly fetching the dataset from the UCI site no need to download the dataset. When you try to run this code on your system make sure the system should have an active Internet connection." }, { "code": null, "e": 31887, "s": 31799, "text": "As the dataset is separated by “,” so we have to pass the sep parameter’s value as “,”." }, { "code": null, "e": 32134, "s": 31887, "text": "Another thing is notice is that the dataset doesn’t contain the header so we will pass the Header parameter’s value as none. If we will not pass the header parameter then it will consider the first line of the dataset as the header.Data Slicing :" }, { "code": null, "e": 32228, "s": 32134, "text": "Before training the model we have to split the dataset into the training and testing dataset." }, { "code": null, "e": 32323, "s": 32228, "text": "To split the dataset for training and testing we are using the sklearn module train_test_split" }, { "code": null, "e": 32473, "s": 32323, "text": "First of all we have to separate the target variable from the attributes in the dataset.X = balance_data.values[:, 1:5]\nY = balance_data.values[:,0]\n" }, { "code": null, "e": 32535, "s": 32473, "text": "X = balance_data.values[:, 1:5]\nY = balance_data.values[:,0]\n" }, { "code": null, "e": 32702, "s": 32535, "text": "Above are the lines from the code which separate the dataset. The variable X contains the attributes while the variable Y contains the target variable of the dataset." }, { "code": null, "e": 32876, "s": 32702, "text": "Next step is to split the dataset for training and testing purpose.X_train, X_test, y_train, y_test = train_test_split( \n X, Y, test_size = 0.3, random_state = 100)" }, { "code": null, "e": 32983, "s": 32876, "text": "X_train, X_test, y_train, y_test = train_test_split( \n X, Y, test_size = 0.3, random_state = 100)" }, { "code": null, "e": 33170, "s": 32983, "text": "Above line split the dataset for training and testing. As we are splitting the dataset in a ratio of 70:30 between training and testing so we are pass test_size parameter’s value as 0.3." }, { "code": null, "e": 33471, "s": 33170, "text": "random_state variable is a pseudo-random number generator state used for random sampling.Terms used in code :Gini index and information gain both of these methods are used to select from the n attributes of the dataset which attribute would be placed at the root node or the internal node.Gini index:" }, { "code": null, "e": 33652, "s": 33471, "text": "Gini index and information gain both of these methods are used to select from the n attributes of the dataset which attribute would be placed at the root node or the internal node." }, { "code": null, "e": 33664, "s": 33652, "text": "Gini index:" }, { "code": null, "e": 33767, "s": 33664, "text": "Gini Index is a metric to measure how often a randomly chosen element would be incorrectly identified." }, { "code": null, "e": 33832, "s": 33767, "text": "It means an attribute with lower gini index should be preferred." }, { "code": null, "e": 33931, "s": 33832, "text": "Sklearn supports “gini” criteria for Gini Index and by default, it takes “gini” value.Entropy: " }, { "code": null, "e": 33940, "s": 33931, "text": "Entropy:" }, { "code": null, "e": 34148, "s": 33945, "text": "Entropy is the measure of uncertainty of a random variable, it characterizes the impurity of an arbitrary collection of examples. The higher the entropy the more the information content.Information Gain" }, { "code": null, "e": 34165, "s": 34148, "text": "Information Gain" }, { "code": null, "e": 34348, "s": 34165, "text": "The entropy typically changes when we use a node in a decision tree to partition the training instances into smaller subsets. Information gain is a measure of this change in entropy." }, { "code": null, "e": 34515, "s": 34348, "text": "Sklearn supports “entropy” criteria for Information Gain and if we want to use Information Gain method in sklearn then we have to mention it explicitly.Accuracy score" }, { "code": null, "e": 34530, "s": 34515, "text": "Accuracy score" }, { "code": null, "e": 34622, "s": 34530, "text": "Accuracy score is used to calculate the accuracy of the trained classifier.Confusion Matrix" }, { "code": null, "e": 34639, "s": 34622, "text": "Confusion Matrix" }, { "code": null, "e": 40563, "s": 34639, "text": "Confusion Matrix is used to understand the trained classifier behavior over the test dataset or validate dataset.Recommended: Please try your approach on {IDE} first, before moving on to the solution.Below is the python code for the decision tree.# Run this program on your local python# interpreter, provided you have installed# the required libraries. # Importing the required packagesimport numpy as npimport pandas as pdfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report # Function importing Datasetdef importdata(): balance_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-'+'databases/balance-scale/balance-scale.data', sep= ',', header = None) # Printing the dataswet shape print (\"Dataset Length: \", len(balance_data)) print (\"Dataset Shape: \", balance_data.shape) # Printing the dataset obseravtions print (\"Dataset: \",balance_data.head()) return balance_data # Function to split the datasetdef splitdataset(balance_data): # Separating the target variable X = balance_data.values[:, 1:5] Y = balance_data.values[:, 0] # Splitting the dataset into train and test X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = 0.3, random_state = 100) return X, Y, X_train, X_test, y_train, y_test # Function to perform training with giniIndex.def train_using_gini(X_train, X_test, y_train): # Creating the classifier object clf_gini = DecisionTreeClassifier(criterion = \"gini\", random_state = 100,max_depth=3, min_samples_leaf=5) # Performing training clf_gini.fit(X_train, y_train) return clf_gini # Function to perform training with entropy.def tarin_using_entropy(X_train, X_test, y_train): # Decision tree with entropy clf_entropy = DecisionTreeClassifier( criterion = \"entropy\", random_state = 100, max_depth = 3, min_samples_leaf = 5) # Performing training clf_entropy.fit(X_train, y_train) return clf_entropy # Function to make predictionsdef prediction(X_test, clf_object): # Predicton on test with giniIndex y_pred = clf_object.predict(X_test) print(\"Predicted values:\") print(y_pred) return y_pred # Function to calculate accuracydef cal_accuracy(y_test, y_pred): print(\"Confusion Matrix: \", confusion_matrix(y_test, y_pred)) print (\"Accuracy : \", accuracy_score(y_test,y_pred)*100) print(\"Report : \", classification_report(y_test, y_pred)) # Driver codedef main(): # Building Phase data = importdata() X, Y, X_train, X_test, y_train, y_test = splitdataset(data) clf_gini = train_using_gini(X_train, X_test, y_train) clf_entropy = tarin_using_entropy(X_train, X_test, y_train) # Operational Phase print(\"Results Using Gini Index:\") # Prediction using gini y_pred_gini = prediction(X_test, clf_gini) cal_accuracy(y_test, y_pred_gini) print(\"Results Using Entropy:\") # Prediction using entropy y_pred_entropy = prediction(X_test, clf_entropy) cal_accuracy(y_test, y_pred_entropy) # Calling main functionif __name__==\"__main__\": main()Data Infomation:\nDataset Length: 625\nDataset Shape: (625, 5)\nDataset: 0 1 2 3 4\n0 B 1 1 1 1\n1 R 1 1 1 2\n2 R 1 1 1 3\n3 R 1 1 1 4\n4 R 1 1 1 5\nResults Using Gini Index:\nPredicted values:\n['R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'L'\n 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L'\n 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'L' 'R'\n 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L'\n 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L'\n 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R'\n 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R'\n 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R'\n 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'R']\n\nConfusion Matrix: [[ 0 6 7]\n [ 0 67 18]\n [ 0 19 71]]\nAccuracy : 73.4042553191\nReport : \n precision recall f1-score support\n B 0.00 0.00 0.00 13\n L 0.73 0.79 0.76 85\n R 0.74 0.79 0.76 90\navg/total 0.68 0.73 0.71 188\n\nResults Using Entropy:\nPredicted values:\n['R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L'\n 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L'\n 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L'\n 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L'\n 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'R' 'R' 'R' 'R' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L'\n 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R'\n 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'R'\n 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'R']\n\nConfusion Matrix: [[ 0 6 7]\n [ 0 63 22]\n [ 0 20 70]]\nAccuracy : 70.7446808511\nReport : \n precision recall f1-score support\n B 0.00 0.00 0.00 13\n L 0.71 0.74 0.72 85\n R 0.71 0.78 0.74 90\navg / total 0.66 0.71 0.68 188My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 40611, "s": 40563, "text": "Below is the python code for the decision tree." }, { "code": "# Run this program on your local python# interpreter, provided you have installed# the required libraries. # Importing the required packagesimport numpy as npimport pandas as pdfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report # Function importing Datasetdef importdata(): balance_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-'+'databases/balance-scale/balance-scale.data', sep= ',', header = None) # Printing the dataswet shape print (\"Dataset Length: \", len(balance_data)) print (\"Dataset Shape: \", balance_data.shape) # Printing the dataset obseravtions print (\"Dataset: \",balance_data.head()) return balance_data # Function to split the datasetdef splitdataset(balance_data): # Separating the target variable X = balance_data.values[:, 1:5] Y = balance_data.values[:, 0] # Splitting the dataset into train and test X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = 0.3, random_state = 100) return X, Y, X_train, X_test, y_train, y_test # Function to perform training with giniIndex.def train_using_gini(X_train, X_test, y_train): # Creating the classifier object clf_gini = DecisionTreeClassifier(criterion = \"gini\", random_state = 100,max_depth=3, min_samples_leaf=5) # Performing training clf_gini.fit(X_train, y_train) return clf_gini # Function to perform training with entropy.def tarin_using_entropy(X_train, X_test, y_train): # Decision tree with entropy clf_entropy = DecisionTreeClassifier( criterion = \"entropy\", random_state = 100, max_depth = 3, min_samples_leaf = 5) # Performing training clf_entropy.fit(X_train, y_train) return clf_entropy # Function to make predictionsdef prediction(X_test, clf_object): # Predicton on test with giniIndex y_pred = clf_object.predict(X_test) print(\"Predicted values:\") print(y_pred) return y_pred # Function to calculate accuracydef cal_accuracy(y_test, y_pred): print(\"Confusion Matrix: \", confusion_matrix(y_test, y_pred)) print (\"Accuracy : \", accuracy_score(y_test,y_pred)*100) print(\"Report : \", classification_report(y_test, y_pred)) # Driver codedef main(): # Building Phase data = importdata() X, Y, X_train, X_test, y_train, y_test = splitdataset(data) clf_gini = train_using_gini(X_train, X_test, y_train) clf_entropy = tarin_using_entropy(X_train, X_test, y_train) # Operational Phase print(\"Results Using Gini Index:\") # Prediction using gini y_pred_gini = prediction(X_test, clf_gini) cal_accuracy(y_test, y_pred_gini) print(\"Results Using Entropy:\") # Prediction using entropy y_pred_entropy = prediction(X_test, clf_entropy) cal_accuracy(y_test, y_pred_entropy) # Calling main functionif __name__==\"__main__\": main()", "e": 43724, "s": 40611, "text": null }, { "code": null, "e": 46254, "s": 43724, "text": "Data Infomation:\nDataset Length: 625\nDataset Shape: (625, 5)\nDataset: 0 1 2 3 4\n0 B 1 1 1 1\n1 R 1 1 1 2\n2 R 1 1 1 3\n3 R 1 1 1 4\n4 R 1 1 1 5\nResults Using Gini Index:\nPredicted values:\n['R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'L'\n 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'L'\n 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'L' 'R'\n 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L'\n 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L'\n 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R'\n 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R'\n 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R'\n 'L' 'R' 'R' 'L' 'L' 'R' 'R' 'R']\n\nConfusion Matrix: [[ 0 6 7]\n [ 0 67 18]\n [ 0 19 71]]\nAccuracy : 73.4042553191\nReport : \n precision recall f1-score support\n B 0.00 0.00 0.00 13\n L 0.73 0.79 0.76 85\n R 0.74 0.79 0.76 90\navg/total 0.68 0.73 0.71 188\n\nResults Using Entropy:\nPredicted values:\n['R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L'\n 'L' 'R' 'L' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L'\n 'L' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L'\n 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'L' 'R' 'L' 'L' 'L' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'R' 'R' 'L' 'R' 'L'\n 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'L' 'L' 'L' 'R' 'L' 'L' 'R' 'R' 'R' 'R' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L'\n 'L' 'L' 'L' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'L' 'R'\n 'L' 'R' 'R' 'L' 'L' 'R' 'L' 'R' 'R' 'R' 'R' 'R' 'L' 'R' 'R' 'R' 'R' 'R'\n 'R' 'L' 'R' 'L' 'R' 'R' 'L' 'R' 'L' 'R' 'L' 'R' 'L' 'L' 'L' 'L' 'L' 'R'\n 'R' 'R' 'L' 'L' 'L' 'R' 'R' 'R']\n\nConfusion Matrix: [[ 0 6 7]\n [ 0 63 22]\n [ 0 20 70]]\nAccuracy : 70.7446808511\nReport : \n precision recall f1-score support\n B 0.00 0.00 0.00 13\n L 0.71 0.74 0.72 85\n R 0.71 0.78 0.74 90\navg / total 0.66 0.71 0.68 188" }, { "code": null, "e": 46271, "s": 46254, "text": "Data Infomation:" }, { "code": null, "e": 46297, "s": 46271, "text": "Results Using Gini Index:" }, { "code": null, "e": 46320, "s": 46297, "text": "Results Using Entropy:" }, { "code": null, "e": 46334, "s": 46320, "text": "shubham_singh" }, { "code": null, "e": 46344, "s": 46334, "text": "knbarnwal" }, { "code": null, "e": 46357, "s": 46344, "text": "khyatichat23" }, { "code": null, "e": 46383, "s": 46357, "text": "Advanced Computer Subject" }, { "code": null, "e": 46400, "s": 46383, "text": "Machine Learning" }, { "code": null, "e": 46419, "s": 46400, "text": "Technical Scripter" }, { "code": null, "e": 46436, "s": 46419, "text": "Machine Learning" }, { "code": null, "e": 46534, "s": 46436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46557, "s": 46534, "text": "System Design Tutorial" }, { "code": null, "e": 46601, "s": 46557, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 46635, "s": 46601, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 46666, "s": 46635, "text": "Clustering in Machine Learning" }, { "code": null, "e": 46692, "s": 46666, "text": "Docker - COPY Instruction" }, { "code": null, "e": 46726, "s": 46692, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 46766, "s": 46726, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 46807, "s": 46766, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 46840, "s": 46807, "text": "Support Vector Machine Algorithm" } ]
Sum of all the levels in a Binary Search Tree - GeeksforGeeks
02 Nov, 2021 Given a Binary Search Tree, the task is to find the horizontal sum of the nodes that are in the same level.Examples: Input: Output: 6 12 24Input: Output: 6 12 12 Approach: Find the height of the given binary tree then the number of levels in the tree will be levels = height + 1. Now create an array sum[] of size levels where sum[i] will store the sum of all the nodes at the ith level. In order to update this array, write a recursive function that add the current node’s data at sum[level] where level is the level of the current node and then recursively call the same method for the child nodes with level as level + 1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>#include <queue>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << endl;} // Function to return the height// of the binary treeint getHeight(Node* root){ if (root->left == NULL && root->right == NULL) return 0; int left = 0; if (root->left != NULL) left = getHeight(root->left); int right = 0; if (root->right != NULL) right = getHeight(root->right); return (max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelvoid calculateLevelSum(Node* node, int level, int sum[]){ if (node == NULL) return; // Add current node data to the sum // of the current node's level sum[level] += node->data; // Recursive call for left and right sub-tree calculateLevelSum(node->left, level + 1, sum); calculateLevelSum(node->right, level + 1, sum);} // Driver codeint main(){ // Create the binary tree Node* root = newNode(6); root->left = newNode(4); root->right = newNode(8); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(7); root->right->right = newNode(9); // Count of levels in the // given binary tree int levels = getHeight(root) + 1; // To store the sum at every level int sum[levels] = { 0 }; calculateLevelSum(root, 0, sum); // Print the required sums printArr(sum, levels); return 0;} // Java implementation of the approachclass Sol{ // A Binary Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i]+ " " );} // Function to return the height// of the binary treestatic int getHeight(Node root){ if (root.left == null && root.right == null) return 0; int left = 0; if (root.left != null) left = getHeight(root.left); int right = 0; if (root.right != null) right = getHeight(root.right); return (Math.max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelstatic void calculateLevelSum(Node node, int level, int sum[]){ if (node == null) return; // Add current node data to the sum // of the current node's level sum[level] += node.data; // Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum);} // Driver codepublic static void main(String args[]){ // Create the binary tree Node root = newNode(6); root.left = newNode(4); root.right = newNode(8); root.left.left = newNode(3); root.left.right = newNode(5); root.right.left = newNode(7); root.right.right = newNode(9); // Count of levels in the // given binary tree int levels = getHeight(root) + 1; // To store the sum at every level int sum[]=new int[levels]; calculateLevelSum(root, 0, sum); // Print the required sums printArr(sum, levels);}} // This code is contributed by andrew1234 # Python3 implementation of above algorithm # Utility class to create a nodeclass Node: def __init__(self, key): self.data = key self.left = self.right = None # Utility function to create a tree nodedef newNode( data): temp = Node(0) temp.data = data temp.left = temp.right = None return temp # Utility function to print# the contents of an arraydef printArr(arr, n): i = 0 while ( i < n): print( arr[i]) i = i + 1 # Function to return the height# of the binary treedef getHeight(root): if (root.left == None and root.right == None): return 0 left = 0 if (root.left != None): left = getHeight(root.left) right = 0 if (root.right != None): right = getHeight(root.right) return (max(left, right) + 1) sum = [] # Recursive function to update sum[] array# such that sum[i] stores the sum# of all the elements at ith leveldef calculateLevelSum(node, level): global sum if (node == None): return # Add current node data to the sum # of the current node's level sum[level] += node.data # Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1) calculateLevelSum(node.right, level + 1) # Driver code # Create the binary treeroot = newNode(6)root.left = newNode(4)root.right = newNode(8)root.left.left = newNode(3)root.left.right = newNode(5)root.right.left = newNode(7)root.right.right = newNode(9) # Count of levels in the# given binary treelevels = getHeight(root) + 1 # To store the sum at every levelsum = [0] * levelscalculateLevelSum(root, 0) # Print the required sumsprintArr(sum, levels) # This code is contributed by Arnab Kundu // C# implementation of the approachusing System;class GFG{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.WriteLine(arr[i]);} // Function to return the height// of the binary treestatic int getHeight(Node root){ if (root.left == null && root.right == null) return 0; int left = 0; if (root.left != null) left = getHeight(root.left); int right = 0; if (root.right != null) right = getHeight(root.right); return (Math.Max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelstatic void calculateLevelSum(Node node, int level, int []sum){ if (node == null) return; // Add current node data to the sum // of the current node's level sum[level] += node.data; // Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum);} // Driver codepublic static void Main(String []args){ // Create the binary tree Node root = newNode(6); root.left = newNode(4); root.right = newNode(8); root.left.left = newNode(3); root.left.right = newNode(5); root.right.left = newNode(7); root.right.right = newNode(9); // Count of levels in the // given binary tree int levels = getHeight(root) + 1; // To store the sum at every level int []sum = new int[levels]; calculateLevelSum(root, 0, sum); // Print the required sums printArr(sum, levels);}} // This code is contributed by 29AjayKumar <script>// Javascript implementation of the approach // A Binary Tree Nodeclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i]+ " <br>" );} // Function to return the height// of the binary treefunction getHeight(root){ if (root.left == null && root.right == null) return 0; let left = 0; if (root.left != null) left = getHeight(root.left); let right = 0; if (root.right != null) right = getHeight(root.right); return (Math.max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelfunction calculateLevelSum(node,level,sum){ if (node == null) return; // Add current node data to the sum // of the current node's level sum[level] += node.data; // Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum); } // Driver code// Create the binary treelet root = new Node(6);root.left = new Node(4);root.right = new Node(8);root.left.left = new Node(3);root.left.right = new Node(5);root.right.left = new Node(7);root.right.right = new Node(9); // Count of levels in the// given binary treelet levels = getHeight(root) + 1; // To store the sum at every levellet sum=new Array(levels);for(let i = 0; i < levels; i++) sum[i] = 0; calculateLevelSum(root, 0, sum); // Print the required sumsprintArr(sum, levels); // This code is contributed by avanitrachhadiya2155</script> 6 12 24 Time Complexity : O(N)Auxiliary Space: O(N) andrew1234 29AjayKumar pankajsharmagfg avanitrachhadiya2155 gabaa406 amartyaghoshgfg Arrays Binary Search Tree Data Structures Data Structures Arrays Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Construct BST from given preorder traversal | Set 1
[ { "code": null, "e": 26065, "s": 26037, "text": "\n02 Nov, 2021" }, { "code": null, "e": 26184, "s": 26065, "text": "Given a Binary Search Tree, the task is to find the horizontal sum of the nodes that are in the same level.Examples: " }, { "code": null, "e": 26193, "s": 26184, "text": "Input: " }, { "code": null, "e": 26217, "s": 26193, "text": "Output: 6 12 24Input: " }, { "code": null, "e": 26235, "s": 26217, "text": "Output: 6 12 12 " }, { "code": null, "e": 26752, "s": 26237, "text": "Approach: Find the height of the given binary tree then the number of levels in the tree will be levels = height + 1. Now create an array sum[] of size levels where sum[i] will store the sum of all the nodes at the ith level. In order to update this array, write a recursive function that add the current node’s data at sum[level] where level is the level of the current node and then recursively call the same method for the child nodes with level as level + 1.Below is the implementation of the above approach: " }, { "code": null, "e": 26756, "s": 26752, "text": "C++" }, { "code": null, "e": 26761, "s": 26756, "text": "Java" }, { "code": null, "e": 26769, "s": 26761, "text": "Python3" }, { "code": null, "e": 26772, "s": 26769, "text": "C#" }, { "code": null, "e": 26783, "s": 26772, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>#include <queue>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << endl;} // Function to return the height// of the binary treeint getHeight(Node* root){ if (root->left == NULL && root->right == NULL) return 0; int left = 0; if (root->left != NULL) left = getHeight(root->left); int right = 0; if (root->right != NULL) right = getHeight(root->right); return (max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelvoid calculateLevelSum(Node* node, int level, int sum[]){ if (node == NULL) return; // Add current node data to the sum // of the current node's level sum[level] += node->data; // Recursive call for left and right sub-tree calculateLevelSum(node->left, level + 1, sum); calculateLevelSum(node->right, level + 1, sum);} // Driver codeint main(){ // Create the binary tree Node* root = newNode(6); root->left = newNode(4); root->right = newNode(8); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(7); root->right->right = newNode(9); // Count of levels in the // given binary tree int levels = getHeight(root) + 1; // To store the sum at every level int sum[levels] = { 0 }; calculateLevelSum(root, 0, sum); // Print the required sums printArr(sum, levels); return 0;}", "e": 28636, "s": 26783, "text": null }, { "code": "// Java implementation of the approachclass Sol{ // A Binary Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i]+ \" \" );} // Function to return the height// of the binary treestatic int getHeight(Node root){ if (root.left == null && root.right == null) return 0; int left = 0; if (root.left != null) left = getHeight(root.left); int right = 0; if (root.right != null) right = getHeight(root.right); return (Math.max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelstatic void calculateLevelSum(Node node, int level, int sum[]){ if (node == null) return; // Add current node data to the sum // of the current node's level sum[level] += node.data; // Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum);} // Driver codepublic static void main(String args[]){ // Create the binary tree Node root = newNode(6); root.left = newNode(4); root.right = newNode(8); root.left.left = newNode(3); root.left.right = newNode(5); root.right.left = newNode(7); root.right.right = newNode(9); // Count of levels in the // given binary tree int levels = getHeight(root) + 1; // To store the sum at every level int sum[]=new int[levels]; calculateLevelSum(root, 0, sum); // Print the required sums printArr(sum, levels);}} // This code is contributed by andrew1234", "e": 30520, "s": 28636, "text": null }, { "code": "# Python3 implementation of above algorithm # Utility class to create a nodeclass Node: def __init__(self, key): self.data = key self.left = self.right = None # Utility function to create a tree nodedef newNode( data): temp = Node(0) temp.data = data temp.left = temp.right = None return temp # Utility function to print# the contents of an arraydef printArr(arr, n): i = 0 while ( i < n): print( arr[i]) i = i + 1 # Function to return the height# of the binary treedef getHeight(root): if (root.left == None and root.right == None): return 0 left = 0 if (root.left != None): left = getHeight(root.left) right = 0 if (root.right != None): right = getHeight(root.right) return (max(left, right) + 1) sum = [] # Recursive function to update sum[] array# such that sum[i] stores the sum# of all the elements at ith leveldef calculateLevelSum(node, level): global sum if (node == None): return # Add current node data to the sum # of the current node's level sum[level] += node.data # Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1) calculateLevelSum(node.right, level + 1) # Driver code # Create the binary treeroot = newNode(6)root.left = newNode(4)root.right = newNode(8)root.left.left = newNode(3)root.left.right = newNode(5)root.right.left = newNode(7)root.right.right = newNode(9) # Count of levels in the# given binary treelevels = getHeight(root) + 1 # To store the sum at every levelsum = [0] * levelscalculateLevelSum(root, 0) # Print the required sumsprintArr(sum, levels) # This code is contributed by Arnab Kundu", "e": 32218, "s": 30520, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.WriteLine(arr[i]);} // Function to return the height// of the binary treestatic int getHeight(Node root){ if (root.left == null && root.right == null) return 0; int left = 0; if (root.left != null) left = getHeight(root.left); int right = 0; if (root.right != null) right = getHeight(root.right); return (Math.Max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelstatic void calculateLevelSum(Node node, int level, int []sum){ if (node == null) return; // Add current node data to the sum // of the current node's level sum[level] += node.data; // Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum);} // Driver codepublic static void Main(String []args){ // Create the binary tree Node root = newNode(6); root.left = newNode(4); root.right = newNode(8); root.left.left = newNode(3); root.left.right = newNode(5); root.right.left = newNode(7); root.right.right = newNode(9); // Count of levels in the // given binary tree int levels = getHeight(root) + 1; // To store the sum at every level int []sum = new int[levels]; calculateLevelSum(root, 0, sum); // Print the required sums printArr(sum, levels);}} // This code is contributed by 29AjayKumar", "e": 34172, "s": 32218, "text": null }, { "code": "<script>// Javascript implementation of the approach // A Binary Tree Nodeclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i]+ \" <br>\" );} // Function to return the height// of the binary treefunction getHeight(root){ if (root.left == null && root.right == null) return 0; let left = 0; if (root.left != null) left = getHeight(root.left); let right = 0; if (root.right != null) right = getHeight(root.right); return (Math.max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelfunction calculateLevelSum(node,level,sum){ if (node == null) return; // Add current node data to the sum // of the current node's level sum[level] += node.data; // Recursive call for left and right sub-tree calculateLevelSum(node.left, level + 1, sum); calculateLevelSum(node.right, level + 1, sum); } // Driver code// Create the binary treelet root = new Node(6);root.left = new Node(4);root.right = new Node(8);root.left.left = new Node(3);root.left.right = new Node(5);root.right.left = new Node(7);root.right.right = new Node(9); // Count of levels in the// given binary treelet levels = getHeight(root) + 1; // To store the sum at every levellet sum=new Array(levels);for(let i = 0; i < levels; i++) sum[i] = 0; calculateLevelSum(root, 0, sum); // Print the required sumsprintArr(sum, levels); // This code is contributed by avanitrachhadiya2155</script>", "e": 35870, "s": 34172, "text": null }, { "code": null, "e": 35878, "s": 35870, "text": "6\n12\n24" }, { "code": null, "e": 35925, "s": 35880, "text": "Time Complexity : O(N)Auxiliary Space: O(N) " }, { "code": null, "e": 35936, "s": 35925, "text": "andrew1234" }, { "code": null, "e": 35948, "s": 35936, "text": "29AjayKumar" }, { "code": null, "e": 35964, "s": 35948, "text": "pankajsharmagfg" }, { "code": null, "e": 35985, "s": 35964, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35994, "s": 35985, "text": "gabaa406" }, { "code": null, "e": 36010, "s": 35994, "text": "amartyaghoshgfg" }, { "code": null, "e": 36017, "s": 36010, "text": "Arrays" }, { "code": null, "e": 36036, "s": 36017, "text": "Binary Search Tree" }, { "code": null, "e": 36052, "s": 36036, "text": "Data Structures" }, { "code": null, "e": 36068, "s": 36052, "text": "Data Structures" }, { "code": null, "e": 36075, "s": 36068, "text": "Arrays" }, { "code": null, "e": 36094, "s": 36075, "text": "Binary Search Tree" }, { "code": null, "e": 36192, "s": 36094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36219, "s": 36192, "text": "Count pairs with given sum" }, { "code": null, "e": 36250, "s": 36219, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36275, "s": 36250, "text": "Window Sliding Technique" }, { "code": null, "e": 36313, "s": 36275, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36334, "s": 36313, "text": "Next Greater Element" }, { "code": null, "e": 36384, "s": 36334, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 36413, "s": 36384, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 36449, "s": 36413, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 36499, "s": 36449, "text": "A program to check if a binary tree is BST or not" } ]
How to use Array.BinarySearch() Method in C# | Set -1 - GeeksforGeeks
29 May, 2021 Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Important Points: Before calling this method, the array must be sorted. This method will return the negative integer if the array doesn’t contain the specified value. The array must be one-dimensional otherwise this method can’t be used. The Icomparable interface must be implemented by the value or every element of the array. The method will return the index of only one of the occurrences if more than one matched elements found in the array and it is not necessary that index will be of the first occurrence. There are total 8 methods in the overload list of this method as follows: BinarySearch(Array, Object) BinarySearch(Array, Object, IComparer) BinarySearch(Array, Int32, Int32, Object) BinarySearch(Array, Int32, Int32, Object, IComparer) BinarySearch<T>(T[], T) BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) This method is used to search a specific element in the entire 1-D sorted array. It used the IComparable interface that is implemented by each element of the 1-D array and the specified object. This method is an O(log n) operation, where n is the Length of the specified array. Syntax: public static int BinarySearch (Array arr, object val);Parameters: arr: It is the sorted 1-D array to search. val: It is the object to search for. Return Value: It returns the index of the specified valin the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows: If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val. If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1). If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr. Exceptions: ArgumentNullException: If the arr is null. RankException: If the arr is multidimensional. ArgumentException: If the val is of a type which is not compatible with the elements of the arr. InvalidOperationException: If the val does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface. Below programs illustrate the above-discussed method: Example 1: C# // C# program to illustrate the// Array.BinarySearch(Array, Object)// Methodusing System; class GFG { // Main Method public static void Main(String[] args) { // taking an 1-D Array int[] arr = new int[7] { 1, 5, 7, 4, 6, 2, 3 }; // for this method array // must be sorted Array.Sort(arr); Console.Write("The elements of Sorted Array: "); // calling the method to // print the values display(arr); // taking the element which is // to search for in a variable // It is not present in the array object s = 8; // calling the method containing // BinarySearch method result(arr, s); // taking the element which is // to search for in a variable // It is present in the array object s1 = 4; // calling the method containing // BinarySearch method result(arr, s1); } // containing BinarySearch Method static void result(int[] arr2, object k) { // using the method int res = Array.BinarySearch(arr2, k); if (res < 0) { Console.WriteLine("\nThe element to search for " + "({0}) is not found.", k); } else { Console.WriteLine("The element to search for " + "({0}) is at index {1}.", k, res); } } // display method static void display(int[] arr1) { // Displaying Elements of array foreach(int i in arr1) Console.Write(i + " "); }} The elements of Sorted Array: 1 2 3 4 5 6 7 The element to search for (8) is not found. The element to search for (4) is at index 3. Example 2: C# // C# program to illustrate the// Array.BinarySearch(Array, Object)// Methodusing System; class GFG { // Main Method public static void Main(String[] args) { // taking an 1-D Array int[] arr = new int[7] { 1, 5, 7, 4, 6, 2, 3 }; // for this method array // must be sorted Array.Sort(arr); Console.Write("The elements of Sorted Array: "); // calling the method to // print the values display(arr); // it will return a negative value as // 9 is not present in the array Console.WriteLine("\nIndex of 9 is: " + Array.BinarySearch(arr, 8)); } // display method static void display(int[] arr1) { // Displaying Elements of array foreach(int i in arr1) Console.Write(i + " "); }} The elements of Sorted Array: 1 2 3 4 5 6 7 Index of 9 is: -8 This method is used to search a specific element in the entire 1-D sorted array using the specified IComparer interface. Syntax: public static int BinarySearch(Array arr, Object val, IComparer comparer)Parameters: arr : The one-dimensional sorted array in which the search will happen. val : The object value which is to search for. comparer : When comparing elements then the IComparer implementation is used. Return Value: It returns the index of the specified val in the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows: If the val is not found and val is less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val. If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1). If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr. Exceptions: ArgumentNullException: If the arr is null. RankException: If arr is multidimensional. ArgumentException: If the range is less than lower bound OR length is less than 0. ArgumentException: If the comparer is null, and value is of a type that is not compatible with the elements of arr. InvalidOperationException: If the comparer is null, value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface. Example: C# // C# program to demonstrate the// Array.BinarySearch(Array,// Object, IComparer) Methodusing System; class GFG { // Main Method public static void Main() { // initializes a new Array. Array arr = Array.CreateInstance(typeof(Int32), 5); // Array elements arr.SetValue(20, 0); arr.SetValue(10, 1); arr.SetValue(30, 2); arr.SetValue(40, 3); arr.SetValue(50, 4); Console.WriteLine("The original Array"); // calling "display" function display(arr); Console.WriteLine("\nsorted array"); // sorting the Array Array.Sort(arr); display(arr); Console.WriteLine("\n1st call"); // search for object 10 object obj1 = 10; // call the "FindObj" function FindObj(arr, obj1); Console.WriteLine("\n2nd call"); object obj2 = 60; FindObj(arr, obj2); } // find object method public static void FindObj(Array Arr, object Obj) { int index = Array.BinarySearch(Arr, Obj, StringComparer.CurrentCulture); if (index < 0) { Console.WriteLine("The object {0} is not found\nNext" + " larger object is at index {1}", Obj, ~index); } else { Console.WriteLine("The object {0} is at index {1}", Obj, index); } } // display method public static void display(Array arr) { foreach(int g in arr) { Console.WriteLine(g); } }} The original Array 20 10 30 40 50 sorted array 10 20 30 40 50 1st call The object 10 is at index 0 2nd call The object 60 is not found Next larger object is at index 5 This method is used to search a value in the range of elements in a 1-D sorted array. It uses the IComparable interface implemented by each element of the array and the specified value. It searches only in a specified boundary which is defined by the user. Syntax: public static int BinarySearch(Array arr, int i, int len, object val);Parameters: arr: It is 1-D array in which the user have to search for an element. i: It is the starting index of the range from where the user want to start the search. len: It is the length of the range in which the user want to search. val: It is the value which the user to search for. Return Value: It returns the index of the specified val in the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows: If the val is not found and val is less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val. If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1). If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr. Exceptions: ArgumentNullException: If the arr is null. RankException: If arr is multidimensional. ArgumentOutOfRangeException: If the index is less than lower bound of array OR length is less than 0. ArgumentException: If the index and length do not specify the valid range in array OR the value is of the type which is not compatible with the elements of the array. InvalidOperationException: If value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface. Example: C# // C# Program to illustrate the use of// Array.BinarySearch(Array, Int32,// Int32, Object) Methodusing System;using System.IO; class GFG { // Main Method static void Main() { // initializing the integer array int[] intArr = { 42, 5, 7, 12, 56, 1, 32 }; // sorts the intArray as it must be // sorted before using method Array.Sort(intArr); // printing the sorted array foreach(int i in intArr) Console.Write(i + " " + "\n"); // intArr is the array we want to find // and 1 is the starting index // of the range to search. 5 is the // length of the range to search. // 32 is the object to search int index = Array.BinarySearch(intArr, 1, 5, 32); if (index >= 0) { // if the element is found it // returns the index of the element Console.WriteLine("Index of 32 is : " + index); } else { // if the element is not // present in the array or // if it is not in the // specified range it prints this Console.Write("Element is not found"); } // intArr is the array we want to // find. and 1 is the starting // index of the range to search. 5 is // the length of the range to search // 44 is the object to search int index1 = Array.BinarySearch(intArr, 1, 5, 44); // as the element is not present // it prints a negative value. Console.WriteLine("Index of 44 is :" + index1); }} 1 5 7 12 32 42 56 Index of 32 is : 4 Index of 44 is :-7 This method is used to search a value in the range of elements in a 1-D sorted array using a specified IComparer interface. Syntax: public static int BinarySearch(Array arr, int index, int length, Object value, IComparer comparer)Parameters: arr : The sorted one-dimensional Array which is to be searched. index : The starting index of the range from which searching will start. length : The length of the range in which the search will happen. value : The object to search for. comparer : When comparing elements then use the IComparer implementation. Return Value: It returns the index of the specified value in the specified arr, if the value is found otherwise it returns a negative number. There are different cases of return values as follows: If the value is not found and value is less than one or more elements in the array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. If the value is not found and value is greater than all elements in the array, the negative number returned is the bitwise complement of (the index of the last element plus 1). If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the value is present in the array. Example: In this example, here we use “CreateInstance()” method to create a typed array and stores some integer value and search some values after sort the array. C# // C# program to demonstrate the// Array.BinarySearch(Array,// Int32, Int32, Object,// IComparer) Methodusing System; class GFG { // Main Method public static void Main() { // initializes a new Array. Array arr = Array.CreateInstance(typeof(Int32), 8); // Array elements arr.SetValue(20, 0); arr.SetValue(10, 1); arr.SetValue(30, 2); arr.SetValue(40, 3); arr.SetValue(50, 4); arr.SetValue(80, 5); arr.SetValue(70, 6); arr.SetValue(60, 7); Console.WriteLine("The original Array"); // calling "display" function display(arr); Console.WriteLine("\nsorted array"); // sorting the Array Array.Sort(arr); display(arr); Console.WriteLine("\n1st call"); // search for object 10 object obj1 = 10; // call the "FindObj" function FindObj(arr, obj1); Console.WriteLine("\n2nd call"); object obj2 = 60; FindObj(arr, obj2); } // find object method public static void FindObj(Array Arr, object Obj) { int index = Array.BinarySearch(Arr, 1, 4, Obj, StringComparer.CurrentCulture); if (index < 0) { Console.WriteLine("The object {0} is not found\n" + "Next larger object is at index {1}", Obj, ~index); } else { Console.WriteLine("The object {0} is at " + "index {1}", Obj, index); } } // display method public static void display(Array arr) { foreach(int g in arr) { Console.WriteLine(g); } }} The original Array 20 10 30 40 50 80 70 60 sorted array 10 20 30 40 50 60 70 80 1st call The object 10 is not found Next larger object is at index 1 2nd call The object 60 is not found Next larger object is at index 5 arorakashish0911 CSharp-Arrays CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 26337, "s": 26309, "text": "\n29 May, 2021" }, { "code": null, "e": 26849, "s": 26337, "text": "Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty." }, { "code": null, "e": 26867, "s": 26849, "text": "Important Points:" }, { "code": null, "e": 26921, "s": 26867, "text": "Before calling this method, the array must be sorted." }, { "code": null, "e": 27016, "s": 26921, "text": "This method will return the negative integer if the array doesn’t contain the specified value." }, { "code": null, "e": 27087, "s": 27016, "text": "The array must be one-dimensional otherwise this method can’t be used." }, { "code": null, "e": 27177, "s": 27087, "text": "The Icomparable interface must be implemented by the value or every element of the array." }, { "code": null, "e": 27362, "s": 27177, "text": "The method will return the index of only one of the occurrences if more than one matched elements found in the array and it is not necessary that index will be of the first occurrence." }, { "code": null, "e": 27436, "s": 27362, "text": "There are total 8 methods in the overload list of this method as follows:" }, { "code": null, "e": 27464, "s": 27436, "text": "BinarySearch(Array, Object)" }, { "code": null, "e": 27503, "s": 27464, "text": "BinarySearch(Array, Object, IComparer)" }, { "code": null, "e": 27545, "s": 27503, "text": "BinarySearch(Array, Int32, Int32, Object)" }, { "code": null, "e": 27598, "s": 27545, "text": "BinarySearch(Array, Int32, Int32, Object, IComparer)" }, { "code": null, "e": 27622, "s": 27598, "text": "BinarySearch<T>(T[], T)" }, { "code": null, "e": 27660, "s": 27622, "text": "BinarySearch<T>(T[], T, IComparer<T>)" }, { "code": null, "e": 27698, "s": 27660, "text": "BinarySearch<T>(T[], Int32, Int32, T)" }, { "code": null, "e": 27750, "s": 27698, "text": "BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)" }, { "code": null, "e": 28029, "s": 27750, "text": "This method is used to search a specific element in the entire 1-D sorted array. It used the IComparable interface that is implemented by each element of the 1-D array and the specified object. This method is an O(log n) operation, where n is the Length of the specified array. " }, { "code": null, "e": 28186, "s": 28029, "text": "Syntax: public static int BinarySearch (Array arr, object val);Parameters: arr: It is the sorted 1-D array to search. val: It is the object to search for. " }, { "code": null, "e": 28377, "s": 28186, "text": "Return Value: It returns the index of the specified valin the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows:" }, { "code": null, "e": 28568, "s": 28377, "text": "If the val is not found and valis less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val." }, { "code": null, "e": 28739, "s": 28568, "text": "If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1)." }, { "code": null, "e": 28903, "s": 28739, "text": "If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr." }, { "code": null, "e": 28916, "s": 28903, "text": "Exceptions: " }, { "code": null, "e": 28959, "s": 28916, "text": "ArgumentNullException: If the arr is null." }, { "code": null, "e": 29006, "s": 28959, "text": "RankException: If the arr is multidimensional." }, { "code": null, "e": 29103, "s": 29006, "text": "ArgumentException: If the val is of a type which is not compatible with the elements of the arr." }, { "code": null, "e": 29275, "s": 29103, "text": "InvalidOperationException: If the val does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface." }, { "code": null, "e": 29329, "s": 29275, "text": "Below programs illustrate the above-discussed method:" }, { "code": null, "e": 29341, "s": 29329, "text": "Example 1: " }, { "code": null, "e": 29344, "s": 29341, "text": "C#" }, { "code": "// C# program to illustrate the// Array.BinarySearch(Array, Object)// Methodusing System; class GFG { // Main Method public static void Main(String[] args) { // taking an 1-D Array int[] arr = new int[7] { 1, 5, 7, 4, 6, 2, 3 }; // for this method array // must be sorted Array.Sort(arr); Console.Write(\"The elements of Sorted Array: \"); // calling the method to // print the values display(arr); // taking the element which is // to search for in a variable // It is not present in the array object s = 8; // calling the method containing // BinarySearch method result(arr, s); // taking the element which is // to search for in a variable // It is present in the array object s1 = 4; // calling the method containing // BinarySearch method result(arr, s1); } // containing BinarySearch Method static void result(int[] arr2, object k) { // using the method int res = Array.BinarySearch(arr2, k); if (res < 0) { Console.WriteLine(\"\\nThe element to search for \" + \"({0}) is not found.\", k); } else { Console.WriteLine(\"The element to search for \" + \"({0}) is at index {1}.\", k, res); } } // display method static void display(int[] arr1) { // Displaying Elements of array foreach(int i in arr1) Console.Write(i + \" \"); }}", "e": 30990, "s": 29344, "text": null }, { "code": null, "e": 31124, "s": 30990, "text": "The elements of Sorted Array: 1 2 3 4 5 6 7 \nThe element to search for (8) is not found.\nThe element to search for (4) is at index 3." }, { "code": null, "e": 31137, "s": 31126, "text": "Example 2:" }, { "code": null, "e": 31140, "s": 31137, "text": "C#" }, { "code": "// C# program to illustrate the// Array.BinarySearch(Array, Object)// Methodusing System; class GFG { // Main Method public static void Main(String[] args) { // taking an 1-D Array int[] arr = new int[7] { 1, 5, 7, 4, 6, 2, 3 }; // for this method array // must be sorted Array.Sort(arr); Console.Write(\"The elements of Sorted Array: \"); // calling the method to // print the values display(arr); // it will return a negative value as // 9 is not present in the array Console.WriteLine(\"\\nIndex of 9 is: \" + Array.BinarySearch(arr, 8)); } // display method static void display(int[] arr1) { // Displaying Elements of array foreach(int i in arr1) Console.Write(i + \" \"); }}", "e": 31954, "s": 31140, "text": null }, { "code": null, "e": 32017, "s": 31954, "text": "The elements of Sorted Array: 1 2 3 4 5 6 7 \nIndex of 9 is: -8" }, { "code": null, "e": 32140, "s": 32019, "text": "This method is used to search a specific element in the entire 1-D sorted array using the specified IComparer interface." }, { "code": null, "e": 32432, "s": 32140, "text": "Syntax: public static int BinarySearch(Array arr, Object val, IComparer comparer)Parameters: arr : The one-dimensional sorted array in which the search will happen. val : The object value which is to search for. comparer : When comparing elements then the IComparer implementation is used. " }, { "code": null, "e": 32625, "s": 32432, "text": "Return Value: It returns the index of the specified val in the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows: " }, { "code": null, "e": 32817, "s": 32625, "text": "If the val is not found and val is less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val." }, { "code": null, "e": 32988, "s": 32817, "text": "If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1)." }, { "code": null, "e": 33152, "s": 32988, "text": "If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr." }, { "code": null, "e": 33166, "s": 33152, "text": "Exceptions: " }, { "code": null, "e": 33209, "s": 33166, "text": "ArgumentNullException: If the arr is null." }, { "code": null, "e": 33252, "s": 33209, "text": "RankException: If arr is multidimensional." }, { "code": null, "e": 33335, "s": 33252, "text": "ArgumentException: If the range is less than lower bound OR length is less than 0." }, { "code": null, "e": 33451, "s": 33335, "text": "ArgumentException: If the comparer is null, and value is of a type that is not compatible with the elements of arr." }, { "code": null, "e": 33643, "s": 33451, "text": "InvalidOperationException: If the comparer is null, value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface." }, { "code": null, "e": 33654, "s": 33643, "text": "Example: " }, { "code": null, "e": 33657, "s": 33654, "text": "C#" }, { "code": "// C# program to demonstrate the// Array.BinarySearch(Array,// Object, IComparer) Methodusing System; class GFG { // Main Method public static void Main() { // initializes a new Array. Array arr = Array.CreateInstance(typeof(Int32), 5); // Array elements arr.SetValue(20, 0); arr.SetValue(10, 1); arr.SetValue(30, 2); arr.SetValue(40, 3); arr.SetValue(50, 4); Console.WriteLine(\"The original Array\"); // calling \"display\" function display(arr); Console.WriteLine(\"\\nsorted array\"); // sorting the Array Array.Sort(arr); display(arr); Console.WriteLine(\"\\n1st call\"); // search for object 10 object obj1 = 10; // call the \"FindObj\" function FindObj(arr, obj1); Console.WriteLine(\"\\n2nd call\"); object obj2 = 60; FindObj(arr, obj2); } // find object method public static void FindObj(Array Arr, object Obj) { int index = Array.BinarySearch(Arr, Obj, StringComparer.CurrentCulture); if (index < 0) { Console.WriteLine(\"The object {0} is not found\\nNext\" + \" larger object is at index {1}\", Obj, ~index); } else { Console.WriteLine(\"The object {0} is at index {1}\", Obj, index); } } // display method public static void display(Array arr) { foreach(int g in arr) { Console.WriteLine(g); } }}", "e": 35305, "s": 33657, "text": null }, { "code": null, "e": 35476, "s": 35305, "text": "The original Array\n20\n10\n30\n40\n50\n\nsorted array\n10\n20\n30\n40\n50\n\n1st call\nThe object 10 is at index 0\n\n2nd call\nThe object 60 is not found\nNext larger object is at index 5" }, { "code": null, "e": 35735, "s": 35478, "text": "This method is used to search a value in the range of elements in a 1-D sorted array. It uses the IComparable interface implemented by each element of the array and the specified value. It searches only in a specified boundary which is defined by the user." }, { "code": null, "e": 36104, "s": 35735, "text": "Syntax: public static int BinarySearch(Array arr, int i, int len, object val);Parameters: arr: It is 1-D array in which the user have to search for an element. i: It is the starting index of the range from where the user want to start the search. len: It is the length of the range in which the user want to search. val: It is the value which the user to search for. " }, { "code": null, "e": 36297, "s": 36104, "text": "Return Value: It returns the index of the specified val in the specified arr if the val is found otherwise it returns a negative number. There are different cases of return values as follows: " }, { "code": null, "e": 36489, "s": 36297, "text": "If the val is not found and val is less than one or more elements in the arr, the negative number returned is the bitwise complement of the index of the first element that is larger than val." }, { "code": null, "e": 36660, "s": 36489, "text": "If the val is not found and val is greater than all elements in the arr, the negative number returned is the bitwise complement of (the index of the last element plus 1)." }, { "code": null, "e": 36824, "s": 36660, "text": "If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the val is present in the arr." }, { "code": null, "e": 36838, "s": 36824, "text": "Exceptions: " }, { "code": null, "e": 36881, "s": 36838, "text": "ArgumentNullException: If the arr is null." }, { "code": null, "e": 36924, "s": 36881, "text": "RankException: If arr is multidimensional." }, { "code": null, "e": 37026, "s": 36924, "text": "ArgumentOutOfRangeException: If the index is less than lower bound of array OR length is less than 0." }, { "code": null, "e": 37193, "s": 37026, "text": "ArgumentException: If the index and length do not specify the valid range in array OR the value is of the type which is not compatible with the elements of the array." }, { "code": null, "e": 37363, "s": 37193, "text": "InvalidOperationException: If value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface." }, { "code": null, "e": 37373, "s": 37363, "text": "Example: " }, { "code": null, "e": 37376, "s": 37373, "text": "C#" }, { "code": "// C# Program to illustrate the use of// Array.BinarySearch(Array, Int32,// Int32, Object) Methodusing System;using System.IO; class GFG { // Main Method static void Main() { // initializing the integer array int[] intArr = { 42, 5, 7, 12, 56, 1, 32 }; // sorts the intArray as it must be // sorted before using method Array.Sort(intArr); // printing the sorted array foreach(int i in intArr) Console.Write(i + \" \" + \"\\n\"); // intArr is the array we want to find // and 1 is the starting index // of the range to search. 5 is the // length of the range to search. // 32 is the object to search int index = Array.BinarySearch(intArr, 1, 5, 32); if (index >= 0) { // if the element is found it // returns the index of the element Console.WriteLine(\"Index of 32 is : \" + index); } else { // if the element is not // present in the array or // if it is not in the // specified range it prints this Console.Write(\"Element is not found\"); } // intArr is the array we want to // find. and 1 is the starting // index of the range to search. 5 is // the length of the range to search // 44 is the object to search int index1 = Array.BinarySearch(intArr, 1, 5, 44); // as the element is not present // it prints a negative value. Console.WriteLine(\"Index of 44 is :\" + index1); }}", "e": 38985, "s": 37376, "text": null }, { "code": null, "e": 39048, "s": 38985, "text": "1 \n5 \n7 \n12 \n32 \n42 \n56 \nIndex of 32 is : 4\nIndex of 44 is :-7" }, { "code": null, "e": 39175, "s": 39050, "text": "This method is used to search a value in the range of elements in a 1-D sorted array using a specified IComparer interface. " }, { "code": null, "e": 39606, "s": 39175, "text": "Syntax: public static int BinarySearch(Array arr, int index, int length, Object value, IComparer comparer)Parameters: arr : The sorted one-dimensional Array which is to be searched. index : The starting index of the range from which searching will start. length : The length of the range in which the search will happen. value : The object to search for. comparer : When comparing elements then use the IComparer implementation. " }, { "code": null, "e": 39804, "s": 39606, "text": "Return Value: It returns the index of the specified value in the specified arr, if the value is found otherwise it returns a negative number. There are different cases of return values as follows: " }, { "code": null, "e": 40004, "s": 39804, "text": "If the value is not found and value is less than one or more elements in the array, the negative number returned is the bitwise complement of the index of the first element that is larger than value." }, { "code": null, "e": 40181, "s": 40004, "text": "If the value is not found and value is greater than all elements in the array, the negative number returned is the bitwise complement of (the index of the last element plus 1)." }, { "code": null, "e": 40349, "s": 40181, "text": "If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if the value is present in the array." }, { "code": null, "e": 40513, "s": 40349, "text": "Example: In this example, here we use “CreateInstance()” method to create a typed array and stores some integer value and search some values after sort the array. " }, { "code": null, "e": 40516, "s": 40513, "text": "C#" }, { "code": "// C# program to demonstrate the// Array.BinarySearch(Array,// Int32, Int32, Object,// IComparer) Methodusing System; class GFG { // Main Method public static void Main() { // initializes a new Array. Array arr = Array.CreateInstance(typeof(Int32), 8); // Array elements arr.SetValue(20, 0); arr.SetValue(10, 1); arr.SetValue(30, 2); arr.SetValue(40, 3); arr.SetValue(50, 4); arr.SetValue(80, 5); arr.SetValue(70, 6); arr.SetValue(60, 7); Console.WriteLine(\"The original Array\"); // calling \"display\" function display(arr); Console.WriteLine(\"\\nsorted array\"); // sorting the Array Array.Sort(arr); display(arr); Console.WriteLine(\"\\n1st call\"); // search for object 10 object obj1 = 10; // call the \"FindObj\" function FindObj(arr, obj1); Console.WriteLine(\"\\n2nd call\"); object obj2 = 60; FindObj(arr, obj2); } // find object method public static void FindObj(Array Arr, object Obj) { int index = Array.BinarySearch(Arr, 1, 4, Obj, StringComparer.CurrentCulture); if (index < 0) { Console.WriteLine(\"The object {0} is not found\\n\" + \"Next larger object is at index {1}\", Obj, ~index); } else { Console.WriteLine(\"The object {0} is at \" + \"index {1}\", Obj, index); } } // display method public static void display(Array arr) { foreach(int g in arr) { Console.WriteLine(g); } }}", "e": 42307, "s": 40516, "text": null }, { "code": null, "e": 42528, "s": 42307, "text": "The original Array\n20\n10\n30\n40\n50\n80\n70\n60\n\nsorted array\n10\n20\n30\n40\n50\n60\n70\n80\n\n1st call\nThe object 10 is not found\nNext larger object is at index 1\n\n2nd call\nThe object 60 is not found\nNext larger object is at index 5" }, { "code": null, "e": 42547, "s": 42530, "text": "arorakashish0911" }, { "code": null, "e": 42561, "s": 42547, "text": "CSharp-Arrays" }, { "code": null, "e": 42575, "s": 42561, "text": "CSharp-method" }, { "code": null, "e": 42578, "s": 42575, "text": "C#" }, { "code": null, "e": 42676, "s": 42578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42704, "s": 42676, "text": "C# Dictionary with examples" }, { "code": null, "e": 42719, "s": 42704, "text": "C# | Delegates" }, { "code": null, "e": 42742, "s": 42719, "text": "C# | Method Overriding" }, { "code": null, "e": 42764, "s": 42742, "text": "C# | Abstract Classes" }, { "code": null, "e": 42810, "s": 42764, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 42833, "s": 42810, "text": "Extension Method in C#" }, { "code": null, "e": 42855, "s": 42833, "text": "C# | Class and Object" }, { "code": null, "e": 42873, "s": 42855, "text": "C# | Constructors" }, { "code": null, "e": 42913, "s": 42873, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Recursive program to check if number is palindrome or not - GeeksforGeeks
24 Feb, 2022 Given a number, the task is to write a recursive function which checks if the given number is palindrome or not. Examples: Input : 121 Output : yes Input : 532 Output : no The approach for writing the function is to call the function recursively till the number is completely traversed from the back. Use a temp variable to store the reverse of the number according to the formula which has been obtained in this post. Pass the temp variable in the parameter and once the base case of n==0 is achieved, return temp which stores the reverse of a number. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Recursive C++ program to check if the// number is palindrome or not#include <bits/stdc++.h>using namespace std; // recursive function that returns the reverse of digitsint rev(int n, int temp){ // base case if (n == 0) return temp; // stores the reverse of a number temp = (temp * 10) + (n % 10); return rev(n / 10, temp);} // Driver Codeint main(){ int n = 121; int temp = rev(n, 0); if (temp == n) cout << "yes" << endl; else cout << "no" << endl; return 0;} // Recursive Java program to// check if the number is// palindrome or notimport java.io.*; class GFG{ // recursive function that// returns the reverse of digitsstatic int rev(int n, int temp){ // base case if (n == 0) return temp; // stores the reverse // of a number temp = (temp * 10) + (n % 10); return rev(n / 10, temp);} // Driver Codepublic static void main (String[] args){ int n = 121; int temp = rev(n, 0); if (temp == n) System.out.println("yes"); else System.out.println("no" );}} // This code is contributed by anuj_67. # Recursive Python3 program to check# if the number is palindrome or not # Recursive function that returns# the reverse of digitsdef rev(n, temp): # base case if (n == 0): return temp; # stores the reverse of a number temp = (temp * 10) + (n % 10); return rev(n // 10, temp); # Driver Coden = 121;temp = rev(n, 0); if (temp == n): print("yes")else: print("no") # This code is contributed# by mits // Recursive C# program to// check if the number is// palindrome or notusing System; class GFG{ // recursive function// that returns the// reverse of digitsstatic int rev(int n, int temp){ // base case if (n == 0) return temp; // stores the reverse // of a number temp = (temp * 10) + (n % 10); return rev(n / 10, temp);} // Driver Codepublic static void Main (){ int n = 121; int temp = rev(n, 0); if (temp == n) Console.WriteLine("yes"); else Console.WriteLine("no" );}} // This code is contributed// by anuj_67. <?php// Recursive PHP program to check// if the number is palindrome or not // Recursive function that returns// the reverse of digitsfunction rev($n, $temp){ // base case if ($n == 0) return $temp; // stores the reverse of a number $temp = ($temp * 10) + ($n % 10); return rev($n / 10, $temp);} // Driver Code$n = 121;$temp = rev($n, 0); if ($temp != $n) echo "yes";else echo "no"; // This code is contributed// by Sach_Code?> <script> // Recursive Javascript program to check if the// number is palindrome or not // recursive function that returns the reverse of digitsfunction rev(n, temp){ // base case if (n == 0) return temp; // stores the reverse of a number temp = (temp * 10) + (n % 10); return rev(Math.floor(n / 10), temp);} // Driver Code let n = 121; let temp = rev(n, 0); if (temp == n) document.write("yes" + "<br>"); else document.write("no" + "<br>"); // This code is contributed by Mayank Tyagi </script> yes vt_m Sach_Code Mithun Kumar mayanktyagi1709 amartyaghoshgfg number-digits palindrome Mathematical Mathematical palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion
[ { "code": null, "e": 26115, "s": 26087, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26240, "s": 26115, "text": "Given a number, the task is to write a recursive function which checks if the given number is palindrome or not. Examples: " }, { "code": null, "e": 26290, "s": 26240, "text": "Input : 121\nOutput : yes\n\nInput : 532\nOutput : no" }, { "code": null, "e": 26726, "s": 26292, "text": "The approach for writing the function is to call the function recursively till the number is completely traversed from the back. Use a temp variable to store the reverse of the number according to the formula which has been obtained in this post. Pass the temp variable in the parameter and once the base case of n==0 is achieved, return temp which stores the reverse of a number. Below is the implementation of the above approach: " }, { "code": null, "e": 26730, "s": 26726, "text": "C++" }, { "code": null, "e": 26735, "s": 26730, "text": "Java" }, { "code": null, "e": 26743, "s": 26735, "text": "Python3" }, { "code": null, "e": 26746, "s": 26743, "text": "C#" }, { "code": null, "e": 26750, "s": 26746, "text": "PHP" }, { "code": null, "e": 26761, "s": 26750, "text": "Javascript" }, { "code": "// Recursive C++ program to check if the// number is palindrome or not#include <bits/stdc++.h>using namespace std; // recursive function that returns the reverse of digitsint rev(int n, int temp){ // base case if (n == 0) return temp; // stores the reverse of a number temp = (temp * 10) + (n % 10); return rev(n / 10, temp);} // Driver Codeint main(){ int n = 121; int temp = rev(n, 0); if (temp == n) cout << \"yes\" << endl; else cout << \"no\" << endl; return 0;}", "e": 27287, "s": 26761, "text": null }, { "code": "// Recursive Java program to// check if the number is// palindrome or notimport java.io.*; class GFG{ // recursive function that// returns the reverse of digitsstatic int rev(int n, int temp){ // base case if (n == 0) return temp; // stores the reverse // of a number temp = (temp * 10) + (n % 10); return rev(n / 10, temp);} // Driver Codepublic static void main (String[] args){ int n = 121; int temp = rev(n, 0); if (temp == n) System.out.println(\"yes\"); else System.out.println(\"no\" );}} // This code is contributed by anuj_67.", "e": 27877, "s": 27287, "text": null }, { "code": "# Recursive Python3 program to check# if the number is palindrome or not # Recursive function that returns# the reverse of digitsdef rev(n, temp): # base case if (n == 0): return temp; # stores the reverse of a number temp = (temp * 10) + (n % 10); return rev(n // 10, temp); # Driver Coden = 121;temp = rev(n, 0); if (temp == n): print(\"yes\")else: print(\"no\") # This code is contributed# by mits", "e": 28305, "s": 27877, "text": null }, { "code": "// Recursive C# program to// check if the number is// palindrome or notusing System; class GFG{ // recursive function// that returns the// reverse of digitsstatic int rev(int n, int temp){ // base case if (n == 0) return temp; // stores the reverse // of a number temp = (temp * 10) + (n % 10); return rev(n / 10, temp);} // Driver Codepublic static void Main (){ int n = 121; int temp = rev(n, 0); if (temp == n) Console.WriteLine(\"yes\"); else Console.WriteLine(\"no\" );}} // This code is contributed// by anuj_67.", "e": 28906, "s": 28305, "text": null }, { "code": "<?php// Recursive PHP program to check// if the number is palindrome or not // Recursive function that returns// the reverse of digitsfunction rev($n, $temp){ // base case if ($n == 0) return $temp; // stores the reverse of a number $temp = ($temp * 10) + ($n % 10); return rev($n / 10, $temp);} // Driver Code$n = 121;$temp = rev($n, 0); if ($temp != $n) echo \"yes\";else echo \"no\"; // This code is contributed// by Sach_Code?>", "e": 29364, "s": 28906, "text": null }, { "code": "<script> // Recursive Javascript program to check if the// number is palindrome or not // recursive function that returns the reverse of digitsfunction rev(n, temp){ // base case if (n == 0) return temp; // stores the reverse of a number temp = (temp * 10) + (n % 10); return rev(Math.floor(n / 10), temp);} // Driver Code let n = 121; let temp = rev(n, 0); if (temp == n) document.write(\"yes\" + \"<br>\"); else document.write(\"no\" + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 29920, "s": 29364, "text": null }, { "code": null, "e": 29924, "s": 29920, "text": "yes" }, { "code": null, "e": 29931, "s": 29926, "text": "vt_m" }, { "code": null, "e": 29941, "s": 29931, "text": "Sach_Code" }, { "code": null, "e": 29954, "s": 29941, "text": "Mithun Kumar" }, { "code": null, "e": 29970, "s": 29954, "text": "mayanktyagi1709" }, { "code": null, "e": 29986, "s": 29970, "text": "amartyaghoshgfg" }, { "code": null, "e": 30000, "s": 29986, "text": "number-digits" }, { "code": null, "e": 30011, "s": 30000, "text": "palindrome" }, { "code": null, "e": 30024, "s": 30011, "text": "Mathematical" }, { "code": null, "e": 30037, "s": 30024, "text": "Mathematical" }, { "code": null, "e": 30048, "s": 30037, "text": "palindrome" }, { "code": null, "e": 30146, "s": 30048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30170, "s": 30146, "text": "Merge two sorted arrays" }, { "code": null, "e": 30213, "s": 30170, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30227, "s": 30213, "text": "Prime Numbers" }, { "code": null, "e": 30269, "s": 30227, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30291, "s": 30269, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30364, "s": 30291, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30385, "s": 30364, "text": "Operators in C / C++" }, { "code": null, "e": 30428, "s": 30385, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30462, "s": 30428, "text": "Program for factorial of a number" } ]
How to create a table in ReactJS ? - GeeksforGeeks
27 Oct, 2021 In this article, we will create a simple table in React.js just like you would create in a normal HTML project. Also, we will style it using normal CSS. Prerequisites: The pre-requisites for this project are: React Functional Components JavaScript ES6 HTML Tables & CSS Creating a React application: Step 1: Create a react application by typing the following command in the terminal. npx create-react-app react-table Step 2: Now, go to the project folder i.e react-table by running the following command. cd react-table Project Structure: It will look like the following: Example 1: Here App.js is the default component. At first, we will see how to create a table using the hardcoded values. Later we will see how to dynamically render the data from an array inside the table. Filename: App.js Javascript import './App.css'; function App() { return ( <div className="App"> <table> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> <tr> <td>Anom</td> <td>19</td> <td>Male</td> </tr> <tr> <td>Megha</td> <td>19</td> <td>Female</td> </tr> <tr> <td>Subham</td> <td>25</td> <td>Male</td> </tr> </table> </div> );} export default App; In the above example, we just simply used the HTML table elements which are <table>, <tr>, <th>, and <td> elements. Example 2: Now lets us see how we can dynamically render data from an array. Instead of manually iterating over the array using a loop, we can simply use the inbuilt Array.map() method. The Array.map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array’s elements. In this case, we will just return a table row on each iteration. Filename: App.js Javascript import './App.css'; // Example of a data array that// you might receive from an APIconst data = [ { name: "Anom", age: 19, gender: "Male" }, { name: "Megha", age: 19, gender: "Female" }, { name: "Subham", age: 25, gender: "Male"},] function App() { return ( <div className="App"> <table> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> {data.map((val, key) => { return ( <tr key={key}> <td>{val.name}</td> <td>{val.age}</td> <td>{val.gender}</td> </tr> ) })} </table> </div> );} export default App; Filename: App.css Now, let’s edit the file named App.css to style the table. CSS .App { width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center;} table { border: 2px solid forestgreen; width: 800px; height: 200px;} th { border-bottom: 1px solid black;} td { text-align: center;} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: CSS-Properties Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to redirect to another page in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS useNavigate() Hook ReactJS defaultProps Re-rendering Components in ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26561, "s": 26533, "text": "\n27 Oct, 2021" }, { "code": null, "e": 26715, "s": 26561, "text": "In this article, we will create a simple table in React.js just like you would create in a normal HTML project. Also, we will style it using normal CSS. " }, { "code": null, "e": 26771, "s": 26715, "text": "Prerequisites: The pre-requisites for this project are:" }, { "code": null, "e": 26777, "s": 26771, "text": "React" }, { "code": null, "e": 26799, "s": 26777, "text": "Functional Components" }, { "code": null, "e": 26814, "s": 26799, "text": "JavaScript ES6" }, { "code": null, "e": 26832, "s": 26814, "text": "HTML Tables & CSS" }, { "code": null, "e": 26862, "s": 26832, "text": "Creating a React application:" }, { "code": null, "e": 26946, "s": 26862, "text": "Step 1: Create a react application by typing the following command in the terminal." }, { "code": null, "e": 26979, "s": 26946, "text": "npx create-react-app react-table" }, { "code": null, "e": 27067, "s": 26979, "text": "Step 2: Now, go to the project folder i.e react-table by running the following command." }, { "code": null, "e": 27082, "s": 27067, "text": "cd react-table" }, { "code": null, "e": 27134, "s": 27082, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 27341, "s": 27134, "text": "Example 1: Here App.js is the default component. At first, we will see how to create a table using the hardcoded values. Later we will see how to dynamically render the data from an array inside the table. " }, { "code": null, "e": 27358, "s": 27341, "text": "Filename: App.js" }, { "code": null, "e": 27369, "s": 27358, "text": "Javascript" }, { "code": "import './App.css'; function App() { return ( <div className=\"App\"> <table> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> <tr> <td>Anom</td> <td>19</td> <td>Male</td> </tr> <tr> <td>Megha</td> <td>19</td> <td>Female</td> </tr> <tr> <td>Subham</td> <td>25</td> <td>Male</td> </tr> </table> </div> );} export default App;", "e": 27881, "s": 27369, "text": null }, { "code": null, "e": 27998, "s": 27881, "text": "In the above example, we just simply used the HTML table elements which are <table>, <tr>, <th>, and <td> elements. " }, { "code": null, "e": 28436, "s": 27998, "text": "Example 2: Now lets us see how we can dynamically render data from an array. Instead of manually iterating over the array using a loop, we can simply use the inbuilt Array.map() method. The Array.map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array’s elements. In this case, we will just return a table row on each iteration." }, { "code": null, "e": 28453, "s": 28436, "text": "Filename: App.js" }, { "code": null, "e": 28464, "s": 28453, "text": "Javascript" }, { "code": "import './App.css'; // Example of a data array that// you might receive from an APIconst data = [ { name: \"Anom\", age: 19, gender: \"Male\" }, { name: \"Megha\", age: 19, gender: \"Female\" }, { name: \"Subham\", age: 25, gender: \"Male\"},] function App() { return ( <div className=\"App\"> <table> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> {data.map((val, key) => { return ( <tr key={key}> <td>{val.name}</td> <td>{val.age}</td> <td>{val.gender}</td> </tr> ) })} </table> </div> );} export default App;", "e": 29127, "s": 28464, "text": null }, { "code": null, "e": 29204, "s": 29127, "text": "Filename: App.css Now, let’s edit the file named App.css to style the table." }, { "code": null, "e": 29208, "s": 29204, "text": "CSS" }, { "code": ".App { width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center;} table { border: 2px solid forestgreen; width: 800px; height: 200px;} th { border-bottom: 1px solid black;} td { text-align: center;}", "e": 29451, "s": 29208, "text": null }, { "code": null, "e": 29564, "s": 29451, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 29574, "s": 29564, "text": "npm start" }, { "code": null, "e": 29673, "s": 29574, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29688, "s": 29673, "text": "CSS-Properties" }, { "code": null, "e": 29695, "s": 29688, "text": "Picked" }, { "code": null, "e": 29711, "s": 29695, "text": "React-Questions" }, { "code": null, "e": 29719, "s": 29711, "text": "ReactJS" }, { "code": null, "e": 29736, "s": 29719, "text": "Web Technologies" }, { "code": null, "e": 29834, "s": 29736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29879, "s": 29834, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 29947, "s": 29879, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 29974, "s": 29947, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29995, "s": 29974, "text": "ReactJS defaultProps" }, { "code": null, "e": 30030, "s": 29995, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 30070, "s": 30030, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30103, "s": 30070, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30148, "s": 30103, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30198, "s": 30148, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Appending to list in Python dictionary - GeeksforGeeks
17 Oct, 2021 In this article, we are going to see how to append to a list in a Python dictionary. In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary. Python3 Details = {"Destination": "China", "Nstionality": "Italian", "Age": []}Details["Age"] += [20, "Twenty"]print(Details) Output: {'Destination': 'China', 'Nstionality': 'Italian', 'Age': [20, 'Twenty']} You can as well append one item. In this method, we will use conditions for checking the key and then append the list into the dictionary. Python3 Details = {}Details["Age"] = [20]print(Details) if "Age" in Details: Details["Age"].append("Twenty") print(Details) Output: {'Age': [20]} {'Age': [20, 'Twenty']} In this method, we are using defaultdict() function, It is a part of the collections module. You have to import the function from the collections module to use it in your program. and then use to append the list into the dictionary. Python3 from collections import defaultdict Details = defaultdict(list)Details["Country"].append("India")print(Details) Output: defaultdict(<class 'list'>, {'Country': ['India']}) Since append takes only one parameter, to insert another parameter, repeat the append method. Python3 from collections import defaultdict Details = defaultdict(list)Details["Country"].append("India")Details["Country"].append("Pakistan")print(Details) Output: defaultdict(<class 'list'>, {'Country': ['India', 'Pakistan']}) We will use the update function to add a new list into the dictionary. You can use the update() function to embed a dictionary inside another dictionary. Python3 Details = {}Details["Age"] = []Details.update({"Age": [18, 20, 25, 29, 30]})print(Details) Output: {'Age': [18, 20, 25, 29, 30]} You can convert a list into a value for a key in a python dictionary using dict() function. Python3 Values = [18, 20, 25, 29, 30]Details = dict({"Age": Values})print(Details) Output: {'Age': [18, 20, 25, 29, 30]} Picked Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25555, "s": 25527, "text": "\n17 Oct, 2021" }, { "code": null, "e": 25640, "s": 25555, "text": "In this article, we are going to see how to append to a list in a Python dictionary." }, { "code": null, "e": 25810, "s": 25640, "text": "In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary." }, { "code": null, "e": 25818, "s": 25810, "text": "Python3" }, { "code": "Details = {\"Destination\": \"China\", \"Nstionality\": \"Italian\", \"Age\": []}Details[\"Age\"] += [20, \"Twenty\"]print(Details)", "e": 25947, "s": 25818, "text": null }, { "code": null, "e": 25955, "s": 25947, "text": "Output:" }, { "code": null, "e": 26029, "s": 25955, "text": "{'Destination': 'China', 'Nstionality': 'Italian', 'Age': [20, 'Twenty']}" }, { "code": null, "e": 26062, "s": 26029, "text": "You can as well append one item." }, { "code": null, "e": 26168, "s": 26062, "text": "In this method, we will use conditions for checking the key and then append the list into the dictionary." }, { "code": null, "e": 26176, "s": 26168, "text": "Python3" }, { "code": "Details = {}Details[\"Age\"] = [20]print(Details) if \"Age\" in Details: Details[\"Age\"].append(\"Twenty\") print(Details)", "e": 26299, "s": 26176, "text": null }, { "code": null, "e": 26307, "s": 26299, "text": "Output:" }, { "code": null, "e": 26345, "s": 26307, "text": "{'Age': [20]}\n{'Age': [20, 'Twenty']}" }, { "code": null, "e": 26578, "s": 26345, "text": "In this method, we are using defaultdict() function, It is a part of the collections module. You have to import the function from the collections module to use it in your program. and then use to append the list into the dictionary." }, { "code": null, "e": 26586, "s": 26578, "text": "Python3" }, { "code": "from collections import defaultdict Details = defaultdict(list)Details[\"Country\"].append(\"India\")print(Details)", "e": 26699, "s": 26586, "text": null }, { "code": null, "e": 26707, "s": 26699, "text": "Output:" }, { "code": null, "e": 26759, "s": 26707, "text": "defaultdict(<class 'list'>, {'Country': ['India']})" }, { "code": null, "e": 26853, "s": 26759, "text": "Since append takes only one parameter, to insert another parameter, repeat the append method." }, { "code": null, "e": 26861, "s": 26853, "text": "Python3" }, { "code": "from collections import defaultdict Details = defaultdict(list)Details[\"Country\"].append(\"India\")Details[\"Country\"].append(\"Pakistan\")print(Details)", "e": 27011, "s": 26861, "text": null }, { "code": null, "e": 27019, "s": 27011, "text": "Output:" }, { "code": null, "e": 27083, "s": 27019, "text": "defaultdict(<class 'list'>, {'Country': ['India', 'Pakistan']})" }, { "code": null, "e": 27238, "s": 27083, "text": "We will use the update function to add a new list into the dictionary. You can use the update() function to embed a dictionary inside another dictionary. " }, { "code": null, "e": 27246, "s": 27238, "text": "Python3" }, { "code": "Details = {}Details[\"Age\"] = []Details.update({\"Age\": [18, 20, 25, 29, 30]})print(Details)", "e": 27337, "s": 27246, "text": null }, { "code": null, "e": 27345, "s": 27337, "text": "Output:" }, { "code": null, "e": 27375, "s": 27345, "text": "{'Age': [18, 20, 25, 29, 30]}" }, { "code": null, "e": 27467, "s": 27375, "text": "You can convert a list into a value for a key in a python dictionary using dict() function." }, { "code": null, "e": 27475, "s": 27467, "text": "Python3" }, { "code": "Values = [18, 20, 25, 29, 30]Details = dict({\"Age\": Values})print(Details)", "e": 27550, "s": 27475, "text": null }, { "code": null, "e": 27558, "s": 27550, "text": "Output:" }, { "code": null, "e": 27588, "s": 27558, "text": "{'Age': [18, 20, 25, 29, 30]}" }, { "code": null, "e": 27595, "s": 27588, "text": "Picked" }, { "code": null, "e": 27622, "s": 27595, "text": "Python dictionary-programs" }, { "code": null, "e": 27634, "s": 27622, "text": "python-dict" }, { "code": null, "e": 27641, "s": 27634, "text": "Python" }, { "code": null, "e": 27657, "s": 27641, "text": "Python Programs" }, { "code": null, "e": 27669, "s": 27657, "text": "python-dict" }, { "code": null, "e": 27767, "s": 27669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27802, "s": 27767, "text": "Read a file line by line in Python" }, { "code": null, "e": 27834, "s": 27802, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27856, "s": 27834, "text": "Enumerate() in Python" }, { "code": null, "e": 27898, "s": 27856, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27928, "s": 27898, "text": "Iterate over a list in Python" }, { "code": null, "e": 27971, "s": 27928, "text": "Python program to convert a list to string" }, { "code": null, "e": 27993, "s": 27971, "text": "Defaultdict in Python" }, { "code": null, "e": 28032, "s": 27993, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28078, "s": 28032, "text": "Python | Split string into list of characters" } ]
Homomorphism & Isomorphism of Group - GeeksforGeeks
26 May, 2021 Introduction :We can say that “o” is the binary operation on set G if : G is an non-empty set & G * G = { (a,b) : a , b∈ G } and o : G * G –> G. Here, aob denotes the image of ordered pair (a,b) under the function / operation o.Example – “+” is called a binary operation on G (any non-empty set ) if & only if : a+b ∈G ; ∀ a,b ∈G and a+b give the same result every time when added.Real example – ‘+’ is a binary operation on the set of natural numbers ‘N’ because a+b ∈ N ; ∀ a,b ∈N and a+b a+b give the same result every time when added. Laws of Binary Operation :In a binary operation o, such that : o : G * G –> G on the set G is :1. Commutative – aob = boa ; ∀ a,b ∈G Example : ‘+’ is a binary operation on the set of natural numbers ‘N’. Taking any 2 random natural numbers , say 6 & 70, so here a = 6 & b = 70, a+b = 6 + 70 = 76 = 70 + 6 = b + aThis is true for all the numbers that come under the natural number. 2. Associative – ao(boc) = (aob)oc ; ∀ a,b,c ∈G Example : ‘+’ is a binary operation on the set of natural numbers ‘N’. Taking any 3 random natural numbers , say 2 , 3 & 7, so here a = 2 & b = 3 and c = 7,LHS : a+(b+c) = 2 +( 3 +7) = 2 + 10 = 12RHS : (a+b)+c = (2 + 3) + 7 = 5 + 7 = 12This is true for all the numbers that come under the natural number. 3. Left Distributive – ao(b*c) = (aob) * (aoc) ; ∀ a,b,c ∈G 4. Right Distributive – (b*c) oa = (boa) * (coa) ; ∀ a,b,c ∈G 5. Left Cancellation – aob =aoc => b = c ; ∀ a,b,c ∈G 6. Right Cancellation – boa = coa => b = c ; ∀ a,b,c ∈G Algebraic Structure :A non-empty set G equipped with 1/more binary operations is called an algebraic structure. Example : a. (N,+) and b. (R, + , .), where N is a set of natural numbers & R is a set of real numbers. Here ‘ . ‘ (dot) specifies a multiplication operation. GROUP : An algebraic structure (G , o) where G is a non-empty set & ‘o’ is a binary operation defined on G is called a Group if the binary operation “o” satisfies the following properties – 1. Closure – a ∈ G ,b ∈ G => aob ∈ G ; ∀ a,b ∈ G 2. Associativity – (aob)oc = ao(boc) ; ∀ a,b,c ∈ G. 3. Identity Element – There exists e in G such that aoe = eoa = a ; ∀ a ∈ G (Example – For addition, identity is 0) 4. Existence of Inverse – For each element a ∈ G ; there exists an inverse(a-1)such that : ∈ G such that – aoa-1 = a-1oa = e Homomorphism of groups :Let (G,o) & (G’,o’) be 2 groups, a mapping “f ” from a group (G,o) to a group (G’,o’) is said to be a homomorphism if – f(aob) = f(a) o' f(b) ∀ a,b ∈ G The essential point here is : The mapping f : G –> G’ may neither be a one-one nor onto mapping, i.e, ‘f’ needs not to be bijective. Example –If (R,+) is a group of all real numbers under the operation ‘+’ & (R -{0},*) is another group of non-zero real numbers under the operation ‘*’ (Multiplication) & f is a mapping from (R,+) to (R -{0},*), defined as : f(a) = 2a ; ∀ a ∈ RThen f is a homomorphism like – f(a+b) = 2a+b = 2a * 2b = f(a).f(b) . So the rule of homomorphism is satisfied & hence f is a homomorphism. Homomorphism Into – A mapping ‘f’, that is homomorphism & also Into. Homomorphism Onto – A mapping ‘f’, that is homomorphism & also onto. Isomorphism of Group :Let (G,o) & (G’,o’) be 2 groups, a mapping “f ” from a group (G,o) to a group (G’,o’) is said to be an isomorphism if – 1. f(aob) = f(a) o' f(b) ∀ a,b ∈ G 2. f is a one- one mapping 3. f is an onto mapping. If ‘f’ is an isomorphic mapping, (G,o) will be isomorphic to the group (G’,o’) & we write : G ≅ G' Note : A mapping f: X -> Y is called : One – One – If x1 ≠x2, then f(x1) ≠ f(x2) or if f(x1) = f(x2) => x1 = x2. Where x1,x2 ∈ XOnto – If every element in the set Y is the f-image of at least one element of set X. Bijective – If it is one one & Onto. One – One – If x1 ≠x2, then f(x1) ≠ f(x2) or if f(x1) = f(x2) => x1 = x2. Where x1,x2 ∈ X Onto – If every element in the set Y is the f-image of at least one element of set X. Bijective – If it is one one & Onto. Example of Isomorphism Group –If G is the multiplicative group of 3 cube-root units , i.e., (G,o) = ( {1, w, w2 } , *) where w3 = 1 & G’ is an additive group of integers modulo 3 – (G’, o’) = ( {1,2,3) , +3). Then : G ≅ G’ , we say G is isomorphic to G’. The structure & order of both the tables are same. The mapping ‘f’ is defined as :f : G -> G’ in such a way that f(1) = 0 , f(w) = 1 & f(w2) = 2. Homomorphism property : f(aob) = f(a) o’ f(b) ∀ a,b ∈ G . Let us take a = w & b = 1LHS : f(a * b) = f( w * 1 ) = f(w) = 1.RHS : f(a) +3 f(b) = f(w) +3 f(1) = 1 + 0 = 1=>LHS = RHS This mapping f is one-one & onto also, therefore, a homomorphism. Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Difference between Propositional Logic and Predicate Logic Logic Notations in LaTeX Univariate, Bivariate and Multivariate data and its analysis Z-test Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 26137, "s": 26109, "text": "\n26 May, 2021" }, { "code": null, "e": 26680, "s": 26137, "text": "Introduction :We can say that “o” is the binary operation on set G if : G is an non-empty set & G * G = { (a,b) : a , b∈ G } and o : G * G –> G. Here, aob denotes the image of ordered pair (a,b) under the function / operation o.Example – “+” is called a binary operation on G (any non-empty set ) if & only if : a+b ∈G ; ∀ a,b ∈G and a+b give the same result every time when added.Real example – ‘+’ is a binary operation on the set of natural numbers ‘N’ because a+b ∈ N ; ∀ a,b ∈N and a+b a+b give the same result every time when added. " }, { "code": null, "e": 26792, "s": 26680, "text": "Laws of Binary Operation :In a binary operation o, such that : o : G * G –> G on the set G is :1. Commutative –" }, { "code": null, "e": 26814, "s": 26792, "text": " aob = boa ; ∀ a,b ∈G" }, { "code": null, "e": 27063, "s": 26814, "text": "Example : ‘+’ is a binary operation on the set of natural numbers ‘N’. Taking any 2 random natural numbers , say 6 & 70, so here a = 6 & b = 70, a+b = 6 + 70 = 76 = 70 + 6 = b + aThis is true for all the numbers that come under the natural number." }, { "code": null, "e": 27080, "s": 27063, "text": "2. Associative –" }, { "code": null, "e": 27111, "s": 27080, "text": "ao(boc) = (aob)oc ; ∀ a,b,c ∈G" }, { "code": null, "e": 27418, "s": 27111, "text": "Example : ‘+’ is a binary operation on the set of natural numbers ‘N’. Taking any 3 random natural numbers , say 2 , 3 & 7, so here a = 2 & b = 3 and c = 7,LHS : a+(b+c) = 2 +( 3 +7) = 2 + 10 = 12RHS : (a+b)+c = (2 + 3) + 7 = 5 + 7 = 12This is true for all the numbers that come under the natural number." }, { "code": null, "e": 27442, "s": 27418, "text": "3. Left Distributive – " }, { "code": null, "e": 27479, "s": 27442, "text": "ao(b*c) = (aob) * (aoc) ; ∀ a,b,c ∈G" }, { "code": null, "e": 27503, "s": 27479, "text": "4. Right Distributive –" }, { "code": null, "e": 27543, "s": 27503, "text": " (b*c) oa = (boa) * (coa) ; ∀ a,b,c ∈G" }, { "code": null, "e": 27566, "s": 27543, "text": "5. Left Cancellation –" }, { "code": null, "e": 27600, "s": 27566, "text": " aob =aoc => b = c ; ∀ a,b,c ∈G" }, { "code": null, "e": 27624, "s": 27600, "text": "6. Right Cancellation –" }, { "code": null, "e": 27658, "s": 27624, "text": " boa = coa => b = c ; ∀ a,b,c ∈G" }, { "code": null, "e": 27931, "s": 27658, "text": "Algebraic Structure :A non-empty set G equipped with 1/more binary operations is called an algebraic structure. Example : a. (N,+) and b. (R, + , .), where N is a set of natural numbers & R is a set of real numbers. Here ‘ . ‘ (dot) specifies a multiplication operation. " }, { "code": null, "e": 28121, "s": 27931, "text": "GROUP : An algebraic structure (G , o) where G is a non-empty set & ‘o’ is a binary operation defined on G is called a Group if the binary operation “o” satisfies the following properties –" }, { "code": null, "e": 28135, "s": 28121, "text": "1. Closure – " }, { "code": null, "e": 28173, "s": 28135, "text": "a ∈ G ,b ∈ G => aob ∈ G ; ∀ a,b ∈ G" }, { "code": null, "e": 28192, "s": 28173, "text": "2. Associativity –" }, { "code": null, "e": 28226, "s": 28192, "text": " (aob)oc = ao(boc) ; ∀ a,b,c ∈ G." }, { "code": null, "e": 28342, "s": 28226, "text": "3. Identity Element – There exists e in G such that aoe = eoa = a ; ∀ a ∈ G (Example – For addition, identity is 0)" }, { "code": null, "e": 28468, "s": 28342, "text": "4. Existence of Inverse – For each element a ∈ G ; there exists an inverse(a-1)such that : ∈ G such that – aoa-1 = a-1oa = e" }, { "code": null, "e": 28612, "s": 28468, "text": "Homomorphism of groups :Let (G,o) & (G’,o’) be 2 groups, a mapping “f ” from a group (G,o) to a group (G’,o’) is said to be a homomorphism if –" }, { "code": null, "e": 28644, "s": 28612, "text": "f(aob) = f(a) o' f(b) ∀ a,b ∈ G" }, { "code": null, "e": 28777, "s": 28644, "text": "The essential point here is : The mapping f : G –> G’ may neither be a one-one nor onto mapping, i.e, ‘f’ needs not to be bijective." }, { "code": null, "e": 29165, "s": 28777, "text": "Example –If (R,+) is a group of all real numbers under the operation ‘+’ & (R -{0},*) is another group of non-zero real numbers under the operation ‘*’ (Multiplication) & f is a mapping from (R,+) to (R -{0},*), defined as : f(a) = 2a ; ∀ a ∈ RThen f is a homomorphism like – f(a+b) = 2a+b = 2a * 2b = f(a).f(b) . So the rule of homomorphism is satisfied & hence f is a homomorphism." }, { "code": null, "e": 29234, "s": 29165, "text": "Homomorphism Into – A mapping ‘f’, that is homomorphism & also Into." }, { "code": null, "e": 29303, "s": 29234, "text": "Homomorphism Onto – A mapping ‘f’, that is homomorphism & also onto." }, { "code": null, "e": 29445, "s": 29303, "text": "Isomorphism of Group :Let (G,o) & (G’,o’) be 2 groups, a mapping “f ” from a group (G,o) to a group (G’,o’) is said to be an isomorphism if –" }, { "code": null, "e": 29532, "s": 29445, "text": "1. f(aob) = f(a) o' f(b) ∀ a,b ∈ G\n2. f is a one- one mapping\n3. f is an onto mapping." }, { "code": null, "e": 29624, "s": 29532, "text": "If ‘f’ is an isomorphic mapping, (G,o) will be isomorphic to the group (G’,o’) & we write :" }, { "code": null, "e": 29631, "s": 29624, "text": "G ≅ G'" }, { "code": null, "e": 29670, "s": 29631, "text": "Note : A mapping f: X -> Y is called :" }, { "code": null, "e": 29900, "s": 29670, "text": "One – One – If x1 ≠x2, then f(x1) ≠ f(x2) or if f(x1) = f(x2) => x1 = x2. Where x1,x2 ∈ XOnto – If every element in the set Y is the f-image of at least one element of set X. Bijective – If it is one one & Onto." }, { "code": null, "e": 29993, "s": 29900, "text": "One – One – If x1 ≠x2, then f(x1) ≠ f(x2) or if f(x1) = f(x2) => x1 = x2. Where x1,x2 ∈ X" }, { "code": null, "e": 30090, "s": 29993, "text": "Onto – If every element in the set Y is the f-image of at least one element of set X. " }, { "code": null, "e": 30132, "s": 30090, "text": "Bijective – If it is one one & Onto." }, { "code": null, "e": 30389, "s": 30132, "text": "Example of Isomorphism Group –If G is the multiplicative group of 3 cube-root units , i.e., (G,o) = ( {1, w, w2 } , *) where w3 = 1 & G’ is an additive group of integers modulo 3 – (G’, o’) = ( {1,2,3) , +3). Then : G ≅ G’ , we say G is isomorphic to G’." }, { "code": null, "e": 30536, "s": 30389, "text": "The structure & order of both the tables are same. The mapping ‘f’ is defined as :f : G -> G’ in such a way that f(1) = 0 , f(w) = 1 & f(w2) = 2." }, { "code": null, "e": 30715, "s": 30536, "text": "Homomorphism property : f(aob) = f(a) o’ f(b) ∀ a,b ∈ G . Let us take a = w & b = 1LHS : f(a * b) = f( w * 1 ) = f(w) = 1.RHS : f(a) +3 f(b) = f(w) +3 f(1) = 1 + 0 = 1=>LHS = RHS" }, { "code": null, "e": 30781, "s": 30715, "text": "This mapping f is one-one & onto also, therefore, a homomorphism." }, { "code": null, "e": 30805, "s": 30781, "text": "Engineering Mathematics" }, { "code": null, "e": 30813, "s": 30805, "text": "GATE CS" }, { "code": null, "e": 30911, "s": 30813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30932, "s": 30911, "text": "Activation Functions" }, { "code": null, "e": 30991, "s": 30932, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 31016, "s": 30991, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 31077, "s": 31016, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 31084, "s": 31077, "text": "Z-test" }, { "code": null, "e": 31104, "s": 31084, "text": "Layers of OSI Model" }, { "code": null, "e": 31128, "s": 31104, "text": "ACID Properties in DBMS" }, { "code": null, "e": 31141, "s": 31128, "text": "TCP/IP Model" }, { "code": null, "e": 31168, "s": 31141, "text": "Types of Operating Systems" } ]
Minimum operations to make XOR of array zero - GeeksforGeeks
28 Apr, 2021 We are given an array of n elements. The task is to make XOR of whole array 0. We can do the following to achieve this. We can select any one of the elements.After selecting an element, we can either increment or decrement it by 1. We can select any one of the elements. After selecting an element, we can either increment or decrement it by 1. We need to find the minimum number of increment/decrement operations required for the selected element to make the XOR sum of the whole array zero. Examples: Input : arr[] = {2, 4, 8} Output : Element = 8, Operation required = 2 Explanation : Select 8 as element and perform 2 time decrement on it. So that it became 6, Now our array is {2, 4, 6} whose XOR sum is 0. Input : arr[] = {1, 1, 1, 1} Output : Element = 1, Operation required = 0 Explanation : Select any of 1 and you have already your XOR sum = 0. So, no operation required. Naive Approach: Select an element and then find the XOR of the rest of the array. If that element became equals to XOR obtained then our XOR of the whole array should become zero. Now, our cost for that will be the absolute difference between the selected element and obtained XOR. This process of finding cost will be done for each element and thus resulting in Time Complexity of (n^2).Efficient Approach: Find the XOR of the whole array. Now, suppose we have selected element arr[i], so cost required for that element will be absolute(arr[i]-(XORsum^arr[i])). Calculating the minimum of these absolute values for each element will be our minimum required operation also the element corresponding to the minimum required operation will be our selected element. C++ Java Python3 C# PHP Javascript // CPP to find min cost to make// XOR of whole array zero#include <bits/stdc++.h>using namespace std; // function to find min costvoid minCost(int arr[], int n){ int cost = INT_MAX; int element; // calculate XOR sum of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and element corresponding for (int i = 0; i < n; i++) { if (cost > abs((XOR ^ arr[i]) - arr[i])) { cost = abs((XOR ^ arr[i]) - arr[i]); element = arr[i]; } } cout << "Element = " << element << endl; cout << "Operation required = " << abs(cost);} // driver programint main(){ int arr[] = { 2, 8, 4, 16 }; int n = sizeof(arr) / sizeof(arr[0]); minCost(arr, n); return 0;} // JAVA program to find min cost to make// XOR of whole array zeroimport java.lang.*; class GFG{ // function to find min cost static void minCost(int[] arr, int n) { int cost = Integer.MAX_VALUE; int element=0; // calculate XOR sum of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and element // corresponding for (int i = 0; i < n; i++) { if (cost > Math.abs((XOR ^ arr[i]) - arr[i])) { cost = Math.abs((XOR ^ arr[i]) - arr[i]); element = arr[i]; } } System.out.println("Element = " + element); System.out.println("Operation required = "+ Math.abs(cost)); } // driver program public static void main (String[] args) { int[] arr = { 2, 8, 4, 16 }; int n = arr.length; minCost(arr, n); }}/* This code is contributed by Kriti Shukla */ # python to find min cost to make# XOR of whole array zero # function to find min costdef minCost(arr,n): cost = 999999; # calculate XOR sum of array XOR = 0; for i in range(0, n): XOR ^= arr[i]; # find the min cost and element # corresponding for i in range(0,n): if (cost > abs((XOR ^ arr[i]) - arr[i])): cost = abs((XOR ^ arr[i]) - arr[i]) element = arr[i] print("Element = ", element) print("Operation required = ", abs(cost)) # driver programarr = [ 2, 8, 4, 16 ]n = len(arr)minCost(arr, n) # This code is contributed by Sam007 // C# program to find min cost to// make XOR of whole array zerousing System; class GFG{ // function to find min cost static void minCost(int []arr, int n) { int cost = int.MaxValue; int element=0; // calculate XOR sum of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and // element corresponding for (int i = 0; i < n; i++) { if (cost > Math.Abs((XOR ^ arr[i]) - arr[i])) { cost = Math.Abs((XOR ^ arr[i]) - arr[i]); element = arr[i]; } } Console.WriteLine("Element = " + element); Console.Write("Operation required = "+ Math.Abs(cost)); } // Driver program public static void Main () { int []arr = {2, 8, 4, 16}; int n = arr.Length; minCost(arr, n); }} // This code is contributed by nitin mittal. <?php// PHP to find min cost to make// XOR of whole array zero // function to find min costfunction minCost($arr, $n){ $cost = PHP_INT_MAX; $element; // calculate XOR sum of array $XOR = 0; for ($i = 0; $i < $n; $i++) $XOR ^= $arr[$i]; // find the min cost and // element corresponding for ($i = 0; $i < $n; $i++) { if ($cost > abs(($XOR ^ $arr[$i]) - $arr[$i])) { $cost = abs(($XOR ^ $arr[$i]) - $arr[$i]); $element = $arr[$i]; } } echo "Element = " , $element ,"\n"; echo "Operation required = " , abs($cost);} // Driver Code$arr = array(2, 8, 4, 16) ;$n = count($arr);minCost($arr, $n); // This code is contributed by vt_m.?> <script> // javascript to find min cost to make// XOR of whole array zero // function to find min costfunction minCost(arr, n){ var cost = 1000000000; var element; // calculate XOR sum of array var XOR = 0; for (var i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and element corresponding for (var i = 0; i < n; i++) { var x= Math.abs((XOR ^ arr[i]) - arr[i]) if (cost > x) { cost = x; element = arr[i]; } } document.write( "Element = " + element + "<br>"); document.write( "Operation required = " + Math.abs(cost));} // driver programvar arr = [ 2, 8, 4, 16 ];var n = arr.length;minCost(arr, n); </script> Output: Element = 16 Operation required = 2 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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m Sam007 itsok Bitwise-XOR Arrays Arrays 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 Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26699, "s": 26671, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26821, "s": 26699, "text": "We are given an array of n elements. The task is to make XOR of whole array 0. We can do the following to achieve this. " }, { "code": null, "e": 26933, "s": 26821, "text": "We can select any one of the elements.After selecting an element, we can either increment or decrement it by 1." }, { "code": null, "e": 26972, "s": 26933, "text": "We can select any one of the elements." }, { "code": null, "e": 27046, "s": 26972, "text": "After selecting an element, we can either increment or decrement it by 1." }, { "code": null, "e": 27195, "s": 27046, "text": "We need to find the minimum number of increment/decrement operations required for the selected element to make the XOR sum of the whole array zero. " }, { "code": null, "e": 27206, "s": 27195, "text": "Examples: " }, { "code": null, "e": 27679, "s": 27206, "text": "Input : arr[] = {2, 4, 8}\nOutput : Element = 8, \n Operation required = 2\nExplanation : Select 8 as element and perform 2 \n time decrement on it. So that it\n became 6, Now our array is {2, 4, 6} \n whose XOR sum is 0.\n\nInput : arr[] = {1, 1, 1, 1}\nOutput : Element = 1, \n Operation required = 0\nExplanation : Select any of 1 and you have already\n your XOR sum = 0. So, no operation \n required." }, { "code": null, "e": 28444, "s": 27679, "text": "Naive Approach: Select an element and then find the XOR of the rest of the array. If that element became equals to XOR obtained then our XOR of the whole array should become zero. Now, our cost for that will be the absolute difference between the selected element and obtained XOR. This process of finding cost will be done for each element and thus resulting in Time Complexity of (n^2).Efficient Approach: Find the XOR of the whole array. Now, suppose we have selected element arr[i], so cost required for that element will be absolute(arr[i]-(XORsum^arr[i])). Calculating the minimum of these absolute values for each element will be our minimum required operation also the element corresponding to the minimum required operation will be our selected element. " }, { "code": null, "e": 28448, "s": 28444, "text": "C++" }, { "code": null, "e": 28453, "s": 28448, "text": "Java" }, { "code": null, "e": 28461, "s": 28453, "text": "Python3" }, { "code": null, "e": 28464, "s": 28461, "text": "C#" }, { "code": null, "e": 28468, "s": 28464, "text": "PHP" }, { "code": null, "e": 28479, "s": 28468, "text": "Javascript" }, { "code": "// CPP to find min cost to make// XOR of whole array zero#include <bits/stdc++.h>using namespace std; // function to find min costvoid minCost(int arr[], int n){ int cost = INT_MAX; int element; // calculate XOR sum of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and element corresponding for (int i = 0; i < n; i++) { if (cost > abs((XOR ^ arr[i]) - arr[i])) { cost = abs((XOR ^ arr[i]) - arr[i]); element = arr[i]; } } cout << \"Element = \" << element << endl; cout << \"Operation required = \" << abs(cost);} // driver programint main(){ int arr[] = { 2, 8, 4, 16 }; int n = sizeof(arr) / sizeof(arr[0]); minCost(arr, n); return 0;}", "e": 29239, "s": 28479, "text": null }, { "code": "// JAVA program to find min cost to make// XOR of whole array zeroimport java.lang.*; class GFG{ // function to find min cost static void minCost(int[] arr, int n) { int cost = Integer.MAX_VALUE; int element=0; // calculate XOR sum of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and element // corresponding for (int i = 0; i < n; i++) { if (cost > Math.abs((XOR ^ arr[i]) - arr[i])) { cost = Math.abs((XOR ^ arr[i]) - arr[i]); element = arr[i]; } } System.out.println(\"Element = \" + element); System.out.println(\"Operation required = \"+ Math.abs(cost)); } // driver program public static void main (String[] args) { int[] arr = { 2, 8, 4, 16 }; int n = arr.length; minCost(arr, n); }}/* This code is contributed by Kriti Shukla */", "e": 30288, "s": 29239, "text": null }, { "code": "# python to find min cost to make# XOR of whole array zero # function to find min costdef minCost(arr,n): cost = 999999; # calculate XOR sum of array XOR = 0; for i in range(0, n): XOR ^= arr[i]; # find the min cost and element # corresponding for i in range(0,n): if (cost > abs((XOR ^ arr[i]) - arr[i])): cost = abs((XOR ^ arr[i]) - arr[i]) element = arr[i] print(\"Element = \", element) print(\"Operation required = \", abs(cost)) # driver programarr = [ 2, 8, 4, 16 ]n = len(arr)minCost(arr, n) # This code is contributed by Sam007", "e": 30897, "s": 30288, "text": null }, { "code": "// C# program to find min cost to// make XOR of whole array zerousing System; class GFG{ // function to find min cost static void minCost(int []arr, int n) { int cost = int.MaxValue; int element=0; // calculate XOR sum of array int XOR = 0; for (int i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and // element corresponding for (int i = 0; i < n; i++) { if (cost > Math.Abs((XOR ^ arr[i]) - arr[i])) { cost = Math.Abs((XOR ^ arr[i]) - arr[i]); element = arr[i]; } } Console.WriteLine(\"Element = \" + element); Console.Write(\"Operation required = \"+ Math.Abs(cost)); } // Driver program public static void Main () { int []arr = {2, 8, 4, 16}; int n = arr.Length; minCost(arr, n); }} // This code is contributed by nitin mittal.", "e": 31857, "s": 30897, "text": null }, { "code": "<?php// PHP to find min cost to make// XOR of whole array zero // function to find min costfunction minCost($arr, $n){ $cost = PHP_INT_MAX; $element; // calculate XOR sum of array $XOR = 0; for ($i = 0; $i < $n; $i++) $XOR ^= $arr[$i]; // find the min cost and // element corresponding for ($i = 0; $i < $n; $i++) { if ($cost > abs(($XOR ^ $arr[$i]) - $arr[$i])) { $cost = abs(($XOR ^ $arr[$i]) - $arr[$i]); $element = $arr[$i]; } } echo \"Element = \" , $element ,\"\\n\"; echo \"Operation required = \" , abs($cost);} // Driver Code$arr = array(2, 8, 4, 16) ;$n = count($arr);minCost($arr, $n); // This code is contributed by vt_m.?>", "e": 32639, "s": 31857, "text": null }, { "code": "<script> // javascript to find min cost to make// XOR of whole array zero // function to find min costfunction minCost(arr, n){ var cost = 1000000000; var element; // calculate XOR sum of array var XOR = 0; for (var i = 0; i < n; i++) XOR ^= arr[i]; // find the min cost and element corresponding for (var i = 0; i < n; i++) { var x= Math.abs((XOR ^ arr[i]) - arr[i]) if (cost > x) { cost = x; element = arr[i]; } } document.write( \"Element = \" + element + \"<br>\"); document.write( \"Operation required = \" + Math.abs(cost));} // driver programvar arr = [ 2, 8, 4, 16 ];var n = arr.length;minCost(arr, n); </script>", "e": 33337, "s": 32639, "text": null }, { "code": null, "e": 33346, "s": 33337, "text": "Output: " }, { "code": null, "e": 33382, "s": 33346, "text": "Element = 16\nOperation required = 2" }, { "code": null, "e": 33844, "s": 33382, "text": "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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33857, "s": 33844, "text": "nitin mittal" }, { "code": null, "e": 33862, "s": 33857, "text": "vt_m" }, { "code": null, "e": 33869, "s": 33862, "text": "Sam007" }, { "code": null, "e": 33875, "s": 33869, "text": "itsok" }, { "code": null, "e": 33887, "s": 33875, "text": "Bitwise-XOR" }, { "code": null, "e": 33894, "s": 33887, "text": "Arrays" }, { "code": null, "e": 33901, "s": 33894, "text": "Arrays" }, { "code": null, "e": 33999, "s": 33901, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34067, "s": 33999, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34111, "s": 34067, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34159, "s": 34111, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34182, "s": 34159, "text": "Introduction to Arrays" }, { "code": null, "e": 34214, "s": 34182, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34228, "s": 34214, "text": "Linear Search" }, { "code": null, "e": 34249, "s": 34228, "text": "Linked List vs Array" }, { "code": null, "e": 34334, "s": 34249, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34379, "s": 34334, "text": "Python | Using 2D arrays/lists the right way" } ]
Top 5 Easter Eggs in Python - GeeksforGeeks
22 Jul, 2021 Python is really an interesting language with very good documentation. In this article, we will go through some fun stuff that isn’t documented and so considered as Easter eggs of Python. Most of the programmers should have started your programming journey from printing “Hello World!”. Would you believe that Python has a secret module to print “Hello World” and the name of the module is __hello__ Python3 import __hello__ Output: Hello world! If you feel bored typing code all day, then check the antigravity module in Python which redirects you to https://xkcd.com/353/ a web-comic. Python3 # redirects you to https://xkcd.com/353/import antigravity “Zen of python” is a guide to Python design principles. It consists of 19 design principles and it is written by an American software developer Tim Peters. This is also by far the only ‘official’ Easter egg that is stated as an ‘Easter egg’ in Python Developer’s Guide. You can see them by importing the module “this”. Python3 import this Output: Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren’t special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one– and preferably only one –obvious way to do it.Although that way may not be obvious at first unless you’re Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it’s a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea — let’s do more of those! Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain-inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. Python3 from __future__ import barry_as_FLUFL 1 <> 21 != 2 Output: True SyntaxError: with Barry as BDFL, use '<>' instead of '!=' Unlike most of the language, Python uses indentation instead of curly braces “{ }”. While making a transition from languages like C++ or JAVA to Python it is a bit difficult to adapt to indentation. Thus if we try to use braces using __future__ module, Python gives a funny reply “not a chance”. Python3 from __future__ import braces Output: File "<stdin>", line 1 SyntaxError: not a chance 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25725, "s": 25537, "text": "Python is really an interesting language with very good documentation. In this article, we will go through some fun stuff that isn’t documented and so considered as Easter eggs of Python." }, { "code": null, "e": 25937, "s": 25725, "text": "Most of the programmers should have started your programming journey from printing “Hello World!”. Would you believe that Python has a secret module to print “Hello World” and the name of the module is __hello__" }, { "code": null, "e": 25945, "s": 25937, "text": "Python3" }, { "code": "import __hello__ ", "e": 25963, "s": 25945, "text": null }, { "code": null, "e": 25971, "s": 25963, "text": "Output:" }, { "code": null, "e": 25984, "s": 25971, "text": "Hello world!" }, { "code": null, "e": 26090, "s": 25984, "text": "If you feel bored typing code all day, then check the antigravity module in Python which redirects you to" }, { "code": null, "e": 26125, "s": 26090, "text": "https://xkcd.com/353/ a web-comic." }, { "code": null, "e": 26133, "s": 26125, "text": "Python3" }, { "code": "# redirects you to https://xkcd.com/353/import antigravity", "e": 26192, "s": 26133, "text": null }, { "code": null, "e": 26513, "s": 26192, "text": "“Zen of python” is a guide to Python design principles. It consists of 19 design principles and it is written by an American software developer Tim Peters. This is also by far the only ‘official’ Easter egg that is stated as an ‘Easter egg’ in Python Developer’s Guide. You can see them by importing the module “this”." }, { "code": null, "e": 26521, "s": 26513, "text": "Python3" }, { "code": "import this", "e": 26533, "s": 26521, "text": null }, { "code": null, "e": 26541, "s": 26533, "text": "Output:" }, { "code": null, "e": 27343, "s": 26541, "text": "Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren’t special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one– and preferably only one –obvious way to do it.Although that way may not be obvious at first unless you’re Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it’s a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea — let’s do more of those!" }, { "code": null, "e": 27513, "s": 27343, "text": "Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain-inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling." }, { "code": null, "e": 27521, "s": 27513, "text": "Python3" }, { "code": "from __future__ import barry_as_FLUFL 1 <> 21 != 2", "e": 27573, "s": 27521, "text": null }, { "code": null, "e": 27581, "s": 27573, "text": "Output:" }, { "code": null, "e": 27644, "s": 27581, "text": "True\nSyntaxError: with Barry as BDFL, use '<>' instead of '!='" }, { "code": null, "e": 27940, "s": 27644, "text": "Unlike most of the language, Python uses indentation instead of curly braces “{ }”. While making a transition from languages like C++ or JAVA to Python it is a bit difficult to adapt to indentation. Thus if we try to use braces using __future__ module, Python gives a funny reply “not a chance”." }, { "code": null, "e": 27948, "s": 27940, "text": "Python3" }, { "code": "from __future__ import braces", "e": 27978, "s": 27948, "text": null }, { "code": null, "e": 27987, "s": 27978, "text": " Output:" }, { "code": null, "e": 28036, "s": 27987, "text": "File \"<stdin>\", line 1\nSyntaxError: not a chance" }, { "code": null, "e": 28051, "s": 28036, "text": "python-utility" }, { "code": null, "e": 28058, "s": 28051, "text": "Python" }, { "code": null, "e": 28156, "s": 28058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28188, "s": 28156, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28230, "s": 28188, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28272, "s": 28230, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28299, "s": 28272, "text": "Python Classes and Objects" }, { "code": null, "e": 28355, "s": 28299, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28377, "s": 28355, "text": "Defaultdict in Python" }, { "code": null, "e": 28416, "s": 28377, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28447, "s": 28416, "text": "Python | os.path.join() method" }, { "code": null, "e": 28476, "s": 28447, "text": "Create a directory in Python" } ]
AngularJS | ng-disabled Directive - GeeksforGeeks
31 Aug, 2021 The ng-disabled Directive in AngularJS is used to enable or disable HTML elements. If the expression inside the ng-disabled attribute returns true then the form field will be disabled or vice versa. It is usually applied on form field (input, select, button, etc). Syntax: <element ng-disabled="expression"> Contents... </element> Example 1: This example uses ng-disabled Directive to disable the button. html <!DOCTYPE html><html> <head> <title>ng-disabled Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-disabled Directive</h2> <div ng-controller="app" ng-init="disable=false"> <button ng-click="geek(disable)" ng-disabled="disable"> Click to Disable </button> <button ng-click="geek(disable)" ng-show="disable"> Click to Enable </button> </div> <script> var app = angular.module("app", []); app.controller('app', ['$scope', function ($app) { $app.geek = function (disable) { $app.disable = !disable; } }]); </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example uses ng-disabled Directive to enable and disable button using checkbox. html <!DOCTYPE html><html> <head> <title>ng-disabled Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-disabled Directive</h2> <div ng-controller="geek"> <h4> Check it <input type="checkbox" ng-model="check" /> </h4> <button type="button" ng-disabled="!(check)"> Click to submit </button> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.disableClick = function (isDisabled) { $scope.isDisabled = !isDisabled; } }]); </script></body> </html> Output: Before clicking the button: After clicking the button: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25518, "s": 25490, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25784, "s": 25518, "text": "The ng-disabled Directive in AngularJS is used to enable or disable HTML elements. If the expression inside the ng-disabled attribute returns true then the form field will be disabled or vice versa. It is usually applied on form field (input, select, button, etc). " }, { "code": null, "e": 25794, "s": 25784, "text": "Syntax: " }, { "code": null, "e": 25852, "s": 25794, "text": "<element ng-disabled=\"expression\"> Contents... </element>" }, { "code": null, "e": 25928, "s": 25852, "text": "Example 1: This example uses ng-disabled Directive to disable the button. " }, { "code": null, "e": 25933, "s": 25928, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>ng-disabled Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-disabled Directive</h2> <div ng-controller=\"app\" ng-init=\"disable=false\"> <button ng-click=\"geek(disable)\" ng-disabled=\"disable\"> Click to Disable </button> <button ng-click=\"geek(disable)\" ng-show=\"disable\"> Click to Enable </button> </div> <script> var app = angular.module(\"app\", []); app.controller('app', ['$scope', function ($app) { $app.geek = function (disable) { $app.disable = !disable; } }]); </script></body> </html>", "e": 26794, "s": 25933, "text": null }, { "code": null, "e": 26832, "s": 26794, "text": "Output: Before clicking the button: " }, { "code": null, "e": 26861, "s": 26832, "text": "After clicking the button: " }, { "code": null, "e": 26961, "s": 26863, "text": "Example 2: This example uses ng-disabled Directive to enable and disable button using checkbox. " }, { "code": null, "e": 26966, "s": 26961, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>ng-disabled Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-disabled Directive</h2> <div ng-controller=\"geek\"> <h4> Check it <input type=\"checkbox\" ng-model=\"check\" /> </h4> <button type=\"button\" ng-disabled=\"!(check)\"> Click to submit </button> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.disableClick = function (isDisabled) { $scope.isDisabled = !isDisabled; } }]); </script></body> </html>", "e": 27809, "s": 26966, "text": null }, { "code": null, "e": 27847, "s": 27809, "text": "Output: Before clicking the button: " }, { "code": null, "e": 27876, "s": 27847, "text": "After clicking the button: " }, { "code": null, "e": 27895, "s": 27876, "text": "Supported Browser:" }, { "code": null, "e": 27909, "s": 27895, "text": "Google Chrome" }, { "code": null, "e": 27924, "s": 27909, "text": "Microsoft Edge" }, { "code": null, "e": 27932, "s": 27924, "text": "Firefox" }, { "code": null, "e": 27938, "s": 27932, "text": "Opera" }, { "code": null, "e": 27945, "s": 27938, "text": "Safari" }, { "code": null, "e": 27957, "s": 27945, "text": "ysachin2314" }, { "code": null, "e": 27978, "s": 27957, "text": "AngularJS-Directives" }, { "code": null, "e": 27988, "s": 27978, "text": "AngularJS" }, { "code": null, "e": 28005, "s": 27988, "text": "Web Technologies" }, { "code": null, "e": 28103, "s": 28005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28138, "s": 28103, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28169, "s": 28138, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 28204, "s": 28169, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28246, "s": 28204, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 28291, "s": 28246, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 28331, "s": 28291, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28364, "s": 28331, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28409, "s": 28364, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28452, "s": 28409, "text": "How to fetch data from an API in ReactJS ?" } ]
Program to convert Java list of Strings to Seq in Scala - GeeksforGeeks
14 Jan, 2020 A java list of Strings can be converted to sequence in Scala by utilizing toSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur.Now, lets see some examples and then discuss how it works in details.Example:1# // Scala program to convert Java list // to Sequence in Scala // Importing Scala's JavaConversions objectimport scala.collection.JavaConversions._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of Strings in Java val list = new java.util.ArrayList[String]() // Adding Strings to the list list.add("geeks") list.add("cs") list.add("portal") // Converting list to Sequence val seq= list.toSeq // Displays seq println(seq) }} Buffer(geeks, cs, portal) Example:2# // Scala program to convert Java list // to Sequence in Scala // Importing Scala's JavaConversions objectimport scala.collection.JavaConversions._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of Strings in Java val list = new java.util.ArrayList[String]() // Adding Strings to the list list.add("i") list.add("am an") list.add("author") // Converting list to Sequence val seq= list.toSeq // Displays seq println(seq) }} Buffer(i, am an, author) Scala scala-collection Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in Scala Scala | Traits Scala ListBuffer Scala | Case Class and Case Object Hello World in Scala Scala | Functions - Basics Scala | Decision Making (if, if-else, Nested if-else, if-else if) Scala List map() method with example Comments In Scala Scala | Try-Catch Exceptions
[ { "code": null, "e": 25301, "s": 25273, "text": "\n14 Jan, 2020" }, { "code": null, "e": 25605, "s": 25301, "text": "A java list of Strings can be converted to sequence in Scala by utilizing toSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur.Now, lets see some examples and then discuss how it works in details.Example:1#" }, { "code": "// Scala program to convert Java list // to Sequence in Scala // Importing Scala's JavaConversions objectimport scala.collection.JavaConversions._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of Strings in Java val list = new java.util.ArrayList[String]() // Adding Strings to the list list.add(\"geeks\") list.add(\"cs\") list.add(\"portal\") // Converting list to Sequence val seq= list.toSeq // Displays seq println(seq) }}", "e": 26206, "s": 25605, "text": null }, { "code": null, "e": 26233, "s": 26206, "text": "Buffer(geeks, cs, portal)\n" }, { "code": null, "e": 26244, "s": 26233, "text": "Example:2#" }, { "code": "// Scala program to convert Java list // to Sequence in Scala // Importing Scala's JavaConversions objectimport scala.collection.JavaConversions._ // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating list of Strings in Java val list = new java.util.ArrayList[String]() // Adding Strings to the list list.add(\"i\") list.add(\"am an\") list.add(\"author\") // Converting list to Sequence val seq= list.toSeq // Displays seq println(seq) }}", "e": 26848, "s": 26244, "text": null }, { "code": null, "e": 26874, "s": 26848, "text": "Buffer(i, am an, author)\n" }, { "code": null, "e": 26880, "s": 26874, "text": "Scala" }, { "code": null, "e": 26897, "s": 26880, "text": "scala-collection" }, { "code": null, "e": 26910, "s": 26897, "text": "Scala-Method" }, { "code": null, "e": 26916, "s": 26910, "text": "Scala" }, { "code": null, "e": 27014, "s": 26916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27035, "s": 27014, "text": "Inheritance in Scala" }, { "code": null, "e": 27050, "s": 27035, "text": "Scala | Traits" }, { "code": null, "e": 27067, "s": 27050, "text": "Scala ListBuffer" }, { "code": null, "e": 27102, "s": 27067, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 27123, "s": 27102, "text": "Hello World in Scala" }, { "code": null, "e": 27150, "s": 27123, "text": "Scala | Functions - Basics" }, { "code": null, "e": 27216, "s": 27150, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" }, { "code": null, "e": 27253, "s": 27216, "text": "Scala List map() method with example" }, { "code": null, "e": 27271, "s": 27253, "text": "Comments In Scala" } ]
Print all possible combinations of words from Dictionary using Trie - GeeksforGeeks
13 Feb, 2020 Given an array of strings arr[], for every string in the array, print all possible combinations of strings that can be concatenated to make that word. Examples: Input: arr[] = ["sam", "sung", "samsung"] Output: sam: sam sung: sung samsung: sam sung samsung String 'samsung' can be formed using two different strings from the array i.e. 'sam' and 'sung' whereas 'samsung' itself is also a string in the array. Input: arr[] = ["ice", "cream", "icecream"] Output: ice: ice cream: cream icecream: ice cream icecream Approach: Add all the given strings into trie. Process every prefix character by character and check if it forms a word from trie by searching. If the prefix is present in the trie then add it to the result and proceed further with the remaining suffix in the string. Once it reaches the end of the string, print all the combinations found. Below is the implementation of the above approach: CPP Java C# // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // Trie nodestruct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if node // represents the end of the word bool isEndOfWord;}; // Returns new trie nodestruct TrieNode*getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node,// marks the node as leaf nodevoid insert(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // Mark node as leaf pCrawl->isEndOfWord = true;} // Returns true if the key is present in the triebool search(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isEndOfWord);} // Result stores the current prefix with// spaces between wordsvoid wordBreakAll(TrieNode* root, string word, int n, string result){ // Process all prefixes one by one for (int i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix string prefix = word.substr(0, i); // If trie conatins this prefix then check // for the remaining string. // Otherwise ignore this prefix if (search(root, prefix)) { // If no more elements are there then print if (i == n) { // Add this element to the previous prefix result += prefix; // If(result == word) then return // If you don't want to print last word cout << "\t" << result << endl; return; } wordBreakAll(root, word.substr(i, n - i), n - i, result + prefix + " "); } }} // Driver codeint main(){ struct TrieNode* root = getNode(); string dictionary[] = { "sam", "sung", "samsung" }; int n = sizeof(dictionary) / sizeof(string); for (int i = 0; i < n; i++) { insert(root, dictionary[i]); } for (int i = 0; i < n; i++) { cout << dictionary[i] << ": \n"; wordBreakAll(root, dictionary[i], dictionary[i].length(), ""); } return 0;} // Java implementation of the approachclass GFG{ static int ALPHABET_SIZE = 26; // Trie nodestatic class TrieNode{ TrieNode []children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if node // represents the end of the word boolean isEndOfWord; public TrieNode() { super(); } }; // Returns new trie nodestatic TrieNode getNode(){ TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode.children[i] = null; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node,// marks the node as leaf nodestatic void insert(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); pCrawl = pCrawl.children[index]; } // Mark node as leaf pCrawl.isEndOfWord = true;} // Returns true if the key is present in the triestatic boolean search(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord);} // Result stores the current prefix with// spaces between wordsstatic void wordBreakAll(TrieNode root, String word, int n, String result){ // Process all prefixes one by one for (int i = 1; i <= n; i++) { // Extract subString from 0 to i in prefix String prefix = word.substring(0, i); // If trie conatins this prefix then check // for the remaining String. // Otherwise ignore this prefix if (search(root, prefix)) { // If no more elements are there then print if (i == n) { // Add this element to the previous prefix result += prefix; // If(result == word) then return // If you don't want to print last word System.out.print("\t" + result +"\n"); return; } wordBreakAll(root, word.substring(i, n), n - i, result + prefix + " "); } }} // Driver codepublic static void main(String[] args){ new TrieNode(); TrieNode root = getNode(); String dictionary[] = {"sam", "sung", "samsung"}; int n = dictionary.length; for (int i = 0; i < n; i++) { insert(root, dictionary[i]); } for (int i = 0; i < n; i++) { System.out.print(dictionary[i]+ ": \n"); wordBreakAll(root, dictionary[i], dictionary[i].length(), ""); }}} // This code is contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ static int ALPHABET_SIZE = 26; // Trie nodeclass TrieNode{ public TrieNode []children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if node // represents the end of the word public bool isEndOfWord; public TrieNode() { } }; // Returns new trie nodestatic TrieNode getNode(){ TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode.children[i] = null; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node,// marks the node as leaf nodestatic void insert(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.Length; i++) { int index = key[i] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); pCrawl = pCrawl.children[index]; } // Mark node as leaf pCrawl.isEndOfWord = true;} // Returns true if the key is present in the triestatic bool search(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.Length; i++) { int index = key[i] - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord);} // Result stores the current prefix with// spaces between wordsstatic void wordBreakAll(TrieNode root, String word, int n, String result){ // Process all prefixes one by one for (int i = 1; i <= n; i++) { // Extract subString from 0 to i in prefix String prefix = word.Substring(0, i); // If trie conatins this prefix then check // for the remaining String. // Otherwise ignore this prefix if (search(root, prefix)) { // If no more elements are there then print if (i == n) { // Add this element to the previous prefix result += prefix; // If(result == word) then return // If you don't want to print last word Console.Write("\t" + result +"\n"); return; } wordBreakAll(root, word.Substring(i, n - i), n - i, result + prefix + " "); } }} // Driver codepublic static void Main(String[] args){ new TrieNode(); TrieNode root = getNode(); String []dictionary = {"sam", "sung", "samsung"}; int n = dictionary.Length; for (int i = 0; i < n; i++) { insert(root, dictionary[i]); } for (int i = 0; i < n; i++) { Console.Write(dictionary[i]+ ": \n"); wordBreakAll(root, dictionary[i], dictionary[i].Length, ""); }}} // This code is contributed by PrinciRaj1992 sam: sam sung: sung samsung: sam sung samsung princiraj1992 Technical Scripter 2019 Trie Arrays Backtracking Strings Technical Scripter Arrays Strings Backtracking Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element N Queen Problem | Backtracking-3 Write a program to print all permutations of a given string Backtracking | Introduction Rat in a Maze | Backtracking-2 The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 26065, "s": 26037, "text": "\n13 Feb, 2020" }, { "code": null, "e": 26216, "s": 26065, "text": "Given an array of strings arr[], for every string in the array, print all possible combinations of strings that can be concatenated to make that word." }, { "code": null, "e": 26226, "s": 26216, "text": "Examples:" }, { "code": null, "e": 26619, "s": 26226, "text": "Input: arr[] = [\"sam\", \"sung\", \"samsung\"]\nOutput:\nsam: \n sam\nsung: \n sung\nsamsung: \n sam sung\n samsung\nString 'samsung' can be formed using two different \nstrings from the array i.e. 'sam' and 'sung' whereas \n'samsung' itself is also a string in the array.\n\nInput: arr[] = [\"ice\", \"cream\", \"icecream\"]\nOutput:\nice: \n ice\ncream: \n cream\nicecream: \n ice cream\n icecream\n" }, { "code": null, "e": 26629, "s": 26619, "text": "Approach:" }, { "code": null, "e": 26666, "s": 26629, "text": "Add all the given strings into trie." }, { "code": null, "e": 26763, "s": 26666, "text": "Process every prefix character by character and check if it forms a word from trie by searching." }, { "code": null, "e": 26887, "s": 26763, "text": "If the prefix is present in the trie then add it to the result and proceed further with the remaining suffix in the string." }, { "code": null, "e": 26960, "s": 26887, "text": "Once it reaches the end of the string, print all the combinations found." }, { "code": null, "e": 27011, "s": 26960, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27015, "s": 27011, "text": "CPP" }, { "code": null, "e": 27020, "s": 27015, "text": "Java" }, { "code": null, "e": 27023, "s": 27020, "text": "C#" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // Trie nodestruct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if node // represents the end of the word bool isEndOfWord;}; // Returns new trie nodestruct TrieNode*getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node,// marks the node as leaf nodevoid insert(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // Mark node as leaf pCrawl->isEndOfWord = true;} // Returns true if the key is present in the triebool search(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isEndOfWord);} // Result stores the current prefix with// spaces between wordsvoid wordBreakAll(TrieNode* root, string word, int n, string result){ // Process all prefixes one by one for (int i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix string prefix = word.substr(0, i); // If trie conatins this prefix then check // for the remaining string. // Otherwise ignore this prefix if (search(root, prefix)) { // If no more elements are there then print if (i == n) { // Add this element to the previous prefix result += prefix; // If(result == word) then return // If you don't want to print last word cout << \"\\t\" << result << endl; return; } wordBreakAll(root, word.substr(i, n - i), n - i, result + prefix + \" \"); } }} // Driver codeint main(){ struct TrieNode* root = getNode(); string dictionary[] = { \"sam\", \"sung\", \"samsung\" }; int n = sizeof(dictionary) / sizeof(string); for (int i = 0; i < n; i++) { insert(root, dictionary[i]); } for (int i = 0; i < n; i++) { cout << dictionary[i] << \": \\n\"; wordBreakAll(root, dictionary[i], dictionary[i].length(), \"\"); } return 0;}", "e": 29792, "s": 27023, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int ALPHABET_SIZE = 26; // Trie nodestatic class TrieNode{ TrieNode []children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if node // represents the end of the word boolean isEndOfWord; public TrieNode() { super(); } }; // Returns new trie nodestatic TrieNode getNode(){ TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode.children[i] = null; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node,// marks the node as leaf nodestatic void insert(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); pCrawl = pCrawl.children[index]; } // Mark node as leaf pCrawl.isEndOfWord = true;} // Returns true if the key is present in the triestatic boolean search(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord);} // Result stores the current prefix with// spaces between wordsstatic void wordBreakAll(TrieNode root, String word, int n, String result){ // Process all prefixes one by one for (int i = 1; i <= n; i++) { // Extract subString from 0 to i in prefix String prefix = word.substring(0, i); // If trie conatins this prefix then check // for the remaining String. // Otherwise ignore this prefix if (search(root, prefix)) { // If no more elements are there then print if (i == n) { // Add this element to the previous prefix result += prefix; // If(result == word) then return // If you don't want to print last word System.out.print(\"\\t\" + result +\"\\n\"); return; } wordBreakAll(root, word.substring(i, n), n - i, result + prefix + \" \"); } }} // Driver codepublic static void main(String[] args){ new TrieNode(); TrieNode root = getNode(); String dictionary[] = {\"sam\", \"sung\", \"samsung\"}; int n = dictionary.length; for (int i = 0; i < n; i++) { insert(root, dictionary[i]); } for (int i = 0; i < n; i++) { System.out.print(dictionary[i]+ \": \\n\"); wordBreakAll(root, dictionary[i], dictionary[i].length(), \"\"); }}} // This code is contributed by PrinciRaj1992", "e": 32712, "s": 29792, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int ALPHABET_SIZE = 26; // Trie nodeclass TrieNode{ public TrieNode []children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if node // represents the end of the word public bool isEndOfWord; public TrieNode() { } }; // Returns new trie nodestatic TrieNode getNode(){ TrieNode pNode = new TrieNode(); pNode.isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode.children[i] = null; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node,// marks the node as leaf nodestatic void insert(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.Length; i++) { int index = key[i] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = getNode(); pCrawl = pCrawl.children[index]; } // Mark node as leaf pCrawl.isEndOfWord = true;} // Returns true if the key is present in the triestatic bool search(TrieNode root, String key){ TrieNode pCrawl = root; for (int i = 0; i < key.Length; i++) { int index = key[i] - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord);} // Result stores the current prefix with// spaces between wordsstatic void wordBreakAll(TrieNode root, String word, int n, String result){ // Process all prefixes one by one for (int i = 1; i <= n; i++) { // Extract subString from 0 to i in prefix String prefix = word.Substring(0, i); // If trie conatins this prefix then check // for the remaining String. // Otherwise ignore this prefix if (search(root, prefix)) { // If no more elements are there then print if (i == n) { // Add this element to the previous prefix result += prefix; // If(result == word) then return // If you don't want to print last word Console.Write(\"\\t\" + result +\"\\n\"); return; } wordBreakAll(root, word.Substring(i, n - i), n - i, result + prefix + \" \"); } }} // Driver codepublic static void Main(String[] args){ new TrieNode(); TrieNode root = getNode(); String []dictionary = {\"sam\", \"sung\", \"samsung\"}; int n = dictionary.Length; for (int i = 0; i < n; i++) { insert(root, dictionary[i]); } for (int i = 0; i < n; i++) { Console.Write(dictionary[i]+ \": \\n\"); wordBreakAll(root, dictionary[i], dictionary[i].Length, \"\"); }}} // This code is contributed by PrinciRaj1992", "e": 35608, "s": 32712, "text": null }, { "code": null, "e": 35674, "s": 35608, "text": "sam: \n sam\nsung: \n sung\nsamsung: \n sam sung\n samsung\n" }, { "code": null, "e": 35688, "s": 35674, "text": "princiraj1992" }, { "code": null, "e": 35712, "s": 35688, "text": "Technical Scripter 2019" }, { "code": null, "e": 35717, "s": 35712, "text": "Trie" }, { "code": null, "e": 35724, "s": 35717, "text": "Arrays" }, { "code": null, "e": 35737, "s": 35724, "text": "Backtracking" }, { "code": null, "e": 35745, "s": 35737, "text": "Strings" }, { "code": null, "e": 35764, "s": 35745, "text": "Technical Scripter" }, { "code": null, "e": 35771, "s": 35764, "text": "Arrays" }, { "code": null, "e": 35779, "s": 35771, "text": "Strings" }, { "code": null, "e": 35792, "s": 35779, "text": "Backtracking" }, { "code": null, "e": 35797, "s": 35792, "text": "Trie" }, { "code": null, "e": 35895, "s": 35797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35922, "s": 35895, "text": "Count pairs with given sum" }, { "code": null, "e": 35953, "s": 35922, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35978, "s": 35953, "text": "Window Sliding Technique" }, { "code": null, "e": 36016, "s": 35978, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36037, "s": 36016, "text": "Next Greater Element" }, { "code": null, "e": 36070, "s": 36037, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 36130, "s": 36070, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36158, "s": 36130, "text": "Backtracking | Introduction" }, { "code": null, "e": 36189, "s": 36158, "text": "Rat in a Maze | Backtracking-2" } ]
How to sort an array in a single loop? - GeeksforGeeks
11 Jun, 2021 Given an array of size N, the task is to sort this array using a single loop.How the array is sorted usually? There are many ways by which the array can be sorted in ascending order, like: Selection Sort Binary Sort Merge Sort Radix Sort Insertion Sort, etc In any of these methods, more than 1 loops is used.Can the array the sorted using a single loop? Since all the known sorting methods use more than 1 loop, it is hard to imagine to do the same with a single loop. Practically, it is not impossible to do so. But doing so won’t be the most efficient. Example 1: Below code will sort an array with integer elements. C++ Java Python3 C# Javascript // C++ code to sort an array of integers// with the help of single loop#include<bits/stdc++.h>using namespace std; // Function for Sorting the array// using a single loopint *sortArrays(int arr[], int length){ // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr;} // Driver codeint main(){ // Declaring an integer array of size 11. int arr[] = { 1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3 }; // Printing the original Array. int length = sizeof(arr)/sizeof(arr[0]); string str; for (int i: arr) { str += to_string(i)+" "; } cout<<"Original array: [" << str << "]" << endl; // Sorting the array using a single loop int *arr1; arr1 = sortArrays(arr, length); // Printing the sorted array. string str1; for (int i = 0; i < length; i++) { str1 += to_string(arr1[i])+" "; } cout << "Sorted array: [" << (str1) << "]";} // This code is contributed by Rajout-Ji // Java code to sort an array of integers// with the help of single loop import java.util.*; class Geeks_For_Geeks { // Function for Sorting the array // using a single loop public static int[] sortArrays(int[] arr) { // Finding the length of array 'arr' int length = arr.length; // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr; } // Declaring main method public static void main(String args[]) { // Declaring an integer array of size 11. int arr[] = { 1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3 }; // Printing the original Array. System.out.println("Original array: " + Arrays.toString(arr)); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. System.out.println("Sorted array: " + Arrays.toString(arr)); }} # Python3 code to sort an array of integers# with the help of single loop # Function for Sorting the array# using a single loopdef sortArrays(arr): # Finding the length of array 'arr' length = len(arr) # Sorting using a single loop j = 0 while j < length - 1: # Checking the condition for two # simultaneous elements of the array if (arr[j] > arr[j + 1]): # Swapping the elements. temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp # updating the value of j = -1 # so after getting updated for j++ # in the loop it becomes 0 and # the loop begins from the start. j = -1 j += 1 return arr # Driver Codeif __name__ == '__main__': # Declaring an integer array of size 11. arr = [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3] # Printing the original Array. print("Original array: ", arr) # Sorting the array using a single loop arr = sortArrays(arr) # Printing the sorted array. print("Sorted array: ", arr) # This code is contributed by Mohit Kumar // C# code to sort an array of integers// with the help of single loopusing System; class GFG{ // Function for Sorting the array // using a single loop public static int[] sortArrays(int[] arr) { // Finding the length of array 'arr' int length = arr.Length; // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr; } // Driver Code public static void Main(String []args) { // Declaring an integer array of size 11. int []arr = { 1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3 }; // Printing the original Array. Console.WriteLine("Original array: " + String.Join(", ", arr)); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. Console.WriteLine("Sorted array: " + String.Join(", ", arr)); }} // This code is contributed by Rajput-Ji <script>// Javascript code to sort an array of integers// with the help of single loop // Function for Sorting the array // using a single loopfunction sortArrays(arr){ // Finding the length of array 'arr' let length = arr.length; // Sorting using a single loop for (let j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr;} // Declaring main methodlet arr=[1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3];document.write("Original array: [" + (arr).join(", ")+"]<br>");// Sorting the array using a single looparr = sortArrays(arr); // Printing the sorted array.document.write("Sorted array: [" + arr.join(", ")+"]<br>"); // This code is contributed by patel2127</script> Original array: [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3] Sorted array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99] Example 2: Below code will sort an array of Strings. C++ Java Python3 C# Javascript // C++ code to sort an array of Strings// with the help of single loop#include<bits/stdc++.h>using namespace std; // Function for Sorting the array using a single loopchar* sortArrays(char arr[], int length){ // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Type Conversion of char to int. int d1 = arr[j]; int d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr;} // Driver codeint main(){ // Declaring a String string geeks = "GEEKSFORGEEKS"; int n = geeks.length(); // declaring character array char arr[n]; // copying the contents of the // string to char array for(int i = 0; i < n; i++) { arr[i] = geeks[i]; } // Printing the original Array. cout<<"Original array: ["; for(int i = 0; i < n; i++) { cout << arr[i]; if(i + 1 != n) cout<<", "; } cout << "]" << endl; // Sorting the array using a single loop char *ansarr; ansarr = sortArrays(arr, n); // Printing the sorted array. cout << "Sorted array: ["; for(int i = 0; i < n; i++) { cout << ansarr[i]; if(i + 1 != n) cout << ", "; } cout << "]" << endl;} // This code is contributed by Rajput-Ji // Java code to sort an array of Strings// with the help of single loop import java.util.*; class Geeks_For_Geeks { // Function for Sorting the array using a single loop public static char[] sortArrays(char[] arr) { // Finding the length of array 'arr' int length = arr.length; // Sorting using a single loop for (int j = 0; j < arr.length - 1; j++) { // Type Conversion of char to int. int d1 = arr[j]; int d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr; } // Declaring main method public static void main(String args[]) { // Declaring a String String geeks = "GEEKSFORGEEKS"; // Declaring a character array // to store characters of geeks in it. char arr[] = geeks.toCharArray(); // Printing the original Array. System.out.println("Original array: " + Arrays.toString(arr)); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. System.out.println("Sorted array: " + Arrays.toString(arr)); }} # Python3 code to sort an array of Strings# with the help of single loop # Function for Sorting the array using a single loopdef sortArrays(arr, length): # Sorting using a single loop j = 0 while(j < length - 1): # Type Conversion of char to int. d1 = arr[j] d2 = arr[j + 1] # Comparing the ascii code. if (d1 > d2): # Swapping of the characters temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp j = -1 j += 1 return arr # Driver code # Declaring a Stringgeeks = "GEEKSFORGEEKS"n = len(geeks) # declaring character arrayarr=[0]*n # copying the contents of the# string to char arrayfor i in range(n): arr[i] = geeks[i] # Printing the original Array.print("Original array: [",end="") for i in range(n): print(arr[i],end="") if (i + 1 != n): print(", ",end="") print("]") # Sorting the array using a single loopansarr = sortArrays(arr, n) # Printing the sorted array.print("Sorted array: [",end="") for i in range(n): print(ansarr[i],end="") if (i + 1 != n): print(", ",end="") print("]") # This code is contributed by shubhamsingh10 // C# code to sort an array of Strings// with the help of single loopusing System; class GFG{ // Function for Sorting the array // using a single loop public static char[] sortArrays(char[] arr) { // Finding the length of array 'arr' int length = arr.Length; // Sorting using a single loop for (int j = 0; j < arr.Length - 1; j++) { // Type Conversion of char to int. int d1 = arr[j]; int d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr; } // Declaring main method public static void Main(String []args) { // Declaring a String String geeks = "GEEKSFORGEEKS"; // Declaring a character array // to store characters of geeks in it. char []arr = geeks.ToCharArray(); // Printing the original Array. Console.WriteLine("Original array: [" + String.Join(", ", arr) + "]"); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. Console.WriteLine("Sorted array: [" + String.Join(", ", arr) + "]"); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript code to sort an array of integers// with the help of single loop // Function for Sorting the array// using a single loopfunction sortArrays(arr){ // Finding the length of array 'arr' let length = arr.length; // Sorting using a single loop for (let j = 0; j < length - 1; j++) { // Type Conversion of char to int. let d1 = arr[j]; let d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr; } // Declaring a String let geeks = "GEEKSFORGEEKS"; // Declaring a character array // to store characters of geeks in it. let arr = geeks.split(""); document.write("Original array: [" + arr.join(", ")+"]<br>");// Sorting the array using a single looparr = sortArrays(arr); // Printing the sorted array.document.write("Sorted array: [" + (arr).join(", ")+"]<br>"); // This code is contributed by shivanisinghss2110 </script> Original array: [G, E, E, K, S, F, O, R, G, E, E, K, S] Sorted array: [E, E, E, E, F, G, G, K, K, O, R, S, S] Is sorting array in single loop better than sorting in more than one loop? Sorting in a single loop, though it seems to be better, is not an efficient approach. Below are some points to be taken into consideration before using single loop sorting: Using a single loop only helps in shorter code The time complexity of the sorting does not change in a single loop (in comparison to more than one loop sorting) Single loop sorting shows that number of loops has little to do with time complexity of the algorithm. mohit kumar 29 Rajput-Ji princiraj1992 SHUBHAMSINGH10 patel2127 shivanisinghss2110 Sorting Technical Scripter Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem C++ Program for QuickSort Stability in sorting algorithms Quick Sort vs Merge Sort Sorting in Java Quickselect Algorithm Recursive Bubble Sort Check if two arrays are equal or not Longest Common Prefix using Sorting Python | Sort a List according to the Length of the Elements
[ { "code": null, "e": 25323, "s": 25295, "text": "\n11 Jun, 2021" }, { "code": null, "e": 25514, "s": 25323, "text": "Given an array of size N, the task is to sort this array using a single loop.How the array is sorted usually? There are many ways by which the array can be sorted in ascending order, like: " }, { "code": null, "e": 25529, "s": 25514, "text": "Selection Sort" }, { "code": null, "e": 25541, "s": 25529, "text": "Binary Sort" }, { "code": null, "e": 25552, "s": 25541, "text": "Merge Sort" }, { "code": null, "e": 25563, "s": 25552, "text": "Radix Sort" }, { "code": null, "e": 25583, "s": 25563, "text": "Insertion Sort, etc" }, { "code": null, "e": 25946, "s": 25583, "text": "In any of these methods, more than 1 loops is used.Can the array the sorted using a single loop? Since all the known sorting methods use more than 1 loop, it is hard to imagine to do the same with a single loop. Practically, it is not impossible to do so. But doing so won’t be the most efficient. Example 1: Below code will sort an array with integer elements. " }, { "code": null, "e": 25950, "s": 25946, "text": "C++" }, { "code": null, "e": 25955, "s": 25950, "text": "Java" }, { "code": null, "e": 25963, "s": 25955, "text": "Python3" }, { "code": null, "e": 25966, "s": 25963, "text": "C#" }, { "code": null, "e": 25977, "s": 25966, "text": "Javascript" }, { "code": "// C++ code to sort an array of integers// with the help of single loop#include<bits/stdc++.h>using namespace std; // Function for Sorting the array// using a single loopint *sortArrays(int arr[], int length){ // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr;} // Driver codeint main(){ // Declaring an integer array of size 11. int arr[] = { 1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3 }; // Printing the original Array. int length = sizeof(arr)/sizeof(arr[0]); string str; for (int i: arr) { str += to_string(i)+\" \"; } cout<<\"Original array: [\" << str << \"]\" << endl; // Sorting the array using a single loop int *arr1; arr1 = sortArrays(arr, length); // Printing the sorted array. string str1; for (int i = 0; i < length; i++) { str1 += to_string(arr1[i])+\" \"; } cout << \"Sorted array: [\" << (str1) << \"]\";} // This code is contributed by Rajout-Ji", "e": 27496, "s": 25977, "text": null }, { "code": "// Java code to sort an array of integers// with the help of single loop import java.util.*; class Geeks_For_Geeks { // Function for Sorting the array // using a single loop public static int[] sortArrays(int[] arr) { // Finding the length of array 'arr' int length = arr.length; // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr; } // Declaring main method public static void main(String args[]) { // Declaring an integer array of size 11. int arr[] = { 1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3 }; // Printing the original Array. System.out.println(\"Original array: \" + Arrays.toString(arr)); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. System.out.println(\"Sorted array: \" + Arrays.toString(arr)); }}", "e": 28990, "s": 27496, "text": null }, { "code": "# Python3 code to sort an array of integers# with the help of single loop # Function for Sorting the array# using a single loopdef sortArrays(arr): # Finding the length of array 'arr' length = len(arr) # Sorting using a single loop j = 0 while j < length - 1: # Checking the condition for two # simultaneous elements of the array if (arr[j] > arr[j + 1]): # Swapping the elements. temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp # updating the value of j = -1 # so after getting updated for j++ # in the loop it becomes 0 and # the loop begins from the start. j = -1 j += 1 return arr # Driver Codeif __name__ == '__main__': # Declaring an integer array of size 11. arr = [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3] # Printing the original Array. print(\"Original array: \", arr) # Sorting the array using a single loop arr = sortArrays(arr) # Printing the sorted array. print(\"Sorted array: \", arr) # This code is contributed by Mohit Kumar", "e": 30119, "s": 28990, "text": null }, { "code": "// C# code to sort an array of integers// with the help of single loopusing System; class GFG{ // Function for Sorting the array // using a single loop public static int[] sortArrays(int[] arr) { // Finding the length of array 'arr' int length = arr.Length; // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr; } // Driver Code public static void Main(String []args) { // Declaring an integer array of size 11. int []arr = { 1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3 }; // Printing the original Array. Console.WriteLine(\"Original array: \" + String.Join(\", \", arr)); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. Console.WriteLine(\"Sorted array: \" + String.Join(\", \", arr)); }} // This code is contributed by Rajput-Ji", "e": 31639, "s": 30119, "text": null }, { "code": "<script>// Javascript code to sort an array of integers// with the help of single loop // Function for Sorting the array // using a single loopfunction sortArrays(arr){ // Finding the length of array 'arr' let length = arr.length; // Sorting using a single loop for (let j = 0; j < length - 1; j++) { // Checking the condition for two // simultaneous elements of the array if (arr[j] > arr[j + 1]) { // Swapping the elements. let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // updating the value of j = -1 // so after getting updated for j++ // in the loop it becomes 0 and // the loop begins from the start. j = -1; } } return arr;} // Declaring main methodlet arr=[1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3];document.write(\"Original array: [\" + (arr).join(\", \")+\"]<br>\");// Sorting the array using a single looparr = sortArrays(arr); // Printing the sorted array.document.write(\"Sorted array: [\" + arr.join(\", \")+\"]<br>\"); // This code is contributed by patel2127</script>", "e": 32917, "s": 31639, "text": null }, { "code": null, "e": 33017, "s": 32917, "text": "Original array: [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3]\nSorted array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99]" }, { "code": null, "e": 33074, "s": 33019, "text": "Example 2: Below code will sort an array of Strings. " }, { "code": null, "e": 33078, "s": 33074, "text": "C++" }, { "code": null, "e": 33083, "s": 33078, "text": "Java" }, { "code": null, "e": 33091, "s": 33083, "text": "Python3" }, { "code": null, "e": 33094, "s": 33091, "text": "C#" }, { "code": null, "e": 33105, "s": 33094, "text": "Javascript" }, { "code": "// C++ code to sort an array of Strings// with the help of single loop#include<bits/stdc++.h>using namespace std; // Function for Sorting the array using a single loopchar* sortArrays(char arr[], int length){ // Sorting using a single loop for (int j = 0; j < length - 1; j++) { // Type Conversion of char to int. int d1 = arr[j]; int d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr;} // Driver codeint main(){ // Declaring a String string geeks = \"GEEKSFORGEEKS\"; int n = geeks.length(); // declaring character array char arr[n]; // copying the contents of the // string to char array for(int i = 0; i < n; i++) { arr[i] = geeks[i]; } // Printing the original Array. cout<<\"Original array: [\"; for(int i = 0; i < n; i++) { cout << arr[i]; if(i + 1 != n) cout<<\", \"; } cout << \"]\" << endl; // Sorting the array using a single loop char *ansarr; ansarr = sortArrays(arr, n); // Printing the sorted array. cout << \"Sorted array: [\"; for(int i = 0; i < n; i++) { cout << ansarr[i]; if(i + 1 != n) cout << \", \"; } cout << \"]\" << endl;} // This code is contributed by Rajput-Ji", "e": 34608, "s": 33105, "text": null }, { "code": "// Java code to sort an array of Strings// with the help of single loop import java.util.*; class Geeks_For_Geeks { // Function for Sorting the array using a single loop public static char[] sortArrays(char[] arr) { // Finding the length of array 'arr' int length = arr.length; // Sorting using a single loop for (int j = 0; j < arr.length - 1; j++) { // Type Conversion of char to int. int d1 = arr[j]; int d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr; } // Declaring main method public static void main(String args[]) { // Declaring a String String geeks = \"GEEKSFORGEEKS\"; // Declaring a character array // to store characters of geeks in it. char arr[] = geeks.toCharArray(); // Printing the original Array. System.out.println(\"Original array: \" + Arrays.toString(arr)); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. System.out.println(\"Sorted array: \" + Arrays.toString(arr)); }}", "e": 36019, "s": 34608, "text": null }, { "code": "# Python3 code to sort an array of Strings# with the help of single loop # Function for Sorting the array using a single loopdef sortArrays(arr, length): # Sorting using a single loop j = 0 while(j < length - 1): # Type Conversion of char to int. d1 = arr[j] d2 = arr[j + 1] # Comparing the ascii code. if (d1 > d2): # Swapping of the characters temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp j = -1 j += 1 return arr # Driver code # Declaring a Stringgeeks = \"GEEKSFORGEEKS\"n = len(geeks) # declaring character arrayarr=[0]*n # copying the contents of the# string to char arrayfor i in range(n): arr[i] = geeks[i] # Printing the original Array.print(\"Original array: [\",end=\"\") for i in range(n): print(arr[i],end=\"\") if (i + 1 != n): print(\", \",end=\"\") print(\"]\") # Sorting the array using a single loopansarr = sortArrays(arr, n) # Printing the sorted array.print(\"Sorted array: [\",end=\"\") for i in range(n): print(ansarr[i],end=\"\") if (i + 1 != n): print(\", \",end=\"\") print(\"]\") # This code is contributed by shubhamsingh10", "e": 37242, "s": 36019, "text": null }, { "code": "// C# code to sort an array of Strings// with the help of single loopusing System; class GFG{ // Function for Sorting the array // using a single loop public static char[] sortArrays(char[] arr) { // Finding the length of array 'arr' int length = arr.Length; // Sorting using a single loop for (int j = 0; j < arr.Length - 1; j++) { // Type Conversion of char to int. int d1 = arr[j]; int d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr; } // Declaring main method public static void Main(String []args) { // Declaring a String String geeks = \"GEEKSFORGEEKS\"; // Declaring a character array // to store characters of geeks in it. char []arr = geeks.ToCharArray(); // Printing the original Array. Console.WriteLine(\"Original array: [\" + String.Join(\", \", arr) + \"]\"); // Sorting the array using a single loop arr = sortArrays(arr); // Printing the sorted array. Console.WriteLine(\"Sorted array: [\" + String.Join(\", \", arr) + \"]\"); }} // This code is contributed by PrinciRaj1992", "e": 38715, "s": 37242, "text": null }, { "code": "<script> // JavaScript code to sort an array of integers// with the help of single loop // Function for Sorting the array// using a single loopfunction sortArrays(arr){ // Finding the length of array 'arr' let length = arr.length; // Sorting using a single loop for (let j = 0; j < length - 1; j++) { // Type Conversion of char to int. let d1 = arr[j]; let d2 = arr[j + 1]; // Comparing the ascii code. if (d1 > d2) { // Swapping of the characters let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j = -1; } } return arr; } // Declaring a String let geeks = \"GEEKSFORGEEKS\"; // Declaring a character array // to store characters of geeks in it. let arr = geeks.split(\"\"); document.write(\"Original array: [\" + arr.join(\", \")+\"]<br>\");// Sorting the array using a single looparr = sortArrays(arr); // Printing the sorted array.document.write(\"Sorted array: [\" + (arr).join(\", \")+\"]<br>\"); // This code is contributed by shivanisinghss2110 </script>", "e": 39984, "s": 38715, "text": null }, { "code": null, "e": 40094, "s": 39984, "text": "Original array: [G, E, E, K, S, F, O, R, G, E, E, K, S]\nSorted array: [E, E, E, E, F, G, G, K, K, O, R, S, S]" }, { "code": null, "e": 40346, "s": 40096, "text": "Is sorting array in single loop better than sorting in more than one loop? Sorting in a single loop, though it seems to be better, is not an efficient approach. Below are some points to be taken into consideration before using single loop sorting: " }, { "code": null, "e": 40393, "s": 40346, "text": "Using a single loop only helps in shorter code" }, { "code": null, "e": 40507, "s": 40393, "text": "The time complexity of the sorting does not change in a single loop (in comparison to more than one loop sorting)" }, { "code": null, "e": 40610, "s": 40507, "text": "Single loop sorting shows that number of loops has little to do with time complexity of the algorithm." }, { "code": null, "e": 40627, "s": 40612, "text": "mohit kumar 29" }, { "code": null, "e": 40637, "s": 40627, "text": "Rajput-Ji" }, { "code": null, "e": 40651, "s": 40637, "text": "princiraj1992" }, { "code": null, "e": 40666, "s": 40651, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 40676, "s": 40666, "text": "patel2127" }, { "code": null, "e": 40695, "s": 40676, "text": "shivanisinghss2110" }, { "code": null, "e": 40703, "s": 40695, "text": "Sorting" }, { "code": null, "e": 40722, "s": 40703, "text": "Technical Scripter" }, { "code": null, "e": 40730, "s": 40722, "text": "Sorting" }, { "code": null, "e": 40828, "s": 40730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40859, "s": 40828, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 40885, "s": 40859, "text": "C++ Program for QuickSort" }, { "code": null, "e": 40917, "s": 40885, "text": "Stability in sorting algorithms" }, { "code": null, "e": 40942, "s": 40917, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 40958, "s": 40942, "text": "Sorting in Java" }, { "code": null, "e": 40980, "s": 40958, "text": "Quickselect Algorithm" }, { "code": null, "e": 41002, "s": 40980, "text": "Recursive Bubble Sort" }, { "code": null, "e": 41039, "s": 41002, "text": "Check if two arrays are equal or not" }, { "code": null, "e": 41075, "s": 41039, "text": "Longest Common Prefix using Sorting" } ]
C - Input and Output
When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement. When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files. C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen. The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen. The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen. The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example − #include <stdio.h> int main( ) { int c; printf( "Enter a value :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows − $./a.out Enter a value : this is test You entered: t The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File). The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout. NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you want to use fgets(). #include <stdio.h> int main( ) { char str[100]; printf( "Enter a value :"); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows − $./a.out Enter a value : this is test You entered: this is test The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided. The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better − #include <stdio.h> int main( ) { char str[100]; int i; printf( "Enter a value :"); scanf("%s %d", str, &i); printf( "\nYou entered: %s %d ", str, i); return 0; } When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows − $./a.out Enter a value : seven 7 You entered: seven 7 Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like "string integer". If you provide "string string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for scanf(). Print Add Notes Bookmark this page
[ { "code": null, "e": 2338, "s": 2084, "text": "When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement." }, { "code": null, "e": 2564, "s": 2338, "text": "When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files." }, { "code": null, "e": 2806, "s": 2564, "text": "C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen." }, { "code": null, "e": 2990, "s": 2806, "text": "The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen." }, { "code": null, "e": 3257, "s": 2990, "text": "The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen." }, { "code": null, "e": 3546, "s": 3257, "text": "The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example −" }, { "code": null, "e": 3706, "s": 3546, "text": "#include <stdio.h>\nint main( ) {\n\n int c;\n\n printf( \"Enter a value :\");\n c = getchar( );\n\n printf( \"\\nYou entered: \");\n putchar( c );\n\n return 0;\n}" }, { "code": null, "e": 3917, "s": 3706, "text": "When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows −" }, { "code": null, "e": 3971, "s": 3917, "text": "$./a.out\nEnter a value : this is test\nYou entered: t\n" }, { "code": null, "e": 4117, "s": 3971, "text": "The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File)." }, { "code": null, "e": 4212, "s": 4117, "text": "The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout." }, { "code": null, "e": 4320, "s": 4212, "text": "NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you want to use fgets()." }, { "code": null, "e": 4484, "s": 4320, "text": "#include <stdio.h>\nint main( ) {\n\n char str[100];\n\n printf( \"Enter a value :\");\n gets( str );\n\n printf( \"\\nYou entered: \");\n puts( str );\n\n return 0;\n}" }, { "code": null, "e": 4699, "s": 4484, "text": "When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows −" }, { "code": null, "e": 4764, "s": 4699, "text": "$./a.out\nEnter a value : this is test\nYou entered: this is test\n" }, { "code": null, "e": 4921, "s": 4764, "text": "The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided." }, { "code": null, "e": 5083, "s": 4921, "text": "The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided." }, { "code": null, "e": 5405, "s": 5083, "text": "The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better −" }, { "code": null, "e": 5589, "s": 5405, "text": "#include <stdio.h>\nint main( ) {\n\n char str[100];\n int i;\n\n printf( \"Enter a value :\");\n scanf(\"%s %d\", str, &i);\n\n printf( \"\\nYou entered: %s %d \", str, i);\n\n return 0;\n}" }, { "code": null, "e": 5782, "s": 5589, "text": "When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows −" }, { "code": null, "e": 5837, "s": 5782, "text": "$./a.out\nEnter a value : seven 7\nYou entered: seven 7\n" }, { "code": null, "e": 6235, "s": 5837, "text": "Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like \"string integer\". If you provide \"string string\" or \"integer integer\", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so \"this is test\" are three strings for scanf()." }, { "code": null, "e": 6242, "s": 6235, "text": " Print" }, { "code": null, "e": 6253, "s": 6242, "text": " Add Notes" } ]
Java Program For Closest Prime Number - GeeksforGeeks
22 Dec, 2021 Given a number N, you have to print its closest prime number. The prime number can be lesser, equal, or greater than the given number. Condition: 1 ≤ N ≤ 100000 Examples: Input : 16 Output: 17 Explanation: The two nearer prime number of 16 are 13 and 17. But among these, 17 is the closest(As its distance is only 1(17-16) from the given number). Input : 97 Output : 97 Explanation : The closest prime number in this case is the given number number itself as the distance is 0 (97-97). Approach : Using Sieve of Eratosthenes store all prime numbers in a Vector.Copy all elements in vector to the new array.Use the upper bound to find the upper bound of the given number in an array.As the array is already sorted in nature, compare previous and current indexed numbers in an array.Return number with the smallest difference. Using Sieve of Eratosthenes store all prime numbers in a Vector. Copy all elements in vector to the new array. Use the upper bound to find the upper bound of the given number in an array. As the array is already sorted in nature, compare previous and current indexed numbers in an array. Return number with the smallest difference. Below is the implementation of the approach. Java // Closest Prime Number in Java import java.util.*;import java.lang.*; public class GFG { static int max = 100005; static Vector<Integer> primeNumber = new Vector<>(); static void sieveOfEratosthenes() { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. boolean prime[] = new boolean[max + 1]; for (int i = 0; i <= max; i++) prime[i] = true; for (int p = 2; p * p <= max; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= max; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= max; i++) { if (prime[i] == true) primeNumber.add(i); } } static int upper_bound(Integer arr[], int low, int high, int X) { // Base Case if (low > high) return low; // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is less than // or equal to X search in // right subarray if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } // If arr[mid] is greater than X // then search in left subarray return upper_bound(arr, low, mid - 1, X); } public static int closetPrime(int number) { // We will handle it (for number = 1) explicitly // as the lower/left number of 1 can give us // negative index which will cost Runtime Error. if (number == 1) return 2; else { // calling sieve of eratosthenes to // fill the array into prime numbers sieveOfEratosthenes(); Integer[] arr = primeNumber.toArray( new Integer[primeNumber.size()]); // searching the index int index = upper_bound(arr, 0, arr.length, number); if (arr[index] == number || arr[index - 1] == number) return number; else if (Math.abs(arr[index] - number) < Math.abs(arr[index - 1] - number)) return arr[index]; else return arr[index - 1]; } } // Driver Program public static void main(String[] args) { int number = 100; System.out.println(closetPrime(number)); }} 101 Time Complexity: O(N log(log(N))) Space Complexity: O(N) jyoti369 surindertarika1234 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23583, "s": 23555, "text": "\n22 Dec, 2021" }, { "code": null, "e": 23718, "s": 23583, "text": "Given a number N, you have to print its closest prime number. The prime number can be lesser, equal, or greater than the given number." }, { "code": null, "e": 23744, "s": 23718, "text": "Condition: 1 ≤ N ≤ 100000" }, { "code": null, "e": 23754, "s": 23744, "text": "Examples:" }, { "code": null, "e": 24074, "s": 23754, "text": "Input : 16\nOutput: 17\n\nExplanation: The two nearer prime number of 16 are 13 and 17. But among these, \n17 is the closest(As its distance is only 1(17-16) from the given number).\n\nInput : 97\nOutput : 97\n\nExplanation : The closest prime number in this case is the given number number \nitself as the distance is 0 (97-97)." }, { "code": null, "e": 24086, "s": 24074, "text": "Approach : " }, { "code": null, "e": 24414, "s": 24086, "text": "Using Sieve of Eratosthenes store all prime numbers in a Vector.Copy all elements in vector to the new array.Use the upper bound to find the upper bound of the given number in an array.As the array is already sorted in nature, compare previous and current indexed numbers in an array.Return number with the smallest difference." }, { "code": null, "e": 24479, "s": 24414, "text": "Using Sieve of Eratosthenes store all prime numbers in a Vector." }, { "code": null, "e": 24525, "s": 24479, "text": "Copy all elements in vector to the new array." }, { "code": null, "e": 24602, "s": 24525, "text": "Use the upper bound to find the upper bound of the given number in an array." }, { "code": null, "e": 24702, "s": 24602, "text": "As the array is already sorted in nature, compare previous and current indexed numbers in an array." }, { "code": null, "e": 24746, "s": 24702, "text": "Return number with the smallest difference." }, { "code": null, "e": 24791, "s": 24746, "text": "Below is the implementation of the approach." }, { "code": null, "e": 24796, "s": 24791, "text": "Java" }, { "code": "// Closest Prime Number in Java import java.util.*;import java.lang.*; public class GFG { static int max = 100005; static Vector<Integer> primeNumber = new Vector<>(); static void sieveOfEratosthenes() { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. boolean prime[] = new boolean[max + 1]; for (int i = 0; i <= max; i++) prime[i] = true; for (int p = 2; p * p <= max; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= max; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= max; i++) { if (prime[i] == true) primeNumber.add(i); } } static int upper_bound(Integer arr[], int low, int high, int X) { // Base Case if (low > high) return low; // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is less than // or equal to X search in // right subarray if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } // If arr[mid] is greater than X // then search in left subarray return upper_bound(arr, low, mid - 1, X); } public static int closetPrime(int number) { // We will handle it (for number = 1) explicitly // as the lower/left number of 1 can give us // negative index which will cost Runtime Error. if (number == 1) return 2; else { // calling sieve of eratosthenes to // fill the array into prime numbers sieveOfEratosthenes(); Integer[] arr = primeNumber.toArray( new Integer[primeNumber.size()]); // searching the index int index = upper_bound(arr, 0, arr.length, number); if (arr[index] == number || arr[index - 1] == number) return number; else if (Math.abs(arr[index] - number) < Math.abs(arr[index - 1] - number)) return arr[index]; else return arr[index - 1]; } } // Driver Program public static void main(String[] args) { int number = 100; System.out.println(closetPrime(number)); }}", "e": 27432, "s": 24796, "text": null }, { "code": null, "e": 27436, "s": 27432, "text": "101" }, { "code": null, "e": 27470, "s": 27436, "text": "Time Complexity: O(N log(log(N)))" }, { "code": null, "e": 27493, "s": 27470, "text": "Space Complexity: O(N)" }, { "code": null, "e": 27502, "s": 27493, "text": "jyoti369" }, { "code": null, "e": 27521, "s": 27502, "text": "surindertarika1234" }, { "code": null, "e": 27526, "s": 27521, "text": "Java" }, { "code": null, "e": 27540, "s": 27526, "text": "Java Programs" }, { "code": null, "e": 27545, "s": 27540, "text": "Java" }, { "code": null, "e": 27643, "s": 27545, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27652, "s": 27643, "text": "Comments" }, { "code": null, "e": 27665, "s": 27652, "text": "Old Comments" }, { "code": null, "e": 27695, "s": 27665, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27710, "s": 27695, "text": "Stream In Java" }, { "code": null, "e": 27731, "s": 27710, "text": "Constructors in Java" }, { "code": null, "e": 27777, "s": 27731, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27796, "s": 27777, "text": "Exceptions in Java" }, { "code": null, "e": 27840, "s": 27796, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27866, "s": 27840, "text": "Java Programming Examples" }, { "code": null, "e": 27900, "s": 27866, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27947, "s": 27900, "text": "Implementing a Linked List in Java using Class" } ]
How to Use Lambda for Efficient Python Code | by Khuyen Tran | Towards Data Science
What this graph reminds you of? Amplification of amplitude in a wave? How can this be made? You take a closer look at the graph and realize something interesting. It looks like as x increases, the value on the y-axis first goes down to -1 then goes up to 1, goes down to -2 then goes up to 2, and so on. This gives you the idea that the graph can be made using a list like this [0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9] If you use matplotlib with the list above as an argument, you should have the graph that is close to the graph above: This looks easy. Once you understand how the graph could be created using a list, you could easily recreate the wave graph. But what if you want to create a much cooler graph that requires a much bigger list, like this? You definitely don’t want to write the list above manually with 200 numbers on the list. So you have to figure out how to use Python to create the list with the number range from (n,m) but with the 0 starts at the beginning, proceeded by -1, 1,-2,2,...n. This list is not difficult to create if we realize that the list sorted by the absolute value of the elements |0|, |-1|, |1|, |-2|, |2|, .., n. So something with sorted and absolute value would work? Bingo! I will show you how to easily create this sort of function on one line of code with lambda. Hey, I am glad you ask. lambda keyword in Python provides a shortcut for declaring small anonymous functions. It behaves just like regular functions. They can be used as an alternative for function objects. Let’s have a small example of how to replace function with lambdas: def mult(x,y): return x*ymult(2,6) Outcome: 12 We can make the code above shorter with lambda mult = lambda x, y: x*ymult(2,6) But do we need to define the name of the multiplication anyway? After all, we just want to create a function that could multiply 2 numbers right? We can reduce the function above to even simpler code: (lambda x, y: x*y)(2, 6) That looks shorter. But why should you bother to learn about lambda , just to save a few lines of code anyway? Because lambda could help you create something more sophisticated easily. Like sorting a list of tuples based on their alphabets: tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')]sorted(tuples, key=lambda x: x[1]) Outcome: [(4, 'a'), (2, 'b'), (3, 'c'), (1, 'd')] This gives you a hint of how to create a graph above using lambda. Ready? Here it is: import matplotlib.pyplot as pltnums = plt.plot(sorted(range(-100, 101), key=lambda x: x * x))plt.plot(nums) Give us the graph: Want to create a function that could take a number to the power of another number? We could use the combination of nested function and lambda : def power(n): return lambda x: x**npower_3 = power(3)list(map(power_3,[2,3,4,5])) Outcome: [8, 27, 64, 125] Or use lambda to manipulate a pandas Dataframe import pandas as pddf = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c']) #Create the 4th column that is the sum of the other 3 columnsdf['d'] = df.apply(lambda row: row['a']+row['b']+row['c'],axis=1) Congratulation! Now you know how to use lambda as a shortcut for functions. I encourage you to use lambda when you want to create a nameless function for a short period of time. You could also use it as an argument to a higher-order function like above or used along with functions like filter() , map() , apply(). I hope this tutorial will give you some motivations and reasons to switch some of your Python code with lambda . A small change in your code could give you a big return in time and efficiency as you increasingly incorporate more sophisticated code for your data science projects. Feel free to fork and play with the code for this article in this Github repo. 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": 549, "s": 171, "text": "What this graph reminds you of? Amplification of amplitude in a wave? How can this be made? You take a closer look at the graph and realize something interesting. It looks like as x increases, the value on the y-axis first goes down to -1 then goes up to 1, goes down to -2 then goes up to 2, and so on. This gives you the idea that the graph can be made using a list like this" }, { "code": null, "e": 616, "s": 549, "text": "[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9]" }, { "code": null, "e": 734, "s": 616, "text": "If you use matplotlib with the list above as an argument, you should have the graph that is close to the graph above:" }, { "code": null, "e": 954, "s": 734, "text": "This looks easy. Once you understand how the graph could be created using a list, you could easily recreate the wave graph. But what if you want to create a much cooler graph that requires a much bigger list, like this?" }, { "code": null, "e": 1139, "s": 954, "text": "You definitely don’t want to write the list above manually with 200 numbers on the list. So you have to figure out how to use Python to create the list with the number range from (n,m)" }, { "code": null, "e": 1209, "s": 1139, "text": "but with the 0 starts at the beginning, proceeded by -1, 1,-2,2,...n." }, { "code": null, "e": 1508, "s": 1209, "text": "This list is not difficult to create if we realize that the list sorted by the absolute value of the elements |0|, |-1|, |1|, |-2|, |2|, .., n. So something with sorted and absolute value would work? Bingo! I will show you how to easily create this sort of function on one line of code with lambda." }, { "code": null, "e": 1783, "s": 1508, "text": "Hey, I am glad you ask. lambda keyword in Python provides a shortcut for declaring small anonymous functions. It behaves just like regular functions. They can be used as an alternative for function objects. Let’s have a small example of how to replace function with lambdas:" }, { "code": null, "e": 1819, "s": 1783, "text": "def mult(x,y): return x*ymult(2,6)" }, { "code": null, "e": 1831, "s": 1819, "text": "Outcome: 12" }, { "code": null, "e": 1878, "s": 1831, "text": "We can make the code above shorter with lambda" }, { "code": null, "e": 1911, "s": 1878, "text": "mult = lambda x, y: x*ymult(2,6)" }, { "code": null, "e": 2112, "s": 1911, "text": "But do we need to define the name of the multiplication anyway? After all, we just want to create a function that could multiply 2 numbers right? We can reduce the function above to even simpler code:" }, { "code": null, "e": 2137, "s": 2112, "text": "(lambda x, y: x*y)(2, 6)" }, { "code": null, "e": 2378, "s": 2137, "text": "That looks shorter. But why should you bother to learn about lambda , just to save a few lines of code anyway? Because lambda could help you create something more sophisticated easily. Like sorting a list of tuples based on their alphabets:" }, { "code": null, "e": 2462, "s": 2378, "text": "tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')]sorted(tuples, key=lambda x: x[1])" }, { "code": null, "e": 2471, "s": 2462, "text": "Outcome:" }, { "code": null, "e": 2512, "s": 2471, "text": "[(4, 'a'), (2, 'b'), (3, 'c'), (1, 'd')]" }, { "code": null, "e": 2598, "s": 2512, "text": "This gives you a hint of how to create a graph above using lambda. Ready? Here it is:" }, { "code": null, "e": 2706, "s": 2598, "text": "import matplotlib.pyplot as pltnums = plt.plot(sorted(range(-100, 101), key=lambda x: x * x))plt.plot(nums)" }, { "code": null, "e": 2725, "s": 2706, "text": "Give us the graph:" }, { "code": null, "e": 2869, "s": 2725, "text": "Want to create a function that could take a number to the power of another number? We could use the combination of nested function and lambda :" }, { "code": null, "e": 2952, "s": 2869, "text": "def power(n): return lambda x: x**npower_3 = power(3)list(map(power_3,[2,3,4,5]))" }, { "code": null, "e": 2961, "s": 2952, "text": "Outcome:" }, { "code": null, "e": 2978, "s": 2961, "text": "[8, 27, 64, 125]" }, { "code": null, "e": 3025, "s": 2978, "text": "Or use lambda to manipulate a pandas Dataframe" }, { "code": null, "e": 3104, "s": 3025, "text": "import pandas as pddf = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])" }, { "code": null, "e": 3231, "s": 3104, "text": "#Create the 4th column that is the sum of the other 3 columnsdf['d'] = df.apply(lambda row: row['a']+row['b']+row['c'],axis=1)" }, { "code": null, "e": 3546, "s": 3231, "text": "Congratulation! Now you know how to use lambda as a shortcut for functions. I encourage you to use lambda when you want to create a nameless function for a short period of time. You could also use it as an argument to a higher-order function like above or used along with functions like filter() , map() , apply()." }, { "code": null, "e": 3826, "s": 3546, "text": "I hope this tutorial will give you some motivations and reasons to switch some of your Python code with lambda . A small change in your code could give you a big return in time and efficiency as you increasingly incorporate more sophisticated code for your data science projects." }, { "code": null, "e": 3905, "s": 3826, "text": "Feel free to fork and play with the code for this article in this Github repo." }, { "code": null, "e": 4065, "s": 3905, "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." } ]
Python 3 - String rstrip() Method
The rstrip() method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters). Following is the syntax for rstrip() method − str.rstrip([chars]) chars − You can supply what chars have to be trimmed. This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters). The following example shows the usage of rstrip() method. #!/usr/bin/python3 str = " this is string example....wow!!! " print (str.rstrip()) str = "*****this is string example....wow!!!*****" print (str.rstrip('*')) When we run above program, it produces the following result − this is string example....wow!!! *****this is string example....wow!!! 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2487, "s": 2340, "text": "The rstrip() method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters)." }, { "code": null, "e": 2533, "s": 2487, "text": "Following is the syntax for rstrip() method −" }, { "code": null, "e": 2554, "s": 2533, "text": "str.rstrip([chars])\n" }, { "code": null, "e": 2608, "s": 2554, "text": "chars − You can supply what chars have to be trimmed." }, { "code": null, "e": 2747, "s": 2608, "text": "This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters)." }, { "code": null, "e": 2805, "s": 2747, "text": "The following example shows the usage of rstrip() method." }, { "code": null, "e": 2973, "s": 2805, "text": "#!/usr/bin/python3\n\nstr = \" this is string example....wow!!! \"\nprint (str.rstrip())\n\nstr = \"*****this is string example....wow!!!*****\"\nprint (str.rstrip('*'))" }, { "code": null, "e": 3035, "s": 2973, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3112, "s": 3035, "text": " this is string example....wow!!!\n*****this is string example....wow!!!\n" }, { "code": null, "e": 3149, "s": 3112, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3165, "s": 3149, "text": " Malhar Lathkar" }, { "code": null, "e": 3198, "s": 3165, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3217, "s": 3198, "text": " Arnab Chakraborty" }, { "code": null, "e": 3252, "s": 3217, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3274, "s": 3252, "text": " In28Minutes Official" }, { "code": null, "e": 3308, "s": 3274, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3336, "s": 3308, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3371, "s": 3336, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3385, "s": 3371, "text": " Lets Kode It" }, { "code": null, "e": 3418, "s": 3385, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3435, "s": 3418, "text": " Abhilash Nelson" }, { "code": null, "e": 3442, "s": 3435, "text": " Print" }, { "code": null, "e": 3453, "s": 3442, "text": " Add Notes" } ]
MongoDB query to search date records using only Month and Day
To search using month and day only, use $where. Let us create a collection with documents − > db.demo181.insertOne({"ShippingDate":new ISODate("2020-01-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5e398a699e4f06af551997fe") } > db.demo181.insertOne({"ShippingDate":new ISODate("2019-12-11")}); { "acknowledged" : true, "insertedId" : ObjectId("5e398a729e4f06af551997ff") } > db.demo181.insertOne({"ShippingDate":new ISODate("2018-01-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5e398a7d9e4f06af55199800") } > db.demo181.insertOne({"ShippingDate":new ISODate("2020-10-12")}); { "acknowledged" : true, "insertedId" : ObjectId("5e398a879e4f06af55199801") } Display all documents from a collection with the help of find() method − > db.demo181.find(); This will produce the following output − { "_id" : ObjectId("5e398a699e4f06af551997fe"), "ShippingDate" : ISODate("2020-01-10T00:00:00Z") } { "_id" : ObjectId("5e398a729e4f06af551997ff"), "ShippingDate" : ISODate("2019-12-11T00:00:00Z") } { "_id" : ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate" : ISODate("2018-01-10T00:00:00Z") } { "_id" : ObjectId("5e398a879e4f06af55199801"), "ShippingDate" : ISODate("2020-10-12T00:00:00Z") } Following is the query to search with Month and Day − > db.demo181.find({$where : function() { return this.ShippingDate.getMonth() == 1 || this.ShippingDate.getDate() == 10} }) This will produce the following output − { "_id" : ObjectId("5e398a699e4f06af551997fe"), "ShippingDate" : ISODate("2020-01-10T00:00:00Z") } { "_id" : ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate" : ISODate("2018-01-10T00:00:00Z") }
[ { "code": null, "e": 1154, "s": 1062, "text": "To search using month and day only, use $where. Let us create a collection with documents −" }, { "code": null, "e": 1766, "s": 1154, "text": "> db.demo181.insertOne({\"ShippingDate\":new ISODate(\"2020-01-10\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e398a699e4f06af551997fe\")\n}\n> db.demo181.insertOne({\"ShippingDate\":new ISODate(\"2019-12-11\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e398a729e4f06af551997ff\")\n}\n> db.demo181.insertOne({\"ShippingDate\":new ISODate(\"2018-01-10\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e398a7d9e4f06af55199800\")\n}\n> db.demo181.insertOne({\"ShippingDate\":new ISODate(\"2020-10-12\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e398a879e4f06af55199801\")\n}" }, { "code": null, "e": 1839, "s": 1766, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1860, "s": 1839, "text": "> db.demo181.find();" }, { "code": null, "e": 1901, "s": 1860, "text": "This will produce the following output −" }, { "code": null, "e": 2297, "s": 1901, "text": "{ \"_id\" : ObjectId(\"5e398a699e4f06af551997fe\"), \"ShippingDate\" : ISODate(\"2020-01-10T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e398a729e4f06af551997ff\"), \"ShippingDate\" : ISODate(\"2019-12-11T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e398a7d9e4f06af55199800\"), \"ShippingDate\" : ISODate(\"2018-01-10T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e398a879e4f06af55199801\"), \"ShippingDate\" : ISODate(\"2020-10-12T00:00:00Z\") }" }, { "code": null, "e": 2351, "s": 2297, "text": "Following is the query to search with Month and Day −" }, { "code": null, "e": 2474, "s": 2351, "text": "> db.demo181.find({$where : function() { return this.ShippingDate.getMonth() == 1 || this.ShippingDate.getDate() == 10} })" }, { "code": null, "e": 2515, "s": 2474, "text": "This will produce the following output −" }, { "code": null, "e": 2713, "s": 2515, "text": "{ \"_id\" : ObjectId(\"5e398a699e4f06af551997fe\"), \"ShippingDate\" : ISODate(\"2020-01-10T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e398a7d9e4f06af55199800\"), \"ShippingDate\" : ISODate(\"2018-01-10T00:00:00Z\") }" } ]
Calculate total time duration (add time) in MySQL?
To calculate the total time duration in MySQL, you need to use SEC_TO_TIME(). Let us see an example by creating a table mysql> create table AddTotalTimeDemo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > LoginTime time - > ); Query OK, 0 rows affected (0.63 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into AddTotalTimeDemo(LoginTime) values('05:05:00'); Query OK, 1 row affected (0.10 sec) mysql> insert into AddTotalTimeDemo(LoginTime) values('07:20:00'); Query OK, 1 row affected (0.16 sec) mysql> insert into AddTotalTimeDemo(LoginTime) values('02:05:00'); Query OK, 1 row affected (0.17 sec) mysql> insert into AddTotalTimeDemo(LoginTime) values('03:03:00'); Query OK, 1 row affected (0.25 sec) mysql> insert into AddTotalTimeDemo(LoginTime) values('05:07:00'); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement. The query is as follows mysql> select *from AddTotalTimeDemo; The following is the output +----+-----------+ | Id | LoginTime | +----+-----------+ | 1 | 05:05:00 | | 2 | 07:20:00 | | 3 | 02:05:00 | | 4 | 03:03:00 | | 5 | 05:07:00 | +----+-----------+ 5 rows in set (0.00 sec) The following is the query to calculate the total time duration in MySQL mysql> SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(LoginTime))) AS TotalTime from AddTotalTimeDemo; The following is the output +-----------+ | TotalTime | +-----------+ | 22:40:00 | +-----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1182, "s": 1062, "text": "To calculate the total time duration in MySQL, you need to use SEC_TO_TIME(). Let us see an example by creating a table" }, { "code": null, "e": 1348, "s": 1182, "text": "mysql> create table AddTotalTimeDemo\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > LoginTime time\n - > );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1403, "s": 1348, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1427, "s": 1403, "text": "The query is as follows" }, { "code": null, "e": 1942, "s": 1427, "text": "mysql> insert into AddTotalTimeDemo(LoginTime) values('05:05:00');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into AddTotalTimeDemo(LoginTime) values('07:20:00');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AddTotalTimeDemo(LoginTime) values('02:05:00');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into AddTotalTimeDemo(LoginTime) values('03:03:00');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into AddTotalTimeDemo(LoginTime) values('05:07:00');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2001, "s": 1942, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2025, "s": 2001, "text": "The query is as follows" }, { "code": null, "e": 2063, "s": 2025, "text": "mysql> select *from AddTotalTimeDemo;" }, { "code": null, "e": 2091, "s": 2063, "text": "The following is the output" }, { "code": null, "e": 2287, "s": 2091, "text": "+----+-----------+\n| Id | LoginTime |\n+----+-----------+\n| 1 | 05:05:00 |\n| 2 | 07:20:00 |\n| 3 | 02:05:00 |\n| 4 | 03:03:00 |\n| 5 | 05:07:00 |\n+----+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2360, "s": 2287, "text": "The following is the query to calculate the total time duration in MySQL" }, { "code": null, "e": 2451, "s": 2360, "text": "mysql> SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(LoginTime))) AS TotalTime from AddTotalTimeDemo;" }, { "code": null, "e": 2479, "s": 2451, "text": "The following is the output" }, { "code": null, "e": 2573, "s": 2479, "text": "+-----------+\n| TotalTime |\n+-----------+\n| 22:40:00 |\n+-----------+\n1 row in set (0.00 sec)" } ]
Fortran - Pointers
In most programming languages, a pointer variable stores the memory address of an object. However, in Fortran, a pointer is a data object that has more functionalities than just storing the memory address. It contains more information about a particular object, like type, rank, extents, and memory address. A pointer is associated with a target by allocation or pointer assignment. A pointer variable is declared with the pointer attribute. The following examples shows declaration of pointer variables − integer, pointer :: p1 ! pointer to integer real, pointer, dimension (:) :: pra ! pointer to 1-dim real array real, pointer, dimension (:,:) :: pra2 ! pointer to 2-dim real array A pointer can point to − An area of dynamically allocated memory. An area of dynamically allocated memory. A data object of the same type as the pointer, with the target attribute. A data object of the same type as the pointer, with the target attribute. The allocate statement allows you to allocate space for a pointer object. For example − program pointerExample implicit none integer, pointer :: p1 allocate(p1) p1 = 1 Print *, p1 p1 = p1 + 4 Print *, p1 end program pointerExample When the above code is compiled and executed, it produces the following result − 1 5 You should empty the allocated storage space by the deallocate statement when it is no longer required and avoid accumulation of unused and unusable memory space. A target is another normal variable, with space set aside for it. A target variable must be declared with the target attribute. You associate a pointer variable with a target variable using the association operator (=>). Let us rewrite the previous example, to demonstrate the concept − program pointerExample implicit none integer, pointer :: p1 integer, target :: t1 p1=>t1 p1 = 1 Print *, p1 Print *, t1 p1 = p1 + 4 Print *, p1 Print *, t1 t1 = 8 Print *, p1 Print *, t1 end program pointerExample When the above code is compiled and executed, it produces the following result − 1 1 5 5 8 8 A pointer can be − Undefined Associated Disassociated In the above program, we have associated the pointer p1, with the target t1, using the => operator. The function associated, tests a pointer’s association status. The nullify statement disassociates a pointer from a target. Nullify does not empty the targets as there could be more than one pointer pointing to the same target. However, emptying the pointer implies nullification also. The following example demonstrates the concepts − program pointerExample implicit none integer, pointer :: p1 integer, target :: t1 integer, target :: t2 p1=>t1 p1 = 1 Print *, p1 Print *, t1 p1 = p1 + 4 Print *, p1 Print *, t1 t1 = 8 Print *, p1 Print *, t1 nullify(p1) Print *, t1 p1=>t2 Print *, associated(p1) Print*, associated(p1, t1) Print*, associated(p1, t2) !what is the value of p1 at present Print *, p1 Print *, t2 p1 = 10 Print *, p1 Print *, t2 end program pointerExample When the above code is compiled and executed, it produces the following result − 1 1 5 5 8 8 8 T F T 0 0 10 10 Please note that each time you run the code, the memory addresses will be different. program pointerExample implicit none integer, pointer :: a, b integer, target :: t integer :: n t = 1 a => t t = 2 b => t n = a + b Print *, a, b, t, n end program pointerExample When the above code is compiled and executed, it produces the following result − 2 2 2 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2454, "s": 2146, "text": "In most programming languages, a pointer variable stores the memory address of an object. However, in Fortran, a pointer is a data object that has more functionalities than just storing the memory address. It contains more information about a particular object, like type, rank, extents, and memory address." }, { "code": null, "e": 2529, "s": 2454, "text": "A pointer is associated with a target by allocation or pointer assignment." }, { "code": null, "e": 2588, "s": 2529, "text": "A pointer variable is declared with the pointer attribute." }, { "code": null, "e": 2652, "s": 2588, "text": "The following examples shows declaration of pointer variables −" }, { "code": null, "e": 2835, "s": 2652, "text": "integer, pointer :: p1 ! pointer to integer \nreal, pointer, dimension (:) :: pra ! pointer to 1-dim real array \nreal, pointer, dimension (:,:) :: pra2 ! pointer to 2-dim real array" }, { "code": null, "e": 2860, "s": 2835, "text": "A pointer can point to −" }, { "code": null, "e": 2901, "s": 2860, "text": "An area of dynamically allocated memory." }, { "code": null, "e": 2942, "s": 2901, "text": "An area of dynamically allocated memory." }, { "code": null, "e": 3016, "s": 2942, "text": "A data object of the same type as the pointer, with the target attribute." }, { "code": null, "e": 3090, "s": 3016, "text": "A data object of the same type as the pointer, with the target attribute." }, { "code": null, "e": 3178, "s": 3090, "text": "The allocate statement allows you to allocate space for a pointer object. For example −" }, { "code": null, "e": 3352, "s": 3178, "text": "program pointerExample\nimplicit none\n\n integer, pointer :: p1\n allocate(p1)\n \n p1 = 1\n Print *, p1\n \n p1 = p1 + 4\n Print *, p1\n \nend program pointerExample" }, { "code": null, "e": 3433, "s": 3352, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3438, "s": 3433, "text": "1\n5\n" }, { "code": null, "e": 3601, "s": 3438, "text": "You should empty the allocated storage space by the deallocate statement when it is no longer required and avoid accumulation of unused and unusable memory space." }, { "code": null, "e": 3729, "s": 3601, "text": "A target is another normal variable, with space set aside for it. A target variable must be declared with the target attribute." }, { "code": null, "e": 3822, "s": 3729, "text": "You associate a pointer variable with a target variable using the association operator (=>)." }, { "code": null, "e": 3888, "s": 3822, "text": "Let us rewrite the previous example, to demonstrate the concept −" }, { "code": null, "e": 4168, "s": 3888, "text": "program pointerExample\nimplicit none\n\n integer, pointer :: p1\n integer, target :: t1 \n \n p1=>t1\n p1 = 1\n \n Print *, p1\n Print *, t1\n \n p1 = p1 + 4\n \n Print *, p1\n Print *, t1\n \n t1 = 8\n \n Print *, p1\n Print *, t1\n \nend program pointerExample" }, { "code": null, "e": 4249, "s": 4168, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4262, "s": 4249, "text": "1\n1\n5\n5\n8\n8\n" }, { "code": null, "e": 4281, "s": 4262, "text": "A pointer can be −" }, { "code": null, "e": 4291, "s": 4281, "text": "Undefined" }, { "code": null, "e": 4302, "s": 4291, "text": "Associated" }, { "code": null, "e": 4316, "s": 4302, "text": "Disassociated" }, { "code": null, "e": 4479, "s": 4316, "text": "In the above program, we have associated the pointer p1, with the target t1, using the => operator. The function associated, tests a pointer’s association status." }, { "code": null, "e": 4540, "s": 4479, "text": "The nullify statement disassociates a pointer from a target." }, { "code": null, "e": 4702, "s": 4540, "text": "Nullify does not empty the targets as there could be more than one pointer pointing to the same target. However, emptying the pointer implies nullification also." }, { "code": null, "e": 4752, "s": 4702, "text": "The following example demonstrates the concepts −" }, { "code": null, "e": 5302, "s": 4752, "text": "program pointerExample\nimplicit none\n\n integer, pointer :: p1\n integer, target :: t1 \n integer, target :: t2\n \n p1=>t1\n p1 = 1\n \n Print *, p1\n Print *, t1\n \n p1 = p1 + 4\n Print *, p1\n Print *, t1\n \n t1 = 8\n Print *, p1\n Print *, t1\n \n nullify(p1)\n Print *, t1\n \n p1=>t2\n Print *, associated(p1)\n Print*, associated(p1, t1)\n Print*, associated(p1, t2)\n \n !what is the value of p1 at present\n Print *, p1\n Print *, t2\n \n p1 = 10\n Print *, p1\n Print *, t2\n \nend program pointerExample" }, { "code": null, "e": 5383, "s": 5302, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5414, "s": 5383, "text": "1\n1\n5\n5\n8\n8\n8\nT\nF\nT\n0\n0\n10\n10\n" }, { "code": null, "e": 5499, "s": 5414, "text": "Please note that each time you run the code, the memory addresses will be different." }, { "code": null, "e": 5719, "s": 5499, "text": "program pointerExample\nimplicit none\n\n integer, pointer :: a, b\n integer, target :: t\n integer :: n\n \n t = 1\n a => t\n t = 2\n b => t\n n = a + b\n \n Print *, a, b, t, n \n \nend program pointerExample" }, { "code": null, "e": 5800, "s": 5719, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5812, "s": 5800, "text": "2 2 2 4\n" }, { "code": null, "e": 5819, "s": 5812, "text": " Print" }, { "code": null, "e": 5830, "s": 5819, "text": " Add Notes" } ]
Optimize your CPU for Deep Learning | by Param Popat | Towards Data Science
In the last few years, Deep Learning has picked up pace in academia as well as industry. Every company is now looking for an A.I. based solution to problems. This boom has its own merits and demerits, but that’s for another article, another day. This surge in Machine Learning practitioners have infiltrated the academia to its roots, and almost every student from every domain has access to AI and ML knowledge via courses, MOOCs, books, articles, and of course papers. This rise was, however, bottlenecked by the availability of hardware resources. It was suggested and demonstrated that a Graphical Processing Unit is one of the best devices you can have to perform your ML tasks at pace. But a good high-performance GPU came with a price tag which can go even up to $20,449.00 for a single NVIDIA Tesla V100 32GB GPU which has server-like compute capabilities. Furthermore, a consumer laptop with a decent GPU costs around $2000 with a GPU like 1050Ti or 1080Ti. To ease the pain, Google, Kaggle, Intel, and Nvidia provides cloud-based High-Compute systems for free with a restriction on either space, compute capability, memory or time. But these online services have their drawbacks which include managing the data(upload/download), data privacy, etc. These issues lead to the main point of my article, “Why not optimize our CPUs to attain a speed-up in Deep Learning tasks?”. Intel has provided optimizations for Python, Tensorflow, Pytorch, etc. with a whole range of Intel Optimized support libraries like NumPy, scikit-learn and many more. These are freely available to download and set-up and provides a speed of anywhere from 2x to even 5x on a CPU like Intel Core i7 which is not also a high-performance CPU like the Xeon Series. In the remaining part of the article, I will demonstrate how to set-up Intel’s optimizations in your PC/laptop and will provide the speed-up data that I observed. For a variety of experiments mentioned below, I will present the time and utilization boosts that I observed. 10-layer Deep CNN for CIFAR-100 Image Classification.3 Layer Deep LSTM for IMDB Sentiment Analysis.6 Layer deep Dense ANN for MNIST image Classification.9 Layer deep Fully Convolutional Auto-Encoder for MNIST. 10-layer Deep CNN for CIFAR-100 Image Classification. 3 Layer Deep LSTM for IMDB Sentiment Analysis. 6 Layer deep Dense ANN for MNIST image Classification. 9 Layer deep Fully Convolutional Auto-Encoder for MNIST. These tasks have been coded in Keras using tensorflow backend and datasets are available in the same hard-drive as that of the codes and executable libraries. The hard-drive utilized is an SSD. We will consider six combinations of optimizations as following. Intel(R) Core (TM) i7.Intel(R) Xeon(R) CPU E3–1535M v6.Intel(R) Core (TM) i7 with Intel Python (Intel i7*).Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python (Intel Xeon*).Intel(R) Core (TM) i7 with Intel Python and Processor Thread optimization (Intel i7(O)).Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python and Processor Thread optimization (Intel Xeon(O)). Intel(R) Core (TM) i7. Intel(R) Xeon(R) CPU E3–1535M v6. Intel(R) Core (TM) i7 with Intel Python (Intel i7*). Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python (Intel Xeon*). Intel(R) Core (TM) i7 with Intel Python and Processor Thread optimization (Intel i7(O)). Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python and Processor Thread optimization (Intel Xeon(O)). For each task, the number epochs were fixed at 50. In the chart below we can see that for an Intel(R) Core (TM) i7–7700HQ CPU @ 2.80GHz CPU, the average time per epoch is nearly 4.67 seconds, and it drops to 1.48 seconds upon proper optimization, which is 3.2x boost up. And for an Intel(R) Xeon(R) CPU E3–1535M v6 @ 3.10GHz CPU, the average time per epoch is nearly 2.21 seconds, and it drops to 0.64 seconds upon proper optimization, which is a 3.45x boost up. The optimization is not just in time, the optimized distribution also optimizes the CPU utilization which eventually leads to better heat management, and your laptops won’t get as heated as they used to while training a deep neural network. We can see that without any optimization the CPU utilization while training maxes out to 100%, slowing down all the other processes and heating the system. However, with proper optimizations, the utilization drops to 70% for i7 and 65% for Xeon despite providing a performance gain in terms of time. These two metrics can be summarized in relative terms as follows. In the above graph, a lower value is better, that is in relative terms Intel Xeon with all the optimizations stands as the benchmark, and an Intel Core i7 processor takes almost twice as time as Xeon, per epoch, after optimizing its usage. The above graph clearly shows the bright side of Intel’s Python Optimization in terms of time taken to train a neural network and CPU’s usage. Intel Software has provided an exhaustive list of resources on how to set this up, but there are some issues which we may usually face. More details about distribution are available here. You can choose between the type of installation, that is, either native pip or conda. I prefer conda as it saves a ton of hassle for me and I can focus on ML rather than on solving compatibility issues for my libraries. You can download Anaconda from here. Their website has all the steps listed to install Anaconda on windows, ubuntu and macOS environments, and are easy to follow. This step is where it usually gets tricky. It is preferred to create a virtual environment for Intel distribution so that you can always add/change your optimized libraries at one place. Let’s create a new virtual environment with the name “intel.” conda create -n intel -c intel intelpython3_full Here -c represents channel, so instead of adding Intel as a channel, we call that channel via -c. Here, intelpython3_full will automatically fetch necessary libraries from Intel’s distribution and install them in your virtual environment. This command will install the following libraries. The following NEW packages will be INSTALLED:asn1crypto intel/win-64::asn1crypto-0.24.0-py36_3bzip2 intel/win-64::bzip2-1.0.6-vc14_17certifi intel/win-64::certifi-2018.1.18-py36_2cffi intel/win-64::cffi-1.11.5-py36_3chardet intel/win-64::chardet-3.0.4-py36_3cryptography intel/win-64::cryptography-2.3-py36_1cycler intel/win-64::cycler-0.10.0-py36_7cython intel/win-64::cython-0.29.3-py36_1daal intel/win-64::daal-2019.3-intel_203daal4py intel/win-64::daal4py-2019.3-py36h7b7c402_6freetype intel/win-64::freetype-2.9-vc14_3funcsigs intel/win-64::funcsigs-1.0.2-py36_7icc_rt intel/win-64::icc_rt-2019.3-intel_203idna intel/win-64::idna-2.6-py36_3impi_rt intel/win-64::impi_rt-2019.3-intel_203intel-openmp intel/win-64::intel-openmp-2019.3-intel_203intelpython intel/win-64::intelpython-2019.3-0intelpython3_core intel/win-64::intelpython3_core-2019.3-0intelpython3_full intel/win-64::intelpython3_full-2019.3-0kiwisolver intel/win-64::kiwisolver-1.0.1-py36_2libpng intel/win-64::libpng-1.6.36-vc14_2llvmlite intel/win-64::llvmlite-0.27.1-py36_0matplotlib intel/win-64::matplotlib-3.0.1-py36_1menuinst intel/win-64::menuinst-1.4.1-py36_6mkl intel/win-64::mkl-2019.3-intel_203mkl-service intel/win-64::mkl-service-1.0.0-py36_7mkl_fft intel/win-64::mkl_fft-1.0.11-py36h7b7c402_0mkl_random intel/win-64::mkl_random-1.0.2-py36h7b7c402_4mpi4py intel/win-64::mpi4py-3.0.0-py36_3numba intel/win-64::numba-0.42.1-np116py36_0numexpr intel/win-64::numexpr-2.6.8-py36_2numpy intel/win-64::numpy-1.16.1-py36h7b7c402_3numpy-base intel/win-64::numpy-base-1.16.1-py36_3openssl intel/win-64::openssl-1.0.2r-vc14_0pandas intel/win-64::pandas-0.24.1-py36_3pip intel/win-64::pip-10.0.1-py36_0pycosat intel/win-64::pycosat-0.6.3-py36_3pycparser intel/win-64::pycparser-2.18-py36_2pyopenssl intel/win-64::pyopenssl-17.5.0-py36_2pyparsing intel/win-64::pyparsing-2.2.0-py36_2pysocks intel/win-64::pysocks-1.6.7-py36_1python intel/win-64::python-3.6.8-6python-dateutil intel/win-64::python-dateutil-2.6.0-py36_12pytz intel/win-64::pytz-2018.4-py36_3pyyaml intel/win-64::pyyaml-4.1-py36_3requests intel/win-64::requests-2.20.1-py36_1ruamel_yaml intel/win-64::ruamel_yaml-0.11.14-py36_4scikit-learn intel/win-64::scikit-learn-0.20.2-py36h7b7c402_2scipy intel/win-64::scipy-1.2.0-py36_3setuptools intel/win-64::setuptools-39.0.1-py36_0six intel/win-64::six-1.11.0-py36_3sqlite intel/win-64::sqlite-3.27.2-vc14_2tbb intel/win-64::tbb-2019.4-vc14_intel_203tbb4py intel/win-64::tbb4py-2019.4-py36_intel_0tcl intel/win-64::tcl-8.6.4-vc14_22tk intel/win-64::tk-8.6.4-vc14_28urllib3 intel/win-64::urllib3-1.24.1-py36_2vc intel/win-64::vc-14.0-2vs2015_runtime intel/win-64::vs2015_runtime-14.0.25420-intel_2wheel intel/win-64::wheel-0.31.0-py36_3win_inet_pton intel/win-64::win_inet_pton-1.0.1-py36_4wincertstore intel/win-64::wincertstore-0.2-py36_3xz intel/win-64::xz-5.2.3-vc14_2zlib intel/win-64::zlib-1.2.11-vc14h21ff451_5 You can see that for each library the wheel’s description starts with “Intel/...” this signifies that the said library is being downloaded from intel’s distribution channel. Once you give yes to install these libraries, they will start getting downloaded and installed. This step is where the first issue comes. Sometimes, these libraries don’t get downloaded, and the list propagates, or we get an SSL error and the command exits. This issue may even be delayed, that is, right now everything will get downloaded and installed, but later on if you want to add any new library, the prompt will throw SSL errors. There’s an easy fix to this problem which needs to be done before creating the virtual environment for Intel as mentioned above. In your shell or command prompt, turn off the anaconda’s default SSL verification via the following command conda config --set ssl_verify false Once SLL verification is turned off, you can repeat step 2 by deleting the previously created environment and starting fresh. Congratulations!! Now you have set up the Intel’s python distribution in your PC/laptop. It’s time to enter the ML pipeline. Intel has provided optimization for tensorflow via all the distribution channels and is very smooth to set up. You can read more about it here. Let’s see how we can install optimized tensorflow for our CPU. Intel Software provides an optimized math kernel library(mkl) which optimizes the mathematical operations and provides the users with required speed-up. Thus, we will install tensorflow-mkl as follows. conda install tensorflow-mkl Or with pip, one can set it up as follows. pip install intel-tensorflow Voila!! Tensorflow is now up and running in your system with necessary optimizations. And if you are a Keras fan then you can set it up with a simple command: - conda install keras -c intel Since we have created a new virtual environment, it will not come with spyder or jupyter notebooks by default. However, it is straightforward to set these up. With a single line, we can do wonders. conda install jupyter -c intel Now that we have set up everything, it’s time to get our hands dirty as we start coding and experimenting with various ML and DL approaches on our optimized CPU systems. Firstly, before executing any code, make sure that you are using the right environment. You need to activate the virtual environment before you can use the libraries installed in it. This activation step is an all-time process, and it is effortless. Write the following command in your anaconda prompt, and you’re good to go. conda activate intel To make sanity checks on your environment, type the following in the command prompt/shell once the environment is activated. python Once you press enter after typing python, the following text should appear in your command prompt. Make sure it says “Intel Corporation” between the pipe and has the message “Intel(R) Distribution for Python is brought to you by Intel Corporation.”. These validate the correct installation of Intel’s Python Distribution. Python 3.6.8 |Intel Corporation| (default, Feb 27 2019, 19:55:17) [MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.Intel(R) Distribution for Python is brought to you by Intel Corporation.Please check out: https://software.intel.com/en-us/python-distribution Now you can use the command line to experiment or write your scripts elsewhere and save them with .py extension. These files can then be accessed by navigating to the location of the file via “cd” command and running the script via: - (intel) C:\Users\User>python script.py By following steps 1 to 4, you will have your system ready with the level of Intel xyz* as mentioned in the performance benchmark charts above. These are still not multi-processor-based thread optimized. I will discuss below how to achieve further optimization for your multi-core CPU. To add further optimizations for your multi-core system, you can add the following lines of code to your .py file, and it will execute the scripts accordingly. Here NUM_PARALLEL_EXEC_UNITS represent the number of cores you have; I have a quad-core i7. Hence the number is 4. For Windows users, you can check the count of cores in your Task Manager via navigating to Task Manager -> Performance -> CPU -> Cores. from keras import backend as Kimport tensorflow as tfNUM_PARALLEL_EXEC_UNITS = 4config = tf.ConfigProto(intra_op_parallelism_threads=NUM_PARALLEL_EXEC_UNITS, inter_op_parallelism_threads=2, allow_soft_placement=True, device_count={'CPU': NUM_PARALLEL_EXEC_UNITS})session = tf.Session(config=config)K.set_session(session)os.environ["OMP_NUM_THREADS"] = "4"os.environ["KMP_BLOCKTIME"] = "30"os.environ["KMP_SETTINGS"] = "1"os.environ["KMP_AFFINITY"] = "granularity=fine,verbose,compact,1,0" If you’re not using Keras and prefer using core tensorflow, then the script remains almost the same, just remove the following 2 lines. from keras import backend as KK.set_session(session) After adding these lines in your code, the speed-up should be comparable to Intel xyz(O) entries in the performance charts above. If you have a GPU in your system and it is conflicting with the current set of libraries or throwing a cudnn error then you can add the following line in your code to disable the GPU. os.environ["CUDA_VISIBLE_DEVICES"] = "-1" That’s it. You have now an optimized pipeline to test and develop machine learning projects and ideas. This channel opens up a lot of opportunities for students involving themselves in academic research to carry on their work with whatever system they have. This pipeline will also prevent the worries of privacy of private data on which a practitioner might be working. It is also to be observed that with proper fine-tuning, one can obtain a 3.45x speed-up in their workflow which means that if you are experimenting with your ideas, you can now work three times as fast as compared to before.
[ { "code": null, "e": 642, "s": 171, "text": "In the last few years, Deep Learning has picked up pace in academia as well as industry. Every company is now looking for an A.I. based solution to problems. This boom has its own merits and demerits, but that’s for another article, another day. This surge in Machine Learning practitioners have infiltrated the academia to its roots, and almost every student from every domain has access to AI and ML knowledge via courses, MOOCs, books, articles, and of course papers." }, { "code": null, "e": 1554, "s": 642, "text": "This rise was, however, bottlenecked by the availability of hardware resources. It was suggested and demonstrated that a Graphical Processing Unit is one of the best devices you can have to perform your ML tasks at pace. But a good high-performance GPU came with a price tag which can go even up to $20,449.00 for a single NVIDIA Tesla V100 32GB GPU which has server-like compute capabilities. Furthermore, a consumer laptop with a decent GPU costs around $2000 with a GPU like 1050Ti or 1080Ti. To ease the pain, Google, Kaggle, Intel, and Nvidia provides cloud-based High-Compute systems for free with a restriction on either space, compute capability, memory or time. But these online services have their drawbacks which include managing the data(upload/download), data privacy, etc. These issues lead to the main point of my article, “Why not optimize our CPUs to attain a speed-up in Deep Learning tasks?”." }, { "code": null, "e": 2077, "s": 1554, "text": "Intel has provided optimizations for Python, Tensorflow, Pytorch, etc. with a whole range of Intel Optimized support libraries like NumPy, scikit-learn and many more. These are freely available to download and set-up and provides a speed of anywhere from 2x to even 5x on a CPU like Intel Core i7 which is not also a high-performance CPU like the Xeon Series. In the remaining part of the article, I will demonstrate how to set-up Intel’s optimizations in your PC/laptop and will provide the speed-up data that I observed." }, { "code": null, "e": 2187, "s": 2077, "text": "For a variety of experiments mentioned below, I will present the time and utilization boosts that I observed." }, { "code": null, "e": 2397, "s": 2187, "text": "10-layer Deep CNN for CIFAR-100 Image Classification.3 Layer Deep LSTM for IMDB Sentiment Analysis.6 Layer deep Dense ANN for MNIST image Classification.9 Layer deep Fully Convolutional Auto-Encoder for MNIST." }, { "code": null, "e": 2451, "s": 2397, "text": "10-layer Deep CNN for CIFAR-100 Image Classification." }, { "code": null, "e": 2498, "s": 2451, "text": "3 Layer Deep LSTM for IMDB Sentiment Analysis." }, { "code": null, "e": 2553, "s": 2498, "text": "6 Layer deep Dense ANN for MNIST image Classification." }, { "code": null, "e": 2610, "s": 2553, "text": "9 Layer deep Fully Convolutional Auto-Encoder for MNIST." }, { "code": null, "e": 2804, "s": 2610, "text": "These tasks have been coded in Keras using tensorflow backend and datasets are available in the same hard-drive as that of the codes and executable libraries. The hard-drive utilized is an SSD." }, { "code": null, "e": 2869, "s": 2804, "text": "We will consider six combinations of optimizations as following." }, { "code": null, "e": 3231, "s": 2869, "text": "Intel(R) Core (TM) i7.Intel(R) Xeon(R) CPU E3–1535M v6.Intel(R) Core (TM) i7 with Intel Python (Intel i7*).Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python (Intel Xeon*).Intel(R) Core (TM) i7 with Intel Python and Processor Thread optimization (Intel i7(O)).Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python and Processor Thread optimization (Intel Xeon(O))." }, { "code": null, "e": 3254, "s": 3231, "text": "Intel(R) Core (TM) i7." }, { "code": null, "e": 3288, "s": 3254, "text": "Intel(R) Xeon(R) CPU E3–1535M v6." }, { "code": null, "e": 3341, "s": 3288, "text": "Intel(R) Core (TM) i7 with Intel Python (Intel i7*)." }, { "code": null, "e": 3407, "s": 3341, "text": "Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python (Intel Xeon*)." }, { "code": null, "e": 3496, "s": 3407, "text": "Intel(R) Core (TM) i7 with Intel Python and Processor Thread optimization (Intel i7(O))." }, { "code": null, "e": 3598, "s": 3496, "text": "Intel(R) Xeon(R) CPU E3–1535M v6 with Intel Python and Processor Thread optimization (Intel Xeon(O))." }, { "code": null, "e": 4061, "s": 3598, "text": "For each task, the number epochs were fixed at 50. In the chart below we can see that for an Intel(R) Core (TM) i7–7700HQ CPU @ 2.80GHz CPU, the average time per epoch is nearly 4.67 seconds, and it drops to 1.48 seconds upon proper optimization, which is 3.2x boost up. And for an Intel(R) Xeon(R) CPU E3–1535M v6 @ 3.10GHz CPU, the average time per epoch is nearly 2.21 seconds, and it drops to 0.64 seconds upon proper optimization, which is a 3.45x boost up." }, { "code": null, "e": 4302, "s": 4061, "text": "The optimization is not just in time, the optimized distribution also optimizes the CPU utilization which eventually leads to better heat management, and your laptops won’t get as heated as they used to while training a deep neural network." }, { "code": null, "e": 4602, "s": 4302, "text": "We can see that without any optimization the CPU utilization while training maxes out to 100%, slowing down all the other processes and heating the system. However, with proper optimizations, the utilization drops to 70% for i7 and 65% for Xeon despite providing a performance gain in terms of time." }, { "code": null, "e": 4668, "s": 4602, "text": "These two metrics can be summarized in relative terms as follows." }, { "code": null, "e": 5051, "s": 4668, "text": "In the above graph, a lower value is better, that is in relative terms Intel Xeon with all the optimizations stands as the benchmark, and an Intel Core i7 processor takes almost twice as time as Xeon, per epoch, after optimizing its usage. The above graph clearly shows the bright side of Intel’s Python Optimization in terms of time taken to train a neural network and CPU’s usage." }, { "code": null, "e": 5459, "s": 5051, "text": "Intel Software has provided an exhaustive list of resources on how to set this up, but there are some issues which we may usually face. More details about distribution are available here. You can choose between the type of installation, that is, either native pip or conda. I prefer conda as it saves a ton of hassle for me and I can focus on ML rather than on solving compatibility issues for my libraries." }, { "code": null, "e": 5622, "s": 5459, "text": "You can download Anaconda from here. Their website has all the steps listed to install Anaconda on windows, ubuntu and macOS environments, and are easy to follow." }, { "code": null, "e": 5871, "s": 5622, "text": "This step is where it usually gets tricky. It is preferred to create a virtual environment for Intel distribution so that you can always add/change your optimized libraries at one place. Let’s create a new virtual environment with the name “intel.”" }, { "code": null, "e": 5920, "s": 5871, "text": "conda create -n intel -c intel intelpython3_full" }, { "code": null, "e": 6210, "s": 5920, "text": "Here -c represents channel, so instead of adding Intel as a channel, we call that channel via -c. Here, intelpython3_full will automatically fetch necessary libraries from Intel’s distribution and install them in your virtual environment. This command will install the following libraries." }, { "code": null, "e": 9775, "s": 6210, "text": "The following NEW packages will be INSTALLED:asn1crypto intel/win-64::asn1crypto-0.24.0-py36_3bzip2 intel/win-64::bzip2-1.0.6-vc14_17certifi intel/win-64::certifi-2018.1.18-py36_2cffi intel/win-64::cffi-1.11.5-py36_3chardet intel/win-64::chardet-3.0.4-py36_3cryptography intel/win-64::cryptography-2.3-py36_1cycler intel/win-64::cycler-0.10.0-py36_7cython intel/win-64::cython-0.29.3-py36_1daal intel/win-64::daal-2019.3-intel_203daal4py intel/win-64::daal4py-2019.3-py36h7b7c402_6freetype intel/win-64::freetype-2.9-vc14_3funcsigs intel/win-64::funcsigs-1.0.2-py36_7icc_rt intel/win-64::icc_rt-2019.3-intel_203idna intel/win-64::idna-2.6-py36_3impi_rt intel/win-64::impi_rt-2019.3-intel_203intel-openmp intel/win-64::intel-openmp-2019.3-intel_203intelpython intel/win-64::intelpython-2019.3-0intelpython3_core intel/win-64::intelpython3_core-2019.3-0intelpython3_full intel/win-64::intelpython3_full-2019.3-0kiwisolver intel/win-64::kiwisolver-1.0.1-py36_2libpng intel/win-64::libpng-1.6.36-vc14_2llvmlite intel/win-64::llvmlite-0.27.1-py36_0matplotlib intel/win-64::matplotlib-3.0.1-py36_1menuinst intel/win-64::menuinst-1.4.1-py36_6mkl intel/win-64::mkl-2019.3-intel_203mkl-service intel/win-64::mkl-service-1.0.0-py36_7mkl_fft intel/win-64::mkl_fft-1.0.11-py36h7b7c402_0mkl_random intel/win-64::mkl_random-1.0.2-py36h7b7c402_4mpi4py intel/win-64::mpi4py-3.0.0-py36_3numba intel/win-64::numba-0.42.1-np116py36_0numexpr intel/win-64::numexpr-2.6.8-py36_2numpy intel/win-64::numpy-1.16.1-py36h7b7c402_3numpy-base intel/win-64::numpy-base-1.16.1-py36_3openssl intel/win-64::openssl-1.0.2r-vc14_0pandas intel/win-64::pandas-0.24.1-py36_3pip intel/win-64::pip-10.0.1-py36_0pycosat intel/win-64::pycosat-0.6.3-py36_3pycparser intel/win-64::pycparser-2.18-py36_2pyopenssl intel/win-64::pyopenssl-17.5.0-py36_2pyparsing intel/win-64::pyparsing-2.2.0-py36_2pysocks intel/win-64::pysocks-1.6.7-py36_1python intel/win-64::python-3.6.8-6python-dateutil intel/win-64::python-dateutil-2.6.0-py36_12pytz intel/win-64::pytz-2018.4-py36_3pyyaml intel/win-64::pyyaml-4.1-py36_3requests intel/win-64::requests-2.20.1-py36_1ruamel_yaml intel/win-64::ruamel_yaml-0.11.14-py36_4scikit-learn intel/win-64::scikit-learn-0.20.2-py36h7b7c402_2scipy intel/win-64::scipy-1.2.0-py36_3setuptools intel/win-64::setuptools-39.0.1-py36_0six intel/win-64::six-1.11.0-py36_3sqlite intel/win-64::sqlite-3.27.2-vc14_2tbb intel/win-64::tbb-2019.4-vc14_intel_203tbb4py intel/win-64::tbb4py-2019.4-py36_intel_0tcl intel/win-64::tcl-8.6.4-vc14_22tk intel/win-64::tk-8.6.4-vc14_28urllib3 intel/win-64::urllib3-1.24.1-py36_2vc intel/win-64::vc-14.0-2vs2015_runtime intel/win-64::vs2015_runtime-14.0.25420-intel_2wheel intel/win-64::wheel-0.31.0-py36_3win_inet_pton intel/win-64::win_inet_pton-1.0.1-py36_4wincertstore intel/win-64::wincertstore-0.2-py36_3xz intel/win-64::xz-5.2.3-vc14_2zlib intel/win-64::zlib-1.2.11-vc14h21ff451_5" }, { "code": null, "e": 10045, "s": 9775, "text": "You can see that for each library the wheel’s description starts with “Intel/...” this signifies that the said library is being downloaded from intel’s distribution channel. Once you give yes to install these libraries, they will start getting downloaded and installed." }, { "code": null, "e": 10516, "s": 10045, "text": "This step is where the first issue comes. Sometimes, these libraries don’t get downloaded, and the list propagates, or we get an SSL error and the command exits. This issue may even be delayed, that is, right now everything will get downloaded and installed, but later on if you want to add any new library, the prompt will throw SSL errors. There’s an easy fix to this problem which needs to be done before creating the virtual environment for Intel as mentioned above." }, { "code": null, "e": 10624, "s": 10516, "text": "In your shell or command prompt, turn off the anaconda’s default SSL verification via the following command" }, { "code": null, "e": 10660, "s": 10624, "text": "conda config --set ssl_verify false" }, { "code": null, "e": 10786, "s": 10660, "text": "Once SLL verification is turned off, you can repeat step 2 by deleting the previously created environment and starting fresh." }, { "code": null, "e": 10911, "s": 10786, "text": "Congratulations!! Now you have set up the Intel’s python distribution in your PC/laptop. It’s time to enter the ML pipeline." }, { "code": null, "e": 11320, "s": 10911, "text": "Intel has provided optimization for tensorflow via all the distribution channels and is very smooth to set up. You can read more about it here. Let’s see how we can install optimized tensorflow for our CPU. Intel Software provides an optimized math kernel library(mkl) which optimizes the mathematical operations and provides the users with required speed-up. Thus, we will install tensorflow-mkl as follows." }, { "code": null, "e": 11349, "s": 11320, "text": "conda install tensorflow-mkl" }, { "code": null, "e": 11392, "s": 11349, "text": "Or with pip, one can set it up as follows." }, { "code": null, "e": 11421, "s": 11392, "text": "pip install intel-tensorflow" }, { "code": null, "e": 11582, "s": 11421, "text": "Voila!! Tensorflow is now up and running in your system with necessary optimizations. And if you are a Keras fan then you can set it up with a simple command: -" }, { "code": null, "e": 11611, "s": 11582, "text": "conda install keras -c intel" }, { "code": null, "e": 11809, "s": 11611, "text": "Since we have created a new virtual environment, it will not come with spyder or jupyter notebooks by default. However, it is straightforward to set these up. With a single line, we can do wonders." }, { "code": null, "e": 11840, "s": 11809, "text": "conda install jupyter -c intel" }, { "code": null, "e": 12336, "s": 11840, "text": "Now that we have set up everything, it’s time to get our hands dirty as we start coding and experimenting with various ML and DL approaches on our optimized CPU systems. Firstly, before executing any code, make sure that you are using the right environment. You need to activate the virtual environment before you can use the libraries installed in it. This activation step is an all-time process, and it is effortless. Write the following command in your anaconda prompt, and you’re good to go." }, { "code": null, "e": 12357, "s": 12336, "text": "conda activate intel" }, { "code": null, "e": 12482, "s": 12357, "text": "To make sanity checks on your environment, type the following in the command prompt/shell once the environment is activated." }, { "code": null, "e": 12489, "s": 12482, "text": "python" }, { "code": null, "e": 12811, "s": 12489, "text": "Once you press enter after typing python, the following text should appear in your command prompt. Make sure it says “Intel Corporation” between the pipe and has the message “Intel(R) Distribution for Python is brought to you by Intel Corporation.”. These validate the correct installation of Intel’s Python Distribution." }, { "code": null, "e": 13126, "s": 12811, "text": "Python 3.6.8 |Intel Corporation| (default, Feb 27 2019, 19:55:17) [MSC v.1900 64 bit (AMD64)] on win32Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.Intel(R) Distribution for Python is brought to you by Intel Corporation.Please check out: https://software.intel.com/en-us/python-distribution" }, { "code": null, "e": 13361, "s": 13126, "text": "Now you can use the command line to experiment or write your scripts elsewhere and save them with .py extension. These files can then be accessed by navigating to the location of the file via “cd” command and running the script via: -" }, { "code": null, "e": 13400, "s": 13361, "text": "(intel) C:\\Users\\User>python script.py" }, { "code": null, "e": 13686, "s": 13400, "text": "By following steps 1 to 4, you will have your system ready with the level of Intel xyz* as mentioned in the performance benchmark charts above. These are still not multi-processor-based thread optimized. I will discuss below how to achieve further optimization for your multi-core CPU." }, { "code": null, "e": 14097, "s": 13686, "text": "To add further optimizations for your multi-core system, you can add the following lines of code to your .py file, and it will execute the scripts accordingly. Here NUM_PARALLEL_EXEC_UNITS represent the number of cores you have; I have a quad-core i7. Hence the number is 4. For Windows users, you can check the count of cores in your Task Manager via navigating to Task Manager -> Performance -> CPU -> Cores." }, { "code": null, "e": 14608, "s": 14097, "text": "from keras import backend as Kimport tensorflow as tfNUM_PARALLEL_EXEC_UNITS = 4config = tf.ConfigProto(intra_op_parallelism_threads=NUM_PARALLEL_EXEC_UNITS, inter_op_parallelism_threads=2, allow_soft_placement=True, device_count={'CPU': NUM_PARALLEL_EXEC_UNITS})session = tf.Session(config=config)K.set_session(session)os.environ[\"OMP_NUM_THREADS\"] = \"4\"os.environ[\"KMP_BLOCKTIME\"] = \"30\"os.environ[\"KMP_SETTINGS\"] = \"1\"os.environ[\"KMP_AFFINITY\"] = \"granularity=fine,verbose,compact,1,0\"" }, { "code": null, "e": 14744, "s": 14608, "text": "If you’re not using Keras and prefer using core tensorflow, then the script remains almost the same, just remove the following 2 lines." }, { "code": null, "e": 14797, "s": 14744, "text": "from keras import backend as KK.set_session(session)" }, { "code": null, "e": 14927, "s": 14797, "text": "After adding these lines in your code, the speed-up should be comparable to Intel xyz(O) entries in the performance charts above." }, { "code": null, "e": 15111, "s": 14927, "text": "If you have a GPU in your system and it is conflicting with the current set of libraries or throwing a cudnn error then you can add the following line in your code to disable the GPU." }, { "code": null, "e": 15153, "s": 15111, "text": "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"" }, { "code": null, "e": 15524, "s": 15153, "text": "That’s it. You have now an optimized pipeline to test and develop machine learning projects and ideas. This channel opens up a lot of opportunities for students involving themselves in academic research to carry on their work with whatever system they have. This pipeline will also prevent the worries of privacy of private data on which a practitioner might be working." } ]
Machine Learning Pipelines: Nonlinear Model Stacking | by Lester Leong | Towards Data Science
Normally, we face data sets that are fairly linear or can be manipulated into one. But what if the data set that we are examining really should be looked at in a nonlinear way? Step into the world of nonlinear feature engineering. First, we’ll look at examples of nonlinear data. Next, we’ll briefly discuss the K-means algorithm as a means to nonlinear feature engineering. Lastly, we’ll apply K-means stacked on top of logistic regression to build a superior model for classification. Nonlinear data occurs quite often in the business world. Examples include, segmenting group behavior (marketing), patterns in inventory by group activity (sales), anomaly detection from previous transactions (finance), etc. [1]. To a more concrete example (supply chain / logistics), we can even see it in a visualization of truck driver data of speeding against distance [1]: From a quick glance, we can see that there are at least 2 groups within this data set. A group split between above 100 distance and below 100 distance. Intuitively, we can see that fitting a linear model here would be horrendous. Thus, we need a different type model. Applying K-means, we can actually find four groups as seen below [1]: With K-means, we can now assign additional analysis on the above drivers’ data set to produce predictive insights to help businesses categorize drivers’ distance traveled and their speeding patterns. In our case, we’ll apply K-means to our own fictitious data set to save us more steps of feature engineering real life data. Before we begin constructing our data, let’s take some time to go over what K-means actually is. K-means is an algorithm that looks for a certain number of clusters within an unlabeled data set [2]. Take note of the word unlabeled. This means that K-means is an unsupervised learning model. This is super helpful, when you get data but don’t really know how to label it. K-means can help out by labeling groups for you — pretty cool! For our data, we’ll use the make_circles data from sklearn [3]. Alright, let’s get to our hands on example: #Load up our packagesimport pandas as pdimport numpy as npimport sklearnimport scipyimport seaborn as snsfrom sklearn.cluster import KMeansfrom sklearn.preprocessing import OneHotEncoderfrom scipy.spatial import Voronoi, voronoi_plot_2dfrom sklearn.data sets.samples_generator import make_circlesfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierimport matplotlib.pyplot as plt%matplotlib notebook Our next step is to use create a K-means class. For those of you unfamiliar with classes (not a subject you take in school), think of a class in coding as a super function that has a lot of functions inside it. Now, I know there’s already a k-means clustering algorithm in sklearn, but I really like this class made by Alice Zheng due to detailed comments and the visualization that we’ll soon see [4]: class KMeansFeaturizer: """Transforms numeric data into k-means cluster memberships. This transformer runs k-means on the input data and converts each data point into the id of the closest cluster. If a target variable is present, it is scaled and included as input to k-means in order to derive clusters that obey the classification boundary as well as group similar points together. Parameters ---------- k: integer, optional, default 100 The number of clusters to group data into. target_scale: float, [0, infty], optional, default 5.0 The scaling factor for the target variable. Set this to zero to ignore the target. For classification problems, larger `target_scale` values will produce clusters that better respect the class boundary. random_state : integer or numpy.RandomState, optional This is passed to k-means as the generator used to initialize the kmeans centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- cluster_centers_ : array, [k, n_features] Coordinates of cluster centers. n_features does count the target column. """ def __init__(self, k=100, target_scale=5.0, random_state=None): self.k = k self.target_scale = target_scale self.random_state = random_state self.cluster_encoder = OneHotEncoder().fit(np.array(range(k)).reshape(-1,1)) def fit(self, X, y=None): """Runs k-means on the input data and find centroids. If no target is given (`y` is None) then run vanilla k-means on input `X`. If target `y` is given, then include the target (weighted by `target_scale`) as an extra dimension for k-means clustering. In this case, run k-means twice, first with the target, then an extra iteration without. After fitting, the attribute `cluster_centers_` are set to the k-means centroids in the input space represented by `X`. Parameters ---------- X : array-like or sparse matrix, shape=(n_data_points, n_features) y : vector of length n_data_points, optional, default None If provided, will be weighted with `target_scale` and included in k-means clustering as hint. """ if y is None: # No target variable, just do plain k-means km_model = KMeans(n_clusters=self.k, n_init=20, random_state=self.random_state) km_model.fit(X) self.km_model_ = km_model self.cluster_centers_ = km_model.cluster_centers_ return self # There is target information. Apply appropriate scaling and include # into input data to k-means data_with_target = np.hstack((X, y[:,np.newaxis]*self.target_scale)) # Build a pre-training k-means model on data and target km_model_pretrain = KMeans(n_clusters=self.k, n_init=20, random_state=self.random_state) km_model_pretrain.fit(data_with_target) # Run k-means a second time to get the clusters in the original space # without target info. Initialize using centroids found in pre-training. # Go through a single iteration of cluster assignment and centroid # recomputation. km_model = KMeans(n_clusters=self.k, init=km_model_pretrain.cluster_centers_[:,:2], n_init=1, max_iter=1) km_model.fit(X) self.km_model = km_model self.cluster_centers_ = km_model.cluster_centers_ return self def transform(self, X, y=None): """Outputs the closest cluster id for each input data point. Parameters ---------- X : array-like or sparse matrix, shape=(n_data_points, n_features) y : vector of length n_data_points, optional, default None Target vector is ignored even if provided. Returns ------- cluster_ids : array, shape[n_data_points,1] """ clusters = self.km_model.predict(X) return self.cluster_encoder.transform(clusters.reshape(-1,1)) def fit_transform(self, X, y=None): """Runs fit followed by transform. """ self.fit(X, y) return self.transform(X, y) Don’t let that huge amount of text bother you. I just put it there incase you wanted to experiment with it on your own projects. Afterwards, we’ll create our training/test set, and set the seed to 420 to get the same results: # Creating our training and test setseed = 420training_data, training_labels = make_circles(n_samples=2000, factor=0.2)kmf_hint = KMeansFeaturizer(k=100, target_scale=10, random_state=seed).fit(training_data, training_labels)kmf_no_hint = KMeansFeaturizer(k=100, target_scale=0, random_state=seed).fit(training_data, training_labels)def kmeans_voronoi_plot(X, y, cluster_centers, ax): #Plots Voronoi diagram of k-means clusters overlaid with data ax.scatter(X[:, 0], X[:, 1], c=y, cmap='Set1', alpha=0.2) vor = Voronoi(cluster_centers) voronoi_plot_2d(vor, ax=ax, show_vertices=False, alpha=0.5) Now, let’s look at our unlabeled nonlinear data: #looking at circles datadf = pd.DataFrame(training_data)ax = sns.scatterplot(x=0, y=1, data=df) Just like our into data set of the drivers’, our circle within a circle is definitely not a linear data set. Next, we’ll apply K-means comparing visual results with giving it a hint on what we think and no hints: #With hintfig = plt.figure()ax = plt.subplot(211, aspect='equal')kmeans_voronoi_plot(training_data, training_labels, kmf_hint.cluster_centers_, ax)ax.set_title('K-Means with Target Hint')#Without hintax2 = plt.subplot(212, aspect='equal')kmeans_voronoi_plot(training_data, training_labels, kmf_no_hint.cluster_centers_, ax2)ax2.set_title('K-Means without Target Hint') I find that in hint versus no hint that the results are fairly close. If you want more automation, then you might want to apply no hint. But if you can spend some time looking at your data set to give it a hint, I would. The reason is it could save you some time in running the model, so k-means spends less time figuring out on its own. Another reason to give k-means a hint is you have domain expertise in your data set and know there are a specific number of clusters. Time for the fun part — making the stacked model. Some of you might be asking, what’s the difference between stacked model and ensemble model. An ensemble model combines multiple machine learning models to make another model [5]. So, not much. I think model stacking is more precise here, since k-means is feeding into logistic regression. If we could draw a Venn diagram, we would find stacked models inside the concept of ensemble model. I couldn’t find a good example on Google images, so I applied the magic of MS paint to present a rough illustration for your viewing pleasure: Ok, art class over and back to coding. We’re going to do a ROC curve of kNN, logistic regression (LR), and k-means feeding into logistic regression. #Generate test data from same distribution of training datatest_data, test_labels = make_moons(n_samples=2000, noise=0.3, random_state=seed+5)training_cluster_features = kmf_hint.transform(training_data)test_cluster_features = kmf_hint.transform(test_data)training_with_cluster = scipy.sparse.hstack((training_data, training_cluster_features))test_with_cluster = scipy.sparse.hstack((test_data, test_cluster_features))#Run the modelslr_cluster = LogisticRegression(random_state=seed).fit(training_with_cluster, training_labels)classifier_names = ['LR', 'kNN']classifiers = [LogisticRegression(random_state=seed), KNeighborsClassifier(5)]for model in classifiers: model.fit(training_data, training_labels) #Plot the ROCdef test_roc(model, data, labels): if hasattr(model, "decision_function"): predictions = model.decision_function(data) else: predictions = model.predict_proba(data)[:,1] fpr, tpr, _ = sklearn.metrics.roc_curve(labels, predictions) return fpr, tprplt.figure()fpr_cluster, tpr_cluster = test_roc(lr_cluster, test_with_cluster, test_labels)plt.plot(fpr_cluster, tpr_cluster, 'r-', label='LR with k-means')for i, model in enumerate(classifiers): fpr, tpr = test_roc(model, test_data, test_labels) plt.plot(fpr, tpr, label=classifier_names[i]) plt.plot([0, 1], [0, 1], 'k--')plt.legend()plt.xlabel('False Positive Rate', fontsize=14)plt.ylabel('True Positive Rate', fontsize=14) Alright, first time I saw a ROC curve, I was like how do I read this thing? Well, what you want is the model that shoots up to the top left corner the fastest. In this case, our most accurate model is the stacked model — linear regression with k-means. The classification that our models worked on is picking where, which data point belongs to the big circle or small circle. Phew, we covered quite a few things here. First, we look at nonlinear data and examples that we might face in the real world. Second, we looked over k-means as a tool to discover more features about our data that was not there before. Next, we applied k-means to our own data set. Lastly, we stacked k-means into logistic regression to make a superior model. Pretty cool stuff overall. Somethings to note, we didn’t tune the models, which would change the performance nor did we compare that many models. But combining unsupervised learning into your supervised models could prove pretty useful and help you deliver insights you couldn’t get otherwise! Disclaimer: All things stated in this article are of my own opinion and not of any employer. Also sprinkled affiliate links. [1] A, Trevino, Introduction to K-means Clustering (2016), https://www.datascience.com/blog/k-means-clustering [2] J, VanderPlas, Python Data Science Handbook: Essential Tools for Working with Data (2016), https://amzn.to/2SMdZue [3] Scikit-learn Developers, sklearn.data sets.make_circles (2019), https://scikit-learn.org/stable/modules/generated/sklearn.data sets.make_circles.html#sklearn.data sets.make_circles [4] A, Zheng, et al, Feature Engineering for Machine Learning: Principles and Techniques for Data Scientists (2018), https://amzn.to/2SOFh3q [5] F, Gunes, Why do stacked ensemble models win data science competitions? (2017), https://blogs.sas.com/content/subconsciousmusings/2017/05/18/stacked-ensemble-models-win-data-science-competitions/
[ { "code": null, "e": 659, "s": 172, "text": "Normally, we face data sets that are fairly linear or can be manipulated into one. But what if the data set that we are examining really should be looked at in a nonlinear way? Step into the world of nonlinear feature engineering. First, we’ll look at examples of nonlinear data. Next, we’ll briefly discuss the K-means algorithm as a means to nonlinear feature engineering. Lastly, we’ll apply K-means stacked on top of logistic regression to build a superior model for classification." }, { "code": null, "e": 1036, "s": 659, "text": "Nonlinear data occurs quite often in the business world. Examples include, segmenting group behavior (marketing), patterns in inventory by group activity (sales), anomaly detection from previous transactions (finance), etc. [1]. To a more concrete example (supply chain / logistics), we can even see it in a visualization of truck driver data of speeding against distance [1]:" }, { "code": null, "e": 1374, "s": 1036, "text": "From a quick glance, we can see that there are at least 2 groups within this data set. A group split between above 100 distance and below 100 distance. Intuitively, we can see that fitting a linear model here would be horrendous. Thus, we need a different type model. Applying K-means, we can actually find four groups as seen below [1]:" }, { "code": null, "e": 1699, "s": 1374, "text": "With K-means, we can now assign additional analysis on the above drivers’ data set to produce predictive insights to help businesses categorize drivers’ distance traveled and their speeding patterns. In our case, we’ll apply K-means to our own fictitious data set to save us more steps of feature engineering real life data." }, { "code": null, "e": 2133, "s": 1699, "text": "Before we begin constructing our data, let’s take some time to go over what K-means actually is. K-means is an algorithm that looks for a certain number of clusters within an unlabeled data set [2]. Take note of the word unlabeled. This means that K-means is an unsupervised learning model. This is super helpful, when you get data but don’t really know how to label it. K-means can help out by labeling groups for you — pretty cool!" }, { "code": null, "e": 2241, "s": 2133, "text": "For our data, we’ll use the make_circles data from sklearn [3]. Alright, let’s get to our hands on example:" }, { "code": null, "e": 2690, "s": 2241, "text": "#Load up our packagesimport pandas as pdimport numpy as npimport sklearnimport scipyimport seaborn as snsfrom sklearn.cluster import KMeansfrom sklearn.preprocessing import OneHotEncoderfrom scipy.spatial import Voronoi, voronoi_plot_2dfrom sklearn.data sets.samples_generator import make_circlesfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierimport matplotlib.pyplot as plt%matplotlib notebook" }, { "code": null, "e": 3093, "s": 2690, "text": "Our next step is to use create a K-means class. For those of you unfamiliar with classes (not a subject you take in school), think of a class in coding as a super function that has a lot of functions inside it. Now, I know there’s already a k-means clustering algorithm in sklearn, but I really like this class made by Alice Zheng due to detailed comments and the visualization that we’ll soon see [4]:" }, { "code": null, "e": 7567, "s": 3093, "text": "class KMeansFeaturizer: \"\"\"Transforms numeric data into k-means cluster memberships. This transformer runs k-means on the input data and converts each data point into the id of the closest cluster. If a target variable is present, it is scaled and included as input to k-means in order to derive clusters that obey the classification boundary as well as group similar points together. Parameters ---------- k: integer, optional, default 100 The number of clusters to group data into. target_scale: float, [0, infty], optional, default 5.0 The scaling factor for the target variable. Set this to zero to ignore the target. For classification problems, larger `target_scale` values will produce clusters that better respect the class boundary. random_state : integer or numpy.RandomState, optional This is passed to k-means as the generator used to initialize the kmeans centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- cluster_centers_ : array, [k, n_features] Coordinates of cluster centers. n_features does count the target column. \"\"\" def __init__(self, k=100, target_scale=5.0, random_state=None): self.k = k self.target_scale = target_scale self.random_state = random_state self.cluster_encoder = OneHotEncoder().fit(np.array(range(k)).reshape(-1,1)) def fit(self, X, y=None): \"\"\"Runs k-means on the input data and find centroids. If no target is given (`y` is None) then run vanilla k-means on input `X`. If target `y` is given, then include the target (weighted by `target_scale`) as an extra dimension for k-means clustering. In this case, run k-means twice, first with the target, then an extra iteration without. After fitting, the attribute `cluster_centers_` are set to the k-means centroids in the input space represented by `X`. Parameters ---------- X : array-like or sparse matrix, shape=(n_data_points, n_features) y : vector of length n_data_points, optional, default None If provided, will be weighted with `target_scale` and included in k-means clustering as hint. \"\"\" if y is None: # No target variable, just do plain k-means km_model = KMeans(n_clusters=self.k, n_init=20, random_state=self.random_state) km_model.fit(X) self.km_model_ = km_model self.cluster_centers_ = km_model.cluster_centers_ return self # There is target information. Apply appropriate scaling and include # into input data to k-means data_with_target = np.hstack((X, y[:,np.newaxis]*self.target_scale)) # Build a pre-training k-means model on data and target km_model_pretrain = KMeans(n_clusters=self.k, n_init=20, random_state=self.random_state) km_model_pretrain.fit(data_with_target) # Run k-means a second time to get the clusters in the original space # without target info. Initialize using centroids found in pre-training. # Go through a single iteration of cluster assignment and centroid # recomputation. km_model = KMeans(n_clusters=self.k, init=km_model_pretrain.cluster_centers_[:,:2], n_init=1, max_iter=1) km_model.fit(X) self.km_model = km_model self.cluster_centers_ = km_model.cluster_centers_ return self def transform(self, X, y=None): \"\"\"Outputs the closest cluster id for each input data point. Parameters ---------- X : array-like or sparse matrix, shape=(n_data_points, n_features) y : vector of length n_data_points, optional, default None Target vector is ignored even if provided. Returns ------- cluster_ids : array, shape[n_data_points,1] \"\"\" clusters = self.km_model.predict(X) return self.cluster_encoder.transform(clusters.reshape(-1,1)) def fit_transform(self, X, y=None): \"\"\"Runs fit followed by transform. \"\"\" self.fit(X, y) return self.transform(X, y)" }, { "code": null, "e": 7793, "s": 7567, "text": "Don’t let that huge amount of text bother you. I just put it there incase you wanted to experiment with it on your own projects. Afterwards, we’ll create our training/test set, and set the seed to 420 to get the same results:" }, { "code": null, "e": 8401, "s": 7793, "text": "# Creating our training and test setseed = 420training_data, training_labels = make_circles(n_samples=2000, factor=0.2)kmf_hint = KMeansFeaturizer(k=100, target_scale=10, random_state=seed).fit(training_data, training_labels)kmf_no_hint = KMeansFeaturizer(k=100, target_scale=0, random_state=seed).fit(training_data, training_labels)def kmeans_voronoi_plot(X, y, cluster_centers, ax): #Plots Voronoi diagram of k-means clusters overlaid with data ax.scatter(X[:, 0], X[:, 1], c=y, cmap='Set1', alpha=0.2) vor = Voronoi(cluster_centers) voronoi_plot_2d(vor, ax=ax, show_vertices=False, alpha=0.5)" }, { "code": null, "e": 8450, "s": 8401, "text": "Now, let’s look at our unlabeled nonlinear data:" }, { "code": null, "e": 8546, "s": 8450, "text": "#looking at circles datadf = pd.DataFrame(training_data)ax = sns.scatterplot(x=0, y=1, data=df)" }, { "code": null, "e": 8759, "s": 8546, "text": "Just like our into data set of the drivers’, our circle within a circle is definitely not a linear data set. Next, we’ll apply K-means comparing visual results with giving it a hint on what we think and no hints:" }, { "code": null, "e": 9128, "s": 8759, "text": "#With hintfig = plt.figure()ax = plt.subplot(211, aspect='equal')kmeans_voronoi_plot(training_data, training_labels, kmf_hint.cluster_centers_, ax)ax.set_title('K-Means with Target Hint')#Without hintax2 = plt.subplot(212, aspect='equal')kmeans_voronoi_plot(training_data, training_labels, kmf_no_hint.cluster_centers_, ax2)ax2.set_title('K-Means without Target Hint')" }, { "code": null, "e": 9600, "s": 9128, "text": "I find that in hint versus no hint that the results are fairly close. If you want more automation, then you might want to apply no hint. But if you can spend some time looking at your data set to give it a hint, I would. The reason is it could save you some time in running the model, so k-means spends less time figuring out on its own. Another reason to give k-means a hint is you have domain expertise in your data set and know there are a specific number of clusters." }, { "code": null, "e": 10183, "s": 9600, "text": "Time for the fun part — making the stacked model. Some of you might be asking, what’s the difference between stacked model and ensemble model. An ensemble model combines multiple machine learning models to make another model [5]. So, not much. I think model stacking is more precise here, since k-means is feeding into logistic regression. If we could draw a Venn diagram, we would find stacked models inside the concept of ensemble model. I couldn’t find a good example on Google images, so I applied the magic of MS paint to present a rough illustration for your viewing pleasure:" }, { "code": null, "e": 10332, "s": 10183, "text": "Ok, art class over and back to coding. We’re going to do a ROC curve of kNN, logistic regression (LR), and k-means feeding into logistic regression." }, { "code": null, "e": 11801, "s": 10332, "text": "#Generate test data from same distribution of training datatest_data, test_labels = make_moons(n_samples=2000, noise=0.3, random_state=seed+5)training_cluster_features = kmf_hint.transform(training_data)test_cluster_features = kmf_hint.transform(test_data)training_with_cluster = scipy.sparse.hstack((training_data, training_cluster_features))test_with_cluster = scipy.sparse.hstack((test_data, test_cluster_features))#Run the modelslr_cluster = LogisticRegression(random_state=seed).fit(training_with_cluster, training_labels)classifier_names = ['LR', 'kNN']classifiers = [LogisticRegression(random_state=seed), KNeighborsClassifier(5)]for model in classifiers: model.fit(training_data, training_labels) #Plot the ROCdef test_roc(model, data, labels): if hasattr(model, \"decision_function\"): predictions = model.decision_function(data) else: predictions = model.predict_proba(data)[:,1] fpr, tpr, _ = sklearn.metrics.roc_curve(labels, predictions) return fpr, tprplt.figure()fpr_cluster, tpr_cluster = test_roc(lr_cluster, test_with_cluster, test_labels)plt.plot(fpr_cluster, tpr_cluster, 'r-', label='LR with k-means')for i, model in enumerate(classifiers): fpr, tpr = test_roc(model, test_data, test_labels) plt.plot(fpr, tpr, label=classifier_names[i]) plt.plot([0, 1], [0, 1], 'k--')plt.legend()plt.xlabel('False Positive Rate', fontsize=14)plt.ylabel('True Positive Rate', fontsize=14)" }, { "code": null, "e": 12177, "s": 11801, "text": "Alright, first time I saw a ROC curve, I was like how do I read this thing? Well, what you want is the model that shoots up to the top left corner the fastest. In this case, our most accurate model is the stacked model — linear regression with k-means. The classification that our models worked on is picking where, which data point belongs to the big circle or small circle." }, { "code": null, "e": 12830, "s": 12177, "text": "Phew, we covered quite a few things here. First, we look at nonlinear data and examples that we might face in the real world. Second, we looked over k-means as a tool to discover more features about our data that was not there before. Next, we applied k-means to our own data set. Lastly, we stacked k-means into logistic regression to make a superior model. Pretty cool stuff overall. Somethings to note, we didn’t tune the models, which would change the performance nor did we compare that many models. But combining unsupervised learning into your supervised models could prove pretty useful and help you deliver insights you couldn’t get otherwise!" }, { "code": null, "e": 12955, "s": 12830, "text": "Disclaimer: All things stated in this article are of my own opinion and not of any employer. Also sprinkled affiliate links." }, { "code": null, "e": 13066, "s": 12955, "text": "[1] A, Trevino, Introduction to K-means Clustering (2016), https://www.datascience.com/blog/k-means-clustering" }, { "code": null, "e": 13185, "s": 13066, "text": "[2] J, VanderPlas, Python Data Science Handbook: Essential Tools for Working with Data (2016), https://amzn.to/2SMdZue" }, { "code": null, "e": 13370, "s": 13185, "text": "[3] Scikit-learn Developers, sklearn.data sets.make_circles (2019), https://scikit-learn.org/stable/modules/generated/sklearn.data sets.make_circles.html#sklearn.data sets.make_circles" }, { "code": null, "e": 13511, "s": 13370, "text": "[4] A, Zheng, et al, Feature Engineering for Machine Learning: Principles and Techniques for Data Scientists (2018), https://amzn.to/2SOFh3q" } ]
Arrays and Strings in C++ - GeeksforGeeks
07 May, 2020 Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers, etc.There are two types of arrays: One Dimensional Array Multi Dimensional Array One Dimensional Array: A one dimensional array is a collection of same data types. 1-D array is declared as: data_type variable_name[size] data_type is the type of array, like int, float, char, etc. variable_name is the name of the array. size is the length of the array which is fixed. Note: The location of the array elements depends upon the data type we use. Below is the illustration of the array: Below is the program to illustrate the traversal of the array: // C++ program to illustrate the traversal// of the array#include "iostream"using namespace std; // Function to illustrate traversal in arr[]void traverseArray(int arr[], int N){ // Iterate from [1, N-1] and print // the element at that index for (int i = 0; i < N; i++) { cout << arr[i] << ' '; }} // Driver Codeint main(){ // Given array int arr[] = { 1, 2, 3, 4 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function call traverseArray(arr, N);} 1 2 3 4 MultiDimensional Array: A multidimensional array is also known as array of arrays. Generally, we use a two-dimensional array. It is also known as the matrix. We use two indices to traverse the rows and columns of the 2D array. It is declared as: data_type variable_name[N][M] data_type is the type of array, like int, float, char, etc. variable_name is the name of the array. N is the number of rows. M is the number of columns. Below is the program to illustrate the traversal of the 2D array: // C++ program to illustrate the traversal// of the 2D array#include "iostream"using namespace std; const int N = 2;const int M = 2; // Function to illustrate traversal in arr[][]void traverse2DArray(int arr[][M], int N){ // Iterate from [1, N-1] and print // the element at that index for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << arr[i][j] << ' '; } cout << endl; }} // Driver Codeint main(){ // Given array int arr[][M] = { { 1, 2 }, { 3, 4 } }; // Function call traverse2DArray(arr, N); return 0;} 1 2 3 4 Strings C++ string class internally uses character array to store character but all memory management, allocation, and null termination are handled by string class itself that is why it is easy to use. For example it is declared as: char str[] = "GeeksforGeeks" Below is the program to illustrate the traversal in the string: // C++ program to illustrate the// traversal of string#include "iostream"using namespace std; // Function to illustrate traversal// in stringvoid traverseString(char str[]){ int i = 0; // Iterate till we found '\0' while (str[i] != '\0') { printf("%c ", str[i]); i++; }} // Driver Codeint main(){ // Given string char str[] = "GeekforGeeks"; // Function call traverseString(str); return 0;} G e e k f o r G e e k s The string data_type in C++ provides various functionality of string manipulation. They are: strcpy(): It is used to copy characters from one string to another string.strcat(): It is used to add the two given strings.strlen(): It is used to find the length of the given string.strcmp(): It is used to compare the two given string. strcpy(): It is used to copy characters from one string to another string. strcat(): It is used to add the two given strings. strlen(): It is used to find the length of the given string. strcmp(): It is used to compare the two given string. Below is the program to illustrate the above functions: // C++ program to illustrate functions// of string manipulation#include "iostream"#include "string.h"using namespace std; // Driver Codeint main(){ // Given two string char str1[100] = "GeekforGeeks"; char str2[100] = "HelloGeek"; // To get the length of the string // use strlen() function int x = strlen(str1); cout << "Length of string " << str1 << " is " << x << endl; cout << endl; // To compare the two string str1 // and str2 use strcmp() function int result = strcmp(str1, str2); // If result is 0 then str1 and str2 // are equals if (result == 0) { cout << "String " << str1 << " and String " << str2 << " are equal." << endl; } else { cout << "String " << str1 << " and String " << str2 << " are not equal." << endl; } cout << endl; cout << "String str1 before: " << str1 << endl; // Use strcpy() to copy character // from one string to another strcpy(str1, str2); cout << "String str1 after: " << str1 << endl; cout << endl; return 0;} Length of string GeekforGeeks is 12 String GeekforGeeks and String HelloGeek are not equal. String str1 before: GeekforGeeks String str1 after: HelloGeek Arrays C++ Strings Arrays Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Trapping Rain Water Program to find sum of elements in a given array Reversal algorithm for array rotation Window Sliding Technique Find duplicates in O(n) time and O(1) extra space | Set 1 Vector in C++ STL Inheritance in C++ Iterators in C++ STL Initialize a vector in C++ (6 different ways) Socket Programming in C/C++
[ { "code": null, "e": 24740, "s": 24712, "text": "\n07 May, 2020" }, { "code": null, "e": 24747, "s": 24740, "text": "Arrays" }, { "code": null, "e": 25260, "s": 24747, "text": "An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers, etc.There are two types of arrays:" }, { "code": null, "e": 25282, "s": 25260, "text": "One Dimensional Array" }, { "code": null, "e": 25306, "s": 25282, "text": "Multi Dimensional Array" }, { "code": null, "e": 25415, "s": 25306, "text": "One Dimensional Array: A one dimensional array is a collection of same data types. 1-D array is declared as:" }, { "code": null, "e": 25595, "s": 25415, "text": "data_type variable_name[size]\n\ndata_type is the type of array, like int, float, char, etc.\nvariable_name is the name of the array.\nsize is the length of the array which is fixed.\n" }, { "code": null, "e": 25671, "s": 25595, "text": "Note: The location of the array elements depends upon the data type we use." }, { "code": null, "e": 25711, "s": 25671, "text": "Below is the illustration of the array:" }, { "code": null, "e": 25774, "s": 25711, "text": "Below is the program to illustrate the traversal of the array:" }, { "code": "// C++ program to illustrate the traversal// of the array#include \"iostream\"using namespace std; // Function to illustrate traversal in arr[]void traverseArray(int arr[], int N){ // Iterate from [1, N-1] and print // the element at that index for (int i = 0; i < N; i++) { cout << arr[i] << ' '; }} // Driver Codeint main(){ // Given array int arr[] = { 1, 2, 3, 4 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function call traverseArray(arr, N);}", "e": 26289, "s": 25774, "text": null }, { "code": null, "e": 26298, "s": 26289, "text": "1 2 3 4\n" }, { "code": null, "e": 26544, "s": 26298, "text": "MultiDimensional Array: A multidimensional array is also known as array of arrays. Generally, we use a two-dimensional array. It is also known as the matrix. We use two indices to traverse the rows and columns of the 2D array. It is declared as:" }, { "code": null, "e": 26729, "s": 26544, "text": "data_type variable_name[N][M]\n\ndata_type is the type of array, like int, float, char, etc.\nvariable_name is the name of the array.\nN is the number of rows.\nM is the number of columns.\n" }, { "code": null, "e": 26795, "s": 26729, "text": "Below is the program to illustrate the traversal of the 2D array:" }, { "code": "// C++ program to illustrate the traversal// of the 2D array#include \"iostream\"using namespace std; const int N = 2;const int M = 2; // Function to illustrate traversal in arr[][]void traverse2DArray(int arr[][M], int N){ // Iterate from [1, N-1] and print // the element at that index for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << arr[i][j] << ' '; } cout << endl; }} // Driver Codeint main(){ // Given array int arr[][M] = { { 1, 2 }, { 3, 4 } }; // Function call traverse2DArray(arr, N); return 0;}", "e": 27389, "s": 26795, "text": null }, { "code": null, "e": 27399, "s": 27389, "text": "1 2 \n3 4\n" }, { "code": null, "e": 27407, "s": 27399, "text": "Strings" }, { "code": null, "e": 27632, "s": 27407, "text": "C++ string class internally uses character array to store character but all memory management, allocation, and null termination are handled by string class itself that is why it is easy to use. For example it is declared as:" }, { "code": null, "e": 27662, "s": 27632, "text": "char str[] = \"GeeksforGeeks\"\n" }, { "code": null, "e": 27726, "s": 27662, "text": "Below is the program to illustrate the traversal in the string:" }, { "code": "// C++ program to illustrate the// traversal of string#include \"iostream\"using namespace std; // Function to illustrate traversal// in stringvoid traverseString(char str[]){ int i = 0; // Iterate till we found '\\0' while (str[i] != '\\0') { printf(\"%c \", str[i]); i++; }} // Driver Codeint main(){ // Given string char str[] = \"GeekforGeeks\"; // Function call traverseString(str); return 0;}", "e": 28168, "s": 27726, "text": null }, { "code": null, "e": 28193, "s": 28168, "text": "G e e k f o r G e e k s\n" }, { "code": null, "e": 28286, "s": 28193, "text": "The string data_type in C++ provides various functionality of string manipulation. They are:" }, { "code": null, "e": 28524, "s": 28286, "text": "strcpy(): It is used to copy characters from one string to another string.strcat(): It is used to add the two given strings.strlen(): It is used to find the length of the given string.strcmp(): It is used to compare the two given string." }, { "code": null, "e": 28599, "s": 28524, "text": "strcpy(): It is used to copy characters from one string to another string." }, { "code": null, "e": 28650, "s": 28599, "text": "strcat(): It is used to add the two given strings." }, { "code": null, "e": 28711, "s": 28650, "text": "strlen(): It is used to find the length of the given string." }, { "code": null, "e": 28765, "s": 28711, "text": "strcmp(): It is used to compare the two given string." }, { "code": null, "e": 28821, "s": 28765, "text": "Below is the program to illustrate the above functions:" }, { "code": "// C++ program to illustrate functions// of string manipulation#include \"iostream\"#include \"string.h\"using namespace std; // Driver Codeint main(){ // Given two string char str1[100] = \"GeekforGeeks\"; char str2[100] = \"HelloGeek\"; // To get the length of the string // use strlen() function int x = strlen(str1); cout << \"Length of string \" << str1 << \" is \" << x << endl; cout << endl; // To compare the two string str1 // and str2 use strcmp() function int result = strcmp(str1, str2); // If result is 0 then str1 and str2 // are equals if (result == 0) { cout << \"String \" << str1 << \" and String \" << str2 << \" are equal.\" << endl; } else { cout << \"String \" << str1 << \" and String \" << str2 << \" are not equal.\" << endl; } cout << endl; cout << \"String str1 before: \" << str1 << endl; // Use strcpy() to copy character // from one string to another strcpy(str1, str2); cout << \"String str1 after: \" << str1 << endl; cout << endl; return 0;}", "e": 29956, "s": 28821, "text": null }, { "code": null, "e": 30113, "s": 29956, "text": "Length of string GeekforGeeks is 12\n\nString GeekforGeeks and String HelloGeek are not equal.\n\nString str1 before: GeekforGeeks\nString str1 after: HelloGeek\n" }, { "code": null, "e": 30120, "s": 30113, "text": "Arrays" }, { "code": null, "e": 30124, "s": 30120, "text": "C++" }, { "code": null, "e": 30132, "s": 30124, "text": "Strings" }, { "code": null, "e": 30139, "s": 30132, "text": "Arrays" }, { "code": null, "e": 30147, "s": 30139, "text": "Strings" }, { "code": null, "e": 30151, "s": 30147, "text": "CPP" }, { "code": null, "e": 30249, "s": 30151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30258, "s": 30249, "text": "Comments" }, { "code": null, "e": 30271, "s": 30258, "text": "Old Comments" }, { "code": null, "e": 30291, "s": 30271, "text": "Trapping Rain Water" }, { "code": null, "e": 30340, "s": 30291, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30378, "s": 30340, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30403, "s": 30378, "text": "Window Sliding Technique" }, { "code": null, "e": 30461, "s": 30403, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30479, "s": 30461, "text": "Vector in C++ STL" }, { "code": null, "e": 30498, "s": 30479, "text": "Inheritance in C++" }, { "code": null, "e": 30519, "s": 30498, "text": "Iterators in C++ STL" }, { "code": null, "e": 30565, "s": 30519, "text": "Initialize a vector in C++ (6 different ways)" } ]
How to get radiobutton output in Tkinter?
The radiobutton widget in Tkinter allows the user to make a selection for only one option from a set of given choices. The radiobutton has only two values, either True or False. If we want to get the output to check which option the user has selected, then we can use the get() method. It returns the object that is defined as the variable. We can display the selection in a label widget by casting the integer value in a string object and pass it in the text attributes. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Define a function to get the output for selected option def selection(): selected = "You selected the option " + str(radio.get()) label.config(text=selected) radio = IntVar() Label(text="Your Favourite programming language:", font=('Aerial 11')).pack() # Define radiobutton for each options r1 = Radiobutton(win, text="C++", variable=radio, value=1, command=selection) r1.pack(anchor=N) r2 = Radiobutton(win, text="Python", variable=radio, value=2, command=selection) r2.pack(anchor=N) r3 = Radiobutton(win, text="Java", variable=radio, value=3, command=selection) r3.pack(anchor=N) # Define a label widget label = Label(win) label.pack() win.mainloop() Executing the above code will display a window with a set of radiobuttons in it. Click any option and it will show the option that you have selected.
[ { "code": null, "e": 1240, "s": 1062, "text": "The radiobutton widget in Tkinter allows the user to make a selection for only one option from a set of given choices. The radiobutton has only two values, either True or False." }, { "code": null, "e": 1534, "s": 1240, "text": "If we want to get the output to check which option the user has selected, then we can use the get() method. It returns the object that is defined as the variable. We can display the selection in a label widget by casting the integer value in a string object and pass it in the text attributes." }, { "code": null, "e": 2396, "s": 1534, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Define a function to get the output for selected option\ndef selection():\n selected = \"You selected the option \" + str(radio.get())\n label.config(text=selected)\n\nradio = IntVar()\nLabel(text=\"Your Favourite programming language:\", font=('Aerial 11')).pack()\n\n# Define radiobutton for each options\nr1 = Radiobutton(win, text=\"C++\", variable=radio, value=1, command=selection)\n\nr1.pack(anchor=N)\nr2 = Radiobutton(win, text=\"Python\", variable=radio, value=2, command=selection)\n\nr2.pack(anchor=N)\nr3 = Radiobutton(win, text=\"Java\", variable=radio, value=3, command=selection)\n\nr3.pack(anchor=N)\n\n# Define a label widget\nlabel = Label(win)\nlabel.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2546, "s": 2396, "text": "Executing the above code will display a window with a set of radiobuttons in it. Click any option and it will show the option that you have selected." } ]
CSS | stroke-linejoin Property - GeeksforGeeks
22 Nov, 2019 The stroke-linejoin property is an inbuilt property used to define the shape that is used to end an open sub-path of a stroke. Syntax: stroke-linejoin: miter | miter-clip | round | bevel | arcs | initial | inherit Property Values: miter: It is used to indicate that a sharp corner would be used to join the two ends. The outer edges of the stroke are extended to the tangents of the path segments until they intersect. This gives the ending a sharp corner.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="153" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html>Output: Example: <!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="153" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html> Output: miter-clip: It is used to indicate that a sharp corner would be used to join the two ends. The outer edges of the stroke are extended to the tangents of the path segments until they intersect.It gives the ending a sharp corner like the miter value except another property. The stroke-miterlimit is used to determine whether the miter would be clipped if it exceeds a certain value. It is used to provide a better-looking miter on very sharp joins or animations.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter-clip; /* setting a lower miterlimit */ stroke-miterlimit: 1; stroke-width: 20px; stroke: green; fill: none; } .stroke2 { stroke-linejoin: miter-clip; /* setting a higher miterlimit */ stroke-miterlimit: 2; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter-clip; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="80" y="25" width="100" height="100" class="stroke1" /> <rect x="220" y="25" width="100" height="100" class="stroke2" /> </svg> </div> </center></body> </html>Output: It gives the ending a sharp corner like the miter value except another property. The stroke-miterlimit is used to determine whether the miter would be clipped if it exceeds a certain value. It is used to provide a better-looking miter on very sharp joins or animations. Example: <!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter-clip; /* setting a lower miterlimit */ stroke-miterlimit: 1; stroke-width: 20px; stroke: green; fill: none; } .stroke2 { stroke-linejoin: miter-clip; /* setting a higher miterlimit */ stroke-miterlimit: 2; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter-clip; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="80" y="25" width="100" height="100" class="stroke1" /> <rect x="220" y="25" width="100" height="100" class="stroke2" /> </svg> </div> </center></body> </html> Output: round: It is used to indicate that rounded the corner would be used to join the two ends.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: round; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: round; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="153" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html>Output: Example: <!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: round; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: round; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="153" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html> Output: bevel: It is used to indicate that the connecting point is cropped perpendicular to the joint.Example:<!DOCTYPE html><html><head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: bevel; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | stroke-linejoin: bevel;</b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="152" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html>Output: Example: <!DOCTYPE html><html><head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: bevel; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | stroke-linejoin: bevel;</b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="152" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html> Output: arcs: It is used to indicate that an arcs corner is to be used to join path segments. This shape is formed by the extension of the outer edges of the stroke having the same curvature as the outer edges at the point they join. initial: It is used to set the property to its default value.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin </title> <style> .stroke1 { stroke-linejoin: initial; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: initial; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="153" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html>Output: Example: <!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin </title> <style> .stroke1 { stroke-linejoin: initial; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: initial; </b> <div class="container"> <svg width="400px" height="200px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect x="153" y="25" width="100" height="100" class="stroke1" /> </svg> </div> </center></body> </html> Output: inherit: It is used to set the property to inherit from its parent. Supported Browsers: The browser supported by stroke-linejoin property are listed below: Chrome Internet Explorer 9 Firefox Safari Opera Note: The stroke-linejoin: arcs; is not supported by any major browsers. CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25376, "s": 25348, "text": "\n22 Nov, 2019" }, { "code": null, "e": 25503, "s": 25376, "text": "The stroke-linejoin property is an inbuilt property used to define the shape that is used to end an open sub-path of a stroke." }, { "code": null, "e": 25511, "s": 25503, "text": "Syntax:" }, { "code": null, "e": 25590, "s": 25511, "text": "stroke-linejoin: miter | miter-clip | round | bevel | arcs | initial | inherit" }, { "code": null, "e": 25607, "s": 25590, "text": "Property Values:" }, { "code": null, "e": 26647, "s": 25607, "text": "miter: It is used to indicate that a sharp corner would be used to join the two ends. The outer edges of the stroke are extended to the tangents of the path segments until they intersect. This gives the ending a sharp corner.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"153\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>Output:" }, { "code": null, "e": 26656, "s": 26647, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"153\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>", "e": 27456, "s": 26656, "text": null }, { "code": null, "e": 27464, "s": 27456, "text": "Output:" }, { "code": null, "e": 29234, "s": 27464, "text": "miter-clip: It is used to indicate that a sharp corner would be used to join the two ends. The outer edges of the stroke are extended to the tangents of the path segments until they intersect.It gives the ending a sharp corner like the miter value except another property. The stroke-miterlimit is used to determine whether the miter would be clipped if it exceeds a certain value. It is used to provide a better-looking miter on very sharp joins or animations.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter-clip; /* setting a lower miterlimit */ stroke-miterlimit: 1; stroke-width: 20px; stroke: green; fill: none; } .stroke2 { stroke-linejoin: miter-clip; /* setting a higher miterlimit */ stroke-miterlimit: 2; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter-clip; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"80\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> <rect x=\"220\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke2\" /> </svg> </div> </center></body> </html>Output:" }, { "code": null, "e": 29504, "s": 29234, "text": "It gives the ending a sharp corner like the miter value except another property. The stroke-miterlimit is used to determine whether the miter would be clipped if it exceeds a certain value. It is used to provide a better-looking miter on very sharp joins or animations." }, { "code": null, "e": 29513, "s": 29504, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: miter-clip; /* setting a lower miterlimit */ stroke-miterlimit: 1; stroke-width: 20px; stroke: green; fill: none; } .stroke2 { stroke-linejoin: miter-clip; /* setting a higher miterlimit */ stroke-miterlimit: 2; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: miter-clip; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"80\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> <rect x=\"220\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke2\" /> </svg> </div> </center></body> </html>", "e": 30807, "s": 29513, "text": null }, { "code": null, "e": 30815, "s": 30807, "text": "Output:" }, { "code": null, "e": 31721, "s": 30815, "text": "round: It is used to indicate that rounded the corner would be used to join the two ends.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: round; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: round; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"153\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>Output:" }, { "code": null, "e": 31730, "s": 31721, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: round; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: round; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"153\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>", "e": 32532, "s": 31730, "text": null }, { "code": null, "e": 32540, "s": 32532, "text": "Output:" }, { "code": null, "e": 33416, "s": 32540, "text": "bevel: It is used to indicate that the connecting point is cropped perpendicular to the joint.Example:<!DOCTYPE html><html><head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: bevel; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | stroke-linejoin: bevel;</b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"152\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>Output:" }, { "code": null, "e": 33425, "s": 33416, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | stroke-linejoin property </title> <style> .stroke1 { stroke-linejoin: bevel; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | stroke-linejoin: bevel;</b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"152\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>", "e": 34192, "s": 33425, "text": null }, { "code": null, "e": 34200, "s": 34192, "text": "Output:" }, { "code": null, "e": 34426, "s": 34200, "text": "arcs: It is used to indicate that an arcs corner is to be used to join path segments. This shape is formed by the extension of the outer edges of the stroke having the same curvature as the outer edges at the point they join." }, { "code": null, "e": 35296, "s": 34426, "text": "initial: It is used to set the property to its default value.Example:<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin </title> <style> .stroke1 { stroke-linejoin: initial; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: initial; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"153\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>Output:" }, { "code": null, "e": 35305, "s": 35296, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | stroke-linejoin </title> <style> .stroke1 { stroke-linejoin: initial; stroke-width: 20px; stroke: green; fill: none; } </style></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-linejoin: initial; </b> <div class=\"container\"> <svg width=\"400px\" height=\"200px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect x=\"153\" y=\"25\" width=\"100\" height=\"100\" class=\"stroke1\" /> </svg> </div> </center></body> </html>", "e": 36099, "s": 35305, "text": null }, { "code": null, "e": 36107, "s": 36099, "text": "Output:" }, { "code": null, "e": 36175, "s": 36107, "text": "inherit: It is used to set the property to inherit from its parent." }, { "code": null, "e": 36263, "s": 36175, "text": "Supported Browsers: The browser supported by stroke-linejoin property are listed below:" }, { "code": null, "e": 36270, "s": 36263, "text": "Chrome" }, { "code": null, "e": 36290, "s": 36270, "text": "Internet Explorer 9" }, { "code": null, "e": 36298, "s": 36290, "text": "Firefox" }, { "code": null, "e": 36305, "s": 36298, "text": "Safari" }, { "code": null, "e": 36311, "s": 36305, "text": "Opera" }, { "code": null, "e": 36384, "s": 36311, "text": "Note: The stroke-linejoin: arcs; is not supported by any major browsers." }, { "code": null, "e": 36399, "s": 36384, "text": "CSS-Properties" }, { "code": null, "e": 36403, "s": 36399, "text": "CSS" }, { "code": null, "e": 36420, "s": 36403, "text": "Web Technologies" }, { "code": null, "e": 36518, "s": 36420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36555, "s": 36518, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 36584, "s": 36555, "text": "Form validation using jQuery" }, { "code": null, "e": 36623, "s": 36584, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 36665, "s": 36623, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 36712, "s": 36665, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 36754, "s": 36712, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 36787, "s": 36754, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36830, "s": 36787, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36875, "s": 36830, "text": "Convert a string to an integer in JavaScript" } ]
Train a Hand Detector using Tensorflow 2 Object Detection API in 2021 | by Aalok Patwardhan | Towards Data Science
I wanted to make a computer vision application that could detect my hands in real-time. There were so many articles online that used the Tensorflow object detection API and Google Colab, but I still struggled a lot to actually get things working. The reason? Versions of libraries and code change! Here is an example of using this detector in a virtual theremin: This article should guide you on what works right now (March 2021). I will assume you know basic Python skills, and enough know-how to look up what you don’t know from other tutorials! 😂 Things we will be using: Google Colab Tensorflow Object Detection API 2 The Egohands dataset: http://vision.soic.indiana.edu/projects/egohands/ Steps:1. Set up environment2. Download and Install Tensorflow 2 Object Detection API3. Download dataset, generate tf_records4. Download model and edit config5. Train model and export to savedmodel format Acknowledgements:Big thanks to github users molyswu, datitran, and gilberttanner from whom I have taken some code and modified it slightly. Please do check out their tutorials as well. Open up a new Google Colab notebook, and mount your Google drive. You don’t need to, but it’s super handy incase you disconnect from your session, or just want to come back to it again. from google.colab import drivedrive.mount('/content/drive')%cd /content/drive/MyDrive We are now inside your Google Drive. (You may need to change that last %cd incase your drive mounts to a slightly different path). Google Colab will be using Tensorflow 2, but just in case, explicitly do this: %tensorflow_version 2.x The first thing is to download and install Tensorflow 2 Object Detection API The simplest way is to first go into your root directory and then clone from git: %cd /content/drive/MyDrive!git clone https://github.com/tensorflow/models.git Then, compile the protos — there is no output by the way.(protoc should work as it is, because Google Colab already has it installed): %cd /content/drive/MyDrive/models/research!protoc object_detection/protos/*.proto --python_out=. Now install the actual API: !cp object_detection/packages/tf2/setup.py . !python -m pip install . Test your tensorflow object detection API 2 installation! Everything should be “OK”. (It’s ok if some of the tests are automatically skipped). #TEST IF YOU WANT!python object_detection/builders/model_builder_tf2_test.py I’ll describe at a top level what you need to do here, as this part hasn’t really changed much from other tutorials. In summary, we are going to download the Egohands dataset but only use a subset of the many many images there, since we are doing transfer learning.We will split them into a train directory and a test directory, and generate .xml files for each of them (containing the bounding box annotations for each image). I have created a general script which: Downloads the whole Egohands dataset and extracts it Only keeps a small number (4) of folders from it Splits the images into a train and test set Creates annotation .csv files with bounding box coordinates First we need to make sure you are in your root directory and then clone my git repo. %cd /content/drive/MyDrive!git clone https://github.com/aalpatya/detect_hands.git From my downloaded repo, copy the egohands_dataset_to_csv.py file into your root location and run it. This will do everything for you — by default it will only take 4 random folders (so 400 images) from the actual Egohands dataset, split them into a train and test set, and generate .csv files. !cp detect_hands/egohands_dataset_to_csv.py .!python egohands_dataset_to_csv.py Big shoutout to https://github.com/molyswu/hand_detection, from whom I got the original script. I’ve just tidied it up a bit and made a few tweaks. 😁 The test_labels.csv and train_labels.csv files that were just created contain the bounding box locations for every image, but surprise surprise, Tensorflow needs that information in a different format, a tf_record. We will create the required files train.record and test.record by using generate_tfrecord.py from my git repo, (I modified this from the wonderful datitran’s tutorial at https://github.com/datitran/raccoon_dataset). %cd /content/drive/MyDrive!cp detect_hands/generate_tfrecord.py .# For the train dataset!python generate_tfrecord.py --csv_input=images/train/train_labels.csv --output_path=train.record# For the test dataset!python generate_tfrecord.py --csv_input=images/test/test_labels.csv --output_path=test.record /content/drive/MyDrive (or whatever your root is called) |__ egohands |__ detect_hands |__ images |__ train |__ <lots of images> |__ train.csv |__ test |__ <lots of images> |__ test.csv |__ train.record |__ test.record Get the download link of a model you want from https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md Here I am using SSD Mobilenet V2 fpnlite 320x320. I found that some models did not work with tensorflow 2, so use this one if you want to be sure. %cd /content/drive/MyDrive!wget http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz# Unzip!tar -xzvf ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz First, create a file called label_map.pbtxt which contains your hand class. It should look like this: item { id: 1 name: 'hand'} Or, you can just note down the path to the one already in my git repo which you should already have: /content/drive/MyDrive/detect_hands/model_data/ssd_mobilenet_v2_fpn_320/label_map.pbtxt Next we will edit the pipeline.config that came with the downloaded tensorflow model. It will be inside the model directory of the model you downloaded from the tensorflow model zoo. For example: ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config Near the start of pipeline.config: Change the number of classes to 1: Towards the middle/end of pipeline.config: Set the path to the model checkpoint. We only want the beginnig part of the checkpoint name until the number. For example: “ckpt-0”, and not “ckpt-0.index”. Set the checkpoint type as “detection” You may also want to change the batch size. In general the lower the batch size the quicker your model loss will drop, but it will take longer to settle at a loss value. I chose a batch size of 4 because I just wanted training to happen faster, I’m not looking for state of the art accuracy here. Play around with this number, and read this article. At the end of pipeline.config: Set the path to label_map.pbtxt (there are two places to do this, one for testing and one for training) Set the path to the train.record and test.record files First we’re going to load up the tensorboard, so that once training begins we can visualise the progress in nice graphs. The logdir argument is the path to the log directory that your training process will create. In our case this will be called output_training, and the logs automatically get stored in output_training/train. %load_ext tensorboard%tensorboard --logdir=/content/drive/MyDrive/output_training/train Now begin training, setting up the right paths to our pipeline config file, as well as the path to the output_training directory (which hasn’t been created yet). %cd /content/drive/MyDrive/models/research/object_detection/#train !python model_main_tf2.py \--pipeline_config_path=/content/drive/MyDrive/detect_hands/model_data/ssd_mobilenet_v2_fpn_320/pipeline.config \--model_dir=/content/drive/MyDrive/output_training --alsologtostderr This will begin the process of training, and you just sit back and wait. Either you wait a long time until the training process finishes, or just cancel the process after some time (perhaps you see on the loss graph that the loss is levelling off). It’s ok to do that, because the training process keeps saving model checkpoints. Now we will export the training output into a savedmodel format so that we can use it for inference. %cd /content/drive/MyDrive/models/research/object_detection!python exporter_main_v2.py \--trained_checkpoint_dir=/content/drive/MyDrive/output_training \--pipeline_config_path=/content/drive/MyDrive/detect_hands/model_data/ssd_mobilenet_v2_fpn_320/pipeline.config \--output_directory /content/drive/MyDrive/inference The important bit of this whole thing is the inference folder. It is the only thing we actually need if we want to perform inference. CONGRATULATIONS! You have trained a hand detector! 🎈🎉🎊 The model can be loaded with tensorflow 2 as detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL) and from there you can use the detect_fn function and go ahead with inference, but I’ll leave that for another tutorial 😉
[ { "code": null, "e": 469, "s": 171, "text": "I wanted to make a computer vision application that could detect my hands in real-time. There were so many articles online that used the Tensorflow object detection API and Google Colab, but I still struggled a lot to actually get things working. The reason? Versions of libraries and code change!" }, { "code": null, "e": 534, "s": 469, "text": "Here is an example of using this detector in a virtual theremin:" }, { "code": null, "e": 721, "s": 534, "text": "This article should guide you on what works right now (March 2021). I will assume you know basic Python skills, and enough know-how to look up what you don’t know from other tutorials! 😂" }, { "code": null, "e": 746, "s": 721, "text": "Things we will be using:" }, { "code": null, "e": 759, "s": 746, "text": "Google Colab" }, { "code": null, "e": 793, "s": 759, "text": "Tensorflow Object Detection API 2" }, { "code": null, "e": 865, "s": 793, "text": "The Egohands dataset: http://vision.soic.indiana.edu/projects/egohands/" }, { "code": null, "e": 1069, "s": 865, "text": "Steps:1. Set up environment2. Download and Install Tensorflow 2 Object Detection API3. Download dataset, generate tf_records4. Download model and edit config5. Train model and export to savedmodel format" }, { "code": null, "e": 1254, "s": 1069, "text": "Acknowledgements:Big thanks to github users molyswu, datitran, and gilberttanner from whom I have taken some code and modified it slightly. Please do check out their tutorials as well." }, { "code": null, "e": 1440, "s": 1254, "text": "Open up a new Google Colab notebook, and mount your Google drive. You don’t need to, but it’s super handy incase you disconnect from your session, or just want to come back to it again." }, { "code": null, "e": 1526, "s": 1440, "text": "from google.colab import drivedrive.mount('/content/drive')%cd /content/drive/MyDrive" }, { "code": null, "e": 1657, "s": 1526, "text": "We are now inside your Google Drive. (You may need to change that last %cd incase your drive mounts to a slightly different path)." }, { "code": null, "e": 1736, "s": 1657, "text": "Google Colab will be using Tensorflow 2, but just in case, explicitly do this:" }, { "code": null, "e": 1760, "s": 1736, "text": "%tensorflow_version 2.x" }, { "code": null, "e": 1919, "s": 1760, "text": "The first thing is to download and install Tensorflow 2 Object Detection API The simplest way is to first go into your root directory and then clone from git:" }, { "code": null, "e": 1997, "s": 1919, "text": "%cd /content/drive/MyDrive!git clone https://github.com/tensorflow/models.git" }, { "code": null, "e": 2132, "s": 1997, "text": "Then, compile the protos — there is no output by the way.(protoc should work as it is, because Google Colab already has it installed):" }, { "code": null, "e": 2229, "s": 2132, "text": "%cd /content/drive/MyDrive/models/research!protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 2257, "s": 2229, "text": "Now install the actual API:" }, { "code": null, "e": 2327, "s": 2257, "text": "!cp object_detection/packages/tf2/setup.py . !python -m pip install ." }, { "code": null, "e": 2470, "s": 2327, "text": "Test your tensorflow object detection API 2 installation! Everything should be “OK”. (It’s ok if some of the tests are automatically skipped)." }, { "code": null, "e": 2547, "s": 2470, "text": "#TEST IF YOU WANT!python object_detection/builders/model_builder_tf2_test.py" }, { "code": null, "e": 2975, "s": 2547, "text": "I’ll describe at a top level what you need to do here, as this part hasn’t really changed much from other tutorials. In summary, we are going to download the Egohands dataset but only use a subset of the many many images there, since we are doing transfer learning.We will split them into a train directory and a test directory, and generate .xml files for each of them (containing the bounding box annotations for each image)." }, { "code": null, "e": 3014, "s": 2975, "text": "I have created a general script which:" }, { "code": null, "e": 3067, "s": 3014, "text": "Downloads the whole Egohands dataset and extracts it" }, { "code": null, "e": 3116, "s": 3067, "text": "Only keeps a small number (4) of folders from it" }, { "code": null, "e": 3160, "s": 3116, "text": "Splits the images into a train and test set" }, { "code": null, "e": 3220, "s": 3160, "text": "Creates annotation .csv files with bounding box coordinates" }, { "code": null, "e": 3306, "s": 3220, "text": "First we need to make sure you are in your root directory and then clone my git repo." }, { "code": null, "e": 3388, "s": 3306, "text": "%cd /content/drive/MyDrive!git clone https://github.com/aalpatya/detect_hands.git" }, { "code": null, "e": 3683, "s": 3388, "text": "From my downloaded repo, copy the egohands_dataset_to_csv.py file into your root location and run it. This will do everything for you — by default it will only take 4 random folders (so 400 images) from the actual Egohands dataset, split them into a train and test set, and generate .csv files." }, { "code": null, "e": 3763, "s": 3683, "text": "!cp detect_hands/egohands_dataset_to_csv.py .!python egohands_dataset_to_csv.py" }, { "code": null, "e": 3913, "s": 3763, "text": "Big shoutout to https://github.com/molyswu/hand_detection, from whom I got the original script. I’ve just tidied it up a bit and made a few tweaks. 😁" }, { "code": null, "e": 4128, "s": 3913, "text": "The test_labels.csv and train_labels.csv files that were just created contain the bounding box locations for every image, but surprise surprise, Tensorflow needs that information in a different format, a tf_record." }, { "code": null, "e": 4344, "s": 4128, "text": "We will create the required files train.record and test.record by using generate_tfrecord.py from my git repo, (I modified this from the wonderful datitran’s tutorial at https://github.com/datitran/raccoon_dataset)." }, { "code": null, "e": 4648, "s": 4344, "text": "%cd /content/drive/MyDrive!cp detect_hands/generate_tfrecord.py .# For the train dataset!python generate_tfrecord.py --csv_input=images/train/train_labels.csv --output_path=train.record# For the test dataset!python generate_tfrecord.py --csv_input=images/test/test_labels.csv --output_path=test.record" }, { "code": null, "e": 4898, "s": 4648, "text": "/content/drive/MyDrive (or whatever your root is called) |__ egohands |__ detect_hands |__ images |__ train |__ <lots of images> |__ train.csv |__ test |__ <lots of images> |__ test.csv |__ train.record |__ test.record" }, { "code": null, "e": 5047, "s": 4898, "text": "Get the download link of a model you want from https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" }, { "code": null, "e": 5194, "s": 5047, "text": "Here I am using SSD Mobilenet V2 fpnlite 320x320. I found that some models did not work with tensorflow 2, so use this one if you want to be sure." }, { "code": null, "e": 5417, "s": 5194, "text": "%cd /content/drive/MyDrive!wget http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz# Unzip!tar -xzvf ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz" }, { "code": null, "e": 5519, "s": 5417, "text": "First, create a file called label_map.pbtxt which contains your hand class. It should look like this:" }, { "code": null, "e": 5548, "s": 5519, "text": "item { id: 1 name: 'hand'}" }, { "code": null, "e": 5737, "s": 5548, "text": "Or, you can just note down the path to the one already in my git repo which you should already have: /content/drive/MyDrive/detect_hands/model_data/ssd_mobilenet_v2_fpn_320/label_map.pbtxt" }, { "code": null, "e": 5995, "s": 5737, "text": "Next we will edit the pipeline.config that came with the downloaded tensorflow model. It will be inside the model directory of the model you downloaded from the tensorflow model zoo. For example: ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config" }, { "code": null, "e": 6030, "s": 5995, "text": "Near the start of pipeline.config:" }, { "code": null, "e": 6065, "s": 6030, "text": "Change the number of classes to 1:" }, { "code": null, "e": 6108, "s": 6065, "text": "Towards the middle/end of pipeline.config:" }, { "code": null, "e": 6265, "s": 6108, "text": "Set the path to the model checkpoint. We only want the beginnig part of the checkpoint name until the number. For example: “ckpt-0”, and not “ckpt-0.index”." }, { "code": null, "e": 6304, "s": 6265, "text": "Set the checkpoint type as “detection”" }, { "code": null, "e": 6654, "s": 6304, "text": "You may also want to change the batch size. In general the lower the batch size the quicker your model loss will drop, but it will take longer to settle at a loss value. I chose a batch size of 4 because I just wanted training to happen faster, I’m not looking for state of the art accuracy here. Play around with this number, and read this article." }, { "code": null, "e": 6685, "s": 6654, "text": "At the end of pipeline.config:" }, { "code": null, "e": 6789, "s": 6685, "text": "Set the path to label_map.pbtxt (there are two places to do this, one for testing and one for training)" }, { "code": null, "e": 6844, "s": 6789, "text": "Set the path to the train.record and test.record files" }, { "code": null, "e": 6965, "s": 6844, "text": "First we’re going to load up the tensorboard, so that once training begins we can visualise the progress in nice graphs." }, { "code": null, "e": 7171, "s": 6965, "text": "The logdir argument is the path to the log directory that your training process will create. In our case this will be called output_training, and the logs automatically get stored in output_training/train." }, { "code": null, "e": 7259, "s": 7171, "text": "%load_ext tensorboard%tensorboard --logdir=/content/drive/MyDrive/output_training/train" }, { "code": null, "e": 7421, "s": 7259, "text": "Now begin training, setting up the right paths to our pipeline config file, as well as the path to the output_training directory (which hasn’t been created yet)." }, { "code": null, "e": 7696, "s": 7421, "text": "%cd /content/drive/MyDrive/models/research/object_detection/#train !python model_main_tf2.py \\--pipeline_config_path=/content/drive/MyDrive/detect_hands/model_data/ssd_mobilenet_v2_fpn_320/pipeline.config \\--model_dir=/content/drive/MyDrive/output_training --alsologtostderr" }, { "code": null, "e": 8026, "s": 7696, "text": "This will begin the process of training, and you just sit back and wait. Either you wait a long time until the training process finishes, or just cancel the process after some time (perhaps you see on the loss graph that the loss is levelling off). It’s ok to do that, because the training process keeps saving model checkpoints." }, { "code": null, "e": 8127, "s": 8026, "text": "Now we will export the training output into a savedmodel format so that we can use it for inference." }, { "code": null, "e": 8444, "s": 8127, "text": "%cd /content/drive/MyDrive/models/research/object_detection!python exporter_main_v2.py \\--trained_checkpoint_dir=/content/drive/MyDrive/output_training \\--pipeline_config_path=/content/drive/MyDrive/detect_hands/model_data/ssd_mobilenet_v2_fpn_320/pipeline.config \\--output_directory /content/drive/MyDrive/inference" }, { "code": null, "e": 8578, "s": 8444, "text": "The important bit of this whole thing is the inference folder. It is the only thing we actually need if we want to perform inference." }, { "code": null, "e": 8633, "s": 8578, "text": "CONGRATULATIONS! You have trained a hand detector! 🎈🎉🎊" }, { "code": null, "e": 8678, "s": 8633, "text": "The model can be loaded with tensorflow 2 as" }, { "code": null, "e": 8731, "s": 8678, "text": "detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)" } ]
jMeter - Webservice Test Plan
In this chapter, we will learn how to create a Test Plan to test a WebService. For our test purpose, we have created a simple webservice project and deployed it on the Tomcat server locally. To create a webservice project, we have used Eclipse IDE. First write the Service Endpoint Interface HelloWorld under the package com.tutorialspoint.ws. The contents of the HelloWorld.java are as follows − package com.tutorialspoint.ws; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; //Service Endpoint Interface @WebService @SOAPBinding(style = Style.RPC) public interface HelloWorld { @WebMethod String getHelloWorldMessage(String string); } This service has a method getHelloWorldMessage which takes a String parameter. Next, create the implementation class HelloWorldImpl.java under the package com.tutorialspoint.ws. package com.tutorialspoint.ws; import javax.jws.WebService; @WebService(endpointInterface="com.tutorialspoint.ws.HelloWorld") public class HelloWorldImpl implements HelloWorld { @Override public String getHelloWorldMessage(String myName) { return("Hello "+myName+" to JAX WS world"); } } Let us now publish this web service locally by creating the Endpoint publisher and expose the service on the server. The publish method takes two parameters − Endpoint URL String. Endpoint URL String. Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above. Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above. The contents of HelloWorldPublisher.java are as follows − package com.tutorialspoint.endpoint; import javax.xml.ws.Endpoint; import com.tutorialspoint.ws.HelloWorldImpl; public class HelloWorldPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:9000/ws/hello", new HelloWorldImpl()); } } Modify the web.xml contents as shown below − <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd"> <web-app> <listener> <listener-class> com.sun.xml.ws.transport.http.servlet.WSServletContextListener </listener-class> </listener> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <session-config> <session-timeout>120</session-timeout> </session-config> </web-app> To deploy this application as a webservice, we would need another configuration file sun-jaxws.xml. The contents of this file are as follows − <?xml version = "1.0" encoding = "UTF-8"?> <endpoints xmlns = "http://java.sun.com/xml/ns/jax-ws/ri/runtime" version = "2.0"> <endpoint name = "HelloWorld" implementation = "com.tutorialspoint.ws.HelloWorldImpl" url-pattern = "/hello"/> </endpoints> Now that all the files are ready, the directory structure would look as shown in the following screenshot − Now create a WAR file of this application. Now create a WAR file of this application. Choose the project → right click → Export → WAR file. Choose the project → right click → Export → WAR file. Save this as hello.war file under the webapps folder of Tomcat server. Save this as hello.war file under the webapps folder of Tomcat server. Now start the Tomcat server. Now start the Tomcat server. Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello Now let us create a test plan to test the above webservice. Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh. Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh. Click the Test Plan node. Click the Test Plan node. Rename this Test Plan node as WebserviceTest. Rename this Test Plan node as WebserviceTest. Add one Thread Group, which is placeholder for all other elements like Samplers, Controllers, and Listeners. Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node. Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node. Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed − Name − webservice user Number of Threads (Users) − 2 Ramp-Up Period − leave the the default value of 0 seconds. Loop Count − 2 Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed − Name − webservice user Name − webservice user Number of Threads (Users) − 2 Number of Threads (Users) − 2 Ramp-Up Period − leave the the default value of 0 seconds. Ramp-Up Period − leave the the default value of 0 seconds. Loop Count − 2 Loop Count − 2 Now that we have defined the users, it is time to define the tasks that they will be performing. We will add SOAP/XML-RPC Request element − Right-click mouse button to get the Add menu. Right-click mouse button to get the Add menu. Select Add → Sampler → SOAP/XML-RPC Request. Select Add → Sampler → SOAP/XML-RPC Request. Select the SOAP/XML-RPC Request element in the tree Select the SOAP/XML-RPC Request element in the tree Edit the following properties as in the image below − Edit the following properties as in the image below − The following details are entered in this element − Name − SOAP/XML-RPC Request URL − http://localhost:8080/hello/hello?wsdl Soap/XML-RPC Data − Enter the below contents The following details are entered in this element − Name − SOAP/XML-RPC Request Name − SOAP/XML-RPC Request URL − http://localhost:8080/hello/hello?wsdl URL − http://localhost:8080/hello/hello?wsdl Soap/XML-RPC Data − Enter the below contents Soap/XML-RPC Data − Enter the below contents <soapenv:Envelope xmlns:soapenv = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:web = "http://ws.tutorialspoint.com/"> <soapenv:Header/> <soapenv:Body> <web:getHelloWorldMessage> <arg0>Manisha</arg0> </web:getHelloWorldMessage> </soapenv:Body> </soapenv:Envelope> The final element you need to add to your Test Plan is a Listener. This element is responsible for storing all of the results of your HTTP requests in a file and presenting a visual model of the data. Select the webservice user element. Select the webservice user element. Add a View Results Tree listener by selecting Add → Listener → View Results Tree. Add a View Results Tree listener by selecting Add → Listener → View Results Tree. Now save the above test plan as test_webservice.jmx. Execute this test plan using Run → Start option. The following output can be seen in the listener. In the last image, you can see the response message "Hello Manisha to JAX WS world". 59 Lectures 9.5 hours Rahul Shetty 54 Lectures 13.5 hours Wallace Tauriac 23 Lectures 1.5 hours Anuja Jain 12 Lectures 1 hours Spotle Learn Print Add Notes Bookmark this page
[ { "code": null, "e": 2096, "s": 1905, "text": "In this chapter, we will learn how to create a Test Plan to test a WebService. For our test purpose, we have created a simple webservice project and deployed it on the Tomcat server locally." }, { "code": null, "e": 2302, "s": 2096, "text": "To create a webservice project, we have used Eclipse IDE. First write the Service Endpoint Interface HelloWorld under the package com.tutorialspoint.ws. The contents of the HelloWorld.java are as follows −" }, { "code": null, "e": 2632, "s": 2302, "text": "package com.tutorialspoint.ws;\n\nimport javax.jws.WebMethod;\nimport javax.jws.WebService;\nimport javax.jws.soap.SOAPBinding;\nimport javax.jws.soap.SOAPBinding.Style;\n\n//Service Endpoint Interface\n@WebService\n@SOAPBinding(style = Style.RPC)\n\npublic interface HelloWorld {\n @WebMethod String getHelloWorldMessage(String string);\n}" }, { "code": null, "e": 2711, "s": 2632, "text": "This service has a method getHelloWorldMessage which takes a String parameter." }, { "code": null, "e": 2810, "s": 2711, "text": "Next, create the implementation class HelloWorldImpl.java under the package com.tutorialspoint.ws." }, { "code": null, "e": 3117, "s": 2810, "text": "package com.tutorialspoint.ws;\n\nimport javax.jws.WebService;\n\n@WebService(endpointInterface=\"com.tutorialspoint.ws.HelloWorld\")\npublic class HelloWorldImpl implements HelloWorld {\n @Override\n public String getHelloWorldMessage(String myName) {\n return(\"Hello \"+myName+\" to JAX WS world\");\n }\n}" }, { "code": null, "e": 3234, "s": 3117, "text": "Let us now publish this web service locally by creating the Endpoint publisher and expose the service on the server." }, { "code": null, "e": 3276, "s": 3234, "text": "The publish method takes two parameters −" }, { "code": null, "e": 3297, "s": 3276, "text": "Endpoint URL String." }, { "code": null, "e": 3318, "s": 3297, "text": "Endpoint URL String." }, { "code": null, "e": 3494, "s": 3318, "text": "Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above." }, { "code": null, "e": 3670, "s": 3494, "text": "Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above." }, { "code": null, "e": 3728, "s": 3670, "text": "The contents of HelloWorldPublisher.java are as follows −" }, { "code": null, "e": 4008, "s": 3728, "text": "package com.tutorialspoint.endpoint;\n\nimport javax.xml.ws.Endpoint;\nimport com.tutorialspoint.ws.HelloWorldImpl;\n\npublic class HelloWorldPublisher {\n public static void main(String[] args) {\n Endpoint.publish(\"http://localhost:9000/ws/hello\", new HelloWorldImpl());\n }\n}" }, { "code": null, "e": 4053, "s": 4008, "text": "Modify the web.xml contents as shown below −" }, { "code": null, "e": 4815, "s": 4053, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE web-app PUBLIC \"-//Sun Microsystems, \n Inc.//DTD Web Application 2.3//EN\" \"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd\">\n\n<web-app>\n <listener>\n <listener-class>\n com.sun.xml.ws.transport.http.servlet.WSServletContextListener\n </listener-class>\n </listener>\n\t\n <servlet>\n <servlet-name>hello</servlet-name>\n <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\t\n <servlet-mapping>\n <servlet-name>hello</servlet-name>\n <url-pattern>/hello</url-pattern>\n </servlet-mapping>\n\t\n <session-config>\n <session-timeout>120</session-timeout>\n </session-config>\n\t\n</web-app>" }, { "code": null, "e": 4958, "s": 4815, "text": "To deploy this application as a webservice, we would need another configuration file sun-jaxws.xml. The contents of this file are as follows −" }, { "code": null, "e": 5235, "s": 4958, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<endpoints\n xmlns = \"http://java.sun.com/xml/ns/jax-ws/ri/runtime\"\n version = \"2.0\">\n \n <endpoint name = \"HelloWorld\" \n implementation = \"com.tutorialspoint.ws.HelloWorldImpl\" \n url-pattern = \"/hello\"/>\n</endpoints>" }, { "code": null, "e": 5343, "s": 5235, "text": "Now that all the files are ready, the directory structure would look as shown in the following screenshot −" }, { "code": null, "e": 5386, "s": 5343, "text": "Now create a WAR file of this application." }, { "code": null, "e": 5429, "s": 5386, "text": "Now create a WAR file of this application." }, { "code": null, "e": 5483, "s": 5429, "text": "Choose the project → right click → Export → WAR file." }, { "code": null, "e": 5537, "s": 5483, "text": "Choose the project → right click → Export → WAR file." }, { "code": null, "e": 5608, "s": 5537, "text": "Save this as hello.war file under the webapps folder of Tomcat server." }, { "code": null, "e": 5679, "s": 5608, "text": "Save this as hello.war file under the webapps folder of Tomcat server." }, { "code": null, "e": 5708, "s": 5679, "text": "Now start the Tomcat server." }, { "code": null, "e": 5737, "s": 5708, "text": "Now start the Tomcat server." }, { "code": null, "e": 5858, "s": 5737, "text": "Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello" }, { "code": null, "e": 5979, "s": 5858, "text": "Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello" }, { "code": null, "e": 6039, "s": 5979, "text": "Now let us create a test plan to test the above webservice." }, { "code": null, "e": 6120, "s": 6039, "text": "Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh." }, { "code": null, "e": 6201, "s": 6120, "text": "Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh." }, { "code": null, "e": 6227, "s": 6201, "text": "Click the Test Plan node." }, { "code": null, "e": 6253, "s": 6227, "text": "Click the Test Plan node." }, { "code": null, "e": 6299, "s": 6253, "text": "Rename this Test Plan node as WebserviceTest." }, { "code": null, "e": 6345, "s": 6299, "text": "Rename this Test Plan node as WebserviceTest." }, { "code": null, "e": 6454, "s": 6345, "text": "Add one Thread Group, which is placeholder for all other elements like Samplers, Controllers, and Listeners." }, { "code": null, "e": 6611, "s": 6454, "text": "Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node." }, { "code": null, "e": 6768, "s": 6611, "text": "Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node." }, { "code": null, "e": 7017, "s": 6768, "text": "Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed −\n\nName − webservice user\nNumber of Threads (Users) − 2\nRamp-Up Period − leave the the default value of 0 seconds.\nLoop Count − 2\n\n" }, { "code": null, "e": 7136, "s": 7017, "text": "Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed −" }, { "code": null, "e": 7159, "s": 7136, "text": "Name − webservice user" }, { "code": null, "e": 7182, "s": 7159, "text": "Name − webservice user" }, { "code": null, "e": 7212, "s": 7182, "text": "Number of Threads (Users) − 2" }, { "code": null, "e": 7242, "s": 7212, "text": "Number of Threads (Users) − 2" }, { "code": null, "e": 7301, "s": 7242, "text": "Ramp-Up Period − leave the the default value of 0 seconds." }, { "code": null, "e": 7360, "s": 7301, "text": "Ramp-Up Period − leave the the default value of 0 seconds." }, { "code": null, "e": 7375, "s": 7360, "text": "Loop Count − 2" }, { "code": null, "e": 7390, "s": 7375, "text": "Loop Count − 2" }, { "code": null, "e": 7487, "s": 7390, "text": "Now that we have defined the users, it is time to define the tasks that they will be performing." }, { "code": null, "e": 7530, "s": 7487, "text": "We will add SOAP/XML-RPC Request element −" }, { "code": null, "e": 7576, "s": 7530, "text": "Right-click mouse button to get the Add menu." }, { "code": null, "e": 7622, "s": 7576, "text": "Right-click mouse button to get the Add menu." }, { "code": null, "e": 7667, "s": 7622, "text": "Select Add → Sampler → SOAP/XML-RPC Request." }, { "code": null, "e": 7712, "s": 7667, "text": "Select Add → Sampler → SOAP/XML-RPC Request." }, { "code": null, "e": 7764, "s": 7712, "text": "Select the SOAP/XML-RPC Request element in the tree" }, { "code": null, "e": 7816, "s": 7764, "text": "Select the SOAP/XML-RPC Request element in the tree" }, { "code": null, "e": 7870, "s": 7816, "text": "Edit the following properties as in the image below −" }, { "code": null, "e": 7924, "s": 7870, "text": "Edit the following properties as in the image below −" }, { "code": null, "e": 8097, "s": 7924, "text": "The following details are entered in this element −\n\nName − SOAP/XML-RPC Request\nURL − http://localhost:8080/hello/hello?wsdl\nSoap/XML-RPC Data − Enter the below contents\n\n" }, { "code": null, "e": 8149, "s": 8097, "text": "The following details are entered in this element −" }, { "code": null, "e": 8177, "s": 8149, "text": "Name − SOAP/XML-RPC Request" }, { "code": null, "e": 8205, "s": 8177, "text": "Name − SOAP/XML-RPC Request" }, { "code": null, "e": 8250, "s": 8205, "text": "URL − http://localhost:8080/hello/hello?wsdl" }, { "code": null, "e": 8295, "s": 8250, "text": "URL − http://localhost:8080/hello/hello?wsdl" }, { "code": null, "e": 8340, "s": 8295, "text": "Soap/XML-RPC Data − Enter the below contents" }, { "code": null, "e": 8385, "s": 8340, "text": "Soap/XML-RPC Data − Enter the below contents" }, { "code": null, "e": 8693, "s": 8385, "text": "<soapenv:Envelope xmlns:soapenv = \"http://schemas.xmlsoap.org/soap/envelope/\" \n xmlns:web = \"http://ws.tutorialspoint.com/\">\n <soapenv:Header/>\n\t\n <soapenv:Body>\n <web:getHelloWorldMessage>\n <arg0>Manisha</arg0>\n </web:getHelloWorldMessage>\n </soapenv:Body>\n \n</soapenv:Envelope>" }, { "code": null, "e": 8894, "s": 8693, "text": "The final element you need to add to your Test Plan is a Listener. This element is responsible for storing all of the results of your HTTP requests in a file and presenting a visual model of the data." }, { "code": null, "e": 8930, "s": 8894, "text": "Select the webservice user element." }, { "code": null, "e": 8966, "s": 8930, "text": "Select the webservice user element." }, { "code": null, "e": 9048, "s": 8966, "text": "Add a View Results Tree listener by selecting Add → Listener → View Results Tree." }, { "code": null, "e": 9130, "s": 9048, "text": "Add a View Results Tree listener by selecting Add → Listener → View Results Tree." }, { "code": null, "e": 9232, "s": 9130, "text": "Now save the above test plan as test_webservice.jmx. Execute this test plan using Run → Start option." }, { "code": null, "e": 9282, "s": 9232, "text": "The following output can be seen in the listener." }, { "code": null, "e": 9367, "s": 9282, "text": "In the last image, you can see the response message \"Hello Manisha to JAX WS world\"." }, { "code": null, "e": 9402, "s": 9367, "text": "\n 59 Lectures \n 9.5 hours \n" }, { "code": null, "e": 9416, "s": 9402, "text": " Rahul Shetty" }, { "code": null, "e": 9452, "s": 9416, "text": "\n 54 Lectures \n 13.5 hours \n" }, { "code": null, "e": 9469, "s": 9452, "text": " Wallace Tauriac" }, { "code": null, "e": 9504, "s": 9469, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9516, "s": 9504, "text": " Anuja Jain" }, { "code": null, "e": 9549, "s": 9516, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 9563, "s": 9549, "text": " Spotle Learn" }, { "code": null, "e": 9570, "s": 9563, "text": " Print" }, { "code": null, "e": 9581, "s": 9570, "text": " Add Notes" } ]
How to Show All Tables in MySQL using Python? - GeeksforGeeks
29 Sep, 2021 A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. In order to make python interact with the MySQL database, we use Python-MySQL-Connector. Here we will try implementing SQL queries which will show the names of all the tables present in the database or server. Syntax: To show the name of tables present inside a database: SHOW Tables; To show the name of tables present inside a server: SELECT table_name FROM information_schema.tables; Database in use: Schema of the database used The following programs implement the same. Example 1: Display table names present inside a database: Python3 import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="", database="gfg") mycursor = mydb.cursor() mycursor.execute("Show tables;") myresult = mycursor.fetchall() for x in myresult: print(x) Output: Table names in gfg database Example 2: Display table names present inside a server: Python3 import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="",) mycursor = mydb.cursor() mycursor.execute("SELECT table_name FROM information_schema.tables;") myresult = mycursor.fetchall() for x in myresult: print(x) Output: Table names in server surindertarika1234 Picked Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24765, "s": 24737, "text": "\n29 Sep, 2021" }, { "code": null, "e": 25027, "s": 24765, "text": "A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server." }, { "code": null, "e": 25237, "s": 25027, "text": "In order to make python interact with the MySQL database, we use Python-MySQL-Connector. Here we will try implementing SQL queries which will show the names of all the tables present in the database or server." }, { "code": null, "e": 25245, "s": 25237, "text": "Syntax:" }, { "code": null, "e": 25299, "s": 25245, "text": "To show the name of tables present inside a database:" }, { "code": null, "e": 25312, "s": 25299, "text": "SHOW Tables;" }, { "code": null, "e": 25364, "s": 25312, "text": "To show the name of tables present inside a server:" }, { "code": null, "e": 25382, "s": 25364, "text": "SELECT table_name" }, { "code": null, "e": 25414, "s": 25382, "text": "FROM information_schema.tables;" }, { "code": null, "e": 25431, "s": 25414, "text": "Database in use:" }, { "code": null, "e": 25459, "s": 25431, "text": "Schema of the database used" }, { "code": null, "e": 25502, "s": 25459, "text": "The following programs implement the same." }, { "code": null, "e": 25560, "s": 25502, "text": "Example 1: Display table names present inside a database:" }, { "code": null, "e": 25568, "s": 25560, "text": "Python3" }, { "code": "import mysql.connector mydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"\", database=\"gfg\") mycursor = mydb.cursor() mycursor.execute(\"Show tables;\") myresult = mycursor.fetchall() for x in myresult: print(x)", "e": 25815, "s": 25568, "text": null }, { "code": null, "e": 25823, "s": 25815, "text": "Output:" }, { "code": null, "e": 25852, "s": 25823, "text": "Table names in gfg database" }, { "code": null, "e": 25908, "s": 25852, "text": "Example 2: Display table names present inside a server:" }, { "code": null, "e": 25916, "s": 25908, "text": "Python3" }, { "code": "import mysql.connector mydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"\",) mycursor = mydb.cursor() mycursor.execute(\"SELECT table_name FROM information_schema.tables;\") myresult = mycursor.fetchall() for x in myresult: print(x)", "e": 26174, "s": 25916, "text": null }, { "code": null, "e": 26182, "s": 26174, "text": "Output:" }, { "code": null, "e": 26204, "s": 26182, "text": "Table names in server" }, { "code": null, "e": 26223, "s": 26204, "text": "surindertarika1234" }, { "code": null, "e": 26230, "s": 26223, "text": "Picked" }, { "code": null, "e": 26243, "s": 26230, "text": "Python-mySQL" }, { "code": null, "e": 26250, "s": 26243, "text": "Python" }, { "code": null, "e": 26348, "s": 26250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26357, "s": 26348, "text": "Comments" }, { "code": null, "e": 26370, "s": 26357, "text": "Old Comments" }, { "code": null, "e": 26388, "s": 26370, "text": "Python Dictionary" }, { "code": null, "e": 26423, "s": 26388, "text": "Read a file line by line in Python" }, { "code": null, "e": 26445, "s": 26423, "text": "Enumerate() in Python" }, { "code": null, "e": 26477, "s": 26445, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26507, "s": 26477, "text": "Iterate over a list in Python" }, { "code": null, "e": 26549, "s": 26507, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26575, "s": 26549, "text": "Python String | replace()" }, { "code": null, "e": 26618, "s": 26575, "text": "Python program to convert a list to string" }, { "code": null, "e": 26662, "s": 26618, "text": "Reading and Writing to text files in Python" } ]
Convert a Number to Hexadecimal in C++
Suppose we have an integer; we have to devise an algorithm to convert it to hexadecimal. For negative numbers we will use the two’s complement method. So, if the input is like 254 and -12, then the output will be fe and fffffff4 respectively. To solve this, we will follow these steps − if num1 is same as 0, then −return "0" if num1 is same as 0, then − return "0" return "0" num := num1 num := num1 s := blank string s := blank string while num is non-zero, do −temp := num mod 16if temp <= 9, then −s := s + temp as numeric characterOtherwises := s + temp as alphabetnum := num / 16 while num is non-zero, do − temp := num mod 16 temp := num mod 16 if temp <= 9, then −s := s + temp as numeric character if temp <= 9, then − s := s + temp as numeric character s := s + temp as numeric character Otherwises := s + temp as alphabet Otherwise s := s + temp as alphabet s := s + temp as alphabet num := num / 16 num := num / 16 reverse the array s reverse the array s return s return s Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string toHex(int num1){ if (num1 == 0) return "0"; u_int num = num1; string s = ""; while (num) { int temp = num % 16; if (temp <= 9) s += (48 + temp); else s += (87 + temp); num = num / 16; } reverse(s.begin(), s.end()); return s; } }; main(){ Solution ob; cout << (ob.toHex(254)) << endl; cout << (ob.toHex(-12)); } 254 -12 fe fffffff4
[ { "code": null, "e": 1213, "s": 1062, "text": "Suppose we have an integer; we have to devise an algorithm to convert it to hexadecimal. For negative numbers we will use the two’s complement method." }, { "code": null, "e": 1305, "s": 1213, "text": "So, if the input is like 254 and -12, then the output will be fe and fffffff4 respectively." }, { "code": null, "e": 1349, "s": 1305, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1388, "s": 1349, "text": "if num1 is same as 0, then −return \"0\"" }, { "code": null, "e": 1417, "s": 1388, "text": "if num1 is same as 0, then −" }, { "code": null, "e": 1428, "s": 1417, "text": "return \"0\"" }, { "code": null, "e": 1439, "s": 1428, "text": "return \"0\"" }, { "code": null, "e": 1451, "s": 1439, "text": "num := num1" }, { "code": null, "e": 1463, "s": 1451, "text": "num := num1" }, { "code": null, "e": 1481, "s": 1463, "text": "s := blank string" }, { "code": null, "e": 1499, "s": 1481, "text": "s := blank string" }, { "code": null, "e": 1648, "s": 1499, "text": "while num is non-zero, do −temp := num mod 16if temp <= 9, then −s := s + temp as numeric characterOtherwises := s + temp as alphabetnum := num / 16" }, { "code": null, "e": 1676, "s": 1648, "text": "while num is non-zero, do −" }, { "code": null, "e": 1695, "s": 1676, "text": "temp := num mod 16" }, { "code": null, "e": 1714, "s": 1695, "text": "temp := num mod 16" }, { "code": null, "e": 1769, "s": 1714, "text": "if temp <= 9, then −s := s + temp as numeric character" }, { "code": null, "e": 1790, "s": 1769, "text": "if temp <= 9, then −" }, { "code": null, "e": 1825, "s": 1790, "text": "s := s + temp as numeric character" }, { "code": null, "e": 1860, "s": 1825, "text": "s := s + temp as numeric character" }, { "code": null, "e": 1895, "s": 1860, "text": "Otherwises := s + temp as alphabet" }, { "code": null, "e": 1905, "s": 1895, "text": "Otherwise" }, { "code": null, "e": 1931, "s": 1905, "text": "s := s + temp as alphabet" }, { "code": null, "e": 1957, "s": 1931, "text": "s := s + temp as alphabet" }, { "code": null, "e": 1973, "s": 1957, "text": "num := num / 16" }, { "code": null, "e": 1989, "s": 1973, "text": "num := num / 16" }, { "code": null, "e": 2009, "s": 1989, "text": "reverse the array s" }, { "code": null, "e": 2029, "s": 2009, "text": "reverse the array s" }, { "code": null, "e": 2038, "s": 2029, "text": "return s" }, { "code": null, "e": 2047, "s": 2038, "text": "return s" }, { "code": null, "e": 2119, "s": 2047, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2130, "s": 2119, "text": " Live Demo" }, { "code": null, "e": 2645, "s": 2130, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n string toHex(int num1){\n if (num1 == 0)\n return \"0\";\n u_int num = num1;\n string s = \"\";\n while (num) {\n int temp = num % 16;\n if (temp <= 9)\n s += (48 + temp);\n else\n s += (87 + temp);\n num = num / 16;\n }\n reverse(s.begin(), s.end());\n return s;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.toHex(254)) << endl;\n cout << (ob.toHex(-12));\n}" }, { "code": null, "e": 2653, "s": 2645, "text": "254\n-12" }, { "code": null, "e": 2665, "s": 2653, "text": "fe\nfffffff4" } ]
Track COVID-19 Data Yourself Using R | by Chris Ross | Towards Data Science
When the global pandemic was first gaining momentum earlier this year, I relied on the media for updates, as most people do. I soon found that the media reports were not only inconsistent but often presented incomplete information. The fundamental issue with these limitations is that they frequently lead to misunderstandings and misinterpretations of the data, as evidenced by the widely divergent views on the severity of this global crisis at any given point in time. Media organizations often cherry-pick the stats and graphs they report with a preference for sensational headlines that align with the story they are trying to tell. You can’t blame them too much for this tendency given their primary goal is to engage their audience. But if you’re hoping to get an accurate and reliable picture of the current impact of COVID-19 in your country, including tracking and charting trends, you can’t beat analyzing the source data yourself. In this article, we’re going to cover how to write a script in R to pull and analyze current coronavirus data. The best part is that once you’ve written the script, you can easily save and rerun it at will. You no longer need to rely on incomplete snapshots of the data based on what others decided to analyze and report. Now you’ll quickly and easily have the most recent COVID-19 data at your fingertips and can track current stats and trends yourself! I use R Studio and have this script saved in R markdown (Rmd). If you prefer to use base R, no worries, the code will work in a standard R script as well. I’m not going to cover how to install R [1] or R Studio [2], but both are open source (and free) and you can check the references below to find detailed documentation and installation instructions. First, open a new Rmd (or R) file. If you’re using Rmd, use Ctrl + Alt + I (Mac: Cmd + Option + I) to insert a code chunk. In this new chunk, we’ll load the packages we’re going to use. Note that you’ll first need to install these two packages if you haven’t already. I included the code below, to both install and load them, though you’ll need to uncomment the install lines (remove the hashtags) first if you need to install them. You only need to install packages once, so feel free to delete those commented lines once you’ve installed them. # install.packages('lubridate')# install.packages('tidyverse')library(lubridate)library(tidyverse) We won’t go into too much detail about what each package does because it’s beyond the scope of this article. I will, however, provide a brief description of them below and include links to their documentation in the references if you want to learn more. I highly recommend you take a closer look at the docs for these packages if you plan to use R regularly. They are awesome and worth learning! The first package is lubridate, which provides a lot of useful functions for working with date variables [3]. For our purposes, we’re just using lubridate to convert the date format provided in the dataset into a date variable recognized by R. The other package, tidyverse, is actually a group of packages that make up the “Tidyverse” [4]. When you install (and load) tidyverse, the entire group of included packages is automatically installed (and loaded) for you. Two of these included packages are worth mentioning because we’ll use them a few times, dplyr and ggplot2. The dplyr package “is a grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges” [5]. There could be a full book just covering how to use dplr, so that description will have to suffice for now. Ggplot2 is another amazing package used for plotting graphs and charts [6]. I took a full semester data visualization class in grad school that exclusively used ggplot2, and we only scratched the surface of available functionality. After installing and loading these two packages, we’re ready to dig in and start exploring the data! When first looking for available coronavirus datasets earlier this year, I checked out several different options. After a few weeks of testing these options out, I developed a preference for the European Center for Disease Control (ECDC) data [7]. It’s consistently updated (nightly) and offers most of the info I was looking for, including daily case counts, deaths, and population info, broken down by country/territory. Over the past 4–5 months, they’ve updated the dataset a few times changing the formatting and adding columns. But overall they’ve been remarkably consistent in maintaining and updating the data. Thus, the ECDC dataset has been my go-to source for COVID-19 tracking, and it’s what we’ll use here. # FROM: https://www.ecdc.europa.eudata <- read.csv(“https://opendata.ecdc.europa.eu/covid19/casedistribution/csv", na.strings = “”, fileEncoding = “UTF-8-BOM”, stringsAsFactors = F)data# convert date formatdata$date_reported <- mdy(paste0(data$month,”-”,data$day,”-”,data$year)) The ECDC provides a handy URL for their dataset in CSV format which we can easily pull into R using the built-in “read.csv” function. The nice thing about this link is that they update the dataset daily using the same URL so you never need to change the code to import the dataset. After running the read.csv line (Ctrl + Enter to run a single line or highlighted selection), the dataset is saved in the “data” variable. Run the next line that just says “data” to take a peek at the raw dataset. As you can see, the “dateRep” column formats the date in a rather unique manner using DD/MM/YYYY. The last line of code in the above chunk essentially just converts that date string into a format that R (and ggplot2) can read. There are numerous ways to accomplish this task but for simplicity, we’ll using the mdy() function included in the lubridate package [3]. Let’s start by taking a look at the cumulative total cases and deaths worldwide. The first line will sum the total number of COVID-19 cases globally to date. Next, we’ll break it down by country and calculate the total number of cases in that country, as well as the maximum number of cases reported in a single day in each country. We then sort the results by total cases in descending order. Below that, we will calculate the same thing but for coronavirus deaths this time (instead of new cases). # total cases worldwide to datesum(data$cases)# total cases and max single day by countrydata %>% group_by(countriesAndTerritories) %>% summarise(cases_sum = sum(cases), cases_max = max(cases)) %>% arrange(desc(cases_sum))# total deaths worldwide to datesum(data$deaths)# total deaths and max single day by countrydata %>% group_by(countriesAndTerritories) %>% summarise(deaths_sum = sum(deaths), deaths_max = max(deaths)) %>% arrange(desc(deaths_sum)) There will be four outputs from the above chunk of code. Below is the last output, showing the total COVID-19 deaths by country, as well as the max number of deaths in a single day. Currently (Aug. 2020), the US has the most coronavirus deaths by a fairly wide margin. Now we’ll start plotting the data to identify trends. Since I live in the US, I’m going to plot US cases. You can easily modify the code using other countries, which we’ll cover shortly. us <- data[data$countriesAndTerritories == ‘United_States_of_America’,]usUS_cases <- ggplot(us, aes(date_reported, as.numeric(cases))) + geom_col(fill = ‘blue’, alpha = 0.6) + theme_minimal(base_size = 14) + xlab(NULL) + ylab(NULL) + scale_x_date(date_labels = “%Y/%m/%d”)US_cases + labs(title=”Daily COVID-19 Cases in US”) First, I filter the dataset to just look at US cases and store that to a variable. I then use ggplot2 to plot the daily new cases of COVID-19. For more info on how to use ggplot2, check out their documentation [6]. After running the above chunk, you should see the below plot. Awesome, right? Of course, the picture painted by the data is not awesome, but the fact that you can track it yourself certainly is! Let’s move on and do the same thing for coronavirus deaths. The code is virtually the same except we are now tracking “deaths” instead of “cases.” US_deaths <- ggplot(us, aes(date_reported, as.numeric(deaths))) + geom_col(fill = ‘purple’, alpha = 0.6) + theme_minimal(base_size = 14) + xlab(NULL) + ylab(NULL) + scale_x_date(date_labels = “%Y/%m/%d”)US_deaths + labs(title=”Daily COVID-19 Deaths in US”) As you can see, the death rate paints a different picture than the case counts. While the 2nd wave of cases was twice the size of the 1st, the 2nd wave of deaths hasn’t eclipsed the 1st (yet). These are interesting trends to watch unfold and are definitely worth tracking. Hold onto your hats, because the last plot we’re going to cover will allow us to compare different countries! I chose the US, China, Italy, and Spain, but you can mix it up and choose whatever countries/territories you’re interested in. # Now lets add in a few more countrieschina <- data[data$countriesAndTerritories == ‘China’,]spain <- data[data$countriesAndTerritories == ‘Spain’,]italy <- data[data$countriesAndTerritories == ‘Italy’,]USplot <- ggplot(us, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000))) + geom_col(fill = ‘blue’, alpha = 0.6) + theme_minimal(base_size = 14) + xlab(NULL) + ylab(NULL) + scale_x_date(date_labels = “%Y/%m/%d”)China_US <- USplot + geom_col(data=china, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000)), fill=”red”, alpha = 0.5)Ch_US_Sp <- China_US + geom_col(data=spain, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000)), fill=”#E69F00", alpha = 0.4)Chn_US_Sp_It <- Ch_US_Sp + geom_col(data=italy, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000)), fill=”#009E73", alpha = 0.9)Chn_US_Sp_It + labs(title=”China, US, Italy, & Spain”) This code chunk looks a bit more intimidating, but it’s actually pretty straightforward. At the top we filter the dataset for the countries we’re interested in and save each in its own variable. The next series of code blocks create the plots that we are going to stack, one for each country we add. Considering we want to compare countries, we will use a new column this time, one that lists the cumulative number of new cases over the past 14 days per 100,000 people in that country. Since the population of each country varies, using the number of cases per 100,000 people allows us to standardize the case counts based on the population. Let’s see how that looks. The little red hump (in the beginning) is China, with Italy in green, Spain in yellow, and the US in blue. As you can see, China was hit first although the overall impact was significantly lower than the other three countries (based on the numbers they reported at least). Sadly, the US still looks in pretty bad shape comparatively. Of these four countries, Spain was hit hardest by the first wave while the US and Italy appear similarly impacted. Unfortunately, the 2nd wave hit the US like a truck (in terms of cumulative cases), although we appear to be starting a downtrend (fingers crossed). Spain’s 2nd wave appears to still be ramping up. We’ll have to continue monitoring their data to see when they start flattening the curve. Italy, on the other hand, appears to have done an excellent job curbing the spread of COVID-19 after their first wave. There may be lessons we can learn from their success. This is just the beginning. We’ve only scratched the surface of what you can do with this data. I hope you take what we covered here and run with it! Let it be a springboard for your own discovery. You no longer need to rely on snippets from the media, or other data scientists, to stay on top of the COVID-19 data and track trends. Let me know in the comments what you do with the data, and share with us what you discover! ✍️ Subscribe to get my newest articles, featured in publications like The Startup & Towards Data Science ➡️ [1] R, “R: The R Project for Statistical Computing” r-project.org, 2020. [Online]. Available: https://www.r-project.org. [Accessed: Aug. 10, 2020]. [2] R Studio, “R Studio IDE Desktop” rstudio.com, 2020. [Online]. Available: https://rstudio.com/products/rstudio. [Accessed: Aug. 10, 2020]. [3] lubridate package | R Documentation, “Make Dealing with Dates a Little Easier” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/lubridate/versions/1.7.9. [Accessed: Aug. 10, 2020]. [4] tidyverse package | R Documentation, “Easily Install and Load the ‘Tidyverse’” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/tidyverse/versions/1.3.0. [Accessed: Aug. 10, 2020]. [5] dplyr package | R Documentation, “A Grammar of Data Manipulation” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/dplyr/versions/0.7.8. [Accessed: Aug. 10, 2020]. [6] ggplot2 package | R Documentation, “Create Elegant Data Visualisations Using the Grammar of Graphics” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/ggplot2/versions/3.3.2. [Accessed: Aug. 10, 2020]. [7] European CDC, “ ECDC COVID-19 pandemic” ecdc.europa.eu, 2020. [Online]. Available: https://www.ecdc.europa.eu/en/covid-19-pandemic. [Accessed: Aug. 10, 2020].
[ { "code": null, "e": 644, "s": 172, "text": "When the global pandemic was first gaining momentum earlier this year, I relied on the media for updates, as most people do. I soon found that the media reports were not only inconsistent but often presented incomplete information. The fundamental issue with these limitations is that they frequently lead to misunderstandings and misinterpretations of the data, as evidenced by the widely divergent views on the severity of this global crisis at any given point in time." }, { "code": null, "e": 1115, "s": 644, "text": "Media organizations often cherry-pick the stats and graphs they report with a preference for sensational headlines that align with the story they are trying to tell. You can’t blame them too much for this tendency given their primary goal is to engage their audience. But if you’re hoping to get an accurate and reliable picture of the current impact of COVID-19 in your country, including tracking and charting trends, you can’t beat analyzing the source data yourself." }, { "code": null, "e": 1570, "s": 1115, "text": "In this article, we’re going to cover how to write a script in R to pull and analyze current coronavirus data. The best part is that once you’ve written the script, you can easily save and rerun it at will. You no longer need to rely on incomplete snapshots of the data based on what others decided to analyze and report. Now you’ll quickly and easily have the most recent COVID-19 data at your fingertips and can track current stats and trends yourself!" }, { "code": null, "e": 1923, "s": 1570, "text": "I use R Studio and have this script saved in R markdown (Rmd). If you prefer to use base R, no worries, the code will work in a standard R script as well. I’m not going to cover how to install R [1] or R Studio [2], but both are open source (and free) and you can check the references below to find detailed documentation and installation instructions." }, { "code": null, "e": 2469, "s": 1923, "text": "First, open a new Rmd (or R) file. If you’re using Rmd, use Ctrl + Alt + I (Mac: Cmd + Option + I) to insert a code chunk. In this new chunk, we’ll load the packages we’re going to use. Note that you’ll first need to install these two packages if you haven’t already. I included the code below, to both install and load them, though you’ll need to uncomment the install lines (remove the hashtags) first if you need to install them. You only need to install packages once, so feel free to delete those commented lines once you’ve installed them." }, { "code": null, "e": 2568, "s": 2469, "text": "# install.packages('lubridate')# install.packages('tidyverse')library(lubridate)library(tidyverse)" }, { "code": null, "e": 2964, "s": 2568, "text": "We won’t go into too much detail about what each package does because it’s beyond the scope of this article. I will, however, provide a brief description of them below and include links to their documentation in the references if you want to learn more. I highly recommend you take a closer look at the docs for these packages if you plan to use R regularly. They are awesome and worth learning!" }, { "code": null, "e": 3537, "s": 2964, "text": "The first package is lubridate, which provides a lot of useful functions for working with date variables [3]. For our purposes, we’re just using lubridate to convert the date format provided in the dataset into a date variable recognized by R. The other package, tidyverse, is actually a group of packages that make up the “Tidyverse” [4]. When you install (and load) tidyverse, the entire group of included packages is automatically installed (and loaded) for you. Two of these included packages are worth mentioning because we’ll use them a few times, dplyr and ggplot2." }, { "code": null, "e": 4139, "s": 3537, "text": "The dplyr package “is a grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges” [5]. There could be a full book just covering how to use dplr, so that description will have to suffice for now. Ggplot2 is another amazing package used for plotting graphs and charts [6]. I took a full semester data visualization class in grad school that exclusively used ggplot2, and we only scratched the surface of available functionality. After installing and loading these two packages, we’re ready to dig in and start exploring the data!" }, { "code": null, "e": 4858, "s": 4139, "text": "When first looking for available coronavirus datasets earlier this year, I checked out several different options. After a few weeks of testing these options out, I developed a preference for the European Center for Disease Control (ECDC) data [7]. It’s consistently updated (nightly) and offers most of the info I was looking for, including daily case counts, deaths, and population info, broken down by country/territory. Over the past 4–5 months, they’ve updated the dataset a few times changing the formatting and adding columns. But overall they’ve been remarkably consistent in maintaining and updating the data. Thus, the ECDC dataset has been my go-to source for COVID-19 tracking, and it’s what we’ll use here." }, { "code": null, "e": 5137, "s": 4858, "text": "# FROM: https://www.ecdc.europa.eudata <- read.csv(“https://opendata.ecdc.europa.eu/covid19/casedistribution/csv\", na.strings = “”, fileEncoding = “UTF-8-BOM”, stringsAsFactors = F)data# convert date formatdata$date_reported <- mdy(paste0(data$month,”-”,data$day,”-”,data$year))" }, { "code": null, "e": 5633, "s": 5137, "text": "The ECDC provides a handy URL for their dataset in CSV format which we can easily pull into R using the built-in “read.csv” function. The nice thing about this link is that they update the dataset daily using the same URL so you never need to change the code to import the dataset. After running the read.csv line (Ctrl + Enter to run a single line or highlighted selection), the dataset is saved in the “data” variable. Run the next line that just says “data” to take a peek at the raw dataset." }, { "code": null, "e": 5998, "s": 5633, "text": "As you can see, the “dateRep” column formats the date in a rather unique manner using DD/MM/YYYY. The last line of code in the above chunk essentially just converts that date string into a format that R (and ggplot2) can read. There are numerous ways to accomplish this task but for simplicity, we’ll using the mdy() function included in the lubridate package [3]." }, { "code": null, "e": 6498, "s": 5998, "text": "Let’s start by taking a look at the cumulative total cases and deaths worldwide. The first line will sum the total number of COVID-19 cases globally to date. Next, we’ll break it down by country and calculate the total number of cases in that country, as well as the maximum number of cases reported in a single day in each country. We then sort the results by total cases in descending order. Below that, we will calculate the same thing but for coronavirus deaths this time (instead of new cases)." }, { "code": null, "e": 6957, "s": 6498, "text": "# total cases worldwide to datesum(data$cases)# total cases and max single day by countrydata %>% group_by(countriesAndTerritories) %>% summarise(cases_sum = sum(cases), cases_max = max(cases)) %>% arrange(desc(cases_sum))# total deaths worldwide to datesum(data$deaths)# total deaths and max single day by countrydata %>% group_by(countriesAndTerritories) %>% summarise(deaths_sum = sum(deaths), deaths_max = max(deaths)) %>% arrange(desc(deaths_sum))" }, { "code": null, "e": 7226, "s": 6957, "text": "There will be four outputs from the above chunk of code. Below is the last output, showing the total COVID-19 deaths by country, as well as the max number of deaths in a single day. Currently (Aug. 2020), the US has the most coronavirus deaths by a fairly wide margin." }, { "code": null, "e": 7413, "s": 7226, "text": "Now we’ll start plotting the data to identify trends. Since I live in the US, I’m going to plot US cases. You can easily modify the code using other countries, which we’ll cover shortly." }, { "code": null, "e": 7740, "s": 7413, "text": "us <- data[data$countriesAndTerritories == ‘United_States_of_America’,]usUS_cases <- ggplot(us, aes(date_reported, as.numeric(cases))) + geom_col(fill = ‘blue’, alpha = 0.6) + theme_minimal(base_size = 14) + xlab(NULL) + ylab(NULL) + scale_x_date(date_labels = “%Y/%m/%d”)US_cases + labs(title=”Daily COVID-19 Cases in US”)" }, { "code": null, "e": 8017, "s": 7740, "text": "First, I filter the dataset to just look at US cases and store that to a variable. I then use ggplot2 to plot the daily new cases of COVID-19. For more info on how to use ggplot2, check out their documentation [6]. After running the above chunk, you should see the below plot." }, { "code": null, "e": 8150, "s": 8017, "text": "Awesome, right? Of course, the picture painted by the data is not awesome, but the fact that you can track it yourself certainly is!" }, { "code": null, "e": 8297, "s": 8150, "text": "Let’s move on and do the same thing for coronavirus deaths. The code is virtually the same except we are now tracking “deaths” instead of “cases.”" }, { "code": null, "e": 8557, "s": 8297, "text": "US_deaths <- ggplot(us, aes(date_reported, as.numeric(deaths))) + geom_col(fill = ‘purple’, alpha = 0.6) + theme_minimal(base_size = 14) + xlab(NULL) + ylab(NULL) + scale_x_date(date_labels = “%Y/%m/%d”)US_deaths + labs(title=”Daily COVID-19 Deaths in US”)" }, { "code": null, "e": 8830, "s": 8557, "text": "As you can see, the death rate paints a different picture than the case counts. While the 2nd wave of cases was twice the size of the 1st, the 2nd wave of deaths hasn’t eclipsed the 1st (yet). These are interesting trends to watch unfold and are definitely worth tracking." }, { "code": null, "e": 9067, "s": 8830, "text": "Hold onto your hats, because the last plot we’re going to cover will allow us to compare different countries! I chose the US, China, Italy, and Spain, but you can mix it up and choose whatever countries/territories you’re interested in." }, { "code": null, "e": 10071, "s": 9067, "text": "# Now lets add in a few more countrieschina <- data[data$countriesAndTerritories == ‘China’,]spain <- data[data$countriesAndTerritories == ‘Spain’,]italy <- data[data$countriesAndTerritories == ‘Italy’,]USplot <- ggplot(us, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000))) + geom_col(fill = ‘blue’, alpha = 0.6) + theme_minimal(base_size = 14) + xlab(NULL) + ylab(NULL) + scale_x_date(date_labels = “%Y/%m/%d”)China_US <- USplot + geom_col(data=china, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000)), fill=”red”, alpha = 0.5)Ch_US_Sp <- China_US + geom_col(data=spain, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000)), fill=”#E69F00\", alpha = 0.4)Chn_US_Sp_It <- Ch_US_Sp + geom_col(data=italy, aes(date_reported, as.numeric(Cumulative_number_for_14_days_of_COVID.19_cases_per_100000)), fill=”#009E73\", alpha = 0.9)Chn_US_Sp_It + labs(title=”China, US, Italy, & Spain”)" }, { "code": null, "e": 10371, "s": 10071, "text": "This code chunk looks a bit more intimidating, but it’s actually pretty straightforward. At the top we filter the dataset for the countries we’re interested in and save each in its own variable. The next series of code blocks create the plots that we are going to stack, one for each country we add." }, { "code": null, "e": 10739, "s": 10371, "text": "Considering we want to compare countries, we will use a new column this time, one that lists the cumulative number of new cases over the past 14 days per 100,000 people in that country. Since the population of each country varies, using the number of cases per 100,000 people allows us to standardize the case counts based on the population. Let’s see how that looks." }, { "code": null, "e": 11188, "s": 10739, "text": "The little red hump (in the beginning) is China, with Italy in green, Spain in yellow, and the US in blue. As you can see, China was hit first although the overall impact was significantly lower than the other three countries (based on the numbers they reported at least). Sadly, the US still looks in pretty bad shape comparatively. Of these four countries, Spain was hit hardest by the first wave while the US and Italy appear similarly impacted." }, { "code": null, "e": 11649, "s": 11188, "text": "Unfortunately, the 2nd wave hit the US like a truck (in terms of cumulative cases), although we appear to be starting a downtrend (fingers crossed). Spain’s 2nd wave appears to still be ramping up. We’ll have to continue monitoring their data to see when they start flattening the curve. Italy, on the other hand, appears to have done an excellent job curbing the spread of COVID-19 after their first wave. There may be lessons we can learn from their success." }, { "code": null, "e": 12074, "s": 11649, "text": "This is just the beginning. We’ve only scratched the surface of what you can do with this data. I hope you take what we covered here and run with it! Let it be a springboard for your own discovery. You no longer need to rely on snippets from the media, or other data scientists, to stay on top of the COVID-19 data and track trends. Let me know in the comments what you do with the data, and share with us what you discover!" }, { "code": null, "e": 12182, "s": 12074, "text": "✍️ Subscribe to get my newest articles, featured in publications like The Startup & Towards Data Science ➡️" }, { "code": null, "e": 12330, "s": 12182, "text": "[1] R, “R: The R Project for Statistical Computing” r-project.org, 2020. [Online]. Available: https://www.r-project.org. [Accessed: Aug. 10, 2020]." }, { "code": null, "e": 12472, "s": 12330, "text": "[2] R Studio, “R Studio IDE Desktop” rstudio.com, 2020. [Online]. Available: https://rstudio.com/products/rstudio. [Accessed: Aug. 10, 2020]." }, { "code": null, "e": 12695, "s": 12472, "text": "[3] lubridate package | R Documentation, “Make Dealing with Dates a Little Easier” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/lubridate/versions/1.7.9. [Accessed: Aug. 10, 2020]." }, { "code": null, "e": 12918, "s": 12695, "text": "[4] tidyverse package | R Documentation, “Easily Install and Load the ‘Tidyverse’” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/tidyverse/versions/1.3.0. [Accessed: Aug. 10, 2020]." }, { "code": null, "e": 13124, "s": 12918, "text": "[5] dplyr package | R Documentation, “A Grammar of Data Manipulation” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/dplyr/versions/0.7.8. [Accessed: Aug. 10, 2020]." }, { "code": null, "e": 13368, "s": 13124, "text": "[6] ggplot2 package | R Documentation, “Create Elegant Data Visualisations Using the Grammar of Graphics” rdocumentation.org, 2020. [Online]. Available: https://www.rdocumentation.org/packages/ggplot2/versions/3.3.2. [Accessed: Aug. 10, 2020]." } ]
Java String regionMatches() Method with Examples - GeeksforGeeks
10 Dec, 2021 The regionMatches() method of the String class has two variants that can be used to test if two string regions are matching or equal. There are two variants of this method, i.e., one is case sensitive test method, and the other ignores the case-sensitive method. Syntax: 1. Case sensitive test method: public boolean regionMatches(int toffset, String other, int ooffset, int len) 2. It has the option to consider or ignore the case method: public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Parameters: ignoreCase: if true, ignore the case when comparing characters. toffset: the starting offset of the subregion in this string. other: the string argument being compared. ooffset: the starting offset of the subregion in the string argument. len: the number of characters to compare. Return Value: A substring of the String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true Example 1: Java // Java Program to find if substrings// or regions of two strings are equal import java.io.*; class CheckIfRegionsEqual { public static void main(String args[]) { // create three string objects String str1 = new String("Welcome to Geeksforgeeks.com"); String str2 = new String("Geeksforgeeks"); String str3 = new String("GEEKSFORGEEKS"); // Comparing str1 and str2 System.out.print( "Result of Comparing of String 1 and String 2: "); System.out.println( str1.regionMatches(11, str2, 0, 13)); // Comparing str1 and str3 System.out.print( "Result of Comparing of String 1 and String 3: "); System.out.println( str1.regionMatches(11, str3, 0, 13)); // Comparing str2 and str3 System.out.print( "Result of Comparing of String 2 and String 3: "); System.out.println( str2.regionMatches(0, str3, 0, 13)); }} Result of Comparing of String 1 and String 2: true Result of Comparing of String 1 and String 3: false Result of Comparing of String 2 and String 3: false Example 2: Java // Java Program to find if substrings// or regions of two strings are equal import java.io.*; class CheckIfRegionsEqual { public static void main(String args[]) { // create three string objects String str1 = new String("Abhishek Rout"); String str2 = new String("abhishek"); String str3 = new String("ABHISHEK"); // Comparing str1 and str2 substrings System.out.print( "Result of comparing String 1 and String 2 : "); System.out.println( str1.regionMatches(true, 0, str2, 0, 8)); // Comparing str1 and str3 substrings System.out.print( "Result of comparing String 1 and String 3 : "); System.out.println( str1.regionMatches(false, 0, str3, 0, 8)); // Comparing str2 and str3 substrings System.out.print( "Result of comparing String 2 and String 3 : "); System.out.println( str2.regionMatches(true, 0, str3, 0, 8)); }} Result of comparing String 1 and String 2 : true Result of comparing String 1 and String 3 : false Result of comparing String 2 and String 3 : true Note: The method returns false if at least one of these is true, toffset is negative. ooffset is negative. toffset+len is greater than the length of this String object. ooffset+len is greater than the length of the other argument. ignoreCase is false, and there is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k) ignoreCase is true, and there is some nonnegative integer k less than len such that: Character.toLowerCase(Character.toUpperCase(this.charAt(toffset+k))) != Character.toLowerCase(Character.toUpperCase(other.charAt(ooffset+k))) nishkarshgandhi Java-String-Programs Java-Strings Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n10 Dec, 2021" }, { "code": null, "e": 23820, "s": 23557, "text": "The regionMatches() method of the String class has two variants that can be used to test if two string regions are matching or equal. There are two variants of this method, i.e., one is case sensitive test method, and the other ignores the case-sensitive method." }, { "code": null, "e": 23828, "s": 23820, "text": "Syntax:" }, { "code": null, "e": 23859, "s": 23828, "text": "1. Case sensitive test method:" }, { "code": null, "e": 23937, "s": 23859, "text": "public boolean regionMatches(int toffset, String other, int ooffset, int len)" }, { "code": null, "e": 23997, "s": 23937, "text": "2. It has the option to consider or ignore the case method:" }, { "code": null, "e": 24095, "s": 23997, "text": "public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)" }, { "code": null, "e": 24107, "s": 24095, "text": "Parameters:" }, { "code": null, "e": 24171, "s": 24107, "text": "ignoreCase: if true, ignore the case when comparing characters." }, { "code": null, "e": 24233, "s": 24171, "text": "toffset: the starting offset of the subregion in this string." }, { "code": null, "e": 24276, "s": 24233, "text": "other: the string argument being compared." }, { "code": null, "e": 24346, "s": 24276, "text": "ooffset: the starting offset of the subregion in the string argument." }, { "code": null, "e": 24388, "s": 24346, "text": "len: the number of characters to compare." }, { "code": null, "e": 24402, "s": 24388, "text": "Return Value:" }, { "code": null, "e": 24872, "s": 24402, "text": "A substring of the String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true" }, { "code": null, "e": 24883, "s": 24872, "text": "Example 1:" }, { "code": null, "e": 24888, "s": 24883, "text": "Java" }, { "code": "// Java Program to find if substrings// or regions of two strings are equal import java.io.*; class CheckIfRegionsEqual { public static void main(String args[]) { // create three string objects String str1 = new String(\"Welcome to Geeksforgeeks.com\"); String str2 = new String(\"Geeksforgeeks\"); String str3 = new String(\"GEEKSFORGEEKS\"); // Comparing str1 and str2 System.out.print( \"Result of Comparing of String 1 and String 2: \"); System.out.println( str1.regionMatches(11, str2, 0, 13)); // Comparing str1 and str3 System.out.print( \"Result of Comparing of String 1 and String 3: \"); System.out.println( str1.regionMatches(11, str3, 0, 13)); // Comparing str2 and str3 System.out.print( \"Result of Comparing of String 2 and String 3: \"); System.out.println( str2.regionMatches(0, str3, 0, 13)); }}", "e": 25871, "s": 24888, "text": null }, { "code": null, "e": 26026, "s": 25871, "text": "Result of Comparing of String 1 and String 2: true\nResult of Comparing of String 1 and String 3: false\nResult of Comparing of String 2 and String 3: false" }, { "code": null, "e": 26037, "s": 26026, "text": "Example 2:" }, { "code": null, "e": 26042, "s": 26037, "text": "Java" }, { "code": "// Java Program to find if substrings// or regions of two strings are equal import java.io.*; class CheckIfRegionsEqual { public static void main(String args[]) { // create three string objects String str1 = new String(\"Abhishek Rout\"); String str2 = new String(\"abhishek\"); String str3 = new String(\"ABHISHEK\"); // Comparing str1 and str2 substrings System.out.print( \"Result of comparing String 1 and String 2 : \"); System.out.println( str1.regionMatches(true, 0, str2, 0, 8)); // Comparing str1 and str3 substrings System.out.print( \"Result of comparing String 1 and String 3 : \"); System.out.println( str1.regionMatches(false, 0, str3, 0, 8)); // Comparing str2 and str3 substrings System.out.print( \"Result of comparing String 2 and String 3 : \"); System.out.println( str2.regionMatches(true, 0, str3, 0, 8)); }}", "e": 27030, "s": 26042, "text": null }, { "code": null, "e": 27178, "s": 27030, "text": "Result of comparing String 1 and String 2 : true\nResult of comparing String 1 and String 3 : false\nResult of comparing String 2 and String 3 : true" }, { "code": null, "e": 27243, "s": 27178, "text": "Note: The method returns false if at least one of these is true," }, { "code": null, "e": 27264, "s": 27243, "text": "toffset is negative." }, { "code": null, "e": 27285, "s": 27264, "text": "ooffset is negative." }, { "code": null, "e": 27347, "s": 27285, "text": "toffset+len is greater than the length of this String object." }, { "code": null, "e": 27409, "s": 27347, "text": "ooffset+len is greater than the length of the other argument." }, { "code": null, "e": 27495, "s": 27409, "text": "ignoreCase is false, and there is some nonnegative integer k less than len such that:" }, { "code": null, "e": 27546, "s": 27495, "text": " this.charAt(toffset+k) != other.charAt(ooffset+k)" }, { "code": null, "e": 27631, "s": 27546, "text": "ignoreCase is true, and there is some nonnegative integer k less than len such that:" }, { "code": null, "e": 27780, "s": 27631, "text": " Character.toLowerCase(Character.toUpperCase(this.charAt(toffset+k))) != \n Character.toLowerCase(Character.toUpperCase(other.charAt(ooffset+k)))" }, { "code": null, "e": 27796, "s": 27780, "text": "nishkarshgandhi" }, { "code": null, "e": 27817, "s": 27796, "text": "Java-String-Programs" }, { "code": null, "e": 27830, "s": 27817, "text": "Java-Strings" }, { "code": null, "e": 27835, "s": 27830, "text": "Java" }, { "code": null, "e": 27849, "s": 27835, "text": "Java Programs" }, { "code": null, "e": 27862, "s": 27849, "text": "Java-Strings" }, { "code": null, "e": 27867, "s": 27862, "text": "Java" }, { "code": null, "e": 27965, "s": 27867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27974, "s": 27965, "text": "Comments" }, { "code": null, "e": 27987, "s": 27974, "text": "Old Comments" }, { "code": null, "e": 28017, "s": 27987, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28032, "s": 28017, "text": "Stream In Java" }, { "code": null, "e": 28053, "s": 28032, "text": "Constructors in Java" }, { "code": null, "e": 28099, "s": 28053, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28118, "s": 28099, "text": "Exceptions in Java" }, { "code": null, "e": 28162, "s": 28118, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28188, "s": 28162, "text": "Java Programming Examples" }, { "code": null, "e": 28222, "s": 28188, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28269, "s": 28222, "text": "Implementing a Linked List in Java using Class" } ]
Variational Autoencoder Demystified With PyTorch Implementation. | by William Falcon | Towards Data Science
It’s likely that you’ve searched for VAE tutorials but have come away empty-handed. Either the tutorial uses MNIST instead of color images or the concepts are conflated and not explained clearly. You’re in luck! This tutorial covers all aspects of VAEs including the matching math and implementation on a realistic dataset of color images. The outline is as follows: Resources (github code, colab).ELBO definition (optional).ELBO, KL divergence explanation (optional).ELBO, reconstruction loss explanation (optional).PyTorch implementation Resources (github code, colab). ELBO definition (optional). ELBO, KL divergence explanation (optional). ELBO, reconstruction loss explanation (optional). PyTorch implementation Follow along with this colab. Code is also available on Github here (don’t forget to star!). For a production/research-ready implementation simply install pytorch-lightning-bolts pip install pytorch-lightning-bolts and import and use/subclass from pl_bolts.models.autoencoders import VAEmodel = VAE()trainer = Trainer()trainer.fit(model) In this section, we’ll discuss the VAE loss. If you don’t care for the math, feel free to skip this section! Distributions: First, let’s define a few things. Let p define a probability distribution. Let q define a probability distribution as well. These distributions could be any distribution you want like Normal, etc... In this tutorial, we don’t specify what these are to keep things easier to understand. So, when you see p, or q, just think of a blackbox that is a distribution. Don’t worry about what is in there. VAE loss: The loss function for the VAE is called the ELBO. The ELBO looks like this: The first term is the KL divergence. The second term is the reconstruction term. Confusion point 1 MSE: Most tutorials equate reconstruction with MSE. But this is misleading because MSE only works when you use certain distributions for p, q. Confusion point 2 KL divergence: Most other tutorials use p, q that are normal. If you assume p, q are Normal distributions, the KL term looks like this (in code): kl = torch.mean(-0.5 * torch.sum(1 + log_var - mu ** 2 - log_var.exp(), dim = 1), dim = 0) But in our equation, we DO NOT assume these are normal. We do this because it makes things much easier to understand and keeps the implementation general so you can use any distribution you want. Let’s break down each component of the loss to understand what each is doing. Let’s first look at the KL divergence term. The first part (min) says that we want to minimize this. Next to that, the E term stands for expectation under q. This means we draw a sample (z) from the q distribution. Notice that in this case, I used a Normal(0, 1) distribution for q. When we code the loss, we have to specify the distributions we want to use. Now that we have a sample, the next parts of the formula ask for two things: 1) the log probability of z under the q distribution, 2) the log probability of z under the p distribution. Notice that z has almost zero probability of having come from p. But has 6% probability of having come from q. If we visualize this it’s clear why: z has a value of 6.0110. If you look at the area of q where z is (ie: the probability), it’s clear that there is a non-zero chance it came from q. But, if you look at p, there’s basically a zero chance that it came from p. If we look back at this part of the loss You can see that we are minimizing the difference between these probabilities. So, to maximize the probability of z under p, we have to shift q closer to p, so that when we sample a new z from q, that value will have a much higher probability. Let’s verify this via code and now our new kl divergence is: Now, this z has a single dimension. But in the real world, we care about n-dimensional zs. To handle this in the implementation, we simply sum over the last dimension. The trick here is that when sampling from a univariate distribution (in this case Normal), if you sum across many of these distributions, it’s equivalent to using an n-dimensional distribution (n-dimensional Normal in this case). Here’s the kl divergence that is distribution agnostic in PyTorch. This generic form of the KL is called the monte-carlo approximation. This means we sample z many times and estimate the KL divergence. (in practice, these estimates are really good and with a batch size of 128 or more, the estimate is very accurate). The second term we’ll look at is the reconstruction term. In the KL explanation we used p(z), q(z|x). For this equation, we need to define a third distribution, P_rec(x|z). To avoid confusion we’ll use P_rec to differentiate. Tip: DO NOT confuse P_rec(x|z) and p(z). So, in this equation we again sample z from q. But now we use that z to calculate the probability of seeing the input x (ie: a color image in this case) given the z that we sampled. First we need to think of our images as having a distribution in image space. Imagine a very high dimensional distribution. For a color image that is 32x32 pixels, that means this distribution has (3x32x32 = 3072) dimensions. So, now we need a way to map the z vector (which is low dimensional) back into a super high dimensional distribution from which we can measure the probability of seeing this particular image. In VAEs, we use a decoder for that. Confusion point 3: Most tutorials show x_hat as an image. However, this is wrong. x_hat IS NOT an image. These are PARAMETERS for a distribution. But because these tutorials use MNIST, the output is already in the zero-one range and can be interpreted as an image. But with color images, this is not true. To finalize the calculation of this formula, we use x_hat to parametrize a likelihood distribution (in this case a normal again) so that we can measure the probability of the input (image) under this high dimensional distribution. ie: we are asking the same question: Given P_rec(x|z) and this image, what is the probability? Since the reconstruction term has a negative sign in front of it, we minimize it by maximizing the probability of this image under P_rec(x|z). Some things may not be obvious still from this explanation. First, each image will end up with its own q. The KL term will push all the qs towards the same p (called the prior). But if all the qs, collapse to p, then the network can cheat by just mapping everything to zero and thus the VAE will collapse. The reconstruction term, forces each q to be unique and spread out so that the image can be reconstructed correctly. This keeps all the qs from collapsing onto each other. As you can see, both terms provide a nice balance to each other. This is also why you may experience instability in training VAEs! Now that you understand the intuition behind the approach and math, let’s code up the VAE in PyTorch. For this implementation, I’ll use PyTorch Lightning which will keep the code short but still scalable. If you skipped the earlier sections, recall that we are now going to implement the following VAE loss: This equation has 3 distributions. Our code will be agnostic to the distributions, but we’ll use Normal for all of them. The first distribution: q(z|x) needs parameters which we generate via an encoder. The second distribution: p(z) is the prior which we will fix to a specific location (0,1). By fixing this distribution, the KL divergence term will force q(z|x) to move closer to p by updating the parameters. The optimization start out with two distributions like this (q, p). and over time, moves q closer to p (p is fixed as you saw, and q has learnable parameters). The third distribution: p(x|z) (usually called the reconstruction), will be used to measure the probability of seeing the image (input) given the z that was sampled. Think about this image as having 3072 dimensions (3 channels x 32 pixels x 32 pixels). So, we can now write a full class that implements this algorithm. What’s nice about Lightning is that all the hard logic is encapsulated in the training_step. This means everyone can know exactly what something is doing when it is written in Lightning by looking at the training_step. Data: The Lightning VAE is fully decoupled from the data! This means we can train on imagenet, or whatever you want. For speed and cost purposes, I’ll use cifar-10 (a much smaller image dataset). Lightning uses regular pytorch dataloaders. But it’s annoying to have to figure out transforms, and other settings to get the data in usable shape. For this, we’ll use the optional abstraction (Datamodule) which abstracts all this complexity from me. Now that we have the VAE and the data, we can train it on as many GPUs as I want. In this case, colab gives us just 1, so we’ll use that. And we’ll see training start... Even just after 18 epochs, I can look at the reconstruction. Even though we didn’t train for long, and used no fancy tricks like perceptual losses, we get something that kind of looks like samples from CIFAR-10. In the next post, I’ll cover the derivation of the ELBO! Remember to star the repo and share if this was useful
[ { "code": null, "e": 367, "s": 171, "text": "It’s likely that you’ve searched for VAE tutorials but have come away empty-handed. Either the tutorial uses MNIST instead of color images or the concepts are conflated and not explained clearly." }, { "code": null, "e": 383, "s": 367, "text": "You’re in luck!" }, { "code": null, "e": 511, "s": 383, "text": "This tutorial covers all aspects of VAEs including the matching math and implementation on a realistic dataset of color images." }, { "code": null, "e": 538, "s": 511, "text": "The outline is as follows:" }, { "code": null, "e": 711, "s": 538, "text": "Resources (github code, colab).ELBO definition (optional).ELBO, KL divergence explanation (optional).ELBO, reconstruction loss explanation (optional).PyTorch implementation" }, { "code": null, "e": 743, "s": 711, "text": "Resources (github code, colab)." }, { "code": null, "e": 771, "s": 743, "text": "ELBO definition (optional)." }, { "code": null, "e": 815, "s": 771, "text": "ELBO, KL divergence explanation (optional)." }, { "code": null, "e": 865, "s": 815, "text": "ELBO, reconstruction loss explanation (optional)." }, { "code": null, "e": 888, "s": 865, "text": "PyTorch implementation" }, { "code": null, "e": 918, "s": 888, "text": "Follow along with this colab." }, { "code": null, "e": 981, "s": 918, "text": "Code is also available on Github here (don’t forget to star!)." }, { "code": null, "e": 1067, "s": 981, "text": "For a production/research-ready implementation simply install pytorch-lightning-bolts" }, { "code": null, "e": 1103, "s": 1067, "text": "pip install pytorch-lightning-bolts" }, { "code": null, "e": 1131, "s": 1103, "text": "and import and use/subclass" }, { "code": null, "e": 1226, "s": 1131, "text": "from pl_bolts.models.autoencoders import VAEmodel = VAE()trainer = Trainer()trainer.fit(model)" }, { "code": null, "e": 1335, "s": 1226, "text": "In this section, we’ll discuss the VAE loss. If you don’t care for the math, feel free to skip this section!" }, { "code": null, "e": 1636, "s": 1335, "text": "Distributions: First, let’s define a few things. Let p define a probability distribution. Let q define a probability distribution as well. These distributions could be any distribution you want like Normal, etc... In this tutorial, we don’t specify what these are to keep things easier to understand." }, { "code": null, "e": 1747, "s": 1636, "text": "So, when you see p, or q, just think of a blackbox that is a distribution. Don’t worry about what is in there." }, { "code": null, "e": 1833, "s": 1747, "text": "VAE loss: The loss function for the VAE is called the ELBO. The ELBO looks like this:" }, { "code": null, "e": 1914, "s": 1833, "text": "The first term is the KL divergence. The second term is the reconstruction term." }, { "code": null, "e": 2075, "s": 1914, "text": "Confusion point 1 MSE: Most tutorials equate reconstruction with MSE. But this is misleading because MSE only works when you use certain distributions for p, q." }, { "code": null, "e": 2239, "s": 2075, "text": "Confusion point 2 KL divergence: Most other tutorials use p, q that are normal. If you assume p, q are Normal distributions, the KL term looks like this (in code):" }, { "code": null, "e": 2330, "s": 2239, "text": "kl = torch.mean(-0.5 * torch.sum(1 + log_var - mu ** 2 - log_var.exp(), dim = 1), dim = 0)" }, { "code": null, "e": 2526, "s": 2330, "text": "But in our equation, we DO NOT assume these are normal. We do this because it makes things much easier to understand and keeps the implementation general so you can use any distribution you want." }, { "code": null, "e": 2604, "s": 2526, "text": "Let’s break down each component of the loss to understand what each is doing." }, { "code": null, "e": 2648, "s": 2604, "text": "Let’s first look at the KL divergence term." }, { "code": null, "e": 2819, "s": 2648, "text": "The first part (min) says that we want to minimize this. Next to that, the E term stands for expectation under q. This means we draw a sample (z) from the q distribution." }, { "code": null, "e": 2963, "s": 2819, "text": "Notice that in this case, I used a Normal(0, 1) distribution for q. When we code the loss, we have to specify the distributions we want to use." }, { "code": null, "e": 3148, "s": 2963, "text": "Now that we have a sample, the next parts of the formula ask for two things: 1) the log probability of z under the q distribution, 2) the log probability of z under the p distribution." }, { "code": null, "e": 3296, "s": 3148, "text": "Notice that z has almost zero probability of having come from p. But has 6% probability of having come from q. If we visualize this it’s clear why:" }, { "code": null, "e": 3519, "s": 3296, "text": "z has a value of 6.0110. If you look at the area of q where z is (ie: the probability), it’s clear that there is a non-zero chance it came from q. But, if you look at p, there’s basically a zero chance that it came from p." }, { "code": null, "e": 3560, "s": 3519, "text": "If we look back at this part of the loss" }, { "code": null, "e": 3639, "s": 3560, "text": "You can see that we are minimizing the difference between these probabilities." }, { "code": null, "e": 3804, "s": 3639, "text": "So, to maximize the probability of z under p, we have to shift q closer to p, so that when we sample a new z from q, that value will have a much higher probability." }, { "code": null, "e": 3831, "s": 3804, "text": "Let’s verify this via code" }, { "code": null, "e": 3865, "s": 3831, "text": "and now our new kl divergence is:" }, { "code": null, "e": 4263, "s": 3865, "text": "Now, this z has a single dimension. But in the real world, we care about n-dimensional zs. To handle this in the implementation, we simply sum over the last dimension. The trick here is that when sampling from a univariate distribution (in this case Normal), if you sum across many of these distributions, it’s equivalent to using an n-dimensional distribution (n-dimensional Normal in this case)." }, { "code": null, "e": 4330, "s": 4263, "text": "Here’s the kl divergence that is distribution agnostic in PyTorch." }, { "code": null, "e": 4581, "s": 4330, "text": "This generic form of the KL is called the monte-carlo approximation. This means we sample z many times and estimate the KL divergence. (in practice, these estimates are really good and with a batch size of 128 or more, the estimate is very accurate)." }, { "code": null, "e": 4639, "s": 4581, "text": "The second term we’ll look at is the reconstruction term." }, { "code": null, "e": 4807, "s": 4639, "text": "In the KL explanation we used p(z), q(z|x). For this equation, we need to define a third distribution, P_rec(x|z). To avoid confusion we’ll use P_rec to differentiate." }, { "code": null, "e": 4848, "s": 4807, "text": "Tip: DO NOT confuse P_rec(x|z) and p(z)." }, { "code": null, "e": 5030, "s": 4848, "text": "So, in this equation we again sample z from q. But now we use that z to calculate the probability of seeing the input x (ie: a color image in this case) given the z that we sampled." }, { "code": null, "e": 5256, "s": 5030, "text": "First we need to think of our images as having a distribution in image space. Imagine a very high dimensional distribution. For a color image that is 32x32 pixels, that means this distribution has (3x32x32 = 3072) dimensions." }, { "code": null, "e": 5484, "s": 5256, "text": "So, now we need a way to map the z vector (which is low dimensional) back into a super high dimensional distribution from which we can measure the probability of seeing this particular image. In VAEs, we use a decoder for that." }, { "code": null, "e": 5790, "s": 5484, "text": "Confusion point 3: Most tutorials show x_hat as an image. However, this is wrong. x_hat IS NOT an image. These are PARAMETERS for a distribution. But because these tutorials use MNIST, the output is already in the zero-one range and can be interpreted as an image. But with color images, this is not true." }, { "code": null, "e": 6021, "s": 5790, "text": "To finalize the calculation of this formula, we use x_hat to parametrize a likelihood distribution (in this case a normal again) so that we can measure the probability of the input (image) under this high dimensional distribution." }, { "code": null, "e": 6116, "s": 6021, "text": "ie: we are asking the same question: Given P_rec(x|z) and this image, what is the probability?" }, { "code": null, "e": 6259, "s": 6116, "text": "Since the reconstruction term has a negative sign in front of it, we minimize it by maximizing the probability of this image under P_rec(x|z)." }, { "code": null, "e": 6565, "s": 6259, "text": "Some things may not be obvious still from this explanation. First, each image will end up with its own q. The KL term will push all the qs towards the same p (called the prior). But if all the qs, collapse to p, then the network can cheat by just mapping everything to zero and thus the VAE will collapse." }, { "code": null, "e": 6737, "s": 6565, "text": "The reconstruction term, forces each q to be unique and spread out so that the image can be reconstructed correctly. This keeps all the qs from collapsing onto each other." }, { "code": null, "e": 6868, "s": 6737, "text": "As you can see, both terms provide a nice balance to each other. This is also why you may experience instability in training VAEs!" }, { "code": null, "e": 7073, "s": 6868, "text": "Now that you understand the intuition behind the approach and math, let’s code up the VAE in PyTorch. For this implementation, I’ll use PyTorch Lightning which will keep the code short but still scalable." }, { "code": null, "e": 7176, "s": 7073, "text": "If you skipped the earlier sections, recall that we are now going to implement the following VAE loss:" }, { "code": null, "e": 7297, "s": 7176, "text": "This equation has 3 distributions. Our code will be agnostic to the distributions, but we’ll use Normal for all of them." }, { "code": null, "e": 7379, "s": 7297, "text": "The first distribution: q(z|x) needs parameters which we generate via an encoder." }, { "code": null, "e": 7588, "s": 7379, "text": "The second distribution: p(z) is the prior which we will fix to a specific location (0,1). By fixing this distribution, the KL divergence term will force q(z|x) to move closer to p by updating the parameters." }, { "code": null, "e": 7656, "s": 7588, "text": "The optimization start out with two distributions like this (q, p)." }, { "code": null, "e": 7748, "s": 7656, "text": "and over time, moves q closer to p (p is fixed as you saw, and q has learnable parameters)." }, { "code": null, "e": 7914, "s": 7748, "text": "The third distribution: p(x|z) (usually called the reconstruction), will be used to measure the probability of seeing the image (input) given the z that was sampled." }, { "code": null, "e": 8001, "s": 7914, "text": "Think about this image as having 3072 dimensions (3 channels x 32 pixels x 32 pixels)." }, { "code": null, "e": 8067, "s": 8001, "text": "So, we can now write a full class that implements this algorithm." }, { "code": null, "e": 8286, "s": 8067, "text": "What’s nice about Lightning is that all the hard logic is encapsulated in the training_step. This means everyone can know exactly what something is doing when it is written in Lightning by looking at the training_step." }, { "code": null, "e": 8482, "s": 8286, "text": "Data: The Lightning VAE is fully decoupled from the data! This means we can train on imagenet, or whatever you want. For speed and cost purposes, I’ll use cifar-10 (a much smaller image dataset)." }, { "code": null, "e": 8733, "s": 8482, "text": "Lightning uses regular pytorch dataloaders. But it’s annoying to have to figure out transforms, and other settings to get the data in usable shape. For this, we’ll use the optional abstraction (Datamodule) which abstracts all this complexity from me." }, { "code": null, "e": 8871, "s": 8733, "text": "Now that we have the VAE and the data, we can train it on as many GPUs as I want. In this case, colab gives us just 1, so we’ll use that." }, { "code": null, "e": 8903, "s": 8871, "text": "And we’ll see training start..." }, { "code": null, "e": 8964, "s": 8903, "text": "Even just after 18 epochs, I can look at the reconstruction." }, { "code": null, "e": 9115, "s": 8964, "text": "Even though we didn’t train for long, and used no fancy tricks like perceptual losses, we get something that kind of looks like samples from CIFAR-10." }, { "code": null, "e": 9172, "s": 9115, "text": "In the next post, I’ll cover the derivation of the ELBO!" } ]
Scrolling to element using Webdriver.
We can perform scrolling to an element using Selenium webdriver. This can be achieved in multiple ways. Selenium cannot handle scrolling directly. It takes the help of the Javascript Executor and Actions class to do scrolling action. First of all we have to identify the element up to which we have to scroll to with the help of any of the locators like class, id, name and so on. Next we shall take the help of the Javascript Executor to run the Javascript commands. The method executeScript is used to execute Javascript commands in Selenium. We have to use the scrollIntoView method in Javascript and pass true as an argument to the method. WebElement e = driver.findElement(By.name("name")); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", e); Code Implementation with Javascript Executor. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ScrollToElementJs{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement m=driver.findElement(By.xpath("//*[text()='Careers']")); // Javascript executor ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView (true);", m); Thread.sleep(200); driver.close(); } } With the Actions class, we shall use the moveToElement method and pass the webelement locator as an argument to the method. Code Implementation with Actions. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class ScrollToElementActions{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement m=driver.findElement(By.xpath("//*[text()='Careers']")); // moveToElement method with Actions class Actions act = new Actions(driver); act.moveToElement(m); act.perform(); driver.close(); } }
[ { "code": null, "e": 1296, "s": 1062, "text": "We can perform scrolling to an element using Selenium webdriver. This can be achieved in multiple ways. Selenium cannot handle scrolling directly. It takes the help of the Javascript Executor and Actions class to do scrolling action." }, { "code": null, "e": 1706, "s": 1296, "text": "First of all we have to identify the element up to which we have to scroll to with the help of any of the locators like class, id, name and so on. Next we shall take the help of the Javascript Executor to run the Javascript commands. The method executeScript is used to execute Javascript commands in Selenium. We have to use the scrollIntoView method in Javascript and pass true as an argument to the method." }, { "code": null, "e": 1844, "s": 1706, "text": "WebElement e = driver.findElement(By.name(\"name\"));\n((JavascriptExecutor) driver).executeScript(\"arguments[0].scrollIntoView(true);\", e);" }, { "code": null, "e": 1890, "s": 1844, "text": "Code Implementation with Javascript Executor." }, { "code": null, "e": 2768, "s": 1890, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ScrollToElementJs{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // identify element\n WebElement m=driver.findElement(By.xpath(\"//*[text()='Careers']\"));\n // Javascript executor\n ((JavascriptExecutor)driver).executeScript(\"arguments[0].scrollIntoView (true);\", m);\n Thread.sleep(200);\n driver.close();\n }\n}" }, { "code": null, "e": 2892, "s": 2768, "text": "With the Actions class, we shall use the moveToElement method and pass the webelement locator as an argument to the method." }, { "code": null, "e": 2926, "s": 2892, "text": "Code Implementation with Actions." }, { "code": null, "e": 3851, "s": 2926, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.interactions.Action;\nimport org.openqa.selenium.interactions.Actions;\npublic class ScrollToElementActions{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n WebElement m=driver.findElement(By.xpath(\"//*[text()='Careers']\"));\n // moveToElement method with Actions class\n Actions act = new Actions(driver);\n act.moveToElement(m);\n act.perform();\n driver.close();\n }\n}" } ]
Detect an object with OpenCV-Python - GeeksforGeeks
18 May, 2020 OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. This article focuses on detecting objects. Note: For more information, refer to Introduction to OpenCV. Object Detection is a computer technology related to computer vision, image processing, and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades. Haar Cascade classifiers are an effective way for object detection. This method was proposed by Paul Viola and Michael Jones in their paper Rapid Object Detection using a Boosted Cascade of Simple Features. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier. Positive images – These images contain the images which we want our classifier to identify. Negative Images – Images of everything else, which do not contain the object we want to detect.Requirements. Steps to download the requirements below: Run The following command in the terminal to install opencv.pip install opencv-python pip install opencv-python Run the following command to in the terminal install the matplotlib.pip install matplotlib pip install matplotlib To download the haar cascade file and image used in the below code as a zip file click here. Note: Put the XML file and the PNG image in the same folder as your Python script. Image used: Opening an image import cv2from matplotlib import pyplot as plt # Opening imageimg = cv2.imread("image.jpg") # OpenCV opens images as BRG # but we want it as RGB and # we also need a grayscale # versionimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Creates the environment # of the picture and shows itplt.subplot(1, 1, 1)plt.imshow(img_rgb)plt.show() Output: Recognition We will use the detectMultiScale() function of OpenCV to recognize big signs as well as small ones: # Use minSize because for not # bothering with extra-small # dots that would look like STOP signsfound = stop_data.detectMultiScale(img_gray, minSize =(20, 20)) # Don't do anything if there's # no signamount_found = len(found) if amount_found != 0: # There may be more than one # sign in the image for (x, y, width, height) in found: # We draw a green rectangle around # every recognized sign cv2.rectangle(img_rgb, (x, y), (x + height, y + width), (0, 255, 0), 5) Here is the full script for lazy devs: import cv2from matplotlib import pyplot as plt # Opening imageimg = cv2.imread("image.jpg") # OpenCV opens images as BRG # but we want it as RGB We'll # also need a grayscale versionimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Use minSize because for not # bothering with extra-small # dots that would look like STOP signsstop_data = cv2.CascadeClassifier('stop_data.xml') found = stop_data.detectMultiScale(img_gray, minSize =(20, 20)) # Don't do anything if there's # no signamount_found = len(found) if amount_found != 0: # There may be more than one # sign in the image for (x, y, width, height) in found: # We draw a green rectangle around # every recognized sign cv2.rectangle(img_rgb, (x, y), (x + height, y + width), (0, 255, 0), 5) # Creates the environment of # the picture and shows itplt.subplot(1, 1, 1)plt.imshow(img_rgb)plt.show() Output : priyankamore OpenCV python Python python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25949, "s": 25921, "text": "\n18 May, 2020" }, { "code": null, "e": 26299, "s": 25949, "text": "OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. This article focuses on detecting objects." }, { "code": null, "e": 26360, "s": 26299, "text": "Note: For more information, refer to Introduction to OpenCV." }, { "code": null, "e": 26619, "s": 26360, "text": "Object Detection is a computer technology related to computer vision, image processing, and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades." }, { "code": null, "e": 26954, "s": 26619, "text": "Haar Cascade classifiers are an effective way for object detection. This method was proposed by Paul Viola and Michael Jones in their paper Rapid Object Detection using a Boosted Cascade of Simple Features. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier." }, { "code": null, "e": 27046, "s": 26954, "text": "Positive images – These images contain the images which we want our classifier to identify." }, { "code": null, "e": 27155, "s": 27046, "text": "Negative Images – Images of everything else, which do not contain the object we want to detect.Requirements." }, { "code": null, "e": 27197, "s": 27155, "text": "Steps to download the requirements below:" }, { "code": null, "e": 27284, "s": 27197, "text": "Run The following command in the terminal to install opencv.pip install opencv-python\n" }, { "code": null, "e": 27311, "s": 27284, "text": "pip install opencv-python\n" }, { "code": null, "e": 27403, "s": 27311, "text": "Run the following command to in the terminal install the matplotlib.pip install matplotlib\n" }, { "code": null, "e": 27427, "s": 27403, "text": "pip install matplotlib\n" }, { "code": null, "e": 27520, "s": 27427, "text": "To download the haar cascade file and image used in the below code as a zip file click here." }, { "code": null, "e": 27603, "s": 27520, "text": "Note: Put the XML file and the PNG image in the same folder as your Python script." }, { "code": null, "e": 27615, "s": 27603, "text": "Image used:" }, { "code": null, "e": 27632, "s": 27615, "text": "Opening an image" }, { "code": "import cv2from matplotlib import pyplot as plt # Opening imageimg = cv2.imread(\"image.jpg\") # OpenCV opens images as BRG # but we want it as RGB and # we also need a grayscale # versionimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Creates the environment # of the picture and shows itplt.subplot(1, 1, 1)plt.imshow(img_rgb)plt.show()", "e": 28022, "s": 27632, "text": null }, { "code": null, "e": 28030, "s": 28022, "text": "Output:" }, { "code": null, "e": 28042, "s": 28030, "text": "Recognition" }, { "code": null, "e": 28142, "s": 28042, "text": "We will use the detectMultiScale() function of OpenCV to recognize big signs as well as small ones:" }, { "code": "# Use minSize because for not # bothering with extra-small # dots that would look like STOP signsfound = stop_data.detectMultiScale(img_gray, minSize =(20, 20)) # Don't do anything if there's # no signamount_found = len(found) if amount_found != 0: # There may be more than one # sign in the image for (x, y, width, height) in found: # We draw a green rectangle around # every recognized sign cv2.rectangle(img_rgb, (x, y), (x + height, y + width), (0, 255, 0), 5)", "e": 28736, "s": 28142, "text": null }, { "code": null, "e": 28775, "s": 28736, "text": "Here is the full script for lazy devs:" }, { "code": "import cv2from matplotlib import pyplot as plt # Opening imageimg = cv2.imread(\"image.jpg\") # OpenCV opens images as BRG # but we want it as RGB We'll # also need a grayscale versionimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Use minSize because for not # bothering with extra-small # dots that would look like STOP signsstop_data = cv2.CascadeClassifier('stop_data.xml') found = stop_data.detectMultiScale(img_gray, minSize =(20, 20)) # Don't do anything if there's # no signamount_found = len(found) if amount_found != 0: # There may be more than one # sign in the image for (x, y, width, height) in found: # We draw a green rectangle around # every recognized sign cv2.rectangle(img_rgb, (x, y), (x + height, y + width), (0, 255, 0), 5) # Creates the environment of # the picture and shows itplt.subplot(1, 1, 1)plt.imshow(img_rgb)plt.show()", "e": 29815, "s": 28775, "text": null }, { "code": null, "e": 29824, "s": 29815, "text": "Output :" }, { "code": null, "e": 29837, "s": 29824, "text": "priyankamore" }, { "code": null, "e": 29844, "s": 29837, "text": "OpenCV" }, { "code": null, "e": 29851, "s": 29844, "text": "python" }, { "code": null, "e": 29858, "s": 29851, "text": "Python" }, { "code": null, "e": 29865, "s": 29858, "text": "python" }, { "code": null, "e": 29963, "s": 29865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29981, "s": 29963, "text": "Python Dictionary" }, { "code": null, "e": 30016, "s": 29981, "text": "Read a file line by line in Python" }, { "code": null, "e": 30048, "s": 30016, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30070, "s": 30048, "text": "Enumerate() in Python" }, { "code": null, "e": 30112, "s": 30070, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30142, "s": 30112, "text": "Iterate over a list in Python" }, { "code": null, "e": 30168, "s": 30142, "text": "Python String | replace()" }, { "code": null, "e": 30212, "s": 30168, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30241, "s": 30212, "text": "*args and **kwargs in Python" } ]
Get a list of a specified column of a Pandas DataFrame - GeeksforGeeks
28 Jul, 2020 In this article, we will discuss how to get a list of specified column of a Pandas Dataframe. First, we will read a csv file into a pandas dataframe. Note: To get the CSV file used click here.Example: Python3 # importing pandas module import pandas as pd # making data frame from csvdata = pd.read_csv("nba.csv") # calling head() method df = data.head(5) # displaying data df Output: Let’s see how to get a list of a specified column of a Pandas DataFrame:We will convert the column “Name” into a list using three different ways.1. Using Series.tolist()From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series.to_list() provided by the Series class to convert the series object and return a list. Python3 # importing pandas moduleimport pandas as pd # making data frame from csvdata = pd.read_csv("nba.csv")df = data.head(5) # Converting a specific Dataframe # column to list using Series.tolist()Name_list = df["Name"].tolist() print("Converting name to list:") # displaying listName_list Output: Let’s break it down and look at the types Python3 # column 'Name' as series objectprint(type(df["Name"])) # Convert series object to a listprint(type(df["Name"].values.tolist() Output: 2. Using numpy.ndarray.tolist()From the dataframe we select the column “Name” using a [] operator that returns a Series object and uses Series.Values to get a NumPy array from the series object. Next, we will use the function tolist() provided by NumPy array to convert it to a list. Python3 # importing pandas moduleimport pandas as pd # making data frame from csvdata = pd.read_csv("nba.csv")df = data.head(5) # Converting a specific Dataframe column# to list using numpy.ndarray.tolist()Name_list = df["Name"].values.tolist() print("Converting name to list:") # displaying listName_list Output: Similarly, breaking it down Python3 # Select a column from dataframe # as series and get a numpy arrayprint(type(df["Name"].values)) # Convert numpy array to a listprint(type(df["Name"].values.tolist() Output: 3. Using Python list() function You can also use the Python list() function with an optional iterable parameter to convert a column into a list. Python3 # importing pandas moduleimport pandas as pd # making data frame from csvdata = pd.read_csv("nba.csv")df = data.head(5) # Converting a specific Dataframe# column to list using list()# function in PythonName_List = list(df["Name"]) print("Converting name to list:") # displaying listName_List Output: Converting index column to list Index column can be converted to list, by calling pandas.DataFrame.index which returns the index column as an array and then calling index_column.tolist() which converts index_column into a list. Python3 # Converting index column to listindex_list = df.index.tolist() print("Converting index to list:") # display index as listindex_list Output: pandas-dataframe-program Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23926, "s": 23898, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24077, "s": 23926, "text": "In this article, we will discuss how to get a list of specified column of a Pandas Dataframe. First, we will read a csv file into a pandas dataframe. " }, { "code": null, "e": 24128, "s": 24077, "text": "Note: To get the CSV file used click here.Example:" }, { "code": null, "e": 24136, "s": 24128, "text": "Python3" }, { "code": "# importing pandas module import pandas as pd # making data frame from csvdata = pd.read_csv(\"nba.csv\") # calling head() method df = data.head(5) # displaying data df", "e": 24316, "s": 24136, "text": null }, { "code": null, "e": 24324, "s": 24316, "text": "Output:" }, { "code": null, "e": 24717, "s": 24324, "text": "Let’s see how to get a list of a specified column of a Pandas DataFrame:We will convert the column “Name” into a list using three different ways.1. Using Series.tolist()From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series.to_list() provided by the Series class to convert the series object and return a list. " }, { "code": null, "e": 24725, "s": 24717, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csvdata = pd.read_csv(\"nba.csv\")df = data.head(5) # Converting a specific Dataframe # column to list using Series.tolist()Name_list = df[\"Name\"].tolist() print(\"Converting name to list:\") # displaying listName_list", "e": 25014, "s": 24725, "text": null }, { "code": null, "e": 25022, "s": 25014, "text": "Output:" }, { "code": null, "e": 25066, "s": 25022, "text": "Let’s break it down and look at the types " }, { "code": null, "e": 25074, "s": 25066, "text": "Python3" }, { "code": "# column 'Name' as series objectprint(type(df[\"Name\"])) # Convert series object to a listprint(type(df[\"Name\"].values.tolist()", "e": 25202, "s": 25074, "text": null }, { "code": null, "e": 25210, "s": 25202, "text": "Output:" }, { "code": null, "e": 25495, "s": 25210, "text": "2. Using numpy.ndarray.tolist()From the dataframe we select the column “Name” using a [] operator that returns a Series object and uses Series.Values to get a NumPy array from the series object. Next, we will use the function tolist() provided by NumPy array to convert it to a list. " }, { "code": null, "e": 25503, "s": 25495, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csvdata = pd.read_csv(\"nba.csv\")df = data.head(5) # Converting a specific Dataframe column# to list using numpy.ndarray.tolist()Name_list = df[\"Name\"].values.tolist() print(\"Converting name to list:\") # displaying listName_list", "e": 25805, "s": 25503, "text": null }, { "code": null, "e": 25813, "s": 25805, "text": "Output:" }, { "code": null, "e": 25843, "s": 25813, "text": "Similarly, breaking it down " }, { "code": null, "e": 25851, "s": 25843, "text": "Python3" }, { "code": "# Select a column from dataframe # as series and get a numpy arrayprint(type(df[\"Name\"].values)) # Convert numpy array to a listprint(type(df[\"Name\"].values.tolist()", "e": 26018, "s": 25851, "text": null }, { "code": null, "e": 26026, "s": 26018, "text": "Output:" }, { "code": null, "e": 26172, "s": 26026, "text": "3. Using Python list() function You can also use the Python list() function with an optional iterable parameter to convert a column into a list. " }, { "code": null, "e": 26180, "s": 26172, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csvdata = pd.read_csv(\"nba.csv\")df = data.head(5) # Converting a specific Dataframe# column to list using list()# function in PythonName_List = list(df[\"Name\"]) print(\"Converting name to list:\") # displaying listName_List", "e": 26476, "s": 26180, "text": null }, { "code": null, "e": 26484, "s": 26476, "text": "Output:" }, { "code": null, "e": 26714, "s": 26484, "text": "Converting index column to list Index column can be converted to list, by calling pandas.DataFrame.index which returns the index column as an array and then calling index_column.tolist() which converts index_column into a list. " }, { "code": null, "e": 26722, "s": 26714, "text": "Python3" }, { "code": "# Converting index column to listindex_list = df.index.tolist() print(\"Converting index to list:\") # display index as listindex_list", "e": 26857, "s": 26722, "text": null }, { "code": null, "e": 26865, "s": 26857, "text": "Output:" }, { "code": null, "e": 26890, "s": 26865, "text": "pandas-dataframe-program" }, { "code": null, "e": 26914, "s": 26890, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26937, "s": 26914, "text": "Python Pandas-exercise" }, { "code": null, "e": 26951, "s": 26937, "text": "Python-pandas" }, { "code": null, "e": 26958, "s": 26951, "text": "Python" }, { "code": null, "e": 27056, "s": 26958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27065, "s": 27056, "text": "Comments" }, { "code": null, "e": 27078, "s": 27065, "text": "Old Comments" }, { "code": null, "e": 27110, "s": 27078, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27166, "s": 27110, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27208, "s": 27166, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27250, "s": 27208, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27286, "s": 27250, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27308, "s": 27286, "text": "Defaultdict in Python" }, { "code": null, "e": 27347, "s": 27308, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27374, "s": 27347, "text": "Python Classes and Objects" }, { "code": null, "e": 27405, "s": 27374, "text": "Python | os.path.join() method" } ]
What is the difference between class and typeof function in R?
The class function in R helps us to understand the type of object, for example the output of class for a data frame is integer and the typeof of the same object is list because data frames are stored as list in the memory but they are represented as a data frame. Check out the below examples with multiple type of objects to understand the differences. Live Demo x1<-rpois(20,2) typeof(x1) [1] "integer" class(x1) [1] "integer" df1<-data.frame(x1) df1 x1 1 1 2 4 3 1 4 0 5 2 6 2 7 4 8 2 9 3 10 4 11 1 12 4 13 0 14 5 15 2 16 2 17 0 18 4 19 3 20 3 typeof(df1) [1] "list" class(x1) [1] "integer" Live Demo M<-matrix(rnorm(40),ncol=2) M [,1] [,2] [1,] 2.02437789 -0.9161853 [2,] -0.60108978 -0.8972007 [3,] 1.27916953 0.1017923 [4,] 1.06998017 1.4839931 [5,] 0.22298522 0.6160919 [6,] -0.29346341 -0.3975116 [7,] 2.07012097 -0.7900820 [8,] 0.36719470 -0.1100298 [9,] -0.69522122 -1.9198172 [10,] 2.07822428 0.2517532 [11,] -1.56267422 1.8295022 [12,] -1.07488221 1.2666054 [13,] -0.79381494 -1.0993693 [14,] -0.16027224 -1.1814177 [15,] 0.67561791 0.7309281 [16,] -1.40912018 -0.3307749 [17,] -0.77769513 0.5527600 [18,] 0.47050704 0.1075593 [19,] -0.46616151 -0.5079660 [20,] -0.01944371 0.1553333 typeof(M) [1] "double" class(M) [1] "matrix" "array"
[ { "code": null, "e": 1416, "s": 1062, "text": "The class function in R helps us to understand the type of object, for example the output of class for a data frame is integer and the typeof of the same object is list because data frames are stored as list in the memory but they are represented as a data frame. Check out the below examples with multiple type of objects to understand the differences." }, { "code": null, "e": 1427, "s": 1416, "text": " Live Demo" }, { "code": null, "e": 1454, "s": 1427, "text": "x1<-rpois(20,2)\ntypeof(x1)" }, { "code": null, "e": 1468, "s": 1454, "text": "[1] \"integer\"" }, { "code": null, "e": 1478, "s": 1468, "text": "class(x1)" }, { "code": null, "e": 1492, "s": 1478, "text": "[1] \"integer\"" }, { "code": null, "e": 1516, "s": 1492, "text": "df1<-data.frame(x1)\ndf1" }, { "code": null, "e": 1622, "s": 1516, "text": " x1\n1 1\n2 4\n3 1\n4 0\n5 2\n6 2\n7 4\n8 2\n9 3\n10 4\n11 1\n12 4\n13 0\n14 5\n15 2\n16 2\n17 0\n18 4\n19 3\n20 3" }, { "code": null, "e": 1634, "s": 1622, "text": "typeof(df1)" }, { "code": null, "e": 1645, "s": 1634, "text": "[1] \"list\"" }, { "code": null, "e": 1655, "s": 1645, "text": "class(x1)" }, { "code": null, "e": 1669, "s": 1655, "text": "[1] \"integer\"" }, { "code": null, "e": 1680, "s": 1669, "text": " Live Demo" }, { "code": null, "e": 1710, "s": 1680, "text": "M<-matrix(rnorm(40),ncol=2)\nM" }, { "code": null, "e": 2337, "s": 1710, "text": " [,1] [,2]\n[1,] 2.02437789 -0.9161853\n[2,] -0.60108978 -0.8972007\n[3,] 1.27916953 0.1017923\n[4,] 1.06998017 1.4839931\n[5,] 0.22298522 0.6160919\n[6,] -0.29346341 -0.3975116\n[7,] 2.07012097 -0.7900820\n[8,] 0.36719470 -0.1100298\n[9,] -0.69522122 -1.9198172\n[10,] 2.07822428 0.2517532\n[11,] -1.56267422 1.8295022\n[12,] -1.07488221 1.2666054\n[13,] -0.79381494 -1.0993693\n[14,] -0.16027224 -1.1814177\n[15,] 0.67561791 0.7309281\n[16,] -1.40912018 -0.3307749\n[17,] -0.77769513 0.5527600\n[18,] 0.47050704 0.1075593\n[19,] -0.46616151 -0.5079660\n[20,] -0.01944371 0.1553333" }, { "code": null, "e": 2347, "s": 2337, "text": "typeof(M)" }, { "code": null, "e": 2360, "s": 2347, "text": "[1] \"double\"" }, { "code": null, "e": 2369, "s": 2360, "text": "class(M)" }, { "code": null, "e": 2390, "s": 2369, "text": "[1] \"matrix\" \"array\"" } ]
Workflow Tools for ML Pipelines. Chapter 5 excerpt of “Data Science in... | by Ben Weber | Towards Data Science
Airflow is becoming the industry standard for authoring data engineering and model pipeline workflows. This chapter of my book explores the process of taking a simple pipeline that runs on a single EC2 instance to a fully-managed Kubernetes ecosystem responsible for scheduling tasks. This posts omits the sections on the fully-managed solutions with GKE and Cloud Composer. leanpub.com Model pipelines are usually part of a broader data platform that provides data sources, such as lakes and warehouses, and data stores, such as an application database. When building a pipeline, it’s useful to be able to schedule a task to run, ensure that any dependencies for the pipeline have already completed, and to backfill historic data if needed. While it’s possible to perform these types of tasks manually, there are a variety of tools that have been developed to improve the management of data science workflows. In this chapter, we’ll explore a batch model pipeline that performs a sequence of tasks in order to train and store results for a propensity model. This is a different type of task than the deployments we’ve explored so far, which have focused on serving real-time model predictions as a web endpoint. In a batch process, you perform a set of operations that store model results that are later served by a different application. For example, a batch model pipeline may predict which users in a game are likely to churn, and a game server fetches predictions for each user that starts a session and provides personalized offers. When building batch model pipelines for production systems, it’s important to make sure that issues with the pipeline are quickly resolved. For example, if the model pipeline is unable to fetch the most recent data for a set of users due to an upstream failure with a database, it’s useful to have a system in place that can send alerts to the team that owns the pipeline and that can rerun portions of the model pipeline in order to resolve any issues with the prerequisite data or model outputs. Workflow tools provide a solution for managing these types of problems in model pipelines. With a workflow tool, you specify the operations that need to be completed, identify dependencies between the operations, and then schedule the operations to be performed by the tool. A workflow tool is responsible for running tasks, provisioning resources, and monitoring the status of tasks. There’s a number of open source tools for building workflows including AirFlow, Luigi, MLflow, and Pentaho Kettle. We’ll focus on Airflow, because it is being widely adopted across companies and cloud platforms and are also providing fully-managed versions of Airflow. In this chapter, we’ll build a batch model pipeline that runs as a Docker container. Next, we’ll schedule the task to run on an EC2 instance using cron, and then explore a managed version of cron using Kubernetes. In the third section, we’ll use Airflow to define a graph of operations to perform in order to run our model pipeline, and explore a cloud offering of Airflow. A common workflow for batch model pipelines is to extract data from a data lake or data warehouse, train a model on historic user behavior, predict future user behavior for more recent data, and then save the results to a data warehouse or application database. In the gaming industry, this is a workflow I’ve seen used for building likelihood to purchase and likelihood to churn models, where the game servers use these predictions to provide different treatments to users based on the model predictions. Usually libraries like sklearn are used to develop models, and languages such as PySpark are used to scale up to the full player base. It is typical for model pipelines to require other ETLs to run in a data platform before the pipeline can run on the most recent data. For example, there may be an upstream step in the data platform that translates json strings into schematized events that are used as input for a model. In this situation, it might be necessary to rerun the pipeline on a day that issues occurred with the json transformation process. For this section, we’ll avoid this complication by using a static input data source, but the tools that we’ll explore provide the functionality needed to handle these issues. There’s typically two types of batch model pipelines that can I’ve seen deployed in the gaming industry: Persistent: A separate training workflow is used to train models from the one used to build predictions. A model is persisted between training runs and loaded in the serving workflow. Transient: The same workflow is used for training and serving predictions, and instead of saving the model as a file, the model is rebuilt for each run. In this section we’ll build a transient batch pipeline, where a new model is retrained with each run. This approach generally results in more compute resources being used if the training process is heavyweight, but it helps avoid issues with model drift, which we’ll discuss in Chapter 11. We’ll author a pipeline that performs the following steps: Fetches a dataset from GitHubTrains a logistic regression modelApplies the regression modelSaves the results to BigQuery Fetches a dataset from GitHub Trains a logistic regression model Applies the regression model Saves the results to BigQuery The pipeline will execute as a single Python script that performs all of these steps. For situations where you want to use intermediate outputs from steps across multiple tasks, it’s useful to decompose the pipeline into multiple processes that are integrated through a workflow tool such as Airflow. We’ll build this script by first writing a Python script that runs on an EC2 instance, and then Dockerize the script so that we can use the container in workflows. To get started, we need to install a library for writing a Pandas data frame to BigQuery: pip install --user pandas_gbq Next, we’ll create a file called pipeline.py that performs the four pipeline steps identified above.. The script shown below performs these steps by loading the necessary libraries, fetching the CSV file from GitHub into a Pandas data frame, splits the data frame into train and test groups to simulate historic and more recent users, builds a logistic regression model using the training data set, creates predictions for the test data set, and saves the resulting data frame to BigQuery. import pandas as pdimport numpy as npfrom google.oauth2 import service_accountfrom sklearn.linear_model import LogisticRegressionfrom datetime import datetimeimport pandas_gbq # fetch the data set and add IDs gamesDF = pd.read_csv("https://github.com/bgweber/Twitch/raw/ master/Recommendations/games-expand.csv")gamesDF['User_ID'] = gamesDF.index gamesDF['New_User'] = np.floor(np.random.randint(0, 10, gamesDF.shape[0])/9)# train and test groups train = gamesDF[gamesDF['New_User'] == 0]x_train = train.iloc[:,0:10]y_train = train['label']test = gameDF[gamesDF['New_User'] == 1]x_test = test.iloc[:,0:10]# build a modelmodel = LogisticRegression()model.fit(x_train, y_train)y_pred = model.predict_proba(x_test)[:, 1]# build a predictions data frameresultDF = pd.DataFrame({'User_ID':test['User_ID'], 'Pred':y_pred}) resultDF['time'] = str(datetime. now())# save predictions to BigQuery table_id = "dsp_demo.user_scores"project_id = "gameanalytics-123"credentials = service_account.Credentials. from_service_account_file('dsdemo.json')pandas_gbq.to_gbq(resultDF, table_id, project_id=project_id, if_exists = 'replace', credentials=credentials) To simulate a real-world data set, the script assigns a User_ID attribute to each record, which represents a unique ID to track different users in a system. The script also splits users into historic and recent groups by assigning a New_User attribute. After building predictions for each of the recent users, we create a results data frame with the user ID, the model predictIon, and a timestamp. It’s useful to apply timestamps to predictions in order to determine if the pipeline has completed successfully. To test the model pipeline, run the following statements on the command line: export GOOGLE_APPLICATION_CREDENTIALS= /home/ec2-user/dsdemo.jsonpython3 pipeline.py If successfully, the script should create a new data set on BigQuery called dsp_demo, create a new table called user_users, and fill the table with user predictions. To test if data was actually populated in BigQuery, run the following commands in Jupyter: from google.cloud import bigqueryclient = bigquery.Client()sql = "select * from dsp_demo.user_scores"client.query(sql).to_dataframe().head() This script will set up a client for connecting to BigQuery and then display the result set of the query submitted to BigQuery. You can also browse to the BigQuery web UI to inspect the results of the pipeline, as shown in Figure 5.1. We now have a script that can fetch data, apply a machine learning model, and save the results as a single process. With many workflow tools, you can run Python code or bash scripts directly, but it’s good to set up isolated environments for executing scripts in order to avoid dependency conflicts for different libraries and runtimes. Luckily, we explored a tool for this in Chapter 4 and can use Docker with workflow tools. It’s useful to wrap Python scripts in Docker for workflow tools, because you can add libraries that may not be installed on the system responsible for scheduling, you can avoid issues with Python version conflicts, and containers are becoming a common way of defining tasks in workflow tools. To containerize our workflow, we need to define a Dockerfile, as shown below. Since we are building out a new Python environment from scratch, we’ll need to install Pandas, sklearn, and the BigQuery library. We also need to copy credentials from the EC2 instance into the container so that we can run the export command for authenticating with GCP. This works for short term deployments, but for longer running containers it’s better to run the export in the instantiated container rather than copying static credentials into images. The Dockerfile lists out the Python libraries needed to run the script, copies in the local files needed for execution, exports credentials, and specifies the script to run. FROM ubuntu:latestMAINTAINER Ben Weber RUN apt-get update \ && apt-get install -y python3-pip python3-dev \ && cd /usr/local/bin \ && ln -s /usr/bin/python3 python \ && pip3 install pandas \ && pip3 install sklearn \ && pip3 install pandas_gbq COPY pipeline.py pipeline.py COPY /home/ec2-user/dsdemo.json dsdemo.jsonRUN export GOOGLE_APPLICATION_CREDENTIALS=/dsdemo.jsonENTRYPOINT ["python3","pipeline.py"] Before deploying this script to production, we need to build an image from the script and test a sample run. The commands below show how to build an image from the Dockerfile, list the Docker images, and run an instance of the model pipeline image. sudo docker image build -t "sklearn_pipeline" .sudo docker imagessudo docker run sklearn_pipeline After running the last command, the containerized pipeline should update the model predictions in BigQuery. We now have a model pipeline that we can run as a single bash command, which we now need to schedule to run at a specific frequency. For testing purposes, we’ll run the script every minute, but in practice models are typically executed hourly, daily, or weekly. A common requirement for model pipelines is running a task at a regular frequency, such as every day or every hour. Cron is a utility that provides scheduling functionality for machines running the Linux operating system. You can Set up a scheduled task using the crontab utility and assign a cron expression that defines how frequently to run the command. Cron jobs run directly on the machine where cron is utilized, and can make use of the runtimes and libraries installed on the system. There are a number of challenges with using cron in production-grade systems, but it’s a great way to get started with scheduling a small number of tasks and it’s good to learn the cron expression syntax that is used in many scheduling systems. The main issue with the cron utility is that it runs on a single machine, and does not natively integrate with tools such as version control. If your machine goes down, then you’ll need to recreate your environment and update your cron table on a new machine. A cron expression defines how frequently to run a command. It is a sequence of 5 numbers that define when to execute for different time granularities, and it can include wildcards to always run for certain time periods. A few sample expresions are shown in the snippet below: # run every minute * * * * * # Run at 10am UTC everyday0 10 * * * # Run at 04:15 on Saturday15 4 * * 6 When getting started with cron, it’s good to use tools to validate your expressions. Cron expressions are used in Airflow and many other scheduling systems. We can use cron to schedule our model pipeline to run on a regular frequency. To schedule a command to run, run the following command on the console: crontab -e This command will open up the cron table file for editing in vi. To schedule the pipeline to run every minute, add the following commands to the file and save. # run every minute * * * * * sudo docker run sklearn_pipeline After exiting the editor, the cron table will be updated with the new command to run. The second part of the cron statement is the command to run. when defining the command to run, it’s useful to include full file paths. With Docker, we just need to define the image to run. To check that the script is actually executing, browse to the BigQuery UI and check the time column on the user_scores model output table. We now have a utility for scheduling our model pipeline on a regular schedule. However, if the machine goes down then our pipeline will fail to execute. To handle this situation, it’s good to explore cloud offerings with cron scheduling capabilities. Cron is useful for simple pipelines, but runs into challenges when tasks have dependencies on other tasks which can fail. To help resolve this issue, where tasks have dependencies and only portions of a pipeline need to be rerun, we can leverage workflow tools. Apache Airflow is currently the most popular tool, but other open source projects are available and provide similar functionality including Luigi and MLflow. There are a few situations where workflow tools provide benefits over using cron directly: Dependencies: Workflow tools define graphs of operations, which makes dependencies explicit. Backfills: It may be necessary to run an ETL on old data, for a range of different dates. Versioning: Most workflow tools integrate with version control systems to manage graphs. Alerting: These tools can send out emails or generate PageDuty alerts when failures occur. Workflow tools are particularly useful in environments where different teams are scheduling tasks. For example, many game companies have data scientists that schedule model pipelines which are dependent on ETLs scheduled by a seperate engineering team. In this section, we’ll schedule our task to run an EC2 instance using hosted Airflow, and then explore a fully-managed version of Airflow on GCP. Airflow is an open source workflow tool that was originally developed by Airbnb and publically released in 2015. It helps solve a challenge that many companies face, which is scheduling tasks that have many dependencies. One of the core concepts in this tool is a graph that defines the tasks to perform and the relationships between these tasks. In Airflow, a graph is referred to as a DAG, which is an acronym for directed acyclic graph. A DAG is a set of tasks to perform, where each task has zero or more upstream dependencies. One of the constraints is that cycles are not allowed, where two tasks have upstream dependencies on each other. DAGs are set up using Python code, which is one of the differences from other workflow tools such as Pentaho Kettle which is GUI focused. The Airflow approach is called “configuration as code”, because a Python script defines the operations to perform within a workflow graph. Using code instead of a GUI to configure workflows is useful because it makes it much easier to integrate with version control tools such as GitHub. To get started with Airflow, we need to install the library, initialize the service, and run the scheduler. To perform these steps, run the following commands on an EC2 instance or your local machine: export AIRFLOW_HOME=~/airflowpip install --user apache-airflowairflow initdbairflow scheduler Airflow also provides a web frontend for managing DAGs that have been scheduled. To start this service, run the following command in a new terminal on the same machine. airflow webserver -p 8080 This command tells Airflow to start the web service on port 8080. You can open a web browser at this port on your machine to view the web frontend for Airflow, as shown in Figure 5.3. Airflow comes preloaded with a number of example DAGs. For our model pipeline we’ll create a new DAG and then notify Airflow of the update. We’ll create a file called sklearn.py with the following DAG definition: from airflow import DAGfrom airflow.operators.bash_operator import BashOperatorfrom datetime import datetime, timedeltadefault_args = { 'owner': 'Airflow', 'depends_on_past': False, 'email': 'bgweber@gmail.com', 'start_date': datetime(2019, 11, 1), 'email_on_failure': True,}dag = DAG('games', default_args=default_args, schedule_interval="* * * * *")t1 = BashOperator( task_id='sklearn_pipeline', bash_command='sudo docker run sklearn_pipeline', dag=dag) There’s a few steps in this Python script to call out. The script uses a Bash operator to define the action to perform. The Bash operator is defined as the last step in the script, which specifies the command to perform. The DAG is instantiated with a number of input arguments that define the workflow settings, such as who to email when the task fails. A cron expression is passed to the DAG object to define the schedule for the task, and the DAG object is passed to the Bash operator to associate the task with this graph of operations. Before adding the DAG to airflow, it’s useful to check for syntax errors in your code. We can run the following command from the terminal to check for issues with the DAG: python3 sklearn.py This command will not run the DAG, but will flag any syntax errors present in the script. To update Airflow with the new DAG file, run the following command: airflow list_dags-------------------------------------------------------------------DAGS-------------------------------------------------------------------games This command will add the DAG to the list of workflows in Airflow. To view the list of DAGs, navigate to the Airflow web server, as shown in Figure 5.4. The web server will show the schedule of the DAG, and provide a history of past runs of the workflow. To check that the DAG is actually working, browse to the BigQuery UI and check for fresh model outputs. We now have an Airflow service up and running that we can use to monitor the execution of our workflows. This setup enables us to track the execution of workflows, backfill any gaps in data sets, and enable alerting for critical workflows. Airflow supports a variety of operations, and many companies author custom operators for internal usage. In our first DAG, we used the Bash operator to define the task to execute, but other options are available for running Docker images, including the Docker operator. The code snippet below shows how to change our DAG to use the Docker operator instead of the Bash operator. from airflow.operators.docker_operator import DockerOperatort1 = DockerOperator( task_id='sklearn_pipeline', image='sklearn_pipeline', dag=dag) The DAG we defined does not have any dependencies, since the container performs all of the steps in the model pipeline. If we had a dependency, such as running a sklearn_etl container before running the model pipeline, we can use the set_upstrean command as shown below. This configuration sets up two tasks, where the pipeline task will execute after the etl task completes. t1 = BashOperator( task_id='sklearn_etl', bash_command='sudo docker run sklearn_etl', dag=dag)t2 = BashOperator( task_id='sklearn_pipeline', bash_command='sudo docker run sklearn_pipeline', dag=dag)t2.set_upstream(t1) Airflow provides a rich set of functionality and we’ve only touched the surface of what the tool provides. While we were already able to schedule the model pipeline with hosted and managed cloud offerings, it’s useful to schedule the task through Airflow for improved monitoring and versioning. The landscape of workflow tools will change over time, but many of the concepts of Airflow will translate to these new tools. In this chapter we explored a batch model pipeline for applying a machine learning model to a set of users and storing the results to BigQuery. To make the pipeline portable, so that we can execute it in different environments, we created a Docker image to define the required libraries and credentials for the pipeline. We then ran the pipeline on an EC2 instance using batch commands, cron, and Airflow. We also used GKE and Cloud Composer to run the container via Kubernetes. Workflow tools can be tedious to set up, especially when installing a cluster deployment, but they provide a number of benefits over manual approaches. One of the key benefits is the ability to handle DAG configuration as code, which enables code reviews and version control for workflows. It’s useful to get experience with configuration as code, because it is an introduction to another concept called “infra as code” that we’ll explore in Chapter 10. Ben Weber is a distinguished data scientist at Zynga. We are hiring!
[ { "code": null, "e": 547, "s": 172, "text": "Airflow is becoming the industry standard for authoring data engineering and model pipeline workflows. This chapter of my book explores the process of taking a simple pipeline that runs on a single EC2 instance to a fully-managed Kubernetes ecosystem responsible for scheduling tasks. This posts omits the sections on the fully-managed solutions with GKE and Cloud Composer." }, { "code": null, "e": 559, "s": 547, "text": "leanpub.com" }, { "code": null, "e": 1083, "s": 559, "text": "Model pipelines are usually part of a broader data platform that provides data sources, such as lakes and warehouses, and data stores, such as an application database. When building a pipeline, it’s useful to be able to schedule a task to run, ensure that any dependencies for the pipeline have already completed, and to backfill historic data if needed. While it’s possible to perform these types of tasks manually, there are a variety of tools that have been developed to improve the management of data science workflows." }, { "code": null, "e": 1711, "s": 1083, "text": "In this chapter, we’ll explore a batch model pipeline that performs a sequence of tasks in order to train and store results for a propensity model. This is a different type of task than the deployments we’ve explored so far, which have focused on serving real-time model predictions as a web endpoint. In a batch process, you perform a set of operations that store model results that are later served by a different application. For example, a batch model pipeline may predict which users in a game are likely to churn, and a game server fetches predictions for each user that starts a session and provides personalized offers." }, { "code": null, "e": 2209, "s": 1711, "text": "When building batch model pipelines for production systems, it’s important to make sure that issues with the pipeline are quickly resolved. For example, if the model pipeline is unable to fetch the most recent data for a set of users due to an upstream failure with a database, it’s useful to have a system in place that can send alerts to the team that owns the pipeline and that can rerun portions of the model pipeline in order to resolve any issues with the prerequisite data or model outputs." }, { "code": null, "e": 2863, "s": 2209, "text": "Workflow tools provide a solution for managing these types of problems in model pipelines. With a workflow tool, you specify the operations that need to be completed, identify dependencies between the operations, and then schedule the operations to be performed by the tool. A workflow tool is responsible for running tasks, provisioning resources, and monitoring the status of tasks. There’s a number of open source tools for building workflows including AirFlow, Luigi, MLflow, and Pentaho Kettle. We’ll focus on Airflow, because it is being widely adopted across companies and cloud platforms and are also providing fully-managed versions of Airflow." }, { "code": null, "e": 3237, "s": 2863, "text": "In this chapter, we’ll build a batch model pipeline that runs as a Docker container. Next, we’ll schedule the task to run on an EC2 instance using cron, and then explore a managed version of cron using Kubernetes. In the third section, we’ll use Airflow to define a graph of operations to perform in order to run our model pipeline, and explore a cloud offering of Airflow." }, { "code": null, "e": 3878, "s": 3237, "text": "A common workflow for batch model pipelines is to extract data from a data lake or data warehouse, train a model on historic user behavior, predict future user behavior for more recent data, and then save the results to a data warehouse or application database. In the gaming industry, this is a workflow I’ve seen used for building likelihood to purchase and likelihood to churn models, where the game servers use these predictions to provide different treatments to users based on the model predictions. Usually libraries like sklearn are used to develop models, and languages such as PySpark are used to scale up to the full player base." }, { "code": null, "e": 4472, "s": 3878, "text": "It is typical for model pipelines to require other ETLs to run in a data platform before the pipeline can run on the most recent data. For example, there may be an upstream step in the data platform that translates json strings into schematized events that are used as input for a model. In this situation, it might be necessary to rerun the pipeline on a day that issues occurred with the json transformation process. For this section, we’ll avoid this complication by using a static input data source, but the tools that we’ll explore provide the functionality needed to handle these issues." }, { "code": null, "e": 4577, "s": 4472, "text": "There’s typically two types of batch model pipelines that can I’ve seen deployed in the gaming industry:" }, { "code": null, "e": 4761, "s": 4577, "text": "Persistent: A separate training workflow is used to train models from the one used to build predictions. A model is persisted between training runs and loaded in the serving workflow." }, { "code": null, "e": 4914, "s": 4761, "text": "Transient: The same workflow is used for training and serving predictions, and instead of saving the model as a file, the model is rebuilt for each run." }, { "code": null, "e": 5263, "s": 4914, "text": "In this section we’ll build a transient batch pipeline, where a new model is retrained with each run. This approach generally results in more compute resources being used if the training process is heavyweight, but it helps avoid issues with model drift, which we’ll discuss in Chapter 11. We’ll author a pipeline that performs the following steps:" }, { "code": null, "e": 5384, "s": 5263, "text": "Fetches a dataset from GitHubTrains a logistic regression modelApplies the regression modelSaves the results to BigQuery" }, { "code": null, "e": 5414, "s": 5384, "text": "Fetches a dataset from GitHub" }, { "code": null, "e": 5449, "s": 5414, "text": "Trains a logistic regression model" }, { "code": null, "e": 5478, "s": 5449, "text": "Applies the regression model" }, { "code": null, "e": 5508, "s": 5478, "text": "Saves the results to BigQuery" }, { "code": null, "e": 5809, "s": 5508, "text": "The pipeline will execute as a single Python script that performs all of these steps. For situations where you want to use intermediate outputs from steps across multiple tasks, it’s useful to decompose the pipeline into multiple processes that are integrated through a workflow tool such as Airflow." }, { "code": null, "e": 6063, "s": 5809, "text": "We’ll build this script by first writing a Python script that runs on an EC2 instance, and then Dockerize the script so that we can use the container in workflows. To get started, we need to install a library for writing a Pandas data frame to BigQuery:" }, { "code": null, "e": 6093, "s": 6063, "text": "pip install --user pandas_gbq" }, { "code": null, "e": 6583, "s": 6093, "text": "Next, we’ll create a file called pipeline.py that performs the four pipeline steps identified above.. The script shown below performs these steps by loading the necessary libraries, fetching the CSV file from GitHub into a Pandas data frame, splits the data frame into train and test groups to simulate historic and more recent users, builds a logistic regression model using the training data set, creates predictions for the test data set, and saves the resulting data frame to BigQuery." }, { "code": null, "e": 7836, "s": 6583, "text": "import pandas as pdimport numpy as npfrom google.oauth2 import service_accountfrom sklearn.linear_model import LogisticRegressionfrom datetime import datetimeimport pandas_gbq # fetch the data set and add IDs gamesDF = pd.read_csv(\"https://github.com/bgweber/Twitch/raw/ master/Recommendations/games-expand.csv\")gamesDF['User_ID'] = gamesDF.index gamesDF['New_User'] = np.floor(np.random.randint(0, 10, gamesDF.shape[0])/9)# train and test groups train = gamesDF[gamesDF['New_User'] == 0]x_train = train.iloc[:,0:10]y_train = train['label']test = gameDF[gamesDF['New_User'] == 1]x_test = test.iloc[:,0:10]# build a modelmodel = LogisticRegression()model.fit(x_train, y_train)y_pred = model.predict_proba(x_test)[:, 1]# build a predictions data frameresultDF = pd.DataFrame({'User_ID':test['User_ID'], 'Pred':y_pred}) resultDF['time'] = str(datetime. now())# save predictions to BigQuery table_id = \"dsp_demo.user_scores\"project_id = \"gameanalytics-123\"credentials = service_account.Credentials. from_service_account_file('dsdemo.json')pandas_gbq.to_gbq(resultDF, table_id, project_id=project_id, if_exists = 'replace', credentials=credentials)" }, { "code": null, "e": 8425, "s": 7836, "text": "To simulate a real-world data set, the script assigns a User_ID attribute to each record, which represents a unique ID to track different users in a system. The script also splits users into historic and recent groups by assigning a New_User attribute. After building predictions for each of the recent users, we create a results data frame with the user ID, the model predictIon, and a timestamp. It’s useful to apply timestamps to predictions in order to determine if the pipeline has completed successfully. To test the model pipeline, run the following statements on the command line:" }, { "code": null, "e": 8518, "s": 8425, "text": "export GOOGLE_APPLICATION_CREDENTIALS= /home/ec2-user/dsdemo.jsonpython3 pipeline.py" }, { "code": null, "e": 8775, "s": 8518, "text": "If successfully, the script should create a new data set on BigQuery called dsp_demo, create a new table called user_users, and fill the table with user predictions. To test if data was actually populated in BigQuery, run the following commands in Jupyter:" }, { "code": null, "e": 8916, "s": 8775, "text": "from google.cloud import bigqueryclient = bigquery.Client()sql = \"select * from dsp_demo.user_scores\"client.query(sql).to_dataframe().head()" }, { "code": null, "e": 9267, "s": 8916, "text": "This script will set up a client for connecting to BigQuery and then display the result set of the query submitted to BigQuery. You can also browse to the BigQuery web UI to inspect the results of the pipeline, as shown in Figure 5.1. We now have a script that can fetch data, apply a machine learning model, and save the results as a single process." }, { "code": null, "e": 9871, "s": 9267, "text": "With many workflow tools, you can run Python code or bash scripts directly, but it’s good to set up isolated environments for executing scripts in order to avoid dependency conflicts for different libraries and runtimes. Luckily, we explored a tool for this in Chapter 4 and can use Docker with workflow tools. It’s useful to wrap Python scripts in Docker for workflow tools, because you can add libraries that may not be installed on the system responsible for scheduling, you can avoid issues with Python version conflicts, and containers are becoming a common way of defining tasks in workflow tools." }, { "code": null, "e": 10579, "s": 9871, "text": "To containerize our workflow, we need to define a Dockerfile, as shown below. Since we are building out a new Python environment from scratch, we’ll need to install Pandas, sklearn, and the BigQuery library. We also need to copy credentials from the EC2 instance into the container so that we can run the export command for authenticating with GCP. This works for short term deployments, but for longer running containers it’s better to run the export in the instantiated container rather than copying static credentials into images. The Dockerfile lists out the Python libraries needed to run the script, copies in the local files needed for execution, exports credentials, and specifies the script to run." }, { "code": null, "e": 11006, "s": 10579, "text": "FROM ubuntu:latestMAINTAINER Ben Weber RUN apt-get update \\ && apt-get install -y python3-pip python3-dev \\ && cd /usr/local/bin \\ && ln -s /usr/bin/python3 python \\ && pip3 install pandas \\ && pip3 install sklearn \\ && pip3 install pandas_gbq COPY pipeline.py pipeline.py COPY /home/ec2-user/dsdemo.json dsdemo.jsonRUN export GOOGLE_APPLICATION_CREDENTIALS=/dsdemo.jsonENTRYPOINT [\"python3\",\"pipeline.py\"]" }, { "code": null, "e": 11255, "s": 11006, "text": "Before deploying this script to production, we need to build an image from the script and test a sample run. The commands below show how to build an image from the Dockerfile, list the Docker images, and run an instance of the model pipeline image." }, { "code": null, "e": 11353, "s": 11255, "text": "sudo docker image build -t \"sklearn_pipeline\" .sudo docker imagessudo docker run sklearn_pipeline" }, { "code": null, "e": 11723, "s": 11353, "text": "After running the last command, the containerized pipeline should update the model predictions in BigQuery. We now have a model pipeline that we can run as a single bash command, which we now need to schedule to run at a specific frequency. For testing purposes, we’ll run the script every minute, but in practice models are typically executed hourly, daily, or weekly." }, { "code": null, "e": 12214, "s": 11723, "text": "A common requirement for model pipelines is running a task at a regular frequency, such as every day or every hour. Cron is a utility that provides scheduling functionality for machines running the Linux operating system. You can Set up a scheduled task using the crontab utility and assign a cron expression that defines how frequently to run the command. Cron jobs run directly on the machine where cron is utilized, and can make use of the runtimes and libraries installed on the system." }, { "code": null, "e": 12719, "s": 12214, "text": "There are a number of challenges with using cron in production-grade systems, but it’s a great way to get started with scheduling a small number of tasks and it’s good to learn the cron expression syntax that is used in many scheduling systems. The main issue with the cron utility is that it runs on a single machine, and does not natively integrate with tools such as version control. If your machine goes down, then you’ll need to recreate your environment and update your cron table on a new machine." }, { "code": null, "e": 12995, "s": 12719, "text": "A cron expression defines how frequently to run a command. It is a sequence of 5 numbers that define when to execute for different time granularities, and it can include wildcards to always run for certain time periods. A few sample expresions are shown in the snippet below:" }, { "code": null, "e": 13100, "s": 12995, "text": "# run every minute * * * * * # Run at 10am UTC everyday0 10 * * * # Run at 04:15 on Saturday15 4 * * 6" }, { "code": null, "e": 13257, "s": 13100, "text": "When getting started with cron, it’s good to use tools to validate your expressions. Cron expressions are used in Airflow and many other scheduling systems." }, { "code": null, "e": 13407, "s": 13257, "text": "We can use cron to schedule our model pipeline to run on a regular frequency. To schedule a command to run, run the following command on the console:" }, { "code": null, "e": 13418, "s": 13407, "text": "crontab -e" }, { "code": null, "e": 13578, "s": 13418, "text": "This command will open up the cron table file for editing in vi. To schedule the pipeline to run every minute, add the following commands to the file and save." }, { "code": null, "e": 13640, "s": 13578, "text": "# run every minute * * * * * sudo docker run sklearn_pipeline" }, { "code": null, "e": 14054, "s": 13640, "text": "After exiting the editor, the cron table will be updated with the new command to run. The second part of the cron statement is the command to run. when defining the command to run, it’s useful to include full file paths. With Docker, we just need to define the image to run. To check that the script is actually executing, browse to the BigQuery UI and check the time column on the user_scores model output table." }, { "code": null, "e": 14305, "s": 14054, "text": "We now have a utility for scheduling our model pipeline on a regular schedule. However, if the machine goes down then our pipeline will fail to execute. To handle this situation, it’s good to explore cloud offerings with cron scheduling capabilities." }, { "code": null, "e": 14725, "s": 14305, "text": "Cron is useful for simple pipelines, but runs into challenges when tasks have dependencies on other tasks which can fail. To help resolve this issue, where tasks have dependencies and only portions of a pipeline need to be rerun, we can leverage workflow tools. Apache Airflow is currently the most popular tool, but other open source projects are available and provide similar functionality including Luigi and MLflow." }, { "code": null, "e": 14816, "s": 14725, "text": "There are a few situations where workflow tools provide benefits over using cron directly:" }, { "code": null, "e": 14909, "s": 14816, "text": "Dependencies: Workflow tools define graphs of operations, which makes dependencies explicit." }, { "code": null, "e": 14999, "s": 14909, "text": "Backfills: It may be necessary to run an ETL on old data, for a range of different dates." }, { "code": null, "e": 15088, "s": 14999, "text": "Versioning: Most workflow tools integrate with version control systems to manage graphs." }, { "code": null, "e": 15179, "s": 15088, "text": "Alerting: These tools can send out emails or generate PageDuty alerts when failures occur." }, { "code": null, "e": 15432, "s": 15179, "text": "Workflow tools are particularly useful in environments where different teams are scheduling tasks. For example, many game companies have data scientists that schedule model pipelines which are dependent on ETLs scheduled by a seperate engineering team." }, { "code": null, "e": 15578, "s": 15432, "text": "In this section, we’ll schedule our task to run an EC2 instance using hosted Airflow, and then explore a fully-managed version of Airflow on GCP." }, { "code": null, "e": 15925, "s": 15578, "text": "Airflow is an open source workflow tool that was originally developed by Airbnb and publically released in 2015. It helps solve a challenge that many companies face, which is scheduling tasks that have many dependencies. One of the core concepts in this tool is a graph that defines the tasks to perform and the relationships between these tasks." }, { "code": null, "e": 16223, "s": 15925, "text": "In Airflow, a graph is referred to as a DAG, which is an acronym for directed acyclic graph. A DAG is a set of tasks to perform, where each task has zero or more upstream dependencies. One of the constraints is that cycles are not allowed, where two tasks have upstream dependencies on each other." }, { "code": null, "e": 16649, "s": 16223, "text": "DAGs are set up using Python code, which is one of the differences from other workflow tools such as Pentaho Kettle which is GUI focused. The Airflow approach is called “configuration as code”, because a Python script defines the operations to perform within a workflow graph. Using code instead of a GUI to configure workflows is useful because it makes it much easier to integrate with version control tools such as GitHub." }, { "code": null, "e": 16850, "s": 16649, "text": "To get started with Airflow, we need to install the library, initialize the service, and run the scheduler. To perform these steps, run the following commands on an EC2 instance or your local machine:" }, { "code": null, "e": 16944, "s": 16850, "text": "export AIRFLOW_HOME=~/airflowpip install --user apache-airflowairflow initdbairflow scheduler" }, { "code": null, "e": 17113, "s": 16944, "text": "Airflow also provides a web frontend for managing DAGs that have been scheduled. To start this service, run the following command in a new terminal on the same machine." }, { "code": null, "e": 17139, "s": 17113, "text": "airflow webserver -p 8080" }, { "code": null, "e": 17323, "s": 17139, "text": "This command tells Airflow to start the web service on port 8080. You can open a web browser at this port on your machine to view the web frontend for Airflow, as shown in Figure 5.3." }, { "code": null, "e": 17536, "s": 17323, "text": "Airflow comes preloaded with a number of example DAGs. For our model pipeline we’ll create a new DAG and then notify Airflow of the update. We’ll create a file called sklearn.py with the following DAG definition:" }, { "code": null, "e": 18018, "s": 17536, "text": "from airflow import DAGfrom airflow.operators.bash_operator import BashOperatorfrom datetime import datetime, timedeltadefault_args = { 'owner': 'Airflow', 'depends_on_past': False, 'email': 'bgweber@gmail.com', 'start_date': datetime(2019, 11, 1), 'email_on_failure': True,}dag = DAG('games', default_args=default_args, schedule_interval=\"* * * * *\")t1 = BashOperator( task_id='sklearn_pipeline', bash_command='sudo docker run sklearn_pipeline', dag=dag)" }, { "code": null, "e": 18559, "s": 18018, "text": "There’s a few steps in this Python script to call out. The script uses a Bash operator to define the action to perform. The Bash operator is defined as the last step in the script, which specifies the command to perform. The DAG is instantiated with a number of input arguments that define the workflow settings, such as who to email when the task fails. A cron expression is passed to the DAG object to define the schedule for the task, and the DAG object is passed to the Bash operator to associate the task with this graph of operations." }, { "code": null, "e": 18731, "s": 18559, "text": "Before adding the DAG to airflow, it’s useful to check for syntax errors in your code. We can run the following command from the terminal to check for issues with the DAG:" }, { "code": null, "e": 18750, "s": 18731, "text": "python3 sklearn.py" }, { "code": null, "e": 18908, "s": 18750, "text": "This command will not run the DAG, but will flag any syntax errors present in the script. To update Airflow with the new DAG file, run the following command:" }, { "code": null, "e": 19069, "s": 18908, "text": "airflow list_dags-------------------------------------------------------------------DAGS-------------------------------------------------------------------games" }, { "code": null, "e": 19428, "s": 19069, "text": "This command will add the DAG to the list of workflows in Airflow. To view the list of DAGs, navigate to the Airflow web server, as shown in Figure 5.4. The web server will show the schedule of the DAG, and provide a history of past runs of the workflow. To check that the DAG is actually working, browse to the BigQuery UI and check for fresh model outputs." }, { "code": null, "e": 19668, "s": 19428, "text": "We now have an Airflow service up and running that we can use to monitor the execution of our workflows. This setup enables us to track the execution of workflows, backfill any gaps in data sets, and enable alerting for critical workflows." }, { "code": null, "e": 20046, "s": 19668, "text": "Airflow supports a variety of operations, and many companies author custom operators for internal usage. In our first DAG, we used the Bash operator to define the task to execute, but other options are available for running Docker images, including the Docker operator. The code snippet below shows how to change our DAG to use the Docker operator instead of the Bash operator." }, { "code": null, "e": 20199, "s": 20046, "text": "from airflow.operators.docker_operator import DockerOperatort1 = DockerOperator( task_id='sklearn_pipeline', image='sklearn_pipeline', dag=dag)" }, { "code": null, "e": 20575, "s": 20199, "text": "The DAG we defined does not have any dependencies, since the container performs all of the steps in the model pipeline. If we had a dependency, such as running a sklearn_etl container before running the model pipeline, we can use the set_upstrean command as shown below. This configuration sets up two tasks, where the pipeline task will execute after the etl task completes." }, { "code": null, "e": 20811, "s": 20575, "text": "t1 = BashOperator( task_id='sklearn_etl', bash_command='sudo docker run sklearn_etl', dag=dag)t2 = BashOperator( task_id='sklearn_pipeline', bash_command='sudo docker run sklearn_pipeline', dag=dag)t2.set_upstream(t1)" }, { "code": null, "e": 21232, "s": 20811, "text": "Airflow provides a rich set of functionality and we’ve only touched the surface of what the tool provides. While we were already able to schedule the model pipeline with hosted and managed cloud offerings, it’s useful to schedule the task through Airflow for improved monitoring and versioning. The landscape of workflow tools will change over time, but many of the concepts of Airflow will translate to these new tools." }, { "code": null, "e": 21711, "s": 21232, "text": "In this chapter we explored a batch model pipeline for applying a machine learning model to a set of users and storing the results to BigQuery. To make the pipeline portable, so that we can execute it in different environments, we created a Docker image to define the required libraries and credentials for the pipeline. We then ran the pipeline on an EC2 instance using batch commands, cron, and Airflow. We also used GKE and Cloud Composer to run the container via Kubernetes." }, { "code": null, "e": 22165, "s": 21711, "text": "Workflow tools can be tedious to set up, especially when installing a cluster deployment, but they provide a number of benefits over manual approaches. One of the key benefits is the ability to handle DAG configuration as code, which enables code reviews and version control for workflows. It’s useful to get experience with configuration as code, because it is an introduction to another concept called “infra as code” that we’ll explore in Chapter 10." } ]
Arduino - Servo Motor
A Servo Motor is a small device that has an output shaft. This shaft can be positioned to specific angular positions by sending the servo a coded signal. As long as the coded signal exists on the input line, the servo will maintain the angular position of the shaft. If the coded signal changes, the angular position of the shaft changes. In practice, servos are used in radio-controlled airplanes to position control surfaces like the elevators and rudders. They are also used in radio-controlled cars, puppets, and of course, robots. Servos are extremely useful in robotics. The motors are small, have built-in control circuitry, and are extremely powerful for their size. A standard servo such as the Futaba S-148 has 42 oz/inches of torque, which is strong for its size. It also draws power proportional to the mechanical load. A lightly loaded servo, therefore, does not consume much energy. The guts of a servo motor is shown in the following picture. You can see the control circuitry, the motor, a set of gears, and the case. You can also see the 3 wires that connect to the outside world. One is for power (+5volts), ground, and the white wire is the control wire. The servo motor has some control circuits and a potentiometer (a variable resistor, aka pot) connected to the output shaft. In the picture above, the pot can be seen on the right side of the circuit board. This pot allows the control circuitry to monitor the current angle of the servo motor. If the shaft is at the correct angle, then the motor shuts off. If the circuit finds that the angle is not correct, it will turn the motor until it is at a desired angle. The output shaft of the servo is capable of traveling somewhere around 180 degrees. Usually, it is somewhere in the 210-degree range, however, it varies depending on the manufacturer. A normal servo is used to control an angular motion of 0 to 180 degrees. It is mechanically not capable of turning any farther due to a mechanical stop built on to the main output gear. The power applied to the motor is proportional to the distance it needs to travel. So, if the shaft needs to turn a large distance, the motor will run at full speed. If it needs to turn only a small amount, the motor will run at a slower speed. This is called proportional control. The control wire is used to communicate the angle. The angle is determined by the duration of a pulse that is applied to the control wire. This is called Pulse Coded Modulation. The servo expects to see a pulse every 20 milliseconds (.02 seconds). The length of the pulse will determine how far the motor turns. A 1.5 millisecond pulse, for example, will make the motor turn to the 90-degree position (often called as the neutral position). If the pulse is shorter than 1.5 milliseconds, then the motor will turn the shaft closer to 0 degrees. If the pulse is longer than 1.5 milliseconds, the shaft turns closer to 180 degrees. You will need the following components − 1 × Arduino UNO board 1 × Servo Motor 1 × ULN2003 driving IC 1 × 10 KΩ Resistor Follow the circuit diagram and make the connections as shown in the image given below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New. /* Controlling a servo position using a potentiometer (variable resistor) */ #include <Servo.h> Servo myservo; // create servo object to control a servo int potpin = 0; // analog pin used to connect the potentiometer int val; // variable to read the value from the analog pin void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) myservo.write(val); // sets the servo position according to the scaled value delay(15); } Servo motors have three terminals - power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino. The ground wire is typically black or brown and should be connected to one terminal of ULN2003 IC (10 -16). To protect your Arduino board from damage, you will need some driver IC to do that. Here we have used ULN2003 IC to drive the servo motor. The signal pin is typically yellow or orange and should be connected to Arduino pin number 9. A voltage divider/potential divider are resistors in a series circuit that scale the output voltage to a particular ratio of the input voltage applied. Following is the circuit diagram − $$V_{out} = (V_{in} \times R_{2})/ (R_{1} + R_{2})$$ Vout is the output potential, which depends on the applied input voltage (Vin) and resistors (R1 and R2) in the series. It means that the current flowing through R1 will also flow through R2 without being divided. In the above equation, as the value of R2 changes, the Vout scales accordingly with respect to the input voltage, Vin. Typically, a potentiometer is a potential divider, which can scale the output voltage of the circuit based on the value of the variable resistor, which is scaled using the knob. It has three pins: GND, Signal, and +5V as shown in the diagram below − By changing the pot’s NOP position, servo motor will change its angle. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3406, "s": 2870, "text": "A Servo Motor is a small device that has an output shaft. This shaft can be positioned to specific angular positions by sending the servo a coded signal. As long as the coded signal exists on the input line, the servo will maintain the angular position of the shaft. If the coded signal changes, the angular position of the shaft changes. In practice, servos are used in radio-controlled airplanes to position control surfaces like the elevators and rudders. They are also used in radio-controlled cars, puppets, and of course, robots." }, { "code": null, "e": 3767, "s": 3406, "text": "Servos are extremely useful in robotics. The motors are small, have built-in control circuitry, and are extremely powerful for their size. A standard servo such as the Futaba S-148 has 42 oz/inches of torque, which is strong for its size. It also draws power proportional to the mechanical load. A lightly loaded servo, therefore, does not consume much energy." }, { "code": null, "e": 4044, "s": 3767, "text": "The guts of a servo motor is shown in the following picture. You can see the control circuitry, the motor, a set of gears, and the case. You can also see the 3 wires that connect to the outside world. One is for power (+5volts), ground, and the white wire is the control wire." }, { "code": null, "e": 4337, "s": 4044, "text": "The servo motor has some control circuits and a potentiometer (a variable resistor, aka pot) connected to the output shaft. In the picture above, the pot can be seen on the right side of the circuit board. This pot allows the control circuitry to monitor the current angle of the servo motor." }, { "code": null, "e": 4878, "s": 4337, "text": "If the shaft is at the correct angle, then the motor shuts off. If the circuit finds that the angle is not correct, it will turn the motor until it is at a desired angle. The output shaft of the servo is capable of traveling somewhere around 180 degrees. Usually, it is somewhere in the 210-degree range, however, it varies depending on the manufacturer. A normal servo is used to control an angular motion of 0 to 180 degrees. It is mechanically not capable of turning any farther due to a mechanical stop built on to the main output gear." }, { "code": null, "e": 5160, "s": 4878, "text": "The power applied to the motor is proportional to the distance it needs to travel. So, if the shaft needs to turn a large distance, the motor will run at full speed. If it needs to turn only a small amount, the motor will run at a slower speed. This is called proportional control." }, { "code": null, "e": 5789, "s": 5160, "text": "The control wire is used to communicate the angle. The angle is determined by the duration of a pulse that is applied to the control wire. This is called Pulse Coded Modulation. The servo expects to see a pulse every 20 milliseconds (.02 seconds). The length of the pulse will determine how far the motor turns. A 1.5 millisecond pulse, for example, will make the motor turn to the 90-degree position (often called as the neutral position). If the pulse is shorter than 1.5 milliseconds, then the motor will turn the shaft closer to 0 degrees. If the pulse is longer than 1.5 milliseconds, the shaft turns closer to 180 degrees." }, { "code": null, "e": 5830, "s": 5789, "text": "You will need the following components −" }, { "code": null, "e": 5852, "s": 5830, "text": "1 × Arduino UNO board" }, { "code": null, "e": 5868, "s": 5852, "text": "1 × Servo Motor" }, { "code": null, "e": 5891, "s": 5868, "text": "1 × ULN2003 driving IC" }, { "code": null, "e": 5910, "s": 5891, "text": "1 × 10 KΩ Resistor" }, { "code": null, "e": 5997, "s": 5910, "text": "Follow the circuit diagram and make the connections as shown in the image given below." }, { "code": null, "e": 6146, "s": 5997, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New." }, { "code": null, "e": 6835, "s": 6146, "text": "/* Controlling a servo position using a potentiometer (variable resistor) */\n\n#include <Servo.h>\n Servo myservo; // create servo object to control a servo\n int potpin = 0; // analog pin used to connect the potentiometer\n int val; // variable to read the value from the analog pin\n\nvoid setup() {\n myservo.attach(9); // attaches the servo on pin 9 to the servo object\n}\n\nvoid loop() {\n val = analogRead(potpin);\n // reads the value of the potentiometer (value between 0 and 1023)\n val = map(val, 0, 1023, 0, 180);\n // scale it to use it with the servo (value between 0 and 180)\n myservo.write(val); // sets the servo position according to the scaled value\n delay(15);\n}" }, { "code": null, "e": 7326, "s": 6835, "text": "Servo motors have three terminals - power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino. The ground wire is typically black or brown and should be connected to one terminal of ULN2003 IC (10 -16). To protect your Arduino board from damage, you will need some driver IC to do that. Here we have used ULN2003 IC to drive the servo motor. The signal pin is typically yellow or orange and should be connected to Arduino pin number 9." }, { "code": null, "e": 7513, "s": 7326, "text": "A voltage divider/potential divider are resistors in a series circuit that scale the output voltage to a particular ratio of the input voltage applied. Following is the circuit diagram −" }, { "code": null, "e": 7566, "s": 7513, "text": "$$V_{out} = (V_{in} \\times R_{2})/ (R_{1} + R_{2})$$" }, { "code": null, "e": 7899, "s": 7566, "text": "Vout is the output potential, which depends on the applied input voltage (Vin) and resistors (R1 and R2) in the series. It means that the current flowing through R1 will also flow through R2 without being divided. In the above equation, as the value of R2 changes, the Vout scales accordingly with respect to the input voltage, Vin." }, { "code": null, "e": 8149, "s": 7899, "text": "Typically, a potentiometer is a potential divider, which can scale the output voltage of the circuit based on the value of the variable resistor, which is scaled using the knob. It has three pins: GND, Signal, and +5V as shown in the diagram below −" }, { "code": null, "e": 8220, "s": 8149, "text": "By changing the pot’s NOP position, servo motor will change its angle." }, { "code": null, "e": 8255, "s": 8220, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8266, "s": 8255, "text": " Amit Rana" }, { "code": null, "e": 8299, "s": 8266, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 8310, "s": 8299, "text": " Amit Rana" }, { "code": null, "e": 8343, "s": 8310, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 8356, "s": 8343, "text": " Ashraf Said" }, { "code": null, "e": 8391, "s": 8356, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8404, "s": 8391, "text": " Ashraf Said" }, { "code": null, "e": 8436, "s": 8404, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 8449, "s": 8436, "text": " Ashraf Said" }, { "code": null, "e": 8480, "s": 8449, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 8493, "s": 8480, "text": " Ashraf Said" }, { "code": null, "e": 8500, "s": 8493, "text": " Print" }, { "code": null, "e": 8511, "s": 8500, "text": " Add Notes" } ]
How to delete all the documents from a collection in MongoDB?
If you want to delete all documents from the collection, you can use deleteMany(). Let us first create a collection and insert some documents to it: > db.deleteDocumentsDemo.insert({"Name":"Larry","Age":23}); WriteResult({ "nInserted" : 1 }) > db.deleteDocumentsDemo.insert({"Name":"Mike","Age":21}); WriteResult({ "nInserted" : 1 }) > db.deleteDocumentsDemo.insert({"Name":"Sam","Age":24}); WriteResult({ "nInserted" : 1 }) Now display all the documents from the collection. The query is as follows: > db.deleteDocumentsDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6ab0e064f3d70fcc914805"), "Name" : "Larry", "Age" : 23 } { "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"), "Name" : "Mike", "Age" : 21 } { "_id" : ObjectId("5c6ab0f864f3d70fcc914807"), "Name" : "Sam", "Age" : 24 } The query is as follows: > db.deleteDocumentsDemo.deleteMany({}); The following is the output: { "acknowledged" : true, "deletedCount" : 3 } Look at the above sample output. Right now, we do not have any documents in the collection ‘deleteDocumentsDemo’ i.e. we have successfully deleted all the documents using the deleteMany() method.
[ { "code": null, "e": 1211, "s": 1062, "text": "If you want to delete all documents from the collection, you can use deleteMany(). Let us first create a collection and insert some documents to it:" }, { "code": null, "e": 1487, "s": 1211, "text": "> db.deleteDocumentsDemo.insert({\"Name\":\"Larry\",\"Age\":23});\nWriteResult({ \"nInserted\" : 1 })\n> db.deleteDocumentsDemo.insert({\"Name\":\"Mike\",\"Age\":21});\nWriteResult({ \"nInserted\" : 1 })\n> db.deleteDocumentsDemo.insert({\"Name\":\"Sam\",\"Age\":24});\nWriteResult({ \"nInserted\" : 1 })" }, { "code": null, "e": 1563, "s": 1487, "text": "Now display all the documents from the collection. The query is as follows:" }, { "code": null, "e": 1605, "s": 1563, "text": "> db.deleteDocumentsDemo.find().pretty();" }, { "code": null, "e": 1634, "s": 1605, "text": "The following is the output:" }, { "code": null, "e": 1895, "s": 1634, "text": "{\n \"_id\" : ObjectId(\"5c6ab0e064f3d70fcc914805\"),\n \"Name\" : \"Larry\",\n \"Age\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c6ab0ef64f3d70fcc914806\"),\n \"Name\" : \"Mike\",\n \"Age\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c6ab0f864f3d70fcc914807\"),\n \"Name\" : \"Sam\",\n \"Age\" : 24\n}" }, { "code": null, "e": 1920, "s": 1895, "text": "The query is as follows:" }, { "code": null, "e": 1961, "s": 1920, "text": "> db.deleteDocumentsDemo.deleteMany({});" }, { "code": null, "e": 1990, "s": 1961, "text": "The following is the output:" }, { "code": null, "e": 2036, "s": 1990, "text": "{ \"acknowledged\" : true, \"deletedCount\" : 3 }" }, { "code": null, "e": 2232, "s": 2036, "text": "Look at the above sample output. Right now, we do not have any documents in the collection ‘deleteDocumentsDemo’ i.e. we have successfully deleted all the documents using the deleteMany() method." } ]
How to print characters from a string starting from 3rd to 5th in Python?
Slicing feature in Python helps fetch a substring from original string. Slice operator [:] needs two operands. First operand is an integer representing index of starting character of slice. Second operand is index of character next to slice. Recalling that index of sequence starts from 0, >>> string = 'abcdefghij' >>> string[2:5] 'cde' Here 3rd character of slice ‘cde’ starts at index 2 and ends at 4, so second operand is given as 5
[ { "code": null, "e": 1352, "s": 1062, "text": "Slicing feature in Python helps fetch a substring from original string. Slice operator [:] needs two operands. First operand is an integer representing index of starting character of slice. Second operand is index of character next to slice. Recalling that index of sequence starts from 0," }, { "code": null, "e": 1401, "s": 1352, "text": ">>> string = 'abcdefghij'\n>>> string[2:5]\n 'cde'" }, { "code": null, "e": 1500, "s": 1401, "text": "Here 3rd character of slice ‘cde’ starts at index 2 and ends at 4, so second operand is given as 5" } ]
How to capture divide by zero exception in C#?
System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero. Let us see an example − using System; namespace ErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } } The values entered here is num1/ num2 − result = num1 / num2; Above, if num2 is set to 0, then the DivideByZeroException is caught since we have handled exception above.
[ { "code": null, "e": 1168, "s": 1062, "text": "System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero." }, { "code": null, "e": 1192, "s": 1168, "text": "Let us see an example −" }, { "code": null, "e": 1784, "s": 1192, "text": "using System;\n\nnamespace ErrorHandlingApplication {\n class DivNumbers {\n int result;\n\n DivNumbers() {\n result = 0;\n }\n public void division(int num1, int num2) {\n try {\n result = num1 / num2;\n } catch (DivideByZeroException e) {\n Console.WriteLine(\"Exception caught: {0}\", e);\n } finally {\n Console.WriteLine(\"Result: {0}\", result);\n }\n }\n static void Main(string[] args) {\n DivNumbers d = new DivNumbers();\n d.division(25, 0);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1824, "s": 1784, "text": "The values entered here is num1/ num2 −" }, { "code": null, "e": 1846, "s": 1824, "text": "result = num1 / num2;" }, { "code": null, "e": 1954, "s": 1846, "text": "Above, if num2 is set to 0, then the DivideByZeroException is caught since we have handled exception above." } ]
Android - Navigation
In this chapter, we will see that how you can provide navigation forward and backward between an application. We will first look at how to provide up navigation in an application. The up navigation will allow our application to move to previous activity from the next activity. It can be done like this. To implement Up navigation, the first step is to declare which activity is the appropriate parent for each activity. You can do it by specifying parentActivityName attribute in an activity. Its syntax is given below − android:parentActivityName = "com.example.test.MainActivity" After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method of the activity. This will enable the back button in the top action bar. getActionBar().setDisplayHomeAsUpEnabled(true); The last thing you need to do is to override onOptionsItemSelected method. when the user presses it, your activity receives a call to onOptionsItemSelected(). The ID for the action is android.R.id.home.Its syntax is given below − public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } } Since you have enabled your back button to navigate within your application, you might want to put the application close function in the device back button. It can be done by overriding onBackPressed and then calling moveTaskToBack and finish method. Its syntax is given below − @Override public void onBackPressed() { moveTaskToBack(true); MainActivity2.this.finish(); } Apart from this setDisplayHomeAsUpEnabled method, there are other methods available in ActionBar API class. They are listed below − addTab(ActionBar.Tab tab, boolean setSelected) This method adds a tab for use in tabbed navigation mode getSelectedTab() This method returns the currently selected tab if in tabbed navigation mode and there is at least one tab present hide() This method hide the ActionBar if it is currently showing removeAllTabs() This method remove all tabs from the action bar and deselect the current tab selectTab(ActionBar.Tab tab) This method select the specified tab The below example demonstrates the use of Navigation. It crates a basic application that allows you to navigate within your application. To experiment with this example, you need to run this on an actual device or in an emulator. Here is the content of src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in=new Intent(MainActivity.this,second_main.class); startActivity(in); } }); } } Here is the content of src/second_main.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by Sairamkrishna on 4/6/2015. */ public class second_main extends Activity { WebView wv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity2); wv = (WebView) findViewById(R.id.webView); wv.setWebViewClient(new MyBrowser()); wv.getSettings().setLoadsImagesAutomatically(true); wv.getSettings().setJavaScriptEnabled(true); wv.loadUrl("http://www.tutorialspoint.com"); } private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } } Here is the content of activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:transitionGroup="true"> <TextView android:text="Navigation example" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:theme="@style/Base.TextAppearance.AppCompat" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="first page" android:id="@+id/button" android:layout_below="@+id/imageView" android:layout_alignRight="@+id/textView" android:layout_alignEnd="@+id/textView" android:layout_marginTop="61dp" android:layout_alignLeft="@+id/imageView" android:layout_alignStart="@+id/imageView" /> </RelativeLayout> Here is the content of activity_main_activity2.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:weightSum="1"> <WebView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/webView" android:layout_gravity="center_horizontal" android:layout_weight="1.03" /> </LinearLayout> Here is the content of Strings.xml. <resources> <string name="app_name">My Application</string> </resources> Here is the content of AndroidManifest.xml. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".second_main"></activity> </application> </manifest> Let's try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window− Now just press on button and the following screen will be shown to you. Second activity contains webview, it has redirected to tutorialspoint.com as shown below 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3787, "s": 3607, "text": "In this chapter, we will see that how you can provide navigation forward and backward between an application. We will first look at how to provide up navigation in an application." }, { "code": null, "e": 3911, "s": 3787, "text": "The up navigation will allow our application to move to previous activity from the next activity. It can be done like this." }, { "code": null, "e": 4129, "s": 3911, "text": "To implement Up navigation, the first step is to declare which activity is the appropriate parent for each activity. You can do it by specifying parentActivityName attribute in an activity. Its syntax is given below −" }, { "code": null, "e": 4192, "s": 4129, "text": "android:parentActivityName = \"com.example.test.MainActivity\" \n" }, { "code": null, "e": 4367, "s": 4192, "text": "After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method of the activity. This will enable the back button in the top action bar." }, { "code": null, "e": 4415, "s": 4367, "text": "getActionBar().setDisplayHomeAsUpEnabled(true);" }, { "code": null, "e": 4645, "s": 4415, "text": "The last thing you need to do is to override onOptionsItemSelected method. when the user presses it, your activity receives a call to onOptionsItemSelected(). The ID for the action is android.R.id.home.Its syntax is given below −" }, { "code": null, "e": 4836, "s": 4645, "text": "public boolean onOptionsItemSelected(MenuItem item) {\n \n switch (item.getItemId()) {\n case android.R.id.home:\n NavUtils.navigateUpFromSameTask(this);\n return true;\n }\t\n}" }, { "code": null, "e": 4993, "s": 4836, "text": "Since you have enabled your back button to navigate within your application, you might want to put the application close function in the device back button." }, { "code": null, "e": 5115, "s": 4993, "text": "It can be done by overriding onBackPressed and then calling moveTaskToBack and finish method. Its syntax is given below −" }, { "code": null, "e": 5215, "s": 5115, "text": "@Override\npublic void onBackPressed() {\n moveTaskToBack(true); \n MainActivity2.this.finish();\n}" }, { "code": null, "e": 5347, "s": 5215, "text": "Apart from this setDisplayHomeAsUpEnabled method, there are other methods available in ActionBar API class. They are listed below −" }, { "code": null, "e": 5394, "s": 5347, "text": "addTab(ActionBar.Tab tab, boolean setSelected)" }, { "code": null, "e": 5451, "s": 5394, "text": "This method adds a tab for use in tabbed navigation mode" }, { "code": null, "e": 5468, "s": 5451, "text": "getSelectedTab()" }, { "code": null, "e": 5582, "s": 5468, "text": "This method returns the currently selected tab if in tabbed navigation mode and there is at least one tab present" }, { "code": null, "e": 5589, "s": 5582, "text": "hide()" }, { "code": null, "e": 5647, "s": 5589, "text": "This method hide the ActionBar if it is currently showing" }, { "code": null, "e": 5663, "s": 5647, "text": "removeAllTabs()" }, { "code": null, "e": 5740, "s": 5663, "text": "This method remove all tabs from the action bar and deselect the current tab" }, { "code": null, "e": 5769, "s": 5740, "text": "selectTab(ActionBar.Tab tab)" }, { "code": null, "e": 5806, "s": 5769, "text": "This method select the specified tab" }, { "code": null, "e": 5943, "s": 5806, "text": "The below example demonstrates the use of Navigation. It crates a basic application that allows you to navigate within your application." }, { "code": null, "e": 6036, "s": 5943, "text": "To experiment with this example, you need to run this on an actual device or in an emulator." }, { "code": null, "e": 6082, "s": 6036, "text": "Here is the content of src/MainActivity.java." }, { "code": null, "e": 6786, "s": 6082, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\n\npublic class MainActivity extends Activity {\n Button b1;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1 = (Button) findViewById(R.id.button);\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent in=new Intent(MainActivity.this,second_main.class);\n startActivity(in);\n }\n });\n }\n}" }, { "code": null, "e": 6831, "s": 6786, "text": "Here is the content of src/second_main.java." }, { "code": null, "e": 7749, "s": 6831, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\n\n/**\n * Created by Sairamkrishna on 4/6/2015.\n*/\n\npublic class second_main extends Activity {\n WebView wv;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main_activity2);\n\n wv = (WebView) findViewById(R.id.webView);\n wv.setWebViewClient(new MyBrowser());\n wv.getSettings().setLoadsImagesAutomatically(true);\n wv.getSettings().setJavaScriptEnabled(true);\n wv.loadUrl(\"http://www.tutorialspoint.com\");\n }\n\n private class MyBrowser extends WebViewClient {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n }\n}" }, { "code": null, "e": 7791, "s": 7749, "text": "Here is the content of activity_main.xml." }, { "code": null, "e": 9731, "s": 7791, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\"\n android:transitionGroup=\"true\">\n \n <TextView android:text=\"Navigation example\" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:theme=\"@style/Base.TextAppearance.AppCompat\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"first page\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\"\n android:layout_marginTop=\"61dp\"\n android:layout_alignLeft=\"@+id/imageView\"\n android:layout_alignStart=\"@+id/imageView\" />\n\n</RelativeLayout>" }, { "code": null, "e": 9783, "s": 9731, "text": "Here is the content of activity_main_activity2.xml." }, { "code": null, "e": 10268, "s": 9783, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:weightSum=\"1\">\n \n <WebView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/webView\"\n android:layout_gravity=\"center_horizontal\"\n android:layout_weight=\"1.03\" />\n\n</LinearLayout>" }, { "code": null, "e": 10304, "s": 10268, "text": "Here is the content of Strings.xml." }, { "code": null, "e": 10380, "s": 10304, "text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>" }, { "code": null, "e": 10424, "s": 10380, "text": "Here is the content of AndroidManifest.xml." }, { "code": null, "e": 11270, "s": 10424, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <uses-permission android:name=\"android.permission.INTERNET\"></uses-permission>\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n\t\t\n <activity android:name=\".second_main\"></activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 11646, "s": 11270, "text": "Let's try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window−" }, { "code": null, "e": 11718, "s": 11646, "text": "Now just press on button and the following screen will be shown to you." }, { "code": null, "e": 11807, "s": 11718, "text": "Second activity contains webview, it has redirected to tutorialspoint.com as shown below" }, { "code": null, "e": 11842, "s": 11807, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11854, "s": 11842, "text": " Aditya Dua" }, { "code": null, "e": 11889, "s": 11854, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11903, "s": 11889, "text": " Sharad Kumar" }, { "code": null, "e": 11935, "s": 11903, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11952, "s": 11935, "text": " Abhilash Nelson" }, { "code": null, "e": 11987, "s": 11952, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12004, "s": 11987, "text": " Abhilash Nelson" }, { "code": null, "e": 12039, "s": 12004, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12056, "s": 12039, "text": " Abhilash Nelson" }, { "code": null, "e": 12089, "s": 12056, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 12106, "s": 12089, "text": " Abhilash Nelson" }, { "code": null, "e": 12113, "s": 12106, "text": " Print" }, { "code": null, "e": 12124, "s": 12113, "text": " Add Notes" } ]
How can we change the JButton text dynamically in Java?
A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate the MouseListener and KeyListener interfaces. By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.getText()) method of a JButton class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JButtonTextChangeTest extends JFrame { private JTextField textField; private JButton button; public JButtonTextChangeTest() { setTitle("JButtonTextChange Test"); setLayout(new FlowLayout()); textField = new JTextField(20); button = new JButton("Initial Button"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (!textField.getText().equals("")) button.setText(textField.getText()); } }); add(textField); add(button); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JButtonTextChangeTest(); } }
[ { "code": null, "e": 1670, "s": 1062, "text": "A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate the MouseListener and KeyListener interfaces. By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.getText()) method of a JButton class." }, { "code": null, "e": 2546, "s": 1670, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JButtonTextChangeTest extends JFrame {\n private JTextField textField;\n private JButton button;\n public JButtonTextChangeTest() {\n setTitle(\"JButtonTextChange Test\");\n setLayout(new FlowLayout());\n textField = new JTextField(20);\n button = new JButton(\"Initial Button\");\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n if (!textField.getText().equals(\"\"))\n button.setText(textField.getText());\n }\n });\n add(textField);\n add(button);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JButtonTextChangeTest();\n }\n}" } ]
How to create a dictionary with list comprehension in Python?
The zip() function which is an in-built function, provides a list of tuples containing elements at same indices from two lists. If two lists are keys and values respectively, this zip object can be used to constructed dictionary object using another built-in function dict() >>> L1=['a','b','c','d'] >>> L2=[1,2,3,4] >>> d1=dict(zip(L1,L2)) >>> d1 {'a': 1, 'b': 2, 'c': 3, 'd': 4} In Python 3.x a dictionary comprehension syntax is also available to construct dictionary from zip object >>> L2=[1,2,3,4] >>> L1=['a','b','c','d'] >>> d={k:v for (k,v) in zip(L1,L2)} >>> d {'a': 1, 'b': 2, 'c': 3, 'd': 4}
[ { "code": null, "e": 1339, "s": 1062, "text": "The zip() function which is an in-built function, provides a list of tuples containing elements at same indices from two lists. If two lists are keys and values respectively, this zip object can be used to constructed dictionary object using another built-in function dict()" }, { "code": null, "e": 1445, "s": 1339, "text": ">>> L1=['a','b','c','d']\n>>> L2=[1,2,3,4]\n>>> d1=dict(zip(L1,L2))\n>>> d1\n{'a': 1, 'b': 2, 'c': 3, 'd': 4}" }, { "code": null, "e": 1551, "s": 1445, "text": "In Python 3.x a dictionary comprehension syntax is also available to construct dictionary from zip object" }, { "code": null, "e": 1668, "s": 1551, "text": ">>> L2=[1,2,3,4]\n>>> L1=['a','b','c','d']\n>>> d={k:v for (k,v) in zip(L1,L2)}\n>>> d\n{'a': 1, 'b': 2, 'c': 3, 'd': 4}" } ]
Implementation of Naive Bayes Classifier with the use of Scikit-learn and ML.NET | by Robert Krzaczyński | Towards Data Science
When we think about machine learning, the first languages that come to mind are Python or R. This is understandable because they provide us with many possibilities to implement these algorithms. However, I work in C# daily and my attention has been attracted by the quite fresh library that is ML.NET. In this article, I would like to show how to implement the Naive Bayes Classifier in Python language using Scikit-learn, and also in C# with the use of the mentioned earlier ML.NET. Naive Bayes Classifier Naive Bayes classifier is a simple, probabilistic classifier that assumes mutual independence of independent variables. It is based on the Bayes’ theorem, which is expressed mathematically as follows: Dataset I used the wine quality dataset from the UCI Machine Learning Repository for the experiment. The analyzed data set has 11 features and 11 classes. The classes determine the quality of the wine in the numerical range 0–10. ML.NET The first step is to create a console application project. Then you have to download the ML.NET library from NuGet Packages. Now you can create classes that correspond to the attributes in the dataset. Created classes are shown in the listing: Then you can go on to load the dataset and divide it into a training set and a testing set. I have adopted a standard structure here, i.e. 80% of the data is a training set, while the rest is a testing set. var dataPath = "../../../winequality-red.csv";var ml = new MLContext();var DataView = ml.Data.LoadFromTextFile<Features>(dataPath, hasHeader: true, separatorChar: ';'); Now it is necessary to adapt the model structure to the standards adopted by the ML.NET library. This means that the property specifying the class must be called Label. The remaining attributes must be condensed under the name Features. var partitions = ml.Data.TrainTestSplit( DataView, testFraction: 0.3);var pipeline = ml.Transforms.Conversion.MapValueToKey(inputColumnName: "Quality", outputColumnName: "Label").Append(ml.Transforms.Concatenate("Features", "FixedAcidity", "VolatileAcidity","CitricAcid", "ResidualSugar", "Chlorides", "FreeSulfurDioxide", "TotalSulfurDioxide","Density", "Ph", "Sulphates", "Alcohol")).AppendCacheCheckpoint(ml); Once you have completed the previous steps, you can move on to creating a training pipeline. Here you choose a classifier in the form of Naive Bayes Classifier, to which you specify in the parameters the column names of the label and features. You indicate the property that means the predicted label too. var trainingPipeline = pipeline.Append(ml.MulticlassClassification.Trainers.NaiveBayes("Label","Features")).Append(ml.Transforms.Conversion.MapKeyToValue("PredictedLabel")); Finally, you can move on to training and testing the model. Everything is closed in two lines of code. var trainedModel = trainingPipeline.Fit(partitions.TrainSet);var testMetrics = ml.MulticlassClassification.Evaluate(trainedModel.Transform(partitions.TestSet)); Scikit-learn In the case of Python implementation, we also start with the handling of dataset files. We use numpy and pandas libraries for this. In the listing, you can see functions that are used to retrieve data from the file and create ndarray from it, which will then be used for the algorithm. from sklearn.naive_bayes import GaussianNBfrom common.import_data import ImportDatafrom sklearn.model_selection import train_test_splitif __name__ == "__main__":data_set = ImportData()x = data_set.import_all_data()y = data_set.import_columns(np.array(['quality'])) The next step is to create a training and test set. In this case, we also use a 20% division for the test set and 80% for the training set. I used the train_test_split function, which comes from the library sklearn. X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) Now you can move on to the Naive Bayes Classifier. In this case, training and testing are also closed in a few lines of code. NB = GaussianNB()NB.fit(X_train, y_train.ravel())predictions = NB.predict(X_test)print('Scores from each Iteration: ', NB.score(X_test, y_test)) Results and summary The accuracy of the Naive Bayes Classifier for Scikit-learn implementation was 56.5%, while for ML.NET it was 41.5%. The difference may be due to other ways of algorithm implementation, but based on the accuracy alone we cannot say which is better. However, we can say that a promising alternative to the implementation of machine learning algorithms is beginning to emerge, which is the use of C# and ML.NET.
[ { "code": null, "e": 366, "s": 171, "text": "When we think about machine learning, the first languages that come to mind are Python or R. This is understandable because they provide us with many possibilities to implement these algorithms." }, { "code": null, "e": 655, "s": 366, "text": "However, I work in C# daily and my attention has been attracted by the quite fresh library that is ML.NET. In this article, I would like to show how to implement the Naive Bayes Classifier in Python language using Scikit-learn, and also in C# with the use of the mentioned earlier ML.NET." }, { "code": null, "e": 678, "s": 655, "text": "Naive Bayes Classifier" }, { "code": null, "e": 879, "s": 678, "text": "Naive Bayes classifier is a simple, probabilistic classifier that assumes mutual independence of independent variables. It is based on the Bayes’ theorem, which is expressed mathematically as follows:" }, { "code": null, "e": 887, "s": 879, "text": "Dataset" }, { "code": null, "e": 1109, "s": 887, "text": "I used the wine quality dataset from the UCI Machine Learning Repository for the experiment. The analyzed data set has 11 features and 11 classes. The classes determine the quality of the wine in the numerical range 0–10." }, { "code": null, "e": 1116, "s": 1109, "text": "ML.NET" }, { "code": null, "e": 1360, "s": 1116, "text": "The first step is to create a console application project. Then you have to download the ML.NET library from NuGet Packages. Now you can create classes that correspond to the attributes in the dataset. Created classes are shown in the listing:" }, { "code": null, "e": 1567, "s": 1360, "text": "Then you can go on to load the dataset and divide it into a training set and a testing set. I have adopted a standard structure here, i.e. 80% of the data is a training set, while the rest is a testing set." }, { "code": null, "e": 1736, "s": 1567, "text": "var dataPath = \"../../../winequality-red.csv\";var ml = new MLContext();var DataView = ml.Data.LoadFromTextFile<Features>(dataPath, hasHeader: true, separatorChar: ';');" }, { "code": null, "e": 1973, "s": 1736, "text": "Now it is necessary to adapt the model structure to the standards adopted by the ML.NET library. This means that the property specifying the class must be called Label. The remaining attributes must be condensed under the name Features." }, { "code": null, "e": 2386, "s": 1973, "text": "var partitions = ml.Data.TrainTestSplit( DataView, testFraction: 0.3);var pipeline = ml.Transforms.Conversion.MapValueToKey(inputColumnName: \"Quality\", outputColumnName: \"Label\").Append(ml.Transforms.Concatenate(\"Features\", \"FixedAcidity\", \"VolatileAcidity\",\"CitricAcid\", \"ResidualSugar\", \"Chlorides\", \"FreeSulfurDioxide\", \"TotalSulfurDioxide\",\"Density\", \"Ph\", \"Sulphates\", \"Alcohol\")).AppendCacheCheckpoint(ml);" }, { "code": null, "e": 2692, "s": 2386, "text": "Once you have completed the previous steps, you can move on to creating a training pipeline. Here you choose a classifier in the form of Naive Bayes Classifier, to which you specify in the parameters the column names of the label and features. You indicate the property that means the predicted label too." }, { "code": null, "e": 2866, "s": 2692, "text": "var trainingPipeline = pipeline.Append(ml.MulticlassClassification.Trainers.NaiveBayes(\"Label\",\"Features\")).Append(ml.Transforms.Conversion.MapKeyToValue(\"PredictedLabel\"));" }, { "code": null, "e": 2969, "s": 2866, "text": "Finally, you can move on to training and testing the model. Everything is closed in two lines of code." }, { "code": null, "e": 3130, "s": 2969, "text": "var trainedModel = trainingPipeline.Fit(partitions.TrainSet);var testMetrics = ml.MulticlassClassification.Evaluate(trainedModel.Transform(partitions.TestSet));" }, { "code": null, "e": 3143, "s": 3130, "text": "Scikit-learn" }, { "code": null, "e": 3429, "s": 3143, "text": "In the case of Python implementation, we also start with the handling of dataset files. We use numpy and pandas libraries for this. In the listing, you can see functions that are used to retrieve data from the file and create ndarray from it, which will then be used for the algorithm." }, { "code": null, "e": 3694, "s": 3429, "text": "from sklearn.naive_bayes import GaussianNBfrom common.import_data import ImportDatafrom sklearn.model_selection import train_test_splitif __name__ == \"__main__\":data_set = ImportData()x = data_set.import_all_data()y = data_set.import_columns(np.array(['quality']))" }, { "code": null, "e": 3910, "s": 3694, "text": "The next step is to create a training and test set. In this case, we also use a 20% division for the test set and 80% for the training set. I used the train_test_split function, which comes from the library sklearn." }, { "code": null, "e": 3983, "s": 3910, "text": "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)" }, { "code": null, "e": 4109, "s": 3983, "text": "Now you can move on to the Naive Bayes Classifier. In this case, training and testing are also closed in a few lines of code." }, { "code": null, "e": 4254, "s": 4109, "text": "NB = GaussianNB()NB.fit(X_train, y_train.ravel())predictions = NB.predict(X_test)print('Scores from each Iteration: ', NB.score(X_test, y_test))" }, { "code": null, "e": 4274, "s": 4254, "text": "Results and summary" } ]
Primary Keys and Group By’s — A Brief SQL Investigation | by Jeremy Chow | Towards Data Science
Today an acquaintance asked me an interesting SQL question, but not in the typical query sense; his question revolved more around an understanding of the underlying framework of SQL. Here is the context: The exercise comes from this PostgreSQL exercise page and has the following schema: The SQL question the website is asking isn’t important, but their posted solution is this: SELECT facs.name AS name, facs.initialoutlay/((sum( CASE WHEN memid = 0 THEN slots * facs.guestcost ELSE slots * membercost END)/3) - facs.monthlymaintenance) AS months FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.facid ORDER BY name; My friend tried switching the line GROUP BY facs.facid to GROUP BY facs.name, which broke the query with the message: column "facs.initialoutlay" must appear in the GROUP BY clause or be used in an aggregate function The question my friend asked was : Why does the above query not work with the lines switched, even if both columns are both unique to each row? If you know the answer, congrats, you should answer my question posted at the end! If you’d like to skip to the answer, scroll to ‘The Answer’ section of this article. Otherwise, let’s go into the thought process of solving this question! First, let’s check for the obvious — Are those columns really unique, and are there multiple combinations of the columns used in our query (name, facid, initialoutlay, monthlymaintenance)? To check this we look at distinct combinations of those columns in the facilities table. SELECT DISTINCT facs.name as name, facs.facid, facs.initialoutlay, facs.monthlymaintenance FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facidORDER BY facid;Output:╔═════════════════╦═══════╦═══════════════╦════════════════════╗║ name ║ facid ║ initialoutlay ║ monthlymaintenance ║╠═════════════════╬═══════╬═══════════════╬════════════════════╣║ Tennis Court 1 ║ 0 ║ 10000 ║ 200 ║║ Tennis Court 2 ║ 1 ║ 8000 ║ 200 ║║ Badminton Court ║ 2 ║ 4000 ║ 50 ║║ Table Tennis ║ 3 ║ 320 ║ 10 ║║ Massage Room 1 ║ 4 ║ 4000 ║ 3000 ║║ Massage Room 2 ║ 5 ║ 4000 ║ 3000 ║║ Squash Court ║ 6 ║ 5000 ║ 80 ║║ Snooker Table ║ 7 ║ 450 ║ 15 ║║ Pool Table ║ 8 ║ 400 ║ 15 ║╚═════════════════╩═══════╩═══════════════╩════════════════════╝ Name and facid are both unique to each row and 1 to 1, and each pair only has one initialoutlay and monthlymaintenance value. Intuitively, grouping by either of those two columns should be functionally equivalent to grouping by the other. So why doesn’t grouping by name work for this query? As you may intuit if you’re familiar with SQL, this is a primary key issue. For those that don’t know, a primary key is the value that uniquely identifies each row of a table, and it can never be ‘NULL’ for a row. But how do we find the designated primary key of a table? A quick google search gives us the following code from the PostgreSQL wiki. Running this on the website’s query section gives the following: SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_typeFROM pg_index iJOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)WHERE i.indrelid = 'cd.facilities'::regclassAND i.indisprimary;Output:╔═════════╦═══════════╗║ attname ║ data_type ║╠═════════╬═══════════╣║ facid ║ integer ║╚═════════╩═══════════╝ So facid is a primary key of the facilities table! Now we’ve confirmed the probable cause, but what is the reason grouping by the primary key allows you to throw in columns with no aggregate function like we do with facs.initialoutlay and facs.monthlymaintenance? SELECT facs.name AS name, facs.initialoutlay/((sum( /* <=========== */ CASE WHEN memid = 0 THEN slots * facs.guestcost ELSE slots * membercost END)/3) - facs.monthlymaintenance) AS months /* <=========== */FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.facid ORDER BY name;/* Shouldn't these two columns be inside of an aggregation? */ To answer this question we look at the PostgreSQL help docs, specifically for GROUP BY : When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column. As a Stack Overflow user Tony L. puts it: Grouping by primary key results in a single record in each group which is logically the same as not grouping at all / grouping by all columns, therefore we can select all other columns. Essentially this means grouping by the primary key of a table results in no change in rows to that table, therefore if we group by the primary key of a table, we can call on all columns of that table with no aggregate function. Let’s reiterate: Given that we’re looking at one table, grouping by its primary key is the same as grouping by everything, which is the same as not grouping at all — each of these approaches will result in one group per row. Once you understand that, you understand the crux of this problem. Because of this, queries like this work: 1. Group by everything:SELECT *FROM cd.facilities fGROUP BY facid, name, membercost, guestcost, initialoutlay, monthlymaintenanceLIMIT 5OUTPUT: which is functionally identical to 2. Don't group by anythingSELECT * FROM cd.facilities fLIMIT 5and 3. Group by primary key but don't aggregateSELECT * FROM cd.facilities fGROUP BY facidLIMIT 5 These all output the same values! Now we have our solution. The reason the first query works is simply that facid is the primary key and name is not. Despite them both being unique to each row, the table facilities was created with facid as the primary key, thus it gets special treatment when used in a group by as covered above. Some alternative solutions to what they posted would be: 1. Group by name then aggregate everything elseSELECT facs.name as name, AVG(facs.initialoutlay)/((sum(case when memid = 0 then slots * facs.guestcost else slots * membercost end)/3) - AVG(facs.monthlymaintenance) as months FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.nameORDER BY name;Why this works:Because facs.name is unique to each row in the facilities table just as facid was, we group by facs.name then add AVG calls around previously unaggregated facilities columns.2. Group by all facility columns used in the select statementSELECT facs.name as name, facs.initialoutlay/((sum(case when memid = 0 then slots * facs.guestcost else slots * membercost end)/3) - facs.monthlymaintenance) as months from cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.name, facs.initialoutlay, facs.guestcost, facs.monthlymaintenance ORDER BY name;Why this works:This includes all the values used in the SELECT statement in the GROUP BY, which is the normal GROUP BY logic and syntax. That concludes the main question, but if you are interested in exploring more quirks, I ran into the following issue while solving the posted problem. If any of you know why feel free to ping me or leave a comment! /* This works (manually lists all columns in the group by)*/SELECT *FROM cd.facilities fGROUP BY facid, name, membercost, guestcost, initialoutlay, monthlymaintenanceLIMIT 5/* This does not (selecting all columns using f.*) */SELECT *FROM cd.facilities fGROUP BY f.*LIMIT 5 Thanks for reading, I hope this article helped you out! Feel free to check out my other tutorials and stay posted for new ones in the future!
[ { "code": null, "e": 376, "s": 172, "text": "Today an acquaintance asked me an interesting SQL question, but not in the typical query sense; his question revolved more around an understanding of the underlying framework of SQL. Here is the context:" }, { "code": null, "e": 460, "s": 376, "text": "The exercise comes from this PostgreSQL exercise page and has the following schema:" }, { "code": null, "e": 551, "s": 460, "text": "The SQL question the website is asking isn’t important, but their posted solution is this:" }, { "code": null, "e": 842, "s": 551, "text": "SELECT facs.name AS name, facs.initialoutlay/((sum( CASE WHEN memid = 0 THEN slots * facs.guestcost ELSE slots * membercost END)/3) - facs.monthlymaintenance) AS months FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.facid ORDER BY name;" }, { "code": null, "e": 960, "s": 842, "text": "My friend tried switching the line GROUP BY facs.facid to GROUP BY facs.name, which broke the query with the message:" }, { "code": null, "e": 1059, "s": 960, "text": "column \"facs.initialoutlay\" must appear in the GROUP BY clause or be used in an aggregate function" }, { "code": null, "e": 1094, "s": 1059, "text": "The question my friend asked was :" }, { "code": null, "e": 1203, "s": 1094, "text": "Why does the above query not work with the lines switched, even if both columns are both unique to each row?" }, { "code": null, "e": 1442, "s": 1203, "text": "If you know the answer, congrats, you should answer my question posted at the end! If you’d like to skip to the answer, scroll to ‘The Answer’ section of this article. Otherwise, let’s go into the thought process of solving this question!" }, { "code": null, "e": 1720, "s": 1442, "text": "First, let’s check for the obvious — Are those columns really unique, and are there multiple combinations of the columns used in our query (name, facid, initialoutlay, monthlymaintenance)? To check this we look at distinct combinations of those columns in the facilities table." }, { "code": null, "e": 2755, "s": 1720, "text": "SELECT DISTINCT facs.name as name, facs.facid, facs.initialoutlay, facs.monthlymaintenance FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facidORDER BY facid;Output:╔═════════════════╦═══════╦═══════════════╦════════════════════╗║ name ║ facid ║ initialoutlay ║ monthlymaintenance ║╠═════════════════╬═══════╬═══════════════╬════════════════════╣║ Tennis Court 1 ║ 0 ║ 10000 ║ 200 ║║ Tennis Court 2 ║ 1 ║ 8000 ║ 200 ║║ Badminton Court ║ 2 ║ 4000 ║ 50 ║║ Table Tennis ║ 3 ║ 320 ║ 10 ║║ Massage Room 1 ║ 4 ║ 4000 ║ 3000 ║║ Massage Room 2 ║ 5 ║ 4000 ║ 3000 ║║ Squash Court ║ 6 ║ 5000 ║ 80 ║║ Snooker Table ║ 7 ║ 450 ║ 15 ║║ Pool Table ║ 8 ║ 400 ║ 15 ║╚═════════════════╩═══════╩═══════════════╩════════════════════╝" }, { "code": null, "e": 3047, "s": 2755, "text": "Name and facid are both unique to each row and 1 to 1, and each pair only has one initialoutlay and monthlymaintenance value. Intuitively, grouping by either of those two columns should be functionally equivalent to grouping by the other. So why doesn’t grouping by name work for this query?" }, { "code": null, "e": 3319, "s": 3047, "text": "As you may intuit if you’re familiar with SQL, this is a primary key issue. For those that don’t know, a primary key is the value that uniquely identifies each row of a table, and it can never be ‘NULL’ for a row. But how do we find the designated primary key of a table?" }, { "code": null, "e": 3460, "s": 3319, "text": "A quick google search gives us the following code from the PostgreSQL wiki. Running this on the website’s query section gives the following:" }, { "code": null, "e": 3831, "s": 3460, "text": "SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_typeFROM pg_index iJOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)WHERE i.indrelid = 'cd.facilities'::regclassAND i.indisprimary;Output:╔═════════╦═══════════╗║ attname ║ data_type ║╠═════════╬═══════════╣║ facid ║ integer ║╚═════════╩═══════════╝" }, { "code": null, "e": 4095, "s": 3831, "text": "So facid is a primary key of the facilities table! Now we’ve confirmed the probable cause, but what is the reason grouping by the primary key allows you to throw in columns with no aggregate function like we do with facs.initialoutlay and facs.monthlymaintenance?" }, { "code": null, "e": 4491, "s": 4095, "text": "SELECT facs.name AS name, facs.initialoutlay/((sum( /* <=========== */ CASE WHEN memid = 0 THEN slots * facs.guestcost ELSE slots * membercost END)/3) - facs.monthlymaintenance) AS months /* <=========== */FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.facid ORDER BY name;/* Shouldn't these two columns be inside of an aggregation? */" }, { "code": null, "e": 4580, "s": 4491, "text": "To answer this question we look at the PostgreSQL help docs, specifically for GROUP BY :" }, { "code": null, "e": 5074, "s": 4580, "text": "When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column." }, { "code": null, "e": 5116, "s": 5074, "text": "As a Stack Overflow user Tony L. puts it:" }, { "code": null, "e": 5302, "s": 5116, "text": "Grouping by primary key results in a single record in each group which is logically the same as not grouping at all / grouping by all columns, therefore we can select all other columns." }, { "code": null, "e": 5530, "s": 5302, "text": "Essentially this means grouping by the primary key of a table results in no change in rows to that table, therefore if we group by the primary key of a table, we can call on all columns of that table with no aggregate function." }, { "code": null, "e": 5822, "s": 5530, "text": "Let’s reiterate: Given that we’re looking at one table, grouping by its primary key is the same as grouping by everything, which is the same as not grouping at all — each of these approaches will result in one group per row. Once you understand that, you understand the crux of this problem." }, { "code": null, "e": 5863, "s": 5822, "text": "Because of this, queries like this work:" }, { "code": null, "e": 6007, "s": 5863, "text": "1. Group by everything:SELECT *FROM cd.facilities fGROUP BY facid, name, membercost, guestcost, initialoutlay, monthlymaintenanceLIMIT 5OUTPUT:" }, { "code": null, "e": 6042, "s": 6007, "text": "which is functionally identical to" }, { "code": null, "e": 6202, "s": 6042, "text": "2. Don't group by anythingSELECT * FROM cd.facilities fLIMIT 5and 3. Group by primary key but don't aggregateSELECT * FROM cd.facilities fGROUP BY facidLIMIT 5" }, { "code": null, "e": 6262, "s": 6202, "text": "These all output the same values! Now we have our solution." }, { "code": null, "e": 6533, "s": 6262, "text": "The reason the first query works is simply that facid is the primary key and name is not. Despite them both being unique to each row, the table facilities was created with facid as the primary key, thus it gets special treatment when used in a group by as covered above." }, { "code": null, "e": 6590, "s": 6533, "text": "Some alternative solutions to what they posted would be:" }, { "code": null, "e": 7669, "s": 6590, "text": "1. Group by name then aggregate everything elseSELECT facs.name as name, AVG(facs.initialoutlay)/((sum(case when memid = 0 then slots * facs.guestcost else slots * membercost end)/3) - AVG(facs.monthlymaintenance) as months FROM cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.nameORDER BY name;Why this works:Because facs.name is unique to each row in the facilities table just as facid was, we group by facs.name then add AVG calls around previously unaggregated facilities columns.2. Group by all facility columns used in the select statementSELECT facs.name as name, facs.initialoutlay/((sum(case when memid = 0 then slots * facs.guestcost else slots * membercost end)/3) - facs.monthlymaintenance) as months from cd.bookings bks INNER JOIN cd.facilities facs ON bks.facid = facs.facid GROUP BY facs.name, facs.initialoutlay, facs.guestcost, facs.monthlymaintenance ORDER BY name;Why this works:This includes all the values used in the SELECT statement in the GROUP BY, which is the normal GROUP BY logic and syntax." }, { "code": null, "e": 7884, "s": 7669, "text": "That concludes the main question, but if you are interested in exploring more quirks, I ran into the following issue while solving the posted problem. If any of you know why feel free to ping me or leave a comment!" }, { "code": null, "e": 8158, "s": 7884, "text": "/* This works (manually lists all columns in the group by)*/SELECT *FROM cd.facilities fGROUP BY facid, name, membercost, guestcost, initialoutlay, monthlymaintenanceLIMIT 5/* This does not (selecting all columns using f.*) */SELECT *FROM cd.facilities fGROUP BY f.*LIMIT 5" } ]
Excel Formulas
A formula in Excel is used to do mathematical calculations. Formulas always start with the equal sign (=) typed in the cell, followed by your calculation. Formulas can be used for calculations such as: =1+1 =2*2 =4/2=2 It can also be used to calculate values using cells as input. Let's have a look at an example. Type or copy the following values: Now we want to do a calculation with those values. Step by step: Select C1 and type (=) Right click A1 Type (+) Right click A2 Press enter Select C1 and type (=) Right click A1 Type (+) Right click A2 Press enter You got it! You have successfully calculated A1(2) + A2(4) = C1(6). Note: Using cells to make calculations is an important part of Excel and you will use this alot as you learn. Lets change from addition to multiplication, by replacing the (+) with a (*). It should now be =A1*A2, press enter to see what happens. You got C1(8), right? Well done! Excel is great in this way. It allows you to add values to cells and make you do calculations on them. Now, try to change the multiplication (*) to subtraction (-) and dividing (/). Delete all values in the sheet after you have tried the different combinations. Let's add new data for the next example, where we will help the Pokemon trainers to count their Pokeballs. Type or copy the following values: The data explained: Column A: Pokemon Trainers Row 1: Types of Pokeballs Range B2:D4: Amount of Pokeballs, Great balls and Ultra balls Note: It is important to practice reading data to understand its context. In this example you should focus on the trainers and their Pokeballs, which have three different types: Pokeball, Great ball and Ultra ball. Let's help Iva to count her Pokeballs. You find Iva in A2(Iva). The values in row 2 B2(2), C2(3), D2(1) belong to her. Count the Pokeballs, step by step: Select cell E2 and type (=) Right click B2 Type (+) Right click C2 Type (+) Right click D2 Hit enter Select cell E2 and type (=) Right click B2 Type (+) Right click C2 Type (+) Right click D2 Hit enter Did you get the value E2(6)? Good job! You have helped Iva to count her Pokeballs. Now, let's help Liam and Adora with counting theirs. Do you remember the fill function that we learned about earlier? It can be used to continue calculations sidewards, downwards and upwards. Let's try it! Lets use the fill function to continue the formula, step by step: Select E2 Fill E2:E4 Select E2 Fill E2:E4 That is cool, right? The fill function continued the calculation that you used for Iva and was able to understand that you wanted to count the cells in the next rows as well. Now we have counted the Pokeballs for all three; Iva(6), Liam(12) and Adora(15). Let's see how many Pokeballs Iva, Liam and Adora have in total. The total is called SUM in Excel. There are two ways to calculate the SUM. Adding cells SUM function Excel has many pre-made functions available for you to use. The SUM function is one of the most used ones. You will learn more about functions in a later chapter. Let's try both approaches. Note: You can navigate to the cells with your keyboard arrows instead of right clicking them. Try it! Sum by adding cells, step by step: Select cell E5, and type = Left click E2 Type (+) Left click E3 Type (+) Left click E4 Hit enter Select cell E5, and type = Left click E2 Type (+) Left click E3 Type (+) Left click E4 Hit enter The result is E5(33). Let's try the SUM function. Remember to delete the values that you currently have in E5. SUM function, step by step: Type E5(=) Write SUM Double click SUM in the menu Mark the range E2:E4 Hit enter Type E5(=) Write SUM Double click SUM in the menu Mark the range E2:E4 Hit enter Great job! You have successfully calculated the SUM using the SUM function. Iva, Liam and Adora have 33 Pokeballs in total. Let's change a value to see what happens. Type B2(7): The value in cell B2 was changed from 2 to 7. Notice that the formulas are doing calculations when we change the value in the cells, and the SUM is updated from 33 to 38. It allows us to change values that are used by the formulas, and the calculations remain. Values used in formulas can be typed directly and by using cells. The formula updates the result if you change the value of cells, which is used in the formula. The fill function can be used to continue your formulas upwards, downwards and sidewards. Excel has pre-built functions, such as SUM. In the next chapter you will learn about relative and absolute references. Complete the Excel formula: 8+10 Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 155, "s": 0, "text": "A formula in Excel is used to do mathematical calculations. Formulas always start with the equal sign (=) typed in the cell, followed by your calculation." }, { "code": null, "e": 202, "s": 155, "text": "Formulas can be used for calculations such as:" }, { "code": null, "e": 207, "s": 202, "text": "=1+1" }, { "code": null, "e": 212, "s": 207, "text": "=2*2" }, { "code": null, "e": 219, "s": 212, "text": "=4/2=2" }, { "code": null, "e": 282, "s": 219, "text": "It can also be used to calculate values using cells as input. " }, { "code": null, "e": 315, "s": 282, "text": "Let's have a look at an example." }, { "code": null, "e": 350, "s": 315, "text": "Type or copy the following values:" }, { "code": null, "e": 401, "s": 350, "text": "Now we want to do a calculation with those values." }, { "code": null, "e": 415, "s": 401, "text": "Step by step:" }, { "code": null, "e": 491, "s": 415, "text": "\nSelect C1 and type (=)\nRight click A1\nType (+)\nRight click A2\nPress enter\n" }, { "code": null, "e": 514, "s": 491, "text": "Select C1 and type (=)" }, { "code": null, "e": 529, "s": 514, "text": "Right click A1" }, { "code": null, "e": 538, "s": 529, "text": "Type (+)" }, { "code": null, "e": 553, "s": 538, "text": "Right click A2" }, { "code": null, "e": 565, "s": 553, "text": "Press enter" }, { "code": null, "e": 633, "s": 565, "text": "You got it! You have successfully calculated A1(2) + A2(4) = C1(6)." }, { "code": null, "e": 743, "s": 633, "text": "Note: Using cells to make calculations is an important part of Excel and you will use this alot as you learn." }, { "code": null, "e": 880, "s": 743, "text": "Lets change from addition to multiplication, by replacing the (+) with a (*). It should now be =A1*A2, press enter to see what happens. " }, { "code": null, "e": 913, "s": 880, "text": "You got C1(8), right? Well done!" }, { "code": null, "e": 1016, "s": 913, "text": "Excel is great in this way. It allows you to add values to cells and make you do calculations on them." }, { "code": null, "e": 1096, "s": 1016, "text": "Now, try to change the multiplication (*) to subtraction (-) and dividing (/). " }, { "code": null, "e": 1176, "s": 1096, "text": "Delete all values in the sheet after you have tried the different combinations." }, { "code": null, "e": 1283, "s": 1176, "text": "Let's add new data for the next example, where we will help the Pokemon trainers to count their Pokeballs." }, { "code": null, "e": 1318, "s": 1283, "text": "Type or copy the following values:" }, { "code": null, "e": 1338, "s": 1318, "text": "The data explained:" }, { "code": null, "e": 1365, "s": 1338, "text": "Column A: Pokemon Trainers" }, { "code": null, "e": 1391, "s": 1365, "text": "Row 1: Types of Pokeballs" }, { "code": null, "e": 1453, "s": 1391, "text": "Range B2:D4: Amount of Pokeballs, Great balls and Ultra balls" }, { "code": null, "e": 1669, "s": 1453, "text": "Note: It is important to practice reading data to understand its context. In this example you should focus on the trainers and their Pokeballs, which have three different types: Pokeball, Great ball and Ultra ball.\n" }, { "code": null, "e": 1788, "s": 1669, "text": "Let's help Iva to count her Pokeballs. You find Iva in A2(Iva). The values in row 2 B2(2), C2(3), D2(1) belong to her." }, { "code": null, "e": 1823, "s": 1788, "text": "Count the Pokeballs, step by step:" }, { "code": null, "e": 1926, "s": 1823, "text": "\nSelect cell E2 and type (=)\nRight click B2\nType (+)\nRight click C2\nType (+)\nRight click D2\nHit enter\n" }, { "code": null, "e": 1954, "s": 1926, "text": "Select cell E2 and type (=)" }, { "code": null, "e": 1969, "s": 1954, "text": "Right click B2" }, { "code": null, "e": 1978, "s": 1969, "text": "Type (+)" }, { "code": null, "e": 1993, "s": 1978, "text": "Right click C2" }, { "code": null, "e": 2002, "s": 1993, "text": "Type (+)" }, { "code": null, "e": 2017, "s": 2002, "text": "Right click D2" }, { "code": null, "e": 2027, "s": 2017, "text": "Hit enter" }, { "code": null, "e": 2110, "s": 2027, "text": "Did you get the value E2(6)? Good job! You have helped Iva to count her Pokeballs." }, { "code": null, "e": 2163, "s": 2110, "text": "Now, let's help Liam and Adora with counting theirs." }, { "code": null, "e": 2316, "s": 2163, "text": "Do you remember the fill function that we learned about earlier? It can be used to continue calculations sidewards, downwards and upwards. Let's try it!" }, { "code": null, "e": 2382, "s": 2316, "text": "Lets use the fill function to continue the formula, step by step:" }, { "code": null, "e": 2405, "s": 2382, "text": "\nSelect E2\nFill E2:E4\n" }, { "code": null, "e": 2415, "s": 2405, "text": "Select E2" }, { "code": null, "e": 2426, "s": 2415, "text": "Fill E2:E4" }, { "code": null, "e": 2602, "s": 2426, "text": "That is cool, right? The fill function continued the calculation that you used for Iva and was able to understand that you wanted to count the cells in the next rows as well. " }, { "code": null, "e": 2684, "s": 2602, "text": "Now we have counted the Pokeballs for all three; Iva(6), Liam(12) and Adora(15). " }, { "code": null, "e": 2748, "s": 2684, "text": "Let's see how many Pokeballs Iva, Liam and Adora have in total." }, { "code": null, "e": 2782, "s": 2748, "text": "The total is called SUM in Excel." }, { "code": null, "e": 2824, "s": 2782, "text": "There are two ways to calculate the SUM. " }, { "code": null, "e": 2837, "s": 2824, "text": "Adding cells" }, { "code": null, "e": 2850, "s": 2837, "text": "SUM function" }, { "code": null, "e": 3013, "s": 2850, "text": "Excel has many pre-made functions available for you to use. The SUM\nfunction is one of the most used ones. You will learn more about functions in a later chapter." }, { "code": null, "e": 3040, "s": 3013, "text": "Let's try both approaches." }, { "code": null, "e": 3142, "s": 3040, "text": "Note: You can navigate to the cells with your keyboard arrows instead of right clicking them. Try it!" }, { "code": null, "e": 3177, "s": 3142, "text": "Sum by adding cells, step by step:" }, { "code": null, "e": 3276, "s": 3177, "text": "\nSelect cell E5, and type =\nLeft click E2\nType (+)\nLeft click E3\nType (+)\nLeft click E4\nHit enter\n" }, { "code": null, "e": 3303, "s": 3276, "text": "Select cell E5, and type =" }, { "code": null, "e": 3317, "s": 3303, "text": "Left click E2" }, { "code": null, "e": 3326, "s": 3317, "text": "Type (+)" }, { "code": null, "e": 3340, "s": 3326, "text": "Left click E3" }, { "code": null, "e": 3349, "s": 3340, "text": "Type (+)" }, { "code": null, "e": 3363, "s": 3349, "text": "Left click E4" }, { "code": null, "e": 3373, "s": 3363, "text": "Hit enter" }, { "code": null, "e": 3395, "s": 3373, "text": "The result is E5(33)." }, { "code": null, "e": 3424, "s": 3395, "text": "Let's try the SUM function. " }, { "code": null, "e": 3485, "s": 3424, "text": "Remember to delete the values that you currently have in E5." }, { "code": null, "e": 3513, "s": 3485, "text": "SUM function, step by step:" }, { "code": null, "e": 3596, "s": 3513, "text": "\nType E5(=)\nWrite SUM\nDouble click SUM in the menu\nMark the range E2:E4\nHit enter\n" }, { "code": null, "e": 3607, "s": 3596, "text": "Type E5(=)" }, { "code": null, "e": 3617, "s": 3607, "text": "Write SUM" }, { "code": null, "e": 3646, "s": 3617, "text": "Double click SUM in the menu" }, { "code": null, "e": 3667, "s": 3646, "text": "Mark the range E2:E4" }, { "code": null, "e": 3677, "s": 3667, "text": "Hit enter" }, { "code": null, "e": 3753, "s": 3677, "text": "Great job! You have successfully calculated the SUM using the SUM function." }, { "code": null, "e": 3801, "s": 3753, "text": "Iva, Liam and Adora have 33 Pokeballs in total." }, { "code": null, "e": 3855, "s": 3801, "text": "Let's change a value to see what happens. Type B2(7):" }, { "code": null, "e": 4117, "s": 3855, "text": "The value in cell B2 was changed from 2 to 7. Notice that the formulas are doing calculations when we change the value in the cells, and the SUM is updated from 33 to 38. It allows us to change values that are used by the formulas, and the calculations remain.\n" }, { "code": null, "e": 4413, "s": 4117, "text": "Values used in formulas can be typed directly and by using cells. The formula updates the result if you change the value of cells, which is used in the formula. The fill function can be used to continue your formulas upwards, downwards and sidewards. Excel has pre-built functions, such as SUM. " }, { "code": null, "e": 4488, "s": 4413, "text": "In the next chapter you will learn about relative and absolute references." }, { "code": null, "e": 4516, "s": 4488, "text": "Complete the Excel formula:" }, { "code": null, "e": 4522, "s": 4516, "text": "8+10\n" }, { "code": null, "e": 4541, "s": 4522, "text": "Start the Exercise" }, { "code": null, "e": 4574, "s": 4541, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 4616, "s": 4574, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 4723, "s": 4616, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4742, "s": 4723, "text": "help@w3schools.com" } ]
Java String startsWith() method example.
The startsWith(String prefix, int toffset) method of the String class tests if the substring of this string beginning at the specified index starts with the specified prefix. import java.lang.*; public class StringDemo { public static void main(String[] args) { String str = "www.tutorialspoint.com"; System.out.println(str); //The start string to be checked String startstr1 = "tutorialspoint"; String startstr2 = "tutorialspoint"; //Checks that string starts with given substring and starting index boolean retval1 = str.startsWith(startstr1); boolean retval2 = str.startsWith(startstr2, 4); //Prints true if the string starts with given substring System.out.println("starts with " + startstr1 + " ? " + retval1); System.out.println("string " + startstr2 + " starting from index 4 ? " + retval2); } } www.tutorialspoint.com starts with tutorialspoint ? false string tutorialspoint starting from index 4 ? true
[ { "code": null, "e": 1237, "s": 1062, "text": "The startsWith(String prefix, int toffset) method of the String class tests if the substring of this string beginning at the specified index starts with the specified prefix." }, { "code": null, "e": 1941, "s": 1237, "text": "import java.lang.*;\n\npublic class StringDemo {\n public static void main(String[] args) {\n String str = \"www.tutorialspoint.com\";\n System.out.println(str);\n\n //The start string to be checked\n String startstr1 = \"tutorialspoint\";\n String startstr2 = \"tutorialspoint\";\n\n //Checks that string starts with given substring and starting index\n boolean retval1 = str.startsWith(startstr1);\n boolean retval2 = str.startsWith(startstr2, 4);\n\n //Prints true if the string starts with given substring\n System.out.println(\"starts with \" + startstr1 + \" ? \" + retval1);\n System.out.println(\"string \" + startstr2 + \" starting from index 4 ? \" + retval2);\n }\n}" }, { "code": null, "e": 2051, "s": 1941, "text": "www.tutorialspoint.com\nstarts with tutorialspoint ? false\nstring tutorialspoint starting from index 4 ? true\n" } ]
Automatic Email Notifications for HiveQL/SQL Script Completion | by Andrew Young | Towards Data Science
If you find this article helpful in any way, please comment or click the applause button at the left to give me free virtual encouragement! This bash script is very useful for executing HiveQL files (.hql)or SQL files (.sql). For instance, rather than having to periodically check when a CREATE TABLE or JOINhas finished, this script provides email notifications as well as a record for the clock time needed for the Hive/SQL operation(s) involved. This is especially useful for completing a series of Hive/SQL JOINs overnight for analysis the next day. A s a practicing data scientist, I dislike overexplained fluff pieces when I’m just looking for code to recycle and modify for my purposes so please find the script below. If you would like more explanation of the script beyond the code comments, please see the appendix at the end. A sufficient explanation of bash , its transformations at the bit-level, HiveQL/SQL and database engines is beyond the scope of this article. As it is written, the script below will only work for HiveQL when copy-pasted. You will have to make slight modifications for it to work with your SQL distribution. For example, changing hive -f to mysql source if you are using MySQL. It is also possible to have the script send emails to more than one email address. #!/bin/bash## By Andrew Young ## Contact: andrew.wong@team.neustar## Last modified date: 13 Dec 2019################## DIRECTIONS #################### Run the following <commands> without the "<" or ">".## <chmod u+x scriptname> to make the script executable. (where scriptname is the name of your script)## To run this script, use the following command:## ./<yourfilename>.sh################################### Ask user for Hive file name ###################################echo Hello. Please enter the HiveQL filename with the file extension. For example, 'script.hql'. To cancel, press 'Control+C'. For your convenience, here is a list of files in the present directory\:ls -lread -p 'Enter the HiveQL filename: ' HIVE_FILE_NAME#read HIVE_FILE_NAMEecho You specified: $HIVE_FILE_NAMEecho Executing...######################## Define variables ########################start="$(date)"starttime=$(date +%s)####################### Run Hive script #######################hive -f "$HIVE_FILE_NAME"################################### Human readable elapsed time ###################################secs_to_human() { if [[ -z ${1} || ${1} -lt 60 ]] ;then min=0 ; secs="${1}" else time_mins=$(echo "scale=2; ${1}/60" | bc) min=$(echo ${time_mins} | cut -d'.' -f1) secs="0.$(echo ${time_mins} | cut -d'.' -f2)" secs=$(echo ${secs}*60|bc|awk '{print int($1+0.5)}') fi timeelapsed="Clock Time Elapsed : ${min} minutes and ${secs} seconds."}################## Send email ##################end="$(date)"endtime=$(date +%s)secs_to_human $(($(date +%s) - ${starttime}))subject="$HIVE_FILE_NAME started @ $start || finished @ $end"## message="Note that $start and $end use server time. \n $timeelapsed"## working version:mail -s "$subject" youremail@wherever.com <<< "$(printf "Server start time: $start \nServer end time: $end \n$timeelapsed")"################### FUTURE WORK #################### 1. Add a diagnostic report. The report will calculate:# a. number of rows,# b. number of distinct observations for each column,# c. an option for a cutoff threshold for observations that ensures the diagnostic report is only produced for tables of a certain size. this can help prevent computationally expensive diagnostics for a large table## 2. Option to save output to a text file for inclusion in email notification.################# H ere I will explain the code for each section of the script. ################## DIRECTIONS #################### Run the following <commands> without the "<" or ">".## <chmod u+x scriptname> to make the script executable. (where scriptname is the name of your script)## To run this script, use the following command:## ./<yourfilename>.sh chmod is a bash command that stands for “change mode.” I am using it to change the permissions of the file. It ensures that you, the owner, is allowed to execute your own file on the node/machine you are using. ################################### Ask user for Hive file name ###################################echo Hello. Please enter the HiveQL filename with the file extension. For example, 'script.hql'. To cancel, press 'Control+C'. For your convenience, here is a list of files in the present directory\:ls -lread -p 'Enter the HiveQL filename: ' HIVE_FILE_NAME#read HIVE_FILE_NAMEecho You specified: $HIVE_FILE_NAMEecho Executing... In this section, I use the command ls -l to list all files in the same directory (i.e. “folder”) as the .sh file you saved my script to. The read -p is used to save the user input, i.e. the name of the .hql or .sql file you want to run, to a variable that is used later on in the script. ######################## Define variables ########################start="$(date)"starttime=$(date +%s) This is where the system’s clock time is recorded. We save two versions to two different variables: startand starttime. start="$(date)" saves the system time and date. starttime=$(date +%s) saves the system time and date in number seconds offset from 1900. The first version is later used in the email to show the timestamp and date of when the HiveQL/SQL script began execution. The second is used to calculate the number of seconds and minutes that have elapsed. This provides a handy record for the amount of time it took to build the table(s) in the HiveQL/SQL script you supplied. ################################### Human readable elapsed time ###################################secs_to_human() { if [[ -z ${1} || ${1} -lt 60 ]] ;then min=0 ; secs="${1}" else time_mins=$(echo "scale=2; ${1}/60" | bc) min=$(echo ${time_mins} | cut -d'.' -f1) secs="0.$(echo ${time_mins} | cut -d'.' -f2)" secs=$(echo ${secs}*60|bc|awk '{print int($1+0.5)}') fi timeelapsed="Clock Time Elapsed : ${min} minutes and ${secs} seconds."} This is a complicated section to decode. Basically, it is a lot of code that does something very simple: finding the difference between start and end time, both in seconds, then converting that elapsed time in seconds to minutes and seconds. For example, if the job took 605 seconds, we transform that to 10 minutes 5 seconds and save it to a variable called timeelapsed to be used in the email we have sent to ourselves and/or various stakeholders. ################## Send email ##################end="$(date)"endtime=$(date +%s)secs_to_human $(($(date +%s) - ${starttime}))subject="$HIVE_FILE_NAME started @ $start || finished @ $end"## message="Note that $start and $end use server time. \n $timeelapsed"## working version:mail -s "$subject" youremail@wherever.com <<< "$(printf "Server start time: $start \nServer end time: $end \n$timeelapsed")" In this section, I again record system time in two different formats as two different variables. I actually only use one of these variables. I decided to keep the unused variable, endtime for potential future extensions to this script. The variable $end is used in the email notification to report the system time and date for when the HiveQL/SQL file completed. I define a variable subject that, unsurprisingly, becomes the subject line of the email. I commented out the message variable because I couldn’t get the printf command to correctly replace \n with new lines in the message body of the email. I left it in place because I wanted to leave you with the option of editing it for your own purposes. mail is a program that sends emails. You will probably have it or something like it. There are other options to mail, like mailx, sendmail, smtp-cli, ssmtp, Swaks and a number of others. Some of these programs are subsets or derivatives of each other. I n the spirit of collaboration and furthering this effort, here are some ideas for future work: Allow a user to specify the directory of HiveQL/SQL files in which to look for the target file to be run. An example use-case is where a user might have organized their HiveQL/SQL code into multiple directories based on project/time.Improve the formatting of the email notification.Add robustness to the script by automatically detecting whether a HiveQL or SQL script was input, and if the latter, an option to specify the distribution (i.e. OracleDB, MySQL, etc.).Add the option for the user to specify whether the output of the query should be sent to the email(s) specified. Use-case: running a multitude of SELECT statements for exploratory data analysis (EDA). For example, counting number of distinct values of each field of a table, finding distinct levels of a categorical field, finding counts by group, numerical summary statistics like mean, median, standard deviation, etc.Add the option for the user to specify one or more email addresses at the command line.Add an option for the user to specify multiple .hql and/or .sql files to be run in sequence or perhaps in parallel.Add a parallelization option. Use-case: you have a tight deadline and need not concern yourself with resource utilization or co-worker etiquette. I need my results!Add an option to schedule code execution. Likely in the form of a sleep specified by the user. Use-case: you want to be courteous and avoid runs during production code runs and when cluster usage is high during the work day.Make one or more of the options above accessible via flags. This would be really cool, but also a lot of work just to add sprinkles on top.More. Allow a user to specify the directory of HiveQL/SQL files in which to look for the target file to be run. An example use-case is where a user might have organized their HiveQL/SQL code into multiple directories based on project/time. Improve the formatting of the email notification. Add robustness to the script by automatically detecting whether a HiveQL or SQL script was input, and if the latter, an option to specify the distribution (i.e. OracleDB, MySQL, etc.). Add the option for the user to specify whether the output of the query should be sent to the email(s) specified. Use-case: running a multitude of SELECT statements for exploratory data analysis (EDA). For example, counting number of distinct values of each field of a table, finding distinct levels of a categorical field, finding counts by group, numerical summary statistics like mean, median, standard deviation, etc. Add the option for the user to specify one or more email addresses at the command line. Add an option for the user to specify multiple .hql and/or .sql files to be run in sequence or perhaps in parallel. Add a parallelization option. Use-case: you have a tight deadline and need not concern yourself with resource utilization or co-worker etiquette. I need my results! Add an option to schedule code execution. Likely in the form of a sleep specified by the user. Use-case: you want to be courteous and avoid runs during production code runs and when cluster usage is high during the work day. Make one or more of the options above accessible via flags. This would be really cool, but also a lot of work just to add sprinkles on top. More. Open whatever command line terminal interface you prefer. Examples include Terminal on MacOS and Cygwin on Windows. MacOS has Terminal already installed. On Windows, you can download Cygwin here.Navigate to the directory with your .hql files. For example, type cd anyoung/hqlscripts/ to change your current working directory to that folder. This is the conceptual equivalent of double-clicking on a folder to open it, except here we are using a text-based command.nano <whateverfilename>.shnano is a command that opens a program of the same name and asks it to create a new file called <whateverfilename>.sh To revise this file, utilize the same command.Copy my script and paste it into this new .sh file. Change the recipient email address in my script from youremail@wherever.com to yours.bash <whateverfilename>.sh Bash uses files of the extension type .sh. This command asks the program, bash to run your “shell” file denoted with the .sh extension. Upon running, the script will output a list of all files in the same directory as the shell script. This list output is something I programmed for convenience.Marvel at your productivity gains! Open whatever command line terminal interface you prefer. Examples include Terminal on MacOS and Cygwin on Windows. MacOS has Terminal already installed. On Windows, you can download Cygwin here. Navigate to the directory with your .hql files. For example, type cd anyoung/hqlscripts/ to change your current working directory to that folder. This is the conceptual equivalent of double-clicking on a folder to open it, except here we are using a text-based command. nano <whateverfilename>.shnano is a command that opens a program of the same name and asks it to create a new file called <whateverfilename>.sh To revise this file, utilize the same command. Copy my script and paste it into this new .sh file. Change the recipient email address in my script from youremail@wherever.com to yours. bash <whateverfilename>.sh Bash uses files of the extension type .sh. This command asks the program, bash to run your “shell” file denoted with the .sh extension. Upon running, the script will output a list of all files in the same directory as the shell script. This list output is something I programmed for convenience. Marvel at your productivity gains! Andrew Young is an R&D Data Scientist Manager at Neustar. For context, Neustar is an information services company that ingests structured and unstructured text and picture data from hundreds of companies in the domains of aviation, banking, government, marketing, social media and telecommunications to name several. Neustar combines these data ingredients then sells a finished dish with added value to enterprise clients for purposes like consulting, cyber security, fraud detection and marketing. In this context, Mr. Young is a hands-on lead architect on a small R&D data science team that builds the system feeding all products and services responsible for $1+ billion in annual revenue for Neustar. A pre-requisite to running the shell script above is to have a HiveQL or SQL script for it to run. Here is an example HiveQL script, example.hql: CREATE TABLE db.tb1 STORED AS ORC ASSELECT *FROM db.tb2WHERE a >= 5;CREATE TABLE db.tb3 STORED AS ORC ASSELECT *FROM db.tb4 aINNER JOIN db.tb5 bON a.col2 = b.col5WHERE dt >= 20191201 AND DOB != 01-01-1900; Note that you can have one or more CREATE TABLE commands in a single HiveQL/SQL script. They will be executed in sequence. If you have access to a cluster of nodes, you can also benefit from parallelization of your queries. I may explain that in another article.
[ { "code": null, "e": 312, "s": 172, "text": "If you find this article helpful in any way, please comment or click the applause button at the left to give me free virtual encouragement!" }, { "code": null, "e": 726, "s": 312, "text": "This bash script is very useful for executing HiveQL files (.hql)or SQL files (.sql). For instance, rather than having to periodically check when a CREATE TABLE or JOINhas finished, this script provides email notifications as well as a record for the clock time needed for the Hive/SQL operation(s) involved. This is especially useful for completing a series of Hive/SQL JOINs overnight for analysis the next day." }, { "code": null, "e": 1469, "s": 726, "text": "A s a practicing data scientist, I dislike overexplained fluff pieces when I’m just looking for code to recycle and modify for my purposes so please find the script below. If you would like more explanation of the script beyond the code comments, please see the appendix at the end. A sufficient explanation of bash , its transformations at the bit-level, HiveQL/SQL and database engines is beyond the scope of this article. As it is written, the script below will only work for HiveQL when copy-pasted. You will have to make slight modifications for it to work with your SQL distribution. For example, changing hive -f to mysql source if you are using MySQL. It is also possible to have the script send emails to more than one email address." }, { "code": null, "e": 3849, "s": 1469, "text": "#!/bin/bash## By Andrew Young ## Contact: andrew.wong@team.neustar## Last modified date: 13 Dec 2019################## DIRECTIONS #################### Run the following <commands> without the \"<\" or \">\".## <chmod u+x scriptname> to make the script executable. (where scriptname is the name of your script)## To run this script, use the following command:## ./<yourfilename>.sh################################### Ask user for Hive file name ###################################echo Hello. Please enter the HiveQL filename with the file extension. For example, 'script.hql'. To cancel, press 'Control+C'. For your convenience, here is a list of files in the present directory\\:ls -lread -p 'Enter the HiveQL filename: ' HIVE_FILE_NAME#read HIVE_FILE_NAMEecho You specified: $HIVE_FILE_NAMEecho Executing...######################## Define variables ########################start=\"$(date)\"starttime=$(date +%s)####################### Run Hive script #######################hive -f \"$HIVE_FILE_NAME\"################################### Human readable elapsed time ###################################secs_to_human() { if [[ -z ${1} || ${1} -lt 60 ]] ;then min=0 ; secs=\"${1}\" else time_mins=$(echo \"scale=2; ${1}/60\" | bc) min=$(echo ${time_mins} | cut -d'.' -f1) secs=\"0.$(echo ${time_mins} | cut -d'.' -f2)\" secs=$(echo ${secs}*60|bc|awk '{print int($1+0.5)}') fi timeelapsed=\"Clock Time Elapsed : ${min} minutes and ${secs} seconds.\"}################## Send email ##################end=\"$(date)\"endtime=$(date +%s)secs_to_human $(($(date +%s) - ${starttime}))subject=\"$HIVE_FILE_NAME started @ $start || finished @ $end\"## message=\"Note that $start and $end use server time. \\n $timeelapsed\"## working version:mail -s \"$subject\" youremail@wherever.com <<< \"$(printf \"Server start time: $start \\nServer end time: $end \\n$timeelapsed\")\"################### FUTURE WORK #################### 1. Add a diagnostic report. The report will calculate:# a. number of rows,# b. number of distinct observations for each column,# c. an option for a cutoff threshold for observations that ensures the diagnostic report is only produced for tables of a certain size. this can help prevent computationally expensive diagnostics for a large table## 2. Option to save output to a text file for inclusion in email notification.#################" }, { "code": null, "e": 3911, "s": 3849, "text": "H ere I will explain the code for each section of the script." }, { "code": null, "e": 4188, "s": 3911, "text": "################## DIRECTIONS #################### Run the following <commands> without the \"<\" or \">\".## <chmod u+x scriptname> to make the script executable. (where scriptname is the name of your script)## To run this script, use the following command:## ./<yourfilename>.sh" }, { "code": null, "e": 4399, "s": 4188, "text": "chmod is a bash command that stands for “change mode.” I am using it to change the permissions of the file. It ensures that you, the owner, is allowed to execute your own file on the node/machine you are using." }, { "code": null, "e": 4827, "s": 4399, "text": "################################### Ask user for Hive file name ###################################echo Hello. Please enter the HiveQL filename with the file extension. For example, 'script.hql'. To cancel, press 'Control+C'. For your convenience, here is a list of files in the present directory\\:ls -lread -p 'Enter the HiveQL filename: ' HIVE_FILE_NAME#read HIVE_FILE_NAMEecho You specified: $HIVE_FILE_NAMEecho Executing..." }, { "code": null, "e": 5115, "s": 4827, "text": "In this section, I use the command ls -l to list all files in the same directory (i.e. “folder”) as the .sh file you saved my script to. The read -p is used to save the user input, i.e. the name of the .hql or .sql file you want to run, to a variable that is used later on in the script." }, { "code": null, "e": 5218, "s": 5115, "text": "######################## Define variables ########################start=\"$(date)\"starttime=$(date +%s)" }, { "code": null, "e": 5338, "s": 5218, "text": "This is where the system’s clock time is recorded. We save two versions to two different variables: startand starttime." }, { "code": null, "e": 5804, "s": 5338, "text": "start=\"$(date)\" saves the system time and date. starttime=$(date +%s) saves the system time and date in number seconds offset from 1900. The first version is later used in the email to show the timestamp and date of when the HiveQL/SQL script began execution. The second is used to calculate the number of seconds and minutes that have elapsed. This provides a handy record for the amount of time it took to build the table(s) in the HiveQL/SQL script you supplied." }, { "code": null, "e": 6288, "s": 5804, "text": "################################### Human readable elapsed time ###################################secs_to_human() { if [[ -z ${1} || ${1} -lt 60 ]] ;then min=0 ; secs=\"${1}\" else time_mins=$(echo \"scale=2; ${1}/60\" | bc) min=$(echo ${time_mins} | cut -d'.' -f1) secs=\"0.$(echo ${time_mins} | cut -d'.' -f2)\" secs=$(echo ${secs}*60|bc|awk '{print int($1+0.5)}') fi timeelapsed=\"Clock Time Elapsed : ${min} minutes and ${secs} seconds.\"}" }, { "code": null, "e": 6738, "s": 6288, "text": "This is a complicated section to decode. Basically, it is a lot of code that does something very simple: finding the difference between start and end time, both in seconds, then converting that elapsed time in seconds to minutes and seconds. For example, if the job took 605 seconds, we transform that to 10 minutes 5 seconds and save it to a variable called timeelapsed to be used in the email we have sent to ourselves and/or various stakeholders." }, { "code": null, "e": 7143, "s": 6738, "text": "################## Send email ##################end=\"$(date)\"endtime=$(date +%s)secs_to_human $(($(date +%s) - ${starttime}))subject=\"$HIVE_FILE_NAME started @ $start || finished @ $end\"## message=\"Note that $start and $end use server time. \\n $timeelapsed\"## working version:mail -s \"$subject\" youremail@wherever.com <<< \"$(printf \"Server start time: $start \\nServer end time: $end \\n$timeelapsed\")\"" }, { "code": null, "e": 7506, "s": 7143, "text": "In this section, I again record system time in two different formats as two different variables. I actually only use one of these variables. I decided to keep the unused variable, endtime for potential future extensions to this script. The variable $end is used in the email notification to report the system time and date for when the HiveQL/SQL file completed." }, { "code": null, "e": 7849, "s": 7506, "text": "I define a variable subject that, unsurprisingly, becomes the subject line of the email. I commented out the message variable because I couldn’t get the printf command to correctly replace \\n with new lines in the message body of the email. I left it in place because I wanted to leave you with the option of editing it for your own purposes." }, { "code": null, "e": 8101, "s": 7849, "text": "mail is a program that sends emails. You will probably have it or something like it. There are other options to mail, like mailx, sendmail, smtp-cli, ssmtp, Swaks and a number of others. Some of these programs are subsets or derivatives of each other." }, { "code": null, "e": 8198, "s": 8101, "text": "I n the spirit of collaboration and furthering this effort, here are some ideas for future work:" }, { "code": null, "e": 9819, "s": 8198, "text": "Allow a user to specify the directory of HiveQL/SQL files in which to look for the target file to be run. An example use-case is where a user might have organized their HiveQL/SQL code into multiple directories based on project/time.Improve the formatting of the email notification.Add robustness to the script by automatically detecting whether a HiveQL or SQL script was input, and if the latter, an option to specify the distribution (i.e. OracleDB, MySQL, etc.).Add the option for the user to specify whether the output of the query should be sent to the email(s) specified. Use-case: running a multitude of SELECT statements for exploratory data analysis (EDA). For example, counting number of distinct values of each field of a table, finding distinct levels of a categorical field, finding counts by group, numerical summary statistics like mean, median, standard deviation, etc.Add the option for the user to specify one or more email addresses at the command line.Add an option for the user to specify multiple .hql and/or .sql files to be run in sequence or perhaps in parallel.Add a parallelization option. Use-case: you have a tight deadline and need not concern yourself with resource utilization or co-worker etiquette. I need my results!Add an option to schedule code execution. Likely in the form of a sleep specified by the user. Use-case: you want to be courteous and avoid runs during production code runs and when cluster usage is high during the work day.Make one or more of the options above accessible via flags. This would be really cool, but also a lot of work just to add sprinkles on top.More." }, { "code": null, "e": 10053, "s": 9819, "text": "Allow a user to specify the directory of HiveQL/SQL files in which to look for the target file to be run. An example use-case is where a user might have organized their HiveQL/SQL code into multiple directories based on project/time." }, { "code": null, "e": 10103, "s": 10053, "text": "Improve the formatting of the email notification." }, { "code": null, "e": 10288, "s": 10103, "text": "Add robustness to the script by automatically detecting whether a HiveQL or SQL script was input, and if the latter, an option to specify the distribution (i.e. OracleDB, MySQL, etc.)." }, { "code": null, "e": 10709, "s": 10288, "text": "Add the option for the user to specify whether the output of the query should be sent to the email(s) specified. Use-case: running a multitude of SELECT statements for exploratory data analysis (EDA). For example, counting number of distinct values of each field of a table, finding distinct levels of a categorical field, finding counts by group, numerical summary statistics like mean, median, standard deviation, etc." }, { "code": null, "e": 10797, "s": 10709, "text": "Add the option for the user to specify one or more email addresses at the command line." }, { "code": null, "e": 10913, "s": 10797, "text": "Add an option for the user to specify multiple .hql and/or .sql files to be run in sequence or perhaps in parallel." }, { "code": null, "e": 11078, "s": 10913, "text": "Add a parallelization option. Use-case: you have a tight deadline and need not concern yourself with resource utilization or co-worker etiquette. I need my results!" }, { "code": null, "e": 11303, "s": 11078, "text": "Add an option to schedule code execution. Likely in the form of a sleep specified by the user. Use-case: you want to be courteous and avoid runs during production code runs and when cluster usage is high during the work day." }, { "code": null, "e": 11443, "s": 11303, "text": "Make one or more of the options above accessible via flags. This would be really cool, but also a lot of work just to add sprinkles on top." }, { "code": null, "e": 11449, "s": 11443, "text": "More." }, { "code": null, "e": 12597, "s": 11449, "text": "Open whatever command line terminal interface you prefer. Examples include Terminal on MacOS and Cygwin on Windows. MacOS has Terminal already installed. On Windows, you can download Cygwin here.Navigate to the directory with your .hql files. For example, type cd anyoung/hqlscripts/ to change your current working directory to that folder. This is the conceptual equivalent of double-clicking on a folder to open it, except here we are using a text-based command.nano <whateverfilename>.shnano is a command that opens a program of the same name and asks it to create a new file called <whateverfilename>.sh To revise this file, utilize the same command.Copy my script and paste it into this new .sh file. Change the recipient email address in my script from youremail@wherever.com to yours.bash <whateverfilename>.sh Bash uses files of the extension type .sh. This command asks the program, bash to run your “shell” file denoted with the .sh extension. Upon running, the script will output a list of all files in the same directory as the shell script. This list output is something I programmed for convenience.Marvel at your productivity gains!" }, { "code": null, "e": 12793, "s": 12597, "text": "Open whatever command line terminal interface you prefer. Examples include Terminal on MacOS and Cygwin on Windows. MacOS has Terminal already installed. On Windows, you can download Cygwin here." }, { "code": null, "e": 13063, "s": 12793, "text": "Navigate to the directory with your .hql files. For example, type cd anyoung/hqlscripts/ to change your current working directory to that folder. This is the conceptual equivalent of double-clicking on a folder to open it, except here we are using a text-based command." }, { "code": null, "e": 13254, "s": 13063, "text": "nano <whateverfilename>.shnano is a command that opens a program of the same name and asks it to create a new file called <whateverfilename>.sh To revise this file, utilize the same command." }, { "code": null, "e": 13392, "s": 13254, "text": "Copy my script and paste it into this new .sh file. Change the recipient email address in my script from youremail@wherever.com to yours." }, { "code": null, "e": 13715, "s": 13392, "text": "bash <whateverfilename>.sh Bash uses files of the extension type .sh. This command asks the program, bash to run your “shell” file denoted with the .sh extension. Upon running, the script will output a list of all files in the same directory as the shell script. This list output is something I programmed for convenience." }, { "code": null, "e": 13750, "s": 13715, "text": "Marvel at your productivity gains!" }, { "code": null, "e": 14455, "s": 13750, "text": "Andrew Young is an R&D Data Scientist Manager at Neustar. For context, Neustar is an information services company that ingests structured and unstructured text and picture data from hundreds of companies in the domains of aviation, banking, government, marketing, social media and telecommunications to name several. Neustar combines these data ingredients then sells a finished dish with added value to enterprise clients for purposes like consulting, cyber security, fraud detection and marketing. In this context, Mr. Young is a hands-on lead architect on a small R&D data science team that builds the system feeding all products and services responsible for $1+ billion in annual revenue for Neustar." }, { "code": null, "e": 14601, "s": 14455, "text": "A pre-requisite to running the shell script above is to have a HiveQL or SQL script for it to run. Here is an example HiveQL script, example.hql:" }, { "code": null, "e": 14807, "s": 14601, "text": "CREATE TABLE db.tb1 STORED AS ORC ASSELECT *FROM db.tb2WHERE a >= 5;CREATE TABLE db.tb3 STORED AS ORC ASSELECT *FROM db.tb4 aINNER JOIN db.tb5 bON a.col2 = b.col5WHERE dt >= 20191201 AND DOB != 01-01-1900;" } ]
How to update a MySQL date type column?
Let us first create a table − mysql> create table DemoTable1451 -> ( -> JoiningDate date -> ); Query OK, 0 rows affected (0.52 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1451 values('2019-07-21'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable1451 values('2018-01-31'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1451 values('2017-06-01'); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select * from DemoTable1451; This will produce the following output − +-------------+ | JoiningDate | +-------------+ | 2019-07-21 | | 2018-01-31 | | 2017-06-01 | +-------------+ 3 rows in set (0.00 sec) Here is the query to update a date type column. We are incrementing the date records with an year − mysql> update DemoTable1451 set JoiningDate=date_add(JoiningDate, interval 1 year); Query OK, 3 rows affected (0.15 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check the table records once again − mysql> select * from DemoTable1451; This will produce the following output − +-------------+ | JoiningDate | +-------------+ | 2020-07-21 | | 2019-01-31 | | 2018-06-01 | +-------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1203, "s": 1092, "text": "mysql> create table DemoTable1451\n -> (\n -> JoiningDate date\n -> );\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 1259, "s": 1203, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1532, "s": 1259, "text": "mysql> insert into DemoTable1451 values('2019-07-21');\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable1451 values('2018-01-31');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable1451 values('2017-06-01');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1592, "s": 1532, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1628, "s": 1592, "text": "mysql> select * from DemoTable1451;" }, { "code": null, "e": 1669, "s": 1628, "text": "This will produce the following output −" }, { "code": null, "e": 1806, "s": 1669, "text": "+-------------+\n| JoiningDate |\n+-------------+\n| 2019-07-21 |\n| 2018-01-31 |\n| 2017-06-01 |\n+-------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1906, "s": 1806, "text": "Here is the query to update a date type column. We are incrementing the date records with an year −" }, { "code": null, "e": 2067, "s": 1906, "text": "mysql> update DemoTable1451 set JoiningDate=date_add(JoiningDate, interval 1 year);\nQuery OK, 3 rows affected (0.15 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2111, "s": 2067, "text": "Let us check the table records once again −" }, { "code": null, "e": 2147, "s": 2111, "text": "mysql> select * from DemoTable1451;" }, { "code": null, "e": 2188, "s": 2147, "text": "This will produce the following output −" }, { "code": null, "e": 2325, "s": 2188, "text": "+-------------+\n| JoiningDate |\n+-------------+\n| 2020-07-21 |\n| 2019-01-31 |\n| 2018-06-01 |\n+-------------+\n3 rows in set (0.00 sec)" } ]
How to remove duplicates from MongoDB Collection?
For this, set “unique:true” i.e. the unique constraint and avoid inserting duplicates as in the below syntax − db.yourCollectionName.ensureIndex({yourFieldName: 1}, {unique: true, dropDups: true}) To understand the above syntax, let us create a collection with documents. Here, duplicate insertion won’t be allowed − > db.demo604.ensureIndex({FirstName: 1}, {unique: true, dropDups: true});{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo604.insertOne({FirstName:"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e960887ed011c280a0905d8") } > db.demo604.insertOne({FirstName:"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e96088aed011c280a0905d9") } > db.demo604.insertOne({FirstName:"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e96088ded011c280a0905da") } > db.demo604.insertOne({FirstName:"Chris"}); 2020-04-15T00:31:35.978+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo604 index: FirstName_1 dup key: { : "Chris" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo604 index: FirstName_1 dup key: { : \"Chris\" }", "op" : { "_id" : ObjectId("5e96088fed011c280a0905db"), "FirstName" : "Chris" } }) WriteError@src/mongo/shell/bulk_api.js:461:48 Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49 Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13 Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21 DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9 @(shell):1:1 Display all documents from a collection with the help of find() method − > db.demo604.find(); This will produce the following output − { "_id" : ObjectId("5e960887ed011c280a0905d8"), "FirstName" : "Chris" } { "_id" : ObjectId("5e96088aed011c280a0905d9"), "FirstName" : "Bob" } { "_id" : ObjectId("5e96088ded011c280a0905da"), "FirstName" : "David" }
[ { "code": null, "e": 1173, "s": 1062, "text": "For this, set “unique:true” i.e. the unique constraint and avoid inserting duplicates as in the below syntax −" }, { "code": null, "e": 1259, "s": 1173, "text": "db.yourCollectionName.ensureIndex({yourFieldName: 1}, {unique: true, dropDups: true})" }, { "code": null, "e": 1379, "s": 1259, "text": "To understand the above syntax, let us create a collection with documents. Here, duplicate insertion won’t be allowed −" }, { "code": null, "e": 2697, "s": 1379, "text": "> db.demo604.ensureIndex({FirstName: 1}, {unique: true, dropDups: true});{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}\n> db.demo604.insertOne({FirstName:\"Chris\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e960887ed011c280a0905d8\")\n}\n> db.demo604.insertOne({FirstName:\"Bob\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e96088aed011c280a0905d9\")\n}\n> db.demo604.insertOne({FirstName:\"David\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e96088ded011c280a0905da\")\n}\n> db.demo604.insertOne({FirstName:\"Chris\"});\n2020-04-15T00:31:35.978+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo604 index: FirstName_1 dup key: { : \"Chris\" } :\nWriteError({\n \"index\" : 0,\n \"code\" : 11000,\n \"errmsg\" : \"E11000 duplicate key error collection: test.demo604 index: FirstName_1 dup key: { : \\\"Chris\\\" }\",\n \"op\" : {\n \"_id\" : ObjectId(\"5e96088fed011c280a0905db\"),\n \"FirstName\" : \"Chris\"\n }\n})\nWriteError@src/mongo/shell/bulk_api.js:461:48\nBulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49\nBulk/executeBatch@src/mongo/shell/bulk_api.js:906:13\nBulk/this.execute@src/mongo/shell/bulk_api.js:1150:21\nDBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9\n@(shell):1:1" }, { "code": null, "e": 2770, "s": 2697, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2791, "s": 2770, "text": "> db.demo604.find();" }, { "code": null, "e": 2832, "s": 2791, "text": "This will produce the following output −" }, { "code": null, "e": 3046, "s": 2832, "text": "{ \"_id\" : ObjectId(\"5e960887ed011c280a0905d8\"), \"FirstName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e96088aed011c280a0905d9\"), \"FirstName\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e96088ded011c280a0905da\"), \"FirstName\" : \"David\" }" } ]
Python | Find missing and additional values in two lists - GeeksforGeeks
21 Nov, 2018 Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements of list2 we need to get the difference of list1 from list2. To find the additional elements of list2, calculate the difference of list2 from list1.Similarly while finding missing elements of list1, calculate the difference of list2 from list1. To find the additional elements in list1, calculate the difference of list1 from list2. Insert the list1 and list2 to set and then use difference function in sets to get the required answer. Prerequisite : Python Set Difference # Python program to find the missing # and additional elements # examples of listslist1 = [1, 2, 3, 4, 5, 6]list2 = [4, 5, 6, 7, 8] # prints the missing and additional elements in list2 print("Missing values in second list:", (set(list1).difference(list2)))print("Additional values in second list:", (set(list2).difference(list1))) # prints the missing and additional elements in list1print("Missing values in first list:", (set(list2).difference(list1)))print("Additional values in first list:", (set(list1).difference(list2))) Output: Missing values in second list: {1, 2, 3} Additional values in second list: {7, 8} Missing values in first list: {7, 8} Additional values in first list: {1, 2, 3} Python list-programs Python set-programs python-list python-set Python python-list python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n21 Nov, 2018" }, { "code": null, "e": 24287, "s": 24212, "text": "Given two lists, find the missing and additional values in both the lists." }, { "code": null, "e": 24297, "s": 24287, "text": "Examples:" }, { "code": null, "e": 24567, "s": 24297, "text": "Input : list1 = [1, 2, 3, 4, 5, 6] \n list2 = [4, 5, 6, 7, 8] \nOutput : Missing values in list1 = [8, 7] \n Additional values in list1 = [1, 2, 3] \n Missing values in list2 = [1, 2, 3] \n Additional values in list2 = [7, 8] \n\nExplanation: \n\n" }, { "code": null, "e": 24938, "s": 24567, "text": "Approach: To find the missing elements of list2 we need to get the difference of list1 from list2. To find the additional elements of list2, calculate the difference of list2 from list1.Similarly while finding missing elements of list1, calculate the difference of list2 from list1. To find the additional elements in list1, calculate the difference of list1 from list2." }, { "code": null, "e": 25041, "s": 24938, "text": "Insert the list1 and list2 to set and then use difference function in sets to get the required answer." }, { "code": null, "e": 25078, "s": 25041, "text": "Prerequisite : Python Set Difference" }, { "code": "# Python program to find the missing # and additional elements # examples of listslist1 = [1, 2, 3, 4, 5, 6]list2 = [4, 5, 6, 7, 8] # prints the missing and additional elements in list2 print(\"Missing values in second list:\", (set(list1).difference(list2)))print(\"Additional values in second list:\", (set(list2).difference(list1))) # prints the missing and additional elements in list1print(\"Missing values in first list:\", (set(list2).difference(list1)))print(\"Additional values in first list:\", (set(list1).difference(list2)))", "e": 25611, "s": 25078, "text": null }, { "code": null, "e": 25619, "s": 25611, "text": "Output:" }, { "code": null, "e": 25782, "s": 25619, "text": "Missing values in second list: {1, 2, 3}\nAdditional values in second list: {7, 8}\nMissing values in first list: {7, 8}\nAdditional values in first list: {1, 2, 3}\n" }, { "code": null, "e": 25803, "s": 25782, "text": "Python list-programs" }, { "code": null, "e": 25823, "s": 25803, "text": "Python set-programs" }, { "code": null, "e": 25835, "s": 25823, "text": "python-list" }, { "code": null, "e": 25846, "s": 25835, "text": "python-set" }, { "code": null, "e": 25853, "s": 25846, "text": "Python" }, { "code": null, "e": 25865, "s": 25853, "text": "python-list" }, { "code": null, "e": 25876, "s": 25865, "text": "python-set" }, { "code": null, "e": 25974, "s": 25876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25992, "s": 25974, "text": "Python Dictionary" }, { "code": null, "e": 26027, "s": 25992, "text": "Read a file line by line in Python" }, { "code": null, "e": 26049, "s": 26027, "text": "Enumerate() in Python" }, { "code": null, "e": 26081, "s": 26049, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26111, "s": 26081, "text": "Iterate over a list in Python" }, { "code": null, "e": 26153, "s": 26111, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26179, "s": 26153, "text": "Python String | replace()" }, { "code": null, "e": 26216, "s": 26179, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26259, "s": 26216, "text": "Python program to convert a list to string" } ]
Largest Element in Array | Practice | GeeksforGeeks
Given an array A[] of size n. The task is to find the largest element in it. Example 1: Input: n = 5 A[] = {1, 8, 7, 56, 90} Output: 90 Explanation: The largest element of given array is 90. Example 2: Input: n = 7 A[] = {1, 2, 0, 3, 2, 4, 5} Output: 5 Explanation: The largest element of given array is 5. Your Task: You don't need to read input or print anything. Your task is to complete the function largest() which takes the array A[] and its size n as inputs and returns the maximum element in the array. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= n<= 103 0 <= A[i] <= 103 Array may contain duplicate elements. 0 mdparvejalam687in 11 hours Java Solution int larger = arr[0]; for(int i=0; i<arr.length;i++){ if(larger<arr[i]){ larger= arr[i]; } } return larger; 0 cchaithanyata3 hours ago #include<stdio.h> #include<conio.h> int main() { int a[1000], i,n, max; printf("enter size of the array:") ; scanf("%d", &n) ; printf("enter elements in an array:") ; for(i=0;i<n;i++) { scanf("%d", &a[i]) ; } max=a[0]; for(i=1;i<n;i++) { if(max<a[i]) max=a[i]; } printf("\n maximum of array is:%d", max) ; return 0; } +1 rahilarahman1 week ago simple python codedef largest( arr, n): arr.sort() return arr[n-1] +1 mp96q2iqslxyjaqior18jrs0xwp7wz21845kzrfr1 week ago Python def largest( arr, n): arr.sort(reverse=True) return arr[0] +1 harshscode1 week ago int m=0; for(int i=0;i<n;i++) { if(a[i]>m) m=a[i]; } return m; 0 vikassinghwow1 week ago class Compute { public int largest(int arr[], int n) { int largest=arr[0]; for(int i=1;i<arr.length;i++) { if(largest<arr[i]) { largest=arr[i]; } } return largest; }} 0 payalchaudhary4422 weeks ago //JAVA CODE: class Compute { public int largest(int arr[], int n) { int larger = arr[0]; for(int i=0; i<arr.length;i++){ if(larger<arr[i]){ larger= arr[i]; } } return larger; }} 0 diagovenk2 weeks ago Hello everyone. Most easy with just one loop and one if statement without using any inbuilt function. java solution. public int largest(int arr[], int n) { int largest = 0; for(int i=0; i<n; i++){ if(arr[i]>largest){ largest = arr[i]; } } return largest; } 0 jeetsorathiya2 weeks ago my solution in java just use sort function Arrays.sort(arr); return arr[n-1]; +1 akash2420182 weeks ago #python3 Code def largest( arr, n): maxium=arr[0] for i in range (n): if(arr[i]>maxium): maxium=arr[i] return maxium 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": 317, "s": 238, "text": "Given an array A[] of size n. The task is to find the largest element in it.\n " }, { "code": null, "e": 328, "s": 317, "text": "Example 1:" }, { "code": null, "e": 431, "s": 328, "text": "Input:\nn = 5\nA[] = {1, 8, 7, 56, 90}\nOutput:\n90\nExplanation:\nThe largest element of given array is 90." }, { "code": null, "e": 444, "s": 433, "text": "Example 2:" }, { "code": null, "e": 549, "s": 444, "text": "Input:\nn = 7\nA[] = {1, 2, 0, 3, 2, 4, 5}\nOutput:\n5\nExplanation:\nThe largest element of given array is 5." }, { "code": null, "e": 757, "s": 551, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function largest() which takes the array A[] and its size n as inputs and returns the maximum element in the array." }, { "code": null, "e": 821, "s": 759, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 905, "s": 823, "text": "Constraints:\n1 <= n<= 103\n0 <= A[i] <= 103\nArray may contain duplicate elements. " }, { "code": null, "e": 907, "s": 905, "text": "0" }, { "code": null, "e": 934, "s": 907, "text": "mdparvejalam687in 11 hours" }, { "code": null, "e": 948, "s": 934, "text": "Java Solution" }, { "code": null, "e": 1091, "s": 950, "text": "int larger = arr[0]; for(int i=0; i<arr.length;i++){ if(larger<arr[i]){ larger= arr[i]; } } return larger;" }, { "code": null, "e": 1093, "s": 1091, "text": "0" }, { "code": null, "e": 1118, "s": 1093, "text": "cchaithanyata3 hours ago" }, { "code": null, "e": 1136, "s": 1118, "text": "#include<stdio.h>" }, { "code": null, "e": 1154, "s": 1136, "text": "#include<conio.h>" }, { "code": null, "e": 1166, "s": 1154, "text": "int main() " }, { "code": null, "e": 1168, "s": 1166, "text": "{" }, { "code": null, "e": 1191, "s": 1168, "text": "int a[1000], i,n, max;" }, { "code": null, "e": 1228, "s": 1191, "text": "printf(\"enter size of the array:\") ;" }, { "code": null, "e": 1246, "s": 1228, "text": "scanf(\"%d\", &n) ;" }, { "code": null, "e": 1286, "s": 1246, "text": "printf(\"enter elements in an array:\") ;" }, { "code": null, "e": 1304, "s": 1286, "text": "for(i=0;i<n;i++) " }, { "code": null, "e": 1306, "s": 1304, "text": "{" }, { "code": null, "e": 1327, "s": 1306, "text": "scanf(\"%d\", &a[i]) ;" }, { "code": null, "e": 1329, "s": 1327, "text": "}" }, { "code": null, "e": 1339, "s": 1329, "text": "max=a[0];" }, { "code": null, "e": 1357, "s": 1339, "text": "for(i=1;i<n;i++) " }, { "code": null, "e": 1359, "s": 1357, "text": "{" }, { "code": null, "e": 1373, "s": 1359, "text": "if(max<a[i]) " }, { "code": null, "e": 1383, "s": 1373, "text": "max=a[i];" }, { "code": null, "e": 1385, "s": 1383, "text": "}" }, { "code": null, "e": 1428, "s": 1385, "text": "printf(\"\\n maximum of array is:%d\", max) ;" }, { "code": null, "e": 1438, "s": 1428, "text": "return 0;" }, { "code": null, "e": 1440, "s": 1438, "text": "}" }, { "code": null, "e": 1443, "s": 1440, "text": "+1" }, { "code": null, "e": 1466, "s": 1443, "text": "rahilarahman1 week ago" }, { "code": null, "e": 1537, "s": 1466, "text": "simple python codedef largest( arr, n): arr.sort() return arr[n-1]" }, { "code": null, "e": 1540, "s": 1537, "text": "+1" }, { "code": null, "e": 1591, "s": 1540, "text": "mp96q2iqslxyjaqior18jrs0xwp7wz21845kzrfr1 week ago" }, { "code": null, "e": 1598, "s": 1591, "text": "Python" }, { "code": null, "e": 1663, "s": 1600, "text": "def largest( arr, n): arr.sort(reverse=True) return arr[0]" }, { "code": null, "e": 1666, "s": 1663, "text": "+1" }, { "code": null, "e": 1687, "s": 1666, "text": "harshscode1 week ago" }, { "code": null, "e": 1795, "s": 1687, "text": " int m=0; for(int i=0;i<n;i++) { if(a[i]>m) m=a[i]; } return m;" }, { "code": null, "e": 1797, "s": 1795, "text": "0" }, { "code": null, "e": 1821, "s": 1797, "text": "vikassinghwow1 week ago" }, { "code": null, "e": 2071, "s": 1821, "text": "class Compute { public int largest(int arr[], int n) { int largest=arr[0]; for(int i=1;i<arr.length;i++) { if(largest<arr[i]) { largest=arr[i]; } } return largest; }}" }, { "code": null, "e": 2073, "s": 2071, "text": "0" }, { "code": null, "e": 2102, "s": 2073, "text": "payalchaudhary4422 weeks ago" }, { "code": null, "e": 2115, "s": 2102, "text": "//JAVA CODE:" }, { "code": null, "e": 2367, "s": 2135, "text": " class Compute { public int largest(int arr[], int n) { int larger = arr[0]; for(int i=0; i<arr.length;i++){ if(larger<arr[i]){ larger= arr[i]; } } return larger; }}" }, { "code": null, "e": 2371, "s": 2369, "text": "0" }, { "code": null, "e": 2392, "s": 2371, "text": "diagovenk2 weeks ago" }, { "code": null, "e": 2509, "s": 2392, "text": "Hello everyone. Most easy with just one loop and one if statement without using any inbuilt function. java solution." }, { "code": null, "e": 2711, "s": 2509, "text": "public int largest(int arr[], int n) { int largest = 0; for(int i=0; i<n; i++){ if(arr[i]>largest){ largest = arr[i]; } } return largest; }" }, { "code": null, "e": 2713, "s": 2711, "text": "0" }, { "code": null, "e": 2738, "s": 2713, "text": "jeetsorathiya2 weeks ago" }, { "code": null, "e": 2758, "s": 2738, "text": "my solution in java" }, { "code": null, "e": 2783, "s": 2760, "text": "just use sort function" }, { "code": null, "e": 2822, "s": 2785, "text": "Arrays.sort(arr); return arr[n-1];" }, { "code": null, "e": 2825, "s": 2822, "text": "+1" }, { "code": null, "e": 2848, "s": 2825, "text": "akash2420182 weeks ago" }, { "code": null, "e": 2863, "s": 2848, "text": "#python3 Code " }, { "code": null, "e": 2990, "s": 2865, "text": "def largest( arr, n): maxium=arr[0] for i in range (n): if(arr[i]>maxium): maxium=arr[i] return maxium" }, { "code": null, "e": 3136, "s": 2990, "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": 3172, "s": 3136, "text": " Login to access your submissions. " }, { "code": null, "e": 3182, "s": 3172, "text": "\nProblem\n" }, { "code": null, "e": 3192, "s": 3182, "text": "\nContest\n" }, { "code": null, "e": 3255, "s": 3192, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3403, "s": 3255, "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": 3611, "s": 3403, "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": 3717, "s": 3611, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Cross Validation — Why & How. Importance Of Cross Validation In... | by Amitrajit Bose | Towards Data Science
So, you have been working on an imbalanced data set for a few days now and trying out different machine learning models, training them on a part of your data set, testing their accuracy and you are ecstatic to see the score going above 0.95 every-time. Do you really think you have achieved 95% accuracy with your model? I’m assuming that you have performed top-notch pre-processing on your data-set, also you have removed any missing values or categorical values and noise. Whatsoever state-of-the-art algorithm you have used to build your hypothesis function and train the machine learning model, you have to evaluate its performance before moving forward with it. Now the easiest and fastest method to evaluate a model is to split the data set into training and testing set, train the model using the training set data and check its accuracy with the accuracy. And do not forget to shuffle the data set before performing the split. But this method is not at all an assurance, in simple words you cannot rely on this approach while finalizing a model. You might be wondering — Why? Let us consider, you are working on a spam emails data set, which contains 98% of spam emails and 2% of non-spam valid emails. In this case, even if you do not create any model but just classify every input as spam, you will be getting 0.98 accuracy. This condition is called accuracy paradox. Imagine what would happen if this was a model for classification of tumour cells or chest X-rays and you had pushed a 98% accurate model to the market. Maybe this would have killed hundreds of patients, you never know. Do not worry and grab a cup of something warm. In the article below, I will be explaining the entire process of evaluation of your machine learning model. All you need to know is some basic Python syntax as a prerequisite. We initially split up the entire data we have got into two sets, one is used to train the model upon and the other is kept as a holdout set which is used to check how the model behaves with completely unseen data. The figure below summarises the entire idea of performing the split. Please note, that the train test ratio can be anything like 80:20, 75:25, 90:10, etc. This is a decision that the machine learning engineer has to take based on the amount of data. A good rule of thumb is to use 25% of the data-set for testing. You can do this with ease using some Python and the open source Sci-kit Learn API. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42, shuffle = True, stratify = y) X is the original entire set of features and y is the entire set of corresponding true labels. The above function splits the entire set into train and test set with a ratio of 0.3 assigned for the test set. The parameter shuffle is set to true, thus the data set will be randomly shuffled before the split. The parameter stratify is recently added to Sci-kit Learn from v0.17 , it is essential when dealing with imbalanced data sets, such as the spam classification example. It makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to the parameter stratify. For example, if the variable y is a binary categorical variable with values 0 and 1 and there are 10% of zeros and 90% of ones, stratify=y will make sure that your random split has 10% of 0's and 90% of 1's. As we were discussing, only checking how many examples from the test set were classified correctly is not a useful metric for checking model performance because of factors such as class imbalance. We need a more robust and nuanced metric. Say hello to the confusion matrix. An easy and popular method of diagnosing model performance. Let us understand this with our scenario of spam email classification. The confusion matrix would look like this. There are several metrics that can be deduced from the confusion matrix, such as — Accuracy = (TP + TN) /(TP + TN + FP + FN)Precision = (TP) / (TP + FP)Recall = (TP) / (TP + FN)F1 Score = (2 x Precision x Recall) / (Precision + Recall)— where TP is True Positive, FN is False Negative and likewise for the rest. Precision is basically all the things that you said were relevant whereas Recall is all the things that are actually relevant. In other words, recall is also referred to as the sensitivity of your model, whereas precision is referred to as Positive Predicted Value. Here’s a one-pager cheat sheet to summarise it all. Now that you have grasped the concept, let's understand how to do it with ease using the Sci-kit Learn API and a few lines of Python. from sklearn.metrics import confusion_matrix, classification_reporty_pred = model.predict (X_test)print(confusion_matrix(y_test, y_pred))print(classification_report(y_test, y_pred)) Assuming that you have prepared the model using the .fit() method on the training set (on which I shall write probably some other day), you then calculate the predicted set of labels using the .predict() method of the model. You have the original labels for these in y_test and you pass the two arrays into the above two functions. What you’ll get will be a two-by-two confusion matrix (because spam classification is binary classification) and a classification report which returns all the above-discussed metrics. Note: The true values are passed as the first parameter and the predicted values is the second parameter. Cross validation is a technique for assessing how the statistical analysis generalises to an independent data set.It is a technique for evaluating machine learning models by training several models on subsets of the available input data and evaluating them on the complementary subset of the data. Using cross-validation, there are high chances that we can detect over-fitting with ease. There are several cross validation techniques such as :-1. K-Fold Cross Validation2. Leave P-out Cross Validation3. Leave One-out Cross Validation4. Repeated Random Sub-sampling Method5. Holdout Method In this post, we will discuss the most popular method of them i.e the K-Fold Cross Validation. The others are also very effective but less common to use. So let’s take a minute to ask ourselves why we need cross-validation — We have been splitting the data set into a training set and testing set (or holdout set). But, the accuracy and metrics are highly biased upon how the split was performed, it depends upon whether the data set was shuffled, which part was taken for training and testing, how much, so on. Moreover, it is not representative of the model’s ability to generalize. This leads us to cross validation. First I would like to introduce you to a golden rule — “Never mix training and test data”. Your first step should always be to isolate the test data-set and use it only for final evaluation. Cross-validation will thus be performed on the training set. Initially, the entire training data set is broken up in k equal parts. The first part is kept as the hold out (testing) set and the remaining k-1 parts are used to train the model. Then the trained model is then tested on the holdout set. The above process is repeated k times, in each case we keep on changing the holdout set. Thus, every data point get an equal opportunity to be included in the test set. Usually, k is equal to 3 or 5. It can be extended even to higher values like 10 or 15 but it becomes extremely computationally expensive and time-consuming. Let us have a look at how we can implement this with a few lines of Python code and the Sci-kit Learn API. from sklearn.model_selection import cross_val_scoreprint(cross_val_score(model, X_train, y_train, cv=5)) We pass the model or classifier object, the features, the labels and the parameter cv which indicates the K for K-Fold cross-validation. The method will return a list of k accuracy values for each iteration. In general, we take the average of them and use it as a consolidated cross-validation score. import numpy as npprint(np.mean(cross_val_score(model, X_train, y_train, cv=5))) Although it might be computationally expensive, cross-validation is essential for evaluating the performance of the learning model. Feel free to have a look at the other cross-validation score evaluation methods which I have included in the references section, at the end of this article. The accuracy requirement of a machine learning model varies across industry, domain, requirement and problem statement. But confirming a final model should never be performed without evaluation of all essential metrics. By the way, once you are done with evaluation and finally confirming your machine learning model, you should re-use the test data that was initially isolated for testing purposes only and train your model with the complete data you have so as to increase the chances for a better prediction. Thanks for reading. This was a high-level overview of the topic, I tried to put my best efforts to explain the concepts at hand in an easy way. Please feel free to comment, criticize and suggest improvements to the article. Also, claps highly encourage me to write more! Stay tuned for more articles. Have a look at this friendly introduction to neural networks with PyTorch. [1]Leave P-out Cross Validation[2]Leave One-out Cross Validation[3]Repeated Random Sub-sampling Method[4]Holdout Method[5]Cross Validation[6]Stanford’s MOOC — Statistical Learning With R — Course notes
[ { "code": null, "e": 493, "s": 172, "text": "So, you have been working on an imbalanced data set for a few days now and trying out different machine learning models, training them on a part of your data set, testing their accuracy and you are ecstatic to see the score going above 0.95 every-time. Do you really think you have achieved 95% accuracy with your model?" }, { "code": null, "e": 839, "s": 493, "text": "I’m assuming that you have performed top-notch pre-processing on your data-set, also you have removed any missing values or categorical values and noise. Whatsoever state-of-the-art algorithm you have used to build your hypothesis function and train the machine learning model, you have to evaluate its performance before moving forward with it." }, { "code": null, "e": 1256, "s": 839, "text": "Now the easiest and fastest method to evaluate a model is to split the data set into training and testing set, train the model using the training set data and check its accuracy with the accuracy. And do not forget to shuffle the data set before performing the split. But this method is not at all an assurance, in simple words you cannot rely on this approach while finalizing a model. You might be wondering — Why?" }, { "code": null, "e": 1550, "s": 1256, "text": "Let us consider, you are working on a spam emails data set, which contains 98% of spam emails and 2% of non-spam valid emails. In this case, even if you do not create any model but just classify every input as spam, you will be getting 0.98 accuracy. This condition is called accuracy paradox." }, { "code": null, "e": 1769, "s": 1550, "text": "Imagine what would happen if this was a model for classification of tumour cells or chest X-rays and you had pushed a 98% accurate model to the market. Maybe this would have killed hundreds of patients, you never know." }, { "code": null, "e": 1992, "s": 1769, "text": "Do not worry and grab a cup of something warm. In the article below, I will be explaining the entire process of evaluation of your machine learning model. All you need to know is some basic Python syntax as a prerequisite." }, { "code": null, "e": 2275, "s": 1992, "text": "We initially split up the entire data we have got into two sets, one is used to train the model upon and the other is kept as a holdout set which is used to check how the model behaves with completely unseen data. The figure below summarises the entire idea of performing the split." }, { "code": null, "e": 2520, "s": 2275, "text": "Please note, that the train test ratio can be anything like 80:20, 75:25, 90:10, etc. This is a decision that the machine learning engineer has to take based on the amount of data. A good rule of thumb is to use 25% of the data-set for testing." }, { "code": null, "e": 2603, "s": 2520, "text": "You can do this with ease using some Python and the open source Sci-kit Learn API." }, { "code": null, "e": 2779, "s": 2603, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42, shuffle = True, stratify = y)" }, { "code": null, "e": 3616, "s": 2779, "text": "X is the original entire set of features and y is the entire set of corresponding true labels. The above function splits the entire set into train and test set with a ratio of 0.3 assigned for the test set. The parameter shuffle is set to true, thus the data set will be randomly shuffled before the split. The parameter stratify is recently added to Sci-kit Learn from v0.17 , it is essential when dealing with imbalanced data sets, such as the spam classification example. It makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to the parameter stratify. For example, if the variable y is a binary categorical variable with values 0 and 1 and there are 10% of zeros and 90% of ones, stratify=y will make sure that your random split has 10% of 0's and 90% of 1's." }, { "code": null, "e": 3855, "s": 3616, "text": "As we were discussing, only checking how many examples from the test set were classified correctly is not a useful metric for checking model performance because of factors such as class imbalance. We need a more robust and nuanced metric." }, { "code": null, "e": 4064, "s": 3855, "text": "Say hello to the confusion matrix. An easy and popular method of diagnosing model performance. Let us understand this with our scenario of spam email classification. The confusion matrix would look like this." }, { "code": null, "e": 4147, "s": 4064, "text": "There are several metrics that can be deduced from the confusion matrix, such as —" }, { "code": null, "e": 4377, "s": 4147, "text": "Accuracy = (TP + TN) /(TP + TN + FP + FN)Precision = (TP) / (TP + FP)Recall = (TP) / (TP + FN)F1 Score = (2 x Precision x Recall) / (Precision + Recall)— where TP is True Positive, FN is False Negative and likewise for the rest." }, { "code": null, "e": 4695, "s": 4377, "text": "Precision is basically all the things that you said were relevant whereas Recall is all the things that are actually relevant. In other words, recall is also referred to as the sensitivity of your model, whereas precision is referred to as Positive Predicted Value. Here’s a one-pager cheat sheet to summarise it all." }, { "code": null, "e": 4829, "s": 4695, "text": "Now that you have grasped the concept, let's understand how to do it with ease using the Sci-kit Learn API and a few lines of Python." }, { "code": null, "e": 5011, "s": 4829, "text": "from sklearn.metrics import confusion_matrix, classification_reporty_pred = model.predict (X_test)print(confusion_matrix(y_test, y_pred))print(classification_report(y_test, y_pred))" }, { "code": null, "e": 5527, "s": 5011, "text": "Assuming that you have prepared the model using the .fit() method on the training set (on which I shall write probably some other day), you then calculate the predicted set of labels using the .predict() method of the model. You have the original labels for these in y_test and you pass the two arrays into the above two functions. What you’ll get will be a two-by-two confusion matrix (because spam classification is binary classification) and a classification report which returns all the above-discussed metrics." }, { "code": null, "e": 5633, "s": 5527, "text": "Note: The true values are passed as the first parameter and the predicted values is the second parameter." }, { "code": null, "e": 6021, "s": 5633, "text": "Cross validation is a technique for assessing how the statistical analysis generalises to an independent data set.It is a technique for evaluating machine learning models by training several models on subsets of the available input data and evaluating them on the complementary subset of the data. Using cross-validation, there are high chances that we can detect over-fitting with ease." }, { "code": null, "e": 6223, "s": 6021, "text": "There are several cross validation techniques such as :-1. K-Fold Cross Validation2. Leave P-out Cross Validation3. Leave One-out Cross Validation4. Repeated Random Sub-sampling Method5. Holdout Method" }, { "code": null, "e": 6377, "s": 6223, "text": "In this post, we will discuss the most popular method of them i.e the K-Fold Cross Validation. The others are also very effective but less common to use." }, { "code": null, "e": 6843, "s": 6377, "text": "So let’s take a minute to ask ourselves why we need cross-validation — We have been splitting the data set into a training set and testing set (or holdout set). But, the accuracy and metrics are highly biased upon how the split was performed, it depends upon whether the data set was shuffled, which part was taken for training and testing, how much, so on. Moreover, it is not representative of the model’s ability to generalize. This leads us to cross validation." }, { "code": null, "e": 7095, "s": 6843, "text": "First I would like to introduce you to a golden rule — “Never mix training and test data”. Your first step should always be to isolate the test data-set and use it only for final evaluation. Cross-validation will thus be performed on the training set." }, { "code": null, "e": 7503, "s": 7095, "text": "Initially, the entire training data set is broken up in k equal parts. The first part is kept as the hold out (testing) set and the remaining k-1 parts are used to train the model. Then the trained model is then tested on the holdout set. The above process is repeated k times, in each case we keep on changing the holdout set. Thus, every data point get an equal opportunity to be included in the test set." }, { "code": null, "e": 7767, "s": 7503, "text": "Usually, k is equal to 3 or 5. It can be extended even to higher values like 10 or 15 but it becomes extremely computationally expensive and time-consuming. Let us have a look at how we can implement this with a few lines of Python code and the Sci-kit Learn API." }, { "code": null, "e": 7872, "s": 7767, "text": "from sklearn.model_selection import cross_val_scoreprint(cross_val_score(model, X_train, y_train, cv=5))" }, { "code": null, "e": 8173, "s": 7872, "text": "We pass the model or classifier object, the features, the labels and the parameter cv which indicates the K for K-Fold cross-validation. The method will return a list of k accuracy values for each iteration. In general, we take the average of them and use it as a consolidated cross-validation score." }, { "code": null, "e": 8254, "s": 8173, "text": "import numpy as npprint(np.mean(cross_val_score(model, X_train, y_train, cv=5)))" }, { "code": null, "e": 8386, "s": 8254, "text": "Although it might be computationally expensive, cross-validation is essential for evaluating the performance of the learning model." }, { "code": null, "e": 8543, "s": 8386, "text": "Feel free to have a look at the other cross-validation score evaluation methods which I have included in the references section, at the end of this article." }, { "code": null, "e": 8763, "s": 8543, "text": "The accuracy requirement of a machine learning model varies across industry, domain, requirement and problem statement. But confirming a final model should never be performed without evaluation of all essential metrics." }, { "code": null, "e": 9055, "s": 8763, "text": "By the way, once you are done with evaluation and finally confirming your machine learning model, you should re-use the test data that was initially isolated for testing purposes only and train your model with the complete data you have so as to increase the chances for a better prediction." }, { "code": null, "e": 9356, "s": 9055, "text": "Thanks for reading. This was a high-level overview of the topic, I tried to put my best efforts to explain the concepts at hand in an easy way. Please feel free to comment, criticize and suggest improvements to the article. Also, claps highly encourage me to write more! Stay tuned for more articles." }, { "code": null, "e": 9431, "s": 9356, "text": "Have a look at this friendly introduction to neural networks with PyTorch." } ]
Area of Largest rectangle that can be inscribed in an Ellipse?
Here we will see the area of largest rectangle that can be inscribed in an ellipse. The rectangle in ellipse will be like below − The a and b are the half of major and minor axis of the ellipse. The upper right corner of the rectangle is (x, y). So the area is Now, after making this equation as f(x) and maximizing the area, we will get the area as #include <iostream> #include <cmath> using namespace std; float area(float a, float b) { if (a < 0 || b < 0 ) //if the valuse are negative it is invalid return -1; float area = 2*a*b; return area; } int main() { float a = 10, b = 8; cout << "Area : " << area(a, b); } Area : 160
[ { "code": null, "e": 1192, "s": 1062, "text": "Here we will see the area of largest rectangle that can be inscribed in an ellipse. The rectangle in ellipse will be like below −" }, { "code": null, "e": 1323, "s": 1192, "text": "The a and b are the half of major and minor axis of the ellipse. The upper right corner of the rectangle is (x, y). So the area is" }, { "code": null, "e": 1412, "s": 1323, "text": "Now, after making this equation as f(x) and maximizing the area, we will get the area as" }, { "code": null, "e": 1701, "s": 1412, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nfloat area(float a, float b) {\n if (a < 0 || b < 0 ) //if the valuse are negative it is invalid\n return -1;\n float area = 2*a*b;\n return area;\n}\nint main() {\n float a = 10, b = 8;\n cout << \"Area : \" << area(a, b);\n}" }, { "code": null, "e": 1712, "s": 1701, "text": "Area : 160" } ]
Explain switch statement in C language
It is used to select one among multiple decisions. ‘switch’ successively tests a value against a list of integers (or) character constant. When a match is found, the statement (or) statements associated with that value are executed. The syntax is given below − switch (expression){ case value1 : stmt1; break; case value2 : stmt2; break; - - - - - - default : stmt – x; } Refer the algorithm given below − Step 1: Declare variables. Step 2: Read expression variable. Step 3: Switch(expression) If value 1 is select : stmt 1 executes break (exists from switch) If value 2 is select : stmt 2 executes ;break If value 3 is select : stmt 3 executes; break ................................................... Default : stmt-x executes; The following C program demonstrates the usage of switch statement − Live Demo #include<stdio.h> main ( ){ int n; printf ("enter a number"); scanf ("%d", &n); switch (n){ case 0 : printf ("zero"); break; case 1 : printf ("one"); break; default : printf ("wrong choice"); } } You will see the following output − enter a number 1 One Consider another program on switch case as mentioned below − Live Demo #include<stdio.h> int main(){ char grade; printf("Enter the grade of a student:\n"); scanf("%c",&grade); switch(grade){ case 'A': printf("Distiction\n"); break; case 'B': printf("First class\n"); break; case 'C': printf("second class \n"); break; case 'D': printf("third class\n"); break; default : printf("Fail"); } printf("Student grade=%c",grade); return 0; } You will see the following output − Run 1:Enter the grade of a student:A Distiction Student grade=A Run 2: Enter the grade of a student:C Second class Student grade=C
[ { "code": null, "e": 1295, "s": 1062, "text": "It is used to select one among multiple decisions. ‘switch’ successively tests a value against a list of integers (or) character constant. When a match is found, the statement (or) statements associated with that value are executed." }, { "code": null, "e": 1323, "s": 1295, "text": "The syntax is given below −" }, { "code": null, "e": 1458, "s": 1323, "text": "switch (expression){\n case value1 : stmt1;\n break;\n case value2 : stmt2;\n break;\n - - - - - -\n default : stmt – x;\n}" }, { "code": null, "e": 1492, "s": 1458, "text": "Refer the algorithm given below −" }, { "code": null, "e": 1829, "s": 1492, "text": "Step 1: Declare variables.\nStep 2: Read expression variable.\nStep 3: Switch(expression)\n If value 1 is select : stmt 1 executes break (exists from switch)\n If value 2 is select : stmt 2 executes ;break\n If value 3 is select : stmt 3 executes; break\n ...................................................\nDefault : stmt-x executes;" }, { "code": null, "e": 1898, "s": 1829, "text": "The following C program demonstrates the usage of switch statement −" }, { "code": null, "e": 1909, "s": 1898, "text": " Live Demo" }, { "code": null, "e": 2156, "s": 1909, "text": "#include<stdio.h>\nmain ( ){\n int n;\n printf (\"enter a number\");\n scanf (\"%d\", &n);\n switch (n){\n case 0 : printf (\"zero\");\n break;\n case 1 : printf (\"one\");\n break;\n default : printf (\"wrong choice\");\n }\n}" }, { "code": null, "e": 2192, "s": 2156, "text": "You will see the following output −" }, { "code": null, "e": 2213, "s": 2192, "text": "enter a number\n1\nOne" }, { "code": null, "e": 2274, "s": 2213, "text": "Consider another program on switch case as mentioned below −" }, { "code": null, "e": 2285, "s": 2274, "text": " Live Demo" }, { "code": null, "e": 2735, "s": 2285, "text": "#include<stdio.h>\nint main(){\n char grade;\n printf(\"Enter the grade of a student:\\n\");\n scanf(\"%c\",&grade);\n switch(grade){\n case 'A': printf(\"Distiction\\n\");\n break;\n case 'B': printf(\"First class\\n\");\n break;\n case 'C': printf(\"second class \\n\");\n break;\n case 'D': printf(\"third class\\n\");\n break;\n default : printf(\"Fail\");\n }\n printf(\"Student grade=%c\",grade);\n return 0;\n}" }, { "code": null, "e": 2771, "s": 2735, "text": "You will see the following output −" }, { "code": null, "e": 2902, "s": 2771, "text": "Run 1:Enter the grade of a student:A\nDistiction\nStudent grade=A\nRun 2: Enter the grade of a student:C\nSecond class\nStudent grade=C" } ]
TimeSpan.Compare() Method in C#
The TimeSpan.Compare() method in C# is used to compare two TimeSpan values and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value. The return value is -1 if span1 is shorter than span2, 0 if span1=span2, whereas 1 if span1 is longer than span2. The syntax is as follows − public static int Compare (TimeSpan span1, TimeSpan span2); Above, the parameter span1 is the 1st time interval to compare, whereas span2 is the 2nd interval to compare. Let us now see an example − Live Demo using System; public class Demo { public static void Main(){ TimeSpan span1 = new TimeSpan(-6, 25, 0); TimeSpan span2 = new TimeSpan(1, 11, 25, 20); TimeSpan span3 = TimeSpan.MinValue; TimeSpan res1 = span1.Add(span2); TimeSpan res2 = span2.Add(span3); Console.WriteLine("Final Timespan (TimeSpan1 + TimeSpan2) = "+res1); Console.WriteLine("Final Timespan (TimeSpan2 + TimeSpan3) = "+res2); Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2)); } } This will produce the following output − Final Timespan (TimeSpan1 + TimeSpan2) = 1.05:50:20 Final Timespan (TimeSpan2 + TimeSpan3) = -10675197.15:22:45.4775808 Result (Comparison of span1 and span2) = -1 Let us now see another example − Live Demo using System; public class Demo { public static void Main(){ TimeSpan span1 = new TimeSpan(-6, 25, 0); TimeSpan span2 = new TimeSpan(1, 10, 0); Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2)); } } This will produce the following output − Result (Comparison of span1 and span2) = -1
[ { "code": null, "e": 1259, "s": 1062, "text": "The TimeSpan.Compare() method in C# is used to compare two TimeSpan values\nand returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value." }, { "code": null, "e": 1373, "s": 1259, "text": "The return value is -1 if span1 is shorter than span2, 0 if span1=span2, whereas 1 if span1 is longer than span2." }, { "code": null, "e": 1400, "s": 1373, "text": "The syntax is as follows −" }, { "code": null, "e": 1460, "s": 1400, "text": "public static int Compare (TimeSpan span1, TimeSpan span2);" }, { "code": null, "e": 1570, "s": 1460, "text": "Above, the parameter span1 is the 1st time interval to compare, whereas span2 is the 2nd interval to compare." }, { "code": null, "e": 1598, "s": 1570, "text": "Let us now see an example −" }, { "code": null, "e": 1609, "s": 1598, "text": " Live Demo" }, { "code": null, "e": 2153, "s": 1609, "text": "using System;\npublic class Demo {\n public static void Main(){\n TimeSpan span1 = new TimeSpan(-6, 25, 0);\n TimeSpan span2 = new TimeSpan(1, 11, 25, 20);\n TimeSpan span3 = TimeSpan.MinValue;\n TimeSpan res1 = span1.Add(span2);\n TimeSpan res2 = span2.Add(span3);\n Console.WriteLine(\"Final Timespan (TimeSpan1 + TimeSpan2) = \"+res1);\n Console.WriteLine(\"Final Timespan (TimeSpan2 + TimeSpan3) = \"+res2);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n }\n}" }, { "code": null, "e": 2194, "s": 2153, "text": "This will produce the following output −" }, { "code": null, "e": 2358, "s": 2194, "text": "Final Timespan (TimeSpan1 + TimeSpan2) = 1.05:50:20\nFinal Timespan (TimeSpan2 + TimeSpan3) = -10675197.15:22:45.4775808\nResult (Comparison of span1 and span2) = -1" }, { "code": null, "e": 2391, "s": 2358, "text": "Let us now see another example −" }, { "code": null, "e": 2402, "s": 2391, "text": " Live Demo" }, { "code": null, "e": 2669, "s": 2402, "text": "using System;\npublic class Demo {\n public static void Main(){\n TimeSpan span1 = new TimeSpan(-6, 25, 0);\n TimeSpan span2 = new TimeSpan(1, 10, 0);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n }\n}" }, { "code": null, "e": 2710, "s": 2669, "text": "This will produce the following output −" }, { "code": null, "e": 2754, "s": 2710, "text": "Result (Comparison of span1 and span2) = -1" } ]
DateFormat format() Method in Java with Examples - GeeksforGeeks
13 Jan, 2022 DateFormat class present inside java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time. DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner. The format() method of DateFormat class in Java is used to format a given date into a Date/Time string. Basically, the method is used to convert this date and time into a particular format i.e., mm/dd/yyyy. Syntax: public final String format(Date date) Parameters: The method takes one parameter date of the Date object type and refers to the date whose string output is to be produced. Return Type: Returns Date or time in string format of mm/dd/yyyy. Example 1: Java // Java Program to Illustrate format() Method// of DateTime Class // Importing required classesimport java.text.*;import java.util.Calendar; // Main class// DateFormat_Demopublic class GFG { // Main driver method public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateInstance(); // Initializing the calender Object Calendar cal = Calendar.getInstance(); // Displaying the actual date System.out.println("The original Date: " + cal.getTime()); // Converting date using format() method String curr_date = DFormat.format(cal.getTime()); // Printing the formatted date System.out.println("Formatted Date: " + curr_date); }} The original Date: Wed Mar 27 11:12:29 UTC 2019 Formatted Date: Mar 27, 2019 Example 2: Java // Java Program to Illustrate format() Method// of DateTime Class // Importing required classesimport java.text.*;import java.util.*; // Main class// DateFormat_Demopublic class GFG { // Main driver method public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); // Initializing the calender Object Calendar cal = Calendar.getInstance(); // Displaying the actual date System.out.println("The original Date: " + cal.getTime()); // Converting date using format() method and // storing date in a string String curr_date = DFormat.format(cal.getTime()); // Printing the formatted date on console System.out.println("Formatted Date: " + curr_date); }} The original Date: Tue Jan 11 05:42:29 UTC 2022 Formatted Date: January 11, 2022 at 5:42:29 AM UTC solankimayank Java - util package Java-DateFormat Java-Functions Java 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 Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java
[ { "code": null, "e": 24508, "s": 24480, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25050, "s": 24508, "text": "DateFormat class present inside java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time. DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner. " }, { "code": null, "e": 25257, "s": 25050, "text": "The format() method of DateFormat class in Java is used to format a given date into a Date/Time string. Basically, the method is used to convert this date and time into a particular format i.e., mm/dd/yyyy." }, { "code": null, "e": 25266, "s": 25257, "text": "Syntax: " }, { "code": null, "e": 25304, "s": 25266, "text": "public final String format(Date date)" }, { "code": null, "e": 25438, "s": 25304, "text": "Parameters: The method takes one parameter date of the Date object type and refers to the date whose string output is to be produced." }, { "code": null, "e": 25504, "s": 25438, "text": "Return Type: Returns Date or time in string format of mm/dd/yyyy." }, { "code": null, "e": 25515, "s": 25504, "text": "Example 1:" }, { "code": null, "e": 25520, "s": 25515, "text": "Java" }, { "code": "// Java Program to Illustrate format() Method// of DateTime Class // Importing required classesimport java.text.*;import java.util.Calendar; // Main class// DateFormat_Demopublic class GFG { // Main driver method public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateInstance(); // Initializing the calender Object Calendar cal = Calendar.getInstance(); // Displaying the actual date System.out.println(\"The original Date: \" + cal.getTime()); // Converting date using format() method String curr_date = DFormat.format(cal.getTime()); // Printing the formatted date System.out.println(\"Formatted Date: \" + curr_date); }}", "e": 26316, "s": 25520, "text": null }, { "code": null, "e": 26393, "s": 26316, "text": "The original Date: Wed Mar 27 11:12:29 UTC 2019\nFormatted Date: Mar 27, 2019" }, { "code": null, "e": 26406, "s": 26395, "text": "Example 2:" }, { "code": null, "e": 26411, "s": 26406, "text": "Java" }, { "code": "// Java Program to Illustrate format() Method// of DateTime Class // Importing required classesimport java.text.*;import java.util.*; // Main class// DateFormat_Demopublic class GFG { // Main driver method public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); // Initializing the calender Object Calendar cal = Calendar.getInstance(); // Displaying the actual date System.out.println(\"The original Date: \" + cal.getTime()); // Converting date using format() method and // storing date in a string String curr_date = DFormat.format(cal.getTime()); // Printing the formatted date on console System.out.println(\"Formatted Date: \" + curr_date); }}", "e": 27329, "s": 26411, "text": null }, { "code": null, "e": 27428, "s": 27329, "text": "The original Date: Tue Jan 11 05:42:29 UTC 2022\nFormatted Date: January 11, 2022 at 5:42:29 AM UTC" }, { "code": null, "e": 27442, "s": 27428, "text": "solankimayank" }, { "code": null, "e": 27462, "s": 27442, "text": "Java - util package" }, { "code": null, "e": 27478, "s": 27462, "text": "Java-DateFormat" }, { "code": null, "e": 27493, "s": 27478, "text": "Java-Functions" }, { "code": null, "e": 27498, "s": 27493, "text": "Java" }, { "code": null, "e": 27503, "s": 27498, "text": "Java" }, { "code": null, "e": 27601, "s": 27503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27610, "s": 27601, "text": "Comments" }, { "code": null, "e": 27623, "s": 27610, "text": "Old Comments" }, { "code": null, "e": 27653, "s": 27623, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27685, "s": 27653, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27736, "s": 27685, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27755, "s": 27736, "text": "Interfaces in Java" }, { "code": null, "e": 27773, "s": 27755, "text": "ArrayList in Java" }, { "code": null, "e": 27804, "s": 27773, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27836, "s": 27804, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27860, "s": 27836, "text": "Singleton Class in Java" }, { "code": null, "e": 27880, "s": 27860, "text": "Stack Class in Java" } ]
Focal Loss & Class Imbalance Data: TensorFlow | Towards Data Science
In machine learning sometimes we are dealt with a very good hand like MNIST fashion data or CIFAR-10 data where the examples of each class in the data-set are well balanced. What happens if in a classification problem the distribution of examples across the known classes are biased or skewed ? Such problems with severe to slight bias in the data-set are common and today we will discuss an approach to handle such class imbalanced data. Let’s consider an extreme case of imbalanced data-set of mails and we build a classifier to detect spam mails. Since spam mails are relatively rarer, let’s consider 5% of all mails are spams. If we just a write a simple one line code as — def detectspam(mail-data): return ‘not spam’ This will give us right answer 95% of time and even though this is an extreme hyperbole but you get the problem. Most importantly, training any model with this data will lead to high confidence prediction of the general mails and due to extreme low number of spam mails in the training data, the model will likely not learn to predict the spam mails correctly. This is why precision, recall, F1 score, ROC/AUC curves are the important metrics that truly tell us the story. As you have already guessed one way to reduce this issue is to do sampling to balance the data-set so that classes are balanced. There are several other ways to address class imbalance problem in machine learning and an excellent comprehensive review has been put together by Jason Brownlee, check it here. In case of computer vision problem, this class imbalance problem can be more critical and here we discuss how the authors approached object detection tasks that lead to the development of focal loss. In case of Fast R-CNN type of algorithms, first we run an image through ConvNet to obtain a feature map and then region proposal is performed (generally around 2K regions) on the high resolution feature map. These are 2-stage detectors and when the Focal Loss paper was introduced the intriguing question was whether one stage detector like YOLO or SSD could obtain same accuracy as 2-stage detectors? One stage detectors were fast but the accuracy during that time was around 10–40% of the 2-stage detectors. The authors suggested that class imbalance during training as the main obstacle that prevents the one stage detectors to obtain same accuracy as 2-stage detectors. An example of such class imbalance is shown in the self-explanatory Figure 1, which is taken from the presentation itself by the original authors. They found that one stage detectors perform better when there are higher number of bounding boxes covering the space of possible objects. But this approach caused a major problem as the foreground and background data are not equally distributed. For example if we consider 20000 bounding boxes mostly 7–10 of them will actually contain any info about the object and the remaining will be containing background and, mostly they will be easy to classify but uninformative. Here, the authors found out that Loss function (e.g. Cross-Entropy) is the main reason that the easy examples will distract the training. Below is a pictorial representation Even though the wrongly classified samples are penalized more (red arrow in fig. 1) than the correct ones (green arrow), in the dense object detection settings, due to the imbalanced sample size, the loss function is overwhelmed with background (easy samples). The Focal Loss addresses this problem and it is designed in such a way so that it reduces the loss (‘down-weight’) for the easy examples and thus the network can focus on training the hard examples. Below is the definition of Focal Loss — In focal loss, there’s a modulating factor multiplied to the Cross-Entropy loss. When a sample is misclassified, p (which represents model’s estimated probability for the class with label y = 1) is low and the modulating factor is near 1 and, the loss is unaffected. As p→1, the modulating factor approaches 0 and the loss for well-classified examples is down-weighted. The effect of γ parameter is shown in the plot below — To quote from the paper — The modulating factor reduces the loss contribution from easy examples and extends the range in which an example receives low loss. To understand this we will compare Cross-Entropy (CE) loss and Focal Loss using the definition above with γ = 2. Consider true value 1.0, and we consider 3 prediction values 0.90 (close), 0.95 (very close), 0.20 (far from true). Let’s see the loss values below using TensorFlow— CE loss when pred is close to true: 0.10536041CE loss when pred is very close to true: 0.051293183CE loss when pred is far from true: 1.6094373focal loss when pred is close to true: 0.0010536041110754007focal loss when pred is very close to true: 0.00012823295779526255focal loss when pred is far from true: 1.0300399017333985 Here we see that compared to CE loss, the modulating factor in focal loss plays an important role. When prediction is close to the truth the loss is penalized way more than when when it is far. Importantly when prediction is 0.90 focal loss will be 0.01 × CE loss but when prediction is 0.95, focal loss will be around 0.002 × CE loss. Now we get a picture how focal loss reduces the loss contribution from easy examples and extends the range in which an example receives low loss. This can also be seen from fig. 3. Now we will use a real-world class imbalanced data-set and see focal loss in action. Data-set Description: Here I have considered an extreme class-imbalanced data-set available in Kaggle and the data-set contains transactions made by credit cards in September 2013 by European cardholders. Let’s use pandas — This data-set presents transactions that occurred in two days and we have 284,807 number of transactions. Features V1, V2,...V28 are the principal components obtained with PCA (original features are not provided due to confidential issues) and the only features which have not been transformed with PCA are ‘Time’ and ‘Amount’. Feature ‘Time’ contains the seconds elapsed between each transaction and the first transaction in the dataset and the feature ‘Amount’ is the transaction amount. Feature ‘Class’ is the response variable and it takes value 1 in case of fraud and 0 otherwise. Class Imbalance: Let’s plot the distribution of the ‘Class’ feature which tells us how many transactions are real and fake. As shown in figure 4 above, overwhelming numbers of transactions are real. Let’s get the numbers with this simple piece of code — print (‘real cases:‘, len(credit_df[credit_df[‘Class’]==0]))print (‘fraud cases: ‘, len(credit_df[credit_df[‘Class’]==1]))>>> real cases: 284315 fraud cases: 492 So the class imbalance ratio is about 1:578, so for 578 real transactions we have one fraud case. First let’s use a simple neural network with cross-entropy loss to predict fraud and real transactions. But before that a little examination tells us that ‘Amount’ and ‘Time’ features are not scaled whereas other features ‘V1’, ‘V2’...etc are scaled. Here we can use StandardScaler/RobustScaler to scale these features and since RobustScaler are robust to outliers, I chose this standardization technique. Let’s now choose the features and label as below — X_labels = credit_df.drop([‘Class’], axis=1)y_labels = credit_df[‘Class’]X_labels = X_labels.to_numpy(dtype=np.float64)y_labels = y_labels.to_numpy(dtype=np.float64)y_lab_cat = tf.keras.utils.to_categorical(y_labels, num_classes=2, dtype=’float32') For the train-test split we use stratify to keep the ratio of labels — x_train, x_test, y_train, y_test = train_test_split(X_labels, y_lab_cat, test_size=0.3, stratify=y_lab_cat, shuffle=True) Now we build a simple neural-net model with 3 dense layers — def simple_model(): input_data = Input(shape=(x_train.shape[1], )) x = Dense(64)(input_data) x = Activation(activations.relu)(x) x = Dense(32)(x) x = Activation(activations.relu)(x) x = Dense(2)(x) x = Activation(activations.softmax)(x) model = Model(inputs=input_data, outputs=x, name=’Simple_Model’) return model Compile the model with categorical cross-entropy as loss— simple_model.compile(optimizer=Adam(learning_rate=5e-3), loss='categorical_crossentropy', metrics=['acc']) Train the model — simple_model.fit(x_train, y_train, validation_split=0.2, epochs=5, shuffle=True, batch_size=256) To truly understand the performance of the model, we need to plot the confusion matrix along with the precision, recall and F1 scores — We see from the confusion matrix and other performance metric scores that as expected the network does extremely good to classify the real transactions but the recall value is below 50% for the fraud class. Our target is to test without changing anything except the loss function can we get better values for the performance metrics ? First let’s define the focal loss with alpha and gamma as hyper-parameters and to do this I have used the tfa module which is a functionality for TensorFlow maintained by SIG-addons (tfa). Under this module among the additional losses, there’s an implementation of Focal Loss and first we import as below — import tensorflow_addons as tfafl = tfa.losses.SigmoidFocalCrossEntropy(alpha, gamma) Using this, let’s define a custom loss function that can be used as a proxy for ‘Focal Loss’ for this specific problem with two classes— def focal_loss_custom(alpha, gamma): def binary_focal_loss(y_true, y_pred): fl = tfa.losses.SigmoidFocalCrossEntropy(alpha=alpha, gamma=gamma) y_true_K = K.ones_like(y_true) focal_loss = fl(y_true, y_pred) return focal_loss return binary_focal_loss We now just repeat the steps above for model definition, compile and fit but this time using focal loss as below — simple_model.compile(optimizer=Adam(learning_rate=5e-3), loss=focal_loss_custom(alpha=0.2, gamma=2.0), metrics=[‘acc’]) For alpha and gamma parameters, I have just used the values suggested in the paper (however the problem is different) and different values need to be tested. simple_model.fit(x_train, y_train, validation_split=0.2, epochs=5, shuffle=True, batch_size=256) Using Focal Loss we see an improvement as below — We see using ‘Focal Loss’ the performance metrics improved considerably and we could detect more ‘Fraud’ transactions (101/148) correctly compared to the previous case (69/148). Here in this post we discuss Focal Loss and how it can improve classification task when the data is highly imbalanced. To demonstrate Focal Loss in action we used Credit Card Transaction data-set which is highly biased towards real transactions and showed how Focal Loss improves the classification performance. I would also like to mention that , in my research with gamma-ray data we are trying to classify Active Galactic Nuclei (AGN) from Pulsars (PSR) and the gamma-ray sky is mostly populated by AGNs. The picture below is an example of such a simulated sky. This is also an example of class-imbalanced data-set in computer vision. [1] Focal Loss Original Paper [2] Focal Loss Original Presentation [3] Notebook Used in this Post: GitHub
[ { "code": null, "e": 725, "s": 47, "text": "In machine learning sometimes we are dealt with a very good hand like MNIST fashion data or CIFAR-10 data where the examples of each class in the data-set are well balanced. What happens if in a classification problem the distribution of examples across the known classes are biased or skewed ? Such problems with severe to slight bias in the data-set are common and today we will discuss an approach to handle such class imbalanced data. Let’s consider an extreme case of imbalanced data-set of mails and we build a classifier to detect spam mails. Since spam mails are relatively rarer, let’s consider 5% of all mails are spams. If we just a write a simple one line code as —" }, { "code": null, "e": 771, "s": 725, "text": "def detectspam(mail-data): return ‘not spam’ " }, { "code": null, "e": 1551, "s": 771, "text": "This will give us right answer 95% of time and even though this is an extreme hyperbole but you get the problem. Most importantly, training any model with this data will lead to high confidence prediction of the general mails and due to extreme low number of spam mails in the training data, the model will likely not learn to predict the spam mails correctly. This is why precision, recall, F1 score, ROC/AUC curves are the important metrics that truly tell us the story. As you have already guessed one way to reduce this issue is to do sampling to balance the data-set so that classes are balanced. There are several other ways to address class imbalance problem in machine learning and an excellent comprehensive review has been put together by Jason Brownlee, check it here." }, { "code": null, "e": 2425, "s": 1551, "text": "In case of computer vision problem, this class imbalance problem can be more critical and here we discuss how the authors approached object detection tasks that lead to the development of focal loss. In case of Fast R-CNN type of algorithms, first we run an image through ConvNet to obtain a feature map and then region proposal is performed (generally around 2K regions) on the high resolution feature map. These are 2-stage detectors and when the Focal Loss paper was introduced the intriguing question was whether one stage detector like YOLO or SSD could obtain same accuracy as 2-stage detectors? One stage detectors were fast but the accuracy during that time was around 10–40% of the 2-stage detectors. The authors suggested that class imbalance during training as the main obstacle that prevents the one stage detectors to obtain same accuracy as 2-stage detectors." }, { "code": null, "e": 3217, "s": 2425, "text": "An example of such class imbalance is shown in the self-explanatory Figure 1, which is taken from the presentation itself by the original authors. They found that one stage detectors perform better when there are higher number of bounding boxes covering the space of possible objects. But this approach caused a major problem as the foreground and background data are not equally distributed. For example if we consider 20000 bounding boxes mostly 7–10 of them will actually contain any info about the object and the remaining will be containing background and, mostly they will be easy to classify but uninformative. Here, the authors found out that Loss function (e.g. Cross-Entropy) is the main reason that the easy examples will distract the training. Below is a pictorial representation" }, { "code": null, "e": 3717, "s": 3217, "text": "Even though the wrongly classified samples are penalized more (red arrow in fig. 1) than the correct ones (green arrow), in the dense object detection settings, due to the imbalanced sample size, the loss function is overwhelmed with background (easy samples). The Focal Loss addresses this problem and it is designed in such a way so that it reduces the loss (‘down-weight’) for the easy examples and thus the network can focus on training the hard examples. Below is the definition of Focal Loss —" }, { "code": null, "e": 4142, "s": 3717, "text": "In focal loss, there’s a modulating factor multiplied to the Cross-Entropy loss. When a sample is misclassified, p (which represents model’s estimated probability for the class with label y = 1) is low and the modulating factor is near 1 and, the loss is unaffected. As p→1, the modulating factor approaches 0 and the loss for well-classified examples is down-weighted. The effect of γ parameter is shown in the plot below —" }, { "code": null, "e": 4168, "s": 4142, "text": "To quote from the paper —" }, { "code": null, "e": 4300, "s": 4168, "text": "The modulating factor reduces the loss contribution from easy examples and extends the range in which an example receives low loss." }, { "code": null, "e": 4579, "s": 4300, "text": "To understand this we will compare Cross-Entropy (CE) loss and Focal Loss using the definition above with γ = 2. Consider true value 1.0, and we consider 3 prediction values 0.90 (close), 0.95 (very close), 0.20 (far from true). Let’s see the loss values below using TensorFlow—" }, { "code": null, "e": 4912, "s": 4579, "text": "CE loss when pred is close to true: 0.10536041CE loss when pred is very close to true: 0.051293183CE loss when pred is far from true: 1.6094373focal loss when pred is close to true: 0.0010536041110754007focal loss when pred is very close to true: 0.00012823295779526255focal loss when pred is far from true: 1.0300399017333985" }, { "code": null, "e": 5514, "s": 4912, "text": "Here we see that compared to CE loss, the modulating factor in focal loss plays an important role. When prediction is close to the truth the loss is penalized way more than when when it is far. Importantly when prediction is 0.90 focal loss will be 0.01 × CE loss but when prediction is 0.95, focal loss will be around 0.002 × CE loss. Now we get a picture how focal loss reduces the loss contribution from easy examples and extends the range in which an example receives low loss. This can also be seen from fig. 3. Now we will use a real-world class imbalanced data-set and see focal loss in action." }, { "code": null, "e": 5738, "s": 5514, "text": "Data-set Description: Here I have considered an extreme class-imbalanced data-set available in Kaggle and the data-set contains transactions made by credit cards in September 2013 by European cardholders. Let’s use pandas —" }, { "code": null, "e": 6324, "s": 5738, "text": "This data-set presents transactions that occurred in two days and we have 284,807 number of transactions. Features V1, V2,...V28 are the principal components obtained with PCA (original features are not provided due to confidential issues) and the only features which have not been transformed with PCA are ‘Time’ and ‘Amount’. Feature ‘Time’ contains the seconds elapsed between each transaction and the first transaction in the dataset and the feature ‘Amount’ is the transaction amount. Feature ‘Class’ is the response variable and it takes value 1 in case of fraud and 0 otherwise." }, { "code": null, "e": 6578, "s": 6324, "text": "Class Imbalance: Let’s plot the distribution of the ‘Class’ feature which tells us how many transactions are real and fake. As shown in figure 4 above, overwhelming numbers of transactions are real. Let’s get the numbers with this simple piece of code —" }, { "code": null, "e": 6745, "s": 6578, "text": "print (‘real cases:‘, len(credit_df[credit_df[‘Class’]==0]))print (‘fraud cases: ‘, len(credit_df[credit_df[‘Class’]==1]))>>> real cases: 284315 fraud cases: 492" }, { "code": null, "e": 7249, "s": 6745, "text": "So the class imbalance ratio is about 1:578, so for 578 real transactions we have one fraud case. First let’s use a simple neural network with cross-entropy loss to predict fraud and real transactions. But before that a little examination tells us that ‘Amount’ and ‘Time’ features are not scaled whereas other features ‘V1’, ‘V2’...etc are scaled. Here we can use StandardScaler/RobustScaler to scale these features and since RobustScaler are robust to outliers, I chose this standardization technique." }, { "code": null, "e": 7300, "s": 7249, "text": "Let’s now choose the features and label as below —" }, { "code": null, "e": 7549, "s": 7300, "text": "X_labels = credit_df.drop([‘Class’], axis=1)y_labels = credit_df[‘Class’]X_labels = X_labels.to_numpy(dtype=np.float64)y_labels = y_labels.to_numpy(dtype=np.float64)y_lab_cat = tf.keras.utils.to_categorical(y_labels, num_classes=2, dtype=’float32')" }, { "code": null, "e": 7620, "s": 7549, "text": "For the train-test split we use stratify to keep the ratio of labels —" }, { "code": null, "e": 7742, "s": 7620, "text": "x_train, x_test, y_train, y_test = train_test_split(X_labels, y_lab_cat, test_size=0.3, stratify=y_lab_cat, shuffle=True)" }, { "code": null, "e": 7803, "s": 7742, "text": "Now we build a simple neural-net model with 3 dense layers —" }, { "code": null, "e": 8136, "s": 7803, "text": "def simple_model(): input_data = Input(shape=(x_train.shape[1], )) x = Dense(64)(input_data) x = Activation(activations.relu)(x) x = Dense(32)(x) x = Activation(activations.relu)(x) x = Dense(2)(x) x = Activation(activations.softmax)(x) model = Model(inputs=input_data, outputs=x, name=’Simple_Model’) return model" }, { "code": null, "e": 8194, "s": 8136, "text": "Compile the model with categorical cross-entropy as loss—" }, { "code": null, "e": 8301, "s": 8194, "text": "simple_model.compile(optimizer=Adam(learning_rate=5e-3), loss='categorical_crossentropy', metrics=['acc'])" }, { "code": null, "e": 8319, "s": 8301, "text": "Train the model —" }, { "code": null, "e": 8416, "s": 8319, "text": "simple_model.fit(x_train, y_train, validation_split=0.2, epochs=5, shuffle=True, batch_size=256)" }, { "code": null, "e": 8552, "s": 8416, "text": "To truly understand the performance of the model, we need to plot the confusion matrix along with the precision, recall and F1 scores —" }, { "code": null, "e": 8887, "s": 8552, "text": "We see from the confusion matrix and other performance metric scores that as expected the network does extremely good to classify the real transactions but the recall value is below 50% for the fraud class. Our target is to test without changing anything except the loss function can we get better values for the performance metrics ?" }, { "code": null, "e": 9194, "s": 8887, "text": "First let’s define the focal loss with alpha and gamma as hyper-parameters and to do this I have used the tfa module which is a functionality for TensorFlow maintained by SIG-addons (tfa). Under this module among the additional losses, there’s an implementation of Focal Loss and first we import as below —" }, { "code": null, "e": 9280, "s": 9194, "text": "import tensorflow_addons as tfafl = tfa.losses.SigmoidFocalCrossEntropy(alpha, gamma)" }, { "code": null, "e": 9417, "s": 9280, "text": "Using this, let’s define a custom loss function that can be used as a proxy for ‘Focal Loss’ for this specific problem with two classes—" }, { "code": null, "e": 9690, "s": 9417, "text": "def focal_loss_custom(alpha, gamma): def binary_focal_loss(y_true, y_pred): fl = tfa.losses.SigmoidFocalCrossEntropy(alpha=alpha, gamma=gamma) y_true_K = K.ones_like(y_true) focal_loss = fl(y_true, y_pred) return focal_loss return binary_focal_loss" }, { "code": null, "e": 9805, "s": 9690, "text": "We now just repeat the steps above for model definition, compile and fit but this time using focal loss as below —" }, { "code": null, "e": 9931, "s": 9805, "text": "simple_model.compile(optimizer=Adam(learning_rate=5e-3), loss=focal_loss_custom(alpha=0.2, gamma=2.0), metrics=[‘acc’])" }, { "code": null, "e": 10089, "s": 9931, "text": "For alpha and gamma parameters, I have just used the values suggested in the paper (however the problem is different) and different values need to be tested." }, { "code": null, "e": 10186, "s": 10089, "text": "simple_model.fit(x_train, y_train, validation_split=0.2, epochs=5, shuffle=True, batch_size=256)" }, { "code": null, "e": 10236, "s": 10186, "text": "Using Focal Loss we see an improvement as below —" }, { "code": null, "e": 10414, "s": 10236, "text": "We see using ‘Focal Loss’ the performance metrics improved considerably and we could detect more ‘Fraud’ transactions (101/148) correctly compared to the previous case (69/148)." }, { "code": null, "e": 10726, "s": 10414, "text": "Here in this post we discuss Focal Loss and how it can improve classification task when the data is highly imbalanced. To demonstrate Focal Loss in action we used Credit Card Transaction data-set which is highly biased towards real transactions and showed how Focal Loss improves the classification performance." }, { "code": null, "e": 11052, "s": 10726, "text": "I would also like to mention that , in my research with gamma-ray data we are trying to classify Active Galactic Nuclei (AGN) from Pulsars (PSR) and the gamma-ray sky is mostly populated by AGNs. The picture below is an example of such a simulated sky. This is also an example of class-imbalanced data-set in computer vision." }, { "code": null, "e": 11082, "s": 11052, "text": "[1] Focal Loss Original Paper" }, { "code": null, "e": 11119, "s": 11082, "text": "[2] Focal Loss Original Presentation" } ]
Matrix Chain Multiplication
If a chain of matrices is given, we have to find the minimum number of the correct sequence of matrices to multiply. We know that the matrix multiplication is associative, so four matrices ABCD, we can multiply A(BCD), (AB)(CD), (ABC)D, A(BC)D, in these sequences. Like these sequences, our task is to find which ordering is efficient to multiply. In the given input there is an array say arr, which contains arr[] = {1, 2, 3, 4}. It means the matrices are of the order (1 x 2), (2 x 3), (3 x 4). Input: The orders of the input matrices. {1, 2, 3, 4}. It means the matrices are {(1 x 2), (2 x 3), (3 x 4)}. Output: Minimum number of operations need multiply these three matrices. Here the result is 18. matOrder(array, n) Input − List of matrices, the number of matrices in the list. Output − Minimum number of matrix multiplication. Begin define table minMul of size n x n, initially fill with all 0s for length := 2 to n, do fir i:=1 to n-length, do j := i + length – 1 minMul[i, j] := ∞ for k := i to j-1, do q := minMul[i, k] + minMul[k+1, j] + array[i-1]*array[k]*array[j] if q < minMul[i, j], then minMul[i, j] := q done done done return minMul[1, n-1] End #include<iostream> using namespace std; int matOrder(int array[], int n) { int minMul[n][n]; //holds the number of scalar multiplication needed for (int i=1; i<n; i++) minMul[i][i] = 0; //for multiplication with 1 matrix, cost is 0 for (int length=2; length<n; length++) { //find the chain length starting from 2 for (int i=1; i<n-length+1; i++) { int j = i+length-1; minMul[i][j] = INT_MAX; //set to infinity for (int k=i; k<=j-1; k++) { //store cost per multiplications int q = minMul[i][k] + minMul[k+1][j] + array[i- 1]*array[k]*array[j]; if (q < minMul[i][j]) minMul[i][j] = q; } } } return minMul[1][n-1]; } int main() { int arr[] = {1, 2, 3, 4}; int size = 4; cout << "Minimum number of matrix multiplications: " << matOrder(arr, size); } Minimum number of matrix multiplications: 18
[ { "code": null, "e": 1179, "s": 1062, "text": "If a chain of matrices is given, we have to find the minimum number of the correct sequence of matrices to multiply." }, { "code": null, "e": 1410, "s": 1179, "text": "We know that the matrix multiplication is associative, so four matrices ABCD, we can multiply A(BCD), (AB)(CD), (ABC)D, A(BC)D, in these sequences. Like these sequences, our task is to find which ordering is efficient to multiply." }, { "code": null, "e": 1559, "s": 1410, "text": "In the given input there is an array say arr, which contains arr[] = {1, 2, 3, 4}. It means the matrices are of the order (1 x 2), (2 x 3), (3 x 4)." }, { "code": null, "e": 1765, "s": 1559, "text": "Input:\nThe orders of the input matrices. {1, 2, 3, 4}. It means the matrices are\n{(1 x 2), (2 x 3), (3 x 4)}.\nOutput:\nMinimum number of operations need multiply these three matrices. Here the result is 18." }, { "code": null, "e": 1784, "s": 1765, "text": "matOrder(array, n)" }, { "code": null, "e": 1846, "s": 1784, "text": "Input − List of matrices, the number of matrices in the list." }, { "code": null, "e": 1896, "s": 1846, "text": "Output − Minimum number of matrix multiplication." }, { "code": null, "e": 2309, "s": 1896, "text": "Begin\n define table minMul of size n x n, initially fill with all 0s\n for length := 2 to n, do\n fir i:=1 to n-length, do\n j := i + length – 1\n minMul[i, j] := ∞\n for k := i to j-1, do\n q := minMul[i, k] + minMul[k+1, j] + array[i-1]*array[k]*array[j]\n if q < minMul[i, j], then minMul[i, j] := q\n done\n done\n done\n return minMul[1, n-1]\nEnd" }, { "code": null, "e": 3218, "s": 2309, "text": "#include<iostream>\nusing namespace std;\n\nint matOrder(int array[], int n) {\n int minMul[n][n]; //holds the number of scalar multiplication needed\n\n for (int i=1; i<n; i++)\n minMul[i][i] = 0; //for multiplication with 1 matrix, cost is 0\n\n for (int length=2; length<n; length++) { //find the chain length starting from 2\n for (int i=1; i<n-length+1; i++) {\n int j = i+length-1;\n minMul[i][j] = INT_MAX; //set to infinity\n for (int k=i; k<=j-1; k++) {\n //store cost per multiplications\n int q = minMul[i][k] + minMul[k+1][j] + array[i- 1]*array[k]*array[j];\n if (q < minMul[i][j])\n minMul[i][j] = q;\n }\n }\n }\n return minMul[1][n-1];\n}\n\nint main() {\n int arr[] = {1, 2, 3, 4};\n int size = 4;\n cout << \"Minimum number of matrix multiplications: \" << matOrder(arr, size);\n}" }, { "code": null, "e": 3263, "s": 3218, "text": "Minimum number of matrix multiplications: 18" } ]
A Python Library to Generate a Synthetic Time Series Data | by MANIE TADAYON | Towards Data Science
Synthetic data is widely used in various domains. This is because many modern algorithms require lots of data for efficient training, and data collection and labeling usually are a time-consuming process and are prone to errors. Furthermore, some real-world data, due to its nature, is confidential and cannot be shared. Some methods, such as generative adversarial network1, are proposed to generate time series data. However, GAN is hard to train and might not be stable; besides, it requires a large volume of data for efficient training. This article will introduce the tsBNgen, a python library, to generate synthetic time series data based on an arbitrary dynamic Bayesian network structure. Although tsBNgen is primarily used to generate time series, it can also generate cross-sectional data by setting the length of time series to one. The following is a list of topics discussed in this article. Introduction Features Instruction Example Conclusion tsBNgen is a python package released under the MIT license to generate time series data from an arbitrary Bayesian network structure. Bayesian networks are a type of probabilistic graphical model widely used to model the uncertainties in real-world processes. Dynamic Bayesian networks (DBNs)are a special class of Bayesian networks that model temporal and time series data. Bayesian networks receive lots of attention in various domains, such as education and medicine. For example, in2, the authors used an HMM, a variant of DBN, to predict student performance in an educational video game. One significant advantage of directed graphical models (Bayesian networks) is that they can represent the causal relationship between nodes in a graph; hence they provide an intuitive method to model real-world processes. This statement makes tsBNgen very useful software to generate data once the graph structure is determined by an expert. In a sense, tsBNgen unlike data-driven methods like the GAN is a model-based approach. To learn more about the package, documentation, and examples, please visit the following GitHub repository. github.com I recently created a series of YouTube videos on to use this package. The videos are also on my GitHub page and you can access them here: I try to go over the Bayesian network and tsBNgen package in detail. If you have any questions or comments, you can ask me on my YouTube channel. Following is the list of supported features and capabilities of tsBNgen: Easy and simple interface.Support for discrete, continuous, and hybrid networks (a mixture of discrete and continuous nodes).Support for discrete nodes using multinomial distributions and Gaussian distributions for continuous nodes.Supports arbitrary loopback (temporal connection) values for temporal dependencies.Easy to modify and extend the code to support the new structure.The model-based approach, which can generate synthetic data once the causal structure is known. Easy and simple interface. Support for discrete, continuous, and hybrid networks (a mixture of discrete and continuous nodes). Support for discrete nodes using multinomial distributions and Gaussian distributions for continuous nodes. Supports arbitrary loopback (temporal connection) values for temporal dependencies. Easy to modify and extend the code to support the new structure. The model-based approach, which can generate synthetic data once the causal structure is known. To use tsBNgen, either clone the above repository or install the software using the following commands: pip install tsBNgen After the software is successfully installed, then issue the following commands to import all the functions and variables. from tsBNgen import * from tsBNgen.tsBNgen import * This is all you need to take advantage of all the functionalities that exist in the software. Before going over some examples, let me define the following parameters, which will be used throughout this section.Note: The following description, tables (as a form of an image), and images are obtained from this paper by the author3. Example 1 Assume you would like to generate data for the following architecture in Fig 1, which is an HMM structure. The top layer nodes are known as states, and the lower ones are called the observation. In HMM, states are discrete, while observations can be either continuous or discrete. The following tables summarize the parameters setting and probability distributions for Fig 1. In Table 1, T refers to the length of time series, N refers to the number of samples, and loopback determines the length of the temporal connection. For example, a loopback value of 1 implies that a node is connected to some other nodes at a previous time. Note: tsBNgen can simulate the standard Bayesian network (cross-sectional data) by setting T=1. Architecture 1 with the above CPDs and parameters can easily be implemented as follows: import timeSTART=time.time()T=20N=1000N_level=[4]Mat=pd.DataFrame(np.array(([0,1],[0,0]))) # HMMNode_Type=['D','C']CPD={'0':[0.25,0.25,0.25,0.25],'01':{'mu0':20,'sigma0':5,'mu1':40,'sigma1':5,'mu2':60,'sigma2':5,'mu3':80,'sigma3':5}}Parent={'0':[],'1':[0]}CPD2={'00':[[0.6,0.3,0.05,0.05],[0.25,0.4,0.25,0.1],[0.1,0.3,0.4,0.2],[0.05,0.05,0.4,0.5]],'01':{'mu0':20,'sigma0':5,'mu1':40,'sigma1':5,'mu2':60,'sigma2':5,'mu3':80,'sigma3':5}}loopbacks={'00':[1]}Parent2={'0':[0],'1':[0]}Time_series1=tsBNgen(T,N,N_level,Mat,Node_Type,CPD,Parent,CPD2,Parent2,loopbacks)Time_series1.BN_data_gen()FINISH=time.time()print('Total Time is',FINISH-START) The above code generates a 1000 time series with length of 20 correspondings to states and observations. Observations are normally distributed with a particular mean and standard deviation. The states are discrete (hence the ‘D’) and take four possible levels determined by the N_level variable. loopbacks is a dictionary in which each key has the following form: node+its parent. Since in architecture 1, only states, namely node 0 (according to the graph’s topological ordering), are connected across time and the parent of node 0 at time t is node 0 at time t-1; therefore, the key value for the loopbacks is ‘00’ and since the temporal connection only spans one unit of time, its value is 1. Node_Type determines the categories of nodes in the graph. For example in this example, the first node is discrete (‘D’) and the second one is continuous (‘C’). Mat represents the adjacency matrix of the network. The total time to generate the above data is 2.06 (s), and running the model through the HMM algorithm gives us more than 93.00 % accuracy for even five samples.Now let’s take a look at a more complex example. From now on, to save some space, I avoid showing the CPD tables and only show the architecture and the python code used to generate data. Example 2 Example 2 refers to the architecture in Fig 2, where the nodes in the first two layers are discrete and the last layer nodes(u2) are continuous. Based on the graph’s topological ordering, you can name them nodes 0, 1, and 2 per time point. Let’s say you would like to generate data when node 0 (the top node) takes two possible values (binary), node 1(the middle node) takes four possible values, and the last node is continuous and will be distributed according to Gaussian distribution for every possible value of its parents. The following python codes simulate this scenario for 2000 samples with a length of 20 for each sample. T=20N=2000N_level=[2,4]Mat=pd.DataFrame(np.array(([0,1,1],[0,0,1],[0,0,0])))Node_Type=['D','D','C']CPD={'0':[0.6,0.4],'01':[[0.5,0.3,0.15,0.05],[0.1,0.15,0.3,0.45]],'012':{'mu0':10,'sigma0':2,'mu1':30,'sigma1':5, 'mu2':50,'sigma2':5,'mu3':70,'sigma3':5,'mu4':15,'sigma4':5,'mu5':50,'sigma5':5,'mu6':70,'sigma6':5,'mu7':90,'sigma7':3}}Parent={'0':[],'1':[0],'2':[0,1]}CPD2={'00':[[0.7,0.3],[0.2,0.8]],'011':[[0.7,0.2,0.1,0],[0.6,0.3,0.05,0.05],[0.35,0.5,0.15,0],[0.2,0.3,0.4,0.1],[0.3,0.3,0.2,0.2],[0.1,0.2,0.3,0.4],[0.05,0.15,0.3,0.5],[0,0.05,0.25,0.7]],'012':{'mu0':10,'sigma0':2,'mu1':30,'sigma1':5, 'mu2':50,'sigma2':5,'mu3':70,'sigma3':5,'mu4':15,'sigma4':5,'mu5':50,'sigma5':5,'mu6':70,'sigma6':5,'mu7':90,'sigma7':3}}Parent2={'0':[0],'1':[0,1],'2':[0,1]}loopbacks={'00':[1],'11':[1]}Time_series2=tsBNgen(T,N,N_level,Mat,Node_Type,CPD,Parent,CPD2,Parent2,loopbacks)Time_series2.BN_data_gen() As the above code shows, node 0 (the top node) has no parent in the first time step (This is what the variable Parent represents). This is sometimes known as the root or an exogenous variable in a causal or Bayesian network. Node 1 is connected to node 0 and node 2 is connected to both nodes 0 and 1. To represent the structure for other time-steps after time 0, the variable Parent2 is used. This says node 0 is connected to itself across time (since ‘00’ is [1] in loopbacks then time t is connected to t-1 only). Node 1 is connected to node 0 for the same time and to node 1 in the previous time (This can be seen from the loopback variable as well). Since tsBNgen is a model-based data generation then you need to provide the distribution (for exogenous node) or conditional distribution of each node. If you would like to generate synthetic data corresponding to architecture with arbitrary distribution then you can choose CPD and CPD2 to be anything you like as long as the sum of entries for each discrete distribution is 1. For example, the CPD for node 0 is [0.6, 0.4]. You can change these values to be anything you like as long as they are added to 1. Example 3 Example 3 refers to the architecture in Fig 3, where the nodes in the first two layers are discrete and the last layer nodes(u2) are continuous. Assume you would like to generate data when node 0 (the top node) is binary, node 1(the middle node) takes four possible values, and node 2 is continuous and will be distributed according to Gaussian distribution for every possible value of its parents. The following python codes simulate this scenario for 1000 samples with a length of 10 for each sample. T=10N=1000N_level=[2,4]Mat=pd.DataFrame(np.array(([0,1,0],[0,0,1],[0,0,0])))Node_Type=['D','D','C']CPD={'0':[0.5,0.5],'01':[[0.6,0.3,0.05,0.05],[0.1,0.2,0.3,0.4]],'12':{'mu0':10,'sigma0':5,'mu1':30,'sigma1':5, 'mu2':60,'sigma2':5,'mu3':80,'sigma3':5}}Parent={'0':[],'1':[0],'2':[1]}CPD2={'00':[[0.7,0.3],[0.3,0.7]],'0011':[[0.7,0.2,0.1,0],[0.5,0.4,0.1,0],[0.45,0.45,0.1,0],[0.3,0.4,0.2,0.1],[0.4,0.4,0.1,0.1],[0.2,0.3,0.3,0.2],[0.2,0.3,0.3,0.2],[0.1,0.2,0.3,0.4],[0.3,0.4,0.2,0.1],[0.2,0.2,0.4,0.2], [0.2,0.1,0.4,0.3],[0.05,0.15,0.3,0.5],[0.1,0.3,0.3,0.3],[0,0.1,0.3,0.6],[0,0.1,0.2,0.7],[0,0,0.3,0.7]],'112':{'mu0':10,'sigma0':2,'mu1':30,'sigma1':2, 'mu2':50,'sigma2':2,'mu3':60,'sigma3':5,'mu4':20,'sigma4':2,'mu5':25,'sigma5':5,'mu6':50,'sigma6':5,'mu7':60,'sigma7':5, 'mu8':40,'sigma8':5,'mu9':50,'sigma9':5,'mu10':70,'sigma10':5,'mu11':85,'sigma11':2,'mu12':60,'sigma12':5, 'mu13':60,'sigma13':5,'mu14':80,'sigma14':3,'mu15':90,'sigma15':3}}Parent2={'0':[0],'1':[0,0,1],'2':[1,1]}loopbacks={'00':[1], '01':[1],'11':[1],'12':[1]}Time_series2=tsBNgen(T,N,N_level,Mat,Node_Type,CPD,Parent,CPD2,Parent2,loopbacks)Time_series2.BN_data_gen() In the same way, you can generate time series data for any graphical models you want. This is a wonderful tool since lots of real-world problems can be modeled as Bayesian and causal networks. For more examples, up-to-date documentation please visit the following GitHub page. github.com If you would like to know more make sure you watch my recent videos on my YouTube channel. Bonus: If you would like to see a comparative analysis of graphical modeling algorithms such as the HMM and deep learning methods such as the LSTM on a synthetically generated time series, please look at this paper4. In this article, I introduced the tsBNgen, a python library to generate synthetic data from an arbitrary BN. The features and capabilities of the software are explained using two examples. For more up-to-date information about the software, please visit the GitHub page mentioned above. [1] M. Frid-Adar, E. Klangand, M. Amitai, J. Goldberger, H. Greenspan, Synthetic data augmentation using gan for improved liver lesion classification(2018), IEEE 2018 15th international symposium on biomedicalimaging. [2] M. Tadayon, G. Pottie, Predicting Student Performance in an Educational Game Using a Hidden Markov Model(2020), IEEE 2020 IEEE Transactions on Education. [3] M. Tadayon, G. Pottie, tsBNgen: A Python Library to Generate Time Series Data from an Arbitrary Dynamic Bayesian Network Structure (2020), arXiv 2020, arXiv preprint arXiv:2009.04595. [4] M. Tadayon, G. Pottie, Comparative Analysis of the Hidden Markov Model and LSTM: A Simulative Approach (2020), arXiv 2020, arXiv preprint arXiv:2008.03825.
[ { "code": null, "e": 493, "s": 172, "text": "Synthetic data is widely used in various domains. This is because many modern algorithms require lots of data for efficient training, and data collection and labeling usually are a time-consuming process and are prone to errors. Furthermore, some real-world data, due to its nature, is confidential and cannot be shared." }, { "code": null, "e": 714, "s": 493, "text": "Some methods, such as generative adversarial network1, are proposed to generate time series data. However, GAN is hard to train and might not be stable; besides, it requires a large volume of data for efficient training." }, { "code": null, "e": 870, "s": 714, "text": "This article will introduce the tsBNgen, a python library, to generate synthetic time series data based on an arbitrary dynamic Bayesian network structure." }, { "code": null, "e": 1017, "s": 870, "text": "Although tsBNgen is primarily used to generate time series, it can also generate cross-sectional data by setting the length of time series to one." }, { "code": null, "e": 1078, "s": 1017, "text": "The following is a list of topics discussed in this article." }, { "code": null, "e": 1091, "s": 1078, "text": "Introduction" }, { "code": null, "e": 1100, "s": 1091, "text": "Features" }, { "code": null, "e": 1112, "s": 1100, "text": "Instruction" }, { "code": null, "e": 1120, "s": 1112, "text": "Example" }, { "code": null, "e": 1131, "s": 1120, "text": "Conclusion" }, { "code": null, "e": 1506, "s": 1131, "text": "tsBNgen is a python package released under the MIT license to generate time series data from an arbitrary Bayesian network structure. Bayesian networks are a type of probabilistic graphical model widely used to model the uncertainties in real-world processes. Dynamic Bayesian networks (DBNs)are a special class of Bayesian networks that model temporal and time series data." }, { "code": null, "e": 2153, "s": 1506, "text": "Bayesian networks receive lots of attention in various domains, such as education and medicine. For example, in2, the authors used an HMM, a variant of DBN, to predict student performance in an educational video game. One significant advantage of directed graphical models (Bayesian networks) is that they can represent the causal relationship between nodes in a graph; hence they provide an intuitive method to model real-world processes. This statement makes tsBNgen very useful software to generate data once the graph structure is determined by an expert. In a sense, tsBNgen unlike data-driven methods like the GAN is a model-based approach." }, { "code": null, "e": 2261, "s": 2153, "text": "To learn more about the package, documentation, and examples, please visit the following GitHub repository." }, { "code": null, "e": 2272, "s": 2261, "text": "github.com" }, { "code": null, "e": 2410, "s": 2272, "text": "I recently created a series of YouTube videos on to use this package. The videos are also on my GitHub page and you can access them here:" }, { "code": null, "e": 2556, "s": 2410, "text": "I try to go over the Bayesian network and tsBNgen package in detail. If you have any questions or comments, you can ask me on my YouTube channel." }, { "code": null, "e": 2629, "s": 2556, "text": "Following is the list of supported features and capabilities of tsBNgen:" }, { "code": null, "e": 3104, "s": 2629, "text": "Easy and simple interface.Support for discrete, continuous, and hybrid networks (a mixture of discrete and continuous nodes).Support for discrete nodes using multinomial distributions and Gaussian distributions for continuous nodes.Supports arbitrary loopback (temporal connection) values for temporal dependencies.Easy to modify and extend the code to support the new structure.The model-based approach, which can generate synthetic data once the causal structure is known." }, { "code": null, "e": 3131, "s": 3104, "text": "Easy and simple interface." }, { "code": null, "e": 3231, "s": 3131, "text": "Support for discrete, continuous, and hybrid networks (a mixture of discrete and continuous nodes)." }, { "code": null, "e": 3339, "s": 3231, "text": "Support for discrete nodes using multinomial distributions and Gaussian distributions for continuous nodes." }, { "code": null, "e": 3423, "s": 3339, "text": "Supports arbitrary loopback (temporal connection) values for temporal dependencies." }, { "code": null, "e": 3488, "s": 3423, "text": "Easy to modify and extend the code to support the new structure." }, { "code": null, "e": 3584, "s": 3488, "text": "The model-based approach, which can generate synthetic data once the causal structure is known." }, { "code": null, "e": 3688, "s": 3584, "text": "To use tsBNgen, either clone the above repository or install the software using the following commands:" }, { "code": null, "e": 3708, "s": 3688, "text": "pip install tsBNgen" }, { "code": null, "e": 3831, "s": 3708, "text": "After the software is successfully installed, then issue the following commands to import all the functions and variables." }, { "code": null, "e": 3883, "s": 3831, "text": "from tsBNgen import * from tsBNgen.tsBNgen import *" }, { "code": null, "e": 3977, "s": 3883, "text": "This is all you need to take advantage of all the functionalities that exist in the software." }, { "code": null, "e": 4214, "s": 3977, "text": "Before going over some examples, let me define the following parameters, which will be used throughout this section.Note: The following description, tables (as a form of an image), and images are obtained from this paper by the author3." }, { "code": null, "e": 4224, "s": 4214, "text": "Example 1" }, { "code": null, "e": 4331, "s": 4224, "text": "Assume you would like to generate data for the following architecture in Fig 1, which is an HMM structure." }, { "code": null, "e": 4600, "s": 4331, "text": "The top layer nodes are known as states, and the lower ones are called the observation. In HMM, states are discrete, while observations can be either continuous or discrete. The following tables summarize the parameters setting and probability distributions for Fig 1." }, { "code": null, "e": 4857, "s": 4600, "text": "In Table 1, T refers to the length of time series, N refers to the number of samples, and loopback determines the length of the temporal connection. For example, a loopback value of 1 implies that a node is connected to some other nodes at a previous time." }, { "code": null, "e": 4953, "s": 4857, "text": "Note: tsBNgen can simulate the standard Bayesian network (cross-sectional data) by setting T=1." }, { "code": null, "e": 5041, "s": 4953, "text": "Architecture 1 with the above CPDs and parameters can easily be implemented as follows:" }, { "code": null, "e": 5681, "s": 5041, "text": "import timeSTART=time.time()T=20N=1000N_level=[4]Mat=pd.DataFrame(np.array(([0,1],[0,0]))) # HMMNode_Type=['D','C']CPD={'0':[0.25,0.25,0.25,0.25],'01':{'mu0':20,'sigma0':5,'mu1':40,'sigma1':5,'mu2':60,'sigma2':5,'mu3':80,'sigma3':5}}Parent={'0':[],'1':[0]}CPD2={'00':[[0.6,0.3,0.05,0.05],[0.25,0.4,0.25,0.1],[0.1,0.3,0.4,0.2],[0.05,0.05,0.4,0.5]],'01':{'mu0':20,'sigma0':5,'mu1':40,'sigma1':5,'mu2':60,'sigma2':5,'mu3':80,'sigma3':5}}loopbacks={'00':[1]}Parent2={'0':[0],'1':[0]}Time_series1=tsBNgen(T,N,N_level,Mat,Node_Type,CPD,Parent,CPD2,Parent2,loopbacks)Time_series1.BN_data_gen()FINISH=time.time()print('Total Time is',FINISH-START)" }, { "code": null, "e": 6590, "s": 5681, "text": "The above code generates a 1000 time series with length of 20 correspondings to states and observations. Observations are normally distributed with a particular mean and standard deviation. The states are discrete (hence the ‘D’) and take four possible levels determined by the N_level variable. loopbacks is a dictionary in which each key has the following form: node+its parent. Since in architecture 1, only states, namely node 0 (according to the graph’s topological ordering), are connected across time and the parent of node 0 at time t is node 0 at time t-1; therefore, the key value for the loopbacks is ‘00’ and since the temporal connection only spans one unit of time, its value is 1. Node_Type determines the categories of nodes in the graph. For example in this example, the first node is discrete (‘D’) and the second one is continuous (‘C’). Mat represents the adjacency matrix of the network." }, { "code": null, "e": 6938, "s": 6590, "text": "The total time to generate the above data is 2.06 (s), and running the model through the HMM algorithm gives us more than 93.00 % accuracy for even five samples.Now let’s take a look at a more complex example. From now on, to save some space, I avoid showing the CPD tables and only show the architecture and the python code used to generate data." }, { "code": null, "e": 6948, "s": 6938, "text": "Example 2" }, { "code": null, "e": 7093, "s": 6948, "text": "Example 2 refers to the architecture in Fig 2, where the nodes in the first two layers are discrete and the last layer nodes(u2) are continuous." }, { "code": null, "e": 7581, "s": 7093, "text": "Based on the graph’s topological ordering, you can name them nodes 0, 1, and 2 per time point. Let’s say you would like to generate data when node 0 (the top node) takes two possible values (binary), node 1(the middle node) takes four possible values, and the last node is continuous and will be distributed according to Gaussian distribution for every possible value of its parents. The following python codes simulate this scenario for 2000 samples with a length of 20 for each sample." }, { "code": null, "e": 8479, "s": 7581, "text": "T=20N=2000N_level=[2,4]Mat=pd.DataFrame(np.array(([0,1,1],[0,0,1],[0,0,0])))Node_Type=['D','D','C']CPD={'0':[0.6,0.4],'01':[[0.5,0.3,0.15,0.05],[0.1,0.15,0.3,0.45]],'012':{'mu0':10,'sigma0':2,'mu1':30,'sigma1':5, 'mu2':50,'sigma2':5,'mu3':70,'sigma3':5,'mu4':15,'sigma4':5,'mu5':50,'sigma5':5,'mu6':70,'sigma6':5,'mu7':90,'sigma7':3}}Parent={'0':[],'1':[0],'2':[0,1]}CPD2={'00':[[0.7,0.3],[0.2,0.8]],'011':[[0.7,0.2,0.1,0],[0.6,0.3,0.05,0.05],[0.35,0.5,0.15,0],[0.2,0.3,0.4,0.1],[0.3,0.3,0.2,0.2],[0.1,0.2,0.3,0.4],[0.05,0.15,0.3,0.5],[0,0.05,0.25,0.7]],'012':{'mu0':10,'sigma0':2,'mu1':30,'sigma1':5, 'mu2':50,'sigma2':5,'mu3':70,'sigma3':5,'mu4':15,'sigma4':5,'mu5':50,'sigma5':5,'mu6':70,'sigma6':5,'mu7':90,'sigma7':3}}Parent2={'0':[0],'1':[0,1],'2':[0,1]}loopbacks={'00':[1],'11':[1]}Time_series2=tsBNgen(T,N,N_level,Mat,Node_Type,CPD,Parent,CPD2,Parent2,loopbacks)Time_series2.BN_data_gen()" }, { "code": null, "e": 9134, "s": 8479, "text": "As the above code shows, node 0 (the top node) has no parent in the first time step (This is what the variable Parent represents). This is sometimes known as the root or an exogenous variable in a causal or Bayesian network. Node 1 is connected to node 0 and node 2 is connected to both nodes 0 and 1. To represent the structure for other time-steps after time 0, the variable Parent2 is used. This says node 0 is connected to itself across time (since ‘00’ is [1] in loopbacks then time t is connected to t-1 only). Node 1 is connected to node 0 for the same time and to node 1 in the previous time (This can be seen from the loopback variable as well)." }, { "code": null, "e": 9644, "s": 9134, "text": "Since tsBNgen is a model-based data generation then you need to provide the distribution (for exogenous node) or conditional distribution of each node. If you would like to generate synthetic data corresponding to architecture with arbitrary distribution then you can choose CPD and CPD2 to be anything you like as long as the sum of entries for each discrete distribution is 1. For example, the CPD for node 0 is [0.6, 0.4]. You can change these values to be anything you like as long as they are added to 1." }, { "code": null, "e": 9654, "s": 9644, "text": "Example 3" }, { "code": null, "e": 9799, "s": 9654, "text": "Example 3 refers to the architecture in Fig 3, where the nodes in the first two layers are discrete and the last layer nodes(u2) are continuous." }, { "code": null, "e": 10157, "s": 9799, "text": "Assume you would like to generate data when node 0 (the top node) is binary, node 1(the middle node) takes four possible values, and node 2 is continuous and will be distributed according to Gaussian distribution for every possible value of its parents. The following python codes simulate this scenario for 1000 samples with a length of 10 for each sample." }, { "code": null, "e": 11310, "s": 10157, "text": "T=10N=1000N_level=[2,4]Mat=pd.DataFrame(np.array(([0,1,0],[0,0,1],[0,0,0])))Node_Type=['D','D','C']CPD={'0':[0.5,0.5],'01':[[0.6,0.3,0.05,0.05],[0.1,0.2,0.3,0.4]],'12':{'mu0':10,'sigma0':5,'mu1':30,'sigma1':5, 'mu2':60,'sigma2':5,'mu3':80,'sigma3':5}}Parent={'0':[],'1':[0],'2':[1]}CPD2={'00':[[0.7,0.3],[0.3,0.7]],'0011':[[0.7,0.2,0.1,0],[0.5,0.4,0.1,0],[0.45,0.45,0.1,0],[0.3,0.4,0.2,0.1],[0.4,0.4,0.1,0.1],[0.2,0.3,0.3,0.2],[0.2,0.3,0.3,0.2],[0.1,0.2,0.3,0.4],[0.3,0.4,0.2,0.1],[0.2,0.2,0.4,0.2], [0.2,0.1,0.4,0.3],[0.05,0.15,0.3,0.5],[0.1,0.3,0.3,0.3],[0,0.1,0.3,0.6],[0,0.1,0.2,0.7],[0,0,0.3,0.7]],'112':{'mu0':10,'sigma0':2,'mu1':30,'sigma1':2, 'mu2':50,'sigma2':2,'mu3':60,'sigma3':5,'mu4':20,'sigma4':2,'mu5':25,'sigma5':5,'mu6':50,'sigma6':5,'mu7':60,'sigma7':5, 'mu8':40,'sigma8':5,'mu9':50,'sigma9':5,'mu10':70,'sigma10':5,'mu11':85,'sigma11':2,'mu12':60,'sigma12':5, 'mu13':60,'sigma13':5,'mu14':80,'sigma14':3,'mu15':90,'sigma15':3}}Parent2={'0':[0],'1':[0,0,1],'2':[1,1]}loopbacks={'00':[1], '01':[1],'11':[1],'12':[1]}Time_series2=tsBNgen(T,N,N_level,Mat,Node_Type,CPD,Parent,CPD2,Parent2,loopbacks)Time_series2.BN_data_gen()" }, { "code": null, "e": 11503, "s": 11310, "text": "In the same way, you can generate time series data for any graphical models you want. This is a wonderful tool since lots of real-world problems can be modeled as Bayesian and causal networks." }, { "code": null, "e": 11587, "s": 11503, "text": "For more examples, up-to-date documentation please visit the following GitHub page." }, { "code": null, "e": 11598, "s": 11587, "text": "github.com" }, { "code": null, "e": 11689, "s": 11598, "text": "If you would like to know more make sure you watch my recent videos on my YouTube channel." }, { "code": null, "e": 11906, "s": 11689, "text": "Bonus: If you would like to see a comparative analysis of graphical modeling algorithms such as the HMM and deep learning methods such as the LSTM on a synthetically generated time series, please look at this paper4." }, { "code": null, "e": 12193, "s": 11906, "text": "In this article, I introduced the tsBNgen, a python library to generate synthetic data from an arbitrary BN. The features and capabilities of the software are explained using two examples. For more up-to-date information about the software, please visit the GitHub page mentioned above." }, { "code": null, "e": 12411, "s": 12193, "text": "[1] M. Frid-Adar, E. Klangand, M. Amitai, J. Goldberger, H. Greenspan, Synthetic data augmentation using gan for improved liver lesion classification(2018), IEEE 2018 15th international symposium on biomedicalimaging." }, { "code": null, "e": 12569, "s": 12411, "text": "[2] M. Tadayon, G. Pottie, Predicting Student Performance in an Educational Game Using a Hidden Markov Model(2020), IEEE 2020 IEEE Transactions on Education." }, { "code": null, "e": 12757, "s": 12569, "text": "[3] M. Tadayon, G. Pottie, tsBNgen: A Python Library to Generate Time Series Data from an Arbitrary Dynamic Bayesian Network Structure (2020), arXiv 2020, arXiv preprint arXiv:2009.04595." } ]
How to convert a string to snake case using JavaScript ? - GeeksforGeeks
25 Dec, 2020 Given a string in and the task is to write a JavaScript code to convert the given string into snake case and print the modified string. Examples: Input: GeeksForGeeks Output: geeks_for_geeks Input: CamelCaseToSnakeCase Output: camel_case_to_snake_case We use match(), map(), join, and toLowerCase() method to convert a given string into snake case string. The match() method is used to match the given string with the pattern and then use map() and toLowerCase() method to convert given string into lower case and then use join() method to join the string using underscore (_). Example: HTML <!DOCTYPE html><html> <head> <title> How to convert a string to snake case using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to convert a string to snake case using JavaScript? </h3> <script> function snake_case_string(str) { return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) .map(s => s.toLowerCase()) .join('_'); } console.log(snake_case_string('GeeksForGeeks')); console.log(snake_case_string('Welcome to GeeksForGeeks')); console.log(snake_case_string('Welcome-to-GeeksForGeeks')); console.log(snake_case_string('Welcome_to_GeeksForGeeks')); </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n25 Dec, 2020" }, { "code": null, "e": 25513, "s": 25376, "text": "Given a string in and the task is to write a JavaScript code to convert the given string into snake case and print the modified string. " }, { "code": null, "e": 25523, "s": 25513, "text": "Examples:" }, { "code": null, "e": 25629, "s": 25523, "text": "Input: GeeksForGeeks\nOutput: geeks_for_geeks\nInput: CamelCaseToSnakeCase\nOutput: camel_case_to_snake_case" }, { "code": null, "e": 25956, "s": 25629, "text": "We use match(), map(), join, and toLowerCase() method to convert a given string into snake case string. The match() method is used to match the given string with the pattern and then use map() and toLowerCase() method to convert given string into lower case and then use join() method to join the string using underscore (_). " }, { "code": null, "e": 25965, "s": 25956, "text": "Example:" }, { "code": null, "e": 25970, "s": 25965, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to convert a string to snake case using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to convert a string to snake case using JavaScript? </h3> <script> function snake_case_string(str) { return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) .map(s => s.toLowerCase()) .join('_'); } console.log(snake_case_string('GeeksForGeeks')); console.log(snake_case_string('Welcome to GeeksForGeeks')); console.log(snake_case_string('Welcome-to-GeeksForGeeks')); console.log(snake_case_string('Welcome_to_GeeksForGeeks')); </script></body> </html>", "e": 26811, "s": 25970, "text": null }, { "code": null, "e": 26819, "s": 26811, "text": "Output:" }, { "code": null, "e": 26828, "s": 26819, "text": "CSS-Misc" }, { "code": null, "e": 26838, "s": 26828, "text": "HTML-Misc" }, { "code": null, "e": 26854, "s": 26838, "text": "JavaScript-Misc" }, { "code": null, "e": 26858, "s": 26854, "text": "CSS" }, { "code": null, "e": 26863, "s": 26858, "text": "HTML" }, { "code": null, "e": 26874, "s": 26863, "text": "JavaScript" }, { "code": null, "e": 26891, "s": 26874, "text": "Web Technologies" }, { "code": null, "e": 26896, "s": 26891, "text": "HTML" }, { "code": null, "e": 26994, "s": 26896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27031, "s": 26994, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27060, "s": 27031, "text": "Form validation using jQuery" }, { "code": null, "e": 27099, "s": 27060, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27141, "s": 27099, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27188, "s": 27141, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 27248, "s": 27188, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27309, "s": 27248, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27362, "s": 27309, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27412, "s": 27362, "text": "How to Insert Form Data into Database using PHP ?" } ]
C++ Program to Search Sorted Sequence Using Divide and Conquer with the Aid of Fibonacci Numbers
In this C++ program we implement a Divide and Conquer approach using Fibonacci numbers. Using Fibonacci numbers, we calculate mid of data array to search the data item. The time complexity of this approach is O(log(n)). Begin Assign the data to the array in a sorted manner. Take input of the element to be searched. Call FibonacciSearch() function. Calculate the mid value using ‘start+fib[index-2]’ expression. If the chosen item is equal to the value at mid index, print result and return to main. If it is lesser than the value at mid index, proceed with the left sub-array. If it is more than the value at mid index, proceed with the right sub-array. If the calculated mid value is equal to either start or end then the item is not found in the array. End #include<iostream> using namespace std; void FibonacciSearch(int *a, int start, int end, int *fib, int index, int item) { int i, mid; mid = start+fib[index-2]; if(item == a[mid]) { cout<<"\n item found at "<<mid<<" index."; return; } else if(item == a[start]) { cout<<"\n item found at "<<start<<" index."; return; } else if(item == a[end]) { cout<<"\n item found at "<<end<<" index."; return; } else if(mid == start || mid == end) { cout<<"\nElement not found"; return; } else if(item > a[mid]) FibonacciSearch(a, mid, end, fib, index-1, item); else FibonacciSearch(a, start, mid, fib, index-2, item); } main() { int n, i, fib[20], a[10]={3, 7, 55, 86, 7, 15, 26, 30, 46, 95}; char ch; fib[0] = 0; fib[1] = 1; i = 1; while(fib[i] < 10) { i++; fib[i] = fib[i-1] + fib[i-2]; } up: cout<<"\nEnter the Element to be searched: "; cin>>n; FibonacciSearch(a, 0, 9, fib, i, n); cout<<"\n\n\tDo you want to search more...enter choice(y/n)?"; cin>>ch; if(ch == 'y' || ch == 'Y') goto up; return 0; } } Enter the Element to be searched: 26 item found at 6 index. Do you want to search more...enter choice(y/n)?y Enter the Element to be searched: 45 item not found Do you want to search more...enter choice(y/n)?n
[ { "code": null, "e": 1282, "s": 1062, "text": "In this C++ program we implement a Divide and Conquer approach using Fibonacci numbers. Using Fibonacci numbers, we calculate mid of data array to search the data item. The time complexity of this approach is O(log(n))." }, { "code": null, "e": 1847, "s": 1282, "text": "Begin\n Assign the data to the array in a sorted manner.\n Take input of the element to be searched.\n Call FibonacciSearch() function.\n Calculate the mid value using ‘start+fib[index-2]’ expression.\n If the chosen item is equal to the value at mid index, print result and return to main.\n If it is lesser than the value at mid index, proceed with the left sub-array.\n If it is more than the value at mid index, proceed with the right sub-array.\n If the calculated mid value is equal to either start or end then the item is not found in the array.\nEnd" }, { "code": null, "e": 3083, "s": 1847, "text": "#include<iostream>\nusing namespace std;\nvoid FibonacciSearch(int *a, int start, int end, int *fib, int index, int item) {\n int i, mid;\n mid = start+fib[index-2];\n if(item == a[mid]) {\n cout<<\"\\n item found at \"<<mid<<\" index.\";\n return;\n } else if(item == a[start]) {\n cout<<\"\\n item found at \"<<start<<\" index.\";\n return;\n } else if(item == a[end]) {\n cout<<\"\\n item found at \"<<end<<\" index.\";\n return;\n } else if(mid == start || mid == end) {\n cout<<\"\\nElement not found\";\n return;\n } else if(item > a[mid])\n FibonacciSearch(a, mid, end, fib, index-1, item);\n else\n FibonacciSearch(a, start, mid, fib, index-2, item);\n }\n main() {\n int n, i, fib[20], a[10]={3, 7, 55, 86, 7, 15, 26, 30, 46, 95};\n char ch;\n fib[0] = 0;\n fib[1] = 1;\n i = 1;\n while(fib[i] < 10) {\n i++;\n fib[i] = fib[i-1] + fib[i-2];\n }\n up:\n cout<<\"\\nEnter the Element to be searched: \";\n cin>>n;\n FibonacciSearch(a, 0, 9, fib, i, n);\n cout<<\"\\n\\n\\tDo you want to search more...enter choice(y/n)?\";\n cin>>ch;\n if(ch == 'y' || ch == 'Y')\n goto up;\n return 0;\n }\n}" }, { "code": null, "e": 3293, "s": 3083, "text": "Enter the Element to be searched: 26\nitem found at 6 index.\nDo you want to search more...enter choice(y/n)?y\nEnter the Element to be searched: 45\nitem not found\nDo you want to search more...enter choice(y/n)?n" } ]
What is a register storage class in C language?
There are four storage classes in C programming language, which are as follows − auto extern static register The keyword is register. The keyword is register. Register variable values are stored in CPU registers, rather than in memory where, normal variables are stored. Register variable values are stored in CPU registers, rather than in memory where, normal variables are stored. Registers are temporary storage units in CPU. Registers are temporary storage units in CPU. They allow faster access time for register variables than normal variables. They allow faster access time for register variables than normal variables. Following is the C program for register storage class − Live Demo #include<stdio.h> main ( ){ register int i; for (i=1; i<=5; i++) printf ("%d ",i); } The output is stated below − 1 2 3 4 5 Consider another C program for register storage class − Live Demo #include<stdio.h> int main(){ register int a; printf("%d",a); //prints default value of a =0 } The output is stated below − 0 Following is the third C program for static storage class − #include<stdio.h> int main(){ register int i = 10; int *p; //int *p = &i; //error occurred ,here we are trying to request address of register variable printf("Value of i: %d", *p); printf("Address of i: %u", p); } The output is stated below − Error:add of reg var?
[ { "code": null, "e": 1143, "s": 1062, "text": "There are four storage classes in C programming language, which are as follows −" }, { "code": null, "e": 1148, "s": 1143, "text": "auto" }, { "code": null, "e": 1155, "s": 1148, "text": "extern" }, { "code": null, "e": 1162, "s": 1155, "text": "static" }, { "code": null, "e": 1171, "s": 1162, "text": "register" }, { "code": null, "e": 1196, "s": 1171, "text": "The keyword is register." }, { "code": null, "e": 1221, "s": 1196, "text": "The keyword is register." }, { "code": null, "e": 1333, "s": 1221, "text": "Register variable values are stored in CPU registers, rather than in memory where, normal variables are stored." }, { "code": null, "e": 1445, "s": 1333, "text": "Register variable values are stored in CPU registers, rather than in memory where, normal variables are stored." }, { "code": null, "e": 1491, "s": 1445, "text": "Registers are temporary storage units in CPU." }, { "code": null, "e": 1537, "s": 1491, "text": "Registers are temporary storage units in CPU." }, { "code": null, "e": 1613, "s": 1537, "text": "They allow faster access time for register variables than normal variables." }, { "code": null, "e": 1689, "s": 1613, "text": "They allow faster access time for register variables than normal variables." }, { "code": null, "e": 1745, "s": 1689, "text": "Following is the C program for register storage class −" }, { "code": null, "e": 1756, "s": 1745, "text": " Live Demo" }, { "code": null, "e": 1853, "s": 1756, "text": "#include<stdio.h>\nmain ( ){\n register int i;\n for (i=1; i<=5; i++)\n printf (\"%d \",i);\n}" }, { "code": null, "e": 1882, "s": 1853, "text": "The output is stated below −" }, { "code": null, "e": 1892, "s": 1882, "text": "1 2 3 4 5" }, { "code": null, "e": 1948, "s": 1892, "text": "Consider another C program for register storage class −" }, { "code": null, "e": 1959, "s": 1948, "text": " Live Demo" }, { "code": null, "e": 2060, "s": 1959, "text": "#include<stdio.h>\nint main(){\n register int a;\n printf(\"%d\",a); //prints default value of a =0\n}" }, { "code": null, "e": 2089, "s": 2060, "text": "The output is stated below −" }, { "code": null, "e": 2091, "s": 2089, "text": "0" }, { "code": null, "e": 2151, "s": 2091, "text": "Following is the third C program for static storage class −" }, { "code": null, "e": 2383, "s": 2151, "text": "#include<stdio.h>\nint main(){\n register int i = 10;\n int *p;\n //int *p = &i; //error occurred ,here we are trying to request address of register variable\n printf(\"Value of i: %d\", *p);\n printf(\"Address of i: %u\", p);\n}" }, { "code": null, "e": 2412, "s": 2383, "text": "The output is stated below −" }, { "code": null, "e": 2434, "s": 2412, "text": "Error:add of reg var?" } ]
Number of positions where a letter can be inserted such that a string becomes palindrome - GeeksforGeeks
03 May, 2021 Given a string str, we need to find the no. of positions where a letter(lowercase) can be inserted so that string becomes a palindrome. Examples: Input : str = "abca" Output : possible palindromic strings: 1) acbca (at position 2) 2) abcba (at position 4) Hence, the output is 2. Input : str = "aaa" Output : possible palindromic strings: 1) aaaa 2) aaaa 3) aaaa 4) aaaa Hence, the output is 4. Naive Approach:This approach is to insert all 26 alphabets at every position possible i.e., N+1 positions and check at every position if this insertion makes it a palindrome and increase the count.Efficient Approach: First you have to observe that we have to make insertion only at the point when the character at that point violates the palindrome condition i.e., . Now, there will be two cases based on the above fact: Case I: What if the given string is already a palindrome Then we can only insert at the position such that the insertion does not violate the palindrome. 1) If the length is even then we can always insert any letter in the middle. 2) If the length is odd then we can insert the letter which is in middle, to the left or right to it. 3) In both the cases we can insert the letter which is in middle(let it be ‘CH’), at positions equals to: (no.of consecutive CH’s to the left of middle letter)*2. Case II:If it is not a palindrome As mentioned above we should start inserting at position where , So we increase the count and check for the cases if insertion at any other position makes it a palindrome. 1) If is a palindrome, then we can insert* at any position before until , K in range .(*letter = S[N-i-1]) 2.)If is a palindrome, then we can insert* at any position after until , K in range .(*letter = S[i]) In all the cases we keep increasing the count. C++ Java Python 3 C# PHP Javascript // CPP code to find the no.of positions where a// letter can be inserted to make it a palindrome#include <bits/stdc++.h>using namespace std; // Function to check if the string is palindromebool isPalindrome(string &s, int i, int j){ int p = j; for (int k = i; k <= p; k++) { if (s[k] != s[p]) return false; p--; } return true;} int countWays(string &s){ // to know the length of string int n = s.length(); int count = 0; // if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (int i = n / 2; i < n; i++) { if (s[i] == s[i + 1]) count++; else break; } if (n % 2 == 0) // if the length is even { count++; count = 2 * count + 1; // sub-case-I } else count = 2 * count + 2; // sub-case-II } else { for (int i = 0; i < n / 2; i++) { // insertion point if (s[i] != s[n - 1 - i]) { int j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (int k = i - 1; k >= 0; k--) { if (s[k] != s[j]) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (int k = n - i; k < n; k++) { if (s[k] != s[i]) break; count++; } count++; } break; } } } return count;} // Driver codeint main(){ string s = "abca"; cout << countWays(s) << endl; return 0;} // Java code to find the no.of positions where a// letter can be inserted to make it a palindrome import java.io.*; class GFG { // Function to check if the string is palindrome static boolean isPalindrome(String s, int i, int j) { int p = j; for (int k = i; k <= p; k++) { if (s.charAt(k) != s.charAt(p)) return false; p--; } return true; } static int countWays(String s) { // to know the length of string int n = s.length(); int count = 0; // if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (int i = n / 2; i < n; i++) { if (s.charAt(i) == s.charAt(i + 1)) count++; else break; } if (n % 2 == 0) // if the length is even { count++; count = 2 * count + 1; // sub-case-I } else count = 2 * count + 2; // sub-case-II } else { for (int i = 0; i < n / 2; i++) { // insertion point if (s.charAt(i) != s.charAt(n - 1 - i)) { int j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (int k = i - 1; k >= 0; k--) { if (s.charAt(k) != s.charAt(j)) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (int k = n - i; k < n; k++) { if (s.charAt(k) != s.charAt(i)) break; count++; } count++; } break; } } } return count; } // Driver code public static void main(String[] args) { String s = "abca"; System.out.println(countWays(s)); }} // This code is contributed by vt_m. # Python 3 code to find the no.of positions# where a letter can be inserted to make it# a palindrome # Function to check if the string# is palindromedef isPalindrome(s, i, j): p = j for k in range(i, p + 1): if (s[k] != s[p]): return False p -= 1 return True def countWays(s): # to know the length of string n = len(s) count = 0 # if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) : # Sub-case-III) for i in range(n // 2, n): if (s[i] == s[i + 1]): count += 1 else: break if (n % 2 == 0): # if the length is even count += 1 count = 2 * count + 1 # sub-case-I else: count = 2 * count + 2 # sub-case-II else : for i in range(n // 2) : # insertion point if (s[i] != s[n - 1 - i]) : j = n - 1 - i # Case-I if (isPalindrome(s, i, n - 2 - i)) : for k in range(i - 1, -1, -1): if (s[k] != s[j]): break count += 1 count += 1 # Case-II if (isPalindrome(s, i + 1, n - 1 - i)) : for k in range(n - i, n) : if (s[k] != s[i]): break count += 1 count += 1 break return count # Driver codeif __name__ == "__main__": s = "abca" print(countWays(s)) # This code is contributed by ita_c // C# code to find the no. of positions// where a letter can be inserted// to make it a palindrome.using System; class GFG { // Function to check if the // string is palindrome static bool isPalindrome(String s, int i, int j) { int p = j; for (int k = i; k <= p; k++) { if (s[k] != s[p]) return false; p--; } return true; } static int countWays(String s) { // to know the length of string int n = s.Length; int count = 0; // if the given string is // a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (int i = n / 2; i < n; i++) { if (s[i] == s[i + 1]) count++; else break; } // if the length is even if (n % 2 == 0) { count++; // sub-case-I count = 2 * count + 1; } else // sub-case-II count = 2 * count + 2; } else { for (int i = 0; i < n / 2; i++) { // insertion point if (s[i] != s[n - 1 - i]) { int j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (int k = i - 1; k >= 0; k--) { if (s[k] != s[j]) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (int k = n - i; k < n; k++) { if (s[k] != s[i]) break; count++; } count++; } break; } } } return count; } // Driver code public static void Main() { String s = "abca"; Console.Write(countWays(s)); }} // This code is contributed by nitin mittal <?php// PHP code to find the no. of// positions where a letter can// be inserted to make it a palindrome // Function to check if the// string is palindromefunction isPalindrome($s, $i, $j){ $p = $j; for ($k = $i; $k <= $p; $k++) { if ($s[$k] != $s[$p]) return false; $p--; } return true;} function countWays($s){ // to know the length of string $n = strlen($s); $count = 0; // if the given string is // a palindrome(Case-I) if (isPalindrome($s, 0, $n - 1)) { // Sub-case-III) for ($i = $n / 2; $i < $n; $i++) { if ($s[$i] == $s[$i + 1]) $count++; else break; } // if the length is even if ($n % 2 == 0) { $count++; // sub-case-I $count = 2 * $count + 1; } else // sub-case-II $count = 2 * $count + 2; } else { for ($i = 0; $i < $n / 2; $i++) { // insertion point if ($s[$i] != $s[$n - 1 - $i]) { $j = $n - 1 - $i; // Case-I if (isPalindrome($s, $i, $n - 2 - $i)) { for ($k = $i - 1; $k >= 0; $k--) { if ($s[$k] != $s[$j]) break; $count++; } $count++; } // Case-II if (isPalindrome($s, $i + 1,$n - 1 - $i)) { for ($k = $n - $i; $k < $n; $k++) { if ($s[$k] != $s[$i]) break; $count++; } $count++; } break; } } } return $count;} // Driver code$s = "abca";echo countWays($s) ; // This code is contributed by nitin mittal?> <script>// Javascript code to find the no.of positions where a// letter can be inserted to make it a palindrome function isPalindrome(s,i,j) { let p = j; for (let k = i; k <= p; k++) { if (s[k] != s[p]) return false; p--; } return true; } // Function to check if the string is palindromefunction countWays(s){ // to know the length of string let n = s.length; let count = 0; // if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (let i = n / 2; i < n; i++) { if (s[i] == s[i + 1]) count++; else break; } if (n % 2 == 0) // if the length is even { count++; count = 2 * count + 1; // sub-case-I } else count = 2 * count + 2; // sub-case-II } else { for (let i = 0; i < n / 2; i++) { // insertion point if (s[i] != s[n - 1 - i]) { let j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (let k = i - 1; k >= 0; k--) { if (s[k] != s[j]) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (let k = n - i; k < n; k++) { if (s[k] != s[i]) break; count++; } count++; } break; } } } return count;} // Driver codelet s = "abca";document.write( countWays(s)); // This code is contributed by avanitrachhadiya2155</script> Output: 2 This article is contributed by Harsha Mogali. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal ukasp avanitrachhadiya2155 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 String Coding Problems for Interviews Hill Cipher Naive algorithm for Pattern Searching Vigenère Cipher How to Append a Character to a String in C Convert character array to string in C++ Print all subsequences of a string Converting Roman Numerals to Decimal lying between 1 to 3999 sprintf() in C Find frequency of each word in a string in Python
[ { "code": null, "e": 24852, "s": 24824, "text": "\n03 May, 2021" }, { "code": null, "e": 25000, "s": 24852, "text": "Given a string str, we need to find the no. of positions where a letter(lowercase) can be inserted so that string becomes a palindrome. Examples: " }, { "code": null, "e": 25324, "s": 25000, "text": "Input : str = \"abca\"\nOutput : possible palindromic strings: \n 1) acbca (at position 2)\n 2) abcba (at position 4)\n Hence, the output is 2.\n\nInput : str = \"aaa\"\nOutput : possible palindromic strings:\n 1) aaaa\n 2) aaaa\n 3) aaaa\n 4) aaaa\n Hence, the output is 4. " }, { "code": null, "e": 26706, "s": 25326, "text": "Naive Approach:This approach is to insert all 26 alphabets at every position possible i.e., N+1 positions and check at every position if this insertion makes it a palindrome and increase the count.Efficient Approach: First you have to observe that we have to make insertion only at the point when the character at that point violates the palindrome condition i.e., . Now, there will be two cases based on the above fact: Case I: What if the given string is already a palindrome Then we can only insert at the position such that the insertion does not violate the palindrome. 1) If the length is even then we can always insert any letter in the middle. 2) If the length is odd then we can insert the letter which is in middle, to the left or right to it. 3) In both the cases we can insert the letter which is in middle(let it be ‘CH’), at positions equals to: (no.of consecutive CH’s to the left of middle letter)*2. Case II:If it is not a palindrome As mentioned above we should start inserting at position where , So we increase the count and check for the cases if insertion at any other position makes it a palindrome. 1) If is a palindrome, then we can insert* at any position before until , K in range .(*letter = S[N-i-1]) 2.)If is a palindrome, then we can insert* at any position after until , K in range .(*letter = S[i]) In all the cases we keep increasing the count. " }, { "code": null, "e": 26710, "s": 26706, "text": "C++" }, { "code": null, "e": 26715, "s": 26710, "text": "Java" }, { "code": null, "e": 26724, "s": 26715, "text": "Python 3" }, { "code": null, "e": 26727, "s": 26724, "text": "C#" }, { "code": null, "e": 26731, "s": 26727, "text": "PHP" }, { "code": null, "e": 26742, "s": 26731, "text": "Javascript" }, { "code": "// CPP code to find the no.of positions where a// letter can be inserted to make it a palindrome#include <bits/stdc++.h>using namespace std; // Function to check if the string is palindromebool isPalindrome(string &s, int i, int j){ int p = j; for (int k = i; k <= p; k++) { if (s[k] != s[p]) return false; p--; } return true;} int countWays(string &s){ // to know the length of string int n = s.length(); int count = 0; // if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (int i = n / 2; i < n; i++) { if (s[i] == s[i + 1]) count++; else break; } if (n % 2 == 0) // if the length is even { count++; count = 2 * count + 1; // sub-case-I } else count = 2 * count + 2; // sub-case-II } else { for (int i = 0; i < n / 2; i++) { // insertion point if (s[i] != s[n - 1 - i]) { int j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (int k = i - 1; k >= 0; k--) { if (s[k] != s[j]) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (int k = n - i; k < n; k++) { if (s[k] != s[i]) break; count++; } count++; } break; } } } return count;} // Driver codeint main(){ string s = \"abca\"; cout << countWays(s) << endl; return 0;}", "e": 28642, "s": 26742, "text": null }, { "code": "// Java code to find the no.of positions where a// letter can be inserted to make it a palindrome import java.io.*; class GFG { // Function to check if the string is palindrome static boolean isPalindrome(String s, int i, int j) { int p = j; for (int k = i; k <= p; k++) { if (s.charAt(k) != s.charAt(p)) return false; p--; } return true; } static int countWays(String s) { // to know the length of string int n = s.length(); int count = 0; // if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (int i = n / 2; i < n; i++) { if (s.charAt(i) == s.charAt(i + 1)) count++; else break; } if (n % 2 == 0) // if the length is even { count++; count = 2 * count + 1; // sub-case-I } else count = 2 * count + 2; // sub-case-II } else { for (int i = 0; i < n / 2; i++) { // insertion point if (s.charAt(i) != s.charAt(n - 1 - i)) { int j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (int k = i - 1; k >= 0; k--) { if (s.charAt(k) != s.charAt(j)) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (int k = n - i; k < n; k++) { if (s.charAt(k) != s.charAt(i)) break; count++; } count++; } break; } } } return count; } // Driver code public static void main(String[] args) { String s = \"abca\"; System.out.println(countWays(s)); }} // This code is contributed by vt_m.", "e": 30946, "s": 28642, "text": null }, { "code": "# Python 3 code to find the no.of positions# where a letter can be inserted to make it# a palindrome # Function to check if the string# is palindromedef isPalindrome(s, i, j): p = j for k in range(i, p + 1): if (s[k] != s[p]): return False p -= 1 return True def countWays(s): # to know the length of string n = len(s) count = 0 # if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) : # Sub-case-III) for i in range(n // 2, n): if (s[i] == s[i + 1]): count += 1 else: break if (n % 2 == 0): # if the length is even count += 1 count = 2 * count + 1 # sub-case-I else: count = 2 * count + 2 # sub-case-II else : for i in range(n // 2) : # insertion point if (s[i] != s[n - 1 - i]) : j = n - 1 - i # Case-I if (isPalindrome(s, i, n - 2 - i)) : for k in range(i - 1, -1, -1): if (s[k] != s[j]): break count += 1 count += 1 # Case-II if (isPalindrome(s, i + 1, n - 1 - i)) : for k in range(n - i, n) : if (s[k] != s[i]): break count += 1 count += 1 break return count # Driver codeif __name__ == \"__main__\": s = \"abca\" print(countWays(s)) # This code is contributed by ita_c", "e": 32649, "s": 30946, "text": null }, { "code": "// C# code to find the no. of positions// where a letter can be inserted// to make it a palindrome.using System; class GFG { // Function to check if the // string is palindrome static bool isPalindrome(String s, int i, int j) { int p = j; for (int k = i; k <= p; k++) { if (s[k] != s[p]) return false; p--; } return true; } static int countWays(String s) { // to know the length of string int n = s.Length; int count = 0; // if the given string is // a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (int i = n / 2; i < n; i++) { if (s[i] == s[i + 1]) count++; else break; } // if the length is even if (n % 2 == 0) { count++; // sub-case-I count = 2 * count + 1; } else // sub-case-II count = 2 * count + 2; } else { for (int i = 0; i < n / 2; i++) { // insertion point if (s[i] != s[n - 1 - i]) { int j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (int k = i - 1; k >= 0; k--) { if (s[k] != s[j]) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (int k = n - i; k < n; k++) { if (s[k] != s[i]) break; count++; } count++; } break; } } } return count; } // Driver code public static void Main() { String s = \"abca\"; Console.Write(countWays(s)); }} // This code is contributed by nitin mittal", "e": 34996, "s": 32649, "text": null }, { "code": "<?php// PHP code to find the no. of// positions where a letter can// be inserted to make it a palindrome // Function to check if the// string is palindromefunction isPalindrome($s, $i, $j){ $p = $j; for ($k = $i; $k <= $p; $k++) { if ($s[$k] != $s[$p]) return false; $p--; } return true;} function countWays($s){ // to know the length of string $n = strlen($s); $count = 0; // if the given string is // a palindrome(Case-I) if (isPalindrome($s, 0, $n - 1)) { // Sub-case-III) for ($i = $n / 2; $i < $n; $i++) { if ($s[$i] == $s[$i + 1]) $count++; else break; } // if the length is even if ($n % 2 == 0) { $count++; // sub-case-I $count = 2 * $count + 1; } else // sub-case-II $count = 2 * $count + 2; } else { for ($i = 0; $i < $n / 2; $i++) { // insertion point if ($s[$i] != $s[$n - 1 - $i]) { $j = $n - 1 - $i; // Case-I if (isPalindrome($s, $i, $n - 2 - $i)) { for ($k = $i - 1; $k >= 0; $k--) { if ($s[$k] != $s[$j]) break; $count++; } $count++; } // Case-II if (isPalindrome($s, $i + 1,$n - 1 - $i)) { for ($k = $n - $i; $k < $n; $k++) { if ($s[$k] != $s[$i]) break; $count++; } $count++; } break; } } } return $count;} // Driver code$s = \"abca\";echo countWays($s) ; // This code is contributed by nitin mittal?>", "e": 37028, "s": 34996, "text": null }, { "code": "<script>// Javascript code to find the no.of positions where a// letter can be inserted to make it a palindrome function isPalindrome(s,i,j) { let p = j; for (let k = i; k <= p; k++) { if (s[k] != s[p]) return false; p--; } return true; } // Function to check if the string is palindromefunction countWays(s){ // to know the length of string let n = s.length; let count = 0; // if the given string is a palindrome(Case-I) if (isPalindrome(s, 0, n - 1)) { // Sub-case-III) for (let i = n / 2; i < n; i++) { if (s[i] == s[i + 1]) count++; else break; } if (n % 2 == 0) // if the length is even { count++; count = 2 * count + 1; // sub-case-I } else count = 2 * count + 2; // sub-case-II } else { for (let i = 0; i < n / 2; i++) { // insertion point if (s[i] != s[n - 1 - i]) { let j = n - 1 - i; // Case-I if (isPalindrome(s, i, n - 2 - i)) { for (let k = i - 1; k >= 0; k--) { if (s[k] != s[j]) break; count++; } count++; } // Case-II if (isPalindrome(s, i + 1, n - 1 - i)) { for (let k = n - i; k < n; k++) { if (s[k] != s[i]) break; count++; } count++; } break; } } } return count;} // Driver codelet s = \"abca\";document.write( countWays(s)); // This code is contributed by avanitrachhadiya2155</script>", "e": 38950, "s": 37028, "text": null }, { "code": null, "e": 38960, "s": 38950, "text": "Output: " }, { "code": null, "e": 38962, "s": 38960, "text": "2" }, { "code": null, "e": 39383, "s": 38962, "text": "This article is contributed by Harsha Mogali. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39396, "s": 39383, "text": "nitin mittal" }, { "code": null, "e": 39402, "s": 39396, "text": "ukasp" }, { "code": null, "e": 39423, "s": 39402, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39434, "s": 39423, "text": "palindrome" }, { "code": null, "e": 39442, "s": 39434, "text": "Strings" }, { "code": null, "e": 39450, "s": 39442, "text": "Strings" }, { "code": null, "e": 39461, "s": 39450, "text": "palindrome" }, { "code": null, "e": 39559, "s": 39461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39568, "s": 39559, "text": "Comments" }, { "code": null, "e": 39581, "s": 39568, "text": "Old Comments" }, { "code": null, "e": 39626, "s": 39581, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 39638, "s": 39626, "text": "Hill Cipher" }, { "code": null, "e": 39676, "s": 39638, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 39693, "s": 39676, "text": "Vigenère Cipher" }, { "code": null, "e": 39736, "s": 39693, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 39777, "s": 39736, "text": "Convert character array to string in C++" }, { "code": null, "e": 39812, "s": 39777, "text": "Print all subsequences of a string" }, { "code": null, "e": 39873, "s": 39812, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" }, { "code": null, "e": 39888, "s": 39873, "text": "sprintf() in C" } ]
BlockingQueue take() method in Java with examples - GeeksforGeeks
23 Aug, 2021 The take() method of BlockingQueue interface is used to retrieve and remove the head of this queue. If the queue is empty then it will wait until an element becomes available. This method is more efficient if working on threads and using BlockingQueue in that process. So the thread that initially calls take() goes to sleep if there is no element available, letting other threads do whatever they need to do. Syntax: public E take() throws InterruptedException Return Value: This method returns value at the head of this BlockingQueue. If the queue is empty then it will wait until an element becomes available.Exception: This method throws following exceptions: InterruptedException– When the interruption occurs at time of waiting for an element to become available if queue is empty. Note: The take() method of BlockingQueue has been inherited from the Queue class in Java.Below programs illustrates take() method of BlockingQueue interface:Program 1: Java // Java Program Demonstrate take()// method of BlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue;public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<String> BQ = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to BlockingQueue BQ.add("Ravi"); BQ.add("Suraj"); BQ.add("Harsh"); BQ.add("Sayan"); // print elements of queue System.out.println("Items in Queue are " + BQ); // remove two elements from queue from head // Applying take() method on queue to remove element String removedItem1 = BQ.take(); // print removedItem and queue System.out.println("Removed Item from head is " + removedItem1); // print elements of queue after removing first item System.out.println("Remaining Items in Queue are " + BQ); // Applying take() method on queue to remove another element String removedItem2 = BQ.take(); // print removedItem and queue System.out.println("Removed Item from head is " + removedItem2); // print elements of queue after removing first item System.out.println("Remaining Items in Queue are " + BQ); }} Items in Queue are [Ravi, Suraj, Harsh, Sayan] Removed Item from head is Ravi Remaining Items in Queue are [Suraj, Harsh, Sayan] Removed Item from head is Suraj Remaining Items in Queue are [Harsh, Sayan] Program 2: Java // Java Program Demonstrate take()// method of BlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { public void takeDemo() throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 5; // create object of BlockingQueue BlockingQueue<Employee> BQ = new LinkedBlockingQueue<Employee>(capacityOfQueue); // Add element to BlockingQueue Employee emp1 = new Employee("Ravi", "Tester", "39000"); Employee emp2 = new Employee("Sanjeet", "Manager", "98000"); // Add Employee Objects to BQ BQ.add(emp1); BQ.add(emp2); // remove elements from the queue // and follow this process again and again // until the queue becomes empty while (BQ.size() != 0) { // Remove Employee item from BlockingQueue // using take() Employee removedEmp = BQ.take(); // print removedItem System.out.println("Removed Item is :"); System.out.println("Employee Name - " + removedEmp.name); System.out.println("Employee Position - " + removedEmp.position); System.out.println("Employee Salary - " + removedEmp.salary); // find size of BQ int size = BQ.size(); // print remaining capacity value System.out.println("\nSize of list :" + size + "\n"); } } // create an Employee Object with name, // position and salary as an attribute public class Employee { public String name; public String position; public String salary; Employee(String name, String position, String salary) { this.name = name; this.position = position; this.salary = salary; } @Override public String toString() { return "Employee [name=" + name + ", position=" + position + ", salary=" + salary + "]"; } } // Main Method public static void main(String[] args) { GFG gfg = new GFG(); try { gfg.takeDemo(); } catch (Exception e) { e.printStackTrace(); } }} Removed Item is : Employee Name - Ravi Employee Position - Tester Employee Salary - 39000 Size of list :1 Removed Item is : Employee Name - Sanjeet Employee Position - Manager Employee Salary - 98000 Size of list :0 sagar0719kumar Java-BlockingQueue Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25617, "s": 25589, "text": "\n23 Aug, 2021" }, { "code": null, "e": 26028, "s": 25617, "text": "The take() method of BlockingQueue interface is used to retrieve and remove the head of this queue. If the queue is empty then it will wait until an element becomes available. This method is more efficient if working on threads and using BlockingQueue in that process. So the thread that initially calls take() goes to sleep if there is no element available, letting other threads do whatever they need to do. " }, { "code": null, "e": 26038, "s": 26028, "text": "Syntax: " }, { "code": null, "e": 26082, "s": 26038, "text": "public E take() throws InterruptedException" }, { "code": null, "e": 26286, "s": 26082, "text": "Return Value: This method returns value at the head of this BlockingQueue. If the queue is empty then it will wait until an element becomes available.Exception: This method throws following exceptions: " }, { "code": null, "e": 26410, "s": 26286, "text": "InterruptedException– When the interruption occurs at time of waiting for an element to become available if queue is empty." }, { "code": null, "e": 26579, "s": 26410, "text": "Note: The take() method of BlockingQueue has been inherited from the Queue class in Java.Below programs illustrates take() method of BlockingQueue interface:Program 1: " }, { "code": null, "e": 26584, "s": 26579, "text": "Java" }, { "code": "// Java Program Demonstrate take()// method of BlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue;public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<String> BQ = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to BlockingQueue BQ.add(\"Ravi\"); BQ.add(\"Suraj\"); BQ.add(\"Harsh\"); BQ.add(\"Sayan\"); // print elements of queue System.out.println(\"Items in Queue are \" + BQ); // remove two elements from queue from head // Applying take() method on queue to remove element String removedItem1 = BQ.take(); // print removedItem and queue System.out.println(\"Removed Item from head is \" + removedItem1); // print elements of queue after removing first item System.out.println(\"Remaining Items in Queue are \" + BQ); // Applying take() method on queue to remove another element String removedItem2 = BQ.take(); // print removedItem and queue System.out.println(\"Removed Item from head is \" + removedItem2); // print elements of queue after removing first item System.out.println(\"Remaining Items in Queue are \" + BQ); }}", "e": 28119, "s": 26584, "text": null }, { "code": null, "e": 28324, "s": 28119, "text": "Items in Queue are [Ravi, Suraj, Harsh, Sayan]\nRemoved Item from head is Ravi\nRemaining Items in Queue are [Suraj, Harsh, Sayan]\nRemoved Item from head is Suraj\nRemaining Items in Queue are [Harsh, Sayan]" }, { "code": null, "e": 28338, "s": 28326, "text": "Program 2: " }, { "code": null, "e": 28343, "s": 28338, "text": "Java" }, { "code": "// Java Program Demonstrate take()// method of BlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { public void takeDemo() throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 5; // create object of BlockingQueue BlockingQueue<Employee> BQ = new LinkedBlockingQueue<Employee>(capacityOfQueue); // Add element to BlockingQueue Employee emp1 = new Employee(\"Ravi\", \"Tester\", \"39000\"); Employee emp2 = new Employee(\"Sanjeet\", \"Manager\", \"98000\"); // Add Employee Objects to BQ BQ.add(emp1); BQ.add(emp2); // remove elements from the queue // and follow this process again and again // until the queue becomes empty while (BQ.size() != 0) { // Remove Employee item from BlockingQueue // using take() Employee removedEmp = BQ.take(); // print removedItem System.out.println(\"Removed Item is :\"); System.out.println(\"Employee Name - \" + removedEmp.name); System.out.println(\"Employee Position - \" + removedEmp.position); System.out.println(\"Employee Salary - \" + removedEmp.salary); // find size of BQ int size = BQ.size(); // print remaining capacity value System.out.println(\"\\nSize of list :\" + size + \"\\n\"); } } // create an Employee Object with name, // position and salary as an attribute public class Employee { public String name; public String position; public String salary; Employee(String name, String position, String salary) { this.name = name; this.position = position; this.salary = salary; } @Override public String toString() { return \"Employee [name=\" + name + \", position=\" + position + \", salary=\" + salary + \"]\"; } } // Main Method public static void main(String[] args) { GFG gfg = new GFG(); try { gfg.takeDemo(); } catch (Exception e) { e.printStackTrace(); } }}", "e": 30702, "s": 28343, "text": null }, { "code": null, "e": 30921, "s": 30702, "text": "Removed Item is :\nEmployee Name - Ravi\nEmployee Position - Tester\nEmployee Salary - 39000\n\nSize of list :1\n\nRemoved Item is :\nEmployee Name - Sanjeet\nEmployee Position - Manager\nEmployee Salary - 98000\n\nSize of list :0" }, { "code": null, "e": 30938, "s": 30923, "text": "sagar0719kumar" }, { "code": null, "e": 30957, "s": 30938, "text": "Java-BlockingQueue" }, { "code": null, "e": 30974, "s": 30957, "text": "Java-Collections" }, { "code": null, "e": 30989, "s": 30974, "text": "Java-Functions" }, { "code": null, "e": 30994, "s": 30989, "text": "Java" }, { "code": null, "e": 30999, "s": 30994, "text": "Java" }, { "code": null, "e": 31016, "s": 30999, "text": "Java-Collections" }, { "code": null, "e": 31114, "s": 31016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31144, "s": 31114, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31159, "s": 31144, "text": "Stream In Java" }, { "code": null, "e": 31178, "s": 31159, "text": "Interfaces in Java" }, { "code": null, "e": 31209, "s": 31178, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31241, "s": 31209, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31259, "s": 31241, "text": "ArrayList in Java" }, { "code": null, "e": 31279, "s": 31259, "text": "Stack Class in Java" }, { "code": null, "e": 31303, "s": 31279, "text": "Singleton Class in Java" }, { "code": null, "e": 31335, "s": 31303, "text": "Multidimensional Arrays in Java" } ]
Database, Table and Column Naming Conventions - GeeksforGeeks
09 Aug, 2021 Overview :Databases are persistent storage mechanisms that are present throughout the lifecycle of any application. Databases are created and maintained by the initial database managers and are continued to be maintained by any new database managers that join the team, thus it is a good habit to keep its characteristics consistent throughout. Naming conventions are a set of guideline that make strong foundations for such a consistent system. These guidelines ensure that the names of database entities are readable, easy to use in queries and do not collide with names of other defined entities or keywords. Naming Databases :When naming databases in a professional environment it mainly depends on what kind of application or website will the database belong to. Suppose you are creating a database for an application XYZ, for a company ABC, then the database would be named ABC_XYZ. Database names are easier to use when short, preferably using abbreviations (Facebook becomes FB), and need not be very descriptive. Building on the same point, IBM states in its documentation that database name or database alias should be a unique character string containing one to eight letters from the set of [a-z, A-Z, 0-9, @, #, $]. You can also add a product’s version to the database name. Naming Tables :Tables represent a group/set of some entity that is usually a real-world object like an employee or consequences of that entity like a project. Tables names are like nouns. Different teams of developers follow different practices while naming their tables but some fundamentals are the key to efficiency. There are following steps for the Naming table are as follows. Step-1 : Table names should be descriptive. If you are designing a table to store the data about customers in a grocery shop then the table can be named “Customer” or “Customers” based on your preference. However, you should avoid abbreviations because different people may have different thought process while creating an abbreviation like “Cus” which may not always align with another person’s naming like “Cust”. So to keep things simple use full names and if you plan on using singular or plural names then that should remain consistent throughout the project. #Creating table Customer CREATE TABLE Customer (column1 datatype, column2 datatype, column3 datatype, ....); Step-2 : You can use underscores to prefix a table name. For example, all vegetarian food tables can be written as “Veg_Food” and non-vegetarian can be written as “NonVeg_Food.” Step-3 : Avoid using DBMS-specific keywords as names for your tables like “Order” (ORDER BY). The server or the RDBMS won’t throw any error while naming a table as “Order” but it is a good practice. Step-4 : Casing depends all on what the developer prefers and what has been used consistently before. But similar to the singular-plural dilemma, you should stick to one case whichever looks readable and easy on the eyes, either it be PascalCase or camelCase or all lowercase etc. CREATE TABLE OldMansions (column1 datatype, column2 datatype, column3 datatype, ....); CREATE TABLE oldMansions (column1 datatype, column2 datatype, column3 datatype, ....); CREATE TABLE oldmansions (column1 datatype, column2 datatype, column3 datatype, ....); CREATE TABLE old_mansions (column1 datatype, column2 datatype, column3 datatype, ....); Naming Columns : Columns are different than tables as they can mean more than just a real-world entity. Columns are the attributes that define a real-world entity. Columns may define the departure time of a train or the distance of a planet from the sun, or simply someone’s name. Thus, it is common sense to name a column corresponding to its use. Column names are like adjectives or verbs. There are the following steps for Naming columns are as follows. Step-1 : Each column name should be unique. If two columns from different tables serving different purposes are in the same database then use some kind of prefixes that separate the two. Step-2 : Column names must not be abstract or cryptic. Use long descriptive names instead of short and unclear abbreviations. Step-3 : The column names must not be very generic. For example, while creating a column that stores the codes of grocery items it would be better to name the column “Grocery_Code” or “ItemCode” instead of just “Code.” You can have a quick look at this column to add suffixes with a specific domain’s prefixes. Naming Primary Keys : Primary keys serve as the unique identifier for your table, thus it is important to be careful while naming them. If several different tables with different uses have the same name for their respective primary key then it would be very confusing. Make sure that instead of naming a primary key representing an identity number as ID, use domain-specific names like StudentID or ID_Student. You can also use suffixes or prefixes with your primary keys to making them stand out from the general column naming. For example, Coordinates_PK or PK_Coordinates. Primary keys serve as the unique identifier for your table, thus it is important to be careful while naming them. If several different tables with different uses have the same name for their respective primary key then it would be very confusing. Make sure that instead of naming a primary key representing an identity number as ID, use domain-specific names like StudentID or ID_Student. You can also use suffixes or prefixes with your primary keys to making them stand out from the general column naming. For example, Coordinates_PK or PK_Coordinates. Naming Foreign Keys : Foreign keys are used as a bridge between two tables, and sometimes among more tables. Thus, it is good to name your foreign key with the same name consistently throughout the database to avoid any confusion. Similar to primary keys, you can add prefix or suffix to a foreign key name, like RoomNo_fk or FK_RoomNo.At the end of the day, no one is going to force you to follow these conventions while creating a database. But following even some of these will make your database better for you as well as anyone else who might work on it in the future. Foreign keys are used as a bridge between two tables, and sometimes among more tables. Thus, it is good to name your foreign key with the same name consistently throughout the database to avoid any confusion. Similar to primary keys, you can add prefix or suffix to a foreign key name, like RoomNo_fk or FK_RoomNo. At the end of the day, no one is going to force you to follow these conventions while creating a database. But following even some of these will make your database better for you as well as anyone else who might work on it in the future. Picked DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS KDD Process in Data Mining Structure of Database Management System Difference between File System and DBMS Advantages of Database Management System Insert Operation in B-Tree Relational Model in DBMS What is Temporary Table in SQL?
[ { "code": null, "e": 24304, "s": 24276, "text": "\n09 Aug, 2021" }, { "code": null, "e": 24917, "s": 24304, "text": "Overview :Databases are persistent storage mechanisms that are present throughout the lifecycle of any application. Databases are created and maintained by the initial database managers and are continued to be maintained by any new database managers that join the team, thus it is a good habit to keep its characteristics consistent throughout. Naming conventions are a set of guideline that make strong foundations for such a consistent system. These guidelines ensure that the names of database entities are readable, easy to use in queries and do not collide with names of other defined entities or keywords. " }, { "code": null, "e": 25594, "s": 24917, "text": "Naming Databases :When naming databases in a professional environment it mainly depends on what kind of application or website will the database belong to. Suppose you are creating a database for an application XYZ, for a company ABC, then the database would be named ABC_XYZ. Database names are easier to use when short, preferably using abbreviations (Facebook becomes FB), and need not be very descriptive. Building on the same point, IBM states in its documentation that database name or database alias should be a unique character string containing one to eight letters from the set of [a-z, A-Z, 0-9, @, #, $]. You can also add a product’s version to the database name. " }, { "code": null, "e": 25977, "s": 25594, "text": "Naming Tables :Tables represent a group/set of some entity that is usually a real-world object like an employee or consequences of that entity like a project. Tables names are like nouns. Different teams of developers follow different practices while naming their tables but some fundamentals are the key to efficiency. There are following steps for the Naming table are as follows." }, { "code": null, "e": 26542, "s": 25977, "text": "Step-1 : Table names should be descriptive. If you are designing a table to store the data about customers in a grocery shop then the table can be named “Customer” or “Customers” based on your preference. However, you should avoid abbreviations because different people may have different thought process while creating an abbreviation like “Cus” which may not always align with another person’s naming like “Cust”. So to keep things simple use full names and if you plan on using singular or plural names then that should remain consistent throughout the project." }, { "code": null, "e": 26651, "s": 26542, "text": "#Creating table Customer\nCREATE TABLE Customer (column1 datatype, column2 datatype, column3 datatype, ....);" }, { "code": null, "e": 26829, "s": 26651, "text": "Step-2 : You can use underscores to prefix a table name. For example, all vegetarian food tables can be written as “Veg_Food” and non-vegetarian can be written as “NonVeg_Food.”" }, { "code": null, "e": 27028, "s": 26829, "text": "Step-3 : Avoid using DBMS-specific keywords as names for your tables like “Order” (ORDER BY). The server or the RDBMS won’t throw any error while naming a table as “Order” but it is a good practice." }, { "code": null, "e": 27309, "s": 27028, "text": "Step-4 : Casing depends all on what the developer prefers and what has been used consistently before. But similar to the singular-plural dilemma, you should stick to one case whichever looks readable and easy on the eyes, either it be PascalCase or camelCase or all lowercase etc." }, { "code": null, "e": 27658, "s": 27309, "text": "CREATE TABLE OldMansions (column1 datatype, column2 datatype, column3 datatype, ....);\nCREATE TABLE oldMansions (column1 datatype, column2 datatype, column3 datatype, ....);\nCREATE TABLE oldmansions (column1 datatype, column2 datatype, column3 datatype, ....);\nCREATE TABLE old_mansions (column1 datatype, column2 datatype, column3 datatype, ....);" }, { "code": null, "e": 28118, "s": 27658, "text": "Naming Columns : Columns are different than tables as they can mean more than just a real-world entity. Columns are the attributes that define a real-world entity. Columns may define the departure time of a train or the distance of a planet from the sun, or simply someone’s name. Thus, it is common sense to name a column corresponding to its use. Column names are like adjectives or verbs. There are the following steps for Naming columns are as follows." }, { "code": null, "e": 28306, "s": 28118, "text": "Step-1 : Each column name should be unique. If two columns from different tables serving different purposes are in the same database then use some kind of prefixes that separate the two. " }, { "code": null, "e": 28433, "s": 28306, "text": "Step-2 : Column names must not be abstract or cryptic. Use long descriptive names instead of short and unclear abbreviations. " }, { "code": null, "e": 28744, "s": 28433, "text": "Step-3 : The column names must not be very generic. For example, while creating a column that stores the codes of grocery items it would be better to name the column “Grocery_Code” or “ItemCode” instead of just “Code.” You can have a quick look at this column to add suffixes with a specific domain’s prefixes." }, { "code": null, "e": 28766, "s": 28744, "text": "Naming Primary Keys :" }, { "code": null, "e": 29320, "s": 28766, "text": "Primary keys serve as the unique identifier for your table, thus it is important to be careful while naming them. If several different tables with different uses have the same name for their respective primary key then it would be very confusing. Make sure that instead of naming a primary key representing an identity number as ID, use domain-specific names like StudentID or ID_Student. You can also use suffixes or prefixes with your primary keys to making them stand out from the general column naming. For example, Coordinates_PK or PK_Coordinates." }, { "code": null, "e": 29568, "s": 29320, "text": "Primary keys serve as the unique identifier for your table, thus it is important to be careful while naming them. If several different tables with different uses have the same name for their respective primary key then it would be very confusing. " }, { "code": null, "e": 29711, "s": 29568, "text": "Make sure that instead of naming a primary key representing an identity number as ID, use domain-specific names like StudentID or ID_Student. " }, { "code": null, "e": 29876, "s": 29711, "text": "You can also use suffixes or prefixes with your primary keys to making them stand out from the general column naming. For example, Coordinates_PK or PK_Coordinates." }, { "code": null, "e": 29898, "s": 29876, "text": "Naming Foreign Keys :" }, { "code": null, "e": 30450, "s": 29898, "text": "Foreign keys are used as a bridge between two tables, and sometimes among more tables. Thus, it is good to name your foreign key with the same name consistently throughout the database to avoid any confusion. Similar to primary keys, you can add prefix or suffix to a foreign key name, like RoomNo_fk or FK_RoomNo.At the end of the day, no one is going to force you to follow these conventions while creating a database. But following even some of these will make your database better for you as well as anyone else who might work on it in the future." }, { "code": null, "e": 30660, "s": 30450, "text": "Foreign keys are used as a bridge between two tables, and sometimes among more tables. Thus, it is good to name your foreign key with the same name consistently throughout the database to avoid any confusion. " }, { "code": null, "e": 30766, "s": 30660, "text": "Similar to primary keys, you can add prefix or suffix to a foreign key name, like RoomNo_fk or FK_RoomNo." }, { "code": null, "e": 31004, "s": 30766, "text": "At the end of the day, no one is going to force you to follow these conventions while creating a database. But following even some of these will make your database better for you as well as anyone else who might work on it in the future." }, { "code": null, "e": 31011, "s": 31004, "text": "Picked" }, { "code": null, "e": 31016, "s": 31011, "text": "DBMS" }, { "code": null, "e": 31021, "s": 31016, "text": "DBMS" }, { "code": null, "e": 31119, "s": 31021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31128, "s": 31119, "text": "Comments" }, { "code": null, "e": 31141, "s": 31128, "text": "Old Comments" }, { "code": null, "e": 31166, "s": 31141, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 31207, "s": 31166, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 31250, "s": 31207, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 31277, "s": 31250, "text": "KDD Process in Data Mining" }, { "code": null, "e": 31317, "s": 31277, "text": "Structure of Database Management System" }, { "code": null, "e": 31357, "s": 31317, "text": "Difference between File System and DBMS" }, { "code": null, "e": 31398, "s": 31357, "text": "Advantages of Database Management System" }, { "code": null, "e": 31425, "s": 31398, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 31450, "s": 31425, "text": "Relational Model in DBMS" } ]