title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C++ Algorithm Library - includes() Function
The C++ function std::algorithm::includes() test whether first set is subset of another or not. This member function expects elements in sorted order. It use operator< for comparison. Following is the declaration for std::algorithm::includes() function form std::algorithm header. template <class InputIterator1, class InputIterator2> bool includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); first1 − Input iterator to the initial position of the first sequence. first1 − Input iterator to the initial position of the first sequence. last1 − Input iterator to the final position of the first sequence. last1 − Input iterator to the final position of the first sequence. first2 − Input iterator to the initial position of the second sequence. first2 − Input iterator to the initial position of the second sequence. last2 − Input iterator to the final position of the second sequence. last2 − Input iterator to the final position of the second sequence. Returns true if first set is subset of another otherwise returns false. Throws exception if element comparison or an operation on an iterator throws exception. Please note that invalid parameters cause undefined behavior. Linear. The following example shows the usage of std::algorithm::includes() function. #include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void) { vector<int> v1 = {1, 2, 3, 4, 5}; vector<int> v2 = {3, 4, 5}; bool result; result = includes(v1.begin(), v1.end(), v2.begin(), v2.end()); if (result == true) cout << "Vector v2 is subset of v1" << endl; v2 = {10}; result = includes(v1.begin(), v1.end(), v2.begin(), v2.end()); if (result == false) cout << "Vector v2 is not subset of v1" << endl; return 0; } Let us compile and run the above program, this will produce the following result − Vector v2 is subset of v1 Vector v2 is not subset of v1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2787, "s": 2603, "text": "The C++ function std::algorithm::includes() test whether first set is subset of another or not. This member function expects elements in sorted order. It use operator< for comparison." }, { "code": null, "e": 2884, "s": 2787, "text": "Following is the declaration for std::algorithm::includes() function form std::algorithm header." }, { "code": null, "e": 3047, "s": 2884, "text": "template <class InputIterator1, class InputIterator2>\nbool includes(InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2);\n" }, { "code": null, "e": 3118, "s": 3047, "text": "first1 − Input iterator to the initial position of the first sequence." }, { "code": null, "e": 3189, "s": 3118, "text": "first1 − Input iterator to the initial position of the first sequence." }, { "code": null, "e": 3257, "s": 3189, "text": "last1 − Input iterator to the final position of the first sequence." }, { "code": null, "e": 3325, "s": 3257, "text": "last1 − Input iterator to the final position of the first sequence." }, { "code": null, "e": 3397, "s": 3325, "text": "first2 − Input iterator to the initial position of the second sequence." }, { "code": null, "e": 3469, "s": 3397, "text": "first2 − Input iterator to the initial position of the second sequence." }, { "code": null, "e": 3538, "s": 3469, "text": "last2 − Input iterator to the final position of the second sequence." }, { "code": null, "e": 3607, "s": 3538, "text": "last2 − Input iterator to the final position of the second sequence." }, { "code": null, "e": 3679, "s": 3607, "text": "Returns true if first set is subset of another otherwise returns false." }, { "code": null, "e": 3767, "s": 3679, "text": "Throws exception if element comparison or an operation on an iterator throws exception." }, { "code": null, "e": 3829, "s": 3767, "text": "Please note that invalid parameters cause undefined behavior." }, { "code": null, "e": 3837, "s": 3829, "text": "Linear." }, { "code": null, "e": 3915, "s": 3837, "text": "The following example shows the usage of std::algorithm::includes() function." }, { "code": null, "e": 4418, "s": 3915, "text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v1 = {1, 2, 3, 4, 5};\n vector<int> v2 = {3, 4, 5};\n bool result;\n\n result = includes(v1.begin(), v1.end(), v2.begin(), v2.end());\n\n if (result == true)\n cout << \"Vector v2 is subset of v1\" << endl;\n\n v2 = {10};\n\n result = includes(v1.begin(), v1.end(), v2.begin(), v2.end());\n\n if (result == false)\n cout << \"Vector v2 is not subset of v1\" << endl;\n\n return 0;\n}" }, { "code": null, "e": 4501, "s": 4418, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4558, "s": 4501, "text": "Vector v2 is subset of v1\nVector v2 is not subset of v1\n" }, { "code": null, "e": 4565, "s": 4558, "text": " Print" }, { "code": null, "e": 4576, "s": 4565, "text": " Add Notes" } ]
Select the date records between two dates in MySQL
To select the date records between two dates, you need to use the BETWEEN keyword. Let us first create a table − mysql> create table DemoTable681(AdmissionDate datetime); Query OK, 0 rows affected (0.75 sec) Insert some records in the table using insert command − mysql> insert into DemoTable681 values('2019-01-21'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable681 values('2019-11-01'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable681 values('2019-12-03'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable681 values('2019-07-03'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable681 values('2019-02-04'); Query OK, 1 row affected (0.34 sec) Display all records from the table using select statement: mysql> select *from DemoTable681; This will produce the following output − +---------------------+ | AdmissionDate | +---------------------+ | 2019-01-21 00:00:00 | | 2019-11-01 00:00:00 | | 2019-12-03 00:00:00 | | 2019-07-03 00:00:00 | | 2019-02-04 00:00:00 | +---------------------+ 5 rows in set (0.00 sec) Following is the query to select the date records between two dates − mysql> select *from DemoTable681 where AdmissionDate between '2019-02-01' and '2019-12-01'; This will produce the following output − +---------------------+ | AdmissionDate | +---------------------+ | 2019-11-01 00:00:00 | | 2019-07-03 00:00:00 | | 2019-02-04 00:00:00 | +---------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1175, "s": 1062, "text": "To select the date records between two dates, you need to use the BETWEEN keyword. Let us first create a table −" }, { "code": null, "e": 1270, "s": 1175, "text": "mysql> create table DemoTable681(AdmissionDate datetime);\nQuery OK, 0 rows affected (0.75 sec)" }, { "code": null, "e": 1326, "s": 1270, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1835, "s": 1326, "text": "mysql> insert into DemoTable681 values('2019-01-21');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable681 values('2019-11-01');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable681 values('2019-12-03');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable681 values('2019-07-03');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable681 values('2019-02-04');\nQuery OK, 1 row affected (0.34 sec)\nDisplay all records from the table using select statement:" }, { "code": null, "e": 1869, "s": 1835, "text": "mysql> select *from DemoTable681;" }, { "code": null, "e": 1910, "s": 1869, "text": "This will produce the following output −" }, { "code": null, "e": 2151, "s": 1910, "text": "+---------------------+\n| AdmissionDate |\n+---------------------+\n| 2019-01-21 00:00:00 |\n| 2019-11-01 00:00:00 |\n| 2019-12-03 00:00:00 |\n| 2019-07-03 00:00:00 |\n| 2019-02-04 00:00:00 |\n+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2221, "s": 2151, "text": "Following is the query to select the date records between two dates −" }, { "code": null, "e": 2313, "s": 2221, "text": "mysql> select *from DemoTable681 where AdmissionDate between '2019-02-01' and '2019-12-01';" }, { "code": null, "e": 2354, "s": 2313, "text": "This will produce the following output −" }, { "code": null, "e": 2547, "s": 2354, "text": "+---------------------+\n| AdmissionDate |\n+---------------------+\n| 2019-11-01 00:00:00 |\n| 2019-07-03 00:00:00 |\n| 2019-02-04 00:00:00 |\n+---------------------+\n3 rows in set (0.00 sec)" } ]
ML | Extra Tree Classifier for Feature Selection - GeeksforGeeks
01 Jul, 2020 Prerequisites: Decision Tree Classifier Extremely Randomized Trees Classifier(Extra Trees Classifier) is a type of ensemble learning technique which aggregates the results of multiple de-correlated decision trees collected in a “forest” to output it’s classification result. In concept, it is very similar to a Random Forest Classifier and only differs from it in the manner of construction of the decision trees in the forest. Each Decision Tree in the Extra Trees Forest is constructed from the original training sample. Then, at each test node, Each tree is provided with a random sample of k features from the feature-set from which each decision tree must select the best feature to split the data based on some mathematical criteria (typically the Gini Index). This random sample of features leads to the creation of multiple de-correlated decision trees. To perform feature selection using the above forest structure, during the construction of the forest, for each feature, the normalized total reduction in the mathematical criteria used in the decision of feature of split (Gini Index if the Gini Index is used in the construction of the forest) is computed. This value is called the Gini Importance of the feature. To perform feature selection, each feature is ordered in descending order according to the Gini Importance of each feature and the user selects the top k features according to his/her choice. Consider the following data:- Let us build a hypothetical Extra Trees Forest for the above data with five decision trees and the value of k which decides the number of features in a random sample of features be two. Here the decision criteria used will be Information Gain. First, we calculate the entropy of the data. Note the formula for calculating the entropy is:- where c is the number of unique class labels and is the proportion of rows with output label is i. Therefore for the given data, the entropy is:- Let the decision trees be constructed such that:- 1st Decision Tree gets data with the features Outlook and Temperature:Note that the formula for Information Gain is:-Thus, Similarly: Note that the formula for Information Gain is:- Thus, Similarly: 2nd Decision Tree gets data with the features Temperature and Wind:Using the above-given formulas:- Using the above-given formulas:- strong>3rd Decision Tree gets data with the features Outlook and Humidity: 4th Decision Tree gets data with the features Temperature and Humidity: 5th Decision Tree gets data with the features Wind and Humidity: Computing total Info Gain for each feature:- Total Info Gain for Outlook = 0.246+0.246 = 0.492 Total Info Gain for Temperature = 0.029+0.029+0.029 = 0.087 Total Info Gain for Humidity = 0.151+0.151+0.151 = 0.453 Total Info Gain for Wind = 0.048+0.048 = 0.096 Thus the most important variable to determine the output label according to the above constructed Extra Trees Forest is the feature “Outlook”.The below given code will demonstrate how to do feature selection by using Extra Trees Classifiers.Step 1: Importing the required librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import ExtraTreesClassifierStep 2: Loading and Cleaning the Data# Changing the working location to the location of the filecd C:\Users\Dev\Desktop\Kaggle # Loading the datadf = pd.read_csv('data.csv') # Separating the dependent and independent variablesy = df['Play Tennis']X = df.drop('Play Tennis', axis = 1) X.head()Step 3: Building the Extra Trees Forest and computing the individual feature importances# Building the modelextra_tree_forest = ExtraTreesClassifier(n_estimators = 5, criterion ='entropy', max_features = 2) # Training the modelextra_tree_forest.fit(X, y) # Computing the importance of each featurefeature_importance = extra_tree_forest.feature_importances_ # Normalizing the individual importancesfeature_importance_normalized = np.std([tree.feature_importances_ for tree in extra_tree_forest.estimators_], axis = 0)Step 4: Visualizing and Comparing the results# Plotting a Bar Graph to compare the modelsplt.bar(X.columns, feature_importance_normalized)plt.xlabel('Feature Labels')plt.ylabel('Feature Importances')plt.title('Comparison of different Feature Importances')plt.show()Thus the above-given output validates our theory about feature selection using Extra Trees Classifier. The importance of features might have different values because of the random nature of feature samples.My Personal Notes arrow_drop_upSave Computing total Info Gain for each feature:- Total Info Gain for Outlook = 0.246+0.246 = 0.492 Total Info Gain for Temperature = 0.029+0.029+0.029 = 0.087 Total Info Gain for Humidity = 0.151+0.151+0.151 = 0.453 Total Info Gain for Wind = 0.048+0.048 = 0.096 Thus the most important variable to determine the output label according to the above constructed Extra Trees Forest is the feature “Outlook”. The below given code will demonstrate how to do feature selection by using Extra Trees Classifiers. Step 1: Importing the required libraries import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import ExtraTreesClassifier Step 2: Loading and Cleaning the Data # Changing the working location to the location of the filecd C:\Users\Dev\Desktop\Kaggle # Loading the datadf = pd.read_csv('data.csv') # Separating the dependent and independent variablesy = df['Play Tennis']X = df.drop('Play Tennis', axis = 1) X.head() Step 3: Building the Extra Trees Forest and computing the individual feature importances # Building the modelextra_tree_forest = ExtraTreesClassifier(n_estimators = 5, criterion ='entropy', max_features = 2) # Training the modelextra_tree_forest.fit(X, y) # Computing the importance of each featurefeature_importance = extra_tree_forest.feature_importances_ # Normalizing the individual importancesfeature_importance_normalized = np.std([tree.feature_importances_ for tree in extra_tree_forest.estimators_], axis = 0) Step 4: Visualizing and Comparing the results # Plotting a Bar Graph to compare the modelsplt.bar(X.columns, feature_importance_normalized)plt.xlabel('Feature Labels')plt.ylabel('Feature Importances')plt.title('Comparison of different Feature Importances')plt.show() Thus the above-given output validates our theory about feature selection using Extra Trees Classifier. The importance of features might have different values because of the random nature of feature samples. nidhi_biet Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree Python | Decision tree implementation Difference between Informed and Uninformed Search in AI Search Algorithms in AI Decision Tree Introduction with example Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 23883, "s": 23855, "text": "\n01 Jul, 2020" }, { "code": null, "e": 23923, "s": 23883, "text": "Prerequisites: Decision Tree Classifier" }, { "code": null, "e": 24311, "s": 23923, "text": "Extremely Randomized Trees Classifier(Extra Trees Classifier) is a type of ensemble learning technique which aggregates the results of multiple de-correlated decision trees collected in a “forest” to output it’s classification result. In concept, it is very similar to a Random Forest Classifier and only differs from it in the manner of construction of the decision trees in the forest." }, { "code": null, "e": 24745, "s": 24311, "text": "Each Decision Tree in the Extra Trees Forest is constructed from the original training sample. Then, at each test node, Each tree is provided with a random sample of k features from the feature-set from which each decision tree must select the best feature to split the data based on some mathematical criteria (typically the Gini Index). This random sample of features leads to the creation of multiple de-correlated decision trees." }, { "code": null, "e": 25301, "s": 24745, "text": "To perform feature selection using the above forest structure, during the construction of the forest, for each feature, the normalized total reduction in the mathematical criteria used in the decision of feature of split (Gini Index if the Gini Index is used in the construction of the forest) is computed. This value is called the Gini Importance of the feature. To perform feature selection, each feature is ordered in descending order according to the Gini Importance of each feature and the user selects the top k features according to his/her choice." }, { "code": null, "e": 25331, "s": 25301, "text": "Consider the following data:-" }, { "code": null, "e": 25670, "s": 25331, "text": "Let us build a hypothetical Extra Trees Forest for the above data with five decision trees and the value of k which decides the number of features in a random sample of features be two. Here the decision criteria used will be Information Gain. First, we calculate the entropy of the data. Note the formula for calculating the entropy is:-" }, { "code": null, "e": 25770, "s": 25670, "text": "where c is the number of unique class labels and is the proportion of rows with output label is i." }, { "code": null, "e": 25817, "s": 25770, "text": "Therefore for the given data, the entropy is:-" }, { "code": null, "e": 25867, "s": 25817, "text": "Let the decision trees be constructed such that:-" }, { "code": null, "e": 26004, "s": 25867, "text": "1st Decision Tree gets data with the features Outlook and Temperature:Note that the formula for Information Gain is:-Thus,\n\n\nSimilarly:\n" }, { "code": null, "e": 26052, "s": 26004, "text": "Note that the formula for Information Gain is:-" }, { "code": null, "e": 26058, "s": 26052, "text": "Thus," }, { "code": null, "e": 26073, "s": 26062, "text": "Similarly:" }, { "code": null, "e": 26178, "s": 26075, "text": "2nd Decision Tree gets data with the features Temperature and Wind:Using the above-given formulas:-\n\n\n" }, { "code": null, "e": 26211, "s": 26178, "text": "Using the above-given formulas:-" }, { "code": null, "e": 26293, "s": 26215, "text": "strong>3rd Decision Tree gets data with the features Outlook and Humidity:\n\n\n" }, { "code": null, "e": 26372, "s": 26297, "text": "4th Decision Tree gets data with the features Temperature and Humidity:\n\n\n" }, { "code": null, "e": 28570, "s": 26376, "text": "5th Decision Tree gets data with the features Wind and Humidity:\n\n\nComputing total Info Gain for each feature:-\nTotal Info Gain for Outlook = 0.246+0.246 = 0.492\n\nTotal Info Gain for Temperature = 0.029+0.029+0.029 = 0.087\n\nTotal Info Gain for Humidity = 0.151+0.151+0.151 = 0.453\n\nTotal Info Gain for Wind = 0.048+0.048 = 0.096 \n\nThus the most important variable to determine the output label according to the above constructed Extra Trees Forest is the feature “Outlook”.The below given code will demonstrate how to do feature selection by using Extra Trees Classifiers.Step 1: Importing the required librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import ExtraTreesClassifierStep 2: Loading and Cleaning the Data# Changing the working location to the location of the filecd C:\\Users\\Dev\\Desktop\\Kaggle # Loading the datadf = pd.read_csv('data.csv') # Separating the dependent and independent variablesy = df['Play Tennis']X = df.drop('Play Tennis', axis = 1) X.head()Step 3: Building the Extra Trees Forest and computing the individual feature importances# Building the modelextra_tree_forest = ExtraTreesClassifier(n_estimators = 5, criterion ='entropy', max_features = 2) # Training the modelextra_tree_forest.fit(X, y) # Computing the importance of each featurefeature_importance = extra_tree_forest.feature_importances_ # Normalizing the individual importancesfeature_importance_normalized = np.std([tree.feature_importances_ for tree in extra_tree_forest.estimators_], axis = 0)Step 4: Visualizing and Comparing the results# Plotting a Bar Graph to compare the modelsplt.bar(X.columns, feature_importance_normalized)plt.xlabel('Feature Labels')plt.ylabel('Feature Importances')plt.title('Comparison of different Feature Importances')plt.show()Thus the above-given output validates our theory about feature selection using Extra Trees Classifier. The importance of features might have different values because of the random nature of feature samples.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28619, "s": 28574, "text": "Computing total Info Gain for each feature:-" }, { "code": null, "e": 28866, "s": 28619, "text": "\nTotal Info Gain for Outlook = 0.246+0.246 = 0.492\n\nTotal Info Gain for Temperature = 0.029+0.029+0.029 = 0.087\n\nTotal Info Gain for Humidity = 0.151+0.151+0.151 = 0.453\n\nTotal Info Gain for Wind = 0.048+0.048 = 0.096 \n\n" }, { "code": null, "e": 29009, "s": 28866, "text": "Thus the most important variable to determine the output label according to the above constructed Extra Trees Forest is the feature “Outlook”." }, { "code": null, "e": 29109, "s": 29009, "text": "The below given code will demonstrate how to do feature selection by using Extra Trees Classifiers." }, { "code": null, "e": 29150, "s": 29109, "text": "Step 1: Importing the required libraries" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import ExtraTreesClassifier", "e": 29268, "s": 29150, "text": null }, { "code": null, "e": 29306, "s": 29268, "text": "Step 2: Loading and Cleaning the Data" }, { "code": "# Changing the working location to the location of the filecd C:\\Users\\Dev\\Desktop\\Kaggle # Loading the datadf = pd.read_csv('data.csv') # Separating the dependent and independent variablesy = df['Play Tennis']X = df.drop('Play Tennis', axis = 1) X.head()", "e": 29565, "s": 29306, "text": null }, { "code": null, "e": 29654, "s": 29565, "text": "Step 3: Building the Extra Trees Forest and computing the individual feature importances" }, { "code": "# Building the modelextra_tree_forest = ExtraTreesClassifier(n_estimators = 5, criterion ='entropy', max_features = 2) # Training the modelextra_tree_forest.fit(X, y) # Computing the importance of each featurefeature_importance = extra_tree_forest.feature_importances_ # Normalizing the individual importancesfeature_importance_normalized = np.std([tree.feature_importances_ for tree in extra_tree_forest.estimators_], axis = 0)", "e": 30204, "s": 29654, "text": null }, { "code": null, "e": 30250, "s": 30204, "text": "Step 4: Visualizing and Comparing the results" }, { "code": "# Plotting a Bar Graph to compare the modelsplt.bar(X.columns, feature_importance_normalized)plt.xlabel('Feature Labels')plt.ylabel('Feature Importances')plt.title('Comparison of different Feature Importances')plt.show()", "e": 30471, "s": 30250, "text": null }, { "code": null, "e": 30678, "s": 30471, "text": "Thus the above-given output validates our theory about feature selection using Extra Trees Classifier. The importance of features might have different values because of the random nature of feature samples." }, { "code": null, "e": 30689, "s": 30678, "text": "nidhi_biet" }, { "code": null, "e": 30706, "s": 30689, "text": "Machine Learning" }, { "code": null, "e": 30713, "s": 30706, "text": "Python" }, { "code": null, "e": 30730, "s": 30713, "text": "Machine Learning" }, { "code": null, "e": 30828, "s": 30730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30837, "s": 30828, "text": "Comments" }, { "code": null, "e": 30850, "s": 30837, "text": "Old Comments" }, { "code": null, "e": 30864, "s": 30850, "text": "Decision Tree" }, { "code": null, "e": 30902, "s": 30864, "text": "Python | Decision tree implementation" }, { "code": null, "e": 30958, "s": 30902, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 30982, "s": 30958, "text": "Search Algorithms in AI" }, { "code": null, "e": 31022, "s": 30982, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31050, "s": 31022, "text": "Read JSON file using Python" }, { "code": null, "e": 31100, "s": 31050, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31122, "s": 31100, "text": "Python map() function" } ]
What is deep copy? Explain with an example in Java.
Creating an exact copy of an existing object in the memory is known as cloning. The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it (clones). In order to use this method, you need to make sure that your class implements the Cloneable interface. Live Demo import java.util.Scanner; public class CloneExample implements Cloneable { private String name; private int age; public CloneExample(String name, int age){ this.name = name; this.age = age; } public void displayData(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); } public static void main(String[] args) throws CloneNotSupportedException { Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); CloneExample std = new CloneExample(name, age); System.out.println("Contents of the original object"); std.displayData(); System.out.println("Contents of the copied object"); CloneExample copiedStd = (CloneExample) std.clone(); copiedStd.displayData(); } } Enter your name Krishna Enter your age 20 Contents of the original object Name : Krishna Age : 20 Contents of the copied object Name : Krishna Age : 20 Whenever you try to create a copy of an object using the shallow copy, all fields of the original objects are copied exactly. But, if it contains any objects as fields then, only references to those objects are copied not the compete objects. This implies that, if you perform shallow copy on an object that contains any objects as fields, since only references are copied in a shallow copy, both the original and copied object points to the same reference internally and, if you do any changes to the data using the copied object, they are reflected in the original object too. Note − By default, the clone() method does a shallow copy. Whenever you try to create a copy of an object, in the deep copy all fields of the original objects are copied exactly, in addition to this, if it contains any objects as fields then copy of those is also created (using the clone() method). This implies that, if perform you deep copy on an object that contains reference (object), both the original and copied object refers to different objects and, if you do any changes to the data the copied object they are not reflected in the original object. Override the clone method and within it copy the reference fields using the clone() method as shown below − protected Object clone() throws CloneNotSupportedException{ StudentData student = (StudentData) super.clone(); student.contact = (Contact) contact.clone(); return student; } In the following example the StudentData class contains a String variable (name), an integer variable (age) and an object (Contact). In the main method we are creating an object of the StudentData class and copying it. From the copied object we are changing the data(field values) of the reference used (Contact object). Then, we are printing the data of copied object first followed by data of the original one. Since we have done a deep copy (by overriding the clone() method), you can observe that the change done is not reflected in the original object. Live Demo import java.util.Scanner; class Contact implements Cloneable{ private long phoneNo; private String email; private String address; public void setPhoneNo(long phoneNo) { this.phoneNo = phoneNo; } public void setEmail(String email) { this.email = email; } public void setAddress(String address) { this.address = address; } Contact(long phoneNo, String email, String address ){ this.phoneNo = phoneNo; this.email = email; this.address = address; } public void displayContact() { System.out.println("Phone no: "+this.phoneNo); System.out.println("Email: "+this.email); System.out.println("Address: "+this.address); } protected Object clone() throws CloneNotSupportedException{ return super.clone(); } } public class StudentData implements Cloneable { private String name; private int age; private Contact contact; public StudentData(String name, int age, Contact contact){ this.name = name; this.age = age; this.contact = contact; } public void displayData(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); contact.displayContact(); } protected Object clone() throws CloneNotSupportedException{ StudentData student = (StudentData) super.clone(); student.contact = (Contact) contact.clone(); return student; } public static void main(String[] args) throws CloneNotSupportedException { Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); System.out.println("#############Contact details#############"); System.out.println("Enter your phone number: "); long phoneNo = sc.nextLong(); System.out.println("Enter your Email ID: "); String email = sc.next(); System.out.println("Enter your address: "); String address = sc.next(); System.out.println(" "); //Creating an object of the class StudentData std = new StudentData(name, age, new Contact(phoneNo, email, address)); //Creating a clone of the above object StudentData copiedStd = (StudentData) std.clone(); //Modifying the data of the contact object copiedStd.contact.setPhoneNo(000000000); copiedStd.contact.setEmail("XXXXXXXXXX"); copiedStd.contact.setAddress("XXXXXXXXXX"); System.out.println("Contents of the copied object::"); copiedStd.displayData(); System.out.println(" "); System.out.println("Contents of the original object::"); std.displayData(); } } Enter your name Krishna Enter your age 20 #############Contact details############# Enter your phone number: 9848022338 Enter your Email ID: [email protected] Enter your address: Hyderabad Contents of the copied object:: Name : Krishna Age : 20 Phone no: 0 Email: XXXXXXXXXX Address: XXXXXXXXXX Contents of the original object:: Name : Krishna Age : 20 Phone no: 9848022338 Email: [email protected] Address: Hyderabad
[ { "code": null, "e": 1142, "s": 1062, "text": "Creating an exact copy of an existing object in the memory is known as cloning." }, { "code": null, "e": 1268, "s": 1142, "text": "The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it (clones)." }, { "code": null, "e": 1371, "s": 1268, "text": "In order to use this method, you need to make sure that your class implements the Cloneable interface." }, { "code": null, "e": 1382, "s": 1371, "text": " Live Demo" }, { "code": null, "e": 2293, "s": 1382, "text": "import java.util.Scanner;\npublic class CloneExample implements Cloneable {\n private String name;\n private int age;\n public CloneExample(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayData(){\n System.out.println(\"Name : \"+this.name);\n System.out.println(\"Age : \"+this.age);\n }\n public static void main(String[] args) throws CloneNotSupportedException {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter your name \");\n String name = sc.next();\n System.out.println(\"Enter your age \");\n int age = sc.nextInt();\n CloneExample std = new CloneExample(name, age);\n System.out.println(\"Contents of the original object\");\n std.displayData();\n System.out.println(\"Contents of the copied object\");\n CloneExample copiedStd = (CloneExample) std.clone();\n copiedStd.displayData();\n }\n}" }, { "code": null, "e": 2445, "s": 2293, "text": "Enter your name\nKrishna\nEnter your age\n20\nContents of the original object\nName : Krishna\nAge : 20\nContents of the copied object\nName : Krishna\nAge : 20" }, { "code": null, "e": 2688, "s": 2445, "text": "Whenever you try to create a copy of an object using the shallow copy, all fields of the original objects are copied exactly. But, if it contains any objects as fields then, only references to those objects are copied not the compete objects." }, { "code": null, "e": 3024, "s": 2688, "text": "This implies that, if you perform shallow copy on an object that contains any objects as fields, since only references are copied in a shallow copy, both the original and copied object points to the same reference internally and, if you do any changes to the data using the copied object, they are reflected in the original object too." }, { "code": null, "e": 3083, "s": 3024, "text": "Note − By default, the clone() method does a shallow copy." }, { "code": null, "e": 3324, "s": 3083, "text": "Whenever you try to create a copy of an object, in the deep copy all fields of the original objects are copied exactly, in addition to this, if it contains any objects as fields then copy of those is also created (using the clone() method)." }, { "code": null, "e": 3583, "s": 3324, "text": "This implies that, if perform you deep copy on an object that contains reference (object), both the original and copied object refers to different objects and, if you do any changes to the data the copied object they are not reflected in the original object." }, { "code": null, "e": 3691, "s": 3583, "text": "Override the clone method and within it copy the reference fields using the clone() method as shown below −" }, { "code": null, "e": 3874, "s": 3691, "text": "protected Object clone() throws CloneNotSupportedException{\n StudentData student = (StudentData) super.clone();\n student.contact = (Contact) contact.clone();\n return student;\n}" }, { "code": null, "e": 4007, "s": 3874, "text": "In the following example the StudentData class contains a String variable (name), an integer variable (age) and an object (Contact)." }, { "code": null, "e": 4287, "s": 4007, "text": "In the main method we are creating an object of the StudentData class and copying it. From the copied object we are changing the data(field values) of the reference used (Contact object). Then, we are printing the data of copied object first followed by data of the original one." }, { "code": null, "e": 4432, "s": 4287, "text": "Since we have done a deep copy (by overriding the clone() method), you can observe that the change done is not reflected in the original object." }, { "code": null, "e": 4443, "s": 4432, "text": " Live Demo" }, { "code": null, "e": 7143, "s": 4443, "text": "import java.util.Scanner;\nclass Contact implements Cloneable{\n private long phoneNo;\n private String email;\n private String address;\n public void setPhoneNo(long phoneNo) {\n this.phoneNo = phoneNo;\n }\n public void setEmail(String email) {\n this.email = email;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n Contact(long phoneNo, String email, String address ){\n this.phoneNo = phoneNo;\n this.email = email;\n this.address = address;\n }\n public void displayContact() {\n System.out.println(\"Phone no: \"+this.phoneNo);\n System.out.println(\"Email: \"+this.email);\n System.out.println(\"Address: \"+this.address);\n }\n protected Object clone() throws CloneNotSupportedException{\n return super.clone();\n }\n}\npublic class StudentData implements Cloneable {\n private String name;\n private int age;\n private Contact contact;\n public StudentData(String name, int age, Contact contact){\n this.name = name;\n this.age = age;\n this.contact = contact;\n }\n public void displayData(){\n System.out.println(\"Name : \"+this.name);\n System.out.println(\"Age : \"+this.age);\n contact.displayContact();\n }\n protected Object clone() throws CloneNotSupportedException{\n StudentData student = (StudentData) super.clone();\n student.contact = (Contact) contact.clone();\n return student;\n }\n public static void main(String[] args) throws CloneNotSupportedException {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter your name \");\n String name = sc.next();\n System.out.println(\"Enter your age \");\n int age = sc.nextInt();\n System.out.println(\"#############Contact details#############\");\n System.out.println(\"Enter your phone number: \");\n long phoneNo = sc.nextLong();\n System.out.println(\"Enter your Email ID: \");\n String email = sc.next();\n System.out.println(\"Enter your address: \");\n String address = sc.next();\n System.out.println(\" \");\n //Creating an object of the class\n StudentData std = new StudentData(name, age, new Contact(phoneNo, email, address));\n //Creating a clone of the above object\n StudentData copiedStd = (StudentData) std.clone();\n //Modifying the data of the contact object\n copiedStd.contact.setPhoneNo(000000000);\n copiedStd.contact.setEmail(\"XXXXXXXXXX\");\n copiedStd.contact.setAddress(\"XXXXXXXXXX\");\n System.out.println(\"Contents of the copied object::\");\n copiedStd.displayData();\n System.out.println(\" \");\n System.out.println(\"Contents of the original object::\");\n std.displayData();\n }\n}" }, { "code": null, "e": 7579, "s": 7143, "text": "Enter your name\nKrishna\nEnter your age\n20\n#############Contact details#############\nEnter your phone number:\n9848022338\nEnter your Email ID:\[email protected]\nEnter your address:\nHyderabad\n\nContents of the copied object::\nName : Krishna\nAge : 20\nPhone no: 0\nEmail: XXXXXXXXXX\nAddress: XXXXXXXXXX\n\nContents of the original object::\nName : Krishna\nAge : 20\nPhone no: 9848022338\nEmail: [email protected]\nAddress: Hyderabad" } ]
How to separate even and odd numbers in an array by using for loop in C language?
An array is a group of related data items that are stored with single name. For example, int student[30]; //student is an array name that holds 30 collection of data items with a single variable name Searching − It is used to find whether particular element is present or not Searching − It is used to find whether particular element is present or not Sorting − It helps in arranging the elements in an array either in ascending or descending order. Sorting − It helps in arranging the elements in an array either in ascending or descending order. Traversing − It processes every element in an array sequentially. Traversing − It processes every element in an array sequentially. Inserting − It helps in inserting the elements in an array. Inserting − It helps in inserting the elements in an array. Deleting − It helps in deleting an element in an array. Deleting − It helps in deleting an element in an array. The logic to find even numbers in an array is as follows − for(i = 0; i < size; i ++){ if(a[i] % 2 == 0){ even[Ecount] = a[i]; Ecount++; } } The logic to find odd numbers in an array is as follows − for(i = 0; i < size; i ++){ if(a[i] % 2 != 0){ odd[Ocount] = a[i]; Ocount++; } } To display even numbers, call display function as mentioned below − printf("no: of elements comes under even are = %d \n", Ecount); printf("The elements that are present in an even array is: "); void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("\n"); } To display odd numbers, call display function as given below − printf("no: of elements comes under odd are = %d \n", Ocount); printf("The elements that are present in an odd array is : "); void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("\n"); } Following is the C program to separate even and odd numbers in an array by using for loop − Live Demo #include<stdio.h> void display(int a[], int size); int main(){ int size, i, a[10], even[20], odd[20]; int Ecount = 0, Ocount = 0; printf("enter size of array :\n"); scanf("%d", &size); printf("enter array elements:\n"); for(i = 0; i < size; i++){ scanf("%d", &a[i]); } for(i = 0; i < size; i ++){ if(a[i] % 2 == 0){ even[Ecount] = a[i]; Ecount++; } else{ odd[Ocount] = a[i]; Ocount++; } } printf("no: of elements comes under even are = %d \n", Ecount); printf("The elements that are present in an even array is: "); display(even, Ecount); printf("no: of elements comes under odd are = %d \n", Ocount); printf("The elements that are present in an odd array is : "); display(odd, Ocount); return 0; } void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("\n"); } When the above program is executed, it produces the following result − enter size of array: 5 enter array elements: 23 45 67 12 34 no: of elements comes under even are = 2 The elements that are present in an even array is: 12 34 no: of elements comes under odd are = 3 The elements that are present in an odd array is : 23 45 67
[ { "code": null, "e": 1138, "s": 1062, "text": "An array is a group of related data items that are stored with single name." }, { "code": null, "e": 1262, "s": 1138, "text": "For example, int student[30]; //student is an array name that holds 30 collection of data items with a single variable name" }, { "code": null, "e": 1338, "s": 1262, "text": "Searching − It is used to find whether particular element is present or not" }, { "code": null, "e": 1414, "s": 1338, "text": "Searching − It is used to find whether particular element is present or not" }, { "code": null, "e": 1512, "s": 1414, "text": "Sorting − It helps in arranging the elements in an array either in ascending or descending order." }, { "code": null, "e": 1610, "s": 1512, "text": "Sorting − It helps in arranging the elements in an array either in ascending or descending order." }, { "code": null, "e": 1676, "s": 1610, "text": "Traversing − It processes every element in an array sequentially." }, { "code": null, "e": 1742, "s": 1676, "text": "Traversing − It processes every element in an array sequentially." }, { "code": null, "e": 1802, "s": 1742, "text": "Inserting − It helps in inserting the elements in an array." }, { "code": null, "e": 1862, "s": 1802, "text": "Inserting − It helps in inserting the elements in an array." }, { "code": null, "e": 1918, "s": 1862, "text": "Deleting − It helps in deleting an element in an array." }, { "code": null, "e": 1974, "s": 1918, "text": "Deleting − It helps in deleting an element in an array." }, { "code": null, "e": 2033, "s": 1974, "text": "The logic to find even numbers in an array is as follows −" }, { "code": null, "e": 2133, "s": 2033, "text": "for(i = 0; i < size; i ++){\n if(a[i] % 2 == 0){\n even[Ecount] = a[i];\n Ecount++;\n }\n}" }, { "code": null, "e": 2191, "s": 2133, "text": "The logic to find odd numbers in an array is as follows −" }, { "code": null, "e": 2290, "s": 2191, "text": "for(i = 0; i < size; i ++){\n if(a[i] % 2 != 0){\n odd[Ocount] = a[i];\n Ocount++;\n }\n}" }, { "code": null, "e": 2358, "s": 2290, "text": "To display even numbers, call display function as mentioned below −" }, { "code": null, "e": 2612, "s": 2358, "text": "printf(\"no: of elements comes under even are = %d \\n\", Ecount);\nprintf(\"The elements that are present in an even array is: \");\nvoid display(int a[], int size){\n int i;\n for(i = 0; i < size; i++){\n printf(\"%d \\t \", a[i]);\n }\n printf(\"\\n\");\n}" }, { "code": null, "e": 2675, "s": 2612, "text": "To display odd numbers, call display function as given below −" }, { "code": null, "e": 2928, "s": 2675, "text": "printf(\"no: of elements comes under odd are = %d \\n\", Ocount);\nprintf(\"The elements that are present in an odd array is : \");\nvoid display(int a[], int size){\n int i;\n for(i = 0; i < size; i++){\n printf(\"%d \\t \", a[i]);\n }\n printf(\"\\n\");\n}" }, { "code": null, "e": 3020, "s": 2928, "text": "Following is the C program to separate even and odd numbers in an array by using for loop −" }, { "code": null, "e": 3031, "s": 3020, "text": " Live Demo" }, { "code": null, "e": 3971, "s": 3031, "text": "#include<stdio.h>\nvoid display(int a[], int size);\nint main(){\n int size, i, a[10], even[20], odd[20];\n int Ecount = 0, Ocount = 0;\n printf(\"enter size of array :\\n\");\n scanf(\"%d\", &size);\n printf(\"enter array elements:\\n\");\n for(i = 0; i < size; i++){\n scanf(\"%d\", &a[i]);\n }\n for(i = 0; i < size; i ++){\n if(a[i] % 2 == 0){\n even[Ecount] = a[i];\n Ecount++;\n }\n else{\n odd[Ocount] = a[i];\n Ocount++;\n }\n }\n printf(\"no: of elements comes under even are = %d \\n\", Ecount);\n printf(\"The elements that are present in an even array is: \");\n display(even, Ecount);\n printf(\"no: of elements comes under odd are = %d \\n\", Ocount);\n printf(\"The elements that are present in an odd array is : \");\n display(odd, Ocount);\n return 0;\n}\nvoid display(int a[], int size){\n int i;\n for(i = 0; i < size; i++){\n printf(\"%d \\t \", a[i]);\n }\n printf(\"\\n\");\n}" }, { "code": null, "e": 4042, "s": 3971, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 4300, "s": 4042, "text": "enter size of array:\n5\nenter array elements:\n23\n45\n67\n12\n34\nno: of elements comes under even are = 2\nThe elements that are present in an even array is: 12 34\nno: of elements comes under odd are = 3\nThe elements that are present in an odd array is : 23 45 67" } ]
How to track football players using Yolo, SORT and Opencv. | by C K | Towards Data Science
In this post, I will show how I detect and track players using Yolov3, Opencv and SORT from video clip, and turn the detections to the bird’s-eye view as shown above. Inspired by Sam Blake’s great work (https://medium.com/hal24k-techblog/how-to-track-objects-in-the-real-world-with-tensorflow-sort-and-opencv-a64d9564ccb1), I will do the following steps for this project: Object Detection (Yolo and Opencv)Object Tracking (SORT)Perspective Transform (Opencv) Object Detection (Yolo and Opencv) Object Tracking (SORT) Perspective Transform (Opencv) In order to have a stable tracking and perspective transform, I need a video clip without camera moving around. I downloaded the video from IPL Ball Detection Datasets. Please be noted that the ball is not tracked in this project, it was already tracked (green bounding box) from the source. The first step is to load the video and detect the players. I used the pre-trained Yolov3 weight and used Opencv’s dnn module and only selected detections classified as ‘person’. I drew bounding boxes for detected players and their tails for previous ten frames. Looks like the pre-trained model is doing quite okay. Next I want to track the player and assign unique IDs to them. I used Alex Bewley’s SORT algorithm(simple online and realtime tracking), which I applied to my previous work. towardsdatascience.com Now each player has a unique ID assigned and displayed in the video. The video looks good now, but I still want to have players’ motion in bird’s-eye view. It can be done by doing perspective transform. There are a little bit math involved, fortunately Opencv’s getPerspectiveTransform function make it a lot easier. I need to find 4 fixed points as reference and identify the coordinations from the video and also from the bird’s-eye view image. First I identify 4 reference points from the video as show in in red spot and get the pixel coordinations. np.array([ [1, 47], # Upper left [878, 54], # Upper right [1019, 544], # Lower right [1, 546] # Lower left ]) I did not really see very solid reference points from the video so I roughly identified 4 points and marked these locations on the bird’s-eye view and got the corresponding pixel coordinations. It will be more precise if the reference points are more robust. np.array([ [871, 37], # Upper left [1490, 39], # Upper right [1458, 959], # Lower right [1061, 955] # Lower left ]) Then by applying Opencv’s getPerspectiveTransform using these reference points, we can transform the detections from video to bird’s-eye view. With player’s movement information, it is possible to do further analysis such as players’ running distance and velocity. The speed for running this player tracking is around 0.3 second per frame on my 2016 Macbook Pro Intel i5 CPU. It is possible to do this real time by using GPU for some applications if necessary. Thanks for reading, comments and suggestions are welcome! In my next post, I used OpenCV to identify players’s team based on their jersey color. Feel free to take a look!
[ { "code": null, "e": 338, "s": 171, "text": "In this post, I will show how I detect and track players using Yolov3, Opencv and SORT from video clip, and turn the detections to the bird’s-eye view as shown above." }, { "code": null, "e": 543, "s": 338, "text": "Inspired by Sam Blake’s great work (https://medium.com/hal24k-techblog/how-to-track-objects-in-the-real-world-with-tensorflow-sort-and-opencv-a64d9564ccb1), I will do the following steps for this project:" }, { "code": null, "e": 630, "s": 543, "text": "Object Detection (Yolo and Opencv)Object Tracking (SORT)Perspective Transform (Opencv)" }, { "code": null, "e": 665, "s": 630, "text": "Object Detection (Yolo and Opencv)" }, { "code": null, "e": 688, "s": 665, "text": "Object Tracking (SORT)" }, { "code": null, "e": 719, "s": 688, "text": "Perspective Transform (Opencv)" }, { "code": null, "e": 1011, "s": 719, "text": "In order to have a stable tracking and perspective transform, I need a video clip without camera moving around. I downloaded the video from IPL Ball Detection Datasets. Please be noted that the ball is not tracked in this project, it was already tracked (green bounding box) from the source." }, { "code": null, "e": 1071, "s": 1011, "text": "The first step is to load the video and detect the players." }, { "code": null, "e": 1190, "s": 1071, "text": "I used the pre-trained Yolov3 weight and used Opencv’s dnn module and only selected detections classified as ‘person’." }, { "code": null, "e": 1274, "s": 1190, "text": "I drew bounding boxes for detected players and their tails for previous ten frames." }, { "code": null, "e": 1328, "s": 1274, "text": "Looks like the pre-trained model is doing quite okay." }, { "code": null, "e": 1502, "s": 1328, "text": "Next I want to track the player and assign unique IDs to them. I used Alex Bewley’s SORT algorithm(simple online and realtime tracking), which I applied to my previous work." }, { "code": null, "e": 1525, "s": 1502, "text": "towardsdatascience.com" }, { "code": null, "e": 1594, "s": 1525, "text": "Now each player has a unique ID assigned and displayed in the video." }, { "code": null, "e": 1842, "s": 1594, "text": "The video looks good now, but I still want to have players’ motion in bird’s-eye view. It can be done by doing perspective transform. There are a little bit math involved, fortunately Opencv’s getPerspectiveTransform function make it a lot easier." }, { "code": null, "e": 1972, "s": 1842, "text": "I need to find 4 fixed points as reference and identify the coordinations from the video and also from the bird’s-eye view image." }, { "code": null, "e": 2079, "s": 1972, "text": "First I identify 4 reference points from the video as show in in red spot and get the pixel coordinations." }, { "code": null, "e": 2251, "s": 2079, "text": "np.array([ [1, 47], # Upper left [878, 54], # Upper right [1019, 544], # Lower right [1, 546] # Lower left ])" }, { "code": null, "e": 2510, "s": 2251, "text": "I did not really see very solid reference points from the video so I roughly identified 4 points and marked these locations on the bird’s-eye view and got the corresponding pixel coordinations. It will be more precise if the reference points are more robust." }, { "code": null, "e": 2688, "s": 2510, "text": "np.array([ [871, 37], # Upper left [1490, 39], # Upper right [1458, 959], # Lower right [1061, 955] # Lower left ])" }, { "code": null, "e": 2831, "s": 2688, "text": "Then by applying Opencv’s getPerspectiveTransform using these reference points, we can transform the detections from video to bird’s-eye view." }, { "code": null, "e": 2953, "s": 2831, "text": "With player’s movement information, it is possible to do further analysis such as players’ running distance and velocity." }, { "code": null, "e": 3149, "s": 2953, "text": "The speed for running this player tracking is around 0.3 second per frame on my 2016 Macbook Pro Intel i5 CPU. It is possible to do this real time by using GPU for some applications if necessary." }, { "code": null, "e": 3207, "s": 3149, "text": "Thanks for reading, comments and suggestions are welcome!" } ]
Visualizing Colors in Images Using Histogram in Python - GeeksforGeeks
18 Jan, 2022 In this article, we will discuss how to visualize colors in an image using histogram in Python. An image consists of various colors and we know that any color is a combination of Red, Green, Blue. So Image consists of Red, Green, Blue colors. So using Histogram we can visualize how much proportion we are having RGB colors in a picture. Histogram actually provides how frequently various colors occur in an image but not the location of color in an image. To visualize colors in the image we need to follow the below steps- To this Concept mainly we need 2 modules. cv2– It is used to load the image and get the RGB data from the image. matplotlib– Used to plot the histograms. To load an image we need to use imread() method which is in the cv2 module. It accepts the image name as a parameter. Syntax : cv2.imread(‘imageName’) To get the RGB colors from the image, the cv2 module provides calchist method that accepts the image object, channel to get a specific color, mask, histogram size, and range. Syntax: cv2.calchist([imageObject], [channelValue], mask, [histSize], [low,high]) imageObject- Variable name in which image is loaded. channelValue- It accepts 0,1,2 values. It helps us to get the required color. 0 indicates blue, 1 indicates red, 2 indicates green. matplotlib provides the hist method which is used to draw the histogram on specified data. Syntax: matplotlib.hist(data,color=”value”) Example: As per the above steps, First imported the required modules, and next we loaded an image using imread() method and using calcHist() method to get the RGB colors from Image and then plot the Histograms using the RGB data. Python3 # import necessary packagesimport cv2import matplotlib.pyplot as plt # load imageimageObj = cv2.imread('SampleGFG.jpg')# to avoid grid linesplt.axis("off")plt.title("Original Image")plt.imshow(cv2.cvtColor(imageObj, cv2.COLOR_BGR2RGB))plt.show() # Get RGB data from imageblue_color = cv2.calcHist([imageObj], [0], None, [256], [0, 256])red_color = cv2.calcHist([imageObj], [1], None, [256], [0, 256])green_color = cv2.calcHist([imageObj], [2], None, [256], [0, 256]) # Separate Histograms for each colorplt.subplot(3, 1, 1)plt.title("histogram of Blue")plt.hist(blue_color, color="blue") plt.subplot(3, 1, 2)plt.title("histogram of Green")plt.hist(green_color, color="green") plt.subplot(3, 1, 3)plt.title("histogram of Red")plt.hist(red_color, color="red") # for clear viewplt.tight_layout()plt.show() # combined histogramplt.title("Histogram of all RGB Colors")plt.hist(blue_color, color="blue")plt.hist(green_color, color="green")plt.hist(red_color, color="red")plt.show() Output sweetyty varshagumber28 Data Visualization Picked Python-matplotlib Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n18 Jan, 2022" }, { "code": null, "e": 23997, "s": 23901, "text": "In this article, we will discuss how to visualize colors in an image using histogram in Python." }, { "code": null, "e": 24239, "s": 23997, "text": "An image consists of various colors and we know that any color is a combination of Red, Green, Blue. So Image consists of Red, Green, Blue colors. So using Histogram we can visualize how much proportion we are having RGB colors in a picture." }, { "code": null, "e": 24426, "s": 24239, "text": "Histogram actually provides how frequently various colors occur in an image but not the location of color in an image. To visualize colors in the image we need to follow the below steps-" }, { "code": null, "e": 24468, "s": 24426, "text": "To this Concept mainly we need 2 modules." }, { "code": null, "e": 24539, "s": 24468, "text": "cv2– It is used to load the image and get the RGB data from the image." }, { "code": null, "e": 24580, "s": 24539, "text": "matplotlib– Used to plot the histograms." }, { "code": null, "e": 24698, "s": 24580, "text": "To load an image we need to use imread() method which is in the cv2 module. It accepts the image name as a parameter." }, { "code": null, "e": 24707, "s": 24698, "text": "Syntax :" }, { "code": null, "e": 24731, "s": 24707, "text": "cv2.imread(‘imageName’)" }, { "code": null, "e": 24906, "s": 24731, "text": "To get the RGB colors from the image, the cv2 module provides calchist method that accepts the image object, channel to get a specific color, mask, histogram size, and range." }, { "code": null, "e": 24914, "s": 24906, "text": "Syntax:" }, { "code": null, "e": 24988, "s": 24914, "text": "cv2.calchist([imageObject], [channelValue], mask, [histSize], [low,high])" }, { "code": null, "e": 25041, "s": 24988, "text": "imageObject- Variable name in which image is loaded." }, { "code": null, "e": 25119, "s": 25041, "text": "channelValue- It accepts 0,1,2 values. It helps us to get the required color." }, { "code": null, "e": 25173, "s": 25119, "text": "0 indicates blue, 1 indicates red, 2 indicates green." }, { "code": null, "e": 25264, "s": 25173, "text": "matplotlib provides the hist method which is used to draw the histogram on specified data." }, { "code": null, "e": 25272, "s": 25264, "text": "Syntax:" }, { "code": null, "e": 25308, "s": 25272, "text": "matplotlib.hist(data,color=”value”)" }, { "code": null, "e": 25317, "s": 25308, "text": "Example:" }, { "code": null, "e": 25538, "s": 25317, "text": "As per the above steps, First imported the required modules, and next we loaded an image using imread() method and using calcHist() method to get the RGB colors from Image and then plot the Histograms using the RGB data." }, { "code": null, "e": 25546, "s": 25538, "text": "Python3" }, { "code": "# import necessary packagesimport cv2import matplotlib.pyplot as plt # load imageimageObj = cv2.imread('SampleGFG.jpg')# to avoid grid linesplt.axis(\"off\")plt.title(\"Original Image\")plt.imshow(cv2.cvtColor(imageObj, cv2.COLOR_BGR2RGB))plt.show() # Get RGB data from imageblue_color = cv2.calcHist([imageObj], [0], None, [256], [0, 256])red_color = cv2.calcHist([imageObj], [1], None, [256], [0, 256])green_color = cv2.calcHist([imageObj], [2], None, [256], [0, 256]) # Separate Histograms for each colorplt.subplot(3, 1, 1)plt.title(\"histogram of Blue\")plt.hist(blue_color, color=\"blue\") plt.subplot(3, 1, 2)plt.title(\"histogram of Green\")plt.hist(green_color, color=\"green\") plt.subplot(3, 1, 3)plt.title(\"histogram of Red\")plt.hist(red_color, color=\"red\") # for clear viewplt.tight_layout()plt.show() # combined histogramplt.title(\"Histogram of all RGB Colors\")plt.hist(blue_color, color=\"blue\")plt.hist(green_color, color=\"green\")plt.hist(red_color, color=\"red\")plt.show()", "e": 26522, "s": 25546, "text": null }, { "code": null, "e": 26529, "s": 26522, "text": "Output" }, { "code": null, "e": 26538, "s": 26529, "text": "sweetyty" }, { "code": null, "e": 26553, "s": 26538, "text": "varshagumber28" }, { "code": null, "e": 26572, "s": 26553, "text": "Data Visualization" }, { "code": null, "e": 26579, "s": 26572, "text": "Picked" }, { "code": null, "e": 26597, "s": 26579, "text": "Python-matplotlib" }, { "code": null, "e": 26611, "s": 26597, "text": "Python-OpenCV" }, { "code": null, "e": 26618, "s": 26611, "text": "Python" }, { "code": null, "e": 26716, "s": 26618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26725, "s": 26716, "text": "Comments" }, { "code": null, "e": 26738, "s": 26725, "text": "Old Comments" }, { "code": null, "e": 26770, "s": 26738, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26826, "s": 26770, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26868, "s": 26826, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26910, "s": 26868, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26946, "s": 26910, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26968, "s": 26946, "text": "Defaultdict in Python" }, { "code": null, "e": 27007, "s": 26968, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27034, "s": 27007, "text": "Python Classes and Objects" }, { "code": null, "e": 27065, "s": 27034, "text": "Python | os.path.join() method" } ]
Multi-Line printing in Python
We have usually seen the print command in python printing one line of output. But if we have multiple lines to print, then in this approach multiple print commands need to be written. This can be avoided by using another technique involving the three single quotes as seen below. Live Demo print(''' Motivational Quote :\n Sometimes later becomes never, Do it now. Great things never come from comfort zones. The harder you work for something, the greater you'll feel when you achieve it. ''') Running the above code gives us the following result: Motivational Quote : Sometimes later becomes never, Do it now. Great things never come from comfort zones. The harder you work for something, the greater you'll feel when you achieve it. We can use multiline printing to produce nicely formatted text also as seen below. print(''' =========================================== || || || WORK || || HARD || || || || || || || =========================================== ''') Running the above code gives us the following result: ============================= || || || WORK || || HARD || || || || || || || =============================
[ { "code": null, "e": 1342, "s": 1062, "text": "We have usually seen the print command in python printing one line of output. But if we have multiple lines to print, then in this approach multiple print commands need to be written. This can be avoided by using another technique involving the three single quotes as seen below." }, { "code": null, "e": 1353, "s": 1342, "text": " Live Demo" }, { "code": null, "e": 1558, "s": 1353, "text": "print('''\nMotivational Quote :\\n\nSometimes later becomes never, Do it now.\nGreat things never come from comfort zones.\nThe harder you work for something, the greater you'll feel when you achieve it.\n''')\n" }, { "code": null, "e": 1612, "s": 1558, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 1800, "s": 1612, "text": "Motivational Quote :\n\nSometimes later becomes never, Do it now.\nGreat things never come from comfort zones.\nThe harder you work for something, the greater you'll feel when you achieve it." }, { "code": null, "e": 1883, "s": 1800, "text": "We can use multiline printing to produce nicely formatted text also as seen below." }, { "code": null, "e": 2251, "s": 1883, "text": "print('''\n===========================================\n|| ||\n|| WORK ||\n|| HARD ||\n|| ||\n|| ||\n|| ||\n===========================================\n''')\n" }, { "code": null, "e": 2305, "s": 2251, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2545, "s": 2305, "text": "=============================\n|| ||\n|| WORK ||\n|| HARD ||\n|| ||\n|| ||\n|| ||\n=============================" } ]
MongoDB query to group by _id
To group by _id in MongoDB, use $group. Let us create a collection with documents − > db.demo529.insertOne({"Score":10});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d5bef4dcbee04fbbbe4") } > db.demo529.insertOne({"Score":20});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d5fef4dcbee04fbbbe5") } > db.demo529.insertOne({"Score":10});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d61ef4dcbee04fbbbe6") } > db.demo529.insertOne({"Score":10});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b1d62ef4dcbee04fbbbe7") } Display all documents from a collection with the help of find() method − > db.demo529.find(); This will produce the following output − { "_id" : ObjectId("5e8b1d5bef4dcbee04fbbbe4"), "Score" : 10 } { "_id" : ObjectId("5e8b1d5fef4dcbee04fbbbe5"), "Score" : 20 } { "_id" : ObjectId("5e8b1d61ef4dcbee04fbbbe6"), "Score" : 10 } { "_id" : ObjectId("5e8b1d62ef4dcbee04fbbbe7"), "Score" : 10 } Following is the query to group by _id − > db.demo529.aggregate( [ ... { ... $group: { ... _id: null, ... count: { $sum: 1 } ... } ... } ... ] ) This will produce the following output − { "_id" : null, "count" : 4 }
[ { "code": null, "e": 1146, "s": 1062, "text": "To group by _id in MongoDB, use $group. Let us create a collection with documents −" }, { "code": null, "e": 1634, "s": 1146, "text": "> db.demo529.insertOne({\"Score\":10});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8b1d5bef4dcbee04fbbbe4\")\n}\n> db.demo529.insertOne({\"Score\":20});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8b1d5fef4dcbee04fbbbe5\")\n}\n> db.demo529.insertOne({\"Score\":10});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8b1d61ef4dcbee04fbbbe6\")\n}\n> db.demo529.insertOne({\"Score\":10});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8b1d62ef4dcbee04fbbbe7\")\n}" }, { "code": null, "e": 1707, "s": 1634, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1728, "s": 1707, "text": "> db.demo529.find();" }, { "code": null, "e": 1769, "s": 1728, "text": "This will produce the following output −" }, { "code": null, "e": 2021, "s": 1769, "text": "{ \"_id\" : ObjectId(\"5e8b1d5bef4dcbee04fbbbe4\"), \"Score\" : 10 }\n{ \"_id\" : ObjectId(\"5e8b1d5fef4dcbee04fbbbe5\"), \"Score\" : 20 }\n{ \"_id\" : ObjectId(\"5e8b1d61ef4dcbee04fbbbe6\"), \"Score\" : 10 }\n{ \"_id\" : ObjectId(\"5e8b1d62ef4dcbee04fbbbe7\"), \"Score\" : 10 }" }, { "code": null, "e": 2062, "s": 2021, "text": "Following is the query to group by _id −" }, { "code": null, "e": 2184, "s": 2062, "text": "> db.demo529.aggregate( [\n... {\n... $group: {\n... _id: null,\n... count: { $sum: 1 }\n... }\n... }\n... ] )" }, { "code": null, "e": 2225, "s": 2184, "text": "This will produce the following output −" }, { "code": null, "e": 2255, "s": 2225, "text": "{ \"_id\" : null, \"count\" : 4 }" } ]
C# program to list the difference between two lists
To get the difference between two lists, firstly set two lists in C# − // first list List < string > list1 = new List < string > (); list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D"); // second list List < string > list2 = new List < string > (); list2.Add("C"); list2.Add("D"); foreach(string value in list2) { Console.WriteLine(value); } To get the difference, use IEnumerable and Except() as shown below. The difference is shown in the third list − IEnumerable < string > list3; list3 = list1.Except(list2); The following is the complete code − Live Demo using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main() { List < string > list1 = new List < string > (); list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D"); Console.WriteLine("First list..."); foreach(string value in list1) { Console.WriteLine(value); } Console.WriteLine("Second list..."); List < string > list2 = new List < string > (); list2.Add("C"); list2.Add("D"); foreach(string value in list2) { Console.WriteLine(value); } Console.WriteLine("Difference in the two lists..."); IEnumerable < string > list3; list3 = list1.Except(list2); foreach(string value in list3) { Console.WriteLine(value); } } } First list... A B C D Second list... C D Difference in the two lists... A B
[ { "code": null, "e": 1133, "s": 1062, "text": "To get the difference between two lists, firstly set two lists in C# −" }, { "code": null, "e": 1419, "s": 1133, "text": "// first list\nList < string > list1 = new List < string > ();\nlist1.Add(\"A\");\nlist1.Add(\"B\");\nlist1.Add(\"C\");\nlist1.Add(\"D\");\n\n// second list\nList < string > list2 = new List < string > ();\nlist2.Add(\"C\");\nlist2.Add(\"D\");\nforeach(string value in list2) {\n Console.WriteLine(value);\n}" }, { "code": null, "e": 1531, "s": 1419, "text": "To get the difference, use IEnumerable and Except() as shown below. The difference is shown in the third list −" }, { "code": null, "e": 1590, "s": 1531, "text": "IEnumerable < string > list3;\nlist3 = list1.Except(list2);" }, { "code": null, "e": 1627, "s": 1590, "text": "The following is the complete code −" }, { "code": null, "e": 1638, "s": 1627, "text": " Live Demo" }, { "code": null, "e": 2470, "s": 1638, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Demo {\n public static void Main() {\n List < string > list1 = new List < string > ();\n list1.Add(\"A\");\n list1.Add(\"B\");\n list1.Add(\"C\");\n list1.Add(\"D\");\n\n Console.WriteLine(\"First list...\");\n foreach(string value in list1) {\n Console.WriteLine(value);\n }\n\n Console.WriteLine(\"Second list...\");\n List < string > list2 = new List < string > ();\n\n list2.Add(\"C\");\n list2.Add(\"D\");\n foreach(string value in list2) {\n Console.WriteLine(value);\n }\n\n Console.WriteLine(\"Difference in the two lists...\");\n IEnumerable < string > list3;\n list3 = list1.Except(list2);\n foreach(string value in list3) {\n Console.WriteLine(value);\n }\n\n }\n}" }, { "code": null, "e": 2546, "s": 2470, "text": "First list...\nA\nB\nC\nD\nSecond list...\nC\nD\nDifference in the two lists...\nA\nB" } ]
How to set the left position of a positioned element with JavaScript?
Use the left property to set the left position of a positioned element, such as a button. You can try to run the following code to set the left position of a positioned element with JavaScript − Live Demo <!DOCTYPE html> <html> <head> <style> #myID { position: absolute; } </style> </head> <body> <h1>Heading 1</h1> <p>This is Demo Text.</p> <button type="button" id="myID" onclick="display()">Change Left Position</button> <script> function display() { document.getElementById("myID").style.left = "150px"; } </script> </body> </html>
[ { "code": null, "e": 1152, "s": 1062, "text": "Use the left property to set the left position of a positioned element, such as a button." }, { "code": null, "e": 1257, "s": 1152, "text": "You can try to run the following code to set the left position of a positioned element with JavaScript −" }, { "code": null, "e": 1267, "s": 1257, "text": "Live Demo" }, { "code": null, "e": 1712, "s": 1267, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #myID {\n position: absolute;\n }\n </style>\n </head>\n <body>\n <h1>Heading 1</h1>\n <p>This is Demo Text.</p>\n <button type=\"button\" id=\"myID\" onclick=\"display()\">Change Left Position</button>\n <script>\n function display() {\n document.getElementById(\"myID\").style.left = \"150px\";\n }\n </script>\n </body>\n</html>" } ]
strcat() function in C/C++ with Example - GeeksforGeeks
14 Oct, 2021 In C/C++, strcat() is a predefined function used for string handling, under string library (string.h in C, and cstring in C++). This function appends the string pointed to by src to the end of the string pointed to by dest. It will append a copy of the source string in the destination string. plus a terminating Null character. The initial character of the string(src) overwrites the Null-character present at the end of the string(dest). The behavior is undefined if: the destination array is not large enough for the contents of both src and dest and the terminating null character if the string overlaps. if either dest or src is not a pointer to a null-terminated byte string. Syntax: char *strcat(char *dest, const char *src) Parameters: The method accepts the following parameters: dest: This is a pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string. src: This is the string to be appended. This should not overlap the destination. Return value: The strcat() function returns dest, the pointer to the destination string. Application: Given two strings src and dest in C++, we need to append string pointed by src to the end of the string pointed by dest. Examples: Input: src = "ForGeeks" dest = "Geeks" Output: "GeeksForGeeks" Input: src = "World" dest = "Hello " Output: "Hello World" Below is the C program to implement the above approach: C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(int argc, const char* argv[]){ // Define a temporary variable char example[100]; // Copy the first string into // the variable strcpy(example, "Geeks"); // Concatenate this string // to the end of the first one strcat(example, "ForGeeks"); // Display the concatenated strings printf("%s\n", example); return 0;} GeeksForGeeks Note: The target string should be made big enough to hold the final string. C-Functions C-String CPP-Functions cpp-strings-library TrueGeek-2021 C Language C++ TrueGeek CPP 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 Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 23841, "s": 23813, "text": "\n14 Oct, 2021" }, { "code": null, "e": 23969, "s": 23841, "text": "In C/C++, strcat() is a predefined function used for string handling, under string library (string.h in C, and cstring in C++)." }, { "code": null, "e": 24281, "s": 23969, "text": "This function appends the string pointed to by src to the end of the string pointed to by dest. It will append a copy of the source string in the destination string. plus a terminating Null character. The initial character of the string(src) overwrites the Null-character present at the end of the string(dest)." }, { "code": null, "e": 24311, "s": 24281, "text": "The behavior is undefined if:" }, { "code": null, "e": 24426, "s": 24311, "text": "the destination array is not large enough for the contents of both src and dest and the terminating null character" }, { "code": null, "e": 24450, "s": 24426, "text": "if the string overlaps." }, { "code": null, "e": 24523, "s": 24450, "text": "if either dest or src is not a pointer to a null-terminated byte string." }, { "code": null, "e": 24531, "s": 24523, "text": "Syntax:" }, { "code": null, "e": 24573, "s": 24531, "text": "char *strcat(char *dest, const char *src)" }, { "code": null, "e": 24630, "s": 24573, "text": "Parameters: The method accepts the following parameters:" }, { "code": null, "e": 24786, "s": 24630, "text": "dest: This is a pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string." }, { "code": null, "e": 24867, "s": 24786, "text": "src: This is the string to be appended. This should not overlap the destination." }, { "code": null, "e": 24956, "s": 24867, "text": "Return value: The strcat() function returns dest, the pointer to the destination string." }, { "code": null, "e": 25090, "s": 24956, "text": "Application: Given two strings src and dest in C++, we need to append string pointed by src to the end of the string pointed by dest." }, { "code": null, "e": 25100, "s": 25090, "text": "Examples:" }, { "code": null, "e": 25237, "s": 25100, "text": "Input: src = \"ForGeeks\"\n dest = \"Geeks\"\nOutput: \"GeeksForGeeks\"\n\nInput: src = \"World\"\n dest = \"Hello \"\nOutput: \"Hello World\"" }, { "code": null, "e": 25293, "s": 25237, "text": "Below is the C program to implement the above approach:" }, { "code": null, "e": 25295, "s": 25293, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(int argc, const char* argv[]){ // Define a temporary variable char example[100]; // Copy the first string into // the variable strcpy(example, \"Geeks\"); // Concatenate this string // to the end of the first one strcat(example, \"ForGeeks\"); // Display the concatenated strings printf(\"%s\\n\", example); return 0;}", "e": 25764, "s": 25295, "text": null }, { "code": null, "e": 25779, "s": 25764, "text": "GeeksForGeeks\n" }, { "code": null, "e": 25855, "s": 25779, "text": "Note: The target string should be made big enough to hold the final string." }, { "code": null, "e": 25867, "s": 25855, "text": "C-Functions" }, { "code": null, "e": 25876, "s": 25867, "text": "C-String" }, { "code": null, "e": 25890, "s": 25876, "text": "CPP-Functions" }, { "code": null, "e": 25910, "s": 25890, "text": "cpp-strings-library" }, { "code": null, "e": 25924, "s": 25910, "text": "TrueGeek-2021" }, { "code": null, "e": 25935, "s": 25924, "text": "C Language" }, { "code": null, "e": 25939, "s": 25935, "text": "C++" }, { "code": null, "e": 25948, "s": 25939, "text": "TrueGeek" }, { "code": null, "e": 25952, "s": 25948, "text": "CPP" }, { "code": null, "e": 26050, "s": 25952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26059, "s": 26050, "text": "Comments" }, { "code": null, "e": 26072, "s": 26059, "text": "Old Comments" }, { "code": null, "e": 26110, "s": 26072, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26136, "s": 26110, "text": "Exception Handling in C++" }, { "code": null, "e": 26156, "s": 26136, "text": "Multithreading in C" }, { "code": null, "e": 26197, "s": 26156, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26219, "s": 26197, "text": "'this' pointer in C++" }, { "code": null, "e": 26237, "s": 26219, "text": "Vector in C++ STL" }, { "code": null, "e": 26283, "s": 26237, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26326, "s": 26283, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26345, "s": 26326, "text": "Inheritance in C++" } ]
A gentle introduction to Apache Arrow with Apache Spark and Pandas | by Antonio Cachuan | Towards Data Science
This time I am going to try to explain how can we use Apache Arrow in conjunction with Apache Spark and Python. First, let me share some basic concepts about this open source project. Apache Arrow is a cross-language development platform for in-memory data. It specifies a standardized language-independent columnar memory format for flat and hierarchical data, organized for efficient analytic operations on modern hardware. [Apache Arrow page] In simple words, It facilitates communication between many components, for example, reading a parquet file with Python (pandas) and transforming to a Spark dataframe, Falcon Data Visualization or Cassandra without worrying about conversion. A good question is to ask how does the data look like in memory? Well, Apache Arrow takes advantage of a columnar buffer to reduce IO and accelerate analytical processing performance. In our case, we will use the pyarrow library to execute some basic codes and check some features. In order to install, we have two options using conda or pip commands*. conda install -c conda-forge pyarrowpip install pyarrow *It’s recommended to use conda in a Python 3 environment. Apache Arrow with Pandas (Local File System) Converting Pandas Dataframe to Apache Arrow Table import numpy as npimport pandas as pdimport pyarrow as padf = pd.DataFrame({'one': [20, np.nan, 2.5],'two': ['january', 'february', 'march'],'three': [True, False, True]},index=list('abc'))table = pa.Table.from_pandas(df) Pyarrow Table to Pandas Data Frame df_new = table.to_pandas() Read CSV from pyarrow import csvfn = ‘data/demo.csv’table = csv.read_csv(fn)df = table.to_pandas() Writing a parquet file from Apache Arrow import pyarrow.parquet as pqpq.write_table(table, 'example.parquet') Reading a parquet file table2 = pq.read_table(‘example.parquet’)table2 Reading some columns from a parquet file table2 = pq.read_table('example.parquet', columns=['one', 'three']) Reading from Partitioned Datasets dataset = pq.ParquetDataset(‘dataset_name_directory/’)table = dataset.read()table Transforming Parquet file into a Pandas DataFrame pdf = pq.read_pandas('example.parquet', columns=['two']).to_pandas()pdf Avoiding pandas index table = pa.Table.from_pandas(df, preserve_index=False)pq.write_table(table, 'example_noindex.parquet')t = pq.read_table('example_noindex.parquet')t.to_pandas() Check metadata parquet_file = pq.ParquetFile(‘example.parquet’)parquet_file.metadata See data schema parquet_file.schema Timestamp Remember Pandas use nanoseconds so you can truncate in milliseconds for compatibility. pq.write_table(table, where, coerce_timestamps='ms')pq.write_table(table, where, coerce_timestamps='ms', allow_truncated_timestamps=True) Compression By default, Apache arrow uses snappy compression (not so compressed but easier access), although other codecs are allowed. pq.write_table(table, where, compression='snappy')pq.write_table(table, where, compression='gzip')pq.write_table(table, where, compression='brotli')pq.write_table(table, where, compression='none') Also, It’s possible to use more than one compression in a table pq.write_table(table, ‘example_diffcompr.parquet’, compression={b’one’: ‘snappy’, b’two’: ‘gzip’}) Write a partitioned Parquet table df = pd.DataFrame({‘one’: [1, 2.5, 3], ‘two’: [‘Peru’, ‘Brasil’, ‘Canada’], ‘three’: [True, False, True]}, index=list(‘abc’))table = pa.Table.from_pandas(df)pq.write_to_dataset(table, root_path=’dataset_name’,partition_cols=[‘one’, ‘two’]) Compatibility note: if you are using pq.write_to_dataset to create a table that will then be used by HIVE then partition column values must be compatible with the allowed character set of the HIVE version you are running. Apache Arrow with HDFS (Remote file-system) Apache Arrow comes with bindings to a C++-based interface to the Hadoop File System. It means that we can read or download all files from HDFS and interpret directly with Python. Connection Host is the namenode, port is usually RPC or WEBHDFS more parameters like user, kerberos ticket are allow. It’s strongly recommended to read about the environmental variables needed. import pyarrow as pahost = '1970.x.x.x'port = 8022fs = pa.hdfs.connect(host, port) Optional if your connection is made front a data or edge node is possible to use just fs = pa.hdfs.connect() Write Parquet files to HDFS pq.write_to_dataset(table, root_path=’dataset_name’, partition_cols=[‘one’, ‘two’], filesystem=fs) Read CSV from HDFS import pandas as pdfrom pyarrow import csvimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘iris.csv’, ‘rb’) as f: df = pd.read_csv(f, nrows = 10)df.head() Read Parquet File from HDFS There is two forms to read a parquet file from HDFS Using pandas and Pyarrow engine import pandas as pdpdIris = pd.read_parquet(‘hdfs:///iris/part-00000–27c8e2d3-fcc9–47ff-8fd1–6ef0b079f30e-c000.snappy.parquet’, engine=’pyarrow’)pdTrain.head() Pyarrow.parquet import pyarrow.parquet as pqpath = ‘hdfs:///iris/part-00000–71c8h2d3-fcc9–47ff-8fd1–6ef0b079f30e-c000.snappy.parquet’table = pq.read_table(path)table.schemadf = table.to_pandas()df.head() Other files extensions As we can store any kind of files (SAS, STATA, Excel, JSON or objects), the majority of then are easily interpreted by Python. To accomplish that we’ll use the open function that returns a buffer object that many pandas function like read_sas, read_json could receive as input instead of a string URL. SAS import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.sas7bdat’, ‘rb’) as f: sas_df = pd.read_sas(f, format='sas7bdat')sas_df.head() Excel import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.xlsx’, ‘rb’) as f: g.download('airplane.xlsx')ex_df = pd.read_excel('airplane.xlsx') JSON import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.json’, ‘rb’) as f: g.download('airplane.json')js_df = pd.read_json('airplane.json') Download files from HDFS If we just need to download the file, Pyarrow provides us with the download function to save the file in local. import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.cs’, ‘rb’) as f: g.download('airplane.cs') Upload files to HDFS If we just need to download the file, Pyarrow provides us with the download function to save the file in local. import pyarrow as pafs = pa.hdfs.connect()with open(‘settings.xml’) as f: pa.hdfs.HadoopFileSystem.upload(fs, ‘/datalake/settings.xml’, f) Apache Arrow with Apache Spark Apache Arrow is integrated with Spark since version 2.3, exists good presentations about optimizing times avoiding serialization & deserialization process and integrating with other libraries like a presentation about accelerating Tensorflow Apache Arrow on Spark from Holden Karau. Exist other useful articles like one published by Brian Cutler and really good examples in the Spark’s official documentation Some interesting uses of Apache Arrow are: Speeding upconversion from Pandas Data Frame to Spark Data Frame Speeding upconversion from Spark Data Frame to Pandas Data Frame Using with Pandas UDF (a.k.a Vectorized UDFs) Optimizing R with Apache Spark The third item will be part from a next article since It’s a very interesting topic in order to expand the integration between Pandas and Spark without losing performance, for the fourth item I recommend you to read the article (was published in 2019!) to get know more about it. Let’s test the conversion among Pandas and Spark first without modifying anything and then allowing Arrow. from pyspark.sql import SparkSessionwarehouseLocation = “/antonio”spark = SparkSession\.builder.appName(“demoMedium”)\.config(“spark.sql.warehouse.dir”, warehouseLocation)\.enableHiveSupport()\.getOrCreate()#Create test Spark DataFramefrom pyspark.sql.functions import randdf = spark.range(1 << 22).toDF(“id”).withColumn(“x”, rand())df.printSchema()#Benchmark time%time pdf = df.toPandas()spark.conf.set(“spark.sql.execution.arrow.enabled”, “true”)%time pdf = df.toPandas()pdf.describe() In the results is clearly more convenient to use Arrow to decrease time conversion. If we need to test the contrary case (pandas to spark df) also we see an optimization in time. %time df = spark.createDataFrame(pdf)spark.conf.set("spark.sql.execution.arrow.enabled", "false")%time df = spark.createDataFrame(pdf)df.describe().show() In conclusion This article's intention was to discover and understand about Apache Arrow and how it works with Apache Spark and Pandas, also I suggest you check the official page of It to know more about other possible integration like CUDA or C++, also if you want to go deeper and learn more about Apache Spark, I think Spark: The Definitive Guide is an excellent book. PS if you have any questions, or would like something clarified, you can find me on Twitter and LinkedIn. I recently published A gentle introduction to Apache Druid a new Apache project ideal for analyzing billions of rows.
[ { "code": null, "e": 356, "s": 172, "text": "This time I am going to try to explain how can we use Apache Arrow in conjunction with Apache Spark and Python. First, let me share some basic concepts about this open source project." }, { "code": null, "e": 618, "s": 356, "text": "Apache Arrow is a cross-language development platform for in-memory data. It specifies a standardized language-independent columnar memory format for flat and hierarchical data, organized for efficient analytic operations on modern hardware. [Apache Arrow page]" }, { "code": null, "e": 859, "s": 618, "text": "In simple words, It facilitates communication between many components, for example, reading a parquet file with Python (pandas) and transforming to a Spark dataframe, Falcon Data Visualization or Cassandra without worrying about conversion." }, { "code": null, "e": 1043, "s": 859, "text": "A good question is to ask how does the data look like in memory? Well, Apache Arrow takes advantage of a columnar buffer to reduce IO and accelerate analytical processing performance." }, { "code": null, "e": 1212, "s": 1043, "text": "In our case, we will use the pyarrow library to execute some basic codes and check some features. In order to install, we have two options using conda or pip commands*." }, { "code": null, "e": 1268, "s": 1212, "text": "conda install -c conda-forge pyarrowpip install pyarrow" }, { "code": null, "e": 1326, "s": 1268, "text": "*It’s recommended to use conda in a Python 3 environment." }, { "code": null, "e": 1371, "s": 1326, "text": "Apache Arrow with Pandas (Local File System)" }, { "code": null, "e": 1421, "s": 1371, "text": "Converting Pandas Dataframe to Apache Arrow Table" }, { "code": null, "e": 1643, "s": 1421, "text": "import numpy as npimport pandas as pdimport pyarrow as padf = pd.DataFrame({'one': [20, np.nan, 2.5],'two': ['january', 'february', 'march'],'three': [True, False, True]},index=list('abc'))table = pa.Table.from_pandas(df)" }, { "code": null, "e": 1678, "s": 1643, "text": "Pyarrow Table to Pandas Data Frame" }, { "code": null, "e": 1705, "s": 1678, "text": "df_new = table.to_pandas()" }, { "code": null, "e": 1714, "s": 1705, "text": "Read CSV" }, { "code": null, "e": 1804, "s": 1714, "text": "from pyarrow import csvfn = ‘data/demo.csv’table = csv.read_csv(fn)df = table.to_pandas()" }, { "code": null, "e": 1845, "s": 1804, "text": "Writing a parquet file from Apache Arrow" }, { "code": null, "e": 1914, "s": 1845, "text": "import pyarrow.parquet as pqpq.write_table(table, 'example.parquet')" }, { "code": null, "e": 1937, "s": 1914, "text": "Reading a parquet file" }, { "code": null, "e": 1985, "s": 1937, "text": "table2 = pq.read_table(‘example.parquet’)table2" }, { "code": null, "e": 2026, "s": 1985, "text": "Reading some columns from a parquet file" }, { "code": null, "e": 2094, "s": 2026, "text": "table2 = pq.read_table('example.parquet', columns=['one', 'three'])" }, { "code": null, "e": 2128, "s": 2094, "text": "Reading from Partitioned Datasets" }, { "code": null, "e": 2210, "s": 2128, "text": "dataset = pq.ParquetDataset(‘dataset_name_directory/’)table = dataset.read()table" }, { "code": null, "e": 2260, "s": 2210, "text": "Transforming Parquet file into a Pandas DataFrame" }, { "code": null, "e": 2332, "s": 2260, "text": "pdf = pq.read_pandas('example.parquet', columns=['two']).to_pandas()pdf" }, { "code": null, "e": 2354, "s": 2332, "text": "Avoiding pandas index" }, { "code": null, "e": 2514, "s": 2354, "text": "table = pa.Table.from_pandas(df, preserve_index=False)pq.write_table(table, 'example_noindex.parquet')t = pq.read_table('example_noindex.parquet')t.to_pandas()" }, { "code": null, "e": 2529, "s": 2514, "text": "Check metadata" }, { "code": null, "e": 2599, "s": 2529, "text": "parquet_file = pq.ParquetFile(‘example.parquet’)parquet_file.metadata" }, { "code": null, "e": 2615, "s": 2599, "text": "See data schema" }, { "code": null, "e": 2635, "s": 2615, "text": "parquet_file.schema" }, { "code": null, "e": 2645, "s": 2635, "text": "Timestamp" }, { "code": null, "e": 2732, "s": 2645, "text": "Remember Pandas use nanoseconds so you can truncate in milliseconds for compatibility." }, { "code": null, "e": 2870, "s": 2732, "text": "pq.write_table(table, where, coerce_timestamps='ms')pq.write_table(table, where, coerce_timestamps='ms', allow_truncated_timestamps=True)" }, { "code": null, "e": 2882, "s": 2870, "text": "Compression" }, { "code": null, "e": 3005, "s": 2882, "text": "By default, Apache arrow uses snappy compression (not so compressed but easier access), although other codecs are allowed." }, { "code": null, "e": 3202, "s": 3005, "text": "pq.write_table(table, where, compression='snappy')pq.write_table(table, where, compression='gzip')pq.write_table(table, where, compression='brotli')pq.write_table(table, where, compression='none')" }, { "code": null, "e": 3266, "s": 3202, "text": "Also, It’s possible to use more than one compression in a table" }, { "code": null, "e": 3365, "s": 3266, "text": "pq.write_table(table, ‘example_diffcompr.parquet’, compression={b’one’: ‘snappy’, b’two’: ‘gzip’})" }, { "code": null, "e": 3399, "s": 3365, "text": "Write a partitioned Parquet table" }, { "code": null, "e": 3693, "s": 3399, "text": "df = pd.DataFrame({‘one’: [1, 2.5, 3], ‘two’: [‘Peru’, ‘Brasil’, ‘Canada’], ‘three’: [True, False, True]}, index=list(‘abc’))table = pa.Table.from_pandas(df)pq.write_to_dataset(table, root_path=’dataset_name’,partition_cols=[‘one’, ‘two’])" }, { "code": null, "e": 3915, "s": 3693, "text": "Compatibility note: if you are using pq.write_to_dataset to create a table that will then be used by HIVE then partition column values must be compatible with the allowed character set of the HIVE version you are running." }, { "code": null, "e": 3959, "s": 3915, "text": "Apache Arrow with HDFS (Remote file-system)" }, { "code": null, "e": 4138, "s": 3959, "text": "Apache Arrow comes with bindings to a C++-based interface to the Hadoop File System. It means that we can read or download all files from HDFS and interpret directly with Python." }, { "code": null, "e": 4149, "s": 4138, "text": "Connection" }, { "code": null, "e": 4332, "s": 4149, "text": "Host is the namenode, port is usually RPC or WEBHDFS more parameters like user, kerberos ticket are allow. It’s strongly recommended to read about the environmental variables needed." }, { "code": null, "e": 4415, "s": 4332, "text": "import pyarrow as pahost = '1970.x.x.x'port = 8022fs = pa.hdfs.connect(host, port)" }, { "code": null, "e": 4501, "s": 4415, "text": "Optional if your connection is made front a data or edge node is possible to use just" }, { "code": null, "e": 4524, "s": 4501, "text": "fs = pa.hdfs.connect()" }, { "code": null, "e": 4552, "s": 4524, "text": "Write Parquet files to HDFS" }, { "code": null, "e": 4651, "s": 4552, "text": "pq.write_to_dataset(table, root_path=’dataset_name’, partition_cols=[‘one’, ‘two’], filesystem=fs)" }, { "code": null, "e": 4670, "s": 4651, "text": "Read CSV from HDFS" }, { "code": null, "e": 4832, "s": 4670, "text": "import pandas as pdfrom pyarrow import csvimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘iris.csv’, ‘rb’) as f: df = pd.read_csv(f, nrows = 10)df.head()" }, { "code": null, "e": 4860, "s": 4832, "text": "Read Parquet File from HDFS" }, { "code": null, "e": 4912, "s": 4860, "text": "There is two forms to read a parquet file from HDFS" }, { "code": null, "e": 4944, "s": 4912, "text": "Using pandas and Pyarrow engine" }, { "code": null, "e": 5104, "s": 4944, "text": "import pandas as pdpdIris = pd.read_parquet(‘hdfs:///iris/part-00000–27c8e2d3-fcc9–47ff-8fd1–6ef0b079f30e-c000.snappy.parquet’, engine=’pyarrow’)pdTrain.head()" }, { "code": null, "e": 5120, "s": 5104, "text": "Pyarrow.parquet" }, { "code": null, "e": 5308, "s": 5120, "text": "import pyarrow.parquet as pqpath = ‘hdfs:///iris/part-00000–71c8h2d3-fcc9–47ff-8fd1–6ef0b079f30e-c000.snappy.parquet’table = pq.read_table(path)table.schemadf = table.to_pandas()df.head()" }, { "code": null, "e": 5331, "s": 5308, "text": "Other files extensions" }, { "code": null, "e": 5633, "s": 5331, "text": "As we can store any kind of files (SAS, STATA, Excel, JSON or objects), the majority of then are easily interpreted by Python. To accomplish that we’ll use the open function that returns a buffer object that many pandas function like read_sas, read_json could receive as input instead of a string URL." }, { "code": null, "e": 5637, "s": 5633, "text": "SAS" }, { "code": null, "e": 5810, "s": 5637, "text": "import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.sas7bdat’, ‘rb’) as f: sas_df = pd.read_sas(f, format='sas7bdat')sas_df.head()" }, { "code": null, "e": 5816, "s": 5810, "text": "Excel" }, { "code": null, "e": 5995, "s": 5816, "text": "import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.xlsx’, ‘rb’) as f: g.download('airplane.xlsx')ex_df = pd.read_excel('airplane.xlsx')" }, { "code": null, "e": 6000, "s": 5995, "text": "JSON" }, { "code": null, "e": 6178, "s": 6000, "text": "import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.json’, ‘rb’) as f: g.download('airplane.json')js_df = pd.read_json('airplane.json')" }, { "code": null, "e": 6203, "s": 6178, "text": "Download files from HDFS" }, { "code": null, "e": 6315, "s": 6203, "text": "If we just need to download the file, Pyarrow provides us with the download function to save the file in local." }, { "code": null, "e": 6452, "s": 6315, "text": "import pandas as pdimport pyarrow as pafs = pa.hdfs.connect()with fs.open(‘/datalake/airplane.cs’, ‘rb’) as f: g.download('airplane.cs')" }, { "code": null, "e": 6473, "s": 6452, "text": "Upload files to HDFS" }, { "code": null, "e": 6585, "s": 6473, "text": "If we just need to download the file, Pyarrow provides us with the download function to save the file in local." }, { "code": null, "e": 6724, "s": 6585, "text": "import pyarrow as pafs = pa.hdfs.connect()with open(‘settings.xml’) as f: pa.hdfs.HadoopFileSystem.upload(fs, ‘/datalake/settings.xml’, f)" }, { "code": null, "e": 6755, "s": 6724, "text": "Apache Arrow with Apache Spark" }, { "code": null, "e": 7038, "s": 6755, "text": "Apache Arrow is integrated with Spark since version 2.3, exists good presentations about optimizing times avoiding serialization & deserialization process and integrating with other libraries like a presentation about accelerating Tensorflow Apache Arrow on Spark from Holden Karau." }, { "code": null, "e": 7164, "s": 7038, "text": "Exist other useful articles like one published by Brian Cutler and really good examples in the Spark’s official documentation" }, { "code": null, "e": 7207, "s": 7164, "text": "Some interesting uses of Apache Arrow are:" }, { "code": null, "e": 7272, "s": 7207, "text": "Speeding upconversion from Pandas Data Frame to Spark Data Frame" }, { "code": null, "e": 7337, "s": 7272, "text": "Speeding upconversion from Spark Data Frame to Pandas Data Frame" }, { "code": null, "e": 7383, "s": 7337, "text": "Using with Pandas UDF (a.k.a Vectorized UDFs)" }, { "code": null, "e": 7414, "s": 7383, "text": "Optimizing R with Apache Spark" }, { "code": null, "e": 7694, "s": 7414, "text": "The third item will be part from a next article since It’s a very interesting topic in order to expand the integration between Pandas and Spark without losing performance, for the fourth item I recommend you to read the article (was published in 2019!) to get know more about it." }, { "code": null, "e": 7801, "s": 7694, "text": "Let’s test the conversion among Pandas and Spark first without modifying anything and then allowing Arrow." }, { "code": null, "e": 8289, "s": 7801, "text": "from pyspark.sql import SparkSessionwarehouseLocation = “/antonio”spark = SparkSession\\.builder.appName(“demoMedium”)\\.config(“spark.sql.warehouse.dir”, warehouseLocation)\\.enableHiveSupport()\\.getOrCreate()#Create test Spark DataFramefrom pyspark.sql.functions import randdf = spark.range(1 << 22).toDF(“id”).withColumn(“x”, rand())df.printSchema()#Benchmark time%time pdf = df.toPandas()spark.conf.set(“spark.sql.execution.arrow.enabled”, “true”)%time pdf = df.toPandas()pdf.describe()" }, { "code": null, "e": 8373, "s": 8289, "text": "In the results is clearly more convenient to use Arrow to decrease time conversion." }, { "code": null, "e": 8468, "s": 8373, "text": "If we need to test the contrary case (pandas to spark df) also we see an optimization in time." }, { "code": null, "e": 8623, "s": 8468, "text": "%time df = spark.createDataFrame(pdf)spark.conf.set(\"spark.sql.execution.arrow.enabled\", \"false\")%time df = spark.createDataFrame(pdf)df.describe().show()" }, { "code": null, "e": 8637, "s": 8623, "text": "In conclusion" }, { "code": null, "e": 8995, "s": 8637, "text": "This article's intention was to discover and understand about Apache Arrow and how it works with Apache Spark and Pandas, also I suggest you check the official page of It to know more about other possible integration like CUDA or C++, also if you want to go deeper and learn more about Apache Spark, I think Spark: The Definitive Guide is an excellent book." } ]
From DataFrame to Network Graph. A quick start guide to visualizing a... | by Ednalyn C. De Dios | Towards Data Science
I just discovered — quite accidentally — how to export data from JIRA so naturally, I began to think of ways to visualize the information and potentially glean some insight from the dataset. I’ve stumbled upon the concept of network graphs and the idea quickly captured my imagination. I realized that I can use it to tell stories not only about the relationships between people but between words as well! But NLP is a big topic, so how about we walk first and run later?! This is just a very gentle introduction so we won’t be using any fancy code here. Network graphs “show interconnections between a set of entities”1 where entities arenodes and the connections between them are represented through links or edges1. In the graph below, the dots are the nodes and the lines are called edges. In this post, I’ll share the code that will let us quickly visualize a Pandas dataframe using a popular network graph package: networkx. First, let’s get our data and load it into a dataframe. You can download the sample dataset here. import pandas as pddf = pd.read_csv('jira_sample.csv') Second, let’s trim the dataframe to only include the columns we want to examine. In this case, we only want the columns ‘Assignee’ and ‘Reporter’. df1 = df[['Assignee', 'Reporter']] Third, it’s time to create the world into which the graph will exist. If you haven’t already, install the networkx package by doing a quick pip install networkx. import networkx as nxG = nx.Graph() Then, let’s populate the graph with the 'Assignee' and 'Reporter' columns from the df1 dataframe. G = nx.from_pandas_edgelist(df1, 'Assignee', 'Reporter') Next, we’ll materialize the graph we created with the help of matplotlib for formatting. from matplotlib.pyplot import figurefigure(figsize=(10, 8))nx.draw_shell(G, with_labels=True) The most important line in the block above is nx.draw_shell(G, with_labels=True). It tells the computer to draw the graph Gusing a shell layout with the labels for entities turned on. Voilà! We got ourselves a network graph: Right off the bat, we can tell that there’s a heavy concentration of lines originating from three major players, ‘barbie.doll’, ‘susan.lee’, and ‘joe.appleseed’. Of course, just to be sure, it’s always a good idea to confirm our ‘eyeballing’ with some hard numbers. Bonus Round Let’s check out ‘barbie.doll’. G['barbie.doll'] To see how many connections ‘barbie.doll’ has, let’s use len(): len(G['barbie.doll']) Next, let’s create another dataframe that shows the nodes and their number of connections. leaderboard = {}for x in G.nodes: leaderboard[x] = len(G[x])s = pd.Series(leaderboard, name='connections')df2 = s.to_frame().sort_values('connections', ascending=False) In the code block above, we first initialized an empty dictionary called ‘leaderboard’ and then used a simple for-loop to populate the dictionary with names and number of connections. Then, we created a series out of the dictionary. Finally, we created another dataframe from the series that we created using to_frame(). To display the dataframe, we simply use df2.head() and we got ourselves a leaderboard! And that’s it! With a few simple lines of code, we quickly made a network graph from a Pandas dataframe and even displayed a table with names and number of connections. I hope you enjoyed this one. Network graph analysis is a big topic but I hope that this gentle introduction will encourage you to explore more and expand your repertoire. In the next article, I’ll walk through Power BI’s custom visual called ‘Network Navigator’ to create a network graph with a few simple clicks of the mouse. Stay tuned! You can reach me on Twitter or LinkedIn. [1]: Data-To-Viz. (May 15, 2020). Network Diagram https://www.data-to-viz.com/graph/network.html
[ { "code": null, "e": 645, "s": 172, "text": "I just discovered — quite accidentally — how to export data from JIRA so naturally, I began to think of ways to visualize the information and potentially glean some insight from the dataset. I’ve stumbled upon the concept of network graphs and the idea quickly captured my imagination. I realized that I can use it to tell stories not only about the relationships between people but between words as well! But NLP is a big topic, so how about we walk first and run later?!" }, { "code": null, "e": 727, "s": 645, "text": "This is just a very gentle introduction so we won’t be using any fancy code here." }, { "code": null, "e": 966, "s": 727, "text": "Network graphs “show interconnections between a set of entities”1 where entities arenodes and the connections between them are represented through links or edges1. In the graph below, the dots are the nodes and the lines are called edges." }, { "code": null, "e": 1103, "s": 966, "text": "In this post, I’ll share the code that will let us quickly visualize a Pandas dataframe using a popular network graph package: networkx." }, { "code": null, "e": 1201, "s": 1103, "text": "First, let’s get our data and load it into a dataframe. You can download the sample dataset here." }, { "code": null, "e": 1256, "s": 1201, "text": "import pandas as pddf = pd.read_csv('jira_sample.csv')" }, { "code": null, "e": 1403, "s": 1256, "text": "Second, let’s trim the dataframe to only include the columns we want to examine. In this case, we only want the columns ‘Assignee’ and ‘Reporter’." }, { "code": null, "e": 1438, "s": 1403, "text": "df1 = df[['Assignee', 'Reporter']]" }, { "code": null, "e": 1600, "s": 1438, "text": "Third, it’s time to create the world into which the graph will exist. If you haven’t already, install the networkx package by doing a quick pip install networkx." }, { "code": null, "e": 1636, "s": 1600, "text": "import networkx as nxG = nx.Graph()" }, { "code": null, "e": 1734, "s": 1636, "text": "Then, let’s populate the graph with the 'Assignee' and 'Reporter' columns from the df1 dataframe." }, { "code": null, "e": 1791, "s": 1734, "text": "G = nx.from_pandas_edgelist(df1, 'Assignee', 'Reporter')" }, { "code": null, "e": 1880, "s": 1791, "text": "Next, we’ll materialize the graph we created with the help of matplotlib for formatting." }, { "code": null, "e": 1974, "s": 1880, "text": "from matplotlib.pyplot import figurefigure(figsize=(10, 8))nx.draw_shell(G, with_labels=True)" }, { "code": null, "e": 2158, "s": 1974, "text": "The most important line in the block above is nx.draw_shell(G, with_labels=True). It tells the computer to draw the graph Gusing a shell layout with the labels for entities turned on." }, { "code": null, "e": 2200, "s": 2158, "text": "Voilà! We got ourselves a network graph:" }, { "code": null, "e": 2466, "s": 2200, "text": "Right off the bat, we can tell that there’s a heavy concentration of lines originating from three major players, ‘barbie.doll’, ‘susan.lee’, and ‘joe.appleseed’. Of course, just to be sure, it’s always a good idea to confirm our ‘eyeballing’ with some hard numbers." }, { "code": null, "e": 2478, "s": 2466, "text": "Bonus Round" }, { "code": null, "e": 2509, "s": 2478, "text": "Let’s check out ‘barbie.doll’." }, { "code": null, "e": 2526, "s": 2509, "text": "G['barbie.doll']" }, { "code": null, "e": 2590, "s": 2526, "text": "To see how many connections ‘barbie.doll’ has, let’s use len():" }, { "code": null, "e": 2612, "s": 2590, "text": "len(G['barbie.doll'])" }, { "code": null, "e": 2703, "s": 2612, "text": "Next, let’s create another dataframe that shows the nodes and their number of connections." }, { "code": null, "e": 2872, "s": 2703, "text": "leaderboard = {}for x in G.nodes: leaderboard[x] = len(G[x])s = pd.Series(leaderboard, name='connections')df2 = s.to_frame().sort_values('connections', ascending=False)" }, { "code": null, "e": 3193, "s": 2872, "text": "In the code block above, we first initialized an empty dictionary called ‘leaderboard’ and then used a simple for-loop to populate the dictionary with names and number of connections. Then, we created a series out of the dictionary. Finally, we created another dataframe from the series that we created using to_frame()." }, { "code": null, "e": 3280, "s": 3193, "text": "To display the dataframe, we simply use df2.head() and we got ourselves a leaderboard!" }, { "code": null, "e": 3449, "s": 3280, "text": "And that’s it! With a few simple lines of code, we quickly made a network graph from a Pandas dataframe and even displayed a table with names and number of connections." }, { "code": null, "e": 3620, "s": 3449, "text": "I hope you enjoyed this one. Network graph analysis is a big topic but I hope that this gentle introduction will encourage you to explore more and expand your repertoire." }, { "code": null, "e": 3776, "s": 3620, "text": "In the next article, I’ll walk through Power BI’s custom visual called ‘Network Navigator’ to create a network graph with a few simple clicks of the mouse." }, { "code": null, "e": 3788, "s": 3776, "text": "Stay tuned!" }, { "code": null, "e": 3829, "s": 3788, "text": "You can reach me on Twitter or LinkedIn." } ]
AWS Lambda - 7 things I wished someone told me | by Charles Malafosse | Towards Data Science
AWS Lambda is quite simple to use but as the same time it can be tricky to implement and optimize. In this post I summarized 3 years of experience working with this service. The result is a list of 7 things I wish I already knew when I started, from service logic, DB connections management and cost optimization. Hope this helps people starting off. AWS Lambda is Amazon “Function as a Service” (FaaS), a category of cloud computing services that allows customers to run application functionalities without the complexity of maintaining the infrastructure. You pay only for the compute time you consume, which is great, and there is no charge when your code is not running. First things first, how does AWS Lambda work? Each lambda function is executed in a container that provides an isolated execution environment. When a function is executed for the first time, a new container with the appropriate resources will be created to execute it, and the code for the function will be loaded into the container. This happens every time the function’s code is updated or when a previously created container is destroyed. Although AWS will reuse a container when one is available, after some time this container is destroyed. There is no documentation that describe when a container is destroyed nor what event can trigger its destruction. We must keep in mind that Lambda function should be stateless and we should accept that a container could live few minutes or few seconds. TAKEAWAY: Lambda need to create an isolated container to execute your code. This container can be destroyed at anytime. Make sure your function’s code is stateless. aws.amazon.com The cold start issue is an important factor to keep in mind when writing a Lambda function. It refers to the fact that when a container is created, AWS needs extra time to load the code and set up the environment versus just reusing an existing container. This is important when a lambda function need to load data, set global variables, and initiate connections to a database. Depending on your function, it can take few milliseconds to few seconds. And anything above 1 second can feel like an eternity for a user of your API! Also note that cold start happens once for each concurrent execution of your function. Therefore, a burst of requests on your lambda can lead to multiple users experiencing a slow execution due to the cold start... not great. When you write your Lambda function code, do not assume that AWS Lambda automatically reuses the execution context for subsequent function invocations. Other factors may dictate a need for AWS Lambda to create a new execution context, which can lead to unexpected results, such as database connection failures. TAKEAWAY: The cold start issue can happen anytime and slow the execution of your lambda function. medium.com Extra care should be used when writing a Lambda function that connects to a SQL database. Lambda is (almost) infinitely scalable. When concurrent executions of a lambda are triggered, each of these executions will set up their own global variables and database connections. Unfortunately, your database’s available connections might not be enough to allow each lambda function to create their own connection. And this could result in a denial of service. Few potential solutions: First, make sure your database connection is established once for each container started. One way to do that is to put the connection in a global variable. Do not forget to include some mechanism in your code to test the validity of the connection and reconnect if lost. Second, use a service such as Amazon RDS Proxy. RDS Proxy allows your applications to pool and share database connections to improve their ability to scale. A bit harder to set up and an extra cost associated to this service, but a more robust solution. TAKEAWAY: Even though Lambda is highly scalable, your DB connections are not. Keep that in mind when using Lambdas. aws.amazon.com Unless you have deep pockets and can afford a fast server to host your SQL database, a query returning large chunk of data can slow your Lambda function. One way I used to speed up things is to use the S3 service. First I dumped an extract of my SQL table to a csv file in a S3 bucket. Next, every time my lambda function starts for the first time (cold start) the file is transferred from S3 to the /tmp/ directory of my lambda container. In python the code to do so is quite simple (to not forget to allow lambda to access S3): import boto3#INITIATE S3s3_resource = boto3.resource('s3')S3_FILENAME ="file.pkl"# A PKL file is a file created by pickle, a Python module that enables objects to be serialized to files on disk and deserialized back into the program at runtime.def download_from_s3(filename): s3_resource.meta.client.download_file("yourS3Bucket", filename, '/tmp/' + filename)#Transfer the S3 file to the /temp folder of the lambdadownload_from_s3(S3_FILENAME) On my lambda with 1280MB of memory, a file of 125mb takes approximately 2000ms to be transferred. Still a significant amount but keep in mind it only has to be done once. The equivalent with an SQL query on my database would be more than 20 seconds. According to the doc: “data transferred between Amazon S3 [...] and AWS Lambda functions in the same AWS Region is free.”, so no worries regarding the cost. TAKEWAY: You can load data directly in your Lambda’s memory thanks to the S3 service. This might be a way to reduce the load on your database and increase the speed of your lambda at the same time. Lambda function can pull in additional code and content in the form of layers. From AWS docs: “A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. With layers, you can use libraries in your function without needing to include them in your deployment package.” Simply put, a lambda layer is a piece of code that can be reused in other lambda functions. The main advantages of layers are, in my opinion: It helps you keep your Lambda deployment package under 3MB, the threshold to be able to edit your code in the AWS console. It helps you reuse pieces of code and python packages (when using python) that are not available right out the box, such as pandas or numpy. Finally, it helps you write readable and clean Lambda functions with reduced operational errors that could occur during installation of dependencies. TAKEAWAY: Use Lambda layers as much as possible to keep your deployment package small and to stay under the 3MB threshold to be able to edit your code in the AWS console. docs.aws.amazon.com One parameter of Lambda functions is the amount of memory available to the function. Lambda allocates CPU power linearly in proportion to the amount of memory configured. According to the docs, at 1,792 MB, a function has the equivalent of one full vCPU (one vCPU-second of credits per second). Of course, higher memory means higher cost. For example, in the eu-west-1 region it costs $0.0000166667 for every GB of memory per second. One might think that increasing the memory of a Lambda function will result in a higher bill. But this is not entirely true for 2 reasons: First, higher memory lambda functions are faster, which means that you’ll pay more per second, but it will take less time. Lambda charge now by milliseconds since AWS Re:Invent 2020 (a change from the 100ms minimum charge). For this reason there is always a sweet spot where you can achieve faster execution time for a lower cost. Below we achieve the lowest cost for our lambda at 1024MB memory. A 10% discount for a 9 times faster execution time. Second, higher memory also comes with a bigger internet connection. This means that queries and API calls are going to return data faster. TAKEAWAY: Increased memory in lambdas do not necessarily translate in higher cost. With more memory lambdas are executed faster. Hence there is usually a sweet spot with higher memory and similar cost. Lambda is priced reasonably. However it is classic to end up with a larger bill than a similar code running on an EC2 instance. Here is why: You do not benefit from potential pseudo-parallel computation. By that I mean that lambda charge as if it was using the entire allocated vCPU even when it’s not, for example when your code is waiting for a query to be executed on a database. There is no spot pricing. You always pay full price. Spot instances with EC2 are great and can help save quite a lot. Below is a table summarizing the price difference of a 128MB lambda vs. a cheap T3.nano. Lambda cost is twice as much, assuming full use of the lambda, and ignoring the fact that T3.nano can run pseudo concurrent execution at no extra cost. Having said that, Lambda flexibility and the fact that there is no infrastructure to manage is worth the price in my opinion. But keep in mind that heavily invoked lambda might be better off running in a EC2 instance. TAKEAWAY: Lambda functions are not always the best option when they are heavily invoked. EC2 or Elastic Beanstalk might be good alternatives. AWS Lambda is a great service. It is fast and reliable and can help deploy code without managing the infrastructure. Nonetheless it can also be expensive both in terms of time and money if not understood to a certain level. Hopefully this article helped you visualize the techniques and details I encountered while developing hundreds of AWS Lambdas.
[ { "code": null, "e": 522, "s": 171, "text": "AWS Lambda is quite simple to use but as the same time it can be tricky to implement and optimize. In this post I summarized 3 years of experience working with this service. The result is a list of 7 things I wish I already knew when I started, from service logic, DB connections management and cost optimization. Hope this helps people starting off." }, { "code": null, "e": 846, "s": 522, "text": "AWS Lambda is Amazon “Function as a Service” (FaaS), a category of cloud computing services that allows customers to run application functionalities without the complexity of maintaining the infrastructure. You pay only for the compute time you consume, which is great, and there is no charge when your code is not running." }, { "code": null, "e": 892, "s": 846, "text": "First things first, how does AWS Lambda work?" }, { "code": null, "e": 1288, "s": 892, "text": "Each lambda function is executed in a container that provides an isolated execution environment. When a function is executed for the first time, a new container with the appropriate resources will be created to execute it, and the code for the function will be loaded into the container. This happens every time the function’s code is updated or when a previously created container is destroyed." }, { "code": null, "e": 1645, "s": 1288, "text": "Although AWS will reuse a container when one is available, after some time this container is destroyed. There is no documentation that describe when a container is destroyed nor what event can trigger its destruction. We must keep in mind that Lambda function should be stateless and we should accept that a container could live few minutes or few seconds." }, { "code": null, "e": 1810, "s": 1645, "text": "TAKEAWAY: Lambda need to create an isolated container to execute your code. This container can be destroyed at anytime. Make sure your function’s code is stateless." }, { "code": null, "e": 1825, "s": 1810, "text": "aws.amazon.com" }, { "code": null, "e": 2081, "s": 1825, "text": "The cold start issue is an important factor to keep in mind when writing a Lambda function. It refers to the fact that when a container is created, AWS needs extra time to load the code and set up the environment versus just reusing an existing container." }, { "code": null, "e": 2354, "s": 2081, "text": "This is important when a lambda function need to load data, set global variables, and initiate connections to a database. Depending on your function, it can take few milliseconds to few seconds. And anything above 1 second can feel like an eternity for a user of your API!" }, { "code": null, "e": 2580, "s": 2354, "text": "Also note that cold start happens once for each concurrent execution of your function. Therefore, a burst of requests on your lambda can lead to multiple users experiencing a slow execution due to the cold start... not great." }, { "code": null, "e": 2891, "s": 2580, "text": "When you write your Lambda function code, do not assume that AWS Lambda automatically reuses the execution context for subsequent function invocations. Other factors may dictate a need for AWS Lambda to create a new execution context, which can lead to unexpected results, such as database connection failures." }, { "code": null, "e": 2989, "s": 2891, "text": "TAKEAWAY: The cold start issue can happen anytime and slow the execution of your lambda function." }, { "code": null, "e": 3000, "s": 2989, "text": "medium.com" }, { "code": null, "e": 3090, "s": 3000, "text": "Extra care should be used when writing a Lambda function that connects to a SQL database." }, { "code": null, "e": 3455, "s": 3090, "text": "Lambda is (almost) infinitely scalable. When concurrent executions of a lambda are triggered, each of these executions will set up their own global variables and database connections. Unfortunately, your database’s available connections might not be enough to allow each lambda function to create their own connection. And this could result in a denial of service." }, { "code": null, "e": 3480, "s": 3455, "text": "Few potential solutions:" }, { "code": null, "e": 3751, "s": 3480, "text": "First, make sure your database connection is established once for each container started. One way to do that is to put the connection in a global variable. Do not forget to include some mechanism in your code to test the validity of the connection and reconnect if lost." }, { "code": null, "e": 4005, "s": 3751, "text": "Second, use a service such as Amazon RDS Proxy. RDS Proxy allows your applications to pool and share database connections to improve their ability to scale. A bit harder to set up and an extra cost associated to this service, but a more robust solution." }, { "code": null, "e": 4121, "s": 4005, "text": "TAKEAWAY: Even though Lambda is highly scalable, your DB connections are not. Keep that in mind when using Lambdas." }, { "code": null, "e": 4136, "s": 4121, "text": "aws.amazon.com" }, { "code": null, "e": 4290, "s": 4136, "text": "Unless you have deep pockets and can afford a fast server to host your SQL database, a query returning large chunk of data can slow your Lambda function." }, { "code": null, "e": 4666, "s": 4290, "text": "One way I used to speed up things is to use the S3 service. First I dumped an extract of my SQL table to a csv file in a S3 bucket. Next, every time my lambda function starts for the first time (cold start) the file is transferred from S3 to the /tmp/ directory of my lambda container. In python the code to do so is quite simple (to not forget to allow lambda to access S3):" }, { "code": null, "e": 5113, "s": 4666, "text": "import boto3#INITIATE S3s3_resource = boto3.resource('s3')S3_FILENAME =\"file.pkl\"# A PKL file is a file created by pickle, a Python module that enables objects to be serialized to files on disk and deserialized back into the program at runtime.def download_from_s3(filename): s3_resource.meta.client.download_file(\"yourS3Bucket\", filename, '/tmp/' + filename)#Transfer the S3 file to the /temp folder of the lambdadownload_from_s3(S3_FILENAME)" }, { "code": null, "e": 5520, "s": 5113, "text": "On my lambda with 1280MB of memory, a file of 125mb takes approximately 2000ms to be transferred. Still a significant amount but keep in mind it only has to be done once. The equivalent with an SQL query on my database would be more than 20 seconds. According to the doc: “data transferred between Amazon S3 [...] and AWS Lambda functions in the same AWS Region is free.”, so no worries regarding the cost." }, { "code": null, "e": 5718, "s": 5520, "text": "TAKEWAY: You can load data directly in your Lambda’s memory thanks to the S3 service. This might be a way to reduce the load on your database and increase the speed of your lambda at the same time." }, { "code": null, "e": 6017, "s": 5718, "text": "Lambda function can pull in additional code and content in the form of layers. From AWS docs: “A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. With layers, you can use libraries in your function without needing to include them in your deployment package.”" }, { "code": null, "e": 6159, "s": 6017, "text": "Simply put, a lambda layer is a piece of code that can be reused in other lambda functions. The main advantages of layers are, in my opinion:" }, { "code": null, "e": 6282, "s": 6159, "text": "It helps you keep your Lambda deployment package under 3MB, the threshold to be able to edit your code in the AWS console." }, { "code": null, "e": 6423, "s": 6282, "text": "It helps you reuse pieces of code and python packages (when using python) that are not available right out the box, such as pandas or numpy." }, { "code": null, "e": 6573, "s": 6423, "text": "Finally, it helps you write readable and clean Lambda functions with reduced operational errors that could occur during installation of dependencies." }, { "code": null, "e": 6744, "s": 6573, "text": "TAKEAWAY: Use Lambda layers as much as possible to keep your deployment package small and to stay under the 3MB threshold to be able to edit your code in the AWS console." }, { "code": null, "e": 6764, "s": 6744, "text": "docs.aws.amazon.com" }, { "code": null, "e": 7059, "s": 6764, "text": "One parameter of Lambda functions is the amount of memory available to the function. Lambda allocates CPU power linearly in proportion to the amount of memory configured. According to the docs, at 1,792 MB, a function has the equivalent of one full vCPU (one vCPU-second of credits per second)." }, { "code": null, "e": 7337, "s": 7059, "text": "Of course, higher memory means higher cost. For example, in the eu-west-1 region it costs $0.0000166667 for every GB of memory per second. One might think that increasing the memory of a Lambda function will result in a higher bill. But this is not entirely true for 2 reasons:" }, { "code": null, "e": 7786, "s": 7337, "text": "First, higher memory lambda functions are faster, which means that you’ll pay more per second, but it will take less time. Lambda charge now by milliseconds since AWS Re:Invent 2020 (a change from the 100ms minimum charge). For this reason there is always a sweet spot where you can achieve faster execution time for a lower cost. Below we achieve the lowest cost for our lambda at 1024MB memory. A 10% discount for a 9 times faster execution time." }, { "code": null, "e": 7925, "s": 7786, "text": "Second, higher memory also comes with a bigger internet connection. This means that queries and API calls are going to return data faster." }, { "code": null, "e": 8127, "s": 7925, "text": "TAKEAWAY: Increased memory in lambdas do not necessarily translate in higher cost. With more memory lambdas are executed faster. Hence there is usually a sweet spot with higher memory and similar cost." }, { "code": null, "e": 8268, "s": 8127, "text": "Lambda is priced reasonably. However it is classic to end up with a larger bill than a similar code running on an EC2 instance. Here is why:" }, { "code": null, "e": 8510, "s": 8268, "text": "You do not benefit from potential pseudo-parallel computation. By that I mean that lambda charge as if it was using the entire allocated vCPU even when it’s not, for example when your code is waiting for a query to be executed on a database." }, { "code": null, "e": 8628, "s": 8510, "text": "There is no spot pricing. You always pay full price. Spot instances with EC2 are great and can help save quite a lot." }, { "code": null, "e": 8869, "s": 8628, "text": "Below is a table summarizing the price difference of a 128MB lambda vs. a cheap T3.nano. Lambda cost is twice as much, assuming full use of the lambda, and ignoring the fact that T3.nano can run pseudo concurrent execution at no extra cost." }, { "code": null, "e": 9087, "s": 8869, "text": "Having said that, Lambda flexibility and the fact that there is no infrastructure to manage is worth the price in my opinion. But keep in mind that heavily invoked lambda might be better off running in a EC2 instance." }, { "code": null, "e": 9229, "s": 9087, "text": "TAKEAWAY: Lambda functions are not always the best option when they are heavily invoked. EC2 or Elastic Beanstalk might be good alternatives." } ]
Hibernate SessionFactory | Singleton | SessionFactory
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Hibernate SessionFactory is a crucial interface of Hibernate API. It is coming from org.hibernate.SessionFactory package. The main goal of this interface is to provide the Hibernate Session instances. We can get the Hibernate SessionFactory object by calling the buildSessionFactory() method. Like below : SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); But the buildSessionFactory() method is deprecated from hibernate 4.x version. And it was replaced with the below syntax : Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); In the hibernate framework, an only heavy object is a SessionFactory object. Because the SessionFactory builds with all the configuration information about the application. Like below : Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); Recommended: The Complete CRUD Application of Hibernate. So that in Hibernate SessionFactory, a configuration file and all the mapping data will be stored. In real time applications like spring with hibernate integration, per each client request if a separate SessionFactory is created then the performance of the application will be reduced. To improve the performance of an application, we need to make the Hibernate SessionFactory ‘s object as a singleton. To implement the Hibernate SessionFactory as a singleton, we create a separate class. Because this class is only responsible for making the Hibernate SessionFactory object as a singleton. Usually, we call such type of classes as utility classes. In that utility class, we define a static factory method to a Hibernate SessionFactory object for one time and return the same factory object always. Since the utility class is only responsible for creating the singleton Hibernate SessionFactory object and returning that object, there is no need for creating an object for utility class. To disallow to creating objects by other classes, we can make the utility class constructor as private. package com.onlinetutorialspoint.config; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtility { public static SessionFactory factory; //to disallow creating objects by other classes. private HibernateUtility() { } //maling the Hibernate SessionFactory object as singleton public static synchronized SessionFactory getSessionFactory() { if (factory == null) { factory = new Configuration().configure("hibernate.cfg.xml"). buildSessionFactory(); } return factory; } } Main.java package com.onlinetutorialspoint.service; import com.onlinetutorialspoint.config.HibernateUtility; import org.hibernate.SessionFactory; public class Main { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtility.getSessionFactory(); System.out.println("Session Factory : " + sessionFactory.hashCode()); SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory(); System.out.println("Session Factory 2 : " + sessionFactory2.hashCode()); SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory(); System.out.println("Session Factory 3 : " + sessionFactory3.hashCode()); } } Session Factory : 1574615832 Session Factory 2 : 1574615832 Session Factory 3 : 1574615832 On the above example, we declared the factory method with the synchronised keyword. Because in case, if the two threads call factory method precisely at the same time, then there is a chance of creating two Hibernate SessionFactory objects. So, it is recommended to make the factory method as a synchronised method. And also we can find the same hashcode for all SessionFactory creations. Then we can say that our application will generate only single Hibernate SessionFactory instance and serve that instance for different client calls. Happy Learning 🙂 hibernate update query example Hibernate Left Join Example Hibernate session differences between load() and get() Custom Generator Class in Hibernate Hibernate Filter Example Xml Configuration Hibernate Native SQL Query Example Hibernate Named Query with Example Hibernate Right Join Example What is Hibernate Hibernate 4 Example with Annotations Mysql Top 10 Advantages of Hibernate Different types of Object States in Hibernate Difference between update vs merge in Hibernate example Hibernate cache first level example Table per Class Strategy in Hibernate Inheritance hibernate update query example Hibernate Left Join Example Hibernate session differences between load() and get() Custom Generator Class in Hibernate Hibernate Filter Example Xml Configuration Hibernate Native SQL Query Example Hibernate Named Query with Example Hibernate Right Join Example What is Hibernate Hibernate 4 Example with Annotations Mysql Top 10 Advantages of Hibernate Different types of Object States in Hibernate Difference between update vs merge in Hibernate example Hibernate cache first level example Table per Class Strategy in Hibernate Inheritance vicky December 25, 2016 at 9:50 am - Reply nice explanation. Mamta December 29, 2016 at 9:33 am - Reply Please suggest the best way to create Sessionfactory There are many ways like one shown above Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); In the second using LocalSessionFactoryBean LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN); sessionFactoryBean.setHibernateProperties(hibernateProperties()); return sessionFactoryBean; Please suggest which one should ne used arun singh May 3, 2017 at 7:24 pm - Reply Very nice explanation, sir Pooja August 3, 2018 at 6:03 pm - Reply So damn helpful...Solved my nightmare Tim May 2, 2019 at 3:12 am - Reply Should be – SessionFactory sessionFactory = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory : ” + sessionFactory.hashCode()); SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode()); SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode()); ashkan May 13, 2019 at 1:10 pm - Reply many thanks for this tutorial. vicky December 25, 2016 at 9:50 am - Reply nice explanation. nice explanation. Mamta December 29, 2016 at 9:33 am - Reply Please suggest the best way to create Sessionfactory There are many ways like one shown above Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); In the second using LocalSessionFactoryBean LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN); sessionFactoryBean.setHibernateProperties(hibernateProperties()); return sessionFactoryBean; Please suggest which one should ne used Please suggest the best way to create Sessionfactory There are many ways like one shown above Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); In the second using LocalSessionFactoryBean LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN); sessionFactoryBean.setHibernateProperties(hibernateProperties()); return sessionFactoryBean; Please suggest which one should ne used arun singh May 3, 2017 at 7:24 pm - Reply Very nice explanation, sir Very nice explanation, sir Pooja August 3, 2018 at 6:03 pm - Reply So damn helpful...Solved my nightmare So damn helpful...Solved my nightmare Tim May 2, 2019 at 3:12 am - Reply Should be – SessionFactory sessionFactory = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory : ” + sessionFactory.hashCode()); SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode()); SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode()); Should be – SessionFactory sessionFactory = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory : ” + sessionFactory.hashCode()); SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode()); SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory(); System.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode()); ashkan May 13, 2019 at 1:10 pm - Reply many thanks for this tutorial. many thanks for this tutorial. Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 599, "s": 398, "text": "Hibernate SessionFactory is a crucial interface of Hibernate API. It is coming from org.hibernate.SessionFactory package. The main goal of this interface is to provide the Hibernate Session instances." }, { "code": null, "e": 704, "s": 599, "text": "We can get the Hibernate SessionFactory object by calling the buildSessionFactory() method. Like below :" }, { "code": null, "e": 792, "s": 704, "text": "SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();\n" }, { "code": null, "e": 915, "s": 792, "text": "But the buildSessionFactory() method is deprecated from hibernate 4.x version. And it was replaced with the below syntax :" }, { "code": null, "e": 1180, "s": 915, "text": "Configuration configuration = new Configuration().configure();\nStandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());\nSessionFactory factory = configuration.buildSessionFactory(builder.build());\n" }, { "code": null, "e": 1353, "s": 1180, "text": "In the hibernate framework, an only heavy object is a SessionFactory object. Because the SessionFactory builds with all the configuration information about the application." }, { "code": null, "e": 1366, "s": 1353, "text": "Like below :" }, { "code": null, "e": 1449, "s": 1366, "text": "Configuration configuration = new Configuration().configure(\"hibernate.cfg.xml\");\n" }, { "code": null, "e": 1506, "s": 1449, "text": "Recommended: The Complete CRUD Application of Hibernate." }, { "code": null, "e": 1909, "s": 1506, "text": "So that in Hibernate SessionFactory, a configuration file and all the mapping data will be stored. In real time applications like spring with hibernate integration, per each client request if a separate SessionFactory is created then the performance of the application will be reduced. To improve the performance of an application, we need to make the Hibernate SessionFactory ‘s object as a singleton." }, { "code": null, "e": 2097, "s": 1909, "text": "To implement the Hibernate SessionFactory as a singleton, we create a separate class. Because this class is only responsible for making the Hibernate SessionFactory object as a singleton." }, { "code": null, "e": 2305, "s": 2097, "text": "Usually, we call such type of classes as utility classes. In that utility class, we define a static factory method to a Hibernate SessionFactory object for one time and return the same factory object always." }, { "code": null, "e": 2598, "s": 2305, "text": "Since the utility class is only responsible for creating the singleton Hibernate SessionFactory object and returning that object, there is no need for creating an object for utility class. To disallow to creating objects by other classes, we can make the utility class constructor as private." }, { "code": null, "e": 3201, "s": 2598, "text": "package com.onlinetutorialspoint.config;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class HibernateUtility {\n\n public static SessionFactory factory;\n//to disallow creating objects by other classes.\n\n private HibernateUtility() {\n }\n//maling the Hibernate SessionFactory object as singleton\n\n public static synchronized SessionFactory getSessionFactory() {\n\n if (factory == null) {\n factory = new Configuration().configure(\"hibernate.cfg.xml\").\n buildSessionFactory();\n }\n return factory;\n }\n}\n" }, { "code": null, "e": 3211, "s": 3201, "text": "Main.java" }, { "code": null, "e": 3870, "s": 3211, "text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.config.HibernateUtility;\nimport org.hibernate.SessionFactory;\n\npublic class Main {\n public static void main(String[] args) {\n SessionFactory sessionFactory = HibernateUtility.getSessionFactory();\n System.out.println(\"Session Factory : \" + sessionFactory.hashCode());\n SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();\n System.out.println(\"Session Factory 2 : \" + sessionFactory2.hashCode());\n SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();\n System.out.println(\"Session Factory 3 : \" + sessionFactory3.hashCode());\n }\n}" }, { "code": null, "e": 3963, "s": 3870, "text": "Session Factory : 1574615832 \nSession Factory 2 : 1574615832 \nSession Factory 3 : 1574615832" }, { "code": null, "e": 4204, "s": 3963, "text": "On the above example, we declared the factory method with the synchronised keyword. Because in case, if the two threads call factory method precisely at the same time, then there is a chance of creating two Hibernate SessionFactory objects." }, { "code": null, "e": 4501, "s": 4204, "text": "So, it is recommended to make the factory method as a synchronised method. And also we can find the same hashcode for all SessionFactory creations. Then we can say that our application will generate only single Hibernate SessionFactory instance and serve that instance for different client calls." }, { "code": null, "e": 4518, "s": 4501, "text": "Happy Learning 🙂" }, { "code": null, "e": 5092, "s": 4518, "text": "\nhibernate update query example\nHibernate Left Join Example\nHibernate session differences between load() and get()\nCustom Generator Class in Hibernate\nHibernate Filter Example Xml Configuration\nHibernate Native SQL Query Example\nHibernate Named Query with Example\nHibernate Right Join Example\nWhat is Hibernate\nHibernate 4 Example with Annotations Mysql\nTop 10 Advantages of Hibernate\nDifferent types of Object States in Hibernate\nDifference between update vs merge in Hibernate example\nHibernate cache first level example\nTable per Class Strategy in Hibernate Inheritance\n" }, { "code": null, "e": 5123, "s": 5092, "text": "hibernate update query example" }, { "code": null, "e": 5151, "s": 5123, "text": "Hibernate Left Join Example" }, { "code": null, "e": 5206, "s": 5151, "text": "Hibernate session differences between load() and get()" }, { "code": null, "e": 5242, "s": 5206, "text": "Custom Generator Class in Hibernate" }, { "code": null, "e": 5285, "s": 5242, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 5320, "s": 5285, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 5355, "s": 5320, "text": "Hibernate Named Query with Example" }, { "code": null, "e": 5384, "s": 5355, "text": "Hibernate Right Join Example" }, { "code": null, "e": 5402, "s": 5384, "text": "What is Hibernate" }, { "code": null, "e": 5445, "s": 5402, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 5476, "s": 5445, "text": "Top 10 Advantages of Hibernate" }, { "code": null, "e": 5522, "s": 5476, "text": "Different types of Object States in Hibernate" }, { "code": null, "e": 5578, "s": 5522, "text": "Difference between update vs merge in Hibernate example" }, { "code": null, "e": 5614, "s": 5578, "text": "Hibernate cache first level example" }, { "code": null, "e": 5664, "s": 5614, "text": "Table per Class Strategy in Hibernate Inheritance" }, { "code": null, "e": 7263, "s": 5664, "text": "\n\n\n\n\n\nvicky\nDecember 25, 2016 at 9:50 am - Reply \n\nnice explanation.\n\n\n\n\n\n\n\n\n\nMamta\nDecember 29, 2016 at 9:33 am - Reply \n\nPlease suggest the best way to create Sessionfactory\nThere are many ways like one shown above\nConfiguration configuration = new Configuration().configure();\nStandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());\nSessionFactory factory = configuration.buildSessionFactory(builder.build());\nIn the\n second using LocalSessionFactoryBean\nLocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();\nsessionFactoryBean.setDataSource(dataSource());\nsessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);\nsessionFactoryBean.setHibernateProperties(hibernateProperties());\nreturn sessionFactoryBean;\nPlease suggest which one should ne used\n\n\n\n\n\n\n\n\n\narun singh\nMay 3, 2017 at 7:24 pm - Reply \n\nVery nice explanation, sir\n\n\n\n\n\n\n\n\n\nPooja\nAugust 3, 2018 at 6:03 pm - Reply \n\nSo damn helpful...Solved my nightmare\n\n\n\n\n\n\n\n\n\nTim\nMay 2, 2019 at 3:12 am - Reply \n\nShould be – \n SessionFactory sessionFactory = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory : ” + sessionFactory.hashCode());\nSessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode());\nSessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode());\n\n\n\n\n\n\n\n\n\nashkan\nMay 13, 2019 at 1:10 pm - Reply \n\nmany thanks for this tutorial.\n\n\n\n\n" }, { "code": null, "e": 7335, "s": 7263, "text": "\n\n\n\n\nvicky\nDecember 25, 2016 at 9:50 am - Reply \n\nnice explanation.\n\n\n\n" }, { "code": null, "e": 7353, "s": 7335, "text": "nice explanation." }, { "code": null, "e": 8138, "s": 7353, "text": "\n\n\n\n\nMamta\nDecember 29, 2016 at 9:33 am - Reply \n\nPlease suggest the best way to create Sessionfactory\nThere are many ways like one shown above\nConfiguration configuration = new Configuration().configure();\nStandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());\nSessionFactory factory = configuration.buildSessionFactory(builder.build());\nIn the\n second using LocalSessionFactoryBean\nLocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();\nsessionFactoryBean.setDataSource(dataSource());\nsessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);\nsessionFactoryBean.setHibernateProperties(hibernateProperties());\nreturn sessionFactoryBean;\nPlease suggest which one should ne used\n\n\n\n" }, { "code": null, "e": 8191, "s": 8138, "text": "Please suggest the best way to create Sessionfactory" }, { "code": null, "e": 8233, "s": 8191, "text": "There are many ways like one shown above" }, { "code": null, "e": 8504, "s": 8233, "text": "Configuration configuration = new Configuration().configure();\nStandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());\nSessionFactory factory = configuration.buildSessionFactory(builder.build());\nIn the" }, { "code": null, "e": 8542, "s": 8504, "text": " second using LocalSessionFactoryBean" }, { "code": null, "e": 8829, "s": 8542, "text": "LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();\nsessionFactoryBean.setDataSource(dataSource());\nsessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);\nsessionFactoryBean.setHibernateProperties(hibernateProperties());\nreturn sessionFactoryBean;" }, { "code": null, "e": 8869, "s": 8829, "text": "Please suggest which one should ne used" }, { "code": null, "e": 8949, "s": 8869, "text": "\n\n\n\n\narun singh\nMay 3, 2017 at 7:24 pm - Reply \n\nVery nice explanation, sir\n\n\n\n" }, { "code": null, "e": 8976, "s": 8949, "text": "Very nice explanation, sir" }, { "code": null, "e": 9065, "s": 8976, "text": "\n\n\n\n\nPooja\nAugust 3, 2018 at 6:03 pm - Reply \n\nSo damn helpful...Solved my nightmare\n\n\n\n" }, { "code": null, "e": 9103, "s": 9065, "text": "So damn helpful...Solved my nightmare" }, { "code": null, "e": 9593, "s": 9103, "text": "\n\n\n\n\nTim\nMay 2, 2019 at 3:12 am - Reply \n\nShould be – \n SessionFactory sessionFactory = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory : ” + sessionFactory.hashCode());\nSessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode());\nSessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode());\n\n\n\n" }, { "code": null, "e": 9608, "s": 9593, "text": "Should be – " }, { "code": null, "e": 9749, "s": 9608, "text": " SessionFactory sessionFactory = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory : ” + sessionFactory.hashCode());" }, { "code": null, "e": 9893, "s": 9749, "text": "SessionFactory sessionFactory2 = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory 2 : ” + sessionFactory2.hashCode());" }, { "code": null, "e": 10037, "s": 9893, "text": "SessionFactory sessionFactory3 = HibernateUtility.getSessionFactory();\nSystem.out.println(“Session Factory 3 : ” + sessionFactory3.hashCode());" }, { "code": null, "e": 10118, "s": 10037, "text": "\n\n\n\n\nashkan\nMay 13, 2019 at 1:10 pm - Reply \n\nmany thanks for this tutorial.\n\n\n\n" }, { "code": null, "e": 10149, "s": 10118, "text": "many thanks for this tutorial." }, { "code": null, "e": 10155, "s": 10153, "text": "Δ" }, { "code": null, "e": 10181, "s": 10155, "text": " Hibernate – Introduction" }, { "code": null, "e": 10205, "s": 10181, "text": " Hibernate – Advantages" }, { "code": null, "e": 10237, "s": 10205, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 10267, "s": 10237, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 10297, "s": 10267, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 10335, "s": 10297, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 10362, "s": 10335, "text": " Hibernate – Object States" }, { "code": null, "e": 10400, "s": 10362, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 10438, "s": 10400, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 10488, "s": 10438, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 10518, "s": 10488, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 10557, "s": 10518, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 10597, "s": 10557, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 10628, "s": 10597, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 10663, "s": 10628, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 10688, "s": 10663, "text": " Hibernate – Named Query" }, { "code": null, "e": 10718, "s": 10688, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 10747, "s": 10718, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 10784, "s": 10747, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 10810, "s": 10784, "text": " Hibernate – Restrictions" }, { "code": null, "e": 10834, "s": 10810, "text": " Hibernate – Projection" }, { "code": null, "e": 10868, "s": 10834, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 10902, "s": 10868, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 10932, "s": 10902, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 10965, "s": 10932, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 10997, "s": 10965, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 11023, "s": 10997, "text": " Hibernate – Update Query" }, { "code": null, "e": 11052, "s": 11023, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 11076, "s": 11052, "text": " Hibernate – Right Join" }, { "code": null, "e": 11099, "s": 11076, "text": " Hibernate – Left Join" }, { "code": null, "e": 11123, "s": 11099, "text": " Hibernate – Pagination" }, { "code": null, "e": 11154, "s": 11123, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 11184, "s": 11154, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 11218, "s": 11184, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 11247, "s": 11218, "text": " Hibernate – Table per Class" }, { "code": null, "e": 11280, "s": 11247, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 11318, "s": 11280, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 11360, "s": 11318, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 11391, "s": 11360, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 11424, "s": 11391, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 11462, "s": 11424, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 11487, "s": 11462, "text": " Hibernate – Interceptor" }, { "code": null, "e": 11533, "s": 11487, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
Develop and sell a Machine Learning app — from start to end tutorial | by Daniel Deutsch | Towards Data Science
After developing and selling a Python API, I now want to expand the idea with a machine learning solution. So I decided to quickly write a COVID-19 prediction algorithm, deploy it, and make it sellable. If you want to see how I did it, check out the post for a step by step tutorial. About this article Disclaimer Stack used 1. Create project formalities 2. Develop a solution for a problem Install packages and track jupyter files properly Develop solution to problem Build server to execute function with REST BONUS: Make reproducible with Docker 3. Deploy to AWS Set up zappa Set up AWS 4. Set up Rapidapi End result Inspiration Final links About In this article, I take the ideas from my previous article “How to sell a Python API from start to end” further and build a machine learning application. If the steps described here are too rough consider reading my previous article first. There are a number of new and more complicated issues to cover in this project: Machine Learning content. The application takes basic steps of building a Machine Learning model. This covers the preparation, but also the prediction.In time evaluation (not in time training) of the prediction. This means that the dataset is freshly fetched and the prediction is performed on the latest data.Deployment. Deploying a Machine Learning app has various challenges. In this article, we met and solved the issue of outsourcing the trained model on AWS.It is not only an API but also has a minor frontend. Machine Learning content. The application takes basic steps of building a Machine Learning model. This covers the preparation, but also the prediction. In time evaluation (not in time training) of the prediction. This means that the dataset is freshly fetched and the prediction is performed on the latest data. Deployment. Deploying a Machine Learning app has various challenges. In this article, we met and solved the issue of outsourcing the trained model on AWS. It is not only an API but also has a minor frontend. It paints a picture for developing a Python API from start to finish and provides help in more difficult areas like the setup with AWS Lambda. There were various difficulties, which allowed me to learn more about the deployment and building process. It is also a great way to build side projects and maybe even make some money. As the Table of content shows, it consists of 4 major parts, namely: Setting up the environmentCreating a problem solution with PythonSetting up AWSSetting up Rapidapi Setting up the environment Creating a problem solution with Python Setting up AWS Setting up Rapidapi You will find all my code open on Github: https://github.com/Createdd/ml_api_covid You will find the end result here on Rapidapi: https://rapidapi.com/Createdd/api/covid_new_cases_prediction I am not associated with any of the services I use in this article. I do not consider myself an expert. If you have the feeling that I am missing important steps or neglected something, consider pointing it out in the comment section or get in touch with me. Also, always make sure to monitor your AWS costs to not pay for things you do not know about. I am always happy for constructive input and how to improve. There are numerous things to improve and build upon. For example, the machine learning part has a very low effort. The preparation was very rough and many steps are missing. From my professional work, I am aware of this fact. However, I cannot cover every detail in one article. Nevertheless, I am curious to hear your suggestions on improvement in the comments. :) If you need more information on certain parts, feel free to point it out in the comments. I consider this as a step by step tutorial. However, as I am already too long working as a developer, I assume some knowledge of certain tools. This makes the tutorial probably an intermediate/advanced app. I assume knowledge of: Python Git Jupyter Notebook Terminal/Shell/Unix commands We will use Github (Code hosting), Anaconda (Dependency and environment management), Docker (for possible further usage in microservices) Jupyter Notebook (code development and documentation), Python (programming language), AWS, especially AWS Lambda and S3(for deployment), Rapidapi (market to sell) It’s always the same but necessary. I do it along with these steps: Create a local folder mkdir NAMECreate a new repository on Github with NAMECreate conda environment conda create --name NAME python=3.7Activate conda environment conda activate PATH_TO_ENVIRONMENTCreate git repo git initConnect to Github repo. Add Readme file, commit it and Create a local folder mkdir NAME Create a new repository on Github with NAME Create conda environment conda create --name NAME python=3.7 Activate conda environment conda activate PATH_TO_ENVIRONMENT Create git repo git init Connect to Github repo. Add Readme file, commit it and git remote add origin URL_TO_GIT_REPOgit push -u origin master Install packages and track jupyter files properly Develop solution to problem Build server to execute function with REST BONUS: Make reproducible with Docker As we will develop a Machine Learning solution, a Jupyter Notebook will be very useful. Install jupyter notebook and jupytext: pip install notebook jupytext Register new environment in jupyter ipython kernel install --name NAME--user Set a hook in .git/hooks/pre-commit for tracking the notebook changes in git properly: touch .git/hooks/pre-commitcode .git/hooks/pre-commit copy this in the file #!/bin/sh# For every ipynb file in the git index, add a Python representationjupytext --from ipynb --to py:light --pre-commit afterward for making the hook executable (on mac) chmod +x .git/hooks/pre-commit As currently, the world is in a pandemic I thought I use one of the multiple datasets for Covid-19 cases. Given the structure of the dataset, we want to predict the new cases of infections per day for a country. pip install -r requirements.txt This will install all packages we need. Have a look in the /development/predict_covid.ipynb notebook to see what libraries are used. Most important are the libraries pandas for transforming the dataset and sklearn for machine learning For the following subheadings please check out the Jupyter notebook for more details: https://github.com/Createdd/ml_api_covid/blob/master/development/predict_covid.ipynb We will use the dataset from https://ourworldindata.org/coronavirus-source-data in csv format. The license of data is Attribution 4.0 International (CC BY 4.0) Source code available on Github In short, I did: Check for missing dataRemove columns with more than 50% missing dataRemove rows with remaining missing content like continent or isocode. (Not useful for my app solution which requires a country)Encode categorical data with labelsFill in the remaining numerical missing data with the mean of the columnSplit into training and test set Check for missing data Remove columns with more than 50% missing data Remove rows with remaining missing content like continent or isocode. (Not useful for my app solution which requires a country) Encode categorical data with labels Fill in the remaining numerical missing data with the mean of the column Split into training and test set Create a Random Forest RegressorTrain it on the data and evaluatePerform hyperparameter tuning with RandomizedSearchCVSave the trained modelPredict the new cases by providing a country name Create a Random Forest Regressor Train it on the data and evaluate Perform hyperparameter tuning with RandomizedSearchCV Save the trained model Predict the new cases by providing a country name For the API functionality, we will use a Flask server (in app.py) https://github.com/Createdd/ml_api_covid/blob/master/app.py @app.route('/')def home(): return render_template("home.html") Which serves a basic HTML and CSS file. This is a little more complex. The key route is this: But before we can return the prediction result we need to get the latest data and pre-process it again. This is done with Pre-process again transforms the downloaded dataset for machine learning purposes, whereas get_prediction_params takes the input value (which is the country to be predicted) and the URL to the latest dataset. Those processes make the prediction true for the latest data but also slows down the app. You might wonder why we do rf = load_model(BUCKET_NAME, MODEL_FILE_NAME, MODEL_LOCAL_PATH). The reason for this is that we need to load the pre-trained model from an AWS S3 bucket to save memory when executing everything with AWS Lambda. Scroll down for more details. But if we do not want to deploy it in the cloud we can simply do something like joblib.load(PATH_TO_YOUR_EXPORTED_MODEL). In the notebook, we export the model with joblib.dump. More info on model exports in the sklearn docs But that is the mere functionality of the FLAK server. Providing a route for serving the HTML template and a route for prediction. Quite simple! Running now env FLASK_APP=app.py FLASK_ENV=development flask run will start the server. Maybe you want to scale the app or allow other people to test it more easily. For this, we can create a Docker container. I will not explain in detail how it works but if you are interested check one of the links in my “Inspiration” section. Building a Docker container is not necessary for making this application work! FROM python:3.7ENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1ENV FLASK_APP=app.pyENV FLASK_ENV=development# install system dependenciesRUN apt-get update \ && apt-get -y install gcc make \ && rm -rf /var/lib/apt/lists/*sRUN python3 --versionRUN pip3 --versionRUN pip install --no-cache-dir --upgrade pipWORKDIR /appCOPY ./requirements.txt /app/requirements.txtRUN pip3 install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 8080CMD ["gunicorn", "--bind", "0.0.0.0:8080", "app:app"] Note: the last line is for starting the Flask server After creating the Dockerfile run docker build -t YOUR_APP_NAME . and afterward docker run -d -p 80:8080 YOUR_APP_NAME Afterward, you will see your app running on http://localhost/ Set up zappa Set up AWS AWS credentials Deploy AWS API Gateway — restrict access Until now this was a rather easy path. Nothing too complicated, nothing too fancy. Now that we come to deployment it gets interesting and challenging. Again, I would strongly encourage you to check out my previous article https://towardsdatascience.com/develop-and-sell-a-python-api-from-start-to-end-tutorial-9a038e433966 if you have any issues with Zappa and AWS. I will not go so much in detail here anymore but rather point out pain points. After we created the app locally we need to start setting up the hosting on a real server. We will use zappa. Zappa makes it super easy to build and deploy server-less, event-driven Python applications (including, but not limited to, WSGI web apps) on AWS Lambda + API Gateway. Think of it as “serverless” web hosting for your Python apps. That means infinite scaling, zero downtime, zero maintenance — and at a fraction of the cost of your current deployments! pip install zappa As we are using a conda environment we need to specify it: which python will give you /Users/XXX/opt/anaconda3/envs/XXXX/bin/python (for Mac) remove the bin/python/ and export export VIRTUAL_ENV=/Users/XXXX/opt/anaconda3/envs/XXXXX/ Now we can do zappa init to set up the config. Just click through everything and you will have a zappa_settings.json like { "dev": { "app_function": "app.app", "aws_region": "eu-central-1", "profile_name": "default", "project_name": "ml-api-covid", "runtime": "python3.7", "s3_bucket": "zappa-eyy4wkd2l", "slim_handler": true, "exclude": [ "*.joblib", "development", "models" ] }} NOTA BENE! Do not enter a name for the s3 bucket as it cannot be found. I really don’t know what the problem with naming your s3 bucket is, but it never worked. There were multiple error statements and I could not resolve this. Just leave the suggested one and everything works fine. ;) Note that we are NOT yet ready to deploy. First, we need to get some AWS credentials. Note: This takes quite some effort. Do not be discouraged by the complexity of AWS and its policy management. First, you need te get an AWS access key id and access key I break it down as simple as possible: Within the AWS Console, type IAM into the search box. IAM is the AWS user and permissions dashboard.Create a groupGive your group a name (for example zappa_group)Create our own specific inline policy for your groupIn the Permissions tab, under the Inline Policies section, choose the link to create a new Inline PolicyIn the Set Permissions screen, click the Custom Policy radio button and click the “Select” button on the right.Create a Custom Policy written in json formatRead through and copy a policy discussed here: https://github.com/Miserlou/Zappa/issues/244Scroll down to “My Custom policy” see a snippet of my policy.After pasting and modifying the json with your AWS Account Number, click the “Validate Policy” button to ensure you copied valid json. Then click the “Apply Policy” button to attach the inline policy to the group.Create a user and add the user to the groupBack at the IAM Dashboard, create a new user with the “Users” left-hand menu option and the “Add User” button.In the Add user screen, give your new user a name and select the Access Type for Programmatic access. Then click the “Next: Permissions” button.In the Set permissions screen, select the group you created earlier in the Add user to group section and click “Next: Tags”.Tags are optional. Add tags if you want, then click “Next: Review”.Review the user details and click “Create user”Copy the user’s keysDon’t close the AWS IAM window yet. In the next step, you will copy and paste these keys into a file. At this point, it’s not a bad idea to copy and save these keys into a text file in a secure location. Make sure you don’t save keys under version control. Within the AWS Console, type IAM into the search box. IAM is the AWS user and permissions dashboard. Create a group Give your group a name (for example zappa_group) Create our own specific inline policy for your group In the Permissions tab, under the Inline Policies section, choose the link to create a new Inline Policy In the Set Permissions screen, click the Custom Policy radio button and click the “Select” button on the right. Create a Custom Policy written in json format Read through and copy a policy discussed here: https://github.com/Miserlou/Zappa/issues/244 Scroll down to “My Custom policy” see a snippet of my policy. After pasting and modifying the json with your AWS Account Number, click the “Validate Policy” button to ensure you copied valid json. Then click the “Apply Policy” button to attach the inline policy to the group. Create a user and add the user to the group Back at the IAM Dashboard, create a new user with the “Users” left-hand menu option and the “Add User” button. In the Add user screen, give your new user a name and select the Access Type for Programmatic access. Then click the “Next: Permissions” button. In the Set permissions screen, select the group you created earlier in the Add user to group section and click “Next: Tags”. Tags are optional. Add tags if you want, then click “Next: Review”. Review the user details and click “Create user” Copy the user’s keys Don’t close the AWS IAM window yet. In the next step, you will copy and paste these keys into a file. At this point, it’s not a bad idea to copy and save these keys into a text file in a secure location. Make sure you don’t save keys under version control. My Custom policy: As you can see in the policy, I added S3 related policies. This is because we want to download our pre-trained model from S3. More Infos on that later. Create a .aws/credentials folder in your root with mkdir ~/.awscode ~/.aws/credentials and paste your credentials from AWS [dev]aws_access_key_id = YOUR_KEYaws_secret_access_key = YOUR_KEY Same with the config code ~/.aws/config# and add:[default]region = YOUR_REGION (eg. eu-central-1) Note that code is for opening a folder with vscode, my editor of choice. Save the AWS access key id and secret access key assigned to the user you created in the file ~/.aws/credentials. Note the .aws/ directory needs to be in your home directory and the credentials file has no file extension. Now you can do deploy your API with zappa deploy dev However, there are a few things to consider: Zappa will pack your entire environment and whole root content. This will be quite large.There is an upload limit for AWS Lambda Zappa will pack your entire environment and whole root content. This will be quite large. There is an upload limit for AWS Lambda There are several discussions on how to reduce the upload size with zappa. Check out the Inspiration section for links. First, we need to reduce the package size for the upload. We will put all exploratory content into an own folder. I named it “development”. Afterwards, you can specify excluded files and folder in zappa_settings.json with exclude: { "dev": { ... "slim_handler": true, "exclude": [ "*.ipynb", "*.joblib", "jupytext_conversion/", ".ipynb_checkpoints/", "predict_covid.ipynb", "development", "models" ] }} You can add everything that doesn’t need to be packaged for deployment. Another issue is the environment dependencies. In our case, we have multiple dependencies, which we don’t need for deployment. To solve this I created a new “requirements_prod.txt” file. This shall only have dependencies which are needed on AWS. Make sure to export your current packages with pip freeze > requirements.txt Afterward, uninstall all packages pip uninstall -r requirements.txt -y Install new packages for deployment and save them in the file pip install Flask pandas boto3 sklearn zappapip freeze > requirements_prod.txt When you hit zappa deploy dev there should be considerably less size to package. You will note that I also set slim_handler=true. This allows us to upload more than 50MB. Behind the scenes, zappa already puts content into an own S3 bucket. Read the zappa docs for more info. Since we excluded our model from the AWS Lambda upload we need to get the model from somewhere else. We will use a AWS S3 Bucket. During the development process, I tried to upload it there programmatically as well but I just uploaded it by hand as it was just faster now. (But you can still try to upload it — I still have an outcommented file in the repo) Go to https://console.aws.amazon.com/s3/ “create bucket”give a name and leave rest as default. check for sufficient permissions.“create bucket” “create bucket” give a name and leave rest as default. check for sufficient permissions. “create bucket” check if you have a sufficient policy for interacting with the bucket and boto3. You should have something similar to { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:ListAllMyBuckets", "s3:GetObject" ], "Resource": [ "arn:aws:s3:::zappa-*", "arn:aws:s3:::*" ] } Finally, there shouldn’t be any errors anymore. However, if there are still some, you can debug with: zappa status# andzappa tail The most common errors are permission related (then check your permission policy) or about python libraries that are incompatible. Either way, zappa will provide good enough error messages for debugging. Top list of errors from my experience are: Policy issues with your user from IAMZappa and size issuesBoto3 and permission/location of files issues Policy issues with your user from IAM Zappa and size issues Boto3 and permission/location of files issues If you update your code don’t forget to update the deployment as well with zappa update dev To set up the API on a market we need to first restrict its usage with an API-key and then set it up on the market platform. To break it down: go to your AWS Console and go to API gatewayclick on your APIwe want to create an x-api-key to restrict undesired access to the API and also have a metered usagecreate a Usage plan for the API, with the desired throttle and quota limitscreate an associated API stageadd an API keyin the API key overview section, click “show” at the API key and copy itthen associate the API with the key and discard all requests that come without the keygo back to the API overview. under resources, click the “/ any” go to the “method request”. then in settings, set “API key required” to truedo the same for the “/{proxy+} Methods” go to your AWS Console and go to API gateway click on your API we want to create an x-api-key to restrict undesired access to the API and also have a metered usage create a Usage plan for the API, with the desired throttle and quota limits create an associated API stage add an API key in the API key overview section, click “show” at the API key and copy it then associate the API with the key and discard all requests that come without the key go back to the API overview. under resources, click the “/ any” go to the “method request”. then in settings, set “API key required” to true do the same for the “/{proxy+} Methods” Now you have restricted access to your API. Add new API Test endpoint with rapidapi Create code to consume API I will not go into detail in this article anymore. Again, check my previous https://towardsdatascience.com/develop-and-sell-a-python-api-from-start-to-end-tutorial-9a038e433966 for setting everything up. There is no big difference in my new machine learning model. https://rapidapi.com/Createdd/api/covid_new_cases_prediction My main motivation this time came from Moez Ali, who provides great articles on deploying machine learning systems. I also enjoy following him on social media. I can recommend his articles: https://towardsdatascience.com/build-and-deploy-your-first-machine-learning-web-app-e020db344a99 https://towardsdatascience.com/deploy-machine-learning-pipeline-on-aws-fargate-eb6e1c50507 Also François Marceau with https://towardsdatascience.com/how-to-deploy-a-machine-learning-model-on-aws-lambda-24c36dcaed20 https://github.com/Miserlou/Zappa/issues/1927 Package Error: python-dateutil https://stackabuse.com/file-management-with-aws-s3-python-and-flask/ https://ianwhitestone.work/zappa-zip-callbacks/ remove unnecessary files in zappa https://stackoverflow.com/questions/62941174/how-to-write-load-machine-learning-model-to-from-s3-bucket-through-joblib https://www.freecodecamp.org/news/what-we-learned-by-serving-machine-learning-models-using-aws-lambda-c70b303404a1/ https://ianwhitestone.work/slides/serverless-meetup-feb-2020.html https://read.iopipe.com/the-right-way-to-do-serverless-in-python-e99535574454 https://www.bluematador.com/blog/serverless-in-aws-lambda-vs-fargate aws lambda vs fargate https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html billing alarm Open source code: https://github.com/Createdd/ml_api_covid On Rapidapi: https://rapidapi.com/Createdd/api/covid_new_cases_prediction Daniel is an entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court. His knowledge and interests currently revolve around programming machine learning applications and all their related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects. Don’t hesitate to get in touch if you have ideas, projects, or problems.
[ { "code": null, "e": 331, "s": 47, "text": "After developing and selling a Python API, I now want to expand the idea with a machine learning solution. So I decided to quickly write a COVID-19 prediction algorithm, deploy it, and make it sellable. If you want to see how I did it, check out the post for a step by step tutorial." }, { "code": null, "e": 350, "s": 331, "text": "About this article" }, { "code": null, "e": 361, "s": 350, "text": "Disclaimer" }, { "code": null, "e": 372, "s": 361, "text": "Stack used" }, { "code": null, "e": 402, "s": 372, "text": "1. Create project formalities" }, { "code": null, "e": 438, "s": 402, "text": "2. Develop a solution for a problem" }, { "code": null, "e": 488, "s": 438, "text": "Install packages and track jupyter files properly" }, { "code": null, "e": 516, "s": 488, "text": "Develop solution to problem" }, { "code": null, "e": 559, "s": 516, "text": "Build server to execute function with REST" }, { "code": null, "e": 596, "s": 559, "text": "BONUS: Make reproducible with Docker" }, { "code": null, "e": 613, "s": 596, "text": "3. Deploy to AWS" }, { "code": null, "e": 626, "s": 613, "text": "Set up zappa" }, { "code": null, "e": 637, "s": 626, "text": "Set up AWS" }, { "code": null, "e": 656, "s": 637, "text": "4. Set up Rapidapi" }, { "code": null, "e": 667, "s": 656, "text": "End result" }, { "code": null, "e": 679, "s": 667, "text": "Inspiration" }, { "code": null, "e": 691, "s": 679, "text": "Final links" }, { "code": null, "e": 697, "s": 691, "text": "About" }, { "code": null, "e": 937, "s": 697, "text": "In this article, I take the ideas from my previous article “How to sell a Python API from start to end” further and build a machine learning application. If the steps described here are too rough consider reading my previous article first." }, { "code": null, "e": 1017, "s": 937, "text": "There are a number of new and more complicated issues to cover in this project:" }, { "code": null, "e": 1534, "s": 1017, "text": "Machine Learning content. The application takes basic steps of building a Machine Learning model. This covers the preparation, but also the prediction.In time evaluation (not in time training) of the prediction. This means that the dataset is freshly fetched and the prediction is performed on the latest data.Deployment. Deploying a Machine Learning app has various challenges. In this article, we met and solved the issue of outsourcing the trained model on AWS.It is not only an API but also has a minor frontend." }, { "code": null, "e": 1686, "s": 1534, "text": "Machine Learning content. The application takes basic steps of building a Machine Learning model. This covers the preparation, but also the prediction." }, { "code": null, "e": 1846, "s": 1686, "text": "In time evaluation (not in time training) of the prediction. This means that the dataset is freshly fetched and the prediction is performed on the latest data." }, { "code": null, "e": 2001, "s": 1846, "text": "Deployment. Deploying a Machine Learning app has various challenges. In this article, we met and solved the issue of outsourcing the trained model on AWS." }, { "code": null, "e": 2054, "s": 2001, "text": "It is not only an API but also has a minor frontend." }, { "code": null, "e": 2197, "s": 2054, "text": "It paints a picture for developing a Python API from start to finish and provides help in more difficult areas like the setup with AWS Lambda." }, { "code": null, "e": 2382, "s": 2197, "text": "There were various difficulties, which allowed me to learn more about the deployment and building process. It is also a great way to build side projects and maybe even make some money." }, { "code": null, "e": 2451, "s": 2382, "text": "As the Table of content shows, it consists of 4 major parts, namely:" }, { "code": null, "e": 2550, "s": 2451, "text": "Setting up the environmentCreating a problem solution with PythonSetting up AWSSetting up Rapidapi" }, { "code": null, "e": 2577, "s": 2550, "text": "Setting up the environment" }, { "code": null, "e": 2617, "s": 2577, "text": "Creating a problem solution with Python" }, { "code": null, "e": 2632, "s": 2617, "text": "Setting up AWS" }, { "code": null, "e": 2652, "s": 2632, "text": "Setting up Rapidapi" }, { "code": null, "e": 2694, "s": 2652, "text": "You will find all my code open on Github:" }, { "code": null, "e": 2735, "s": 2694, "text": "https://github.com/Createdd/ml_api_covid" }, { "code": null, "e": 2782, "s": 2735, "text": "You will find the end result here on Rapidapi:" }, { "code": null, "e": 2843, "s": 2782, "text": "https://rapidapi.com/Createdd/api/covid_new_cases_prediction" }, { "code": null, "e": 2911, "s": 2843, "text": "I am not associated with any of the services I use in this article." }, { "code": null, "e": 3196, "s": 2911, "text": "I do not consider myself an expert. If you have the feeling that I am missing important steps or neglected something, consider pointing it out in the comment section or get in touch with me. Also, always make sure to monitor your AWS costs to not pay for things you do not know about." }, { "code": null, "e": 3257, "s": 3196, "text": "I am always happy for constructive input and how to improve." }, { "code": null, "e": 3623, "s": 3257, "text": "There are numerous things to improve and build upon. For example, the machine learning part has a very low effort. The preparation was very rough and many steps are missing. From my professional work, I am aware of this fact. However, I cannot cover every detail in one article. Nevertheless, I am curious to hear your suggestions on improvement in the comments. :)" }, { "code": null, "e": 3713, "s": 3623, "text": "If you need more information on certain parts, feel free to point it out in the comments." }, { "code": null, "e": 3920, "s": 3713, "text": "I consider this as a step by step tutorial. However, as I am already too long working as a developer, I assume some knowledge of certain tools. This makes the tutorial probably an intermediate/advanced app." }, { "code": null, "e": 3943, "s": 3920, "text": "I assume knowledge of:" }, { "code": null, "e": 3950, "s": 3943, "text": "Python" }, { "code": null, "e": 3954, "s": 3950, "text": "Git" }, { "code": null, "e": 3971, "s": 3954, "text": "Jupyter Notebook" }, { "code": null, "e": 4000, "s": 3971, "text": "Terminal/Shell/Unix commands" }, { "code": null, "e": 4012, "s": 4000, "text": "We will use" }, { "code": null, "e": 4035, "s": 4012, "text": "Github (Code hosting)," }, { "code": null, "e": 4085, "s": 4035, "text": "Anaconda (Dependency and environment management)," }, { "code": null, "e": 4138, "s": 4085, "text": "Docker (for possible further usage in microservices)" }, { "code": null, "e": 4193, "s": 4138, "text": "Jupyter Notebook (code development and documentation)," }, { "code": null, "e": 4224, "s": 4193, "text": "Python (programming language)," }, { "code": null, "e": 4275, "s": 4224, "text": "AWS, especially AWS Lambda and S3(for deployment)," }, { "code": null, "e": 4301, "s": 4275, "text": "Rapidapi (market to sell)" }, { "code": null, "e": 4369, "s": 4301, "text": "It’s always the same but necessary. I do it along with these steps:" }, { "code": null, "e": 4644, "s": 4369, "text": "Create a local folder mkdir NAMECreate a new repository on Github with NAMECreate conda environment conda create --name NAME python=3.7Activate conda environment conda activate PATH_TO_ENVIRONMENTCreate git repo git initConnect to Github repo. Add Readme file, commit it and" }, { "code": null, "e": 4677, "s": 4644, "text": "Create a local folder mkdir NAME" }, { "code": null, "e": 4721, "s": 4677, "text": "Create a new repository on Github with NAME" }, { "code": null, "e": 4782, "s": 4721, "text": "Create conda environment conda create --name NAME python=3.7" }, { "code": null, "e": 4844, "s": 4782, "text": "Activate conda environment conda activate PATH_TO_ENVIRONMENT" }, { "code": null, "e": 4869, "s": 4844, "text": "Create git repo git init" }, { "code": null, "e": 4924, "s": 4869, "text": "Connect to Github repo. Add Readme file, commit it and" }, { "code": null, "e": 4987, "s": 4924, "text": "git remote add origin URL_TO_GIT_REPOgit push -u origin master" }, { "code": null, "e": 5037, "s": 4987, "text": "Install packages and track jupyter files properly" }, { "code": null, "e": 5065, "s": 5037, "text": "Develop solution to problem" }, { "code": null, "e": 5108, "s": 5065, "text": "Build server to execute function with REST" }, { "code": null, "e": 5145, "s": 5108, "text": "BONUS: Make reproducible with Docker" }, { "code": null, "e": 5233, "s": 5145, "text": "As we will develop a Machine Learning solution, a Jupyter Notebook will be very useful." }, { "code": null, "e": 5272, "s": 5233, "text": "Install jupyter notebook and jupytext:" }, { "code": null, "e": 5302, "s": 5272, "text": "pip install notebook jupytext" }, { "code": null, "e": 5379, "s": 5302, "text": "Register new environment in jupyter ipython kernel install --name NAME--user" }, { "code": null, "e": 5466, "s": 5379, "text": "Set a hook in .git/hooks/pre-commit for tracking the notebook changes in git properly:" }, { "code": null, "e": 5521, "s": 5466, "text": "touch .git/hooks/pre-commitcode .git/hooks/pre-commit" }, { "code": null, "e": 5543, "s": 5521, "text": "copy this in the file" }, { "code": null, "e": 5669, "s": 5543, "text": "#!/bin/sh# For every ipynb file in the git index, add a Python representationjupytext --from ipynb --to py:light --pre-commit" }, { "code": null, "e": 5719, "s": 5669, "text": "afterward for making the hook executable (on mac)" }, { "code": null, "e": 5750, "s": 5719, "text": "chmod +x .git/hooks/pre-commit" }, { "code": null, "e": 5962, "s": 5750, "text": "As currently, the world is in a pandemic I thought I use one of the multiple datasets for Covid-19 cases. Given the structure of the dataset, we want to predict the new cases of infections per day for a country." }, { "code": null, "e": 5994, "s": 5962, "text": "pip install -r requirements.txt" }, { "code": null, "e": 6127, "s": 5994, "text": "This will install all packages we need. Have a look in the /development/predict_covid.ipynb notebook to see what libraries are used." }, { "code": null, "e": 6160, "s": 6127, "text": "Most important are the libraries" }, { "code": null, "e": 6200, "s": 6160, "text": "pandas for transforming the dataset and" }, { "code": null, "e": 6229, "s": 6200, "text": "sklearn for machine learning" }, { "code": null, "e": 6315, "s": 6229, "text": "For the following subheadings please check out the Jupyter notebook for more details:" }, { "code": null, "e": 6400, "s": 6315, "text": "https://github.com/Createdd/ml_api_covid/blob/master/development/predict_covid.ipynb" }, { "code": null, "e": 6495, "s": 6400, "text": "We will use the dataset from https://ourworldindata.org/coronavirus-source-data in csv format." }, { "code": null, "e": 6560, "s": 6495, "text": "The license of data is Attribution 4.0 International (CC BY 4.0)" }, { "code": null, "e": 6592, "s": 6560, "text": "Source code available on Github" }, { "code": null, "e": 6609, "s": 6592, "text": "In short, I did:" }, { "code": null, "e": 6944, "s": 6609, "text": "Check for missing dataRemove columns with more than 50% missing dataRemove rows with remaining missing content like continent or isocode. (Not useful for my app solution which requires a country)Encode categorical data with labelsFill in the remaining numerical missing data with the mean of the columnSplit into training and test set" }, { "code": null, "e": 6967, "s": 6944, "text": "Check for missing data" }, { "code": null, "e": 7014, "s": 6967, "text": "Remove columns with more than 50% missing data" }, { "code": null, "e": 7142, "s": 7014, "text": "Remove rows with remaining missing content like continent or isocode. (Not useful for my app solution which requires a country)" }, { "code": null, "e": 7178, "s": 7142, "text": "Encode categorical data with labels" }, { "code": null, "e": 7251, "s": 7178, "text": "Fill in the remaining numerical missing data with the mean of the column" }, { "code": null, "e": 7284, "s": 7251, "text": "Split into training and test set" }, { "code": null, "e": 7474, "s": 7284, "text": "Create a Random Forest RegressorTrain it on the data and evaluatePerform hyperparameter tuning with RandomizedSearchCVSave the trained modelPredict the new cases by providing a country name" }, { "code": null, "e": 7507, "s": 7474, "text": "Create a Random Forest Regressor" }, { "code": null, "e": 7541, "s": 7507, "text": "Train it on the data and evaluate" }, { "code": null, "e": 7595, "s": 7541, "text": "Perform hyperparameter tuning with RandomizedSearchCV" }, { "code": null, "e": 7618, "s": 7595, "text": "Save the trained model" }, { "code": null, "e": 7668, "s": 7618, "text": "Predict the new cases by providing a country name" }, { "code": null, "e": 7734, "s": 7668, "text": "For the API functionality, we will use a Flask server (in app.py)" }, { "code": null, "e": 7794, "s": 7734, "text": "https://github.com/Createdd/ml_api_covid/blob/master/app.py" }, { "code": null, "e": 7860, "s": 7794, "text": "@app.route('/')def home(): return render_template(\"home.html\")" }, { "code": null, "e": 7900, "s": 7860, "text": "Which serves a basic HTML and CSS file." }, { "code": null, "e": 7931, "s": 7900, "text": "This is a little more complex." }, { "code": null, "e": 7954, "s": 7931, "text": "The key route is this:" }, { "code": null, "e": 8076, "s": 7954, "text": "But before we can return the prediction result we need to get the latest data and pre-process it again. This is done with" }, { "code": null, "e": 8285, "s": 8076, "text": "Pre-process again transforms the downloaded dataset for machine learning purposes, whereas get_prediction_params takes the input value (which is the country to be predicted) and the URL to the latest dataset." }, { "code": null, "e": 8375, "s": 8285, "text": "Those processes make the prediction true for the latest data but also slows down the app." }, { "code": null, "e": 8643, "s": 8375, "text": "You might wonder why we do rf = load_model(BUCKET_NAME, MODEL_FILE_NAME, MODEL_LOCAL_PATH). The reason for this is that we need to load the pre-trained model from an AWS S3 bucket to save memory when executing everything with AWS Lambda. Scroll down for more details." }, { "code": null, "e": 8867, "s": 8643, "text": "But if we do not want to deploy it in the cloud we can simply do something like joblib.load(PATH_TO_YOUR_EXPORTED_MODEL). In the notebook, we export the model with joblib.dump. More info on model exports in the sklearn docs" }, { "code": null, "e": 9012, "s": 8867, "text": "But that is the mere functionality of the FLAK server. Providing a route for serving the HTML template and a route for prediction. Quite simple!" }, { "code": null, "e": 9024, "s": 9012, "text": "Running now" }, { "code": null, "e": 9077, "s": 9024, "text": "env FLASK_APP=app.py FLASK_ENV=development flask run" }, { "code": null, "e": 9100, "s": 9077, "text": "will start the server." }, { "code": null, "e": 9342, "s": 9100, "text": "Maybe you want to scale the app or allow other people to test it more easily. For this, we can create a Docker container. I will not explain in detail how it works but if you are interested check one of the links in my “Inspiration” section." }, { "code": null, "e": 9421, "s": 9342, "text": "Building a Docker container is not necessary for making this application work!" }, { "code": null, "e": 9916, "s": 9421, "text": "FROM python:3.7ENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1ENV FLASK_APP=app.pyENV FLASK_ENV=development# install system dependenciesRUN apt-get update \\ && apt-get -y install gcc make \\ && rm -rf /var/lib/apt/lists/*sRUN python3 --versionRUN pip3 --versionRUN pip install --no-cache-dir --upgrade pipWORKDIR /appCOPY ./requirements.txt /app/requirements.txtRUN pip3 install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 8080CMD [\"gunicorn\", \"--bind\", \"0.0.0.0:8080\", \"app:app\"]" }, { "code": null, "e": 9969, "s": 9916, "text": "Note: the last line is for starting the Flask server" }, { "code": null, "e": 10003, "s": 9969, "text": "After creating the Dockerfile run" }, { "code": null, "e": 10035, "s": 10003, "text": "docker build -t YOUR_APP_NAME ." }, { "code": null, "e": 10049, "s": 10035, "text": "and afterward" }, { "code": null, "e": 10088, "s": 10049, "text": "docker run -d -p 80:8080 YOUR_APP_NAME" }, { "code": null, "e": 10150, "s": 10088, "text": "Afterward, you will see your app running on http://localhost/" }, { "code": null, "e": 10163, "s": 10150, "text": "Set up zappa" }, { "code": null, "e": 10174, "s": 10163, "text": "Set up AWS" }, { "code": null, "e": 10190, "s": 10174, "text": "AWS credentials" }, { "code": null, "e": 10197, "s": 10190, "text": "Deploy" }, { "code": null, "e": 10231, "s": 10197, "text": "AWS API Gateway — restrict access" }, { "code": null, "e": 10382, "s": 10231, "text": "Until now this was a rather easy path. Nothing too complicated, nothing too fancy. Now that we come to deployment it gets interesting and challenging." }, { "code": null, "e": 10597, "s": 10382, "text": "Again, I would strongly encourage you to check out my previous article https://towardsdatascience.com/develop-and-sell-a-python-api-from-start-to-end-tutorial-9a038e433966 if you have any issues with Zappa and AWS." }, { "code": null, "e": 10676, "s": 10597, "text": "I will not go so much in detail here anymore but rather point out pain points." }, { "code": null, "e": 10786, "s": 10676, "text": "After we created the app locally we need to start setting up the hosting on a real server. We will use zappa." }, { "code": null, "e": 11138, "s": 10786, "text": "Zappa makes it super easy to build and deploy server-less, event-driven Python applications (including, but not limited to, WSGI web apps) on AWS Lambda + API Gateway. Think of it as “serverless” web hosting for your Python apps. That means infinite scaling, zero downtime, zero maintenance — and at a fraction of the cost of your current deployments!" }, { "code": null, "e": 11156, "s": 11138, "text": "pip install zappa" }, { "code": null, "e": 11215, "s": 11156, "text": "As we are using a conda environment we need to specify it:" }, { "code": null, "e": 11228, "s": 11215, "text": "which python" }, { "code": null, "e": 11298, "s": 11228, "text": "will give you /Users/XXX/opt/anaconda3/envs/XXXX/bin/python (for Mac)" }, { "code": null, "e": 11332, "s": 11298, "text": "remove the bin/python/ and export" }, { "code": null, "e": 11389, "s": 11332, "text": "export VIRTUAL_ENV=/Users/XXXX/opt/anaconda3/envs/XXXXX/" }, { "code": null, "e": 11403, "s": 11389, "text": "Now we can do" }, { "code": null, "e": 11414, "s": 11403, "text": "zappa init" }, { "code": null, "e": 11436, "s": 11414, "text": "to set up the config." }, { "code": null, "e": 11511, "s": 11436, "text": "Just click through everything and you will have a zappa_settings.json like" }, { "code": null, "e": 11850, "s": 11511, "text": "{ \"dev\": { \"app_function\": \"app.app\", \"aws_region\": \"eu-central-1\", \"profile_name\": \"default\", \"project_name\": \"ml-api-covid\", \"runtime\": \"python3.7\", \"s3_bucket\": \"zappa-eyy4wkd2l\", \"slim_handler\": true, \"exclude\": [ \"*.joblib\", \"development\", \"models\" ] }}" }, { "code": null, "e": 12137, "s": 11850, "text": "NOTA BENE! Do not enter a name for the s3 bucket as it cannot be found. I really don’t know what the problem with naming your s3 bucket is, but it never worked. There were multiple error statements and I could not resolve this. Just leave the suggested one and everything works fine. ;)" }, { "code": null, "e": 12223, "s": 12137, "text": "Note that we are NOT yet ready to deploy. First, we need to get some AWS credentials." }, { "code": null, "e": 12333, "s": 12223, "text": "Note: This takes quite some effort. Do not be discouraged by the complexity of AWS and its policy management." }, { "code": null, "e": 12392, "s": 12333, "text": "First, you need te get an AWS access key id and access key" }, { "code": null, "e": 12431, "s": 12392, "text": "I break it down as simple as possible:" }, { "code": null, "e": 14082, "s": 12431, "text": "Within the AWS Console, type IAM into the search box. IAM is the AWS user and permissions dashboard.Create a groupGive your group a name (for example zappa_group)Create our own specific inline policy for your groupIn the Permissions tab, under the Inline Policies section, choose the link to create a new Inline PolicyIn the Set Permissions screen, click the Custom Policy radio button and click the “Select” button on the right.Create a Custom Policy written in json formatRead through and copy a policy discussed here: https://github.com/Miserlou/Zappa/issues/244Scroll down to “My Custom policy” see a snippet of my policy.After pasting and modifying the json with your AWS Account Number, click the “Validate Policy” button to ensure you copied valid json. Then click the “Apply Policy” button to attach the inline policy to the group.Create a user and add the user to the groupBack at the IAM Dashboard, create a new user with the “Users” left-hand menu option and the “Add User” button.In the Add user screen, give your new user a name and select the Access Type for Programmatic access. Then click the “Next: Permissions” button.In the Set permissions screen, select the group you created earlier in the Add user to group section and click “Next: Tags”.Tags are optional. Add tags if you want, then click “Next: Review”.Review the user details and click “Create user”Copy the user’s keysDon’t close the AWS IAM window yet. In the next step, you will copy and paste these keys into a file. At this point, it’s not a bad idea to copy and save these keys into a text file in a secure location. Make sure you don’t save keys under version control." }, { "code": null, "e": 14183, "s": 14082, "text": "Within the AWS Console, type IAM into the search box. IAM is the AWS user and permissions dashboard." }, { "code": null, "e": 14198, "s": 14183, "text": "Create a group" }, { "code": null, "e": 14247, "s": 14198, "text": "Give your group a name (for example zappa_group)" }, { "code": null, "e": 14300, "s": 14247, "text": "Create our own specific inline policy for your group" }, { "code": null, "e": 14405, "s": 14300, "text": "In the Permissions tab, under the Inline Policies section, choose the link to create a new Inline Policy" }, { "code": null, "e": 14517, "s": 14405, "text": "In the Set Permissions screen, click the Custom Policy radio button and click the “Select” button on the right." }, { "code": null, "e": 14563, "s": 14517, "text": "Create a Custom Policy written in json format" }, { "code": null, "e": 14655, "s": 14563, "text": "Read through and copy a policy discussed here: https://github.com/Miserlou/Zappa/issues/244" }, { "code": null, "e": 14717, "s": 14655, "text": "Scroll down to “My Custom policy” see a snippet of my policy." }, { "code": null, "e": 14931, "s": 14717, "text": "After pasting and modifying the json with your AWS Account Number, click the “Validate Policy” button to ensure you copied valid json. Then click the “Apply Policy” button to attach the inline policy to the group." }, { "code": null, "e": 14975, "s": 14931, "text": "Create a user and add the user to the group" }, { "code": null, "e": 15086, "s": 14975, "text": "Back at the IAM Dashboard, create a new user with the “Users” left-hand menu option and the “Add User” button." }, { "code": null, "e": 15231, "s": 15086, "text": "In the Add user screen, give your new user a name and select the Access Type for Programmatic access. Then click the “Next: Permissions” button." }, { "code": null, "e": 15356, "s": 15231, "text": "In the Set permissions screen, select the group you created earlier in the Add user to group section and click “Next: Tags”." }, { "code": null, "e": 15424, "s": 15356, "text": "Tags are optional. Add tags if you want, then click “Next: Review”." }, { "code": null, "e": 15472, "s": 15424, "text": "Review the user details and click “Create user”" }, { "code": null, "e": 15493, "s": 15472, "text": "Copy the user’s keys" }, { "code": null, "e": 15750, "s": 15493, "text": "Don’t close the AWS IAM window yet. In the next step, you will copy and paste these keys into a file. At this point, it’s not a bad idea to copy and save these keys into a text file in a secure location. Make sure you don’t save keys under version control." }, { "code": null, "e": 15768, "s": 15750, "text": "My Custom policy:" }, { "code": null, "e": 15920, "s": 15768, "text": "As you can see in the policy, I added S3 related policies. This is because we want to download our pre-trained model from S3. More Infos on that later." }, { "code": null, "e": 15971, "s": 15920, "text": "Create a .aws/credentials folder in your root with" }, { "code": null, "e": 16007, "s": 15971, "text": "mkdir ~/.awscode ~/.aws/credentials" }, { "code": null, "e": 16043, "s": 16007, "text": "and paste your credentials from AWS" }, { "code": null, "e": 16109, "s": 16043, "text": "[dev]aws_access_key_id = YOUR_KEYaws_secret_access_key = YOUR_KEY" }, { "code": null, "e": 16130, "s": 16109, "text": "Same with the config" }, { "code": null, "e": 16207, "s": 16130, "text": "code ~/.aws/config# and add:[default]region = YOUR_REGION (eg. eu-central-1)" }, { "code": null, "e": 16280, "s": 16207, "text": "Note that code is for opening a folder with vscode, my editor of choice." }, { "code": null, "e": 16502, "s": 16280, "text": "Save the AWS access key id and secret access key assigned to the user you created in the file ~/.aws/credentials. Note the .aws/ directory needs to be in your home directory and the credentials file has no file extension." }, { "code": null, "e": 16538, "s": 16502, "text": "Now you can do deploy your API with" }, { "code": null, "e": 16555, "s": 16538, "text": "zappa deploy dev" }, { "code": null, "e": 16600, "s": 16555, "text": "However, there are a few things to consider:" }, { "code": null, "e": 16729, "s": 16600, "text": "Zappa will pack your entire environment and whole root content. This will be quite large.There is an upload limit for AWS Lambda" }, { "code": null, "e": 16819, "s": 16729, "text": "Zappa will pack your entire environment and whole root content. This will be quite large." }, { "code": null, "e": 16859, "s": 16819, "text": "There is an upload limit for AWS Lambda" }, { "code": null, "e": 16979, "s": 16859, "text": "There are several discussions on how to reduce the upload size with zappa. Check out the Inspiration section for links." }, { "code": null, "e": 17037, "s": 16979, "text": "First, we need to reduce the package size for the upload." }, { "code": null, "e": 17210, "s": 17037, "text": "We will put all exploratory content into an own folder. I named it “development”. Afterwards, you can specify excluded files and folder in zappa_settings.json with exclude:" }, { "code": null, "e": 17438, "s": 17210, "text": "{ \"dev\": { ... \"slim_handler\": true, \"exclude\": [ \"*.ipynb\", \"*.joblib\", \"jupytext_conversion/\", \".ipynb_checkpoints/\", \"predict_covid.ipynb\", \"development\", \"models\" ] }}" }, { "code": null, "e": 17510, "s": 17438, "text": "You can add everything that doesn’t need to be packaged for deployment." }, { "code": null, "e": 17756, "s": 17510, "text": "Another issue is the environment dependencies. In our case, we have multiple dependencies, which we don’t need for deployment. To solve this I created a new “requirements_prod.txt” file. This shall only have dependencies which are needed on AWS." }, { "code": null, "e": 17803, "s": 17756, "text": "Make sure to export your current packages with" }, { "code": null, "e": 17833, "s": 17803, "text": "pip freeze > requirements.txt" }, { "code": null, "e": 17867, "s": 17833, "text": "Afterward, uninstall all packages" }, { "code": null, "e": 17904, "s": 17867, "text": "pip uninstall -r requirements.txt -y" }, { "code": null, "e": 17966, "s": 17904, "text": "Install new packages for deployment and save them in the file" }, { "code": null, "e": 18045, "s": 17966, "text": "pip install Flask pandas boto3 sklearn zappapip freeze > requirements_prod.txt" }, { "code": null, "e": 18126, "s": 18045, "text": "When you hit zappa deploy dev there should be considerably less size to package." }, { "code": null, "e": 18320, "s": 18126, "text": "You will note that I also set slim_handler=true. This allows us to upload more than 50MB. Behind the scenes, zappa already puts content into an own S3 bucket. Read the zappa docs for more info." }, { "code": null, "e": 18450, "s": 18320, "text": "Since we excluded our model from the AWS Lambda upload we need to get the model from somewhere else. We will use a AWS S3 Bucket." }, { "code": null, "e": 18677, "s": 18450, "text": "During the development process, I tried to upload it there programmatically as well but I just uploaded it by hand as it was just faster now. (But you can still try to upload it — I still have an outcommented file in the repo)" }, { "code": null, "e": 18718, "s": 18677, "text": "Go to https://console.aws.amazon.com/s3/" }, { "code": null, "e": 18821, "s": 18718, "text": "“create bucket”give a name and leave rest as default. check for sufficient permissions.“create bucket”" }, { "code": null, "e": 18837, "s": 18821, "text": "“create bucket”" }, { "code": null, "e": 18910, "s": 18837, "text": "give a name and leave rest as default. check for sufficient permissions." }, { "code": null, "e": 18926, "s": 18910, "text": "“create bucket”" }, { "code": null, "e": 19044, "s": 18926, "text": "check if you have a sufficient policy for interacting with the bucket and boto3. You should have something similar to" }, { "code": null, "e": 19323, "s": 19044, "text": "{ \"Effect\": \"Allow\", \"Action\": [ \"s3:CreateBucket\", \"s3:ListBucket\", \"s3:ListBucketMultipartUploads\", \"s3:ListAllMyBuckets\", \"s3:GetObject\" ], \"Resource\": [ \"arn:aws:s3:::zappa-*\", \"arn:aws:s3:::*\" ] }" }, { "code": null, "e": 19425, "s": 19323, "text": "Finally, there shouldn’t be any errors anymore. However, if there are still some, you can debug with:" }, { "code": null, "e": 19453, "s": 19425, "text": "zappa status# andzappa tail" }, { "code": null, "e": 19700, "s": 19453, "text": "The most common errors are permission related (then check your permission policy) or about python libraries that are incompatible. Either way, zappa will provide good enough error messages for debugging. Top list of errors from my experience are:" }, { "code": null, "e": 19804, "s": 19700, "text": "Policy issues with your user from IAMZappa and size issuesBoto3 and permission/location of files issues" }, { "code": null, "e": 19842, "s": 19804, "text": "Policy issues with your user from IAM" }, { "code": null, "e": 19864, "s": 19842, "text": "Zappa and size issues" }, { "code": null, "e": 19910, "s": 19864, "text": "Boto3 and permission/location of files issues" }, { "code": null, "e": 19985, "s": 19910, "text": "If you update your code don’t forget to update the deployment as well with" }, { "code": null, "e": 20002, "s": 19985, "text": "zappa update dev" }, { "code": null, "e": 20127, "s": 20002, "text": "To set up the API on a market we need to first restrict its usage with an API-key and then set it up on the market platform." }, { "code": null, "e": 20145, "s": 20127, "text": "To break it down:" }, { "code": null, "e": 20763, "s": 20145, "text": "go to your AWS Console and go to API gatewayclick on your APIwe want to create an x-api-key to restrict undesired access to the API and also have a metered usagecreate a Usage plan for the API, with the desired throttle and quota limitscreate an associated API stageadd an API keyin the API key overview section, click “show” at the API key and copy itthen associate the API with the key and discard all requests that come without the keygo back to the API overview. under resources, click the “/ any” go to the “method request”. then in settings, set “API key required” to truedo the same for the “/{proxy+} Methods”" }, { "code": null, "e": 20808, "s": 20763, "text": "go to your AWS Console and go to API gateway" }, { "code": null, "e": 20826, "s": 20808, "text": "click on your API" }, { "code": null, "e": 20927, "s": 20826, "text": "we want to create an x-api-key to restrict undesired access to the API and also have a metered usage" }, { "code": null, "e": 21003, "s": 20927, "text": "create a Usage plan for the API, with the desired throttle and quota limits" }, { "code": null, "e": 21034, "s": 21003, "text": "create an associated API stage" }, { "code": null, "e": 21049, "s": 21034, "text": "add an API key" }, { "code": null, "e": 21122, "s": 21049, "text": "in the API key overview section, click “show” at the API key and copy it" }, { "code": null, "e": 21209, "s": 21122, "text": "then associate the API with the key and discard all requests that come without the key" }, { "code": null, "e": 21350, "s": 21209, "text": "go back to the API overview. under resources, click the “/ any” go to the “method request”. then in settings, set “API key required” to true" }, { "code": null, "e": 21390, "s": 21350, "text": "do the same for the “/{proxy+} Methods”" }, { "code": null, "e": 21434, "s": 21390, "text": "Now you have restricted access to your API." }, { "code": null, "e": 21446, "s": 21434, "text": "Add new API" }, { "code": null, "e": 21474, "s": 21446, "text": "Test endpoint with rapidapi" }, { "code": null, "e": 21501, "s": 21474, "text": "Create code to consume API" }, { "code": null, "e": 21766, "s": 21501, "text": "I will not go into detail in this article anymore. Again, check my previous https://towardsdatascience.com/develop-and-sell-a-python-api-from-start-to-end-tutorial-9a038e433966 for setting everything up. There is no big difference in my new machine learning model." }, { "code": null, "e": 21827, "s": 21766, "text": "https://rapidapi.com/Createdd/api/covid_new_cases_prediction" }, { "code": null, "e": 22017, "s": 21827, "text": "My main motivation this time came from Moez Ali, who provides great articles on deploying machine learning systems. I also enjoy following him on social media. I can recommend his articles:" }, { "code": null, "e": 22114, "s": 22017, "text": "https://towardsdatascience.com/build-and-deploy-your-first-machine-learning-web-app-e020db344a99" }, { "code": null, "e": 22205, "s": 22114, "text": "https://towardsdatascience.com/deploy-machine-learning-pipeline-on-aws-fargate-eb6e1c50507" }, { "code": null, "e": 22233, "s": 22205, "text": "Also François Marceau with" }, { "code": null, "e": 22330, "s": 22233, "text": "https://towardsdatascience.com/how-to-deploy-a-machine-learning-model-on-aws-lambda-24c36dcaed20" }, { "code": null, "e": 22407, "s": 22330, "text": "https://github.com/Miserlou/Zappa/issues/1927 Package Error: python-dateutil" }, { "code": null, "e": 22476, "s": 22407, "text": "https://stackabuse.com/file-management-with-aws-s3-python-and-flask/" }, { "code": null, "e": 22558, "s": 22476, "text": "https://ianwhitestone.work/zappa-zip-callbacks/ remove unnecessary files in zappa" }, { "code": null, "e": 22677, "s": 22558, "text": "https://stackoverflow.com/questions/62941174/how-to-write-load-machine-learning-model-to-from-s3-bucket-through-joblib" }, { "code": null, "e": 22793, "s": 22677, "text": "https://www.freecodecamp.org/news/what-we-learned-by-serving-machine-learning-models-using-aws-lambda-c70b303404a1/" }, { "code": null, "e": 22859, "s": 22793, "text": "https://ianwhitestone.work/slides/serverless-meetup-feb-2020.html" }, { "code": null, "e": 22937, "s": 22859, "text": "https://read.iopipe.com/the-right-way-to-do-serverless-in-python-e99535574454" }, { "code": null, "e": 23028, "s": 22937, "text": "https://www.bluematador.com/blog/serverless-in-aws-lambda-vs-fargate aws lambda vs fargate" }, { "code": null, "e": 23152, "s": 23028, "text": "https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html billing alarm" }, { "code": null, "e": 23170, "s": 23152, "text": "Open source code:" }, { "code": null, "e": 23211, "s": 23170, "text": "https://github.com/Createdd/ml_api_covid" }, { "code": null, "e": 23224, "s": 23211, "text": "On Rapidapi:" }, { "code": null, "e": 23285, "s": 23224, "text": "https://rapidapi.com/Createdd/api/covid_new_cases_prediction" }, { "code": null, "e": 23462, "s": 23285, "text": "Daniel is an entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court." }, { "code": null, "e": 23708, "s": 23462, "text": "His knowledge and interests currently revolve around programming machine learning applications and all their related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects." } ]
MongoDB checking for not null?
Use $ne to check for not null. Let us create a collection with documents − > db.demo764.insertOne({"LoginUserName":"Chris","LoginPassword":"Chris_12"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb04ee55637cd592b2a4afc") } > db.demo764.insertOne({"LoginUserName":"Chris","LoginPassword":null}); { "acknowledged" : true, "insertedId" : ObjectId("5eb04eee5637cd592b2a4afd") } > db.demo764.insertOne({"LoginUserName":"Chris","LoginPassword":""}); { "acknowledged" : true, "insertedId" : ObjectId("5eb04ef35637cd592b2a4afe") } Display all documents from a collection with the help of find() method − > db.demo764.find(); This will produce the following output − { "_id" : ObjectId("5eb04ee55637cd592b2a4afc"), "LoginUserName" : "Chris", "LoginPassword" : "Chris_12" } { "_id" : ObjectId("5eb04eee5637cd592b2a4afd"), "LoginUserName" : "Chris", "LoginPassword" : null } { "_id" : ObjectId("5eb04ef35637cd592b2a4afe"), "LoginUserName" : "Chris", "LoginPassword" : "" } Following is the query to check for not null − > db.demo764.find({"LoginUserName":"Chris","LoginPassword" : { '$ne': null } }); This will produce the following output − { "_id" : ObjectId("5eb04ee55637cd592b2a4afc"), "LoginUserName" : "Chris", "LoginPassword" : "Chris_12" } { "_id" : ObjectId("5eb04ef35637cd592b2a4afe"), "LoginUserName" : "Chris", "LoginPassword" : "" }
[ { "code": null, "e": 1137, "s": 1062, "text": "Use $ne to check for not null. Let us create a collection with documents −" }, { "code": null, "e": 1612, "s": 1137, "text": "> db.demo764.insertOne({\"LoginUserName\":\"Chris\",\"LoginPassword\":\"Chris_12\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb04ee55637cd592b2a4afc\")\n}\n> db.demo764.insertOne({\"LoginUserName\":\"Chris\",\"LoginPassword\":null});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb04eee5637cd592b2a4afd\")\n}\n> db.demo764.insertOne({\"LoginUserName\":\"Chris\",\"LoginPassword\":\"\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb04ef35637cd592b2a4afe\")\n}" }, { "code": null, "e": 1685, "s": 1612, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1706, "s": 1685, "text": "> db.demo764.find();" }, { "code": null, "e": 1747, "s": 1706, "text": "This will produce the following output −" }, { "code": null, "e": 2051, "s": 1747, "text": "{ \"_id\" : ObjectId(\"5eb04ee55637cd592b2a4afc\"), \"LoginUserName\" : \"Chris\", \"LoginPassword\" : \"Chris_12\" }\n{ \"_id\" : ObjectId(\"5eb04eee5637cd592b2a4afd\"), \"LoginUserName\" : \"Chris\", \"LoginPassword\" : null }\n{ \"_id\" : ObjectId(\"5eb04ef35637cd592b2a4afe\"), \"LoginUserName\" : \"Chris\", \"LoginPassword\" : \"\" }" }, { "code": null, "e": 2098, "s": 2051, "text": "Following is the query to check for not null −" }, { "code": null, "e": 2179, "s": 2098, "text": "> db.demo764.find({\"LoginUserName\":\"Chris\",\"LoginPassword\" : { '$ne': null } });" }, { "code": null, "e": 2220, "s": 2179, "text": "This will produce the following output −" }, { "code": null, "e": 2424, "s": 2220, "text": "{ \"_id\" : ObjectId(\"5eb04ee55637cd592b2a4afc\"), \"LoginUserName\" : \"Chris\", \"LoginPassword\" : \"Chris_12\" }\n{ \"_id\" : ObjectId(\"5eb04ef35637cd592b2a4afe\"), \"LoginUserName\" : \"Chris\", \"LoginPassword\" : \"\" }" } ]
Java DOM Parser - Create XML Document
Here is the XML we need to create − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> package com.tutorialspoint.xml; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; public class CreateXmlFileDemo { public static void main(String argv[]) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("cars"); doc.appendChild(rootElement); // supercars element Element supercar = doc.createElement("supercars"); rootElement.appendChild(supercar); // setting attribute to element Attr attr = doc.createAttribute("company"); attr.setValue("Ferrari"); supercar.setAttributeNode(attr); // carname element Element carname = doc.createElement("carname"); Attr attrType = doc.createAttribute("type"); attrType.setValue("formula one"); carname.setAttributeNode(attrType); carname.appendChild(doc.createTextNode("Ferrari 101")); supercar.appendChild(carname); Element carname1 = doc.createElement("carname"); Attr attrType1 = doc.createAttribute("type"); attrType1.setValue("sports"); carname1.setAttributeNode(attrType1); carname1.appendChild(doc.createTextNode("Ferrari 202")); supercar.appendChild(carname1); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\cars.xml")); transformer.transform(source, result); // Output to console for testing StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2359, "s": 2323, "text": "Here is the XML we need to create −" }, { "code": null, "e": 2597, "s": 2359, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>" }, { "code": null, "e": 5000, "s": 2597, "text": "package com.tutorialspoint.xml;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\nimport org.w3c.dom.Attr;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport java.io.File;\n\npublic class CreateXmlFileDemo {\n\n public static void main(String argv[]) {\n\n try {\n DocumentBuilderFactory dbFactory =\n DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.newDocument();\n \n // root element\n Element rootElement = doc.createElement(\"cars\");\n doc.appendChild(rootElement);\n\n // supercars element\n Element supercar = doc.createElement(\"supercars\");\n rootElement.appendChild(supercar);\n\n // setting attribute to element\n Attr attr = doc.createAttribute(\"company\");\n attr.setValue(\"Ferrari\");\n supercar.setAttributeNode(attr);\n\n // carname element\n Element carname = doc.createElement(\"carname\");\n Attr attrType = doc.createAttribute(\"type\");\n attrType.setValue(\"formula one\");\n carname.setAttributeNode(attrType);\n carname.appendChild(doc.createTextNode(\"Ferrari 101\"));\n supercar.appendChild(carname);\n\n Element carname1 = doc.createElement(\"carname\");\n Attr attrType1 = doc.createAttribute(\"type\");\n attrType1.setValue(\"sports\");\n carname1.setAttributeNode(attrType1);\n carname1.appendChild(doc.createTextNode(\"Ferrari 202\"));\n supercar.appendChild(carname1);\n\n // write the content into xml file\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n DOMSource source = new DOMSource(doc);\n StreamResult result = new StreamResult(new File(\"C:\\\\cars.xml\"));\n transformer.transform(source, result);\n \n // Output to console for testing\n StreamResult consoleResult = new StreamResult(System.out);\n transformer.transform(source, consoleResult);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 5042, "s": 5000, "text": "This would produce the following result −" }, { "code": null, "e": 5282, "s": 5042, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 5315, "s": 5282, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5331, "s": 5315, "text": " Malhar Lathkar" }, { "code": null, "e": 5364, "s": 5331, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5380, "s": 5364, "text": " Malhar Lathkar" }, { "code": null, "e": 5415, "s": 5380, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5429, "s": 5415, "text": " Anadi Sharma" }, { "code": null, "e": 5463, "s": 5429, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5477, "s": 5463, "text": " Tushar Kale" }, { "code": null, "e": 5514, "s": 5477, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5529, "s": 5514, "text": " Monica Mittal" }, { "code": null, "e": 5562, "s": 5529, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5581, "s": 5562, "text": " Arnab Chakraborty" }, { "code": null, "e": 5588, "s": 5581, "text": " Print" }, { "code": null, "e": 5599, "s": 5588, "text": " Add Notes" } ]
Domained - Multi Tool Subdomain Enumeration Suite on Kali Linux - GeeksforGeeks
23 Aug, 2021 Information Gathering is the crucial step in the process of penetration testing. The more you collect the information the more it will help you to get a better testing methodology. So for this purpose of Information Gathering, the Domained tool is created. Domained is a framework collection of various subdomain detection tools. Domained is a python language-based tool that uses several subdomain enumeration tools and wordlists to create a unique list of subdomains passed to the EyeWitness tool for reporting with categorized snapshots, server response headers, and signature-based default credentials checking. Several tools are integrated with the Domained tool that covers the enumeration phase, reporting, and wordlists. Domained tools will allow the penetration tester to verify the target against different programs. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux Sublist3r enumall Knock Subbrute massdns Recon-ng Amass SubFinder EyeWitness SecList (DNS Recon List) LevelUp All.txt Subdomain List Step 1: Fire up your Kali Linux terminal and move to Desktop using the following command. cd Desktop Step 2: You are on Desktop now create a new directory called Domained using the following command. In this directory, we will complete the installation of the Domained tool. mkdir Domained Step 3: Now switch to Domained directory using the following command. cd Domained Step 4: Now you have to install the tool. You have to clone the tool from Github. sudo git clone https://github.com/TypeError/domained.git Step 5: The tool has been downloaded successfully in the Domained directory. Now list out the contents of the tool by using the below command. ls Step 6: You can observe that there is a new directory created of the domained tool that has been generated while we were installing the tool. Now move to that directory using the below command: cd domained Step 7: Once again to discover the contents of the tool, use the below command. ls Step 8: Install Required Python Modules, use the following command. sudo pip install -r ./ext/requirements.txt Step 9: Install Tools which are mentioned above, use the following command. sudo python3 domained.py --install Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of tool) index of the tool. python3 domained.py -h Example 1: Uses subdomain geeksforgeeks.org (Sublist3r (+subbrute), enumall, Knock, Amass, and SubFinder) python3 domained.py -d geeksforgeeks.org 1. In this example, We will be enumerating the subdomains from the above-listed tools. The more subdomains we collect will help us to expand our target scope. 2. In the below Screenshot, We have the list of subdomains collected by the Sublist3r tool. 3. In the below Screenshot, We have the list of subdomains collected by the Subfinder tool. 4. In the below Screenshot, We have the list of subdomains collected by Amass tool. Example 2: Uses subdomain geeksforgeeks.org, only Amass and SubFinder and notification python3 domained.py -d geeksforgeeks.org --quick --notify 1. In this example, We will be performing quick enumeration by choosing only 2 tools for the enumeration process. Amass and SubFinder tools are being selected for this demonstration. In the below Screenshot, the domained tool has started the enumeration process by selecting 1st tool (Amass). 2. In the below Screenshot, After the Amass tool Subfinder tool have to enumerate the subdomains. 3. In the below Screenshot, 2 text files are created which contain subdomains of geeksforgeeks.org which are enumerated using the Amass and Subfinder tool. Domained is an all-in-one framework that consists of almost every tool which is required for Information Gathering and Enumeration. You can use this Suite for Bug Bounty Programs and Penetration Testing Process. how-to-install Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples 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": 24015, "s": 23987, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24842, "s": 24015, "text": "Information Gathering is the crucial step in the process of penetration testing. The more you collect the information the more it will help you to get a better testing methodology. So for this purpose of Information Gathering, the Domained tool is created. Domained is a framework collection of various subdomain detection tools. Domained is a python language-based tool that uses several subdomain enumeration tools and wordlists to create a unique list of subdomains passed to the EyeWitness tool for reporting with categorized snapshots, server response headers, and signature-based default credentials checking. Several tools are integrated with the Domained tool that covers the enumeration phase, reporting, and wordlists. Domained tools will allow the penetration tester to verify the target against different programs." }, { "code": null, "e": 25008, "s": 24842, "text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux" }, { "code": null, "e": 25018, "s": 25008, "text": "Sublist3r" }, { "code": null, "e": 25026, "s": 25018, "text": "enumall" }, { "code": null, "e": 25032, "s": 25026, "text": "Knock" }, { "code": null, "e": 25041, "s": 25032, "text": "Subbrute" }, { "code": null, "e": 25049, "s": 25041, "text": "massdns" }, { "code": null, "e": 25058, "s": 25049, "text": "Recon-ng" }, { "code": null, "e": 25064, "s": 25058, "text": "Amass" }, { "code": null, "e": 25074, "s": 25064, "text": "SubFinder" }, { "code": null, "e": 25085, "s": 25074, "text": "EyeWitness" }, { "code": null, "e": 25110, "s": 25085, "text": "SecList (DNS Recon List)" }, { "code": null, "e": 25141, "s": 25110, "text": "LevelUp All.txt Subdomain List" }, { "code": null, "e": 25231, "s": 25141, "text": "Step 1: Fire up your Kali Linux terminal and move to Desktop using the following command." }, { "code": null, "e": 25242, "s": 25231, "text": "cd Desktop" }, { "code": null, "e": 25416, "s": 25242, "text": "Step 2: You are on Desktop now create a new directory called Domained using the following command. In this directory, we will complete the installation of the Domained tool." }, { "code": null, "e": 25431, "s": 25416, "text": "mkdir Domained" }, { "code": null, "e": 25501, "s": 25431, "text": "Step 3: Now switch to Domained directory using the following command." }, { "code": null, "e": 25513, "s": 25501, "text": "cd Domained" }, { "code": null, "e": 25595, "s": 25513, "text": "Step 4: Now you have to install the tool. You have to clone the tool from Github." }, { "code": null, "e": 25652, "s": 25595, "text": "sudo git clone https://github.com/TypeError/domained.git" }, { "code": null, "e": 25795, "s": 25652, "text": "Step 5: The tool has been downloaded successfully in the Domained directory. Now list out the contents of the tool by using the below command." }, { "code": null, "e": 25798, "s": 25795, "text": "ls" }, { "code": null, "e": 25992, "s": 25798, "text": "Step 6: You can observe that there is a new directory created of the domained tool that has been generated while we were installing the tool. Now move to that directory using the below command:" }, { "code": null, "e": 26004, "s": 25992, "text": "cd domained" }, { "code": null, "e": 26084, "s": 26004, "text": "Step 7: Once again to discover the contents of the tool, use the below command." }, { "code": null, "e": 26087, "s": 26084, "text": "ls" }, { "code": null, "e": 26155, "s": 26087, "text": "Step 8: Install Required Python Modules, use the following command." }, { "code": null, "e": 26198, "s": 26155, "text": "sudo pip install -r ./ext/requirements.txt" }, { "code": null, "e": 26274, "s": 26198, "text": "Step 9: Install Tools which are mentioned above, use the following command." }, { "code": null, "e": 26309, "s": 26274, "text": "sudo python3 domained.py --install" }, { "code": null, "e": 26454, "s": 26309, "text": "Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of tool) index of the tool." }, { "code": null, "e": 26477, "s": 26454, "text": "python3 domained.py -h" }, { "code": null, "e": 26583, "s": 26477, "text": "Example 1: Uses subdomain geeksforgeeks.org (Sublist3r (+subbrute), enumall, Knock, Amass, and SubFinder)" }, { "code": null, "e": 26624, "s": 26583, "text": "python3 domained.py -d geeksforgeeks.org" }, { "code": null, "e": 26783, "s": 26624, "text": "1. In this example, We will be enumerating the subdomains from the above-listed tools. The more subdomains we collect will help us to expand our target scope." }, { "code": null, "e": 26875, "s": 26783, "text": "2. In the below Screenshot, We have the list of subdomains collected by the Sublist3r tool." }, { "code": null, "e": 26967, "s": 26875, "text": "3. In the below Screenshot, We have the list of subdomains collected by the Subfinder tool." }, { "code": null, "e": 27051, "s": 26967, "text": "4. In the below Screenshot, We have the list of subdomains collected by Amass tool." }, { "code": null, "e": 27138, "s": 27051, "text": "Example 2: Uses subdomain geeksforgeeks.org, only Amass and SubFinder and notification" }, { "code": null, "e": 27196, "s": 27138, "text": "python3 domained.py -d geeksforgeeks.org --quick --notify" }, { "code": null, "e": 27489, "s": 27196, "text": "1. In this example, We will be performing quick enumeration by choosing only 2 tools for the enumeration process. Amass and SubFinder tools are being selected for this demonstration. In the below Screenshot, the domained tool has started the enumeration process by selecting 1st tool (Amass)." }, { "code": null, "e": 27587, "s": 27489, "text": "2. In the below Screenshot, After the Amass tool Subfinder tool have to enumerate the subdomains." }, { "code": null, "e": 27743, "s": 27587, "text": "3. In the below Screenshot, 2 text files are created which contain subdomains of geeksforgeeks.org which are enumerated using the Amass and Subfinder tool." }, { "code": null, "e": 27955, "s": 27743, "text": "Domained is an all-in-one framework that consists of almost every tool which is required for Information Gathering and Enumeration. You can use this Suite for Bug Bounty Programs and Penetration Testing Process." }, { "code": null, "e": 27970, "s": 27955, "text": "how-to-install" }, { "code": null, "e": 27981, "s": 27970, "text": "Kali-Linux" }, { "code": null, "e": 27993, "s": 27981, "text": "Linux-Tools" }, { "code": null, "e": 28004, "s": 27993, "text": "Linux-Unix" }, { "code": null, "e": 28102, "s": 28004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28111, "s": 28102, "text": "Comments" }, { "code": null, "e": 28124, "s": 28111, "text": "Old Comments" }, { "code": null, "e": 28150, "s": 28124, "text": "Thread functions in C/C++" }, { "code": null, "e": 28187, "s": 28150, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28221, "s": 28187, "text": "mv command in Linux with examples" }, { "code": null, "e": 28256, "s": 28221, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28282, "s": 28256, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28319, "s": 28282, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28359, "s": 28319, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 28388, "s": 28359, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28430, "s": 28388, "text": "Named Pipe or FIFO with example C program" } ]
How to Create Pivot Tables in R? - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss how to create the pivot table in the R Programming Language. The Pivot table is one of Microsoft Excel’s most powerful features that let us extract the significance from a large and detailed data set. A Pivot Table often shows some statistical value about the dataset by grouping some values from a column together, To do so in the R programming Language, we use the group_by() and the summarize() function of the dplyr package library. The dplyr package in the R Programming Language is a structure of data manipulation that provides a uniform set of verbs that help us in preprocessing large data. The group_by() function groups the data using one or more variables and then summarize function creates the summary of data by those groups using aggregate function passed to it. Syntax: df %>% group_by( grouping_variables) %>% summarize( label = aggregate_fun() ) Parameter: df: determines the data frame in use. grouping_variables: determine the variable used to group data. aggregate_fun(): determines the function used for summary. for example, sum, mean, etc. Example 1: Create pivot tables R # create sample data framesample_data <- data.frame(label=c('Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3'), value=c(222, 18, 51, 52, 44, 19, 100, 98, 34)) # load library dplyrlibrary(dplyr) # create pivot table with sum of value as summarysample_data %>% group_by(label) %>% summarize(sum_values = sum(value)) Output: # A tibble: 3 x 2 label sum_values <chr> <dbl> 1 Geek1 374 2 Geek2 160 3 Geek3 104 Example 2: Create pivot table R # create sample data framesample_data <- data.frame(label=c('Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3'), value=c(222, 18, 51, 52, 44, 19, 100, 98, 34)) # load library dplyrlibrary(dplyr) # create pivot table with sum of value as summarysample_data %>% group_by(label) %>% summarize(average_values = mean(value)) Output: # A tibble: 3 x 2 label average_values <chr> <dbl> 1 Geek1 125. 2 Geek2 53.3 3 Geek3 34.7 Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n19 Dec, 2021" }, { "code": null, "e": 24945, "s": 24851, "text": "In this article, we will discuss how to create the pivot table in the R Programming Language." }, { "code": null, "e": 25663, "s": 24945, "text": "The Pivot table is one of Microsoft Excel’s most powerful features that let us extract the significance from a large and detailed data set. A Pivot Table often shows some statistical value about the dataset by grouping some values from a column together, To do so in the R programming Language, we use the group_by() and the summarize() function of the dplyr package library. The dplyr package in the R Programming Language is a structure of data manipulation that provides a uniform set of verbs that help us in preprocessing large data. The group_by() function groups the data using one or more variables and then summarize function creates the summary of data by those groups using aggregate function passed to it." }, { "code": null, "e": 25671, "s": 25663, "text": "Syntax:" }, { "code": null, "e": 25749, "s": 25671, "text": "df %>% group_by( grouping_variables) %>% summarize( label = aggregate_fun() )" }, { "code": null, "e": 25760, "s": 25749, "text": "Parameter:" }, { "code": null, "e": 25798, "s": 25760, "text": "df: determines the data frame in use." }, { "code": null, "e": 25861, "s": 25798, "text": "grouping_variables: determine the variable used to group data." }, { "code": null, "e": 25949, "s": 25861, "text": "aggregate_fun(): determines the function used for summary. for example, sum, mean, etc." }, { "code": null, "e": 25980, "s": 25949, "text": "Example 1: Create pivot tables" }, { "code": null, "e": 25982, "s": 25980, "text": "R" }, { "code": "# create sample data framesample_data <- data.frame(label=c('Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3'), value=c(222, 18, 51, 52, 44, 19, 100, 98, 34)) # load library dplyrlibrary(dplyr) # create pivot table with sum of value as summarysample_data %>% group_by(label) %>% summarize(sum_values = sum(value))", "e": 26423, "s": 25982, "text": null }, { "code": null, "e": 26431, "s": 26423, "text": "Output:" }, { "code": null, "e": 26542, "s": 26431, "text": "# A tibble: 3 x 2\n label sum_values\n <chr> <dbl>\n1 Geek1 374\n2 Geek2 160\n3 Geek3 104" }, { "code": null, "e": 26572, "s": 26542, "text": "Example 2: Create pivot table" }, { "code": null, "e": 26574, "s": 26572, "text": "R" }, { "code": "# create sample data framesample_data <- data.frame(label=c('Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3', 'Geek1', 'Geek2', 'Geek3'), value=c(222, 18, 51, 52, 44, 19, 100, 98, 34)) # load library dplyrlibrary(dplyr) # create pivot table with sum of value as summarysample_data %>% group_by(label) %>% summarize(average_values = mean(value))", "e": 27020, "s": 26574, "text": null }, { "code": null, "e": 27028, "s": 27020, "text": "Output:" }, { "code": null, "e": 27160, "s": 27028, "text": "# A tibble: 3 x 2\n label average_values\n <chr> <dbl>\n1 Geek1 125. \n2 Geek2 53.3\n3 Geek3 34.7" }, { "code": null, "e": 27167, "s": 27160, "text": "Picked" }, { "code": null, "e": 27175, "s": 27167, "text": "R Dplyr" }, { "code": null, "e": 27186, "s": 27175, "text": "R Language" }, { "code": null, "e": 27284, "s": 27186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27293, "s": 27284, "text": "Comments" }, { "code": null, "e": 27306, "s": 27293, "text": "Old Comments" }, { "code": null, "e": 27358, "s": 27306, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27396, "s": 27358, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27431, "s": 27396, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27489, "s": 27431, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27538, "s": 27489, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27581, "s": 27538, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27631, "s": 27581, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27648, "s": 27631, "text": "R - if statement" }, { "code": null, "e": 27685, "s": 27648, "text": "How to import an Excel File into R ?" } ]
Angle between two Planes in 3D - GeeksforGeeks
03 May, 2021 Given two planes P1: a1 * x + b1 * y + c1 * z + d1 = 0 and P2: a2 * x + b2 * y + c2 * z + d2 = 0. The task is to find the angle between these two planes in 3D. Examples: Input: a1 = 1, b1 = 1, c1 = 2, d1 = 1, a2 = 2, b2 = -1, c2 = 1, d2 = -4 Output: Angle is 60.0 degreeInput: a1 = 2, b1 = 2, c1 = -3, d1 = -5, a2 = 3, b2 = -3, c2 = 5, d2 = -6 Output: Angle is 123.696598882 degree Approach: Consider the below equations of given two planes: P1 : a1 * x + b1 * y + c1 * z + d1 = 0 and, P2 : a2 * x + b2 * y + c2 * z + d2 = 0, where a1, b1, c1, and a2, b2, c2 are direction ratios of normal to the plane P1 and P2. The angle between two planes is equal to the angle determined by the normal vectors of the planes. Angle between these planes is given by using the following formula:- Cos A = Using inverse property, we get: A = Below is the implementation of the above formulae: C++ C Java Python C# PHP Javascript // C++ program to find// the Angle between// two Planes in 3 D.#include <bits/stdc++.h>#include<math.h> using namespace std; // Function to find Anglevoid distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = 3.14159; float A = (180 / pi) * (acos(d)); cout << "Angle is " << A << " degree";} // Driver Codeint main(){ float a1 = 1; float b1 = 1; float c1 = 2; float d1 = 1; float a2 = 2; float b2 = -1; float c2 = 1; float d2 = -4; distance(a1, b1, c1, a2, b2, c2); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku) // C program to find// the Angle between// two Planes in 3 D.#include<stdio.h>#include<math.h> // Function to find Anglevoid distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = 3.14159; float A = (180 / pi) * (acos(d)); printf("Angle is %.2f degree", A);} // Driver Codeint main(){ float a1 = 1; float b1 = 1; float c1 = 2; float d1 = 1; float a2 = 2; float b2 = -1; float c2 = 1; float d2 = -4; distance(a1, b1, c1, a2, b2, c2); return 0;} // This code is contributed// by Amber_Saxena. // Java program to find// the Angle between// two Planes in 3 D.import java .io.*;import java.lang.Math; class GFG{ // Function to find Anglestatic void distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = (float)Math.sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = (float)Math.sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = (float)3.14159; float A = (180 / pi) * (float)(Math.acos(d)); System.out.println("Angle is "+ A +" degree");} // Driver codepublic static void main(String[] args){ float a1 = 1; float b1 = 1; float c1 = 2; float d1 = 1; float a2 = 2; float b2 = -1; float c2 = 1; float d2 = -4; distance(a1, b1, c1, a2, b2, c2);}} // This code is contributed// by Amber_Saxena. # Python program to find the Angle between# two Planes in 3 D. import math # Function to find Angledef distance(a1, b1, c1, a2, b2, c2): d = ( a1 * a2 + b1 * b2 + c1 * c2 ) e1 = math.sqrt( a1 * a1 + b1 * b1 + c1 * c1) e2 = math.sqrt( a2 * a2 + b2 * b2 + c2 * c2) d = d / (e1 * e2) A = math.degrees(math.acos(d)) print("Angle is"), A, ("degree") # Driver Codea1 = 1b1 = 1c1 = 2d1 = 1a2 = 2b2 = -1c2 = 1d2 = -4distance(a1, b1, c1, a2, b2, c2) // C# program to find// the Angle between// two Planes in 3 D.using System; class GFG{ // Function to find Anglestatic void distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = (float)Math.Sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = (float)Math.Sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = (float)3.14159; float A = (180 / pi) * (float)(Math.Acos(d)); Console.Write("Angle is "+ A +" degree");} // Driver codepublic static void Main(){ float a1 = 1; float b1 = 1; float c1 = 2; float a2 = 2; float b2 = -1; float c2 = 1; distance(a1, b1, c1, a2, b2, c2);}} // This code is contributed// by ChitraNayal <?php// PHP program to find the Angle// between two Planes in 3 D. // Function to find Anglefunction distance($a1, $b1, $c1, $a2, $b2, $c2){ $d = ($a1 * $a2 + $b1 * $b2 + $c1 * $c2); $e1 = sqrt($a1 * $a1 + $b1 * $b1 + $c1 * $c1); $e2 = sqrt($a2 * $a2 + $b2 * $b2 + $c2 * $c2); $d = $d / ($e1 * $e2); $pi = 3.14159; $A = (180 / $pi) * (acos($d)); echo sprintf("Angle is %.2f degree", $A);} // Driver Code$a1 = 1;$b1 = 1;$c1 = 2;$d1 = 1;$a2 = 2;$b2 = -1;$c2 = 1;$d2 = -4;distance($a1, $b1, $c1, $a2, $b2, $c2); // This code is contributed// by Amber_Saxena.?> <script> // JavaScript program to find // the Angle between // two Planes in 3 D. // Function to find Angle function distance(a1, b1, c1, a2, b2, c2) { var d = a1 * a2 + b1 * b2 + c1 * c2; var e1 = Math.sqrt(a1 * a1 + b1 * b1 + c1 * c1); var e2 = Math.sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = parseFloat(d / (e1 * e2)); var pi = 3.14159; var A = (180 / pi) * Math.acos(d); document.write("Angle is " + A.toFixed(1) + " degree"); } // Driver Code var a1 = 1; var b1 = 1; var c1 = 2; var d1 = 1; var a2 = 2; var b2 = -1; var c2 = 1; var d2 = -4; distance(a1, b1, c1, a2, b2, c2); </script> Angle is 60.0 degree Amber_Saxena ukasp Akanksha_Rai rdtank Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Closest Pair of Points | O(nlogn) Implementation Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25176, "s": 25148, "text": "\n03 May, 2021" }, { "code": null, "e": 25337, "s": 25176, "text": "Given two planes P1: a1 * x + b1 * y + c1 * z + d1 = 0 and P2: a2 * x + b2 * y + c2 * z + d2 = 0. The task is to find the angle between these two planes in 3D. " }, { "code": null, "e": 25349, "s": 25337, "text": "Examples: " }, { "code": null, "e": 25561, "s": 25349, "text": "Input: a1 = 1, b1 = 1, c1 = 2, d1 = 1, a2 = 2, b2 = -1, c2 = 1, d2 = -4 Output: Angle is 60.0 degreeInput: a1 = 2, b1 = 2, c1 = -3, d1 = -5, a2 = 3, b2 = -3, c2 = 5, d2 = -6 Output: Angle is 123.696598882 degree" }, { "code": null, "e": 25625, "s": 25563, "text": "Approach: Consider the below equations of given two planes: " }, { "code": null, "e": 25710, "s": 25625, "text": "P1 : a1 * x + b1 * y + c1 * z + d1 = 0 and,\nP2 : a2 * x + b2 * y + c2 * z + d2 = 0, " }, { "code": null, "e": 26063, "s": 25710, "text": "where a1, b1, c1, and a2, b2, c2 are direction ratios of normal to the plane P1 and P2. The angle between two planes is equal to the angle determined by the normal vectors of the planes. Angle between these planes is given by using the following formula:- Cos A = Using inverse property, we get: A = Below is the implementation of the above formulae: " }, { "code": null, "e": 26067, "s": 26063, "text": "C++" }, { "code": null, "e": 26069, "s": 26067, "text": "C" }, { "code": null, "e": 26074, "s": 26069, "text": "Java" }, { "code": null, "e": 26081, "s": 26074, "text": "Python" }, { "code": null, "e": 26084, "s": 26081, "text": "C#" }, { "code": null, "e": 26088, "s": 26084, "text": "PHP" }, { "code": null, "e": 26099, "s": 26088, "text": "Javascript" }, { "code": "// C++ program to find// the Angle between// two Planes in 3 D.#include <bits/stdc++.h>#include<math.h> using namespace std; // Function to find Anglevoid distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = 3.14159; float A = (180 / pi) * (acos(d)); cout << \"Angle is \" << A << \" degree\";} // Driver Codeint main(){ float a1 = 1; float b1 = 1; float c1 = 2; float d1 = 1; float a2 = 2; float b2 = -1; float c2 = 1; float d2 = -4; distance(a1, b1, c1, a2, b2, c2); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 26961, "s": 26099, "text": null }, { "code": "// C program to find// the Angle between// two Planes in 3 D.#include<stdio.h>#include<math.h> // Function to find Anglevoid distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = 3.14159; float A = (180 / pi) * (acos(d)); printf(\"Angle is %.2f degree\", A);} // Driver Codeint main(){ float a1 = 1; float b1 = 1; float c1 = 2; float d1 = 1; float a2 = 2; float b2 = -1; float c2 = 1; float d2 = -4; distance(a1, b1, c1, a2, b2, c2); return 0;} // This code is contributed// by Amber_Saxena.", "e": 27771, "s": 26961, "text": null }, { "code": "// Java program to find// the Angle between// two Planes in 3 D.import java .io.*;import java.lang.Math; class GFG{ // Function to find Anglestatic void distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = (float)Math.sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = (float)Math.sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = (float)3.14159; float A = (180 / pi) * (float)(Math.acos(d)); System.out.println(\"Angle is \"+ A +\" degree\");} // Driver codepublic static void main(String[] args){ float a1 = 1; float b1 = 1; float c1 = 2; float d1 = 1; float a2 = 2; float b2 = -1; float c2 = 1; float d2 = -4; distance(a1, b1, c1, a2, b2, c2);}} // This code is contributed// by Amber_Saxena.", "e": 28727, "s": 27771, "text": null }, { "code": "# Python program to find the Angle between# two Planes in 3 D. import math # Function to find Angledef distance(a1, b1, c1, a2, b2, c2): d = ( a1 * a2 + b1 * b2 + c1 * c2 ) e1 = math.sqrt( a1 * a1 + b1 * b1 + c1 * c1) e2 = math.sqrt( a2 * a2 + b2 * b2 + c2 * c2) d = d / (e1 * e2) A = math.degrees(math.acos(d)) print(\"Angle is\"), A, (\"degree\") # Driver Codea1 = 1b1 = 1c1 = 2d1 = 1a2 = 2b2 = -1c2 = 1d2 = -4distance(a1, b1, c1, a2, b2, c2) ", "e": 29192, "s": 28727, "text": null }, { "code": "// C# program to find// the Angle between// two Planes in 3 D.using System; class GFG{ // Function to find Anglestatic void distance(float a1, float b1, float c1, float a2, float b2, float c2){ float d = (a1 * a2 + b1 * b2 + c1 * c2); float e1 = (float)Math.Sqrt(a1 * a1 + b1 * b1 + c1 * c1); float e2 = (float)Math.Sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = d / (e1 * e2); float pi = (float)3.14159; float A = (180 / pi) * (float)(Math.Acos(d)); Console.Write(\"Angle is \"+ A +\" degree\");} // Driver codepublic static void Main(){ float a1 = 1; float b1 = 1; float c1 = 2; float a2 = 2; float b2 = -1; float c2 = 1; distance(a1, b1, c1, a2, b2, c2);}} // This code is contributed// by ChitraNayal", "e": 30069, "s": 29192, "text": null }, { "code": "<?php// PHP program to find the Angle// between two Planes in 3 D. // Function to find Anglefunction distance($a1, $b1, $c1, $a2, $b2, $c2){ $d = ($a1 * $a2 + $b1 * $b2 + $c1 * $c2); $e1 = sqrt($a1 * $a1 + $b1 * $b1 + $c1 * $c1); $e2 = sqrt($a2 * $a2 + $b2 * $b2 + $c2 * $c2); $d = $d / ($e1 * $e2); $pi = 3.14159; $A = (180 / $pi) * (acos($d)); echo sprintf(\"Angle is %.2f degree\", $A);} // Driver Code$a1 = 1;$b1 = 1;$c1 = 2;$d1 = 1;$a2 = 2;$b2 = -1;$c2 = 1;$d2 = -4;distance($a1, $b1, $c1, $a2, $b2, $c2); // This code is contributed// by Amber_Saxena.?>", "e": 30730, "s": 30069, "text": null }, { "code": "<script> // JavaScript program to find // the Angle between // two Planes in 3 D. // Function to find Angle function distance(a1, b1, c1, a2, b2, c2) { var d = a1 * a2 + b1 * b2 + c1 * c2; var e1 = Math.sqrt(a1 * a1 + b1 * b1 + c1 * c1); var e2 = Math.sqrt(a2 * a2 + b2 * b2 + c2 * c2); d = parseFloat(d / (e1 * e2)); var pi = 3.14159; var A = (180 / pi) * Math.acos(d); document.write(\"Angle is \" + A.toFixed(1) + \" degree\"); } // Driver Code var a1 = 1; var b1 = 1; var c1 = 2; var d1 = 1; var a2 = 2; var b2 = -1; var c2 = 1; var d2 = -4; distance(a1, b1, c1, a2, b2, c2); </script>", "e": 31465, "s": 30730, "text": null }, { "code": null, "e": 31486, "s": 31465, "text": "Angle is 60.0 degree" }, { "code": null, "e": 31501, "s": 31488, "text": "Amber_Saxena" }, { "code": null, "e": 31507, "s": 31501, "text": "ukasp" }, { "code": null, "e": 31520, "s": 31507, "text": "Akanksha_Rai" }, { "code": null, "e": 31527, "s": 31520, "text": "rdtank" }, { "code": null, "e": 31537, "s": 31527, "text": "Geometric" }, { "code": null, "e": 31550, "s": 31537, "text": "Mathematical" }, { "code": null, "e": 31569, "s": 31550, "text": "School Programming" }, { "code": null, "e": 31582, "s": 31569, "text": "Mathematical" }, { "code": null, "e": 31592, "s": 31582, "text": "Geometric" }, { "code": null, "e": 31690, "s": 31592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31699, "s": 31690, "text": "Comments" }, { "code": null, "e": 31712, "s": 31699, "text": "Old Comments" }, { "code": null, "e": 31765, "s": 31712, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 31816, "s": 31765, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 31865, "s": 31816, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 31899, "s": 31865, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 31957, "s": 31899, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 31987, "s": 31957, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32002, "s": 31987, "text": "C++ Data Types" }, { "code": null, "e": 32062, "s": 32002, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32105, "s": 32062, "text": "Set in C++ Standard Template Library (STL)" } ]
Class or Static Variables in Python?
When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance. Class or static variable are quite distinct from and does not conflict with any other member variable with the same name. Below is a program to demonstrate the use of class or static variable − class Fruits(object): count = 0 def __init__(self, name, count): self.name = name self.count = count Fruits.count = Fruits.count + count def main(): apples = Fruits("apples", 3); pears = Fruits("pears", 4); print (apples.count) print (pears.count) print (Fruits.count) print (apples.__class__.count) # This is Fruit.count print (type(pears).count) # So is this if __name__ == '__main__': main() 3 4 7 7 7 Another example to demonstrate the use of variable defined on the class level − class example: staticVariable = 9 # Access through class print (example.staticVariable) # Gives 9 #Access through an instance instance = example() print(instance.staticVariable) #Again gives 9 #Change within an instance instance.staticVariable = 12 print(instance.staticVariable) # Gives 12 print(example.staticVariable) #Gives 9 9 9 12 9
[ { "code": null, "e": 1275, "s": 1062, "text": "When we declare a variable inside a class but outside any method, it is called as class or static variable in python.\nClass or static variable can be referred through a class but not directly through an instance." }, { "code": null, "e": 1469, "s": 1275, "text": "Class or static variable are quite distinct from and does not conflict with any other member variable with the same name. Below is a program to demonstrate the use of class or static variable −" }, { "code": null, "e": 1866, "s": 1469, "text": "class Fruits(object):\ncount = 0\ndef __init__(self, name, count):\nself.name = name\nself.count = count\nFruits.count = Fruits.count + count\n\ndef main():\napples = Fruits(\"apples\", 3);\npears = Fruits(\"pears\", 4);\nprint (apples.count)\nprint (pears.count)\nprint (Fruits.count)\nprint (apples.__class__.count) # This is Fruit.count\nprint (type(pears).count) # So is this\n\nif __name__ == '__main__':\nmain()" }, { "code": null, "e": 1876, "s": 1866, "text": "3\n4\n7\n7\n7" }, { "code": null, "e": 1956, "s": 1876, "text": "Another example to demonstrate the use of variable defined on the class level −" }, { "code": null, "e": 2289, "s": 1956, "text": "class example:\nstaticVariable = 9 # Access through class\n\nprint (example.staticVariable) # Gives 9\n\n#Access through an instance\ninstance = example()\nprint(instance.staticVariable) #Again gives 9\n\n#Change within an instance\ninstance.staticVariable = 12\nprint(instance.staticVariable) # Gives 12\nprint(example.staticVariable) #Gives 9" }, { "code": null, "e": 2298, "s": 2289, "text": "9\n9\n12\n9" } ]
C library function - atof()
The C library function double atof(const char *str) converts the string argument str to a floating-point number (type double). Following is the declaration for atof() function. double atof(const char *str) str − This is the string having the representation of a floating-point number. str − This is the string having the representation of a floating-point number. This function returns the converted floating point number as a double value. If no valid conversion could be performed, it returns zero (0.0). The following example shows the usage of atof() function. #include <stdio.h> #include <stdlib.h> #include <string.h> int main () { float val; char str[20]; strcpy(str, "98993489"); val = atof(str); printf("String value = %s, Float value = %f\n", str, val); strcpy(str, "tutorialspoint.com"); val = atof(str); printf("String value = %s, Float value = %f\n", str, val); return(0); } Let us compile and run the above program that will produce the following result − String value = 98993489, Float value = 98993488.000000 String value = tutorialspoint.com, Float value = 0.000000 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2134, "s": 2007, "text": "The C library function double atof(const char *str) converts the string argument str to a floating-point number (type double)." }, { "code": null, "e": 2184, "s": 2134, "text": "Following is the declaration for atof() function." }, { "code": null, "e": 2213, "s": 2184, "text": "double atof(const char *str)" }, { "code": null, "e": 2292, "s": 2213, "text": "str − This is the string having the representation of a floating-point number." }, { "code": null, "e": 2371, "s": 2292, "text": "str − This is the string having the representation of a floating-point number." }, { "code": null, "e": 2514, "s": 2371, "text": "This function returns the converted floating point number as a double value. If no valid conversion could be performed, it returns zero (0.0)." }, { "code": null, "e": 2572, "s": 2514, "text": "The following example shows the usage of atof() function." }, { "code": null, "e": 2929, "s": 2572, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main () {\n float val;\n char str[20];\n \n strcpy(str, \"98993489\");\n val = atof(str);\n printf(\"String value = %s, Float value = %f\\n\", str, val);\n\n strcpy(str, \"tutorialspoint.com\");\n val = atof(str);\n printf(\"String value = %s, Float value = %f\\n\", str, val);\n\n return(0);\n}" }, { "code": null, "e": 3011, "s": 2929, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3125, "s": 3011, "text": "String value = 98993489, Float value = 98993488.000000\nString value = tutorialspoint.com, Float value = 0.000000\n" }, { "code": null, "e": 3158, "s": 3125, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3173, "s": 3158, "text": " Nishant Malik" }, { "code": null, "e": 3208, "s": 3173, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3223, "s": 3208, "text": " Nishant Malik" }, { "code": null, "e": 3258, "s": 3223, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3272, "s": 3258, "text": " Asif Hussain" }, { "code": null, "e": 3305, "s": 3272, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3323, "s": 3305, "text": " Richa Maheshwari" }, { "code": null, "e": 3358, "s": 3323, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3377, "s": 3358, "text": " Vandana Annavaram" }, { "code": null, "e": 3410, "s": 3377, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3422, "s": 3410, "text": " Amit Diwan" }, { "code": null, "e": 3429, "s": 3422, "text": " Print" }, { "code": null, "e": 3440, "s": 3429, "text": " Add Notes" } ]
jQuery.getScript() Method
The jQuery.getScript( url, [callback] ) method loads and executes a JavaScript file using an HTTP GET request. The method returns XMLHttpRequest object. Here is the simple syntax to use this method − $.getScript( url, [callback] ) Here is the description of all the parameters used by this method − url − A string containing the URL to which the request is sent url − A string containing the URL to which the request is sent callback − This optional parameter represents a function to be executed whenever the data is loaded successfully. callback − This optional parameter represents a function to be executed whenever the data is loaded successfully. Assuming we have following JavaScript content in result.js file − function CheckJS(){ alert("This is JavaScript"); } Following is a simple example a simple showing the usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#driver").click(function(event){ $.getScript('result.js', function(jd) { // Call custom function defined in script CheckJS(); }); }); }); </script> </head> <body> <p>Click on the button to load result.js file −</p> <div id = "stage" style = "background-color:cc0;"> STAGE </div> <input type = "button" id = "driver" value = "Load Data" /> </body> </html> This should produce following result − Click on the button to load result.js file − 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2433, "s": 2322, "text": "The jQuery.getScript( url, [callback] ) method loads and executes a JavaScript file using an HTTP GET request." }, { "code": null, "e": 2475, "s": 2433, "text": "The method returns XMLHttpRequest object." }, { "code": null, "e": 2522, "s": 2475, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2554, "s": 2522, "text": "$.getScript( url, [callback] )\n" }, { "code": null, "e": 2622, "s": 2554, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2685, "s": 2622, "text": "url − A string containing the URL to which the request is sent" }, { "code": null, "e": 2748, "s": 2685, "text": "url − A string containing the URL to which the request is sent" }, { "code": null, "e": 2862, "s": 2748, "text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully." }, { "code": null, "e": 2976, "s": 2862, "text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully." }, { "code": null, "e": 3042, "s": 2976, "text": "Assuming we have following JavaScript content in result.js file −" }, { "code": null, "e": 3096, "s": 3042, "text": "function CheckJS(){\n alert(\"This is JavaScript\");\n}" }, { "code": null, "e": 3170, "s": 3096, "text": "Following is a simple example a simple showing the usage of this method −" }, { "code": null, "e": 3995, "s": 3170, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\t\t\t\n $(\"#driver\").click(function(event){\n $.getScript('result.js', function(jd) {\n // Call custom function defined in script\n CheckJS();\n });\n });\n\t\t\t\t\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load result.js file −</p>\n\t\t\n <div id = \"stage\" style = \"background-color:cc0;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>" }, { "code": null, "e": 4034, "s": 3995, "text": "This should produce following result −" }, { "code": null, "e": 4079, "s": 4034, "text": "Click on the button to load result.js file −" }, { "code": null, "e": 4112, "s": 4079, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4126, "s": 4112, "text": " Mahesh Kumar" }, { "code": null, "e": 4161, "s": 4126, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4175, "s": 4161, "text": " Pratik Singh" }, { "code": null, "e": 4210, "s": 4175, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4227, "s": 4210, "text": " Frahaan Hussain" }, { "code": null, "e": 4260, "s": 4227, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4288, "s": 4260, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4321, "s": 4288, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4342, "s": 4321, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4374, "s": 4342, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4391, "s": 4374, "text": " Laurence Svekis" }, { "code": null, "e": 4398, "s": 4391, "text": " Print" }, { "code": null, "e": 4409, "s": 4398, "text": " Add Notes" } ]
Private Constructors and Singleton Classes in C#
A private constructor is used in classes containing only static member as shown below − class Demo { // private constructor private Demo() { } public static a = 10; } A singleton class has normal methods and you can call it using an instance. To prevent multiple instances of the class, the private constructor is used. Let us see an example − public class Singleton { static Singleton a = null; private Singleton() { } }
[ { "code": null, "e": 1150, "s": 1062, "text": "A private constructor is used in classes containing only static member as shown below −" }, { "code": null, "e": 1239, "s": 1150, "text": "class Demo {\n // private constructor\n private Demo() { }\n\n public static a = 10;\n}" }, { "code": null, "e": 1315, "s": 1239, "text": "A singleton class has normal methods and you can call it using an instance." }, { "code": null, "e": 1392, "s": 1315, "text": "To prevent multiple instances of the class, the private constructor is used." }, { "code": null, "e": 1416, "s": 1392, "text": "Let us see an example −" }, { "code": null, "e": 1503, "s": 1416, "text": "public class Singleton {\n static Singleton a = null;\n private Singleton() {\n }\n}" } ]
How to Change the position of MessageBox using Python Tkinter
Let us suppose that we want to create a dialogue box using tkinter. To create the dialogue box we can use the MessageBox library which contains several functions to quickly create dialogue types. To adjust the position of the created Dialogue Box, we can use its “toplevel” property which basically gives the priority to the current box and keeps all the other processes in the backend. It contains some other functions like title, message, and details. To change the position of the MessageBox widget, we will use geometry method. #import the tkinter library from tkinter import * #define the messagebox function def messagebox(): #toplevel function creates MessageBox dialog which appears on top of the screen top=Toplevel(win) top.title("Click Me") #Define the position of the MessageBox x_position = 600 y_position = 400 top.geometry(f"600x200+{x_position}+{y_position}") #Define the property of the messageBox l1=Label(top, text= "Hello! TutorialsPoint",bg= "green", fg= "white",font=('Times New Roman', 24),height=50, width= 50).pack() #Create an instance of the tkinter frame #And resize the frame win = Tk() win.geometry("600x200") win.title("Window-1") Button(win, text="Click Me", command=messagebox, width=8).pack(pady=80) win.mainloop() Running the above code will generate the following output window. When you click the “Click Me” button, it will open the following dialogue box which can be positioned later.
[ { "code": null, "e": 1258, "s": 1062, "text": "Let us suppose that we want to create a dialogue box using tkinter. To create the\ndialogue box we can use the MessageBox library which contains several functions\nto quickly create dialogue types." }, { "code": null, "e": 1449, "s": 1258, "text": "To adjust the position of the created Dialogue Box, we can use its “toplevel”\nproperty which basically gives the priority to the current box and keeps all the other\nprocesses in the backend." }, { "code": null, "e": 1594, "s": 1449, "text": "It contains some other functions like title, message, and details. To change the position of the MessageBox widget, we will use geometry method." }, { "code": null, "e": 2340, "s": 1594, "text": "#import the tkinter library\n\nfrom tkinter import *\n\n#define the messagebox function\ndef messagebox():\n\n#toplevel function creates MessageBox dialog which appears on top of the screen\n top=Toplevel(win)\n top.title(\"Click Me\")\n #Define the position of the MessageBox\n x_position = 600\n y_position = 400\n top.geometry(f\"600x200+{x_position}+{y_position}\")\n #Define the property of the messageBox\n l1=Label(top, text= \"Hello! TutorialsPoint\",bg= \"green\", fg=\n\"white\",font=('Times New Roman', 24),height=50, width= 50).pack()\n\n#Create an instance of the tkinter frame\n#And resize the frame\nwin = Tk()\nwin.geometry(\"600x200\")\nwin.title(\"Window-1\")\nButton(win, text=\"Click Me\", command=messagebox,\nwidth=8).pack(pady=80)\n\nwin.mainloop()" }, { "code": null, "e": 2406, "s": 2340, "text": "Running the above code will generate the following output window." }, { "code": null, "e": 2515, "s": 2406, "text": "When you click the “Click Me” button, it will open the following dialogue box which\ncan be positioned later." } ]
Java Program to convert integer to hexadecimal
Use the + Integer.toHexString() method in Java to convert integer to hexadecimal. Let’s say the following is our integer. int val = 768; Let us convert it to a hexadecimal value. Integer.toHexString(val) The following is the final example with the output. Live Demo public class Demo { public static void main(String[] args) { int val = 768; // integer System.out.println("Integer: "+val); // hex System.out.println("Hex String = " + Integer.toHexString(val)); } } Integer: 768 Hex String = 300
[ { "code": null, "e": 1144, "s": 1062, "text": "Use the + Integer.toHexString() method in Java to convert integer to hexadecimal." }, { "code": null, "e": 1184, "s": 1144, "text": "Let’s say the following is our integer." }, { "code": null, "e": 1199, "s": 1184, "text": "int val = 768;" }, { "code": null, "e": 1241, "s": 1199, "text": "Let us convert it to a hexadecimal value." }, { "code": null, "e": 1266, "s": 1241, "text": "Integer.toHexString(val)" }, { "code": null, "e": 1318, "s": 1266, "text": "The following is the final example with the output." }, { "code": null, "e": 1329, "s": 1318, "text": " Live Demo" }, { "code": null, "e": 1571, "s": 1329, "text": "public class Demo {\n public static void main(String[] args) {\n int val = 768;\n // integer\n System.out.println(\"Integer: \"+val);\n // hex\n System.out.println(\"Hex String = \" + Integer.toHexString(val));\n }\n}" }, { "code": null, "e": 1601, "s": 1571, "text": "Integer: 768\nHex String = 300" } ]
How to avoid inserting duplicate rows in MySQL?
To avoid inserting duplicate rows in MySQL, you can use UNIQUE(). The syntax is as follows − ALTER TABLE yourTableName ADD UNIQUE(yourColumnName1,yourColumnName2,...N); To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table avoidInsertingDuplicateRows -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstValue int, -> SecondValue int -> ); Query OK, 0 rows affected (0.53 sec) Now check the description of table using desc command. The query is as follows − mysql> desc avoidInsertingDuplicateRows; Sample The following is The output − +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | FirstValue | int(11) | YES | | NULL | | | SecondValue | int(11) | YES | | NULL | | +-------------+---------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) Here is the query to avoid inserting duplicate rows in MySQL. We will set it with the insert command to insert records in the table − mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20); Query OK, 1 row affected (0.24 sec) mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20); ERROR 1062 (23000): Duplicate entry '10-20' for key 'FirstValue' Display all records from the table using select statement. The query is as follows − mysql> select *from avoidInsertingDuplicateRows; Here is the output − +----+------------+-------------+ | Id | FirstValue | SecondValue | +----+------------+-------------+ | 1 | 10 | 20 | +----+------------+-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "To avoid inserting duplicate rows in MySQL, you can use UNIQUE(). The syntax is as follows −" }, { "code": null, "e": 1231, "s": 1155, "text": "ALTER TABLE yourTableName ADD UNIQUE(yourColumnName1,yourColumnName2,...N);" }, { "code": null, "e": 1287, "s": 1231, "text": "To understand the above syntax, let us create a table. " }, { "code": null, "e": 1331, "s": 1287, "text": "The query to create a table is as follows −" }, { "code": null, "e": 1527, "s": 1331, "text": "mysql> create table avoidInsertingDuplicateRows\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> FirstValue int,\n -> SecondValue int\n -> );\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1583, "s": 1527, "text": "Now check the description of table using desc command. " }, { "code": null, "e": 1609, "s": 1583, "text": "The query is as follows −" }, { "code": null, "e": 1650, "s": 1609, "text": "mysql> desc avoidInsertingDuplicateRows;" }, { "code": null, "e": 1687, "s": 1650, "text": "Sample The following is The output −" }, { "code": null, "e": 2174, "s": 1687, "text": "+-------------+---------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+---------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| FirstValue | int(11) | YES | | NULL | |\n| SecondValue | int(11) | YES | | NULL | |\n+-------------+---------+------+-----+---------+----------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2308, "s": 2174, "text": "Here is the query to avoid inserting duplicate rows in MySQL. We will set it with the insert command to insert records in the table −" }, { "code": null, "e": 2581, "s": 2308, "text": "mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);\nERROR 1062 (23000): Duplicate entry '10-20' for key 'FirstValue'" }, { "code": null, "e": 2641, "s": 2581, "text": "Display all records from the table using select statement. " }, { "code": null, "e": 2667, "s": 2641, "text": "The query is as follows −" }, { "code": null, "e": 2716, "s": 2667, "text": "mysql> select *from avoidInsertingDuplicateRows;" }, { "code": null, "e": 2737, "s": 2716, "text": "Here is the output −" }, { "code": null, "e": 2931, "s": 2737, "text": "+----+------------+-------------+\n| Id | FirstValue | SecondValue |\n+----+------------+-------------+\n| 1 | 10 | 20 |\n+----+------------+-------------+\n1 row in set (0.00 sec)" } ]
Swing Examples - Using Checkboxes
Following example showcase how to use standard checkboxes in a Java Swing application. We are using the following APIs. JCheckBox − To create a standard checkbox. JCheckBox − To create a standard checkbox. JCheckBox.setEnabled(false); − To disable a checkbox. JCheckBox.setEnabled(false); − To disable a checkbox. JCheckBox.setMnemonic(KeyEvent.VK_C) − To set a keyboard shortcut a checkbox. JCheckBox.setMnemonic(KeyEvent.VK_C) − To set a keyboard shortcut a checkbox. JCheckBox.setSelected(true) − To set a checkbox selected. JCheckBox.setSelected(true) − To set a checkbox selected. import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JCheckBox checkBox1 = new JCheckBox("Check Me 1"); JCheckBox checkBox2 = new JCheckBox("Check Me 2"); checkBox2.setEnabled(false); JCheckBox checkBox3 = new JCheckBox("Check Me 3"); checkBox3.setMnemonic(KeyEvent.VK_C); checkBox1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); JOptionPane.showMessageDialog(frame, ((JCheckBox)source).getText() + ": " + ((JCheckBox)source).isSelected()); } }); panel.add(checkBox1); panel.add(checkBox2); panel.add(checkBox3); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 2039, "text": "Following example showcase how to use standard checkboxes in a Java Swing application." }, { "code": null, "e": 2159, "s": 2126, "text": "We are using the following APIs." }, { "code": null, "e": 2202, "s": 2159, "text": "JCheckBox − To create a standard checkbox." }, { "code": null, "e": 2245, "s": 2202, "text": "JCheckBox − To create a standard checkbox." }, { "code": null, "e": 2299, "s": 2245, "text": "JCheckBox.setEnabled(false); − To disable a checkbox." }, { "code": null, "e": 2353, "s": 2299, "text": "JCheckBox.setEnabled(false); − To disable a checkbox." }, { "code": null, "e": 2431, "s": 2353, "text": "JCheckBox.setMnemonic(KeyEvent.VK_C) − To set a keyboard shortcut a checkbox." }, { "code": null, "e": 2509, "s": 2431, "text": "JCheckBox.setMnemonic(KeyEvent.VK_C) − To set a keyboard shortcut a checkbox." }, { "code": null, "e": 2567, "s": 2509, "text": "JCheckBox.setSelected(true) − To set a checkbox selected." }, { "code": null, "e": 2625, "s": 2567, "text": "JCheckBox.setSelected(true) − To set a checkbox selected." }, { "code": null, "e": 4252, "s": 2625, "text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\n\nimport javax.swing.JCheckBox;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JCheckBox checkBox1 = new JCheckBox(\"Check Me 1\");\n JCheckBox checkBox2 = new JCheckBox(\"Check Me 2\");\n checkBox2.setEnabled(false);\n JCheckBox checkBox3 = new JCheckBox(\"Check Me 3\");\n checkBox3.setMnemonic(KeyEvent.VK_C);\n\n checkBox1.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n Object source = e.getSource();\n JOptionPane.showMessageDialog(frame, \n ((JCheckBox)source).getText() + \": \" + ((JCheckBox)source).isSelected());\n }\n }); \n\n panel.add(checkBox1);\n panel.add(checkBox2);\n panel.add(checkBox3);\n\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}" }, { "code": null, "e": 4259, "s": 4252, "text": " Print" }, { "code": null, "e": 4270, "s": 4259, "text": " Add Notes" } ]
How to setup Anaconda path to environment variable ? - GeeksforGeeks
06 Nov, 2021 Anaconda is open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming languages. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda. Environment variables basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment. The region from which this variable can be accessed or over which it is defined is termed as the scope of the variable. Download Anaconda for Python. Make sure to download the “Python 3.7 Version” for the appropriate architecture. After the download is over, go through How to install Anaconda on windows? and follow the given instructions. After the installation is done, we need to set up the environment variable. Go to Control Panel -> System and Security -> System Under the Advanced System Setting option click on Environment Variables as shown below: Now, we have to alter the “Path” variable under System variables so that it also contains the path to the Anaconda environment. Select the “Path” variable and click on the Edit button as shown below: We will see a list of different paths, click on the New button and then add the path where Anaconda is installed. Click on OK, Save the settings and it is done !! Now to check whether the installation is done correctly, open the command prompt and type anaconda-navigator. It will start the anaconda navigator App if installed correctly. In Linux, there are several ways to install Anaconda. But we will refer to the simplest and easy way to install Anaconda using the terminal. Go through How to install Anaconda on Linux? and follow the instructions. Generally, the Path variable is automatically set in Linux at the time of installation, but it can also be set manually by the following steps: Go to Application -> Accessories -> Terminal For setting up Environment Variable, type the following command in the Terminal with the use of the Installation path: export ANACONDA = /home/nikhil/anaconda3 For setting up the Environment Value, type the following command in the Terminal with the use of the Installation path: export PATH = $PATH:/home/nikhil/anaconda3/bin It is done!! Now to check whether the installation is done correctly, open Terminal and type anaconda-navigator. It will start the anaconda navigator App if installed correctly. reenadevi98412200 python-basics How To Python 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? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24973, "s": 24945, "text": "\n06 Nov, 2021" }, { "code": null, "e": 25353, "s": 24973, "text": "Anaconda is open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming languages. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda. " }, { "code": null, "e": 25639, "s": 25353, "text": "Environment variables basically define the behavior of the environment. They can affect the processes ongoing or the programs that are executed in the environment. The region from which this variable can be accessed or over which it is defined is termed as the scope of the variable. " }, { "code": null, "e": 25751, "s": 25639, "text": "Download Anaconda for Python. Make sure to download the “Python 3.7 Version” for the appropriate architecture. " }, { "code": null, "e": 25862, "s": 25751, "text": "After the download is over, go through How to install Anaconda on windows? and follow the given instructions. " }, { "code": null, "e": 26080, "s": 25862, "text": "After the installation is done, we need to set up the environment variable. Go to Control Panel -> System and Security -> System Under the Advanced System Setting option click on Environment Variables as shown below: " }, { "code": null, "e": 26281, "s": 26080, "text": "Now, we have to alter the “Path” variable under System variables so that it also contains the path to the Anaconda environment. Select the “Path” variable and click on the Edit button as shown below: " }, { "code": null, "e": 26396, "s": 26281, "text": "We will see a list of different paths, click on the New button and then add the path where Anaconda is installed. " }, { "code": null, "e": 26621, "s": 26396, "text": "Click on OK, Save the settings and it is done !! Now to check whether the installation is done correctly, open the command prompt and type anaconda-navigator. It will start the anaconda navigator App if installed correctly. " }, { "code": null, "e": 26981, "s": 26621, "text": "In Linux, there are several ways to install Anaconda. But we will refer to the simplest and easy way to install Anaconda using the terminal. Go through How to install Anaconda on Linux? and follow the instructions. Generally, the Path variable is automatically set in Linux at the time of installation, but it can also be set manually by the following steps: " }, { "code": null, "e": 27026, "s": 26981, "text": "Go to Application -> Accessories -> Terminal" }, { "code": null, "e": 27146, "s": 27026, "text": "For setting up Environment Variable, type the following command in the Terminal with the use of the Installation path: " }, { "code": null, "e": 27187, "s": 27146, "text": "export ANACONDA = /home/nikhil/anaconda3" }, { "code": null, "e": 27308, "s": 27187, "text": "For setting up the Environment Value, type the following command in the Terminal with the use of the Installation path: " }, { "code": null, "e": 27355, "s": 27308, "text": "export PATH = $PATH:/home/nikhil/anaconda3/bin" }, { "code": null, "e": 27535, "s": 27355, "text": "It is done!! Now to check whether the installation is done correctly, open Terminal and type anaconda-navigator. It will start the anaconda navigator App if installed correctly. " }, { "code": null, "e": 27555, "s": 27537, "text": "reenadevi98412200" }, { "code": null, "e": 27569, "s": 27555, "text": "python-basics" }, { "code": null, "e": 27576, "s": 27569, "text": "How To" }, { "code": null, "e": 27583, "s": 27576, "text": "Python" }, { "code": null, "e": 27681, "s": 27583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27708, "s": 27681, "text": "How to Align Text in HTML?" }, { "code": null, "e": 27753, "s": 27708, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 27801, "s": 27753, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27815, "s": 27801, "text": "Java Tutorial" }, { "code": null, "e": 27849, "s": 27815, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27877, "s": 27849, "text": "Read JSON file using Python" }, { "code": null, "e": 27927, "s": 27877, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27949, "s": 27927, "text": "Python map() function" } ]
Find quotient and remainder by dividing an integer in JavaScript - GeeksforGeeks
23 Apr, 2019 There are various methods to divide an integer number by another number and get its quotient and remainder. Example 1: This example uses the Math.floor() function to calculate the divisor. <!DOCTYPE html> <html> <head> <title> Integer division with remainder. </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "Geek_up"></p> <button onclick = "Geeks()"> Click Here </button> <p id = "Geek_down" style = "color:green;"></p> <script> var up = document.getElementById("Geek_up"); var a = 39; var b = 5; up.innerHTML = a + "/" + b; function Geeks() { var down = document.getElementById("Geek_down"); down.innerHTML = "divisor = " + Math.floor(a/b) + "<br>" + "remainder = "+ a%b; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example uses the binary ~~ operator to calculate the divisor. <!DOCTYPE html> <html> <head> <title> Integer division with remainder. </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "Geek_up"></p> <button onclick = "Geeks()"> Click Here </button> <p id="Geek_down" style="color:green;"></p> <script> var up = document.getElementById("Geek_up"); var a = 39; var b = 5; up.innerHTML = a + "/" + b; function Geeks() { var down = document.getElementById("Geek_down"); var num = ~~(a / b); down.innerHTML = "divisor = " + num + "<br>" + "remainder = "+ a%b; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 3:This example uses the right shift >> operator to calculate the divisor. <!DOCTYPE html> <html> <head> <title> Integer division with remainder. </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "Geek_up"></p> <button onclick = "Geeks()"> Click Here </button> <p id="Geek_down" style="color:green;"></p> <script> var up = document.getElementById("Geek_up"); var a = 39; var b = 5; up.innerHTML = a + "/" + b; function Geeks() { var down = document.getElementById("Geek_down"); var num = (a / b) >> 0; down.innerHTML = "divisor = " + num + "<br>" + "remainder = "+ a%b; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-math JavaScript-Misc JavaScript Web Technologies Web technologies Questions 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 How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 37970, "s": 37942, "text": "\n23 Apr, 2019" }, { "code": null, "e": 38078, "s": 37970, "text": "There are various methods to divide an integer number by another number and get its quotient and remainder." }, { "code": null, "e": 38159, "s": 38078, "text": "Example 1: This example uses the Math.floor() function to calculate the divisor." }, { "code": "<!DOCTYPE html> <html> <head> <title> Integer division with remainder. </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"Geek_up\"></p> <button onclick = \"Geeks()\"> Click Here </button> <p id = \"Geek_down\" style = \"color:green;\"></p> <script> var up = document.getElementById(\"Geek_up\"); var a = 39; var b = 5; up.innerHTML = a + \"/\" + b; function Geeks() { var down = document.getElementById(\"Geek_down\"); down.innerHTML = \"divisor = \" + Math.floor(a/b) + \"<br>\" + \"remainder = \"+ a%b; } </script> </body> </html> ", "e": 38926, "s": 38159, "text": null }, { "code": null, "e": 38934, "s": 38926, "text": "Output:" }, { "code": null, "e": 38965, "s": 38934, "text": "Before clicking on the button:" }, { "code": null, "e": 38995, "s": 38965, "text": "After clicking on the button:" }, { "code": null, "e": 39073, "s": 38995, "text": "Example 2: This example uses the binary ~~ operator to calculate the divisor." }, { "code": "<!DOCTYPE html> <html> <head> <title> Integer division with remainder. </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"Geek_up\"></p> <button onclick = \"Geeks()\"> Click Here </button> <p id=\"Geek_down\" style=\"color:green;\"></p> <script> var up = document.getElementById(\"Geek_up\"); var a = 39; var b = 5; up.innerHTML = a + \"/\" + b; function Geeks() { var down = document.getElementById(\"Geek_down\"); var num = ~~(a / b); down.innerHTML = \"divisor = \" + num + \"<br>\" + \"remainder = \"+ a%b; } </script> </body> </html> ", "e": 39864, "s": 39073, "text": null }, { "code": null, "e": 39872, "s": 39864, "text": "Output:" }, { "code": null, "e": 39903, "s": 39872, "text": "Before clicking on the button:" }, { "code": null, "e": 39933, "s": 39903, "text": "After clicking on the button:" }, { "code": null, "e": 40015, "s": 39933, "text": "Example 3:This example uses the right shift >> operator to calculate the divisor." }, { "code": "<!DOCTYPE html> <html> <head> <title> Integer division with remainder. </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"Geek_up\"></p> <button onclick = \"Geeks()\"> Click Here </button> <p id=\"Geek_down\" style=\"color:green;\"></p> <script> var up = document.getElementById(\"Geek_up\"); var a = 39; var b = 5; up.innerHTML = a + \"/\" + b; function Geeks() { var down = document.getElementById(\"Geek_down\"); var num = (a / b) >> 0; down.innerHTML = \"divisor = \" + num + \"<br>\" + \"remainder = \"+ a%b; } </script> </body> </html> ", "e": 40803, "s": 40015, "text": null }, { "code": null, "e": 40811, "s": 40803, "text": "Output:" }, { "code": null, "e": 40842, "s": 40811, "text": "Before clicking on the button:" }, { "code": null, "e": 40872, "s": 40842, "text": "After clicking on the button:" }, { "code": null, "e": 40888, "s": 40872, "text": "javascript-math" }, { "code": null, "e": 40904, "s": 40888, "text": "JavaScript-Misc" }, { "code": null, "e": 40915, "s": 40904, "text": "JavaScript" }, { "code": null, "e": 40932, "s": 40915, "text": "Web Technologies" }, { "code": null, "e": 40959, "s": 40932, "text": "Web technologies Questions" }, { "code": null, "e": 41057, "s": 40959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41102, "s": 41057, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41163, "s": 41102, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 41232, "s": 41163, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 41304, "s": 41232, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41356, "s": 41304, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 41398, "s": 41356, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 41431, "s": 41398, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41474, "s": 41431, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41536, "s": 41474, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Short-Circuiting in C++ and Linux - GeeksforGeeks
17 Dec, 2021 Short-circuiting is one of the optimization steps of the compiler, in this step unnecessary calculation is avoided during the evaluation of an expression. Expression is evaluated from left to right. It works under certain cases when the value of the expression can be calculated certainly by only evaluating parts of the expression. Short-circuiting in C++In C++ short-circuiting occurs while evaluating ‘&&’ (AND) and ‘||'(OR) logical operators. While evaluating ‘&&’ operator if the left-hand side of ‘&&’ gives false, then the expression will always yield false irrespective of the value of the right-hand side of ‘&&’, so checking right-hand side of ‘&&’ makes no sense. So, in this situation evaluation of the right-hand side is avoided by the compiler. Similarly, in the case of logical OR ‘||’ operation when the left-hand side gives ‘true’, the result of the expression will always be true irrespective of the value of the right-hand side. Short-circuiting using AND(&&) and OR(||) logical operator. C++ #include <bits/stdc++.h>using namespace std; int main(){ // Short circuiting // logical "||"(OR) int a = 1, b = 1, c = 1; // a and b are equal if (a == b || c++) { cout << "Value of 'c' will" << " not increment due" << " to short-circuit" << endl; } else { cout << "Value of 'c' " << " is incremented as there" << " is no short-circuit" << endl; } // Short circuiting // logical "&&"(OR) if (a == b && c++) { cout << "Value of 'c' will" << " increment as there" << " is no short circuit" << endl; } else { cout << "Value of 'c' will" << " not increment due to short circuit" << endl; }} Value of 'c' will not increment due to short-circuit Value of 'c' will increment as there is no short circuit Short Circuiting in Linux In Linux, short-circuiting takes place while evaluating ‘&&’ and ‘||’ operators just like C++. Logical AND(&&) short circuiting: PHP if [[ "$1" -gt 5 ]] && [[ "$1" -lt 10 ]]; then echo "This output will not be printed"else echo "This output will be printed" " actually due to short circuit" fi if [[ "$1" -lt 5 ]] && [[ "$1" -lt 10 ]]; then echo "This output will be printed" " as there will be no short circuit"else echo "This output will be printed" " actually due to short circuit" fi Output: Logical OR(||) short-circuiting: PHP if [[ "$1" -lt 5 ]] || [[ "$1" -gt 10 ]]; then echo "This output will be printed" " actually due to short circuit" else echo "This output will be printed" " as there will be no short circuit" fi if [[ "$1" -gt 5 ]] || [[ "$1" -lt 10 ]]; then echo "This output will be printed" " as there will be no short circuit"else echo "This output will be printed" " actually due to short circuit" fi Output: Note: ‘&&’ operator is often used as a replacement to ‘if’ statement. For example, to check for the existence of a file you could use either of the below: if [[ -e “$filename” ]]; thenecho “exists”fi [[ -e “$filename” ]] && echo “exists” In this case, bash first executes the expression on the left of the &&(and). If that expression has a non-zero return value (i.e. it failed), then there is no need to evaluate the right side of the && because the overall exit status is already known to be non-zero since both sides have to return a success indicator for a logical and to return success. surinderdawra388 prachisoda1234 cpp-operator Operators C++ Linux-Unix cpp-operator Operators CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 23733, "s": 23705, "text": "\n17 Dec, 2021" }, { "code": null, "e": 24066, "s": 23733, "text": "Short-circuiting is one of the optimization steps of the compiler, in this step unnecessary calculation is avoided during the evaluation of an expression. Expression is evaluated from left to right. It works under certain cases when the value of the expression can be calculated certainly by only evaluating parts of the expression." }, { "code": null, "e": 24681, "s": 24066, "text": "Short-circuiting in C++In C++ short-circuiting occurs while evaluating ‘&&’ (AND) and ‘||'(OR) logical operators. While evaluating ‘&&’ operator if the left-hand side of ‘&&’ gives false, then the expression will always yield false irrespective of the value of the right-hand side of ‘&&’, so checking right-hand side of ‘&&’ makes no sense. So, in this situation evaluation of the right-hand side is avoided by the compiler. Similarly, in the case of logical OR ‘||’ operation when the left-hand side gives ‘true’, the result of the expression will always be true irrespective of the value of the right-hand side." }, { "code": null, "e": 24741, "s": 24681, "text": "Short-circuiting using AND(&&) and OR(||) logical operator." }, { "code": null, "e": 24745, "s": 24741, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ // Short circuiting // logical \"||\"(OR) int a = 1, b = 1, c = 1; // a and b are equal if (a == b || c++) { cout << \"Value of 'c' will\" << \" not increment due\" << \" to short-circuit\" << endl; } else { cout << \"Value of 'c' \" << \" is incremented as there\" << \" is no short-circuit\" << endl; } // Short circuiting // logical \"&&\"(OR) if (a == b && c++) { cout << \"Value of 'c' will\" << \" increment as there\" << \" is no short circuit\" << endl; } else { cout << \"Value of 'c' will\" << \" not increment due to short circuit\" << endl; }}", "e": 25538, "s": 24745, "text": null }, { "code": null, "e": 25649, "s": 25538, "text": "Value of 'c' will not increment due to short-circuit\nValue of 'c' will increment as there is no short circuit" }, { "code": null, "e": 25772, "s": 25651, "text": "Short Circuiting in Linux In Linux, short-circuiting takes place while evaluating ‘&&’ and ‘||’ operators just like C++." }, { "code": null, "e": 25807, "s": 25772, "text": "Logical AND(&&) short circuiting: " }, { "code": null, "e": 25811, "s": 25807, "text": "PHP" }, { "code": "if [[ \"$1\" -gt 5 ]] && [[ \"$1\" -lt 10 ]]; then echo \"This output will not be printed\"else echo \"This output will be printed\" \" actually due to short circuit\" fi if [[ \"$1\" -lt 5 ]] && [[ \"$1\" -lt 10 ]]; then echo \"This output will be printed\" \" as there will be no short circuit\"else echo \"This output will be printed\" \" actually due to short circuit\" fi", "e": 26209, "s": 25811, "text": null }, { "code": null, "e": 26218, "s": 26209, "text": "Output: " }, { "code": null, "e": 26251, "s": 26218, "text": "Logical OR(||) short-circuiting:" }, { "code": null, "e": 26255, "s": 26251, "text": "PHP" }, { "code": "if [[ \"$1\" -lt 5 ]] || [[ \"$1\" -gt 10 ]]; then echo \"This output will be printed\" \" actually due to short circuit\" else echo \"This output will be printed\" \" as there will be no short circuit\" fi if [[ \"$1\" -gt 5 ]] || [[ \"$1\" -lt 10 ]]; then echo \"This output will be printed\" \" as there will be no short circuit\"else echo \"This output will be printed\" \" actually due to short circuit\" fi", "e": 26692, "s": 26255, "text": null }, { "code": null, "e": 26700, "s": 26692, "text": "Output:" }, { "code": null, "e": 26770, "s": 26700, "text": "Note: ‘&&’ operator is often used as a replacement to ‘if’ statement." }, { "code": null, "e": 26855, "s": 26770, "text": "For example, to check for the existence of a file you could use either of the below:" }, { "code": null, "e": 26900, "s": 26855, "text": "if [[ -e “$filename” ]]; thenecho “exists”fi" }, { "code": null, "e": 26938, "s": 26900, "text": "[[ -e “$filename” ]] && echo “exists”" }, { "code": null, "e": 27293, "s": 26938, "text": "In this case, bash first executes the expression on the left of the &&(and). If that expression has a non-zero return value (i.e. it failed), then there is no need to evaluate the right side of the && because the overall exit status is already known to be non-zero since both sides have to return a success indicator for a logical and to return success. " }, { "code": null, "e": 27310, "s": 27293, "text": "surinderdawra388" }, { "code": null, "e": 27325, "s": 27310, "text": "prachisoda1234" }, { "code": null, "e": 27338, "s": 27325, "text": "cpp-operator" }, { "code": null, "e": 27348, "s": 27338, "text": "Operators" }, { "code": null, "e": 27352, "s": 27348, "text": "C++" }, { "code": null, "e": 27363, "s": 27352, "text": "Linux-Unix" }, { "code": null, "e": 27376, "s": 27363, "text": "cpp-operator" }, { "code": null, "e": 27386, "s": 27376, "text": "Operators" }, { "code": null, "e": 27390, "s": 27386, "text": "CPP" }, { "code": null, "e": 27488, "s": 27390, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27497, "s": 27488, "text": "Comments" }, { "code": null, "e": 27510, "s": 27497, "text": "Old Comments" }, { "code": null, "e": 27538, "s": 27510, "text": "Operator Overloading in C++" }, { "code": null, "e": 27562, "s": 27538, "text": "Sorting a vector in C++" }, { "code": null, "e": 27595, "s": 27562, "text": "Friend class and function in C++" }, { "code": null, "e": 27615, "s": 27595, "text": "Polymorphism in C++" }, { "code": null, "e": 27659, "s": 27615, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 27699, "s": 27659, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 27739, "s": 27699, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 27766, "s": 27739, "text": "grep command in Unix/Linux" }, { "code": null, "e": 27801, "s": 27766, "text": "cut command in Linux with examples" } ]
Operators in Java - GeeksforGeeks
21 Apr, 2022 Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. Some of the types are: Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operatorsinstance of operator Arithmetic Operators Unary Operators Assignment Operator Relational Operators Logical Operators Ternary Operator Bitwise Operators Shift Operators instance of operator Let’s take a look at them in detail. 1. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types. * : Multiplication / : Division % : Modulo + : Addition – : Subtraction 2. Unary Operators: Unary operators need only one operand. They are used to increment, decrement or negate a value. – : Unary minus, used for negating the values. + : Unary plus indicates the positive value (numbers are positive without this, however). It performs an automatic conversion to int when the type of its operand is the byte, char, or short. This is called unary numeric promotion. ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment operators. Post-Increment: Value is first used for computing the result and then incremented.Pre-Increment: Value is incremented first, and then the result is computed. Post-Increment: Value is first used for computing the result and then incremented. Pre-Increment: Value is incremented first, and then the result is computed. — : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operators. Post-decrement: Value is first used for computing the result and then decremented.Pre-Decrement: Value is decremented first, and then the result is computed. Post-decrement: Value is first used for computing the result and then decremented. Pre-Decrement: Value is decremented first, and then the result is computed. ! : Logical not operator, used for inverting a boolean value. 3. Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable. It has a right to left associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is: variable = value; In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5. +=, for adding left operand with right operand and then assigning it to the variable on the left. -=, for subtracting right operand from left operand and then assigning it to the variable on the left. *=, for multiplying left operand with right operand and then assigning it to the variable on the left. /=, for dividing left operand by right operand and then assigning it to the variable on the left. %=, for assigning modulo of left operand by right operand and then assigning it to the variable on the left. 4. Relational Operators: These operators are used to check for relations like equality, greater than, less than. They return boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements. The general format is, variable relation_operator value Some of the relational operators are- ==, Equal to: returns true if the left-hand side is equal to the right-hand side.!=, Not Equal to: returns true if the left-hand side is not equal to the right-hand side.<, less than: returns true if the left-hand side is less than the right-hand side.<=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.>, Greater than: returns true if the left-hand side is greater than the right-hand side.>=, Greater than or equal to: returns true if the left-hand side is greater than or equal to the right-hand side. ==, Equal to: returns true if the left-hand side is equal to the right-hand side. !=, Not Equal to: returns true if the left-hand side is not equal to the right-hand side. <, less than: returns true if the left-hand side is less than the right-hand side. <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side. >, Greater than: returns true if the left-hand side is greater than the right-hand side. >=, Greater than or equal to: returns true if the left-hand side is greater than or equal to the right-hand side. 5. Logical Operators: These operators are used to perform “logical AND” and “logical OR” operations, i.e., the function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Java also have “Logical NOT”, it returns true when condition is false and vice-versa Conditional operators are: &&, Logical AND: returns true when both conditions are true. ||, Logical OR: returns true if at least one condition is true. ! , Logical NOT: returns true when condition is false and vice-versa 6. Ternary operator: Ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name ternary. The general format is: condition ? if true : if false The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:.’ Java // Java program to illustrate// max of three numbers using// ternary operator.public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 30, result; // result holds max of three // numbers result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c); System.out.println("Max of three numbers = " + result); }} Max of three numbers = 30 7. Bitwise Operators: These operators are used to perform the manipulation of individual bits of a number. They can be used with any of the integer types. They are used when performing update and query operations of the Binary indexed trees. &, Bitwise AND operator: returns bit by bit AND of input values. |, Bitwise OR operator: returns bit by bit OR of input values. ^, Bitwise XOR operator: returns bit by bit XOR of input values. ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the input value, i.e., with all bits inverted. 8. Shift Operators: These operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two, respectively. They can be used when we have to multiply or divide a number by two. General format- number shift_op number_of_places_to_shift; <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two. >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of the initial number. Similar effect as of dividing the number with some power of two. >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0. 9. instanceof operator: The instance of the operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass, or an interface. General format- object instance of class/subclass/interface Java // Java program to illustrate// instance of operatorclass operators { public static void main(String[] args) { Person obj1 = new Person(); Person obj2 = new Boy(); // As obj is of type person, it is not an // instance of Boy or interface System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person)); System.out.println("obj1 instanceof Boy: " + (obj1 instanceof Boy)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); // Since obj2 is of type boy, // whose parent class is person // and it implements the interface Myinterface // it is instance of all of these classes System.out.println("obj2 instanceof Person: " + (obj2 instanceof Person)); System.out.println("obj2 instanceof Boy: " + (obj2 instanceof Boy)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); }} class Person {} class Boy extends Person implements MyInterface {} interface MyInterface {} obj1 instanceof Person: true obj1 instanceof Boy: false obj1 instanceof MyInterface: false obj2 instanceof Person: true obj2 instanceof Boy: true obj2 instanceof MyInterface: true Precedence and associative rules are used when dealing with hybrid equations involving more than one type of operator. In such cases, these rules determine which part of the equation to consider first, as there can be many different valuations for the same equation. The below table depicts the precedence of operators in decreasing order as magnitude, with the top representing the highest precedence and the bottom showing the lowest precedence. 1. Precedence and Associativity: There is often confusion when it comes to hybrid equations that are equations having multiple operators. The problem is which part to solve first. There is a golden rule to follow in these situations. If the operators have different precedence, solve the higher precedence first. If they have the same precedence, solve according to associativity, that is, either from right to left or from left to right. Explanation of the below program is well written in comments within the program itself. Java public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30; // precedence rules for arithmetic operators. // (* = / = %) > (+ = -) // prints a+(b/d) System.out.println("a+b/d = " + (a + b / d)); // if same precendence then associative // rules are followed. // e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f) System.out.println("a+b*d-e/f = " + (a + b * d - e / f)); }} a+b/d = 20 a+b*d-e/f = 219 2. Be a Compiler: Compiler in our systems uses a lex tool to match the greatest match when generating tokens. This creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too many of the readers, this might seem to create a compiler error. But this statement is absolutely correct as the token created by lex are a, =, b, ++, +, c. Therefore, this statement has a similar effect of first assigning b+c to a and then incrementing b. Similarly, a=b+++++c; would generate error as tokens generated are a, =, b, ++, ++, +, c. which is actually an error as there is no operand after the second unary operand. Java public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 0; // a=b+++c is compiled as // b++ +c // a=b+c then b=b+1 a = b++ + c; System.out.println("Value of a(b+c), " + " b(b+1), c = " + a + ", " + b + ", " + c); // a=b+++++c is compiled as // b++ ++ +c // which gives error. // a=b+++++c; // System.out.println(b+++++c); }} Value of a(b+c), b(b+1), c = 10, 11, 0 3. Using + over (): When using + operator inside system.out.println() make sure to do addition using parenthesis. If we write something before doing addition, then string addition takes place, that is, associativity of addition is left to right, and hence integers are added to a string first producing a string, and string objects concatenate when using +. Therefore it can create unwanted results. Java public class operators { public static void main(String[] args) { int x = 5, y = 8; // concatenates x and y as // first x is added to "concatenation (x+y) = " // producing "concatenation (x+y) = 5" // and then 8 is further concatenated. System.out.println("Concatenation (x+y)= " + x + y); // addition of x and y System.out.println("Addition (x+y) = " + (x + y)); }} Concatenation (x+y)= 58 Addition (x+y) = 13 This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above. Tarun21 Aniket Krishna tejaswikurella Shreevardhan vkramsngh07 manmeetjuneja5 aadarsh baid punamsingh628700 nishkarshgandhi madhavgupta22 java-basics Java-Operators Java School Programming Java-Operators Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Reverse a string in Java Arrays.sort() in Java with examples How to iterate any Map in Java Initialize an ArrayList in Java Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 28559, "s": 28531, "text": "\n21 Apr, 2022" }, { "code": null, "e": 28722, "s": 28559, "text": "Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. Some of the types are:" }, { "code": null, "e": 28882, "s": 28722, "text": "Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operatorsinstance of operator" }, { "code": null, "e": 28903, "s": 28882, "text": "Arithmetic Operators" }, { "code": null, "e": 28919, "s": 28903, "text": "Unary Operators" }, { "code": null, "e": 28939, "s": 28919, "text": "Assignment Operator" }, { "code": null, "e": 28960, "s": 28939, "text": "Relational Operators" }, { "code": null, "e": 28978, "s": 28960, "text": "Logical Operators" }, { "code": null, "e": 28995, "s": 28978, "text": "Ternary Operator" }, { "code": null, "e": 29013, "s": 28995, "text": "Bitwise Operators" }, { "code": null, "e": 29029, "s": 29013, "text": "Shift Operators" }, { "code": null, "e": 29050, "s": 29029, "text": "instance of operator" }, { "code": null, "e": 29088, "s": 29050, "text": "Let’s take a look at them in detail. " }, { "code": null, "e": 29193, "s": 29088, "text": "1. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types. " }, { "code": null, "e": 29212, "s": 29193, "text": "* : Multiplication" }, { "code": null, "e": 29225, "s": 29212, "text": "/ : Division" }, { "code": null, "e": 29236, "s": 29225, "text": "% : Modulo" }, { "code": null, "e": 29249, "s": 29236, "text": "+ : Addition" }, { "code": null, "e": 29265, "s": 29249, "text": "– : Subtraction" }, { "code": null, "e": 29382, "s": 29265, "text": "2. Unary Operators: Unary operators need only one operand. They are used to increment, decrement or negate a value. " }, { "code": null, "e": 29429, "s": 29382, "text": "– : Unary minus, used for negating the values." }, { "code": null, "e": 29660, "s": 29429, "text": "+ : Unary plus indicates the positive value (numbers are positive without this, however). It performs an automatic conversion to int when the type of its operand is the byte, char, or short. This is called unary numeric promotion." }, { "code": null, "e": 29929, "s": 29660, "text": "++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment operators. Post-Increment: Value is first used for computing the result and then incremented.Pre-Increment: Value is incremented first, and then the result is computed." }, { "code": null, "e": 30012, "s": 29929, "text": "Post-Increment: Value is first used for computing the result and then incremented." }, { "code": null, "e": 30088, "s": 30012, "text": "Pre-Increment: Value is incremented first, and then the result is computed." }, { "code": null, "e": 30356, "s": 30088, "text": "— : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operators. Post-decrement: Value is first used for computing the result and then decremented.Pre-Decrement: Value is decremented first, and then the result is computed." }, { "code": null, "e": 30439, "s": 30356, "text": "Post-decrement: Value is first used for computing the result and then decremented." }, { "code": null, "e": 30515, "s": 30439, "text": "Pre-Decrement: Value is decremented first, and then the result is computed." }, { "code": null, "e": 30577, "s": 30515, "text": "! : Logical not operator, used for inverting a boolean value." }, { "code": null, "e": 30898, "s": 30577, "text": "3. Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable. It has a right to left associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side value must be declared before using it or should be a constant. " }, { "code": null, "e": 30948, "s": 30898, "text": "The general format of the assignment operator is:" }, { "code": null, "e": 30966, "s": 30948, "text": "variable = value;" }, { "code": null, "e": 31170, "s": 30966, "text": "In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5. " }, { "code": null, "e": 31268, "s": 31170, "text": "+=, for adding left operand with right operand and then assigning it to the variable on the left." }, { "code": null, "e": 31371, "s": 31268, "text": "-=, for subtracting right operand from left operand and then assigning it to the variable on the left." }, { "code": null, "e": 31474, "s": 31371, "text": "*=, for multiplying left operand with right operand and then assigning it to the variable on the left." }, { "code": null, "e": 31572, "s": 31474, "text": "/=, for dividing left operand by right operand and then assigning it to the variable on the left." }, { "code": null, "e": 31681, "s": 31572, "text": "%=, for assigning modulo of left operand by right operand and then assigning it to the variable on the left." }, { "code": null, "e": 31957, "s": 31681, "text": "4. Relational Operators: These operators are used to check for relations like equality, greater than, less than. They return boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements. The general format is, " }, { "code": null, "e": 31990, "s": 31957, "text": "variable relation_operator value" }, { "code": null, "e": 32588, "s": 31990, "text": "Some of the relational operators are- ==, Equal to: returns true if the left-hand side is equal to the right-hand side.!=, Not Equal to: returns true if the left-hand side is not equal to the right-hand side.<, less than: returns true if the left-hand side is less than the right-hand side.<=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.>, Greater than: returns true if the left-hand side is greater than the right-hand side.>=, Greater than or equal to: returns true if the left-hand side is greater than or equal to the right-hand side." }, { "code": null, "e": 32670, "s": 32588, "text": "==, Equal to: returns true if the left-hand side is equal to the right-hand side." }, { "code": null, "e": 32760, "s": 32670, "text": "!=, Not Equal to: returns true if the left-hand side is not equal to the right-hand side." }, { "code": null, "e": 32843, "s": 32760, "text": "<, less than: returns true if the left-hand side is less than the right-hand side." }, { "code": null, "e": 32950, "s": 32843, "text": "<=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side." }, { "code": null, "e": 33039, "s": 32950, "text": ">, Greater than: returns true if the left-hand side is greater than the right-hand side." }, { "code": null, "e": 33153, "s": 33039, "text": ">=, Greater than or equal to: returns true if the left-hand side is greater than or equal to the right-hand side." }, { "code": null, "e": 33619, "s": 33153, "text": "5. Logical Operators: These operators are used to perform “logical AND” and “logical OR” operations, i.e., the function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Java also have “Logical NOT”, it returns true when condition is false and vice-versa" }, { "code": null, "e": 33646, "s": 33619, "text": "Conditional operators are:" }, { "code": null, "e": 33707, "s": 33646, "text": "&&, Logical AND: returns true when both conditions are true." }, { "code": null, "e": 33771, "s": 33707, "text": "||, Logical OR: returns true if at least one condition is true." }, { "code": null, "e": 33840, "s": 33771, "text": "! , Logical NOT: returns true when condition is false and vice-versa" }, { "code": null, "e": 33977, "s": 33840, "text": "6. Ternary operator: Ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name ternary." }, { "code": null, "e": 34000, "s": 33977, "text": "The general format is:" }, { "code": null, "e": 34031, "s": 34000, "text": "condition ? if true : if false" }, { "code": null, "e": 34185, "s": 34031, "text": "The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:.’ " }, { "code": null, "e": 34190, "s": 34185, "text": "Java" }, { "code": "// Java program to illustrate// max of three numbers using// ternary operator.public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 30, result; // result holds max of three // numbers result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c); System.out.println(\"Max of three numbers = \" + result); }}", "e": 34607, "s": 34190, "text": null }, { "code": null, "e": 34633, "s": 34607, "text": "Max of three numbers = 30" }, { "code": null, "e": 34876, "s": 34633, "text": "7. Bitwise Operators: These operators are used to perform the manipulation of individual bits of a number. They can be used with any of the integer types. They are used when performing update and query operations of the Binary indexed trees. " }, { "code": null, "e": 34941, "s": 34876, "text": "&, Bitwise AND operator: returns bit by bit AND of input values." }, { "code": null, "e": 35004, "s": 34941, "text": "|, Bitwise OR operator: returns bit by bit OR of input values." }, { "code": null, "e": 35069, "s": 35004, "text": "^, Bitwise XOR operator: returns bit by bit XOR of input values." }, { "code": null, "e": 35226, "s": 35069, "text": "~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the input value, i.e., with all bits inverted." }, { "code": null, "e": 35467, "s": 35226, "text": "8. Shift Operators: These operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two, respectively. They can be used when we have to multiply or divide a number by two. General format- " }, { "code": null, "e": 35511, "s": 35467, "text": " number shift_op number_of_places_to_shift;" }, { "code": null, "e": 35685, "s": 35511, "text": "<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two." }, { "code": null, "e": 35925, "s": 35685, "text": ">>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of the initial number. Similar effect as of dividing the number with some power of two." }, { "code": null, "e": 36073, "s": 35925, "text": ">>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0." }, { "code": null, "e": 36262, "s": 36073, "text": "9. instanceof operator: The instance of the operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass, or an interface. General format- " }, { "code": null, "e": 36306, "s": 36262, "text": "object instance of class/subclass/interface" }, { "code": null, "e": 36311, "s": 36306, "text": "Java" }, { "code": "// Java program to illustrate// instance of operatorclass operators { public static void main(String[] args) { Person obj1 = new Person(); Person obj2 = new Boy(); // As obj is of type person, it is not an // instance of Boy or interface System.out.println(\"obj1 instanceof Person: \" + (obj1 instanceof Person)); System.out.println(\"obj1 instanceof Boy: \" + (obj1 instanceof Boy)); System.out.println(\"obj1 instanceof MyInterface: \" + (obj1 instanceof MyInterface)); // Since obj2 is of type boy, // whose parent class is person // and it implements the interface Myinterface // it is instance of all of these classes System.out.println(\"obj2 instanceof Person: \" + (obj2 instanceof Person)); System.out.println(\"obj2 instanceof Boy: \" + (obj2 instanceof Boy)); System.out.println(\"obj2 instanceof MyInterface: \" + (obj2 instanceof MyInterface)); }} class Person {} class Boy extends Person implements MyInterface {} interface MyInterface {}", "e": 37519, "s": 36311, "text": null }, { "code": null, "e": 37699, "s": 37519, "text": "obj1 instanceof Person: true\nobj1 instanceof Boy: false\nobj1 instanceof MyInterface: false\nobj2 instanceof Person: true\nobj2 instanceof Boy: true\nobj2 instanceof MyInterface: true" }, { "code": null, "e": 38147, "s": 37699, "text": "Precedence and associative rules are used when dealing with hybrid equations involving more than one type of operator. In such cases, these rules determine which part of the equation to consider first, as there can be many different valuations for the same equation. The below table depicts the precedence of operators in decreasing order as magnitude, with the top representing the highest precedence and the bottom showing the lowest precedence." }, { "code": null, "e": 38674, "s": 38147, "text": "1. Precedence and Associativity: There is often confusion when it comes to hybrid equations that are equations having multiple operators. The problem is which part to solve first. There is a golden rule to follow in these situations. If the operators have different precedence, solve the higher precedence first. If they have the same precedence, solve according to associativity, that is, either from right to left or from left to right. Explanation of the below program is well written in comments within the program itself." }, { "code": null, "e": 38679, "s": 38674, "text": "Java" }, { "code": "public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30; // precedence rules for arithmetic operators. // (* = / = %) > (+ = -) // prints a+(b/d) System.out.println(\"a+b/d = \" + (a + b / d)); // if same precendence then associative // rules are followed. // e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f) System.out.println(\"a+b*d-e/f = \" + (a + b * d - e / f)); }}", "e": 39197, "s": 38679, "text": null }, { "code": null, "e": 39224, "s": 39197, "text": "a+b/d = 20\na+b*d-e/f = 219" }, { "code": null, "e": 39859, "s": 39224, "text": "2. Be a Compiler: Compiler in our systems uses a lex tool to match the greatest match when generating tokens. This creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too many of the readers, this might seem to create a compiler error. But this statement is absolutely correct as the token created by lex are a, =, b, ++, +, c. Therefore, this statement has a similar effect of first assigning b+c to a and then incrementing b. Similarly, a=b+++++c; would generate error as tokens generated are a, =, b, ++, ++, +, c. which is actually an error as there is no operand after the second unary operand." }, { "code": null, "e": 39864, "s": 39859, "text": "Java" }, { "code": "public class operators { public static void main(String[] args) { int a = 20, b = 10, c = 0; // a=b+++c is compiled as // b++ +c // a=b+c then b=b+1 a = b++ + c; System.out.println(\"Value of a(b+c), \" + \" b(b+1), c = \" + a + \", \" + b + \", \" + c); // a=b+++++c is compiled as // b++ ++ +c // which gives error. // a=b+++++c; // System.out.println(b+++++c); }}", "e": 40363, "s": 39864, "text": null }, { "code": null, "e": 40403, "s": 40363, "text": "Value of a(b+c), b(b+1), c = 10, 11, 0" }, { "code": null, "e": 40803, "s": 40403, "text": "3. Using + over (): When using + operator inside system.out.println() make sure to do addition using parenthesis. If we write something before doing addition, then string addition takes place, that is, associativity of addition is left to right, and hence integers are added to a string first producing a string, and string objects concatenate when using +. Therefore it can create unwanted results." }, { "code": null, "e": 40808, "s": 40803, "text": "Java" }, { "code": "public class operators { public static void main(String[] args) { int x = 5, y = 8; // concatenates x and y as // first x is added to \"concatenation (x+y) = \" // producing \"concatenation (x+y) = 5\" // and then 8 is further concatenated. System.out.println(\"Concatenation (x+y)= \" + x + y); // addition of x and y System.out.println(\"Addition (x+y) = \" + (x + y)); }}", "e": 41243, "s": 40808, "text": null }, { "code": null, "e": 41287, "s": 41243, "text": "Concatenation (x+y)= 58\nAddition (x+y) = 13" }, { "code": null, "e": 41710, "s": 41287, "text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above." }, { "code": null, "e": 41718, "s": 41710, "text": "Tarun21" }, { "code": null, "e": 41733, "s": 41718, "text": "Aniket Krishna" }, { "code": null, "e": 41748, "s": 41733, "text": "tejaswikurella" }, { "code": null, "e": 41761, "s": 41748, "text": "Shreevardhan" }, { "code": null, "e": 41773, "s": 41761, "text": "vkramsngh07" }, { "code": null, "e": 41788, "s": 41773, "text": "manmeetjuneja5" }, { "code": null, "e": 41801, "s": 41788, "text": "aadarsh baid" }, { "code": null, "e": 41818, "s": 41801, "text": "punamsingh628700" }, { "code": null, "e": 41834, "s": 41818, "text": "nishkarshgandhi" }, { "code": null, "e": 41848, "s": 41834, "text": "madhavgupta22" }, { "code": null, "e": 41860, "s": 41848, "text": "java-basics" }, { "code": null, "e": 41875, "s": 41860, "text": "Java-Operators" }, { "code": null, "e": 41880, "s": 41875, "text": "Java" }, { "code": null, "e": 41899, "s": 41880, "text": "School Programming" }, { "code": null, "e": 41914, "s": 41899, "text": "Java-Operators" }, { "code": null, "e": 41919, "s": 41914, "text": "Java" }, { "code": null, "e": 42017, "s": 41919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42026, "s": 42017, "text": "Comments" }, { "code": null, "e": 42039, "s": 42026, "text": "Old Comments" }, { "code": null, "e": 42083, "s": 42039, "text": "Split() String method in Java with examples" }, { "code": null, "e": 42108, "s": 42083, "text": "Reverse a string in Java" }, { "code": null, "e": 42144, "s": 42108, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 42175, "s": 42144, "text": "How to iterate any Map in Java" }, { "code": null, "e": 42207, "s": 42175, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 42225, "s": 42207, "text": "Python Dictionary" }, { "code": null, "e": 42241, "s": 42225, "text": "Arrays in C/C++" }, { "code": null, "e": 42266, "s": 42241, "text": "Reverse a string in Java" }, { "code": null, "e": 42285, "s": 42266, "text": "Inheritance in C++" } ]
Raspberry Pi - Linux Shell
The Shell, called Bash in Raspberry Pi, is the text-based way of issuing instructions to your Pi board. In this chapter, let us learn about the Linux shell in Raspberry Pi. First, we will understand how to open a shell window. You can open a shell window by using one of the two following ways − There is a Terminal icon, having a >_ prompt, on the top of the screen. Click on it and you will get a shell window. There is a Terminal icon, having a >_ prompt, on the top of the screen. Click on it and you will get a shell window. Another way is to use the Accessories section of the Application menu. You can find the Terminal there. Another way is to use the Accessories section of the Application menu. You can find the Terminal there. Both of the above approaches will open a shell window on the desktop. The prompt looks like as follows − pi@raspberrypi ~ $ It contains lots of information. Let us see the various bits − pi It represents the name of that user who logged in. raspberrypi It represents the hostname of the machine i.e.; the name other computers use to identify when connecting to it. The tilde symbol (~) The tilde symbol tells the user which directory they are looking at. The presence of this horizontal wiggly line is known as home directory and the presence of this symbol shows that we are working in that directory. The dollar sign ($) It represents the presence of the ordinary user and not all-powerful superuser. A # symbol means a superuser. When you start the shell window, you start in your home directory. To see the folders and files in your home directory, you need to issue a command which is as follows − pi@raspberrypi ~ $ ls The output is as follows − Desktop Downloads Pictures python_games Videos Documents Music Public Templates You can see the files and folders after issuing the ls command. As we know that Linux is case sensitive hence the commands LS, Ls, ls and lS are all different. You can see the above output, it’s all blue which means these are all directories. We can go to these directories and check which files they contain. The command to change the directory is cd. You need to use the cd command along with the name of the directory which you want to see. The example for changing the directory in Raspberry Pi is given below − pi@raspberrypi ~ $ cd Pictures The command to find the information about a particular file is file. You need to put the name of the file after the command to check the information about that file. Check the below example for finding information about the files in Raspberry Pi− pi@raspberrypi ~ /Pictures $ file leekha.png aarav.png leekha.png: PNG image data, 50 x 85, 8-bit/color RGBA, noninterlaced aarav.png: PNG image data, 100 x 150, 8-bit/color RGBA, noninterlaced We can also use the file command on directories. It will give us some information about the directories as well − pi@raspberrypi ~ $ file Pictures Desktop Pictures: directory Desktop: directory Earlier, we have used the cd command to change into a directory that is inside the current working directory. But sometimes, we need to go to the parent directory i.e. into the directory which is above the current working directory. The command for this is cd..(cd with two dots), as given below − pi@raspberrypi ~ /Pictures $ cd.. pi@raspberrypi ~ $ The tilde symbol represents your home directory. The following diagram shows the part of the directory tree on your Raspberry Pi computer − The directories and their uses are as follows − bin Bin, short for binaries, contains some small programs that behave like commands in the shell. For example, ls and mkdir. boot This directory contains the heart of the OS i.e. the Linux kernel. It also contains the configuration files containing the technical settings for Raspberry Pi computer. dev This directory contains a list of devices. For example, the devices like disks and network connections. etc This directory is used for various configuration files. These configuration files apply to all the users on the computer. home This is the directory where a user can store or write files by default. lib The directory contains various libraries that are used by different OS programs. lost+found This directory is used, if the file system gets corrupted and recovers partially. media You connect a removable storage device such as a USB key and it is automatically recognized. All the details will be stored in the media directory. mnt mnt stands for mount and will store all the details of the removable storage devices that we mount ourselves. root It is reserved for the use of the root users and we don’t have the permission to change into this directory as an ordinary user. The shell enables the Raspberry Pi users to go straight to the location by specifying a path. We have the following two types of paths − It is a bit like giving the directions to the directory from where the user is now. On the other hand, an absolute path is like a street address. This path is exactly the same wherever the user is. These paths are measured from the root. Hence, they start with a slash (/). For example, we know the absolute path to the pi directory is /home/pi. Now, go straight forward to this directory by using the following command − cd /home/pi If you want to go to the root, you can use the following command − cd / We can use the listing command (ls) to look inside any directory outside the current working directory as follows − pi@raspberrypi ~ $ ls /boot There are several advanced options, which we can use with the ls command. These options are given in the following table − This option is 1 not l and it outputs the results in a single column instead of a row. The ls command with this option will display all the files. All the files will also include hidden files. This option will add a symbol besides a filename. It will do this to indicate the file type. If you use this option, you will notice a / after directories names and a * after executable files. This option is short for human-readable. It expresses file sizes by using kilobytes, megabytes, and gigabytes. This option will display the result in the long format. It shows the information about the permissions of files, their last modification date, their size. This option will list the result as a list separated by commas. This option is the recursive option. It will also list files and directories in the current working directories, open the subdirectories(if any) and list their results too. This option will sort the result as per the date and time they were last modified. This option will sort your result as per the file extension. Furthermore, we will learn about the other important aspects related to Linux Shell in Raspberry Pi. Long format is one of the most useful formats of the ls command, because it provides us the additional information on the file. You can use the ls command with the long listing option as follows − pi@raspberrypi ~ $ ls -l total 65 -rw-r--r-- 1 pi pi 256 Feb 18 22:45 Leekha.txt drwxr-xr-x 2 pi pi 4096 Jan 25 17:45 Desktop drwxr-xr-x 5 pi pi 4096 Jan 25 17:50 Documents drwxr-xr-x 2 pi pi 4096 Jan 25 17:52 Downloads drwxr-xr-x 2 pi pi 4096 Jan 25 17:53 Music drwxr-xr-x 2 pi pi 4096 Jan 25 17:45 Pictures drwxr-xr-x 2 pi pi 4096 Jan 25 17:45 Public drwxr-xr-x 2 pi pi 4096 Jan 25 17:54 Templates drwxr-xr-x 2 pi pi 4096 Jan 25 17:54 Videos From the above output, it is very easy to understand that each line relates to one file or directory having its name on the right and the date and time, when it was last modified next to that. The number 256, 4096 represents the size of the file. You can see some files and directories are having the same size. The remaining part of this output shows the permissions i.e. who is allowed to use the file and what the user is allowed to do with that file or directory. The permissions on a file are divided in the following three categories − Owner It is the person who created the file. This permission consists of the things the file owner can do. Group These are the people who belong to a group that has the permission to use the file. This permission consists of the things which the group owners can do. World These are known as the world permissions i.e. the things that everyone can do with that file or directory. In Raspberry Pi, we have two main types of files. One is regular files which have a hyphen (-) and others are directories having a d. Now let us understand the different types of permissions the owner, group and world have respectively − Read permission − This permission gives the user ability to open and look at the contents of a file or to list a directory. Read permission − This permission gives the user ability to open and look at the contents of a file or to list a directory. Write permission − This permission gives the user the ability to change the content of a file. It allows the user to create or delete the files in a directory. Write permission − This permission gives the user the ability to change the content of a file. It allows the user to create or delete the files in a directory. Execute permission − This permission gives the user an ability to treat a file as a program and run it. It also gives permission to enter a directory using the cd command. Execute permission − This permission gives the user an ability to treat a file as a program and run it. It also gives permission to enter a directory using the cd command. The ls command deluges with the information that you cannot even notice sometimes, because it flies past our eyes faster than we understand or see it. To avoid this or solve this problem, we can use a command called less. This command will take our listing and enable us to page through it and that is one screen at a time. To use this command, we need to use a | (pipe character) after the listing (ls) command. The example of less command in Raspberry Pi is given below − ls -RXF | less The less command can also be used to view the content of a text file. For this, we need to provide the filename as an argument, as given below − less /boot/config.txt Here we will be learning few tricks to speed up the use of the shell − If you want to retype a command, then you can save retyping it because, shell keeps the record of history i.e. the commands you entered previously. If you want to retype a command, then you can save retyping it because, shell keeps the record of history i.e. the commands you entered previously. In case if you want to reuse your last command, you just need to use two exclamation marks and press enter. In case if you want to reuse your last command, you just need to use two exclamation marks and press enter. You can also bring back the previous commands in order by tapping the up arrow. You can also bring back the previous commands in order by tapping the up arrow. Similarly, you can also move through your history of commands in another direction by tapping the down arrow. Similarly, you can also move through your history of commands in another direction by tapping the down arrow. The shell also guesses what the user wants to type and it also automatically completes it for us. The shell also guesses what the user wants to type and it also automatically completes it for us. Redirecting files means, you can send the results from a command to a file instead of sending the results to the screen. For this, we need to use a > (greater-than) sign along with the file name, which we would like to send the output to. The example of creating file by using redirection in Raspberry Pi is given below − ls > ~/gaurav.txt There are other commands too and with their help, we can display the content online. These commands are explained below − The echo command, as the name implies, will display on screen whatever we write after it. The best use of this command is to solve mathematical problems. You need to put the expression between two pairs of brackets and put a dollar sign in front. The example of echo command is given below − echo $((5*5)) The date command, as the name implies, will display on screen the current date and time. The cal command (cal stands for calculator) will display the current month’s calendar with today highlighted. With the help of option -y, you can see the whole year calendar. Here, we will understand how to create and remove directories in Raspberry Pi. Let us begin by learning about creating directories. The command to create a directory under your home directory is mkdir. In the below example, we will be creating a directory named AI_Python − mkdir AI_Python You can also use one command to create several directories as follows − pi@raspberrypi ~ $ mkdir AI_Python Machine_Learning Tutorialspoint pi@raspberrypi ~ $ ls Downloads AI_Python Machine_Learning Tutorialspoint Desktop Pictures Documents Public If you want to remove an empty directory, you can use the command rmdir as follows − pi@raspberrypi ~ $ rmdir AI_Python On the other hand, if you want to remove non-empty directories, you need to use the command rm -R as follows − pi@raspberrypi ~ $ rm -R Machine_Learning We can use the rm command to delete a file. The syntax for deleting a file would be as follows − rm options filename In an example given below, we will be deleting a text file named leekha.txt − pi@raspberrypi ~ $ rm leekha.txt Like mkdir, the rm command will not tell us what it is doing. To know its function, we need to use the verbose(-v) option as follows − pi@raspberrypi ~ $ rm -v leekha.txt removed 'leekha.txt' We can also delete more than one file at a time as follows − pi@raspberrypi ~ $ rm -v leekha.txt gaurav.txt aarav.txt removed 'leekha.txt' removed 'gaurav.txt' removed 'aarav.txt' A directory contains a lot of files with the similar filenames and if you want to delete a group of such files, you don’t need to repeat the command by typing out each filename. In shell, wildcards will do this job for us. Following table provides us a quick reference to the wildcards, which we can use in Raspberry Pi − The below given example will remove all the files starting with letters lee, rm –vi lee* Copying files is one of the fundamentals things we would like to do. The command for this is cp, which can be used as follows − cp [options] copy_from copy_to Here, we need to replace copy_from with the file you want to copy and copy_to for where you want to copy it. Let us see an example of using the command to copy the respective file. Suppose, if you want to copy the file leekha.txt from the /desktop directory to the home directory, you can use the cp command as follows − cp /Desktop/leekha.txt ~ We can also specify a path to an existing folder to send the file to as follows − cp /Desktop/leekha.txt ~/doc/ Rather than making a copy of the file, if you want to move it from one place to another then, you can use the mv command as follows − mv ~/Desktop/leekha.txt ~/Documents The above command will move the file named leekha.txt from Desktop directory to the Documents directory. Both of these directories are in the home directory. With the help of following command, we can reboot our Raspberry Pi without disconnecting and reconnecting the power − sudo reboot With the help of following command, we can safely turn off our Raspberry Pi − sudo halt 48 Lectures 2 hours Comfiny 27 Lectures 2 hours Axel Mammitzsch 25 Lectures 1 hours Axel Mammitzsch 96 Lectures 9.5 hours Edouard Renard 10 Lectures 34 mins Ashraf Said 12 Lectures 45 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2190, "s": 1963, "text": "The Shell, called Bash in Raspberry Pi, is the text-based way of issuing instructions to your Pi board. In this chapter, let us learn about the Linux shell in Raspberry Pi. First, we will understand how to open a shell window." }, { "code": null, "e": 2259, "s": 2190, "text": "You can open a shell window by using one of the two following ways −" }, { "code": null, "e": 2376, "s": 2259, "text": "There is a Terminal icon, having a >_ prompt, on the top of the screen. Click on it and you will get a shell window." }, { "code": null, "e": 2493, "s": 2376, "text": "There is a Terminal icon, having a >_ prompt, on the top of the screen. Click on it and you will get a shell window." }, { "code": null, "e": 2597, "s": 2493, "text": "Another way is to use the Accessories section of the Application menu. You can find the Terminal there." }, { "code": null, "e": 2701, "s": 2597, "text": "Another way is to use the Accessories section of the Application menu. You can find the Terminal there." }, { "code": null, "e": 2771, "s": 2701, "text": "Both of the above approaches will open a shell window on the desktop." }, { "code": null, "e": 2806, "s": 2771, "text": "The prompt looks like as follows −" }, { "code": null, "e": 2826, "s": 2806, "text": "pi@raspberrypi ~ $\n" }, { "code": null, "e": 2889, "s": 2826, "text": "It contains lots of information. Let us see the various bits −" }, { "code": null, "e": 2892, "s": 2889, "text": "pi" }, { "code": null, "e": 2943, "s": 2892, "text": "It represents the name of that user who logged in." }, { "code": null, "e": 2955, "s": 2943, "text": "raspberrypi" }, { "code": null, "e": 3067, "s": 2955, "text": "It represents the hostname of the machine i.e.; the name other computers use to identify when connecting to it." }, { "code": null, "e": 3088, "s": 3067, "text": "The tilde symbol (~)" }, { "code": null, "e": 3305, "s": 3088, "text": "The tilde symbol tells the user which directory they are looking at. The presence of this horizontal wiggly line is known as home directory and the presence of this symbol shows that we are working in that directory." }, { "code": null, "e": 3325, "s": 3305, "text": "The dollar sign ($)" }, { "code": null, "e": 3435, "s": 3325, "text": "It represents the presence of the ordinary user and not all-powerful superuser. A # symbol means a superuser." }, { "code": null, "e": 3502, "s": 3435, "text": "When you start the shell window, you start in your home directory." }, { "code": null, "e": 3605, "s": 3502, "text": "To see the folders and files in your home directory, you need to issue a command which is as follows −" }, { "code": null, "e": 3628, "s": 3605, "text": "pi@raspberrypi ~ $ ls\n" }, { "code": null, "e": 3655, "s": 3628, "text": "The output is as follows −" }, { "code": null, "e": 3736, "s": 3655, "text": "Desktop Downloads Pictures python_games Videos\nDocuments Music Public Templates\n" }, { "code": null, "e": 3800, "s": 3736, "text": "You can see the files and folders after issuing the ls command." }, { "code": null, "e": 3896, "s": 3800, "text": "As we know that Linux is case sensitive hence the commands LS, Ls, ls and lS are all different." }, { "code": null, "e": 4180, "s": 3896, "text": "You can see the above output, it’s all blue which means these are all directories. We can go to these directories and check which files they contain. The command to change the directory is cd. You need to use the cd command along with the name of the directory which you want to see." }, { "code": null, "e": 4252, "s": 4180, "text": "The example for changing the directory in Raspberry Pi is given below −" }, { "code": null, "e": 4284, "s": 4252, "text": "pi@raspberrypi ~ $ cd Pictures\n" }, { "code": null, "e": 4450, "s": 4284, "text": "The command to find the information about a particular file is file. You need to put the name of the file after the command to check the information about that file." }, { "code": null, "e": 4531, "s": 4450, "text": "Check the below example for finding information about the files in Raspberry Pi−" }, { "code": null, "e": 4726, "s": 4531, "text": "pi@raspberrypi ~ /Pictures $ file leekha.png aarav.png\nleekha.png: PNG image data, 50 x 85, 8-bit/color RGBA, noninterlaced\naarav.png: PNG image data, 100 x 150, 8-bit/color RGBA, noninterlaced\n" }, { "code": null, "e": 4840, "s": 4726, "text": "We can also use the file command on directories. It will give us some information about the directories as well −" }, { "code": null, "e": 4921, "s": 4840, "text": "pi@raspberrypi ~ $ file Pictures Desktop\nPictures: directory\nDesktop: directory\n" }, { "code": null, "e": 5154, "s": 4921, "text": "Earlier, we have used the cd command to change into a directory that is inside the current working directory. But sometimes, we need to go to the parent directory i.e. into the directory which is above the current working directory." }, { "code": null, "e": 5219, "s": 5154, "text": "The command for this is cd..(cd with two dots), as given below −" }, { "code": null, "e": 5273, "s": 5219, "text": "pi@raspberrypi ~ /Pictures $ cd..\npi@raspberrypi ~ $\n" }, { "code": null, "e": 5322, "s": 5273, "text": "The tilde symbol represents your home directory." }, { "code": null, "e": 5413, "s": 5322, "text": "The following diagram shows the part of the directory tree on your Raspberry Pi computer −" }, { "code": null, "e": 5461, "s": 5413, "text": "The directories and their uses are as follows −" }, { "code": null, "e": 5465, "s": 5461, "text": "bin" }, { "code": null, "e": 5586, "s": 5465, "text": "Bin, short for binaries, contains some small programs that behave like commands in the shell. For example, ls and mkdir." }, { "code": null, "e": 5591, "s": 5586, "text": "boot" }, { "code": null, "e": 5760, "s": 5591, "text": "This directory contains the heart of the OS i.e. the Linux kernel. It also contains the configuration files containing the technical settings for Raspberry Pi computer." }, { "code": null, "e": 5764, "s": 5760, "text": "dev" }, { "code": null, "e": 5868, "s": 5764, "text": "This directory contains a list of devices. For example, the devices like disks and network connections." }, { "code": null, "e": 5872, "s": 5868, "text": "etc" }, { "code": null, "e": 5994, "s": 5872, "text": "This directory is used for various configuration files. These configuration files apply to all the users on the computer." }, { "code": null, "e": 5999, "s": 5994, "text": "home" }, { "code": null, "e": 6071, "s": 5999, "text": "This is the directory where a user can store or write files by default." }, { "code": null, "e": 6075, "s": 6071, "text": "lib" }, { "code": null, "e": 6156, "s": 6075, "text": "The directory contains various libraries that are used by different OS programs." }, { "code": null, "e": 6167, "s": 6156, "text": "lost+found" }, { "code": null, "e": 6249, "s": 6167, "text": "This directory is used, if the file system gets corrupted and recovers partially." }, { "code": null, "e": 6255, "s": 6249, "text": "media" }, { "code": null, "e": 6403, "s": 6255, "text": "You connect a removable storage device such as a USB key and it is automatically recognized. All the details will be stored in the media directory." }, { "code": null, "e": 6407, "s": 6403, "text": "mnt" }, { "code": null, "e": 6517, "s": 6407, "text": "mnt stands for mount and will store all the details of the removable storage devices that we mount ourselves." }, { "code": null, "e": 6522, "s": 6517, "text": "root" }, { "code": null, "e": 6651, "s": 6522, "text": "It is reserved for the use of the root users and we don’t have the permission to change into this directory as an ordinary user." }, { "code": null, "e": 6745, "s": 6651, "text": "The shell enables the Raspberry Pi users to go straight to the location by specifying a path." }, { "code": null, "e": 6788, "s": 6745, "text": "We have the following two types of paths −" }, { "code": null, "e": 6872, "s": 6788, "text": "It is a bit like giving the directions to the directory from where the user is now." }, { "code": null, "e": 7062, "s": 6872, "text": "On the other hand, an absolute path is like a street address. This path is exactly the same wherever the user is. These paths are measured from the root. Hence, they start with a slash (/)." }, { "code": null, "e": 7134, "s": 7062, "text": "For example, we know the absolute path to the pi directory is /home/pi." }, { "code": null, "e": 7210, "s": 7134, "text": "Now, go straight forward to this directory by using the following command −" }, { "code": null, "e": 7223, "s": 7210, "text": "cd /home/pi\n" }, { "code": null, "e": 7290, "s": 7223, "text": "If you want to go to the root, you can use the following command −" }, { "code": null, "e": 7296, "s": 7290, "text": "cd /\n" }, { "code": null, "e": 7412, "s": 7296, "text": "We can use the listing command (ls) to look inside any directory outside the current working directory as follows −" }, { "code": null, "e": 7441, "s": 7412, "text": "pi@raspberrypi ~ $ ls /boot\n" }, { "code": null, "e": 7515, "s": 7441, "text": "There are several advanced options, which we can use with the ls command." }, { "code": null, "e": 7564, "s": 7515, "text": "These options are given in the following table −" }, { "code": null, "e": 7651, "s": 7564, "text": "This option is 1 not l and it outputs the results in a single column instead of a row." }, { "code": null, "e": 7757, "s": 7651, "text": "The ls command with this option will display all the files. All the files will also include hidden files." }, { "code": null, "e": 7950, "s": 7757, "text": "This option will add a symbol besides a filename. It will do this to indicate the file type. If you use this option, you will notice a / after directories names and a * after executable files." }, { "code": null, "e": 8061, "s": 7950, "text": "This option is short for human-readable. It expresses file sizes by using kilobytes, megabytes, and gigabytes." }, { "code": null, "e": 8216, "s": 8061, "text": "This option will display the result in the long format. It shows the information about the permissions of files, their last modification date, their size." }, { "code": null, "e": 8280, "s": 8216, "text": "This option will list the result as a list separated by commas." }, { "code": null, "e": 8453, "s": 8280, "text": "This option is the recursive option. It will also list files and directories in the current working directories, open the subdirectories(if any) and list their results too." }, { "code": null, "e": 8536, "s": 8453, "text": "This option will sort the result as per the date and time they were last modified." }, { "code": null, "e": 8597, "s": 8536, "text": "This option will sort your result as per the file extension." }, { "code": null, "e": 8698, "s": 8597, "text": "Furthermore, we will learn about the other important aspects related to Linux Shell in Raspberry Pi." }, { "code": null, "e": 8826, "s": 8698, "text": "Long format is one of the most useful formats of the ls command, because it provides us the additional information on the file." }, { "code": null, "e": 8895, "s": 8826, "text": "You can use the ls command with the long listing option as follows −" }, { "code": null, "e": 9340, "s": 8895, "text": "pi@raspberrypi ~ $ ls -l\ntotal 65\n-rw-r--r-- 1 pi pi 256 Feb 18 22:45 Leekha.txt\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:45 Desktop\ndrwxr-xr-x 5 pi pi 4096 Jan 25 17:50 Documents\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:52 Downloads\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:53 Music\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:45 Pictures\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:45 Public\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:54 Templates\ndrwxr-xr-x 2 pi pi 4096 Jan 25 17:54 Videos\n" }, { "code": null, "e": 9533, "s": 9340, "text": "From the above output, it is very easy to understand that each line relates to one file or directory having its name on the right and the date and time, when it was last modified next to that." }, { "code": null, "e": 9652, "s": 9533, "text": "The number 256, 4096 represents the size of the file. You can see some files and directories are having the same size." }, { "code": null, "e": 9808, "s": 9652, "text": "The remaining part of this output shows the permissions i.e. who is allowed to use the file and what the user is allowed to do with that file or directory." }, { "code": null, "e": 9882, "s": 9808, "text": "The permissions on a file are divided in the following three categories −" }, { "code": null, "e": 9888, "s": 9882, "text": "Owner" }, { "code": null, "e": 9989, "s": 9888, "text": "It is the person who created the file. This permission consists of the things the file owner can do." }, { "code": null, "e": 9995, "s": 9989, "text": "Group" }, { "code": null, "e": 10149, "s": 9995, "text": "These are the people who belong to a group that has the permission to use the file. This permission consists of the things which the group owners can do." }, { "code": null, "e": 10155, "s": 10149, "text": "World" }, { "code": null, "e": 10262, "s": 10155, "text": "These are known as the world permissions i.e. the things that everyone can do with that file or directory." }, { "code": null, "e": 10396, "s": 10262, "text": "In Raspberry Pi, we have two main types of files. One is regular files which have a hyphen (-) and others are directories having a d." }, { "code": null, "e": 10500, "s": 10396, "text": "Now let us understand the different types of permissions the owner, group and world have respectively −" }, { "code": null, "e": 10624, "s": 10500, "text": "Read permission − This permission gives the user ability to open and look at the contents of a file or to list a directory." }, { "code": null, "e": 10748, "s": 10624, "text": "Read permission − This permission gives the user ability to open and look at the contents of a file or to list a directory." }, { "code": null, "e": 10908, "s": 10748, "text": "Write permission − This permission gives the user the ability to change the content of a file. It allows the user to create or delete the files in a directory." }, { "code": null, "e": 11068, "s": 10908, "text": "Write permission − This permission gives the user the ability to change the content of a file. It allows the user to create or delete the files in a directory." }, { "code": null, "e": 11240, "s": 11068, "text": "Execute permission − This permission gives the user an ability to treat a file as a program and run it. It also gives permission to enter a directory using the cd command." }, { "code": null, "e": 11412, "s": 11240, "text": "Execute permission − This permission gives the user an ability to treat a file as a program and run it. It also gives permission to enter a directory using the cd command." }, { "code": null, "e": 11634, "s": 11412, "text": "The ls command deluges with the information that you cannot even notice sometimes, because it flies past our eyes faster than we understand or see it. To avoid this or solve this problem, we can use a command called less." }, { "code": null, "e": 11825, "s": 11634, "text": "This command will take our listing and enable us to page through it and that is one screen at a time. To use this command, we need to use a | (pipe character) after the listing (ls) command." }, { "code": null, "e": 11886, "s": 11825, "text": "The example of less command in Raspberry Pi is given below −" }, { "code": null, "e": 11902, "s": 11886, "text": "ls -RXF | less\n" }, { "code": null, "e": 11972, "s": 11902, "text": "The less command can also be used to view the content of a text file." }, { "code": null, "e": 12047, "s": 11972, "text": "For this, we need to provide the filename as an argument, as given below −" }, { "code": null, "e": 12070, "s": 12047, "text": "less /boot/config.txt\n" }, { "code": null, "e": 12141, "s": 12070, "text": "Here we will be learning few tricks to speed up the use of the shell −" }, { "code": null, "e": 12289, "s": 12141, "text": "If you want to retype a command, then you can save retyping it because, shell keeps the record of history i.e. the commands you entered previously." }, { "code": null, "e": 12437, "s": 12289, "text": "If you want to retype a command, then you can save retyping it because, shell keeps the record of history i.e. the commands you entered previously." }, { "code": null, "e": 12545, "s": 12437, "text": "In case if you want to reuse your last command, you just need to use two exclamation marks and press enter." }, { "code": null, "e": 12653, "s": 12545, "text": "In case if you want to reuse your last command, you just need to use two exclamation marks and press enter." }, { "code": null, "e": 12733, "s": 12653, "text": "You can also bring back the previous commands in order by tapping the up arrow." }, { "code": null, "e": 12813, "s": 12733, "text": "You can also bring back the previous commands in order by tapping the up arrow." }, { "code": null, "e": 12923, "s": 12813, "text": "Similarly, you can also move through your history of commands in another direction by tapping the down arrow." }, { "code": null, "e": 13033, "s": 12923, "text": "Similarly, you can also move through your history of commands in another direction by tapping the down arrow." }, { "code": null, "e": 13131, "s": 13033, "text": "The shell also guesses what the user wants to type and it also automatically completes it for us." }, { "code": null, "e": 13229, "s": 13131, "text": "The shell also guesses what the user wants to type and it also automatically completes it for us." }, { "code": null, "e": 13468, "s": 13229, "text": "Redirecting files means, you can send the results from a command to a file instead of sending the results to the screen. For this, we need to use a > (greater-than) sign along with the file name, which we would like to send the output to." }, { "code": null, "e": 13551, "s": 13468, "text": "The example of creating file by using redirection in Raspberry Pi is given below −" }, { "code": null, "e": 13570, "s": 13551, "text": "ls > ~/gaurav.txt\n" }, { "code": null, "e": 13692, "s": 13570, "text": "There are other commands too and with their help, we can display the content online. These commands are explained below −" }, { "code": null, "e": 13939, "s": 13692, "text": "The echo command, as the name implies, will display on screen whatever we write after it. The best use of this command is to solve mathematical problems. You need to put the expression between two pairs of brackets and put a dollar sign in front." }, { "code": null, "e": 13984, "s": 13939, "text": "The example of echo command is given below −" }, { "code": null, "e": 13999, "s": 13984, "text": "echo $((5*5))\n" }, { "code": null, "e": 14088, "s": 13999, "text": "The date command, as the name implies, will display on screen the current date and time." }, { "code": null, "e": 14263, "s": 14088, "text": "The cal command (cal stands for calculator) will display the current month’s calendar with today highlighted. With the help of option -y, you can see the whole year calendar." }, { "code": null, "e": 14395, "s": 14263, "text": "Here, we will understand how to create and remove directories in Raspberry Pi. Let us begin by learning about creating directories." }, { "code": null, "e": 14465, "s": 14395, "text": "The command to create a directory under your home directory is mkdir." }, { "code": null, "e": 14537, "s": 14465, "text": "In the below example, we will be creating a directory named AI_Python −" }, { "code": null, "e": 14554, "s": 14537, "text": "mkdir AI_Python\n" }, { "code": null, "e": 14626, "s": 14554, "text": "You can also use one command to create several directories as follows −" }, { "code": null, "e": 14802, "s": 14626, "text": "pi@raspberrypi ~ $ mkdir AI_Python Machine_Learning Tutorialspoint\npi@raspberrypi ~ $ ls\nDownloads AI_Python Machine_Learning Tutorialspoint Desktop Pictures Documents Public\n" }, { "code": null, "e": 14887, "s": 14802, "text": "If you want to remove an empty directory, you can use the command rmdir as follows −" }, { "code": null, "e": 14923, "s": 14887, "text": "pi@raspberrypi ~ $ rmdir AI_Python\n" }, { "code": null, "e": 15034, "s": 14923, "text": "On the other hand, if you want to remove non-empty directories, you need to use the command rm -R as follows −" }, { "code": null, "e": 15077, "s": 15034, "text": "pi@raspberrypi ~ $ rm -R Machine_Learning\n" }, { "code": null, "e": 15121, "s": 15077, "text": "We can use the rm command to delete a file." }, { "code": null, "e": 15174, "s": 15121, "text": "The syntax for deleting a file would be as follows −" }, { "code": null, "e": 15195, "s": 15174, "text": "rm options filename\n" }, { "code": null, "e": 15273, "s": 15195, "text": "In an example given below, we will be deleting a text file named leekha.txt −" }, { "code": null, "e": 15307, "s": 15273, "text": "pi@raspberrypi ~ $ rm leekha.txt\n" }, { "code": null, "e": 15369, "s": 15307, "text": "Like mkdir, the rm command will not tell us what it is doing." }, { "code": null, "e": 15442, "s": 15369, "text": "To know its function, we need to use the verbose(-v) option as follows −" }, { "code": null, "e": 15500, "s": 15442, "text": "pi@raspberrypi ~ $ rm -v leekha.txt\nremoved 'leekha.txt'\n" }, { "code": null, "e": 15561, "s": 15500, "text": "We can also delete more than one file at a time as follows −" }, { "code": null, "e": 15681, "s": 15561, "text": "pi@raspberrypi ~ $ rm -v leekha.txt gaurav.txt aarav.txt\nremoved 'leekha.txt'\nremoved 'gaurav.txt'\nremoved 'aarav.txt'\n" }, { "code": null, "e": 15904, "s": 15681, "text": "A directory contains a lot of files with the similar filenames and if you want to delete a group of such files, you don’t need to repeat the command by typing out each filename. In shell, wildcards will do this job for us." }, { "code": null, "e": 16003, "s": 15904, "text": "Following table provides us a quick reference to the wildcards, which we can use in Raspberry Pi −" }, { "code": null, "e": 16080, "s": 16003, "text": "The below given example will remove all the files starting with letters lee," }, { "code": null, "e": 16093, "s": 16080, "text": "rm –vi lee*\n" }, { "code": null, "e": 16162, "s": 16093, "text": "Copying files is one of the fundamentals things we would like to do." }, { "code": null, "e": 16221, "s": 16162, "text": "The command for this is cp, which can be used as follows −" }, { "code": null, "e": 16253, "s": 16221, "text": "cp [options] copy_from copy_to\n" }, { "code": null, "e": 16362, "s": 16253, "text": "Here, we need to replace copy_from with the file you want to copy and copy_to for where you want to copy it." }, { "code": null, "e": 16434, "s": 16362, "text": "Let us see an example of using the command to copy the respective file." }, { "code": null, "e": 16574, "s": 16434, "text": "Suppose, if you want to copy the file leekha.txt from the /desktop directory to the home directory, you can use the cp command as follows −" }, { "code": null, "e": 16600, "s": 16574, "text": "cp /Desktop/leekha.txt ~\n" }, { "code": null, "e": 16682, "s": 16600, "text": "We can also specify a path to an existing folder to send the file to as follows −" }, { "code": null, "e": 16713, "s": 16682, "text": "cp /Desktop/leekha.txt ~/doc/\n" }, { "code": null, "e": 16847, "s": 16713, "text": "Rather than making a copy of the file, if you want to move it from one place to another then, you can use the mv command as follows −" }, { "code": null, "e": 16884, "s": 16847, "text": "mv ~/Desktop/leekha.txt ~/Documents\n" }, { "code": null, "e": 17042, "s": 16884, "text": "The above command will move the file named leekha.txt from Desktop directory to the Documents directory. Both of these directories are in the home directory." }, { "code": null, "e": 17160, "s": 17042, "text": "With the help of following command, we can reboot our Raspberry Pi without disconnecting and reconnecting the power −" }, { "code": null, "e": 17173, "s": 17160, "text": "sudo reboot\n" }, { "code": null, "e": 17251, "s": 17173, "text": "With the help of following command, we can safely turn off our Raspberry Pi −" }, { "code": null, "e": 17262, "s": 17251, "text": "sudo halt\n" }, { "code": null, "e": 17295, "s": 17262, "text": "\n 48 Lectures \n 2 hours \n" }, { "code": null, "e": 17304, "s": 17295, "text": " Comfiny" }, { "code": null, "e": 17337, "s": 17304, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 17354, "s": 17337, "text": " Axel Mammitzsch" }, { "code": null, "e": 17387, "s": 17354, "text": "\n 25 Lectures \n 1 hours \n" }, { "code": null, "e": 17404, "s": 17387, "text": " Axel Mammitzsch" }, { "code": null, "e": 17439, "s": 17404, "text": "\n 96 Lectures \n 9.5 hours \n" }, { "code": null, "e": 17455, "s": 17439, "text": " Edouard Renard" }, { "code": null, "e": 17487, "s": 17455, "text": "\n 10 Lectures \n 34 mins\n" }, { "code": null, "e": 17500, "s": 17487, "text": " Ashraf Said" }, { "code": null, "e": 17532, "s": 17500, "text": "\n 12 Lectures \n 45 mins\n" }, { "code": null, "e": 17545, "s": 17532, "text": " Ashraf Said" }, { "code": null, "e": 17552, "s": 17545, "text": " Print" }, { "code": null, "e": 17563, "s": 17552, "text": " Add Notes" } ]
GraphQL - Validation
While adding or modifying data, it is important to validate the user input. For example, we may need to ensure that the value of a field is always not null. We can use ! (non-nullable) type marker in GraphQL to perform such validation. The syntax for using the ! type marker is as given below − type TypeName { field1:String!, field2:String!, field3:Int! } The above syntax ensures that all the fields are not null. If we want to implement additional rules like checking a string's length or checking if a number is within a given range, we can define custom validators. The custom validation logic will be a part of the resolver function. Let us understand this with the help of an example. Let us create a signup form with basic validation. The form will have email, firstname and password fields. Create a folder named validation-app. Change the directory to validation-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter. Add schema.graphql file in the project folder validation-app and add the following code − type Query { greeting:String } type Mutation { signUp(input:SignUpInput):String } input SignUpInput { email:String!, password:String!, firstName:String! } Note − We can use the input type SignUpInput to reduce the number of parameters in signUp function. So, signUp function takes only one parameter of type SignUpInput. Create a file resolvers.js in the project folder and add the following code − const Query = { greeting:() => "Hello" } const Mutation ={ signUp:(root,args,context,info) => { const {email,firstName,password} = args.input; const emailExpression = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const isValidEmail = emailExpression.test(String(email).toLowerCase()) if(!isValidEmail) throw new Error("email not in proper format") if(firstName.length > 15) throw new Error("firstName should be less than 15 characters") if(password.length < 8 ) throw new Error("password should be minimum 8 characters") return "success"; } } module.exports = {Query,Mutation} The resolver function, signUp accepts parameters email, password and firstName. These will be passed through input variable so that it can be accessed through args.input. Create a server.js file. Refer step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we will use GraphiQL as a client to test the application. Open the browser and enter the URL http://localhost:9000/graphiql. Type the following query in the editor − mutation doSignUp($input:SignUpInput) { signUp(input:$input) } Since input to signup function is a complex type, we need to use query variables in graphiql. For this, we need to first give a name to the query and call it doSignUp, the $input is a query variable. The following query variable must be entered in query variables tab of graphiql − { "input":{ "email": "abc@abc", "firstName": "kannan", "password": "pass@1234" } } The errors array contains the details of validation errors as shown below − { "data": { "signUp": null }, "errors": [ { "message": "email not in proper format", "locations": [ { "line": 2, "column": 4 } ], "path": [ "signUp" ] } ] } We have to enter a proper input for each field as given below − { "input":{ "email": "[email protected]", "firstName": "kannan", "password": "pass@1234" } } The response is as follows − { "data": { "signUp": "success" } } Here, in the below query, we are not assigning any password. { "input":{ "email": "[email protected]", "firstName": "kannan" } } If a required field is not provided, then qraphql server will display the following error − { "errors": [ { "message": "Variable \"$input\" got invalid value {\"email\":\"[email protected]\",\"firstName\":\"kannan\"}; Field value.password of required type String! was not provided.", "locations": [ { "line": 1, "column": 19 } ] } ] } 43 Lectures 3 hours Nilay Mehta 53 Lectures 3 hours Asfend Yar 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2187, "s": 1951, "text": "While adding or modifying data, it is important to validate the user input. For example, we may need to ensure that the value of a field is always not null. We can use ! (non-nullable) type marker in GraphQL to perform such validation." }, { "code": null, "e": 2246, "s": 2187, "text": "The syntax for using the ! type marker is as given below −" }, { "code": null, "e": 2318, "s": 2246, "text": "type TypeName {\n field1:String!,\n field2:String!,\n field3:Int!\n}\n" }, { "code": null, "e": 2377, "s": 2318, "text": "The above syntax ensures that all the fields are not null." }, { "code": null, "e": 2653, "s": 2377, "text": "If we want to implement additional rules like checking a string's length or checking if a number is within a given range, we can define custom validators. The custom validation logic will be a part of the resolver function. Let us understand this with the help of an example." }, { "code": null, "e": 2761, "s": 2653, "text": "Let us create a signup form with basic validation. The form will have email, firstname and password fields." }, { "code": null, "e": 2921, "s": 2761, "text": "Create a folder named validation-app. Change the directory to validation-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter." }, { "code": null, "e": 3011, "s": 2921, "text": "Add schema.graphql file in the project folder validation-app and add the following code −" }, { "code": null, "e": 3183, "s": 3011, "text": "type Query {\n greeting:String\n}\n\ntype Mutation {\n signUp(input:SignUpInput):String\n}\n\ninput SignUpInput {\n email:String!,\n password:String!,\n firstName:String!\n}" }, { "code": null, "e": 3349, "s": 3183, "text": "Note − We can use the input type SignUpInput to reduce the number of parameters in signUp function. So, signUp function takes only one parameter of type SignUpInput." }, { "code": null, "e": 3427, "s": 3349, "text": "Create a file resolvers.js in the project folder and add the following code −" }, { "code": null, "e": 4202, "s": 3427, "text": "const Query = {\n greeting:() => \"Hello\"\n}\n\nconst Mutation ={\n signUp:(root,args,context,info) => {\n\n const {email,firstName,password} = args.input;\n\n const emailExpression = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n \n const isValidEmail = emailExpression.test(String(email).toLowerCase())\n if(!isValidEmail)\n throw new Error(\"email not in proper format\")\n\n if(firstName.length > 15)\n throw new Error(\"firstName should be less than 15 characters\")\n\n if(password.length < 8 )\n throw new Error(\"password should be minimum 8 characters\")\n \n return \"success\";\n }\n}\nmodule.exports = {Query,Mutation}" }, { "code": null, "e": 4373, "s": 4202, "text": "The resolver function, signUp accepts parameters email, password and firstName. These will be passed through input variable so that it can be accessed through args.input." }, { "code": null, "e": 4605, "s": 4373, "text": "Create a server.js file. Refer step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we will use GraphiQL as a client to test the application.\n" }, { "code": null, "e": 4713, "s": 4605, "text": "Open the browser and enter the URL http://localhost:9000/graphiql. Type the following query in the editor −" }, { "code": null, "e": 4779, "s": 4713, "text": "mutation doSignUp($input:SignUpInput) {\n signUp(input:$input)\n}" }, { "code": null, "e": 4979, "s": 4779, "text": "Since input to signup function is a complex type, we need to use query variables in graphiql. For this, we need to first give a name to the query and call it doSignUp, the $input is a query variable." }, { "code": null, "e": 5061, "s": 4979, "text": "The following query variable must be entered in query variables tab of graphiql −" }, { "code": null, "e": 5168, "s": 5061, "text": "{\n \"input\":{\n \"email\": \"abc@abc\",\n \"firstName\": \"kannan\",\n \"password\": \"pass@1234\"\n }\n}" }, { "code": null, "e": 5244, "s": 5168, "text": "The errors array contains the details of validation errors as shown below −" }, { "code": null, "e": 5546, "s": 5244, "text": "{\n \"data\": {\n \"signUp\": null\n },\n \n \"errors\": [\n {\n \"message\": \"email not in proper format\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 4\n }\n ],\n \"path\": [\n \"signUp\"\n ]\n }\n ]\n}" }, { "code": null, "e": 5610, "s": 5546, "text": "We have to enter a proper input for each field as given below −" }, { "code": null, "e": 5721, "s": 5610, "text": "{\n \"input\":{\n \"email\": \"[email protected]\",\n \"firstName\": \"kannan\",\n \"password\": \"pass@1234\"\n }\n}" }, { "code": null, "e": 5750, "s": 5721, "text": "The response is as follows −" }, { "code": null, "e": 5798, "s": 5750, "text": "{\n \"data\": {\n \"signUp\": \"success\"\n }\n}" }, { "code": null, "e": 5859, "s": 5798, "text": "Here, in the below query, we are not assigning any password." }, { "code": null, "e": 5939, "s": 5859, "text": "{\n \"input\":{\n \"email\": \"[email protected]\",\n \"firstName\": \"kannan\"\n }\n}" }, { "code": null, "e": 6031, "s": 5939, "text": "If a required field is not provided, then qraphql server will display the following error −" }, { "code": null, "e": 6367, "s": 6031, "text": "{\n \"errors\": [\n {\n \"message\": \"Variable \\\"$input\\\" got invalid value {\\\"email\\\":\\\"[email protected]\\\",\\\"firstName\\\":\\\"kannan\\\"}; Field value.password of required type String! was not provided.\",\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 19\n }\n ]\n }\n ]\n}" }, { "code": null, "e": 6400, "s": 6367, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 6413, "s": 6400, "text": " Nilay Mehta" }, { "code": null, "e": 6446, "s": 6413, "text": "\n 53 Lectures \n 3 hours \n" }, { "code": null, "e": 6458, "s": 6446, "text": " Asfend Yar" }, { "code": null, "e": 6491, "s": 6458, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6509, "s": 6491, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 6516, "s": 6509, "text": " Print" }, { "code": null, "e": 6527, "s": 6516, "text": " Add Notes" } ]
How to Generate Prediction Intervals with Scikit-Learn and Python | by Will Koehrsen | Towards Data Science
“All models are wrong but some are useful” — George Box. It’s critical to keep this sage advice in mind when we present machine learning predictions. With all machine learning pipelines, there are limitations: features which affect the target that are not in the data (latent variables), or assumptions made by the model which don’t align with reality. These are overlooked when we show a single exact number for a prediction — the house will be $450,300.01 —which gives the impression we are entirely confident our model is a source of truth. A more honest way to show predictions from a model is as a range of estimates: there might be a most likely value, but there is also a wide interval where the real value could be. This isn’t a topic typically addressed in data science courses, but it’s crucial that we show uncertainty in predictions and don’t oversell the capabilities of machine learning. While people crave certainty, I think it’s better to show a wide prediction interval that does contain the true value than an exact estimate which is far from reality. In this article, we’ll walk through one method of producing uncertainty intervals in Scikit-Learn. The full code is available on GitHub with an interactive version of the Jupyter Notebook on nbviewer. We’ll focus primarily on implementation, with a brief section and resources for understanding the theory at the end. Generating prediction intervals is another tool in the data science toolbox, one critical for earning the trust of non-data-scientists. For this walk-through, we’ll use real-world building energy data from a machine learning competition which was hosted on DrivenData. You can get the raw data here, but I’ve provided a cleaned-up version in GitHub which has energy and eight features measured at 15-minute intervals. data.head() The objective is to predict the energy consumption from the features. (This is an actual task we do every day at Cortex Building Intel!). There are undoubtedly hidden features (latent variables) not captured in our data that affect energy consumption, and therefore, we want to show the uncertainty in our estimates by predicting both an upper and lower bound for energy use. # Use plotly + cufflinks for interactive plottingimport cufflinks as cfdata.resample('12 H').mean().iplot() To generate prediction intervals in Scikit-Learn, we’ll use the Gradient Boosting Regressor, working from this example in the docs. The basic idea is straightforward: For the lower prediction, use GradientBoostingRegressor(loss="quantile", alpha=lower_quantile) with lower_quantile representing the lower bound, say 0.1 for the 10th percentileFor the upper prediction, use the GradientBoostingRegressor(loss="quantile", alpha=upper_quantile) with upper_quantile representing the upper bound, say 0.9 for the 90th percentileFor the mid prediction, use GradientBoostingRegressor(loss="quantile", alpha=0.5) which predicts the median, or the default loss="ls" (for least squares) which predicts the mean. The example in the docs uses the latter approach, and so will we. For the lower prediction, use GradientBoostingRegressor(loss="quantile", alpha=lower_quantile) with lower_quantile representing the lower bound, say 0.1 for the 10th percentile For the upper prediction, use the GradientBoostingRegressor(loss="quantile", alpha=upper_quantile) with upper_quantile representing the upper bound, say 0.9 for the 90th percentile For the mid prediction, use GradientBoostingRegressor(loss="quantile", alpha=0.5) which predicts the median, or the default loss="ls" (for least squares) which predicts the mean. The example in the docs uses the latter approach, and so will we. At a high level, the loss is the function optimized by the model. When we change the loss to quantile and choose alpha (the quantile), we’re able to get predictions corresponding to percentiles. If we use lower and upper quantiles, we can produce an estimated range. (We won’t get into the details on the quantile loss right here — see the background on Quantile Loss below.) After splitting the data into train and test sets, we build the model. We actually have to use 3 separate Gradient Boosting Regressors because each model is optimizing a different function and must be trained separately. from sklearn.ensemble import GradientBoostingRegressor# Set lower and upper quantileLOWER_ALPHA = 0.1UPPER_ALPHA = 0.9# Each model has to be separatelower_model = GradientBoostingRegressor(loss="quantile", alpha=LOWER_ALPHA)# The mid model will use the default lossmid_model = GradientBoostingRegressor(loss="ls")upper_model = GradientBoostingRegressor(loss="quantile", alpha=UPPER_ALPHA) Training and predicting uses the familiar Scikit-Learn syntax: # Fit modelslower_model.fit(X_train, y_train)mid_model.fit(X_train, y_train)upper_model.fit(X_train, y_train)# Record actual values on test setpredictions = pd.DataFrame(y_test)# Predictpredictions['lower'] = lower_model.predict(X_test)predictions['mid'] = mid_model.predict(X_test)predictions['upper'] = upper_model.predict(X_test) Just like that, we have prediction intervals! With a little bit of plotly, we can generate a nice interactive plot. As with any machine learning model, we want to quantify the error for our predictions on the test set (where we have the actual answers). Measuring the error of a prediction interval is a little bit trickier than a point prediction. We can calculate the percentage of the time the actual value is within the range, but this can be easily optimized by making the interval very wide. Therefore, we also want a metric that takes into account how far away the predictions are from the actual value, such as absolute error. In the notebook, I’ve provided a function that calculates the absolute error for the lower, mid, and upper predictions and then averages the upper and lower error for an “Interval” absolute error. We can do this for each data point and then plot a boxplot of the errors (the percent in bounds is in the title): Interestingly, for this model, the median absolute error for the lower prediction is actually less than for the mid prediction. This model doesn’t have superb accuracy and could probably benefit from optimization (adjusting model hyperparameters). The actual value is between the lower and upper bounds just over half the time, a metric we could increase by lowering the lower quantile and raising the upper quantile at a loss in precision. There are probably better metrics, but I selected these because they are simple to calculate and easy to interpret. The actual metrics you use should depend on the problem you’re trying to solve and your objectives. Fitting and predicting with 3 separate models is somewhat tedious, so we can write a model that wraps the Gradient Boosting Regressors into a single class. It’s derived from a Scikit-Learn model, so we use the same syntax for training / prediction, except now it’s in one call: # Instantiate the classmodel = GradientBoostingPredictionIntervals( lower_alpha=0.1, upper_alpha=0.9)# Fit and make predictions_ = model.fit(X_train, y_train)predictions = model.predict(X_test, y_test) The model also comes with some plotting utilities: fig = model.plot_intervals(mid=True, start='2017-05-26', stop='2017-06-01')iplot(fig) Please use and adapt the model as you see fit! This is only one method of making uncertainty predictions, but I think it’s useful because it uses the Scikit-Learn syntax (meaning a shallow learning curve) and we can expand on it as needed. In general, this is a good approach to data science problems: start with the simple solution and add complexity only as required! The Gradient Boosting Regressor is an ensemble model, composed of individual decision/regression trees. (For the original explanation of the model, see Friedman’s 1999 paper “Greedy Function Approximation: A Gradient Boosting Machine”.) In contrast to a random forest, which trains trees in parallel, a gradient boosting machine trains trees sequentially, with each tree learning from the mistakes (residuals) of the current ensemble. The contribution of a tree to the model is determined by minimizing the loss function of the model’s predictions and the actual targets in the training set. With the default loss function — least squares — the gradient boosting regressor is predicting the mean. The critical point to understand is that the least squares loss penalizes low and high errors equally: In contrast, the quantile loss penalizes errors based on the quantile and whether the error was positive (actual > predicted) or negative (actual < predicted). This allows the gradient boosting model to optimize not for the mean, but for percentiles. The quantile loss is: Where α is the quantile. Let’s walk through a quick example using an actual value of 10 and our quantiles of 0.1 and 0.9: If α = 0.1 and predicted = 15, then loss = (0.1–1) * (10–15) = 4.5If α = 0.1 and predicted = 5, then loss = 0.1 * (10–5) = 0.5If α = 0.9 and predicted = 15, then loss = (0.9–1) * (10–15) = 0.5If α = 0.9 and predicted = 5, then loss = 0.9 * (10–5) = 4.5 If α = 0.1 and predicted = 15, then loss = (0.1–1) * (10–15) = 4.5 If α = 0.1 and predicted = 5, then loss = 0.1 * (10–5) = 0.5 If α = 0.9 and predicted = 15, then loss = (0.9–1) * (10–15) = 0.5 If α = 0.9 and predicted = 5, then loss = 0.9 * (10–5) = 4.5 For a quantile < 0.5, if the prediction is greater than the actual value (case 1), the loss is greater than for a prediction an equal distance above the actual value. For a quantile > 0.5, if the prediction is less than the actual value (case 4), the loss is greater than for a prediction an equal distance below the actual value. With a quantile == 0.5, then predictions above and below the actual value result in an equal error and the model optimizes for the median. (For the mid model, we can use either loss="quantile", alpha=0.5 for the median, or loss="ls" for the mean). The quantile loss is best illustrated in a graph showing loss versus error: Quantiles < 0.5 drive the predictions below the median and quantiles > 0.5 drive the predictions above the median. This is a great reminder that the loss function of a machine learning method dictates what you are optimizing for! Depending on the output we want, we can optimize for the mean (least squares), median (quantile loss with alpha == 0.5) , or any percentile (quantile loss with alpha == percentile / 100). This is a relatively simple explanation of the quantile loss, but it’s more than enough to get you started generating prediction intervals with the model walkthrough. To go further, check out this article or start on the Wikipedia page and look into the sources. Predicting a single number from a machine learning model gives the illusion we have a high level of confidence in the entire modeling process. However, when we remember that any model is only an approximation, we see the need for expressing uncertainty when making estimates. One way to do this is by generating prediction intervals with the Gradient Boosting Regressor in Scikit-Learn. This is only one way to predict ranges (see confidence intervals from linear regression for example), but it’s relatively simple and can be tuned as needed. In this article, we saw a complete implementation and picked up some of the theory behind the quantile loss function. Solving data science problems is about having many tools in your toolbox to apply as needed. Generating prediction intervals is a helpful technique, and I encourage you to take this walkthrough and apply it to your problems. (The best way to learn any technique is through practice!) We know machine learning can do some pretty incredible things, but it’s not perfect and we shouldn’t portray it as such. To gain the trust of decision-makers, we often need to present not a single number as our estimate, but rather a prediction range indicating the uncertainty inherent in all models. I write about Data Science and occasionally other interesting topics. You can follow me on twitter for useful techniques and tools. If saving the world while helping the bottom line appeals to you, then get in touch with us at Cortex.
[ { "code": null, "e": 715, "s": 171, "text": "“All models are wrong but some are useful” — George Box. It’s critical to keep this sage advice in mind when we present machine learning predictions. With all machine learning pipelines, there are limitations: features which affect the target that are not in the data (latent variables), or assumptions made by the model which don’t align with reality. These are overlooked when we show a single exact number for a prediction — the house will be $450,300.01 —which gives the impression we are entirely confident our model is a source of truth." }, { "code": null, "e": 1241, "s": 715, "text": "A more honest way to show predictions from a model is as a range of estimates: there might be a most likely value, but there is also a wide interval where the real value could be. This isn’t a topic typically addressed in data science courses, but it’s crucial that we show uncertainty in predictions and don’t oversell the capabilities of machine learning. While people crave certainty, I think it’s better to show a wide prediction interval that does contain the true value than an exact estimate which is far from reality." }, { "code": null, "e": 1695, "s": 1241, "text": "In this article, we’ll walk through one method of producing uncertainty intervals in Scikit-Learn. The full code is available on GitHub with an interactive version of the Jupyter Notebook on nbviewer. We’ll focus primarily on implementation, with a brief section and resources for understanding the theory at the end. Generating prediction intervals is another tool in the data science toolbox, one critical for earning the trust of non-data-scientists." }, { "code": null, "e": 1977, "s": 1695, "text": "For this walk-through, we’ll use real-world building energy data from a machine learning competition which was hosted on DrivenData. You can get the raw data here, but I’ve provided a cleaned-up version in GitHub which has energy and eight features measured at 15-minute intervals." }, { "code": null, "e": 1989, "s": 1977, "text": "data.head()" }, { "code": null, "e": 2365, "s": 1989, "text": "The objective is to predict the energy consumption from the features. (This is an actual task we do every day at Cortex Building Intel!). There are undoubtedly hidden features (latent variables) not captured in our data that affect energy consumption, and therefore, we want to show the uncertainty in our estimates by predicting both an upper and lower bound for energy use." }, { "code": null, "e": 2473, "s": 2365, "text": "# Use plotly + cufflinks for interactive plottingimport cufflinks as cfdata.resample('12 H').mean().iplot()" }, { "code": null, "e": 2640, "s": 2473, "text": "To generate prediction intervals in Scikit-Learn, we’ll use the Gradient Boosting Regressor, working from this example in the docs. The basic idea is straightforward:" }, { "code": null, "e": 3241, "s": 2640, "text": "For the lower prediction, use GradientBoostingRegressor(loss=\"quantile\", alpha=lower_quantile) with lower_quantile representing the lower bound, say 0.1 for the 10th percentileFor the upper prediction, use the GradientBoostingRegressor(loss=\"quantile\", alpha=upper_quantile) with upper_quantile representing the upper bound, say 0.9 for the 90th percentileFor the mid prediction, use GradientBoostingRegressor(loss=\"quantile\", alpha=0.5) which predicts the median, or the default loss=\"ls\" (for least squares) which predicts the mean. The example in the docs uses the latter approach, and so will we." }, { "code": null, "e": 3418, "s": 3241, "text": "For the lower prediction, use GradientBoostingRegressor(loss=\"quantile\", alpha=lower_quantile) with lower_quantile representing the lower bound, say 0.1 for the 10th percentile" }, { "code": null, "e": 3599, "s": 3418, "text": "For the upper prediction, use the GradientBoostingRegressor(loss=\"quantile\", alpha=upper_quantile) with upper_quantile representing the upper bound, say 0.9 for the 90th percentile" }, { "code": null, "e": 3844, "s": 3599, "text": "For the mid prediction, use GradientBoostingRegressor(loss=\"quantile\", alpha=0.5) which predicts the median, or the default loss=\"ls\" (for least squares) which predicts the mean. The example in the docs uses the latter approach, and so will we." }, { "code": null, "e": 4220, "s": 3844, "text": "At a high level, the loss is the function optimized by the model. When we change the loss to quantile and choose alpha (the quantile), we’re able to get predictions corresponding to percentiles. If we use lower and upper quantiles, we can produce an estimated range. (We won’t get into the details on the quantile loss right here — see the background on Quantile Loss below.)" }, { "code": null, "e": 4441, "s": 4220, "text": "After splitting the data into train and test sets, we build the model. We actually have to use 3 separate Gradient Boosting Regressors because each model is optimizing a different function and must be trained separately." }, { "code": null, "e": 4927, "s": 4441, "text": "from sklearn.ensemble import GradientBoostingRegressor# Set lower and upper quantileLOWER_ALPHA = 0.1UPPER_ALPHA = 0.9# Each model has to be separatelower_model = GradientBoostingRegressor(loss=\"quantile\", alpha=LOWER_ALPHA)# The mid model will use the default lossmid_model = GradientBoostingRegressor(loss=\"ls\")upper_model = GradientBoostingRegressor(loss=\"quantile\", alpha=UPPER_ALPHA)" }, { "code": null, "e": 4990, "s": 4927, "text": "Training and predicting uses the familiar Scikit-Learn syntax:" }, { "code": null, "e": 5323, "s": 4990, "text": "# Fit modelslower_model.fit(X_train, y_train)mid_model.fit(X_train, y_train)upper_model.fit(X_train, y_train)# Record actual values on test setpredictions = pd.DataFrame(y_test)# Predictpredictions['lower'] = lower_model.predict(X_test)predictions['mid'] = mid_model.predict(X_test)predictions['upper'] = upper_model.predict(X_test)" }, { "code": null, "e": 5369, "s": 5323, "text": "Just like that, we have prediction intervals!" }, { "code": null, "e": 5439, "s": 5369, "text": "With a little bit of plotly, we can generate a nice interactive plot." }, { "code": null, "e": 5958, "s": 5439, "text": "As with any machine learning model, we want to quantify the error for our predictions on the test set (where we have the actual answers). Measuring the error of a prediction interval is a little bit trickier than a point prediction. We can calculate the percentage of the time the actual value is within the range, but this can be easily optimized by making the interval very wide. Therefore, we also want a metric that takes into account how far away the predictions are from the actual value, such as absolute error." }, { "code": null, "e": 6269, "s": 5958, "text": "In the notebook, I’ve provided a function that calculates the absolute error for the lower, mid, and upper predictions and then averages the upper and lower error for an “Interval” absolute error. We can do this for each data point and then plot a boxplot of the errors (the percent in bounds is in the title):" }, { "code": null, "e": 6710, "s": 6269, "text": "Interestingly, for this model, the median absolute error for the lower prediction is actually less than for the mid prediction. This model doesn’t have superb accuracy and could probably benefit from optimization (adjusting model hyperparameters). The actual value is between the lower and upper bounds just over half the time, a metric we could increase by lowering the lower quantile and raising the upper quantile at a loss in precision." }, { "code": null, "e": 6926, "s": 6710, "text": "There are probably better metrics, but I selected these because they are simple to calculate and easy to interpret. The actual metrics you use should depend on the problem you’re trying to solve and your objectives." }, { "code": null, "e": 7204, "s": 6926, "text": "Fitting and predicting with 3 separate models is somewhat tedious, so we can write a model that wraps the Gradient Boosting Regressors into a single class. It’s derived from a Scikit-Learn model, so we use the same syntax for training / prediction, except now it’s in one call:" }, { "code": null, "e": 7409, "s": 7204, "text": "# Instantiate the classmodel = GradientBoostingPredictionIntervals( lower_alpha=0.1, upper_alpha=0.9)# Fit and make predictions_ = model.fit(X_train, y_train)predictions = model.predict(X_test, y_test)" }, { "code": null, "e": 7460, "s": 7409, "text": "The model also comes with some plotting utilities:" }, { "code": null, "e": 7573, "s": 7460, "text": "fig = model.plot_intervals(mid=True, start='2017-05-26', stop='2017-06-01')iplot(fig)" }, { "code": null, "e": 7943, "s": 7573, "text": "Please use and adapt the model as you see fit! This is only one method of making uncertainty predictions, but I think it’s useful because it uses the Scikit-Learn syntax (meaning a shallow learning curve) and we can expand on it as needed. In general, this is a good approach to data science problems: start with the simple solution and add complexity only as required!" }, { "code": null, "e": 8535, "s": 7943, "text": "The Gradient Boosting Regressor is an ensemble model, composed of individual decision/regression trees. (For the original explanation of the model, see Friedman’s 1999 paper “Greedy Function Approximation: A Gradient Boosting Machine”.) In contrast to a random forest, which trains trees in parallel, a gradient boosting machine trains trees sequentially, with each tree learning from the mistakes (residuals) of the current ensemble. The contribution of a tree to the model is determined by minimizing the loss function of the model’s predictions and the actual targets in the training set." }, { "code": null, "e": 8743, "s": 8535, "text": "With the default loss function — least squares — the gradient boosting regressor is predicting the mean. The critical point to understand is that the least squares loss penalizes low and high errors equally:" }, { "code": null, "e": 9016, "s": 8743, "text": "In contrast, the quantile loss penalizes errors based on the quantile and whether the error was positive (actual > predicted) or negative (actual < predicted). This allows the gradient boosting model to optimize not for the mean, but for percentiles. The quantile loss is:" }, { "code": null, "e": 9138, "s": 9016, "text": "Where α is the quantile. Let’s walk through a quick example using an actual value of 10 and our quantiles of 0.1 and 0.9:" }, { "code": null, "e": 9391, "s": 9138, "text": "If α = 0.1 and predicted = 15, then loss = (0.1–1) * (10–15) = 4.5If α = 0.1 and predicted = 5, then loss = 0.1 * (10–5) = 0.5If α = 0.9 and predicted = 15, then loss = (0.9–1) * (10–15) = 0.5If α = 0.9 and predicted = 5, then loss = 0.9 * (10–5) = 4.5" }, { "code": null, "e": 9458, "s": 9391, "text": "If α = 0.1 and predicted = 15, then loss = (0.1–1) * (10–15) = 4.5" }, { "code": null, "e": 9519, "s": 9458, "text": "If α = 0.1 and predicted = 5, then loss = 0.1 * (10–5) = 0.5" }, { "code": null, "e": 9586, "s": 9519, "text": "If α = 0.9 and predicted = 15, then loss = (0.9–1) * (10–15) = 0.5" }, { "code": null, "e": 9647, "s": 9586, "text": "If α = 0.9 and predicted = 5, then loss = 0.9 * (10–5) = 4.5" }, { "code": null, "e": 10117, "s": 9647, "text": "For a quantile < 0.5, if the prediction is greater than the actual value (case 1), the loss is greater than for a prediction an equal distance above the actual value. For a quantile > 0.5, if the prediction is less than the actual value (case 4), the loss is greater than for a prediction an equal distance below the actual value. With a quantile == 0.5, then predictions above and below the actual value result in an equal error and the model optimizes for the median." }, { "code": null, "e": 10226, "s": 10117, "text": "(For the mid model, we can use either loss=\"quantile\", alpha=0.5 for the median, or loss=\"ls\" for the mean)." }, { "code": null, "e": 10302, "s": 10226, "text": "The quantile loss is best illustrated in a graph showing loss versus error:" }, { "code": null, "e": 10532, "s": 10302, "text": "Quantiles < 0.5 drive the predictions below the median and quantiles > 0.5 drive the predictions above the median. This is a great reminder that the loss function of a machine learning method dictates what you are optimizing for!" }, { "code": null, "e": 10983, "s": 10532, "text": "Depending on the output we want, we can optimize for the mean (least squares), median (quantile loss with alpha == 0.5) , or any percentile (quantile loss with alpha == percentile / 100). This is a relatively simple explanation of the quantile loss, but it’s more than enough to get you started generating prediction intervals with the model walkthrough. To go further, check out this article or start on the Wikipedia page and look into the sources." }, { "code": null, "e": 11645, "s": 10983, "text": "Predicting a single number from a machine learning model gives the illusion we have a high level of confidence in the entire modeling process. However, when we remember that any model is only an approximation, we see the need for expressing uncertainty when making estimates. One way to do this is by generating prediction intervals with the Gradient Boosting Regressor in Scikit-Learn. This is only one way to predict ranges (see confidence intervals from linear regression for example), but it’s relatively simple and can be tuned as needed. In this article, we saw a complete implementation and picked up some of the theory behind the quantile loss function." }, { "code": null, "e": 12231, "s": 11645, "text": "Solving data science problems is about having many tools in your toolbox to apply as needed. Generating prediction intervals is a helpful technique, and I encourage you to take this walkthrough and apply it to your problems. (The best way to learn any technique is through practice!) We know machine learning can do some pretty incredible things, but it’s not perfect and we shouldn’t portray it as such. To gain the trust of decision-makers, we often need to present not a single number as our estimate, but rather a prediction range indicating the uncertainty inherent in all models." } ]
Associative Arrays in PHP
Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. Let us see an example− $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array. To implement Associative Arrays in PHP, the code is as follows − Live Demo <?php $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" ); echo "Value 1 = " .reset($arr); ?> This will produce the following output− Value 1 = 150 Let us now see another example − Live Demo <?php $salaries = array("jack" => 2000, "qadir" => 1000); echo "Salary of jack is ". $salaries['jack'] . "\n"; $salaries['jack'] = "high"; $salaries['tom'] = "low"; echo "Salary of jack is ". $salaries['jack'] . "\n"; ?> This will produce the following output− Salary of jack is 2000 Salary of jack is high
[ { "code": null, "e": 1248, "s": 1062, "text": "Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them." }, { "code": null, "e": 1271, "s": 1248, "text": "Let us see an example−" }, { "code": null, "e": 1346, "s": 1271, "text": "$arr = array( \"p\"=>\"150\", \"q\"=>\"100\", \"r\"=>\"120\", \"s\"=>\"110\", \"t\"=>\"115\");" }, { "code": null, "e": 1398, "s": 1346, "text": "Above, we can see key and value pairs in the array." }, { "code": null, "e": 1463, "s": 1398, "text": "To implement Associative Arrays in PHP, the code is as follows −" }, { "code": null, "e": 1474, "s": 1463, "text": " Live Demo" }, { "code": null, "e": 1633, "s": 1474, "text": "<?php\n $arr = array( \"p\"=>\"150\", \"q\"=>\"100\", \"r\"=>\"120\", \"s\"=>\"110\", \"t\"=>\"115\", \"u\"=>\"103\", \"v\"=>\"105\", \"w\"=>\"125\" );\n echo \"Value 1 = \" .reset($arr);\n?>" }, { "code": null, "e": 1673, "s": 1633, "text": "This will produce the following output−" }, { "code": null, "e": 1687, "s": 1673, "text": "Value 1 = 150" }, { "code": null, "e": 1720, "s": 1687, "text": "Let us now see another example −" }, { "code": null, "e": 1731, "s": 1720, "text": " Live Demo" }, { "code": null, "e": 1967, "s": 1731, "text": "<?php\n $salaries = array(\"jack\" => 2000, \"qadir\" => 1000);\n echo \"Salary of jack is \". $salaries['jack'] . \"\\n\";\n $salaries['jack'] = \"high\";\n $salaries['tom'] = \"low\";\n echo \"Salary of jack is \". $salaries['jack'] . \"\\n\";\n?>" }, { "code": null, "e": 2007, "s": 1967, "text": "This will produce the following output−" }, { "code": null, "e": 2053, "s": 2007, "text": "Salary of jack is 2000\nSalary of jack is high" } ]
Denoising techniques in digital image processing using MATLAB - GeeksforGeeks
28 Mar, 2022 Denoising is the process of removing or reducing the noise or artefacts from the image. Denoising makes the image more clear and enables us to see finer details in the image clearly. It does not change the brightness or contrast of the image directly, but due to the removal of artefacts, the final image may look brighter. In this denoising process, we choose a 2-D box and slide it over the image. The intensity of each and every pixel of the original image is recalculated using the box. Box averaging can be defined as the intensity of the corresponding pixel would be replaced with the average of all intensities of its neighbour pixels spanned by the box. This is a point operator. Now, let’s suppose the box size is 5 by 5. It will span over 25 pixels at one time. The intensity value of the central pixel (point operator on central pixel) will be the average of intensities of all the 25 pixels covered by the box of 5 by 5 dimensions. Example: Matlab % MATLAB code for Box averaging% Read the cameraman image.k1=imread("cameraman.jpg"); % create the noise of standard deviation 25n=25*randn(size(k1)); %add the noise to the image=noisy_imagek2=double(k1)+n; %display the noisy image.imtool(k2,[]); %averaging using [5 5] sliding box.k3=uint8(colfilt(k2,[5 5], 'sliding', @mean)); %display the denoised image.imtool(k3,[]); %averaging using [9 9] sliding box.k4=uint8(colfilt(k2, [9 9], 'sliding', @mean)); %display the denoised image.imtool(k4,[]); Output: But there are some disadvantages of this technique: It reduces the noise to a small extent but introduces blurriness in the image. If we increase the box size then smoothness and blurriness in the image increase proportionately. Convolution does a similar work as the box averaging. In the convolution technique, we define the box and initialise it with the values. For denoising purposes, we initialise the box such that it behaves like averaging box. The convolution box is called the kernel. The kernel slides over the image. The value of the central pixel is replaced by the average of all the neighbour pixels spanned by the kernel. kernel working: The values of the kernel and respective pixel got multiplied and all such products got added to give the final result. If our kernel is of size [5 5] then we initialise the kernel with 1/25. When all the pixels got multiplied by 1/25 and added together, the final result is just the average of all those 25 pixels over which the kernel is placed at a certain point in time. The advantage of convolution over box averaging is that sometimes the convolution filter (kernel) is separable and we break the larger kernel into two or more pieces. It reduces the computational operations to perform. Example: Matlab % MATLAB code for denoised imaged using% convolution filter technique% Read the cameraman image.k1=imread("cameraman.jpg"); % create the noise.n=25*randn(size(k1)); % add the noise to the image = noisy_imagek2=double(k1)+n; % create the kernel of size [5 5]h1=ones(5,5)*1/25; % convulse the image with the kernel.k3=uint8(conv2(k2, h1,'same')); % display the denoised image.imtool(k3,[]); % create the kernel of size [9 9]h2=ones(9,9)*1/81; % convulse the image with the kernel.k4=conv2(k2,h2,'same'); % display the denoised image.imtool(k4,[]); Output: A drawback of this technique is: It also introduces the blurriness in the image in addition to reducing the noise. The image gets blurred at the edges due to the wrong averaging result. This kernel or filter has more weightage for the central pixel. While averaging at the edges, more weightage is given to the edged pixel and thus it gives us the pixel value close to the actual one, therefore, reduces the blurriness at the edges. Keep in mind that if we increase the size of the filter, the degree of denoising increases and also the blurriness. But blurriness is significantly less in comparison to other averaging techniques. Example: Matlab % MATLAB code for denoised using% Gaussian Filter:k1=imread("cameraman.jpg"); % create the noise.n=25*randn(size(k1)); % add the noise to the image = noisy_imagek2=double(k1)+n; %create and print the kernel of size [3 3]h1=fspecial('gaussian',3,1);h1 % convulse the image with the kernel.k3=uint8(conv2(k2, h1,'same')); % display the denoised image.imtool(k3,[]); % create and print the kernel of size [20 20]h2=fspecial('gaussian',20,1);h2 % convulse the image with the kernel.k4=uint8(conv2(k2,h2,'same')); % display the denoised image.imtool(k4,[]); Output: This is a very simple and interesting technique of denoising. The requirement for using this technique is that: We should have 2 or more images of the same scene or object. The noise of the image capturing device should be fixed. For example, the camera has a noise of a standard deviation of 20. Collect the multiple images captured by the same device and of the same object. Just take the average of all the images to get the resultant image. The intensity of every pixel will be replaced by the average of the intensities of the corresponding pixel in all those collected images.This technique will reduce the noise and also there would not be any blurriness in the final image. Let say we have n images. Then the noise will be reduced by the degree: The more number images used for averaging the more clear image we’ll get after denoising. Example: Matlab % MATLAB code for denoising by averaging% Read the cameraman image: original image.I=imread("cameraman.jpg"); % Create noise-1 of std=40n1=40*randn(size(I)); % Create first noisy_image by adding the noise to orig image.I1=double(I)+n1; % Create noise-2 of std=40n2=40*randn(size(I)); % Create 2nd noisy_image by adding the noise to orig image.I2=double(I)+n2; % Create noise-3 of std=40n3=40*randn(size(I)); % Create 3rd noisy_image by adding the noise to orig image.I3=double(I)+n3; % Create noise-4 of std=40n4=40*randn(size(I)); % Create 4th noisy_image by adding the noise to orig image.I4=double(I)+n4; % Create noise-5 of std=40n5=40*randn(size(I)); % Create 5th noisy_image by adding the noise to orig image.I5=double(I)+n5; % Now lets see denoising.d1=(I1+I2)/2;d2=(I1+I2+I3)/3;d3=(I1+I2+I3+I4)/4;d4=(I1+I2+I3+I4+I5)/5; %display each denoised image with original noisy image.imtool(I1,[]);imtool(d1,[]);imtool(d2,[]);imtool(d3,[]);imtool(d4,[]); Output: Noisy_image and Denoised-1 Noisy_image and Denoised-2 Noisy_image and Denoised-3 Noisy_image and Denoised-4 The quality increases directly if we take more images for averaging. akshaysingh98088 rkbhola5 Image-Processing MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Trigonometric Functions in MATLAB Boundary Extraction of image using MATLAB What is Upsampling in MATLAB? How to find sum of elements of an array in MATLAB? How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? Text Formatting in MATLAB How to inverse a vector in MATLAB? Turn an Array into a Column Vector in MATLAB Clear variable from Memory in MATLAB How to Permute the Rows and Columns in a Matrix on MATLAB?
[ { "code": null, "e": 24281, "s": 24253, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24605, "s": 24281, "text": "Denoising is the process of removing or reducing the noise or artefacts from the image. Denoising makes the image more clear and enables us to see finer details in the image clearly. It does not change the brightness or contrast of the image directly, but due to the removal of artefacts, the final image may look brighter." }, { "code": null, "e": 24773, "s": 24605, "text": "In this denoising process, we choose a 2-D box and slide it over the image. The intensity of each and every pixel of the original image is recalculated using the box. " }, { "code": null, "e": 24971, "s": 24773, "text": "Box averaging can be defined as the intensity of the corresponding pixel would be replaced with the average of all intensities of its neighbour pixels spanned by the box. This is a point operator. " }, { "code": null, "e": 25228, "s": 24971, "text": "Now, let’s suppose the box size is 5 by 5. It will span over 25 pixels at one time. The intensity value of the central pixel (point operator on central pixel) will be the average of intensities of all the 25 pixels covered by the box of 5 by 5 dimensions. " }, { "code": null, "e": 25237, "s": 25228, "text": "Example:" }, { "code": null, "e": 25244, "s": 25237, "text": "Matlab" }, { "code": "% MATLAB code for Box averaging% Read the cameraman image.k1=imread(\"cameraman.jpg\"); % create the noise of standard deviation 25n=25*randn(size(k1)); %add the noise to the image=noisy_imagek2=double(k1)+n; %display the noisy image.imtool(k2,[]); %averaging using [5 5] sliding box.k3=uint8(colfilt(k2,[5 5], 'sliding', @mean)); %display the denoised image.imtool(k3,[]); %averaging using [9 9] sliding box.k4=uint8(colfilt(k2, [9 9], 'sliding', @mean)); %display the denoised image.imtool(k4,[]);", "e": 25742, "s": 25244, "text": null }, { "code": null, "e": 25750, "s": 25742, "text": "Output:" }, { "code": null, "e": 25802, "s": 25750, "text": "But there are some disadvantages of this technique:" }, { "code": null, "e": 25881, "s": 25802, "text": "It reduces the noise to a small extent but introduces blurriness in the image." }, { "code": null, "e": 25979, "s": 25881, "text": "If we increase the box size then smoothness and blurriness in the image increase proportionately." }, { "code": null, "e": 26389, "s": 25979, "text": "Convolution does a similar work as the box averaging. In the convolution technique, we define the box and initialise it with the values. For denoising purposes, we initialise the box such that it behaves like averaging box. The convolution box is called the kernel. The kernel slides over the image. The value of the central pixel is replaced by the average of all the neighbour pixels spanned by the kernel. " }, { "code": null, "e": 26779, "s": 26389, "text": "kernel working: The values of the kernel and respective pixel got multiplied and all such products got added to give the final result. If our kernel is of size [5 5] then we initialise the kernel with 1/25. When all the pixels got multiplied by 1/25 and added together, the final result is just the average of all those 25 pixels over which the kernel is placed at a certain point in time." }, { "code": null, "e": 26999, "s": 26779, "text": "The advantage of convolution over box averaging is that sometimes the convolution filter (kernel) is separable and we break the larger kernel into two or more pieces. It reduces the computational operations to perform. " }, { "code": null, "e": 27008, "s": 26999, "text": "Example:" }, { "code": null, "e": 27015, "s": 27008, "text": "Matlab" }, { "code": "% MATLAB code for denoised imaged using% convolution filter technique% Read the cameraman image.k1=imread(\"cameraman.jpg\"); % create the noise.n=25*randn(size(k1)); % add the noise to the image = noisy_imagek2=double(k1)+n; % create the kernel of size [5 5]h1=ones(5,5)*1/25; % convulse the image with the kernel.k3=uint8(conv2(k2, h1,'same')); % display the denoised image.imtool(k3,[]); % create the kernel of size [9 9]h2=ones(9,9)*1/81; % convulse the image with the kernel.k4=conv2(k2,h2,'same'); % display the denoised image.imtool(k4,[]);", "e": 27561, "s": 27015, "text": null }, { "code": null, "e": 27569, "s": 27561, "text": "Output:" }, { "code": null, "e": 27602, "s": 27569, "text": "A drawback of this technique is:" }, { "code": null, "e": 27684, "s": 27602, "text": "It also introduces the blurriness in the image in addition to reducing the noise." }, { "code": null, "e": 27755, "s": 27684, "text": "The image gets blurred at the edges due to the wrong averaging result." }, { "code": null, "e": 28003, "s": 27755, "text": "This kernel or filter has more weightage for the central pixel. While averaging at the edges, more weightage is given to the edged pixel and thus it gives us the pixel value close to the actual one, therefore, reduces the blurriness at the edges. " }, { "code": null, "e": 28201, "s": 28003, "text": "Keep in mind that if we increase the size of the filter, the degree of denoising increases and also the blurriness. But blurriness is significantly less in comparison to other averaging techniques." }, { "code": null, "e": 28210, "s": 28201, "text": "Example:" }, { "code": null, "e": 28217, "s": 28210, "text": "Matlab" }, { "code": "% MATLAB code for denoised using% Gaussian Filter:k1=imread(\"cameraman.jpg\"); % create the noise.n=25*randn(size(k1)); % add the noise to the image = noisy_imagek2=double(k1)+n; %create and print the kernel of size [3 3]h1=fspecial('gaussian',3,1);h1 % convulse the image with the kernel.k3=uint8(conv2(k2, h1,'same')); % display the denoised image.imtool(k3,[]); % create and print the kernel of size [20 20]h2=fspecial('gaussian',20,1);h2 % convulse the image with the kernel.k4=uint8(conv2(k2,h2,'same')); % display the denoised image.imtool(k4,[]);", "e": 28770, "s": 28217, "text": null }, { "code": null, "e": 28778, "s": 28770, "text": "Output:" }, { "code": null, "e": 28890, "s": 28778, "text": "This is a very simple and interesting technique of denoising. The requirement for using this technique is that:" }, { "code": null, "e": 28951, "s": 28890, "text": "We should have 2 or more images of the same scene or object." }, { "code": null, "e": 29075, "s": 28951, "text": "The noise of the image capturing device should be fixed. For example, the camera has a noise of a standard deviation of 20." }, { "code": null, "e": 29461, "s": 29075, "text": "Collect the multiple images captured by the same device and of the same object. Just take the average of all the images to get the resultant image. The intensity of every pixel will be replaced by the average of the intensities of the corresponding pixel in all those collected images.This technique will reduce the noise and also there would not be any blurriness in the final image. " }, { "code": null, "e": 29534, "s": 29461, "text": "Let say we have n images. Then the noise will be reduced by the degree: " }, { "code": null, "e": 29624, "s": 29534, "text": "The more number images used for averaging the more clear image we’ll get after denoising." }, { "code": null, "e": 29633, "s": 29624, "text": "Example:" }, { "code": null, "e": 29640, "s": 29633, "text": "Matlab" }, { "code": "% MATLAB code for denoising by averaging% Read the cameraman image: original image.I=imread(\"cameraman.jpg\"); % Create noise-1 of std=40n1=40*randn(size(I)); % Create first noisy_image by adding the noise to orig image.I1=double(I)+n1; % Create noise-2 of std=40n2=40*randn(size(I)); % Create 2nd noisy_image by adding the noise to orig image.I2=double(I)+n2; % Create noise-3 of std=40n3=40*randn(size(I)); % Create 3rd noisy_image by adding the noise to orig image.I3=double(I)+n3; % Create noise-4 of std=40n4=40*randn(size(I)); % Create 4th noisy_image by adding the noise to orig image.I4=double(I)+n4; % Create noise-5 of std=40n5=40*randn(size(I)); % Create 5th noisy_image by adding the noise to orig image.I5=double(I)+n5; % Now lets see denoising.d1=(I1+I2)/2;d2=(I1+I2+I3)/3;d3=(I1+I2+I3+I4)/4;d4=(I1+I2+I3+I4+I5)/5; %display each denoised image with original noisy image.imtool(I1,[]);imtool(d1,[]);imtool(d2,[]);imtool(d3,[]);imtool(d4,[]);", "e": 30594, "s": 29640, "text": null }, { "code": null, "e": 30603, "s": 30594, "text": "Output: " }, { "code": null, "e": 30630, "s": 30603, "text": "Noisy_image and Denoised-1" }, { "code": null, "e": 30657, "s": 30630, "text": "Noisy_image and Denoised-2" }, { "code": null, "e": 30684, "s": 30657, "text": "Noisy_image and Denoised-3" }, { "code": null, "e": 30711, "s": 30684, "text": "Noisy_image and Denoised-4" }, { "code": null, "e": 30780, "s": 30711, "text": "The quality increases directly if we take more images for averaging." }, { "code": null, "e": 30799, "s": 30782, "text": "akshaysingh98088" }, { "code": null, "e": 30808, "s": 30799, "text": "rkbhola5" }, { "code": null, "e": 30825, "s": 30808, "text": "Image-Processing" }, { "code": null, "e": 30849, "s": 30825, "text": "MATLAB image-processing" }, { "code": null, "e": 30856, "s": 30849, "text": "MATLAB" }, { "code": null, "e": 30954, "s": 30856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30963, "s": 30954, "text": "Comments" }, { "code": null, "e": 30976, "s": 30963, "text": "Old Comments" }, { "code": null, "e": 31010, "s": 30976, "text": "Trigonometric Functions in MATLAB" }, { "code": null, "e": 31052, "s": 31010, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 31082, "s": 31052, "text": "What is Upsampling in MATLAB?" }, { "code": null, "e": 31133, "s": 31082, "text": "How to find sum of elements of an array in MATLAB?" }, { "code": null, "e": 31212, "s": 31133, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" }, { "code": null, "e": 31238, "s": 31212, "text": "Text Formatting in MATLAB" }, { "code": null, "e": 31273, "s": 31238, "text": "How to inverse a vector in MATLAB?" }, { "code": null, "e": 31318, "s": 31273, "text": "Turn an Array into a Column Vector in MATLAB" }, { "code": null, "e": 31355, "s": 31318, "text": "Clear variable from Memory in MATLAB" } ]
Search Data in Django From Firebase - GeeksforGeeks
08 Oct, 2021 Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data. Here, We are going to learn How we can search for data in Firebase. To do so follow the below steps: Step 1: If you are new to firebase then please refer to this. Step 2: Go to urls.py file and create a path to move to the webpage to search for data. Python from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ #when we are moving to search then move to this url path('search/', views.search), #showing search detail on this url path('searchusers/', views.searchusers),] Step 3 : Then move to views.py file and write the following function to render to html page. Python from django.shortcuts import renderfrom django.views.decorators.http import require_http_methodsfrom django.views.decorators.csrf import csrf_exemptfrom django.contrib.auth.decorators import login_requiredimport pyrebase config={ "databaseURL": "*********************", "projectId": "*******************", }firebase=pyrebase.initialize_app(config)authe = firebase.auth()database=firebase.database() # move to this search.html page to search for contentdef search(request): return render(request, "search.html") # after typing what to search this function will be calleddef searchusers(request): value = request.POST.get('search') # if no value is given then render to search.h6tml if value =="": return render(request, "search.html") title = request.POST['category'] if title =="": return render(request, "search.html") if value is None or title is None: print(value ,"Value",title) return render(request, "search.html") else: if title == "Users": data = database.child('users').shallow().get().val() uidlist = [] requid = 'null' # append all the id in uidlist for i in data: uidlist.append(i) # if we have find all the uid then # we will look for the one we need for i in uidlist: val = database.child('users').child(i).child('name').get().val() val=val.lower() value=value.lower() print(val,value) # if uid we want is value then # we will store that in requid if (val == value): requid = i if requid=='null': return render(request, "search.html") print(requid) # then we will retrieve all the data related to that uid name = database.child('users').child(requid).child('name').get().val() course = database.child('users').child(requid).child('course').get().val() branch = database.child('users').child(requid).child('branch').get().val() img = database.child('users').child(requid).child('imgUrl').get().val() Name = [] Name.append(name) Course = [] Course.append(course) Branch = [] Branch.append(branch) Image = [] Image.append(img) comb_lis = zip(Name, Course, Branch, Image) # send all data in zip form to searchusers.html return render(request, "SearchUsers.html", {"comb_lis": comb_lis}) Step 4: Then we will move to search.html page and write the following code to search for data in firebase. Comments are written inside to understand it better. HTML {% load static %}<html lang="en"> <head> <title>Search Page</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <link rel='stylesheet' href="{% static '/css/Search.css' %}"> <link rel="stylesheet" type="text/css" href="{%static '/css/footer.css' %}"> </head> <body> <div class="container"> <div class="inner"> <form method="post" action="/searchusers/"> {% csrf_token %} <!--Type the name you want to search and click on submit--> <input type="text" placeholder="Enter Title..." aria-label="Search.." name="search" id="search"> <select name="category" id="category" name=""> <option value="">Select Category</option> <!--select type to user--> <option value="Users">Users</option> </select> <input type="submit" value="Find"> </form> </div> </div> </body></html> Step 5: Then we will move to the searchusers.html page and it will show the retrieved data on the Webpage as shown in the output. HTML {% load static %}<html lang="en"> <head> <title>User's List</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <link rel='stylesheet' href="{% static '/css/Search.css' %}"> </head> <body> <div class="tm-container"> <div class="tm-main-content"> <section class="tm-section tm-section-small text-center"> <!--Showing all the details we retrieved Here--> {% for name,course,branch,image in comb_lis %} <h1>Here are the results:</h1> <div class="image"> <img src="{{image}}" alt="Profile"> <h3 class="tm-section-header3">Name: {{name}}</h3> <h3 class="tm-section-header2">Course: {{ course }}, {{ branch }} </h3> </div> {% endfor %} </section> </div> <br> </div> </body></html> Output: ruhelaa48 gabaa406 Django-models Firebase Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24247, "s": 23901, "text": "Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data." }, { "code": null, "e": 24348, "s": 24247, "text": "Here, We are going to learn How we can search for data in Firebase. To do so follow the below steps:" }, { "code": null, "e": 24410, "s": 24348, "text": "Step 1: If you are new to firebase then please refer to this." }, { "code": null, "e": 24498, "s": 24410, "text": "Step 2: Go to urls.py file and create a path to move to the webpage to search for data." }, { "code": null, "e": 24505, "s": 24498, "text": "Python" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ #when we are moving to search then move to this url path('search/', views.search), #showing search detail on this url path('searchusers/', views.searchusers),]", "e": 24779, "s": 24505, "text": null }, { "code": null, "e": 24873, "s": 24779, "text": "Step 3 : Then move to views.py file and write the following function to render to html page. " }, { "code": null, "e": 24880, "s": 24873, "text": "Python" }, { "code": "from django.shortcuts import renderfrom django.views.decorators.http import require_http_methodsfrom django.views.decorators.csrf import csrf_exemptfrom django.contrib.auth.decorators import login_requiredimport pyrebase config={ \"databaseURL\": \"*********************\", \"projectId\": \"*******************\", }firebase=pyrebase.initialize_app(config)authe = firebase.auth()database=firebase.database() # move to this search.html page to search for contentdef search(request): return render(request, \"search.html\") # after typing what to search this function will be calleddef searchusers(request): value = request.POST.get('search') # if no value is given then render to search.h6tml if value ==\"\": return render(request, \"search.html\") title = request.POST['category'] if title ==\"\": return render(request, \"search.html\") if value is None or title is None: print(value ,\"Value\",title) return render(request, \"search.html\") else: if title == \"Users\": data = database.child('users').shallow().get().val() uidlist = [] requid = 'null' # append all the id in uidlist for i in data: uidlist.append(i) # if we have find all the uid then # we will look for the one we need for i in uidlist: val = database.child('users').child(i).child('name').get().val() val=val.lower() value=value.lower() print(val,value) # if uid we want is value then # we will store that in requid if (val == value): requid = i if requid=='null': return render(request, \"search.html\") print(requid) # then we will retrieve all the data related to that uid name = database.child('users').child(requid).child('name').get().val() course = database.child('users').child(requid).child('course').get().val() branch = database.child('users').child(requid).child('branch').get().val() img = database.child('users').child(requid).child('imgUrl').get().val() Name = [] Name.append(name) Course = [] Course.append(course) Branch = [] Branch.append(branch) Image = [] Image.append(img) comb_lis = zip(Name, Course, Branch, Image) # send all data in zip form to searchusers.html return render(request, \"SearchUsers.html\", {\"comb_lis\": comb_lis})", "e": 27571, "s": 24880, "text": null }, { "code": null, "e": 27734, "s": 27571, "text": " Step 4: Then we will move to search.html page and write the following code to search for data in firebase. Comments are written inside to understand it better. " }, { "code": null, "e": 27739, "s": 27734, "text": "HTML" }, { "code": "{% load static %}<html lang=\"en\"> <head> <title>Search Page</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"></script> <link rel='stylesheet' href=\"{% static '/css/Search.css' %}\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"{%static '/css/footer.css' %}\"> </head> <body> <div class=\"container\"> <div class=\"inner\"> <form method=\"post\" action=\"/searchusers/\"> {% csrf_token %} <!--Type the name you want to search and click on submit--> <input type=\"text\" placeholder=\"Enter Title...\" aria-label=\"Search..\" name=\"search\" id=\"search\"> <select name=\"category\" id=\"category\" name=\"\"> <option value=\"\">Select Category</option> <!--select type to user--> <option value=\"Users\">Users</option> </select> <input type=\"submit\" value=\"Find\"> </form> </div> </div> </body></html>", "e": 29157, "s": 27739, "text": null }, { "code": null, "e": 29290, "s": 29157, "text": " Step 5: Then we will move to the searchusers.html page and it will show the retrieved data on the Webpage as shown in the output. " }, { "code": null, "e": 29295, "s": 29290, "text": "HTML" }, { "code": "{% load static %}<html lang=\"en\"> <head> <title>User's List</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"></script> <link rel='stylesheet' href=\"{% static '/css/Search.css' %}\"> </head> <body> <div class=\"tm-container\"> <div class=\"tm-main-content\"> <section class=\"tm-section tm-section-small text-center\"> <!--Showing all the details we retrieved Here--> {% for name,course,branch,image in comb_lis %} <h1>Here are the results:</h1> <div class=\"image\"> <img src=\"{{image}}\" alt=\"Profile\"> <h3 class=\"tm-section-header3\">Name: {{name}}</h3> <h3 class=\"tm-section-header2\">Course: {{ course }}, {{ branch }} </h3> </div> {% endfor %} </section> </div> <br> </div> </body></html>", "e": 30613, "s": 29295, "text": null }, { "code": null, "e": 30622, "s": 30613, "text": "Output: " }, { "code": null, "e": 30634, "s": 30624, "text": "ruhelaa48" }, { "code": null, "e": 30643, "s": 30634, "text": "gabaa406" }, { "code": null, "e": 30657, "s": 30643, "text": "Django-models" }, { "code": null, "e": 30666, "s": 30657, "text": "Firebase" }, { "code": null, "e": 30680, "s": 30666, "text": "Python Django" }, { "code": null, "e": 30687, "s": 30680, "text": "Python" }, { "code": null, "e": 30785, "s": 30687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30794, "s": 30785, "text": "Comments" }, { "code": null, "e": 30807, "s": 30794, "text": "Old Comments" }, { "code": null, "e": 30843, "s": 30807, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 30866, "s": 30843, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 30905, "s": 30866, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 30938, "s": 30905, "text": "Python | Convert set into a list" }, { "code": null, "e": 30987, "s": 30938, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 31028, "s": 30987, "text": "Python - Call function from another file" }, { "code": null, "e": 31044, "s": 31028, "text": "loops in python" }, { "code": null, "e": 31095, "s": 31044, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 31127, "s": 31095, "text": "Python Dictionary keys() method" } ]
How to sum values of Pandas dataframe by rows? - GeeksforGeeks
26 Mar, 2021 While working on the python pandas module there may be a need, to sum up, the rows of a Dataframe. Below are the examples of summing the rows of a Dataframe. A Dataframe is a 2-dimensional data structure in form of a table with rows and columns. It can be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, an Excel file, or from a python list or dictionary as well. Pandas dataframe.sum() function returns the sum of the values for the requested axis. Syntax: DataFrame.sum(axis) Parameters: axis : {index (0), columns (1)} Sum of each row: df.sum(axis=1) Example 1: Summing all the rows of a Dataframe using the sum function and setting the axis value to 1 for summing up the row values and displaying the result as output. Python3 # importing pandas module as pdimport pandas as pd # creating a dataframe using dictionarydf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96]}) # sum() method sums up the rows and columns of a dataframe# axis = 1 sums up the rowsdf = df.sum(axis = 1)print(df) Output : Sum of all the rows by index Example 2: Summing all the rows or some rows of the Dataframe as per requirement using loc function and the sum function and setting the axis to 1 for summing up rows. It sums up only the rows specified and puts NaN values in the remaining places. Python3 # importing pandas as pdimport pandas as pd # creating the dataframe using pandas DataFramedf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96], 'Z':['a', 'b', 'c', 'd', 'e']}) # df['column_name'] = df.loc[start_row_index:end_row_index,# ['column1','column2']].sum(axis = 1)# summing columns X and Y for row from 1 - 3df['Sum_of_row'] = df.loc[1 : 3,['X' , 'Y']].sum(axis = 1)print(df) Output : Summing all rows from row 1 to 3 Example 3 : Summing the rows using the eval function to evaluate the sum of the rows with the specified expression as a parameter. Python3 # importing pandas as pdimport pandas as pd # creating the dataframe using pandas DataFramedf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96], 'Z':['a', 'b', 'c', 'd', 'e']}) # eval('expression') calculates the sum of the specified columns of that rowdf = df.eval('Sum = X + Y')print(df) Output : Sum of rows using the eval function Example 4 : Summing the rows using the eval function to evaluate the sum of the rows with specified rows using loc with the expression to calculate the sum as a parameter to eval function. It only returns the rows which are being specified in the loc and chops off the remaining. Python3 # importing pandas as pdimport pandas as pd # creating the dataframe using pandas DataFramedf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96], 'Z':['a', 'b', 'c', 'd', 'e']}) # eval('expression') calculates the sum# of the specified columns of that row# using loc for specified rowsdf = df.loc[2:4].eval('Sum = X + Y')display(df) Output : Summing specified rows only using eval Picked 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. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe sum() function in Python
[ { "code": null, "e": 24866, "s": 24838, "text": "\n26 Mar, 2021" }, { "code": null, "e": 25276, "s": 24866, "text": "While working on the python pandas module there may be a need, to sum up, the rows of a Dataframe. Below are the examples of summing the rows of a Dataframe. A Dataframe is a 2-dimensional data structure in form of a table with rows and columns. It can be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, an Excel file, or from a python list or dictionary as well." }, { "code": null, "e": 25362, "s": 25276, "text": "Pandas dataframe.sum() function returns the sum of the values for the requested axis." }, { "code": null, "e": 25390, "s": 25362, "text": "Syntax: DataFrame.sum(axis)" }, { "code": null, "e": 25402, "s": 25390, "text": "Parameters:" }, { "code": null, "e": 25434, "s": 25402, "text": "axis : {index (0), columns (1)}" }, { "code": null, "e": 25451, "s": 25434, "text": "Sum of each row:" }, { "code": null, "e": 25466, "s": 25451, "text": "df.sum(axis=1)" }, { "code": null, "e": 25477, "s": 25466, "text": "Example 1:" }, { "code": null, "e": 25635, "s": 25477, "text": "Summing all the rows of a Dataframe using the sum function and setting the axis value to 1 for summing up the row values and displaying the result as output." }, { "code": null, "e": 25643, "s": 25635, "text": "Python3" }, { "code": "# importing pandas module as pdimport pandas as pd # creating a dataframe using dictionarydf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96]}) # sum() method sums up the rows and columns of a dataframe# axis = 1 sums up the rowsdf = df.sum(axis = 1)print(df)", "e": 25936, "s": 25643, "text": null }, { "code": null, "e": 25946, "s": 25936, "text": "Output : " }, { "code": null, "e": 25975, "s": 25946, "text": "Sum of all the rows by index" }, { "code": null, "e": 25986, "s": 25975, "text": "Example 2:" }, { "code": null, "e": 26223, "s": 25986, "text": "Summing all the rows or some rows of the Dataframe as per requirement using loc function and the sum function and setting the axis to 1 for summing up rows. It sums up only the rows specified and puts NaN values in the remaining places." }, { "code": null, "e": 26231, "s": 26223, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # creating the dataframe using pandas DataFramedf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96], 'Z':['a', 'b', 'c', 'd', 'e']}) # df['column_name'] = df.loc[start_row_index:end_row_index,# ['column1','column2']].sum(axis = 1)# summing columns X and Y for row from 1 - 3df['Sum_of_row'] = df.loc[1 : 3,['X' , 'Y']].sum(axis = 1)print(df)", "e": 26667, "s": 26231, "text": null }, { "code": null, "e": 26676, "s": 26667, "text": "Output :" }, { "code": null, "e": 26709, "s": 26676, "text": "Summing all rows from row 1 to 3" }, { "code": null, "e": 26721, "s": 26709, "text": "Example 3 :" }, { "code": null, "e": 26840, "s": 26721, "text": "Summing the rows using the eval function to evaluate the sum of the rows with the specified expression as a parameter." }, { "code": null, "e": 26848, "s": 26840, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # creating the dataframe using pandas DataFramedf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96], 'Z':['a', 'b', 'c', 'd', 'e']}) # eval('expression') calculates the sum of the specified columns of that rowdf = df.eval('Sum = X + Y')print(df)", "e": 27188, "s": 26848, "text": null }, { "code": null, "e": 27198, "s": 27188, "text": "Output : " }, { "code": null, "e": 27234, "s": 27198, "text": "Sum of rows using the eval function" }, { "code": null, "e": 27246, "s": 27234, "text": "Example 4 :" }, { "code": null, "e": 27514, "s": 27246, "text": "Summing the rows using the eval function to evaluate the sum of the rows with specified rows using loc with the expression to calculate the sum as a parameter to eval function. It only returns the rows which are being specified in the loc and chops off the remaining." }, { "code": null, "e": 27522, "s": 27514, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # creating the dataframe using pandas DataFramedf = pd.DataFrame({'X':[1, 2, 3, 4, 5], 'Y':[54, 12, 57, 48, 96], 'Z':['a', 'b', 'c', 'd', 'e']}) # eval('expression') calculates the sum# of the specified columns of that row# using loc for specified rowsdf = df.loc[2:4].eval('Sum = X + Y')display(df)", "e": 27904, "s": 27522, "text": null }, { "code": null, "e": 27914, "s": 27904, "text": "Output : " }, { "code": null, "e": 27953, "s": 27914, "text": "Summing specified rows only using eval" }, { "code": null, "e": 27960, "s": 27953, "text": "Picked" }, { "code": null, "e": 27984, "s": 27960, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28007, "s": 27984, "text": "Python Pandas-exercise" }, { "code": null, "e": 28021, "s": 28007, "text": "Python-pandas" }, { "code": null, "e": 28028, "s": 28021, "text": "Python" }, { "code": null, "e": 28126, "s": 28028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28144, "s": 28126, "text": "Python Dictionary" }, { "code": null, "e": 28166, "s": 28144, "text": "Enumerate() in Python" }, { "code": null, "e": 28198, "s": 28166, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28240, "s": 28198, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28277, "s": 28240, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28321, "s": 28277, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28350, "s": 28321, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28392, "s": 28350, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28448, "s": 28392, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to insert Slide From Bottom animation in RecyclerView in Android - GeeksforGeeks
08 Jul, 2020 In this article, the animation that makes the items slide from the bottom is added in the recycler view. Here we don`t use any other library to add the animation. Adding animations make the application attractive and give a better user experience. Approach:Step 1: Create “anim” resource directory. Right-click on res folder and follow path res -> new -> Android Resource Directory From the Resource type, choose “anim” and don’t change Directory name then press ok.Step 2: Create an Animation file.Right-click on “anim” directory and create a new Animation Resource File. anim -> new -> Animation Resource File -> create “slide_from_bottom” xml file. Add the below code in slide_from_bottom.xml file. Here the animation is defined. XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:duration="600"><translate android:fromYDelta="50%p" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:toYDelta="0"/><alpha android:fromAlpha="0" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:toAlpha="1"/></set> Step 3: Create one more animation file to hold “slide_from_bottom.xml” anim -> new -> Animation Resource File -> create “layout_animation_slide_from_bottom” xml file Add the below code in the XML file that is just created. Here, animation slide_from_buttom is added that is defined in the previous step. XML <?xml version="1.0" encoding="utf-8"?><layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android" android:animation="@anim/slide_from_bottom" android:animationOrder="normal" android:delay="15%"></layoutAnimation> Step 4:(Final) Call that animation in Your RecyclerView. In the tag layoutAnimation, add layout_animation_slide_from_bottom.xml. Now while displaying the list items in recycler view, the items will add with the animation that is carried by the layout_animation_slide_from_bottom.xml and defined in slide_from_bottom.xml. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#6F6A6A" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:layoutAnimation="@anim/layout_animation_slide_from_bottom" android:orientation="vertical" android:id="@+id/recyclerView" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: android How To Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Align Text in HTML? How to Install FFmpeg on Windows? How to Install Jupyter Notebook on MacOS? How to Install Python Pandas on MacOS? How to Override compareTo Method in Java? Arrays in Java Split() String method in Java with examples For-each loop in Java Initialize an ArrayList in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 25169, "s": 25141, "text": "\n08 Jul, 2020" }, { "code": null, "e": 25417, "s": 25169, "text": "In this article, the animation that makes the items slide from the bottom is added in the recycler view. Here we don`t use any other library to add the animation. Adding animations make the application attractive and give a better user experience." }, { "code": null, "e": 25513, "s": 25417, "text": "Approach:Step 1: Create “anim” resource directory. Right-click on res folder and follow path " }, { "code": null, "e": 25554, "s": 25513, "text": "res -> new -> Android Resource Directory" }, { "code": null, "e": 25748, "s": 25554, "text": " From the Resource type, choose “anim” and don’t change Directory name then press ok.Step 2: Create an Animation file.Right-click on “anim” directory and create a new Animation Resource File. " }, { "code": null, "e": 25827, "s": 25748, "text": "anim -> new -> Animation Resource File -> create “slide_from_bottom” xml file." }, { "code": null, "e": 25909, "s": 25827, "text": "Add the below code in slide_from_bottom.xml file. Here the animation is defined. " }, { "code": null, "e": 25913, "s": 25909, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:duration=\"600\"><translate android:fromYDelta=\"50%p\" android:interpolator=\"@android:anim/accelerate_decelerate_interpolator\" android:toYDelta=\"0\"/><alpha android:fromAlpha=\"0\" android:interpolator=\"@android:anim/accelerate_decelerate_interpolator\" android:toAlpha=\"1\"/></set>", "e": 26319, "s": 25913, "text": null }, { "code": null, "e": 26391, "s": 26319, "text": "Step 3: Create one more animation file to hold “slide_from_bottom.xml” " }, { "code": null, "e": 26486, "s": 26391, "text": "anim -> new -> Animation Resource File -> create “layout_animation_slide_from_bottom” xml file" }, { "code": null, "e": 26626, "s": 26486, "text": " Add the below code in the XML file that is just created. Here, animation slide_from_buttom is added that is defined in the previous step." }, { "code": null, "e": 26630, "s": 26626, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layoutAnimation xmlns:android=\"http://schemas.android.com/apk/res/android\" android:animation=\"@anim/slide_from_bottom\" android:animationOrder=\"normal\" android:delay=\"15%\"></layoutAnimation>", "e": 26863, "s": 26630, "text": null }, { "code": null, "e": 27184, "s": 26863, "text": "Step 4:(Final) Call that animation in Your RecyclerView. In the tag layoutAnimation, add layout_animation_slide_from_bottom.xml. Now while displaying the list items in recycler view, the items will add with the animation that is carried by the layout_animation_slide_from_bottom.xml and defined in slide_from_bottom.xml." }, { "code": null, "e": 27188, "s": 27184, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#6F6A6A\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layoutAnimation=\"@anim/layout_animation_slide_from_bottom\" android:orientation=\"vertical\" android:id=\"@+id/recyclerView\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 27939, "s": 27188, "text": null }, { "code": null, "e": 27947, "s": 27939, "text": "Output:" }, { "code": null, "e": 27955, "s": 27947, "text": "android" }, { "code": null, "e": 27962, "s": 27955, "text": "How To" }, { "code": null, "e": 27967, "s": 27962, "text": "Java" }, { "code": null, "e": 27972, "s": 27967, "text": "Java" }, { "code": null, "e": 28070, "s": 27972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28079, "s": 28070, "text": "Comments" }, { "code": null, "e": 28092, "s": 28079, "text": "Old Comments" }, { "code": null, "e": 28119, "s": 28092, "text": "How to Align Text in HTML?" }, { "code": null, "e": 28153, "s": 28119, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28195, "s": 28153, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 28234, "s": 28195, "text": "How to Install Python Pandas on MacOS?" }, { "code": null, "e": 28276, "s": 28234, "text": "How to Override compareTo Method in Java?" }, { "code": null, "e": 28291, "s": 28276, "text": "Arrays in Java" }, { "code": null, "e": 28335, "s": 28291, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28357, "s": 28335, "text": "For-each loop in Java" }, { "code": null, "e": 28389, "s": 28357, "text": "Initialize an ArrayList in Java" } ]
Database Management Systems | Set 8 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE 2005 CS exam. 1) Which one of the following statements about normal forms is FALSE?(a) BCNF is stricter than 3NF(b) Lossless, dependency-preserving decomposition into 3NF is always possible(c) Lossless, dependency-preserving decomposition into BCNF is always possible(d) Any relation with two attributes is in BCNF Answer (c)It is not always possible to decompose a table in BCNF and preserve dependencies. For example, a set of functional dependencies {AB –> C, C –> B} cannot be decomposed in BCNF. See this for more details. 2) The following table has two attributes A and C where A is the primary key and C is the foreign key referencing A with on-delete cascade. A C ----- 2 4 3 4 4 3 5 2 7 2 9 5 6 4 The set of all tuples that must be additionally deleted to preserve referential integrity when the tuple (2,4) is deleted is:(a) (3,4) and (6,4)(b) (5,2) and (7,2)(c) (5,2), (7,2) and (9,5)(d) (3,4), (4,3) and (6,4) Answer (C)When (2,4) is deleted. Since C is a foreign key referring A with delete on cascade, all entries with value 2 in C must be deleted. So (5, 2) and (7, 2) are deleted. As a result of this 5 and 7 are deleted from A which causes (9, 5) to be deleted. 3) The relation book (title, price) contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list? select title from book as B where (select count(*) from book as T where T.price > B.price) < 5 (a) Titles of the four most expensive books(b) Title of the fifth most inexpensive book(c) Title of the fifth most expensive book(d) Titles of the five most expensive books Answer (d)When a subquery uses values from outer query, the subquery is called correlated subquery. The correlated subquery is evaluated once for each row processed by the outer query.The outer query selects all titles from book table. For every selected book, the subquery returns count of those books which are more expensive than the selected book. The where clause of outer query will be true for 5 most expensive book. For example count (*) will be 0 for the most expensive book and count(*) will be 1 for second most expensive book. Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2005 DBMS GATE CS MCQ DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? SQL Trigger | Student Database Difference between Clustered and Non-clustered index Layers of OSI Model Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems Semaphores in Process Synchronization
[ { "code": null, "e": 29544, "s": 29516, "text": "\n27 Mar, 2017" }, { "code": null, "e": 29602, "s": 29544, "text": "Following questions have been asked in GATE 2005 CS exam." }, { "code": null, "e": 29903, "s": 29602, "text": "1) Which one of the following statements about normal forms is FALSE?(a) BCNF is stricter than 3NF(b) Lossless, dependency-preserving decomposition into 3NF is always possible(c) Lossless, dependency-preserving decomposition into BCNF is always possible(d) Any relation with two attributes is in BCNF" }, { "code": null, "e": 30116, "s": 29903, "text": "Answer (c)It is not always possible to decompose a table in BCNF and preserve dependencies. For example, a set of functional dependencies {AB –> C, C –> B} cannot be decomposed in BCNF. See this for more details." }, { "code": null, "e": 30256, "s": 30116, "text": "2) The following table has two attributes A and C where A is the primary key and C is the foreign key referencing A with on-delete cascade." }, { "code": null, "e": 30311, "s": 30256, "text": "A C\n-----\n2 4\n3 4\n4 3\n5 2\n7 2\n9 5\n6 4\n" }, { "code": null, "e": 30527, "s": 30311, "text": "The set of all tuples that must be additionally deleted to preserve referential integrity when the tuple (2,4) is deleted is:(a) (3,4) and (6,4)(b) (5,2) and (7,2)(c) (5,2), (7,2) and (9,5)(d) (3,4), (4,3) and (6,4)" }, { "code": null, "e": 30784, "s": 30527, "text": "Answer (C)When (2,4) is deleted. Since C is a foreign key referring A with delete on cascade, all entries with value 2 in C must be deleted. So (5, 2) and (7, 2) are deleted. As a result of this 5 and 7 are deleted from A which causes (9, 5) to be deleted." }, { "code": null, "e": 30959, "s": 30784, "text": "3) The relation book (title, price) contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list?" }, { "code": null, "e": 31071, "s": 30959, "text": " select title\n from book as B\n where (select count(*)\n from book as T\n where T.price > B.price) < 5\n" }, { "code": null, "e": 31244, "s": 31071, "text": "(a) Titles of the four most expensive books(b) Title of the fifth most inexpensive book(c) Title of the fifth most expensive book(d) Titles of the five most expensive books" }, { "code": null, "e": 31783, "s": 31244, "text": "Answer (d)When a subquery uses values from outer query, the subquery is called correlated subquery. The correlated subquery is evaluated once for each row processed by the outer query.The outer query selects all titles from book table. For every selected book, the subquery returns count of those books which are more expensive than the selected book. The where clause of outer query will be true for 5 most expensive book. For example count (*) will be 0 for the most expensive book and count(*) will be 1 for second most expensive book." }, { "code": null, "e": 31897, "s": 31783, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 32046, "s": 31897, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 32059, "s": 32046, "text": "GATE-CS-2005" }, { "code": null, "e": 32064, "s": 32059, "text": "DBMS" }, { "code": null, "e": 32072, "s": 32064, "text": "GATE CS" }, { "code": null, "e": 32076, "s": 32072, "text": "MCQ" }, { "code": null, "e": 32081, "s": 32076, "text": "DBMS" }, { "code": null, "e": 32179, "s": 32081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32188, "s": 32179, "text": "Comments" }, { "code": null, "e": 32201, "s": 32188, "text": "Old Comments" }, { "code": null, "e": 32248, "s": 32201, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 32266, "s": 32248, "text": "SQL | WITH clause" }, { "code": null, "e": 32307, "s": 32266, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 32338, "s": 32307, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 32391, "s": 32338, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 32411, "s": 32391, "text": "Layers of OSI Model" }, { "code": null, "e": 32438, "s": 32411, "text": "Types of Operating Systems" }, { "code": null, "e": 32451, "s": 32438, "text": "TCP/IP Model" }, { "code": null, "e": 32500, "s": 32451, "text": "Page Replacement Algorithms in Operating Systems" } ]
queue::empty() and queue::size() in C++ STL - GeeksforGeeks
27 Oct, 2021 Queue are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. empty() function is used to check if the queue container is empty or not. Syntax : queuename.empty() Parameters : No parameters are passed Returns : True, if list is empty False, Otherwise Examples: Input : myqueue = 1, 2, 3 myqueue.empty(); Output : False Input : myqueue myqueue.empty(); Output : True Errors and Exceptions Shows error if a parameter is passedShows no exception throw guarantee. Shows error if a parameter is passed Shows no exception throw guarantee. // CPP program to illustrate// Implementation of empty() function#include <iostream>#include <queue>using namespace std; int main(){ queue<int> myqueue; myqueue.push(1); // Queue becomes 1 if (myqueue.empty()) { cout << "True"; } else { cout << "False"; } return 0;} Output: False Application : Given a queue of integers, find the sum of the all the integers. Input : 1, 8, 3, 6, 2 Output : 20 Algorithm1. Check if the queue is empty, if not add the front element to a variable initialized as 0, and pop the front element.2. Repeat this step until the queue is empty.3. Print the final value of the variable. // CPP program to illustrate// Application of empty() function#include <iostream>#include <queue>using namespace std; int main(){ int sum = 0; queue<int> myqueue; myqueue.push(1); myqueue.push(8); myqueue.push(3); myqueue.push(6); myqueue.push(2); // Queue becomes 1, 8, 3, 6, 2 while (!myqueue.empty()) { sum = sum + myqueue.front(); myqueue.pop(); } cout << sum; return 0;} Output: 20 size() function is used to return the size of the list container or the number of elements in the list container. Syntax : queuename.size() Parameters : No parameters are passed Returns : Number of elements in the container Examples: Input : myqueue = 1, 2, 3 myqueue.size(); Output : 3 Input : myqueue myqueue.size(); Output : 0 Errors and Exceptions Shows error if a parameter is passed.Shows no exception throw guarantee Shows error if a parameter is passed. Shows no exception throw guarantee // CPP program to illustrate// Implementation of size() function#include <iostream>#include <queue>using namespace std; int main(){ int sum = 0; queue<int> myqueue; myqueue.push(1); myqueue.push(8); myqueue.push(3); myqueue.push(6); myqueue.push(2); // Queue becomes 1, 8, 3, 6, 2 cout << myqueue.size(); return 0;} Output: 5 Application : Given a queue of integers, find the sum of the all the integers. Input : 1, 8, 3, 6, 2 Output : 20 Algorithm1. Check if the size of the queue is zero, if not add the front element to a variable initialized as 0, and pop the front element.2. Repeat this step until the queue size becomes 0.3. Print the final value of the variable. // CPP program to illustrate// Application of empty() function#include <iostream>#include <queue>using namespace std; int main(){ int sum = 0; queue<int> myqueue; myqueue.push(1); myqueue.push(8); myqueue.push(3); myqueue.push(6); myqueue.push(2); // Queue becomes 1, 8, 3, 6, 2 while (myqueue.size() > 0) { sum = sum + myqueue.front(); myqueue.pop(); } cout << sum; return 0;} Output: 20 chhabradhanvi cpp-containers-library CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Pure Virtual Functions and Abstract Classes in C++
[ { "code": null, "e": 25368, "s": 25340, "text": "\n27 Oct, 2021" }, { "code": null, "e": 25545, "s": 25368, "text": "Queue are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front." }, { "code": null, "e": 25619, "s": 25545, "text": "empty() function is used to check if the queue container is empty or not." }, { "code": null, "e": 25628, "s": 25619, "text": "Syntax :" }, { "code": null, "e": 25735, "s": 25628, "text": "queuename.empty()\nParameters :\nNo parameters are passed\nReturns :\nTrue, if list is empty\nFalse, Otherwise\n" }, { "code": null, "e": 25745, "s": 25735, "text": "Examples:" }, { "code": null, "e": 25872, "s": 25745, "text": "Input : myqueue = 1, 2, 3\n myqueue.empty();\nOutput : False\n\nInput : myqueue\n myqueue.empty();\nOutput : True\n" }, { "code": null, "e": 25894, "s": 25872, "text": "Errors and Exceptions" }, { "code": null, "e": 25966, "s": 25894, "text": "Shows error if a parameter is passedShows no exception throw guarantee." }, { "code": null, "e": 26003, "s": 25966, "text": "Shows error if a parameter is passed" }, { "code": null, "e": 26039, "s": 26003, "text": "Shows no exception throw guarantee." }, { "code": "// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <queue>using namespace std; int main(){ queue<int> myqueue; myqueue.push(1); // Queue becomes 1 if (myqueue.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}", "e": 26349, "s": 26039, "text": null }, { "code": null, "e": 26357, "s": 26349, "text": "Output:" }, { "code": null, "e": 26364, "s": 26357, "text": "False\n" }, { "code": null, "e": 26443, "s": 26364, "text": "Application : Given a queue of integers, find the sum of the all the integers." }, { "code": null, "e": 26479, "s": 26443, "text": "Input : 1, 8, 3, 6, 2\nOutput : 20\n" }, { "code": null, "e": 26694, "s": 26479, "text": "Algorithm1. Check if the queue is empty, if not add the front element to a variable initialized as 0, and pop the front element.2. Repeat this step until the queue is empty.3. Print the final value of the variable." }, { "code": "// CPP program to illustrate// Application of empty() function#include <iostream>#include <queue>using namespace std; int main(){ int sum = 0; queue<int> myqueue; myqueue.push(1); myqueue.push(8); myqueue.push(3); myqueue.push(6); myqueue.push(2); // Queue becomes 1, 8, 3, 6, 2 while (!myqueue.empty()) { sum = sum + myqueue.front(); myqueue.pop(); } cout << sum; return 0;}", "e": 27125, "s": 26694, "text": null }, { "code": null, "e": 27133, "s": 27125, "text": "Output:" }, { "code": null, "e": 27137, "s": 27133, "text": "20\n" }, { "code": null, "e": 27251, "s": 27137, "text": "size() function is used to return the size of the list container or the number of elements in the list container." }, { "code": null, "e": 27260, "s": 27251, "text": "Syntax :" }, { "code": null, "e": 27362, "s": 27260, "text": "queuename.size()\nParameters :\nNo parameters are passed\nReturns :\nNumber of elements in the container\n" }, { "code": null, "e": 27372, "s": 27362, "text": "Examples:" }, { "code": null, "e": 27490, "s": 27372, "text": "Input : myqueue = 1, 2, 3\n myqueue.size();\nOutput : 3\n\nInput : myqueue\n myqueue.size();\nOutput : 0\n" }, { "code": null, "e": 27512, "s": 27490, "text": "Errors and Exceptions" }, { "code": null, "e": 27584, "s": 27512, "text": "Shows error if a parameter is passed.Shows no exception throw guarantee" }, { "code": null, "e": 27622, "s": 27584, "text": "Shows error if a parameter is passed." }, { "code": null, "e": 27657, "s": 27622, "text": "Shows no exception throw guarantee" }, { "code": "// CPP program to illustrate// Implementation of size() function#include <iostream>#include <queue>using namespace std; int main(){ int sum = 0; queue<int> myqueue; myqueue.push(1); myqueue.push(8); myqueue.push(3); myqueue.push(6); myqueue.push(2); // Queue becomes 1, 8, 3, 6, 2 cout << myqueue.size(); return 0;}", "e": 28010, "s": 27657, "text": null }, { "code": null, "e": 28018, "s": 28010, "text": "Output:" }, { "code": null, "e": 28021, "s": 28018, "text": "5\n" }, { "code": null, "e": 28100, "s": 28021, "text": "Application : Given a queue of integers, find the sum of the all the integers." }, { "code": null, "e": 28136, "s": 28100, "text": "Input : 1, 8, 3, 6, 2\nOutput : 20\n" }, { "code": null, "e": 28368, "s": 28136, "text": "Algorithm1. Check if the size of the queue is zero, if not add the front element to a variable initialized as 0, and pop the front element.2. Repeat this step until the queue size becomes 0.3. Print the final value of the variable." }, { "code": "// CPP program to illustrate// Application of empty() function#include <iostream>#include <queue>using namespace std; int main(){ int sum = 0; queue<int> myqueue; myqueue.push(1); myqueue.push(8); myqueue.push(3); myqueue.push(6); myqueue.push(2); // Queue becomes 1, 8, 3, 6, 2 while (myqueue.size() > 0) { sum = sum + myqueue.front(); myqueue.pop(); } cout << sum; return 0;}", "e": 28801, "s": 28368, "text": null }, { "code": null, "e": 28809, "s": 28801, "text": "Output:" }, { "code": null, "e": 28813, "s": 28809, "text": "20\n" }, { "code": null, "e": 28827, "s": 28813, "text": "chhabradhanvi" }, { "code": null, "e": 28850, "s": 28827, "text": "cpp-containers-library" }, { "code": null, "e": 28862, "s": 28850, "text": "CPP-Library" }, { "code": null, "e": 28866, "s": 28862, "text": "STL" }, { "code": null, "e": 28870, "s": 28866, "text": "C++" }, { "code": null, "e": 28874, "s": 28870, "text": "STL" }, { "code": null, "e": 28878, "s": 28874, "text": "CPP" }, { "code": null, "e": 28976, "s": 28878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29004, "s": 28976, "text": "Operator Overloading in C++" }, { "code": null, "e": 29024, "s": 29004, "text": "Polymorphism in C++" }, { "code": null, "e": 29057, "s": 29024, "text": "Friend class and function in C++" }, { "code": null, "e": 29081, "s": 29057, "text": "Sorting a vector in C++" }, { "code": null, "e": 29106, "s": 29081, "text": "std::string class in C++" }, { "code": null, "e": 29130, "s": 29106, "text": "Inline Functions in C++" }, { "code": null, "e": 29174, "s": 29130, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29227, "s": 29174, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 29263, "s": 29227, "text": "Convert string to char array in C++" } ]
HTML <link> Tag - GeeksforGeeks
16 Dec, 2021 The <link> tag in HTML is used to define a link between a document and an external resource. The link tag is mainly used to link to external style sheets. This element can appear multiple times but it goes only in the head section. The link element is empty, it contains attributes only. The values in the link element denote how the item being linked to & is related to the containing document. Syntax: <link rel="stylesheet" type="text/css" href="styles.css"> Attributes values: charset: It is used to specify the character encoding for the HTML linked document. crossOrigin: It assigns the CORS settings of the linked document. disabled: It is used to specify that the linked document is disabled. href: It s used to specify the URL of the linked document. hreflang: It is used to specify the language for a linked document. media: It is used to specify what media/device the target resource is optimized for. rel: It is used to specify the relationship between the current and the linked document. rev: It assigns the reverse relationship from the linked document to the current document. sizes: It is used to specify the sizes of the icon for visual media and it only works when rel=”icon”. target: It is used to specify the window or a frame where the linked document is loaded. type: It is used to set/return the content type of the linked document. Example 1: In this example, we have used the <link> tag & declared the rel attribute & type attribute inside of the tag in HTML. HTML <!DOCTYPE html><html><head> <link rel="stylesheet" type="text/css" href="style.css"></head> <body> <h1>GeeksforGeeks</h1> <h3>HTML Link Tag</h3> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. </p> </body></html> Output: HTML <link> tag Example 2: In this example, we have used the hreflang attribute whose value is set to”en-us” which will specify the language of the linked document. And we are linking an external CSS file that contains a color property for the h1 tag which is set to green. HTML <!DOCTYPE html><html><head> <title>HTML Link Tag</title> <link rel="stylesheet" type="text/css" href="style.css" hreflang="en-us"></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML Link Tag</h2></body></html> Output: HTML <link> tag Supported Browsers: Google Chrome 93.0 & above Internet Explorer 11.0 Microsoft Edge 93.0 Firefox 92.0 & above Safari 14.1 Opera 79.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Akanksha_Rai bhaskargeeksforgeeks HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26249, "s": 26221, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26645, "s": 26249, "text": "The <link> tag in HTML is used to define a link between a document and an external resource. The link tag is mainly used to link to external style sheets. This element can appear multiple times but it goes only in the head section. The link element is empty, it contains attributes only. The values in the link element denote how the item being linked to & is related to the containing document." }, { "code": null, "e": 26653, "s": 26645, "text": "Syntax:" }, { "code": null, "e": 26712, "s": 26653, "text": " <link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">" }, { "code": null, "e": 26731, "s": 26712, "text": "Attributes values:" }, { "code": null, "e": 26815, "s": 26731, "text": "charset: It is used to specify the character encoding for the HTML linked document." }, { "code": null, "e": 26881, "s": 26815, "text": "crossOrigin: It assigns the CORS settings of the linked document." }, { "code": null, "e": 26951, "s": 26881, "text": "disabled: It is used to specify that the linked document is disabled." }, { "code": null, "e": 27010, "s": 26951, "text": "href: It s used to specify the URL of the linked document." }, { "code": null, "e": 27078, "s": 27010, "text": "hreflang: It is used to specify the language for a linked document." }, { "code": null, "e": 27163, "s": 27078, "text": "media: It is used to specify what media/device the target resource is optimized for." }, { "code": null, "e": 27252, "s": 27163, "text": "rel: It is used to specify the relationship between the current and the linked document." }, { "code": null, "e": 27343, "s": 27252, "text": "rev: It assigns the reverse relationship from the linked document to the current document." }, { "code": null, "e": 27446, "s": 27343, "text": "sizes: It is used to specify the sizes of the icon for visual media and it only works when rel=”icon”." }, { "code": null, "e": 27535, "s": 27446, "text": "target: It is used to specify the window or a frame where the linked document is loaded." }, { "code": null, "e": 27607, "s": 27535, "text": "type: It is used to set/return the content type of the linked document." }, { "code": null, "e": 27736, "s": 27607, "text": "Example 1: In this example, we have used the <link> tag & declared the rel attribute & type attribute inside of the tag in HTML." }, { "code": null, "e": 27741, "s": 27736, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head> <body> <h1>GeeksforGeeks</h1> <h3>HTML Link Tag</h3> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. </p> </body></html>", "e": 28111, "s": 27741, "text": null }, { "code": null, "e": 28120, "s": 28111, "text": " Output:" }, { "code": null, "e": 28136, "s": 28120, "text": "HTML <link> tag" }, { "code": null, "e": 28394, "s": 28136, "text": "Example 2: In this example, we have used the hreflang attribute whose value is set to”en-us” which will specify the language of the linked document. And we are linking an external CSS file that contains a color property for the h1 tag which is set to green." }, { "code": null, "e": 28399, "s": 28394, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>HTML Link Tag</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" hreflang=\"en-us\"></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML Link Tag</h2></body></html>", "e": 28643, "s": 28399, "text": null }, { "code": null, "e": 28651, "s": 28643, "text": "Output:" }, { "code": null, "e": 28667, "s": 28651, "text": "HTML <link> tag" }, { "code": null, "e": 28687, "s": 28667, "text": "Supported Browsers:" }, { "code": null, "e": 28714, "s": 28687, "text": "Google Chrome 93.0 & above" }, { "code": null, "e": 28737, "s": 28714, "text": "Internet Explorer 11.0" }, { "code": null, "e": 28757, "s": 28737, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 28778, "s": 28757, "text": "Firefox 92.0 & above" }, { "code": null, "e": 28790, "s": 28778, "text": "Safari 14.1" }, { "code": null, "e": 28801, "s": 28790, "text": "Opera 79.0" }, { "code": null, "e": 28938, "s": 28801, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28951, "s": 28938, "text": "Akanksha_Rai" }, { "code": null, "e": 28972, "s": 28951, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28982, "s": 28972, "text": "HTML-Tags" }, { "code": null, "e": 28987, "s": 28982, "text": "HTML" }, { "code": null, "e": 29004, "s": 28987, "text": "Web Technologies" }, { "code": null, "e": 29009, "s": 29004, "text": "HTML" }, { "code": null, "e": 29107, "s": 29009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29131, "s": 29107, "text": "REST API (Introduction)" }, { "code": null, "e": 29172, "s": 29131, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29209, "s": 29172, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29238, "s": 29209, "text": "Form validation using jQuery" }, { "code": null, "e": 29258, "s": 29238, "text": "Angular File Upload" }, { "code": null, "e": 29298, "s": 29258, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29331, "s": 29298, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29376, "s": 29331, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29419, "s": 29376, "text": "How to fetch data from an API in ReactJS ?" } ]
C# | Char.IsNumber() Method - GeeksforGeeks
01 Feb, 2019 In C#, Char.IsNumber() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a number or not. Valid numbers will be the members of the UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, or UnicodeCategory.OtherNumber category. This method can be overloaded by passing different type and number of arguments to it. Char.IsNumber(Char) MethodChar.IsNumber(String, Int32) Method Char.IsNumber(Char) Method Char.IsNumber(String, Int32) Method Note: The only difference between Char.IsDigit() and Char.IsNumber() method is that IsDigit() method will only check whether a Char is a radix-10 digit or not. While IsNumber() method will check whether a char is a decimal digit, numbers include characters, fractions, subscripts, superscripts, Roman numerals, currency numerators, and encircled numbers or not. This method is used to check whether the specified Unicode character matches number or not. If it matches then it returns True otherwise return False. Syntax: public static bool IsNumber(char ch); Parameter: ch: It is required Unicode character of System.char type which is to be checked. Return Type: The method returns True, if it successfully matches any number, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsNumber(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if 5 is a // number or not char ch1 = '5'; result = Char.IsNumber(ch1); Console.WriteLine(result); // checking if 'c' is a // number or not char ch2 = 'c'; result = Char.IsNumber(ch2); Console.WriteLine(result); }} True False This method is used to check whether the specified string at specified position matches with any number or not. If it matches then it returns True otherwise returns False. Syntax: public static bool IsNumber(string str, int index); Parameters: Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32. Return Type: The method returns True if it successfully matches any number at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean. Exceptions: If the value of str is null then this method will give ArgumentNullException. If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException. Example: // C# program to illustrate the// Char.IsNumber(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for number in a // string at a desired position string str1 = "GeeksforGeeks"; result = Char.IsNumber(str1, 2); Console.WriteLine(result); // checking for number in a // string at a desired position string str2 = "geeks5forgeeks"; result = Char.IsNumber(str2, 5); Console.WriteLine(result); }} False True Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsNumber?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# Dictionary with examples C# | Arrays of Strings C# | Delegates C# | Method Overriding C# | Abstract Classes C# | Replace() Method
[ { "code": null, "e": 24118, "s": 24090, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24410, "s": 24118, "text": "In C#, Char.IsNumber() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a number or not. Valid numbers will be the members of the UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, or UnicodeCategory.OtherNumber category." }, { "code": null, "e": 24497, "s": 24410, "text": "This method can be overloaded by passing different type and number of arguments to it." }, { "code": null, "e": 24559, "s": 24497, "text": "Char.IsNumber(Char) MethodChar.IsNumber(String, Int32) Method" }, { "code": null, "e": 24586, "s": 24559, "text": "Char.IsNumber(Char) Method" }, { "code": null, "e": 24622, "s": 24586, "text": "Char.IsNumber(String, Int32) Method" }, { "code": null, "e": 24984, "s": 24622, "text": "Note: The only difference between Char.IsDigit() and Char.IsNumber() method is that IsDigit() method will only check whether a Char is a radix-10 digit or not. While IsNumber() method will check whether a char is a decimal digit, numbers include characters, fractions, subscripts, superscripts, Roman numerals, currency numerators, and encircled numbers or not." }, { "code": null, "e": 25135, "s": 24984, "text": "This method is used to check whether the specified Unicode character matches number or not. If it matches then it returns True otherwise return False." }, { "code": null, "e": 25143, "s": 25135, "text": "Syntax:" }, { "code": null, "e": 25181, "s": 25143, "text": "public static bool IsNumber(char ch);" }, { "code": null, "e": 25192, "s": 25181, "text": "Parameter:" }, { "code": null, "e": 25273, "s": 25192, "text": "ch: It is required Unicode character of System.char type which is to be checked." }, { "code": null, "e": 25425, "s": 25273, "text": "Return Type: The method returns True, if it successfully matches any number, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 25434, "s": 25425, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsNumber(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if 5 is a // number or not char ch1 = '5'; result = Char.IsNumber(ch1); Console.WriteLine(result); // checking if 'c' is a // number or not char ch2 = 'c'; result = Char.IsNumber(ch2); Console.WriteLine(result); }}", "e": 25936, "s": 25434, "text": null }, { "code": null, "e": 25948, "s": 25936, "text": "True\nFalse\n" }, { "code": null, "e": 26120, "s": 25948, "text": "This method is used to check whether the specified string at specified position matches with any number or not. If it matches then it returns True otherwise returns False." }, { "code": null, "e": 26128, "s": 26120, "text": "Syntax:" }, { "code": null, "e": 26180, "s": 26128, "text": "public static bool IsNumber(string str, int index);" }, { "code": null, "e": 26192, "s": 26180, "text": "Parameters:" }, { "code": null, "e": 26377, "s": 26192, "text": "Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32." }, { "code": null, "e": 26575, "s": 26377, "text": "Return Type: The method returns True if it successfully matches any number at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 26587, "s": 26575, "text": "Exceptions:" }, { "code": null, "e": 26665, "s": 26587, "text": "If the value of str is null then this method will give ArgumentNullException." }, { "code": null, "e": 26793, "s": 26665, "text": "If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException." }, { "code": null, "e": 26802, "s": 26793, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsNumber(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for number in a // string at a desired position string str1 = \"GeeksforGeeks\"; result = Char.IsNumber(str1, 2); Console.WriteLine(result); // checking for number in a // string at a desired position string str2 = \"geeks5forgeeks\"; result = Char.IsNumber(str2, 5); Console.WriteLine(result); }}", "e": 27392, "s": 26802, "text": null }, { "code": null, "e": 27404, "s": 27392, "text": "False\nTrue\n" }, { "code": null, "e": 27504, "s": 27404, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsNumber?view=netframework-4.7.2" }, { "code": null, "e": 27523, "s": 27504, "text": "CSharp-Char-Struct" }, { "code": null, "e": 27537, "s": 27523, "text": "CSharp-method" }, { "code": null, "e": 27540, "s": 27537, "text": "C#" }, { "code": null, "e": 27638, "s": 27540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27692, "s": 27638, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 27734, "s": 27692, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 27796, "s": 27734, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 27824, "s": 27796, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 27852, "s": 27824, "text": "C# Dictionary with examples" }, { "code": null, "e": 27875, "s": 27852, "text": "C# | Arrays of Strings" }, { "code": null, "e": 27890, "s": 27875, "text": "C# | Delegates" }, { "code": null, "e": 27913, "s": 27890, "text": "C# | Method Overriding" }, { "code": null, "e": 27935, "s": 27913, "text": "C# | Abstract Classes" } ]
Perl exec Function
This function executes a system command (directly, not within a shell) and never returns to the calling script, except if the command specified does not exist and has been called directly, instead of indirectly through a shell. The operation works as follows − If there is only one scalar argument that contains no shell metacharacters, then the argument is converted into a list and the command is executed directly, without a shell. If there is only one scalar argument that contains shell metacharacters, then the argument is executed through the standard shell, usually /bin/sh on Unix. If LIST is more than one argument, or an array with more than one value, then the command is executed directly without the use of a shell. Following is the simple syntax for this function − exec EXPR LIST exec LIST This function returns 0 only if the command specified cannot be executed. 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2220, "text": "This function executes a system command (directly, not within a shell) and never returns to the calling script, except if the command specified does not exist and has been called directly, instead of indirectly through a shell. The operation works as follows −" }, { "code": null, "e": 2655, "s": 2481, "text": "If there is only one scalar argument that contains no shell metacharacters, then the argument is converted into a list and the command is executed directly, without a shell." }, { "code": null, "e": 2811, "s": 2655, "text": "If there is only one scalar argument that contains shell metacharacters, then the argument is executed through the standard shell, usually /bin/sh on Unix." }, { "code": null, "e": 2950, "s": 2811, "text": "If LIST is more than one argument, or an array with more than one value, then the command is executed directly without the use of a shell." }, { "code": null, "e": 3001, "s": 2950, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 3028, "s": 3001, "text": "exec EXPR LIST\n\nexec LIST\n" }, { "code": null, "e": 3102, "s": 3028, "text": "This function returns 0 only if the command specified cannot be executed." }, { "code": null, "e": 3137, "s": 3102, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3151, "s": 3137, "text": " Devi Killada" }, { "code": null, "e": 3186, "s": 3151, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3206, "s": 3186, "text": " Harshit Srivastava" }, { "code": null, "e": 3239, "s": 3206, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3255, "s": 3239, "text": " TELCOMA Global" }, { "code": null, "e": 3288, "s": 3255, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3305, "s": 3288, "text": " Mohammad Nauman" }, { "code": null, "e": 3338, "s": 3305, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3361, "s": 3338, "text": " Stone River ELearning" }, { "code": null, "e": 3396, "s": 3361, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3419, "s": 3396, "text": " Stone River ELearning" }, { "code": null, "e": 3426, "s": 3419, "text": " Print" }, { "code": null, "e": 3437, "s": 3426, "text": " Add Notes" } ]
Can I import same package twice? Will JVM load the package twice at runtime?
In Java classes and interfaces related to each other are grouped under a package. Package is nothing but a directory storing classes and interfaces of a particular concept. For example, all the classes and interfaces related to input and output operations are stored in java.io package. You can group required classes and interfaces under one package just by declaring the package at the top of the Class/Interface (file) using the keyword package as − package com.tutorialspoint.mypackage; public class Sample{ public void demo(){ System.out.println("This is a method of the sample class"); } public static void main(String args[]){ System.out.println("Hello how are you......"); } } Unlike other programs to compile a program with a package, you need to use the –d option of the javac command specifying the destination path where you need to create the package. javac –d . Sample.java If you haven’t mentioned the destination path the package will be created in the current directory. To access the classes/interfaces that are grouped under a package, you need to add the location of the package in the classpath variable (or make sure the package is in the current directory) and import the class/interface of it using the import keyword. import com.tutorialspoint.mypackage.Sample; public class Test{ public static void main(String args[]){ Sample obj = new Sample(); obj.demo(); } } This is a method of the sample class Yes, you can import a class twice in Java, it doesn’t create any issues but, irrespective of the number of times you import, JVM loads the class only once. In the following Java program, we are trying to import the Sample class of the com.tutorialspoint.mypackage package only once. import com.tutorialspoint.mypackage.Sample; import com.tutorialspoint.mypackage.Sample; public class Test{ public static void main(String args[]){ Sample obj = new Sample(); obj.demo(); } } Sample class loaded This is a method of the sample class
[ { "code": null, "e": 1349, "s": 1062, "text": "In Java classes and interfaces related to each other are grouped under a package. Package is nothing but a directory storing classes and interfaces of a particular concept. For example, all the classes and interfaces related to input and output operations are stored in java.io package." }, { "code": null, "e": 1515, "s": 1349, "text": "You can group required classes and interfaces under one package just by declaring the package at the top of the Class/Interface (file) using the keyword package as −" }, { "code": null, "e": 1771, "s": 1515, "text": "package com.tutorialspoint.mypackage;\npublic class Sample{\n public void demo(){\n System.out.println(\"This is a method of the sample class\");\n }\n public static void main(String args[]){\n System.out.println(\"Hello how are you......\");\n }\n}" }, { "code": null, "e": 1951, "s": 1771, "text": "Unlike other programs to compile a program with a package, you need to use the –d option of the javac command specifying the destination path where you need to create the package." }, { "code": null, "e": 1974, "s": 1951, "text": "javac –d . Sample.java" }, { "code": null, "e": 2074, "s": 1974, "text": "If you haven’t mentioned the destination path the package will be created in the current directory." }, { "code": null, "e": 2329, "s": 2074, "text": "To access the classes/interfaces that are grouped under a package, you need to add the location of the package in the classpath variable (or make sure the package is in the current directory) and import the class/interface of it using the import keyword." }, { "code": null, "e": 2493, "s": 2329, "text": "import com.tutorialspoint.mypackage.Sample;\npublic class Test{\n public static void main(String args[]){\n Sample obj = new Sample();\n obj.demo();\n }\n}" }, { "code": null, "e": 2530, "s": 2493, "text": "This is a method of the sample class" }, { "code": null, "e": 2686, "s": 2530, "text": "Yes, you can import a class twice in Java, it doesn’t create any issues but, irrespective of the number of times you import, JVM loads the class only once." }, { "code": null, "e": 2813, "s": 2686, "text": "In the following Java program, we are trying to import the Sample class of the com.tutorialspoint.mypackage package only once." }, { "code": null, "e": 3021, "s": 2813, "text": "import com.tutorialspoint.mypackage.Sample;\nimport com.tutorialspoint.mypackage.Sample;\npublic class Test{\n public static void main(String args[]){\n Sample obj = new Sample();\n obj.demo();\n }\n}" }, { "code": null, "e": 3078, "s": 3021, "text": "Sample class loaded\nThis is a method of the sample class" } ]
Directories in Python
All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories. You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created. os.mkdir("newdir") Following is the example to create a directory test in the current directory − #!/usr/bin/python import os # Create a directory "test" os.mkdir("test") You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory. os.chdir("newdir") Following is the example to go into "/home/newdir" directory − #!/usr/bin/python import os # Changing a directory to "/home/newdir" os.chdir("/home/newdir") The getcwd() method displays the current working directory. os.getcwd() Following is the example to give current directory − #!/usr/bin/python import os # This would give location of the current directory os.getcwd() The rmdir() method deletes the directory, which is passed as an argument in the method. Before removing a directory, all the contents in it should be removed. os.rmdir('dirname') Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory. #!/usr/bin/python import os # This would remove "/tmp/test" directory. os.rmdir( "/tmp/test" )
[ { "code": null, "e": 1248, "s": 1062, "text": "All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories." }, { "code": null, "e": 1446, "s": 1248, "text": "You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created." }, { "code": null, "e": 1465, "s": 1446, "text": "os.mkdir(\"newdir\")" }, { "code": null, "e": 1544, "s": 1465, "text": "Following is the example to create a directory test in the current directory −" }, { "code": null, "e": 1617, "s": 1544, "text": "#!/usr/bin/python\nimport os\n# Create a directory \"test\"\nos.mkdir(\"test\")" }, { "code": null, "e": 1799, "s": 1617, "text": "You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory." }, { "code": null, "e": 1819, "s": 1799, "text": "os.chdir(\"newdir\")\n" }, { "code": null, "e": 1882, "s": 1819, "text": "Following is the example to go into \"/home/newdir\" directory −" }, { "code": null, "e": 1976, "s": 1882, "text": "#!/usr/bin/python\nimport os\n# Changing a directory to \"/home/newdir\"\nos.chdir(\"/home/newdir\")" }, { "code": null, "e": 2036, "s": 1976, "text": "The getcwd() method displays the current working directory." }, { "code": null, "e": 2049, "s": 2036, "text": "os.getcwd()\n" }, { "code": null, "e": 2102, "s": 2049, "text": "Following is the example to give current directory −" }, { "code": null, "e": 2194, "s": 2102, "text": "#!/usr/bin/python\nimport os\n# This would give location of the current directory\nos.getcwd()" }, { "code": null, "e": 2282, "s": 2194, "text": "The rmdir() method deletes the directory, which is passed as an argument in the method." }, { "code": null, "e": 2353, "s": 2282, "text": "Before removing a directory, all the contents in it should be removed." }, { "code": null, "e": 2374, "s": 2353, "text": "os.rmdir('dirname')\n" }, { "code": null, "e": 2565, "s": 2374, "text": "Following is the example to remove \"/tmp/test\" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory." }, { "code": null, "e": 2660, "s": 2565, "text": "#!/usr/bin/python\nimport os\n# This would remove \"/tmp/test\" directory.\nos.rmdir( \"/tmp/test\" )" } ]
C program to find out cosine and sine values using math.h library.
To find the cosine and sine values for every 10 degrees from 0 to 150. The logic used to find the cosine values is as follows − Declare MAX and PI value at the starting of a program while(angle <= MAX){ x = (PI/MAX)*angle; y = cos(x); printf("%15d %13.4f\n", angle, y); angle = angle + 10; } The logic used to find the sine values is as follows − Declare MAX and PI value at the starting of a program. while(angle <= MAX){ x = (PI/MAX)*angle; y = sin(x); printf("%15d %13.4f\n", angle, y); angle = angle + 10; } Following is the C program to find the cosine values − //cosine values #include<stdio.h> #include <math.h> #define PI 3.1416 #define MAX 150 main ( ) { int angle; float x,y; angle = 0; printf("Angle cos(angle)\n\n"); while(angle <= MAX) { x = (PI/MAX)*angle; y = cos(x); printf("%15d %13.4f\n", angle, y); angle = angle + 10; } } When the above program is executed, it produces the following output − Angle cos(angle) 0 1.0000 10 0.9781 20 0.9135 30 0.8090 40 0.6691 50 0.5000 60 0.3090 70 0.1045 80 -0.1045 90 -0.3090 100 -0.5000 110 -0.6691 120 -0.8090 130 -0.9135 140 -0.9781 150 -1.0000 Following is the C program to find the sine values − //sine values #include<stdio.h> #include <math.h> #define PI 3.1416 #define MAX 150 main ( ){ int angle; float x,y; angle = 0; printf("Angle sin(angle)\n\n"); while(angle <= MAX){ x = (PI/MAX)*angle; y = sin(x); printf("%15d %13.4f\n", angle, y); angle = angle + 10; } } When the above program is executed, it produces the following output − Angle sin(angle) 0 0.0000 10 0.2079 20 0.4067 30 0.5878 40 0.7431 50 0.8660 60 0.9511 70 0.9945 80 0.9945 90 0.9511 100 0.8660 110 0.7431 120 0.5878 130 0.4067 140 0.2079 150 -0.0000
[ { "code": null, "e": 1133, "s": 1062, "text": "To find the cosine and sine values for every 10 degrees from 0 to 150." }, { "code": null, "e": 1190, "s": 1133, "text": "The logic used to find the cosine values is as follows −" }, { "code": null, "e": 1244, "s": 1190, "text": "Declare MAX and PI value at the starting of a program" }, { "code": null, "e": 1366, "s": 1244, "text": "while(angle <= MAX){\n x = (PI/MAX)*angle;\n y = cos(x);\n printf(\"%15d %13.4f\\n\", angle, y);\n angle = angle + 10;\n}" }, { "code": null, "e": 1421, "s": 1366, "text": "The logic used to find the sine values is as follows −" }, { "code": null, "e": 1476, "s": 1421, "text": "Declare MAX and PI value at the starting of a program." }, { "code": null, "e": 1598, "s": 1476, "text": "while(angle <= MAX){\n x = (PI/MAX)*angle;\n y = sin(x);\n printf(\"%15d %13.4f\\n\", angle, y);\n angle = angle + 10;\n}" }, { "code": null, "e": 1653, "s": 1598, "text": "Following is the C program to find the cosine values −" }, { "code": null, "e": 1970, "s": 1653, "text": "//cosine values\n#include<stdio.h>\n#include <math.h>\n#define PI 3.1416\n#define MAX 150\nmain ( ) {\n int angle;\n float x,y;\n angle = 0;\n printf(\"Angle cos(angle)\\n\\n\");\n while(angle <= MAX) {\n x = (PI/MAX)*angle;\n y = cos(x);\n printf(\"%15d %13.4f\\n\", angle, y);\n angle = angle + 10;\n }\n}" }, { "code": null, "e": 2041, "s": 1970, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2231, "s": 2041, "text": "Angle cos(angle)\n0 1.0000\n10 0.9781\n20 0.9135\n30 0.8090\n40 0.6691\n50 0.5000\n60 0.3090\n70 0.1045\n80 -0.1045\n90 -0.3090\n100 -0.5000\n110 -0.6691\n120 -0.8090\n130 -0.9135\n140 -0.9781\n150 -1.0000" }, { "code": null, "e": 2284, "s": 2231, "text": "Following is the C program to find the sine values −" }, { "code": null, "e": 2597, "s": 2284, "text": "//sine values\n#include<stdio.h>\n#include <math.h>\n#define PI 3.1416\n#define MAX 150\nmain ( ){\n int angle;\n float x,y;\n angle = 0;\n printf(\"Angle sin(angle)\\n\\n\");\n while(angle <= MAX){\n x = (PI/MAX)*angle;\n y = sin(x);\n printf(\"%15d %13.4f\\n\", angle, y);\n angle = angle + 10;\n }\n}" }, { "code": null, "e": 2668, "s": 2597, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2852, "s": 2668, "text": "Angle sin(angle)\n\n0 0.0000\n10 0.2079\n20 0.4067\n30 0.5878\n40 0.7431\n50 0.8660\n60 0.9511\n70 0.9945\n80 0.9945\n90 0.9511\n100 0.8660\n110 0.7431\n120 0.5878\n130 0.4067\n140 0.2079\n150 -0.0000" } ]
How to get the list of all databases using JDBC?
You can get the list of databases in MySQL using the SHOW DATABASES query. show databases; Following JDBC program retrieves the list of databases by executing the show databases query. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ShowDatabasesExample { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("Show Databases"); System.out.println("List of databases: "); while(rs.next()) { System.out.print(rs.getString(1)); System.out.println(); } } } Connection established...... List of databases: information_schema base details errors logging mydatabase mydb mysql performance_schema sample_database sampledb students sys testdb world Or, You can use the getCatalogs() method of the DatabaseMetaData interface. import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; public class ListOfAllDatabases { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Retrieving the meta data object DatabaseMetaData metaData = con.getMetaData(); //Retrieving the list of database names ResultSet tables = metaData.getCatalogs(); while (tables.next()) { System.out.println(tables.getString("TABLE_CAT")); } } } Connection established...... List of databases: information_schema base details errors logging mydatabase mydb mysql performance_schema sample_database sampledb students sys testdb world
[ { "code": null, "e": 1137, "s": 1062, "text": "You can get the list of databases in MySQL using the SHOW DATABASES query." }, { "code": null, "e": 1153, "s": 1137, "text": "show databases;" }, { "code": null, "e": 1247, "s": 1153, "text": "Following JDBC program retrieves the list of databases by executing the show databases query." }, { "code": null, "e": 2117, "s": 1247, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class ShowDatabasesExample {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"Show Databases\");\n System.out.println(\"List of databases: \");\n while(rs.next()) {\n System.out.print(rs.getString(1));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 2304, "s": 2117, "text": "Connection established......\nList of databases:\ninformation_schema\nbase\ndetails\nerrors\nlogging\nmydatabase\nmydb\nmysql\nperformance_schema\nsample_database\nsampledb\nstudents\nsys\ntestdb\nworld" }, { "code": null, "e": 2380, "s": 2304, "text": "Or, You can use the getCatalogs() method of the DatabaseMetaData interface." }, { "code": null, "e": 3216, "s": 2380, "text": "import java.sql.Connection;\nimport java.sql.DatabaseMetaData;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\npublic class ListOfAllDatabases {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Retrieving the meta data object\n DatabaseMetaData metaData = con.getMetaData();\n //Retrieving the list of database names\n ResultSet tables = metaData.getCatalogs();\n while (tables.next()) {\n System.out.println(tables.getString(\"TABLE_CAT\"));\n }\n }\n}" }, { "code": null, "e": 3403, "s": 3216, "text": "Connection established......\nList of databases:\ninformation_schema\nbase\ndetails\nerrors\nlogging\nmydatabase\nmydb\nmysql\nperformance_schema\nsample_database\nsampledb\nstudents\nsys\ntestdb\nworld" } ]
Working with RxJS & ReactJS
In this chapter, we will see how to use RxJs with ReactJS. We will not get into the installation process for Reactjs here, to know about ReactJS Installation refer this link: /reactjs/reactjs_environment_setup.htm We will directly work on an example below, where will use Ajax from RxJS to load data. import React, { Component } from "react"; import ReactDOM from "react-dom"; import { ajax } from 'rxjs/ajax'; import { map } from 'rxjs/operators'; class App extends Component { constructor() { super(); this.state = { data: [] }; } componentDidMount() { const response = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response)); response.subscribe(res => { this.setState({ data: res }); }); } render() { return ( <div> <h3>Using RxJS with ReactJS</h3> <ul> {this.state.data.map(el => ( <li> {el.id}: {el.name} </li> ))} </ul> </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); <!DOCTYPE html> <html> <head> <meta charset = "UTF-8" /> <title>ReactJS Demo</title> <head> <body> <div id = "root"></div> </body> </html> We have used ajax from RxJS that will load data from this Url − https://jsonplaceholder.typicode.com/users. When you compile, the display is as shown below − 51 Lectures 4 hours Daniel Stern Print Add Notes Bookmark this page
[ { "code": null, "e": 2038, "s": 1824, "text": "In this chapter, we will see how to use RxJs with ReactJS. We will not get into the installation process for Reactjs here, to know about ReactJS Installation refer this link: /reactjs/reactjs_environment_setup.htm" }, { "code": null, "e": 2125, "s": 2038, "text": "We will directly work on an example below, where will use Ajax from RxJS to load data." }, { "code": null, "e": 2955, "s": 2125, "text": "import React, { Component } from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { ajax } from 'rxjs/ajax';\nimport { map } from 'rxjs/operators';\nclass App extends Component {\n constructor() {\n super();\n this.state = { data: [] };\n }\n componentDidMount() {\n const response = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));\n response.subscribe(res => {\n this.setState({ data: res });\n });\n }\n render() {\n return (\n <div>\n <h3>Using RxJS with ReactJS</h3>\n <ul>\n {this.state.data.map(el => (\n <li>\n {el.id}: {el.name}\n </li>\n ))}\n </ul>\n </div>\n );\n }\n}\nReactDOM.render(<App />, document.getElementById(\"root\"));" }, { "code": null, "e": 3124, "s": 2955, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\" />\n <title>ReactJS Demo</title>\n <head>\n <body>\n <div id = \"root\"></div>\n </body>\n</html>" }, { "code": null, "e": 3232, "s": 3124, "text": "We have used ajax from RxJS that will load data from this Url − https://jsonplaceholder.typicode.com/users." }, { "code": null, "e": 3282, "s": 3232, "text": "When you compile, the display is as shown below −" }, { "code": null, "e": 3315, "s": 3282, "text": "\n 51 Lectures \n 4 hours \n" }, { "code": null, "e": 3329, "s": 3315, "text": " Daniel Stern" }, { "code": null, "e": 3336, "s": 3329, "text": " Print" }, { "code": null, "e": 3347, "s": 3336, "text": " Add Notes" } ]
How to plot contourf and log color scale in Matplotlib?
To plot contourf and log scale in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Initialize a variable,N, for number of sample data. Create x, y, X, Y, Z1, Z2 and z data points using numpy. Create a figure and a set of subplots. Plot contours using contourf() method. Create a colorbar for a scalar mappable instance. To display the figure, use show() method. import matplotlib.pyplot as plt import numpy as np from numpy import ma from matplotlib import ticker, cm plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True N = 100 x = np.linspace(-3.0, 3.0, N) y = np.linspace(-2.0, 2.0, N) X, Y = np.meshgrid(x, y) Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) z = Z1 + 50 * Z2 z[:5, :5] = -1 z = ma.masked_where(z <= 0, z) fig, ax = plt.subplots() cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r) cbar = fig.colorbar(cs) plt.show()
[ { "code": null, "e": 1142, "s": 1062, "text": "To plot contourf and log scale in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1218, "s": 1142, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1270, "s": 1218, "text": "Initialize a variable,N, for number of sample data." }, { "code": null, "e": 1327, "s": 1270, "text": "Create x, y, X, Y, Z1, Z2 and z data points using numpy." }, { "code": null, "e": 1366, "s": 1327, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1405, "s": 1366, "text": "Plot contours using contourf() method." }, { "code": null, "e": 1455, "s": 1405, "text": "Create a colorbar for a scalar mappable instance." }, { "code": null, "e": 1497, "s": 1455, "text": "To display the figure, use show() method." }, { "code": null, "e": 2050, "s": 1497, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import ma\nfrom matplotlib import ticker, cm\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nN = 100\nx = np.linspace(-3.0, 3.0, N)\ny = np.linspace(-2.0, 2.0, N)\n\nX, Y = np.meshgrid(x, y)\n\nZ1 = np.exp(-X**2 - Y**2)\nZ2 = np.exp(-(X * 10)**2 - (Y * 10)**2)\n\nz = Z1 + 50 * Z2\nz[:5, :5] = -1\nz = ma.masked_where(z <= 0, z)\nfig, ax = plt.subplots()\n\ncs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)\ncbar = fig.colorbar(cs)\n\nplt.show()" } ]
Implementing Vignere Cipher
In this chapter, let us understand how to implement Vignere cipher. Consider the text This is basic implementation of Vignere Cipher is to be encoded and the key used is PIZZA. You can use the following code to implement a Vignere cipher in Python − import pyperclip LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): myMessage = "This is basic implementation of Vignere Cipher" myKey = 'PIZZA' myMode = 'encrypt' if myMode == 'encrypt': translated = encryptMessage(myKey, myMessage) elif myMode == 'decrypt': translated = decryptMessage(myKey, myMessage) print('%sed message:' % (myMode.title())) print(translated) print() def encryptMessage(key, message): return translateMessage(key, message, 'encrypt') def decryptMessage(key, message): return translateMessage(key, message, 'decrypt') def translateMessage(key, message, mode): translated = [] # stores the encrypted/decrypted message string keyIndex = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == 'encrypt': num += LETTERS.find(key[keyIndex]) elif mode == 'decrypt': num -= LETTERS.find(key[keyIndex]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) keyIndex += 1 if keyIndex == len(key): keyIndex = 0 else: translated.append(symbol) return ''.join(translated) if __name__ == '__main__': main() You can observe the following output when you implement the code given above − The possible combinations of hacking the Vignere cipher is next to impossible. Hence, it is considered as a secure encryption mode. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2469, "s": 2292, "text": "In this chapter, let us understand how to implement Vignere cipher. Consider the text This is basic implementation of Vignere Cipher is to be encoded and the key used is PIZZA." }, { "code": null, "e": 2542, "s": 2469, "text": "You can use the following code to implement a Vignere cipher in Python −" }, { "code": null, "e": 3968, "s": 2542, "text": "import pyperclip\n\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\ndef main():\n myMessage = \"This is basic implementation of Vignere Cipher\"\n myKey = 'PIZZA'\n myMode = 'encrypt'\n \n if myMode == 'encrypt':\n translated = encryptMessage(myKey, myMessage)\n elif myMode == 'decrypt':\n translated = decryptMessage(myKey, myMessage)\n \n print('%sed message:' % (myMode.title()))\n print(translated)\n print()\ndef encryptMessage(key, message):\n return translateMessage(key, message, 'encrypt')\ndef decryptMessage(key, message):\n return translateMessage(key, message, 'decrypt')\ndef translateMessage(key, message, mode):\n translated = [] # stores the encrypted/decrypted message string\n keyIndex = 0\n key = key.upper()\n \n for symbol in message:\n num = LETTERS.find(symbol.upper())\n if num != -1:\n if mode == 'encrypt':\n num += LETTERS.find(key[keyIndex])\n\t\t\t\telif mode == 'decrypt':\n num -= LETTERS.find(key[keyIndex])\n num %= len(LETTERS)\n \n if symbol.isupper():\n translated.append(LETTERS[num])\n elif symbol.islower():\n translated.append(LETTERS[num].lower())\n keyIndex += 1\n \n if keyIndex == len(key):\n keyIndex = 0\n else:\n translated.append(symbol)\n return ''.join(translated)\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 4047, "s": 3968, "text": "You can observe the following output when you implement the code given above −" }, { "code": null, "e": 4179, "s": 4047, "text": "The possible combinations of hacking the Vignere cipher is next to impossible. Hence, it is considered as a secure encryption mode." }, { "code": null, "e": 4212, "s": 4179, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4228, "s": 4212, "text": " Total Seminars" }, { "code": null, "e": 4261, "s": 4228, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4284, "s": 4261, "text": " Stone River ELearning" }, { "code": null, "e": 4291, "s": 4284, "text": " Print" }, { "code": null, "e": 4302, "s": 4291, "text": " Add Notes" } ]
Feature Selection With BorutaPy. This post will serve as a tutorial on... | by Jason Wong | Towards Data Science
This post will serve as a tutorial on how to implement BorutaPy when performing feature selection for a predictive classification model. I will go through some strengths as well as a few weaknesses when choosing to go with BorutaPy. I will be using the Tanzania well classification dataset to try and build a classification model to predict if a well is functional, functional but in need of repair, or not functional. Feature selection is one of the most important steps in machine learning. When inputting features into a model, the goal is to feed the model with features that are relevant for predicting a class. Including irrelevant features poses the problem of unnecessary noise in the data, resulting in lower model accuracy. Generally, we use statistical-based feature selection methods such as ANOVA or the Chi-squared test, evaluating the relationship between each predictor variable with the target variable. “Boruta is an all relevant feature selection method, while most other are minimal optimal; this means it tries to find all features carrying information usable for prediction, rather than finding a possibly compact subset of features on which some classifier has a minimal error.” -Miron B. Kursa With boruta, the features are curating down to the ‘all relevant’ stopping point and not the ‘minimal optimal’ stopping point. An all relevant variable being not redundant when used for prediction. Boruta is based on two ideas, shadow features and binomial distribution. When using boruta, the features are not evaluated with themselves but with a randomized version of them. For the binomial distribution idea, boruta takes a feature that we aren’t aware of being useful or not and either refuses or accepts the feature based on three areas defined by selecting the tails of the distribution, 0.5 percent for an example. Area of refusal: area where features are dropped as they are considered noise. Area of irresolution: area where boruta is indecisive about the features area of acceptance: area where the features are considered predictive For an example, I will build a ternary classification model to be used with the Tanzanian Water Well Data. This classifier will predict the status of the water well, the dataset can be retrieved here. I will start by going through how I processed the data for the model. To install BorutaPy run the following code in your notebook or terminal. The dependencies for Boruta are numpy, scipy, and scikit-learn. ###Installing BorutaPypip install BorutaPy###Importing the libraries for data processingimport pandas as pdimport numpy as np###Reading in the datatrain_data = pd.read_csv(‘../data/train_data.csv’)train_target = pd.read_csv(‘../data/train_targets.csv’)test = pd.read_csv(‘../data/test_set_values.csv’)###Adding training label to training dataframetrain = train_data.merge(train_target, on='id', how='inner')###‘status group' needs to be converted to numerical values for the ###classification model and not ‘functional’, ‘non-functional’, and ###‘functional in need of repair’.status_group_numeric = {'functional': 2, 'functional needs repair': 1, 'non functional': 0}train['status'] = train.status_group.replace(status_group_numeric) Checking for any missing values in the dataset train.isna().sum() Around 69 percent of the values in the permit field are true and 31 percent are false. I also chose to fill in the missing values with the same ratio. I also need to convert the values to be numerical. train['permit'].fillna(False, limit=947, inplace=True)train['permit'].fillna(True, inplace=True)###Function to take values in permit field and change them to ###numerical valuesdef permit(row): if row['permit'] == True: return 1 else: return 0train['permit'] = train.apply(lambda x: permit(x), axis=1) The public meeting field holds 91 percent True and 9 percent False. I chose to fill the missing values with the same ratio. I also need to change the values to be numerical. train['public_meeting'].fillna(False, limit=300, inplace=True)train['public_meeting'].fillna(True, inplace=True)###Function to take values in public field and convert them to ###numerical valuesdef public(row): if row['public_meeting'] == True: return 1 else: return 0train['public_meeting'] = train.apply(lambda x: public(x), axis=1) The funder column shows who funded the well. There are 1,897 different outcomes but it looks like only the top 7 fields have values that occur more over a thousand times. I’m going to divide this column into 7 different categories with these, the rest of the fields will be categorized as ‘other’. def categorize_funder(train): '''This function will go through every row in the dataframe column funder and if the value is any of the top 7 fields, will return those values. If the value does not equal any of these top 7 fields, it will return other.''' if train['funder'] == 'Government Of Tanzania': return 'govt' elif train['funder'] == 'Danida': return 'danida' elif train['funder'] == 'Hesawa': return 'hesawa' elif train['funder'] == 'Rwssp': return 'rwssp' elif train['funder'] == 'World Bank': return 'world_bank' elif train['funder'] == 'Kkkt': return 'kkkt' elif train['funder'] == 'World Vision': return 'world_vision' else: return 'other'train['funder'] = train.apply(lambda x: categorize_funder(x), axis=1) Binning the installer field into 7 categories def categorize_installer(train): '''This function will go through every row in the installer column and if the value is equal to any of the top 7, will return those values. If not, will return other.''' if train['installer'] == 'DWE': return 'dwe' elif train['installer'] == 'Government': return 'govt' elif train['installer'] == 'RWE': return 'rwe' elif train['installer'] == 'Commu': return 'commu' elif train['installer'] == 'DANIDA': return 'danida' elif train['installer'] == 'KKKT': return 'kkkt' elif train['installer'] == 'Hesawa': return 'hesawa' else: return 'other'train['installer'] = train.apply(lambda x: categorize_installer(x), axis=1) Binning the scheme management field into 7 categories def categorize_scheme(row): '''This function will go through each row in the scheme management column and if the value is equal to any of the top 7, will return those values. If not, will categorize the value as other.''' if row['scheme_management'] == 'VWC': return 'vwc' elif row['scheme_management'] == 'WUG': return 'wug' elif row['scheme_management'] == 'Water authority': return 'water_authority' elif row['scheme_management'] == 'WUA': return 'wua' elif row['scheme_management'] == 'Water Board': return 'water_board' elif row['scheme_management'] == 'Parastatal': return 'parastatal' elif row['scheme_management'] == 'Private operator': return 'private_operator' else: return 'other'train['scheme_management'] = train.apply(lambda x: categorize_scheme(x), axis=1) It looks like the construction year field will be pretty hard for our model to categorize since we have 55 different construction years in the dataset. I am going to try binning these years into decades. def categorize_contruction(row): if row['construction_year'] < 1970: return '1960s' elif row['construction_year'] < 1980: return '1970s' elif row['construction_year'] < 1990: return '1980s' elif row['construction_year'] < 2000: return '1990s' elif row['construction_year'] < 2010: return '2000s' elif row['construction_year'] < 2020: return '2010s'train['construction_year'] = train.apply(lambda x: categorize_contruction(x), axis=1) I chose to drop the fields that had values similar to another and the fields holding values that I could not find enough information relevant for the predictive model. The dropped features could hold important information, I’d recommend taking a closer look into the data. I’m going to move forward without them for the purpose of this example. - train = train.drop(columns=['subvillage'], axis=1)- train = train.drop(columns=['scheme_name'], axis=1)- train = train.drop(columns=['wpt_name'], axis=1)- train = train.drop(columns=['region'], axis=1)- train = train.drop(columns=['extraction_type', 'extraction_type_group'], axis=1)- train = train.drop(columns=['management_group'], axis=1)- train = train.drop(columns=['payment_type'], axis=1)- train = train.drop(columns=['water_quality'], axis=1)- train = train.drop(columns=['quantity_group'], axis=1)- train = train.drop(columns=['source_type'], axis=1)- train = train.drop(columns=['waterpoint_type_group'], axis=1) pivot_train = pd.pivot_table(train, index=['status_group'], values='status', aggfunc='count')pivot_train X = train.drop(columns=['id', 'status_group', 'status', 'date_recorded'], axis=1)y = train.statusX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) I encoded the categorical features with one Sklearn’s hot encoder and scaled the continuous features Sklearn’s standard scaler. ###Instantiating One Hot Encoderohe = OneHotEncoder()###Defining features to encodeohe_features = ['funder', 'installer', 'basin', 'region_code', 'district_code', 'lga', 'public_meeting', 'scheme_management', 'permit', 'construction_year', 'extraction_type_class', 'management', 'payment', 'quality_group', 'quantity', 'source', 'waterpoint_type']###Defining continuous numerical featurescont_features = ['amount_tsh', 'gps_height', 'longitude', 'latitude', 'population'###Creating series for categorical test and trainX_train_cat = X_train[ohe_features]X_test_cat = X_test[ohe_features]###Fitting encoder to training categorical features and transforming ###test and trainX_train_ohe = ohe.fit_transform(X_train_cat)X_test_ohe = ohe.transform(X_test_cat)###Converting series to dataframescolumns = ohe.get_feature_names(input_features=X_train_cat.columns)X_train_processed = pd.DataFrame(X_train_ohe.todense(), columns=columns)X_test_processed = pd.DataFrame(X_test_ohe.todense(), columns=columns)###Instantiating Standard Scalerss = StandardScaler()###Converting continuous feature values to floatsX_train_cont = X_train[cont_features].astype(float)X_test_cont = X_test[cont_features].astype(float)###Fitting scaler to training continuous features and transforming ###train and testX_train_scaled = ss.fit_transform(X_train_cont)X_test_scaled = ss.transform(X_test_cont)###Concatenating scaled and encoded dataframesX_train_a2 = pd.concat([pd.DataFrame(X_train_scaled), X_train_processed], axis=1)X_test_a2 = pd.concat([pd.DataFrame(X_test_scaled), X_test_processed], axis=1) ###Classification Algorithmfrom sklearn.ensemble import RandomForestClassifier###Model evaluationfrom sklearn.model_selection import cross_val_scorefrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score###Feature Selectionfrom boruta import BorutaPy For this example, I chose to use random forest classifier, an ensemble tree-based learning algorithm. It is a set of decision trees created with a randomly selected subset of the training data. The random forest classifier then aggregates the votes from different decision trees to choose the final class of the test object. This first run with the random forest classifier will include all of the features then I will run BorutaPy. ###Instantiating Random Forest Classifierrf = RandomForestClassifier(n_estimators=500, random_state=42)###Fitting Random Forest Classifier to training datarf.fit(X_train_a2, y_train)###Print accuracy and recall scores for both test and train###Average is set to micro for recall score since this is a ###multi-class classification model. Micro-average aggregates the ###contributions of all classes to compute the average metric. Micro ###is preferred for data with class imbalance.print('Test Accuracy:')print(accuracy_score(y_test, rf.predict(X_test_a2)))print('Test Recall:')print(recall_score(y_test, rf.predict(X_test_a2), average='micro'))print('Train Accuracy:')print(accuracy_score(y_train, rf.predict(X_train_a2)))print('Train Recall:')print(recall_score(y_train, rf.predict(X_train_a2), average='micro'))####Output:Test Accuracy:0.80006734006734Test Recall:0.6729820394303477Train Accuracy:0.9955555555555555Train Recall:0.9902567898799216 This resulted with a test score (mean accuracy) of 80% and a training score of 96%, now I will run the features through BorutaPy and see which ones are selected as relevant. Begins by providing randomness to the features by creating duplicate features and shuffling the values in each column to remove their correlations with the response. (Shadow Features) Trains a random forest classifier on the dataset and calculates the relevance/importance by gathering the Z-scores. Finds the maximum Z-score among shadow attributes and assigns a hit to every attribute with a Z-score higher than the maximum Z-score of its shadow feature. (accuracy loss divided by the standard deviation of accuracy loss) Takes each attribute that has not yet been determined important and perform a two-sided test of quality with the maximum Z-score among shadow attributes. Tags the attributes with an importance level lower than MZSA as ‘unimportant’. Tags the attributes with an importance level higher than MZSA as ‘important’. Removes all shadow attributes Repeats this process until the importance is computed for all attributes or the algorithm reaches the set number of iterations ###define X and y for boruta, algorithm takes numpy arrays as inputs ###and not dataframe (why you see .values)X_boruta = train_all.drop(columns=['status'], axis=1).valuesy_boruta = train_all.status.values###define random forest classifier, set n_jobs parameter to -1 to ###utilize all processors and set n_estimators parameter to 500, ###number of trees in the forest.rf = RandomForestClassifier(n_jobs=-1, n_estimators=500, oob_score=True, max_depth=6)###Define borutapy with rf as estimator and verbose parameter set to ###2 to output which features have been selected alreadyfeat_selector = BorutaPy(rf, n_estimators='auto', verbose=2, random_state=42)###fit boruta selector to X and y borutafeat_selector.fit(X_boruta, y_boruta)Output:Iteration: 1 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 2 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 3 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 4 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 5 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 6 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 7 / 100Confirmed: 0Tentative: 277Rejected: 0Iteration: 8 / 100Confirmed: 110Tentative: 49Rejected: 118Iteration: 9 / 100Confirmed: 110Tentative: 49Rejected: 118Iteration: 10 / 100Confirmed: 110Tentative: 49Rejected: 118...Iteration: 90 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 91 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 92 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 93 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 94 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 95 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 96 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 97 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 98 / 100Confirmed: 122Tentative: 11Rejected: 144Iteration: 99 / 100Confirmed: 122Tentative: 11Rejected: 144BorutaPy finished running.Iteration: 100 / 100Confirmed: 122Tentative: 2Rejected: 144 Checking accepted features ###Print accepted features as well as features that boruta did not ###deem unimportant or important (area of irresolution)accept = X.columns[feat_selector.support_].to_list()irresolution = X.columns[feat_selector.support_weak_].to_list()###Call transform on boruta to update X_boruta to selected featuresX_filtered = feat_selector.transform(X_boruta)print('Accepted features:')print('----------------------------')print(list(accept))print('----------------------------')print(list(irresolution)) By using these selected features and tuning the hyperparameter max_depth to 6, we get improved scores. ###Creating new dataframe from original X dataframe with only the ###selected features from BorutaPynew_x = train_all[accept]X2_boruta = new_x.drop(['status'], axis=1)y2_boruta = new_x.status###Train test split on updated XX_t, X_val, y_t, y_val = train_test_split(new_x, y, random_state=42)###Instantiating Random Forest Classifierrf2 = RandomForestClassifier(n_jobs=-1, n_estimators=500, oob_score=True, max_depth=6, random_state=42)###Fitting Random Forest Classifier to train and testrf2.fit(X_t, y_t)###Predicting on test datay_pred = rf2.predict(X_val)###Test Scorerf2.score(X_val, y_val)###Training Scorerf2.score(X_t, y_t)###Print accuracy and recall scores for both test and train ###Average is set to micro for recall score since this is a ###multi-class classification model. Micro-average aggregates the ###contributions of all classes to compute the average metric. Micro ###is preferred for data with class imbalance.print('Test Accuracy:')print(accuracy_score(y_test, rf.predict(X_test_a2)))print('Test Recall:')print(recall_score(y_test, rf.predict(X_test_a2), average='micro'))print('Train Accuracy:')print(accuracy_score(y_train, rf.predict(X_train_a2)))print('Train Recall:')print(recall_score(y_train, rf.predict(X_train_a2), average='micro'))###Output:Test Accuracy:0.797068340067343Test Recall:0.769820394303477Train Accuracy:0.818649338720538Train Recall:0.810256789879921 This second run with only the selected features results in a testing score of 80 percent and a training score of 81 percent. Definitely an improvement from our first iteration with a testing score of 80 percent and a training score of 96 percent. We are minimizing the gap between the testing and training scores (model is becoming less overfit). Boruta is powerful feature selection algorithm which you can implement across most datasets. It can be super helpful in a time crunch as well as datasets containing a large amount of weakly correlated predictor variables. The main disadvantage is the computation time, while a lot of algorithms can be executed in seconds or milliseconds, boruta’s execution time is measured in hours. This can make it extremely difficult to adjust the parameters as each tune will require significant additional time. Boruta may not be the best option for the dataset you’re working with and I’d recommend testing other algorithms as well and comparing the results. References: Bhattacharyya, I. (2018, September 18). Feature Selection (Boruta /Light GBM/Chi Square)-Categorical Feature Selection. Retrieved from https://medium.com/@indreshbhattacharyya/feature-selection-categorical-feature-selection-boruta-light-gbm-chi-square-bf47e94e2558 Danielhomola. (2016, February 08). BorutaPy — an all relevant feature selection method. Retrieved from http://danielhomola.com/2015/05/08/borutapy-an-all-relevant-feature-selection-method/ Boruta. (n.d.). Retrieved from https://pypi.org/project/Boruta/
[ { "code": null, "e": 590, "s": 171, "text": "This post will serve as a tutorial on how to implement BorutaPy when performing feature selection for a predictive classification model. I will go through some strengths as well as a few weaknesses when choosing to go with BorutaPy. I will be using the Tanzania well classification dataset to try and build a classification model to predict if a well is functional, functional but in need of repair, or not functional." }, { "code": null, "e": 1092, "s": 590, "text": "Feature selection is one of the most important steps in machine learning. When inputting features into a model, the goal is to feed the model with features that are relevant for predicting a class. Including irrelevant features poses the problem of unnecessary noise in the data, resulting in lower model accuracy. Generally, we use statistical-based feature selection methods such as ANOVA or the Chi-squared test, evaluating the relationship between each predictor variable with the target variable." }, { "code": null, "e": 1389, "s": 1092, "text": "“Boruta is an all relevant feature selection method, while most other are minimal optimal; this means it tries to find all features carrying information usable for prediction, rather than finding a possibly compact subset of features on which some classifier has a minimal error.” -Miron B. Kursa" }, { "code": null, "e": 2011, "s": 1389, "text": "With boruta, the features are curating down to the ‘all relevant’ stopping point and not the ‘minimal optimal’ stopping point. An all relevant variable being not redundant when used for prediction. Boruta is based on two ideas, shadow features and binomial distribution. When using boruta, the features are not evaluated with themselves but with a randomized version of them. For the binomial distribution idea, boruta takes a feature that we aren’t aware of being useful or not and either refuses or accepts the feature based on three areas defined by selecting the tails of the distribution, 0.5 percent for an example." }, { "code": null, "e": 2090, "s": 2011, "text": "Area of refusal: area where features are dropped as they are considered noise." }, { "code": null, "e": 2163, "s": 2090, "text": "Area of irresolution: area where boruta is indecisive about the features" }, { "code": null, "e": 2233, "s": 2163, "text": "area of acceptance: area where the features are considered predictive" }, { "code": null, "e": 2504, "s": 2233, "text": "For an example, I will build a ternary classification model to be used with the Tanzanian Water Well Data. This classifier will predict the status of the water well, the dataset can be retrieved here. I will start by going through how I processed the data for the model." }, { "code": null, "e": 2641, "s": 2504, "text": "To install BorutaPy run the following code in your notebook or terminal. The dependencies for Boruta are numpy, scipy, and scikit-learn." }, { "code": null, "e": 3422, "s": 2641, "text": "###Installing BorutaPypip install BorutaPy###Importing the libraries for data processingimport pandas as pdimport numpy as np###Reading in the datatrain_data = pd.read_csv(‘../data/train_data.csv’)train_target = pd.read_csv(‘../data/train_targets.csv’)test = pd.read_csv(‘../data/test_set_values.csv’)###Adding training label to training dataframetrain = train_data.merge(train_target, on='id', how='inner')###‘status group' needs to be converted to numerical values for the ###classification model and not ‘functional’, ‘non-functional’, and ###‘functional in need of repair’.status_group_numeric = {'functional': 2, 'functional needs repair': 1, 'non functional': 0}train['status'] = train.status_group.replace(status_group_numeric)" }, { "code": null, "e": 3469, "s": 3422, "text": "Checking for any missing values in the dataset" }, { "code": null, "e": 3488, "s": 3469, "text": "train.isna().sum()" }, { "code": null, "e": 3690, "s": 3488, "text": "Around 69 percent of the values in the permit field are true and 31 percent are false. I also chose to fill in the missing values with the same ratio. I also need to convert the values to be numerical." }, { "code": null, "e": 4012, "s": 3690, "text": "train['permit'].fillna(False, limit=947, inplace=True)train['permit'].fillna(True, inplace=True)###Function to take values in permit field and change them to ###numerical valuesdef permit(row): if row['permit'] == True: return 1 else: return 0train['permit'] = train.apply(lambda x: permit(x), axis=1)" }, { "code": null, "e": 4186, "s": 4012, "text": "The public meeting field holds 91 percent True and 9 percent False. I chose to fill the missing values with the same ratio. I also need to change the values to be numerical." }, { "code": null, "e": 4541, "s": 4186, "text": "train['public_meeting'].fillna(False, limit=300, inplace=True)train['public_meeting'].fillna(True, inplace=True)###Function to take values in public field and convert them to ###numerical valuesdef public(row): if row['public_meeting'] == True: return 1 else: return 0train['public_meeting'] = train.apply(lambda x: public(x), axis=1)" }, { "code": null, "e": 4839, "s": 4541, "text": "The funder column shows who funded the well. There are 1,897 different outcomes but it looks like only the top 7 fields have values that occur more over a thousand times. I’m going to divide this column into 7 different categories with these, the rest of the fields will be categorized as ‘other’." }, { "code": null, "e": 5655, "s": 4839, "text": "def categorize_funder(train): '''This function will go through every row in the dataframe column funder and if the value is any of the top 7 fields, will return those values. If the value does not equal any of these top 7 fields, it will return other.''' if train['funder'] == 'Government Of Tanzania': return 'govt' elif train['funder'] == 'Danida': return 'danida' elif train['funder'] == 'Hesawa': return 'hesawa' elif train['funder'] == 'Rwssp': return 'rwssp' elif train['funder'] == 'World Bank': return 'world_bank' elif train['funder'] == 'Kkkt': return 'kkkt' elif train['funder'] == 'World Vision': return 'world_vision' else: return 'other'train['funder'] = train.apply(lambda x: categorize_funder(x), axis=1)" }, { "code": null, "e": 5701, "s": 5655, "text": "Binning the installer field into 7 categories" }, { "code": null, "e": 6448, "s": 5701, "text": "def categorize_installer(train): '''This function will go through every row in the installer column and if the value is equal to any of the top 7, will return those values. If not, will return other.''' if train['installer'] == 'DWE': return 'dwe' elif train['installer'] == 'Government': return 'govt' elif train['installer'] == 'RWE': return 'rwe' elif train['installer'] == 'Commu': return 'commu' elif train['installer'] == 'DANIDA': return 'danida' elif train['installer'] == 'KKKT': return 'kkkt' elif train['installer'] == 'Hesawa': return 'hesawa' else: return 'other'train['installer'] = train.apply(lambda x: categorize_installer(x), axis=1)" }, { "code": null, "e": 6502, "s": 6448, "text": "Binning the scheme management field into 7 categories" }, { "code": null, "e": 7370, "s": 6502, "text": "def categorize_scheme(row): '''This function will go through each row in the scheme management column and if the value is equal to any of the top 7, will return those values. If not, will categorize the value as other.''' if row['scheme_management'] == 'VWC': return 'vwc' elif row['scheme_management'] == 'WUG': return 'wug' elif row['scheme_management'] == 'Water authority': return 'water_authority' elif row['scheme_management'] == 'WUA': return 'wua' elif row['scheme_management'] == 'Water Board': return 'water_board' elif row['scheme_management'] == 'Parastatal': return 'parastatal' elif row['scheme_management'] == 'Private operator': return 'private_operator' else: return 'other'train['scheme_management'] = train.apply(lambda x: categorize_scheme(x), axis=1)" }, { "code": null, "e": 7574, "s": 7370, "text": "It looks like the construction year field will be pretty hard for our model to categorize since we have 55 different construction years in the dataset. I am going to try binning these years into decades." }, { "code": null, "e": 8068, "s": 7574, "text": "def categorize_contruction(row): if row['construction_year'] < 1970: return '1960s' elif row['construction_year'] < 1980: return '1970s' elif row['construction_year'] < 1990: return '1980s' elif row['construction_year'] < 2000: return '1990s' elif row['construction_year'] < 2010: return '2000s' elif row['construction_year'] < 2020: return '2010s'train['construction_year'] = train.apply(lambda x: categorize_contruction(x), axis=1)" }, { "code": null, "e": 8413, "s": 8068, "text": "I chose to drop the fields that had values similar to another and the fields holding values that I could not find enough information relevant for the predictive model. The dropped features could hold important information, I’d recommend taking a closer look into the data. I’m going to move forward without them for the purpose of this example." }, { "code": null, "e": 9055, "s": 8413, "text": "- train = train.drop(columns=['subvillage'], axis=1)- train = train.drop(columns=['scheme_name'], axis=1)- train = train.drop(columns=['wpt_name'], axis=1)- train = train.drop(columns=['region'], axis=1)- train = train.drop(columns=['extraction_type', 'extraction_type_group'], axis=1)- train = train.drop(columns=['management_group'], axis=1)- train = train.drop(columns=['payment_type'], axis=1)- train = train.drop(columns=['water_quality'], axis=1)- train = train.drop(columns=['quantity_group'], axis=1)- train = train.drop(columns=['source_type'], axis=1)- train = train.drop(columns=['waterpoint_type_group'], axis=1)" }, { "code": null, "e": 9215, "s": 9055, "text": "pivot_train = pd.pivot_table(train, index=['status_group'], values='status', aggfunc='count')pivot_train" }, { "code": null, "e": 9387, "s": 9215, "text": "X = train.drop(columns=['id', 'status_group', 'status', 'date_recorded'], axis=1)y = train.statusX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)" }, { "code": null, "e": 9515, "s": 9387, "text": "I encoded the categorical features with one Sklearn’s hot encoder and scaled the continuous features Sklearn’s standard scaler." }, { "code": null, "e": 11188, "s": 9515, "text": "###Instantiating One Hot Encoderohe = OneHotEncoder()###Defining features to encodeohe_features = ['funder', 'installer', 'basin', 'region_code', 'district_code', 'lga', 'public_meeting', 'scheme_management', 'permit', 'construction_year', 'extraction_type_class', 'management', 'payment', 'quality_group', 'quantity', 'source', 'waterpoint_type']###Defining continuous numerical featurescont_features = ['amount_tsh', 'gps_height', 'longitude', 'latitude', 'population'###Creating series for categorical test and trainX_train_cat = X_train[ohe_features]X_test_cat = X_test[ohe_features]###Fitting encoder to training categorical features and transforming ###test and trainX_train_ohe = ohe.fit_transform(X_train_cat)X_test_ohe = ohe.transform(X_test_cat)###Converting series to dataframescolumns = ohe.get_feature_names(input_features=X_train_cat.columns)X_train_processed = pd.DataFrame(X_train_ohe.todense(), columns=columns)X_test_processed = pd.DataFrame(X_test_ohe.todense(), columns=columns)###Instantiating Standard Scalerss = StandardScaler()###Converting continuous feature values to floatsX_train_cont = X_train[cont_features].astype(float)X_test_cont = X_test[cont_features].astype(float)###Fitting scaler to training continuous features and transforming ###train and testX_train_scaled = ss.fit_transform(X_train_cont)X_test_scaled = ss.transform(X_test_cont)###Concatenating scaled and encoded dataframesX_train_a2 = pd.concat([pd.DataFrame(X_train_scaled), X_train_processed], axis=1)X_test_a2 = pd.concat([pd.DataFrame(X_test_scaled), X_test_processed], axis=1)" }, { "code": null, "e": 11482, "s": 11188, "text": "###Classification Algorithmfrom sklearn.ensemble import RandomForestClassifier###Model evaluationfrom sklearn.model_selection import cross_val_scorefrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score###Feature Selectionfrom boruta import BorutaPy" }, { "code": null, "e": 11915, "s": 11482, "text": "For this example, I chose to use random forest classifier, an ensemble tree-based learning algorithm. It is a set of decision trees created with a randomly selected subset of the training data. The random forest classifier then aggregates the votes from different decision trees to choose the final class of the test object. This first run with the random forest classifier will include all of the features then I will run BorutaPy." }, { "code": null, "e": 12866, "s": 11915, "text": "###Instantiating Random Forest Classifierrf = RandomForestClassifier(n_estimators=500, random_state=42)###Fitting Random Forest Classifier to training datarf.fit(X_train_a2, y_train)###Print accuracy and recall scores for both test and train###Average is set to micro for recall score since this is a ###multi-class classification model. Micro-average aggregates the ###contributions of all classes to compute the average metric. Micro ###is preferred for data with class imbalance.print('Test Accuracy:')print(accuracy_score(y_test, rf.predict(X_test_a2)))print('Test Recall:')print(recall_score(y_test, rf.predict(X_test_a2), average='micro'))print('Train Accuracy:')print(accuracy_score(y_train, rf.predict(X_train_a2)))print('Train Recall:')print(recall_score(y_train, rf.predict(X_train_a2), average='micro'))####Output:Test Accuracy:0.80006734006734Test Recall:0.6729820394303477Train Accuracy:0.9955555555555555Train Recall:0.9902567898799216" }, { "code": null, "e": 13040, "s": 12866, "text": "This resulted with a test score (mean accuracy) of 80% and a training score of 96%, now I will run the features through BorutaPy and see which ones are selected as relevant." }, { "code": null, "e": 13224, "s": 13040, "text": "Begins by providing randomness to the features by creating duplicate features and shuffling the values in each column to remove their correlations with the response. (Shadow Features)" }, { "code": null, "e": 13340, "s": 13224, "text": "Trains a random forest classifier on the dataset and calculates the relevance/importance by gathering the Z-scores." }, { "code": null, "e": 13564, "s": 13340, "text": "Finds the maximum Z-score among shadow attributes and assigns a hit to every attribute with a Z-score higher than the maximum Z-score of its shadow feature. (accuracy loss divided by the standard deviation of accuracy loss)" }, { "code": null, "e": 13718, "s": 13564, "text": "Takes each attribute that has not yet been determined important and perform a two-sided test of quality with the maximum Z-score among shadow attributes." }, { "code": null, "e": 13797, "s": 13718, "text": "Tags the attributes with an importance level lower than MZSA as ‘unimportant’." }, { "code": null, "e": 13875, "s": 13797, "text": "Tags the attributes with an importance level higher than MZSA as ‘important’." }, { "code": null, "e": 13905, "s": 13875, "text": "Removes all shadow attributes" }, { "code": null, "e": 14032, "s": 13905, "text": "Repeats this process until the importance is computed for all attributes or the algorithm reaches the set number of iterations" }, { "code": null, "e": 16095, "s": 14032, "text": "###define X and y for boruta, algorithm takes numpy arrays as inputs ###and not dataframe (why you see .values)X_boruta = train_all.drop(columns=['status'], axis=1).valuesy_boruta = train_all.status.values###define random forest classifier, set n_jobs parameter to -1 to ###utilize all processors and set n_estimators parameter to 500, ###number of trees in the forest.rf = RandomForestClassifier(n_jobs=-1, n_estimators=500, oob_score=True, max_depth=6)###Define borutapy with rf as estimator and verbose parameter set to ###2 to output which features have been selected alreadyfeat_selector = BorutaPy(rf, n_estimators='auto', verbose=2, random_state=42)###fit boruta selector to X and y borutafeat_selector.fit(X_boruta, y_boruta)Output:Iteration: \t1 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t2 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t3 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t4 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t5 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t6 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t7 / 100Confirmed: \t0Tentative: \t277Rejected: \t0Iteration: \t8 / 100Confirmed: \t110Tentative: \t49Rejected: \t118Iteration: \t9 / 100Confirmed: \t110Tentative: \t49Rejected: \t118Iteration: \t10 / 100Confirmed: \t110Tentative: \t49Rejected: \t118...Iteration: \t90 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t91 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t92 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t93 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t94 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t95 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t96 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t97 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t98 / 100Confirmed: \t122Tentative: \t11Rejected: \t144Iteration: \t99 / 100Confirmed: \t122Tentative: \t11Rejected: \t144BorutaPy finished running.Iteration: \t100 / 100Confirmed: \t122Tentative: \t2Rejected: \t144" }, { "code": null, "e": 16122, "s": 16095, "text": "Checking accepted features" }, { "code": null, "e": 16618, "s": 16122, "text": "###Print accepted features as well as features that boruta did not ###deem unimportant or important (area of irresolution)accept = X.columns[feat_selector.support_].to_list()irresolution = X.columns[feat_selector.support_weak_].to_list()###Call transform on boruta to update X_boruta to selected featuresX_filtered = feat_selector.transform(X_boruta)print('Accepted features:')print('----------------------------')print(list(accept))print('----------------------------')print(list(irresolution))" }, { "code": null, "e": 16721, "s": 16618, "text": "By using these selected features and tuning the hyperparameter max_depth to 6, we get improved scores." }, { "code": null, "e": 18118, "s": 16721, "text": "###Creating new dataframe from original X dataframe with only the ###selected features from BorutaPynew_x = train_all[accept]X2_boruta = new_x.drop(['status'], axis=1)y2_boruta = new_x.status###Train test split on updated XX_t, X_val, y_t, y_val = train_test_split(new_x, y, random_state=42)###Instantiating Random Forest Classifierrf2 = RandomForestClassifier(n_jobs=-1, n_estimators=500, oob_score=True, max_depth=6, random_state=42)###Fitting Random Forest Classifier to train and testrf2.fit(X_t, y_t)###Predicting on test datay_pred = rf2.predict(X_val)###Test Scorerf2.score(X_val, y_val)###Training Scorerf2.score(X_t, y_t)###Print accuracy and recall scores for both test and train ###Average is set to micro for recall score since this is a ###multi-class classification model. Micro-average aggregates the ###contributions of all classes to compute the average metric. Micro ###is preferred for data with class imbalance.print('Test Accuracy:')print(accuracy_score(y_test, rf.predict(X_test_a2)))print('Test Recall:')print(recall_score(y_test, rf.predict(X_test_a2), average='micro'))print('Train Accuracy:')print(accuracy_score(y_train, rf.predict(X_train_a2)))print('Train Recall:')print(recall_score(y_train, rf.predict(X_train_a2), average='micro'))###Output:Test Accuracy:0.797068340067343Test Recall:0.769820394303477Train Accuracy:0.818649338720538Train Recall:0.810256789879921" }, { "code": null, "e": 18465, "s": 18118, "text": "This second run with only the selected features results in a testing score of 80 percent and a training score of 81 percent. Definitely an improvement from our first iteration with a testing score of 80 percent and a training score of 96 percent. We are minimizing the gap between the testing and training scores (model is becoming less overfit)." }, { "code": null, "e": 19115, "s": 18465, "text": "Boruta is powerful feature selection algorithm which you can implement across most datasets. It can be super helpful in a time crunch as well as datasets containing a large amount of weakly correlated predictor variables. The main disadvantage is the computation time, while a lot of algorithms can be executed in seconds or milliseconds, boruta’s execution time is measured in hours. This can make it extremely difficult to adjust the parameters as each tune will require significant additional time. Boruta may not be the best option for the dataset you’re working with and I’d recommend testing other algorithms as well and comparing the results." }, { "code": null, "e": 19127, "s": 19115, "text": "References:" }, { "code": null, "e": 19392, "s": 19127, "text": "Bhattacharyya, I. (2018, September 18). Feature Selection (Boruta /Light GBM/Chi Square)-Categorical Feature Selection. Retrieved from https://medium.com/@indreshbhattacharyya/feature-selection-categorical-feature-selection-boruta-light-gbm-chi-square-bf47e94e2558" }, { "code": null, "e": 19581, "s": 19392, "text": "Danielhomola. (2016, February 08). BorutaPy — an all relevant feature selection method. Retrieved from http://danielhomola.com/2015/05/08/borutapy-an-all-relevant-feature-selection-method/" } ]
Tryit Editor v3.7
Tryit: HTML dotted table borders
[]
Create high quality synthetic data in your cloud with Gretel.ai and Python | by Alexander Watson | Towards Data Science
Whether your concern is HIPAA for Healthcare, PCI for the financial industry, or GDPR or CCPA for protecting consumer data, being able to get started building without needing a data processing agreement (DPA) in place to work with SaaS services can significantly reduce the time it takes to start your project and start creating value. Today we will walk through an example using Gretel.ai in a local (your cloud, or on-premises) configuration to generate high quality synthetic data and models. To get started you need just three things. Dataset to synthesize in CSV or Pandas Dataframe formatGretel.ai API key (it’s free)Local computer / VM / cloud instance Dataset to synthesize in CSV or Pandas Dataframe format Gretel.ai API key (it’s free) Local computer / VM / cloud instance Recommended setup. We recommend the following hardware configuration: CPU: 8+ vCPU cores recommended for synthetic record generation. GPU: Nvidia Tesla P4 with CUDA 10.x support recommended for training. RAM: 8GB+. Operating system: Ubuntu 18.04 for GPU support, or Mac OS X (no GPU support with Macs). See TensorFlow’s excellent setup guide for GPU acceleration. While a GPU is not required, it is generally at least 10x faster training on GPU than CPU. Or run on CPU and grab a ☕. With an API key, you get free access to the Gretel public beta’s premium features which augment our open source library for synthetic data generation with improved field-to-field correlations, automated synthetic data record validation, and reporting for synthetic data quality. Log in or create a free account to Gretel.ai with a Github or Google email. Click on your profile icon at the top right, then API Key. Generate a new API token and copy to the clipboard. We recommend setting up a virtual Python environment for your runtime to keep your system tidy and clean, in this example we will use the Anaconda package manager as it has great support for Tensorflow, GPU acceleration, and thousands of data science packages. You can download and install Anaconda here https://www.anaconda.com/products/individual. conda install python=3.8conda create --name synthetics python=3.8 conda activate synthetics # activate your virtual environmentconda install jupyter # set up notebook environmentjupyter notebook # launch notebook in browser Install dependencies such as gretel-synthetics, Tensorflow, Pandas, and Gretel helpers (API key required) into your new virtual environment. Add the code samples below directly into your notebook, or download the complete synthetics notebook from Github. Load the source from CSV into a Pandas Dataframe, add or drop any columns, configure training parameters, and train the model. We recommend at least 5,000 rows of training data when possible. Use Gretel.ai’s reporting functionality to verify that the synthetic dataset contains the same correlations and insights as the original source data. # Preview the synthetic Dataframebundle.synthetic_df()# Generate a synthetic data reportbundle.generate_report()# Save the synthetic dataset to CSVbundle.synthetic_df().to_csv('synthetic-data.csv', index=False) Download your new synthetic dataset, and explore correlations and insights in the synthetic data report! Download our walkthrough notebook on Github, load the notebook in your local notebook server, connect your API key, and start creating synthetic data! colab.research.google.com At Gretel.ai we are super excited about the possibility of using synthetic data to augment training sets to create ML and AI models that generalize better against unknown data and with reduced algorithmic biases. We’d love to hear about your use cases- feel free to reach out to us for a more in-depth discussion in the comments, twitter, or [email protected]. Like gretel-synthetics? Give us a ⭐ on Github!
[ { "code": null, "e": 668, "s": 172, "text": "Whether your concern is HIPAA for Healthcare, PCI for the financial industry, or GDPR or CCPA for protecting consumer data, being able to get started building without needing a data processing agreement (DPA) in place to work with SaaS services can significantly reduce the time it takes to start your project and start creating value. Today we will walk through an example using Gretel.ai in a local (your cloud, or on-premises) configuration to generate high quality synthetic data and models." }, { "code": null, "e": 711, "s": 668, "text": "To get started you need just three things." }, { "code": null, "e": 832, "s": 711, "text": "Dataset to synthesize in CSV or Pandas Dataframe formatGretel.ai API key (it’s free)Local computer / VM / cloud instance" }, { "code": null, "e": 888, "s": 832, "text": "Dataset to synthesize in CSV or Pandas Dataframe format" }, { "code": null, "e": 918, "s": 888, "text": "Gretel.ai API key (it’s free)" }, { "code": null, "e": 955, "s": 918, "text": "Local computer / VM / cloud instance" }, { "code": null, "e": 1258, "s": 955, "text": "Recommended setup. We recommend the following hardware configuration: CPU: 8+ vCPU cores recommended for synthetic record generation. GPU: Nvidia Tesla P4 with CUDA 10.x support recommended for training. RAM: 8GB+. Operating system: Ubuntu 18.04 for GPU support, or Mac OS X (no GPU support with Macs)." }, { "code": null, "e": 1438, "s": 1258, "text": "See TensorFlow’s excellent setup guide for GPU acceleration. While a GPU is not required, it is generally at least 10x faster training on GPU than CPU. Or run on CPU and grab a ☕." }, { "code": null, "e": 1717, "s": 1438, "text": "With an API key, you get free access to the Gretel public beta’s premium features which augment our open source library for synthetic data generation with improved field-to-field correlations, automated synthetic data record validation, and reporting for synthetic data quality." }, { "code": null, "e": 1904, "s": 1717, "text": "Log in or create a free account to Gretel.ai with a Github or Google email. Click on your profile icon at the top right, then API Key. Generate a new API token and copy to the clipboard." }, { "code": null, "e": 2254, "s": 1904, "text": "We recommend setting up a virtual Python environment for your runtime to keep your system tidy and clean, in this example we will use the Anaconda package manager as it has great support for Tensorflow, GPU acceleration, and thousands of data science packages. You can download and install Anaconda here https://www.anaconda.com/products/individual." }, { "code": null, "e": 2478, "s": 2254, "text": "conda install python=3.8conda create --name synthetics python=3.8 conda activate synthetics # activate your virtual environmentconda install jupyter # set up notebook environmentjupyter notebook # launch notebook in browser" }, { "code": null, "e": 2733, "s": 2478, "text": "Install dependencies such as gretel-synthetics, Tensorflow, Pandas, and Gretel helpers (API key required) into your new virtual environment. Add the code samples below directly into your notebook, or download the complete synthetics notebook from Github." }, { "code": null, "e": 2925, "s": 2733, "text": "Load the source from CSV into a Pandas Dataframe, add or drop any columns, configure training parameters, and train the model. We recommend at least 5,000 rows of training data when possible." }, { "code": null, "e": 3075, "s": 2925, "text": "Use Gretel.ai’s reporting functionality to verify that the synthetic dataset contains the same correlations and insights as the original source data." }, { "code": null, "e": 3286, "s": 3075, "text": "# Preview the synthetic Dataframebundle.synthetic_df()# Generate a synthetic data reportbundle.generate_report()# Save the synthetic dataset to CSVbundle.synthetic_df().to_csv('synthetic-data.csv', index=False)" }, { "code": null, "e": 3391, "s": 3286, "text": "Download your new synthetic dataset, and explore correlations and insights in the synthetic data report!" }, { "code": null, "e": 3542, "s": 3391, "text": "Download our walkthrough notebook on Github, load the notebook in your local notebook server, connect your API key, and start creating synthetic data!" }, { "code": null, "e": 3568, "s": 3542, "text": "colab.research.google.com" } ]
C | Operators | Question 18 - GeeksforGeeks
10 Sep, 2020 In C, two integers can be swapped using minimum(A) 0 extra variable(B) 1 extra variable(C) 2 extra variable(D) 4 extra variableAnswer: (A)Explanation: We can swap two variables without any extra variable using bitwise XOR operator ‘^’. Let X and Y be two variables to be swapped. Following steps swap X and Y. X = X ^ Y; Y = X ^ Y; X = X ^ Y; See http://en.wikipedia.org/wiki/XOR_swap_algorithmQuiz of this Question C-Operators Operators C Quiz Operators Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C | Advanced Pointer | Question 1 C | File Handling | Question 2 C | Pointer Basics | Question 1 C | Operators | Question 1 C | Loops & Control Structure | Question 8 C | Advanced Pointer | Question 2 C Quiz - 101 | Question 2 C | Dynamic Memory Allocation | Question 7 C | Advanced Pointer | Question 4 C | Advanced Pointer | Question 9
[ { "code": null, "e": 23835, "s": 23807, "text": "\n10 Sep, 2020" }, { "code": null, "e": 24145, "s": 23835, "text": "In C, two integers can be swapped using minimum(A) 0 extra variable(B) 1 extra variable(C) 2 extra variable(D) 4 extra variableAnswer: (A)Explanation: We can swap two variables without any extra variable using bitwise XOR operator ‘^’. Let X and Y be two variables to be swapped. Following steps swap X and Y." }, { "code": null, "e": 24185, "s": 24145, "text": " X = X ^ Y;\n Y = X ^ Y;\n X = X ^ Y;\n" }, { "code": null, "e": 24258, "s": 24185, "text": "See http://en.wikipedia.org/wiki/XOR_swap_algorithmQuiz of this Question" }, { "code": null, "e": 24270, "s": 24258, "text": "C-Operators" }, { "code": null, "e": 24280, "s": 24270, "text": "Operators" }, { "code": null, "e": 24287, "s": 24280, "text": "C Quiz" }, { "code": null, "e": 24297, "s": 24287, "text": "Operators" }, { "code": null, "e": 24395, "s": 24297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24404, "s": 24395, "text": "Comments" }, { "code": null, "e": 24417, "s": 24404, "text": "Old Comments" }, { "code": null, "e": 24451, "s": 24417, "text": "C | Advanced Pointer | Question 1" }, { "code": null, "e": 24482, "s": 24451, "text": "C | File Handling | Question 2" }, { "code": null, "e": 24514, "s": 24482, "text": "C | Pointer Basics | Question 1" }, { "code": null, "e": 24541, "s": 24514, "text": "C | Operators | Question 1" }, { "code": null, "e": 24584, "s": 24541, "text": "C | Loops & Control Structure | Question 8" }, { "code": null, "e": 24618, "s": 24584, "text": "C | Advanced Pointer | Question 2" }, { "code": null, "e": 24644, "s": 24618, "text": "C Quiz - 101 | Question 2" }, { "code": null, "e": 24687, "s": 24644, "text": "C | Dynamic Memory Allocation | Question 7" }, { "code": null, "e": 24721, "s": 24687, "text": "C | Advanced Pointer | Question 4" } ]
JSP - Actions
In this chapter, we will discuss Actions in JSP. These actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard − <jsp:action_name attribute = "value" /> Action elements are basically predefined functions. The following table lists out the available JSP actions − jsp:include Includes a file at the time the page is requested. jsp:useBean Finds or instantiates a JavaBean. jsp:setProperty Sets the property of a JavaBean. jsp:getProperty Inserts the property of a JavaBean into the output. jsp:forward Forwards the requester to a new page. jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. jsp:element Defines XML elements dynamically. jsp:attribute Defines dynamically-defined XML element's attribute. jsp:body Defines dynamically-defined XML element's body. jsp:text Used to write template text in JSP pages and documents. There are two attributes that are common to all Action elements: the id attribute and the scope attribute. The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object, the id value can be used to reference it through the implicit object PageContext. This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application. This action lets you insert files into the page being generated. The syntax looks like this − <jsp:include page = "relative URL" flush = "true" /> Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. Following table lists out the attributes associated with the include action − page The relative URL of the page to be included. flush The boolean attribute determines whether the included resource has its buffer flushed before it is included. Let us define the following two files (a)date.jsp and (b) main.jsp as follows − Following is the content of the date.jsp file − <p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p> Following is the content of the main.jsp file − <html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:include page = "date.jsp" flush = "true" /> </center> </body> </html> Let us now keep all these files in the root directory and try to access main.jsp. You will receive the following output − The include action Example Today's date: 12-Sep-2010 14:54:22 The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object. The simplest way to load a bean is as follows − <jsp:useBean id = "name" class = "package.class" /> Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve the bean properties. Following table lists out the attributes associated with the useBean action − class Designates the full package name of the bean. type Specifies the type of the variable that will refer to the object. beanName Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class. Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid example related to these actions. The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action − You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below − <jsp:useBean id = "myName" ... /> ... <jsp:setProperty name = "myName" property = "someProperty" .../> In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as given below − <jsp:useBean id = "myName" ... > ... <jsp:setProperty name = "myName" property = "someProperty" .../> </jsp:useBean> Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found. Following table lists out the attributes associated with the setProperty action − name Designates the bean the property of which will be set. The Bean must have been previously defined. property Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. value The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored. param The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither. The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output. The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows − <jsp:useBean id = "myName" ... /> ... <jsp:getProperty name = "myName" property = "someProperty" .../> Following table lists out the required attributes associated with the getProperty action − name The name of the Bean that has a property to be retrieved. The Bean must have been previously defined. property The property attribute is the name of the Bean property to be retrieved. Let us define a test bean that will further be used in our example − /* File: TestBean.java */ package action; public class TestBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } } Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and the CLASSPATH variable should also be set to this folder − Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter − <html> <head> <title>Using JavaBeans in JSP</title> </head> <body> <center> <h2>Using JavaBeans in JSP</h2> <jsp:useBean id = "test" class = "action.TestBean" /> <jsp:setProperty name = "test" property = "message" value = "Hello JSP..." /> <p>Got message....</p> <jsp:getProperty name = "test" property = "message" /> </center> </body> </html> Let us now try to access main.jsp, it would display the following result − Using JavaBeans in JSP Got message.... Hello JSP... The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet. Following is the syntax of the forward action − <jsp:forward page = "Relative URL" /> Following table lists out the required attributes associated with the forward action − page Should consist of a relative URL of another resource such as a static page, another JSP page, or a Java Servlet. Let us reuse the following two files (a) date.jsp and (b) main.jsp as follows − Following is the content of the date.jsp file − <p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p> Following is the content of the main.jsp file − <html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:forward page = "date.jsp" /> </center> </body> </html> Let us now keep all these files in the root directory and try to access main.jsp. This would display result something like as below. Here it discarded the content from the main page and displayed the content from forwarded page only. Today's date: 12-Sep-2010 14:54:22 The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed. If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean. The plugin action has several attributes that correspond to common HTML tags used to format Java components. The <param> element can also be used to send parameters to the Applet or Bean. Following is the typical syntax of using the plugin action − <jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class" width = "60" height = "80"> <jsp:param name = "fontcolor" value = "red" /> <jsp:param name = "background" value = "black" /> <jsp:fallback> Unable to initialize Java Plugin </jsp:fallback> </jsp:plugin> You can try this action using some applet if you are interested. A new element, the <fallback> element, can be used to specify an error string to be sent to the user in case the component fails. The <jsp:element> Action The <jsp:attribute> Action The <jsp:body> Action The <jsp:element>, <jsp:attribute> and <jsp:body> actions are used to define XML elements dynamically. The word dynamically is important, because it means that the XML elements can be generated at request time rather than statically at compile time. Following is a simple example to define XML elements dynamically − <%@page language = "java" contentType = "text/html"%> <html xmlns = "http://www.w3c.org/1999/xhtml" xmlns:jsp = "http://java.sun.com/JSP/Page"> <head><title>Generate XML Element</title></head> <body> <jsp:element name = "xmlElement"> <jsp:attribute name = "xmlElementAttr"> Value for the attribute </jsp:attribute> <jsp:body> Body for XML element </jsp:body> </jsp:element> </body> </html> This would produce the following HTML code at run time − <html xmlns = "http://www.w3c.org/1999/xhtml" xmlns:jsp = "http://java.sun.com/JSP/Page"> <head><title>Generate XML Element</title></head> <body> <xmlElement xmlElementAttr = "Value for the attribute"> Body for XML element </xmlElement> </body> </html> The <jsp:text> action can be used to write the template text in JSP pages and documents. Following is the simple syntax for this action − <jsp:text>Template data</jsp:text> The body of the template cannot contain other elements; it can only contain text and EL expressions (Note − EL expressions are explained in a subsequent chapter). Note that in XML files, you cannot use expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section. <jsp:text><![CDATA[<br>]]></jsp:text> If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the <jsp:text> element as follows − <jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">]]></jsp:text> <head><title>jsp:text action</title></head> <body> <books><book><jsp:text> Welcome to JSP Programming </jsp:text></book></books> </body> </html> Try the above example with and without <jsp:text> action. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2513, "s": 2239, "text": "In this chapter, we will discuss Actions in JSP. These actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin." }, { "code": null, "e": 2599, "s": 2513, "text": "There is only one syntax for the Action element, as it conforms to the XML standard −" }, { "code": null, "e": 2640, "s": 2599, "text": "<jsp:action_name attribute = \"value\" />\n" }, { "code": null, "e": 2750, "s": 2640, "text": "Action elements are basically predefined functions. The following table lists out the available JSP actions −" }, { "code": null, "e": 2762, "s": 2750, "text": "jsp:include" }, { "code": null, "e": 2813, "s": 2762, "text": "Includes a file at the time the page is requested." }, { "code": null, "e": 2825, "s": 2813, "text": "jsp:useBean" }, { "code": null, "e": 2859, "s": 2825, "text": "Finds or instantiates a JavaBean." }, { "code": null, "e": 2875, "s": 2859, "text": "jsp:setProperty" }, { "code": null, "e": 2908, "s": 2875, "text": "Sets the property of a JavaBean." }, { "code": null, "e": 2924, "s": 2908, "text": "jsp:getProperty" }, { "code": null, "e": 2976, "s": 2924, "text": "Inserts the property of a JavaBean into the output." }, { "code": null, "e": 2988, "s": 2976, "text": "jsp:forward" }, { "code": null, "e": 3026, "s": 2988, "text": "Forwards the requester to a new page." }, { "code": null, "e": 3037, "s": 3026, "text": "jsp:plugin" }, { "code": null, "e": 3124, "s": 3037, "text": "Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin." }, { "code": null, "e": 3136, "s": 3124, "text": "jsp:element" }, { "code": null, "e": 3170, "s": 3136, "text": "Defines XML elements dynamically." }, { "code": null, "e": 3184, "s": 3170, "text": "jsp:attribute" }, { "code": null, "e": 3237, "s": 3184, "text": "Defines dynamically-defined XML element's attribute." }, { "code": null, "e": 3246, "s": 3237, "text": "jsp:body" }, { "code": null, "e": 3294, "s": 3246, "text": "Defines dynamically-defined XML element's body." }, { "code": null, "e": 3303, "s": 3294, "text": "jsp:text" }, { "code": null, "e": 3359, "s": 3303, "text": "Used to write template text in JSP pages and documents." }, { "code": null, "e": 3466, "s": 3359, "text": "There are two attributes that are common to all Action elements: the id attribute and the scope attribute." }, { "code": null, "e": 3713, "s": 3466, "text": "The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object, the id value can be used to reference it through the implicit object PageContext." }, { "code": null, "e": 4025, "s": 3713, "text": "This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application." }, { "code": null, "e": 4119, "s": 4025, "text": "This action lets you insert files into the page being generated. The syntax looks like this −" }, { "code": null, "e": 4173, "s": 4119, "text": "<jsp:include page = \"relative URL\" flush = \"true\" />\n" }, { "code": null, "e": 4345, "s": 4173, "text": "Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested." }, { "code": null, "e": 4423, "s": 4345, "text": "Following table lists out the attributes associated with the include action −" }, { "code": null, "e": 4428, "s": 4423, "text": "page" }, { "code": null, "e": 4473, "s": 4428, "text": "The relative URL of the page to be included." }, { "code": null, "e": 4479, "s": 4473, "text": "flush" }, { "code": null, "e": 4588, "s": 4479, "text": "The boolean attribute determines whether the included resource has its buffer flushed before it is included." }, { "code": null, "e": 4668, "s": 4588, "text": "Let us define the following two files (a)date.jsp and (b) main.jsp as follows −" }, { "code": null, "e": 4716, "s": 4668, "text": "Following is the content of the date.jsp file −" }, { "code": null, "e": 4783, "s": 4716, "text": "<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>" }, { "code": null, "e": 4831, "s": 4783, "text": "Following is the content of the main.jsp file −" }, { "code": null, "e": 5074, "s": 4831, "text": "<html>\n <head>\n <title>The include Action Example</title>\n </head>\n \n <body>\n <center>\n <h2>The include action Example</h2>\n <jsp:include page = \"date.jsp\" flush = \"true\" />\n </center>\n </body>\n</html>" }, { "code": null, "e": 5196, "s": 5074, "text": "Let us now keep all these files in the root directory and try to access main.jsp. You will receive the following output −" }, { "code": null, "e": 5264, "s": 5196, "text": "\nThe include action Example\n Today's date: 12-Sep-2010 14:54:22\n\n" }, { "code": null, "e": 5455, "s": 5264, "text": "The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object." }, { "code": null, "e": 5503, "s": 5455, "text": "The simplest way to load a bean is as follows −" }, { "code": null, "e": 5556, "s": 5503, "text": "<jsp:useBean id = \"name\" class = \"package.class\" />\n" }, { "code": null, "e": 5685, "s": 5556, "text": "Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve the bean properties." }, { "code": null, "e": 5763, "s": 5685, "text": "Following table lists out the attributes associated with the useBean action −" }, { "code": null, "e": 5769, "s": 5763, "text": "class" }, { "code": null, "e": 5815, "s": 5769, "text": "Designates the full package name of the bean." }, { "code": null, "e": 5820, "s": 5815, "text": "type" }, { "code": null, "e": 5886, "s": 5820, "text": "Specifies the type of the variable that will refer to the object." }, { "code": null, "e": 5895, "s": 5886, "text": "beanName" }, { "code": null, "e": 5995, "s": 5895, "text": "Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class." }, { "code": null, "e": 6122, "s": 5995, "text": "Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid example related to these actions." }, { "code": null, "e": 6296, "s": 6122, "text": "The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action −" }, { "code": null, "e": 6386, "s": 6296, "text": "You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below −" }, { "code": null, "e": 6490, "s": 6386, "text": "<jsp:useBean id = \"myName\" ... />\n...\n<jsp:setProperty name = \"myName\" property = \"someProperty\" .../>\n" }, { "code": null, "e": 6617, "s": 6490, "text": "In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found." }, { "code": null, "e": 6732, "s": 6617, "text": "A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as given below −" }, { "code": null, "e": 6855, "s": 6732, "text": "<jsp:useBean id = \"myName\" ... >\n ...\n <jsp:setProperty name = \"myName\" property = \"someProperty\" .../>\n</jsp:useBean>" }, { "code": null, "e": 6966, "s": 6855, "text": "Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found." }, { "code": null, "e": 7048, "s": 6966, "text": "Following table lists out the attributes associated with the setProperty action −" }, { "code": null, "e": 7053, "s": 7048, "text": "name" }, { "code": null, "e": 7152, "s": 7053, "text": "Designates the bean the property of which will be set. The Bean must have been previously defined." }, { "code": null, "e": 7161, "s": 7152, "text": "property" }, { "code": null, "e": 7338, "s": 7161, "text": "Indicates the property you want to set. A value of \"*\" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods." }, { "code": null, "e": 7344, "s": 7338, "text": "value" }, { "code": null, "e": 7503, "s": 7344, "text": "The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored." }, { "code": null, "e": 7509, "s": 7503, "text": "param" }, { "code": null, "e": 7680, "s": 7509, "text": "The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither." }, { "code": null, "e": 7822, "s": 7680, "text": "The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output." }, { "code": null, "e": 7951, "s": 7822, "text": "The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows −" }, { "code": null, "e": 8054, "s": 7951, "text": "<jsp:useBean id = \"myName\" ... />\n...\n<jsp:getProperty name = \"myName\" property = \"someProperty\" .../>" }, { "code": null, "e": 8145, "s": 8054, "text": "Following table lists out the required attributes associated with the getProperty action −" }, { "code": null, "e": 8150, "s": 8145, "text": "name" }, { "code": null, "e": 8252, "s": 8150, "text": "The name of the Bean that has a property to be retrieved. The Bean must have been previously defined." }, { "code": null, "e": 8261, "s": 8252, "text": "property" }, { "code": null, "e": 8334, "s": 8261, "text": "The property attribute is the name of the Bean property to be retrieved." }, { "code": null, "e": 8403, "s": 8334, "text": "Let us define a test bean that will further be used in our example −" }, { "code": null, "e": 8666, "s": 8403, "text": "/* File: TestBean.java */\npackage action;\n \npublic class TestBean {\n private String message = \"No message specified\";\n \n public String getMessage() {\n return(message);\n }\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "code": null, "e": 8902, "s": 8666, "text": "Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\\apache-tomcat-7.0.2\\webapps\\WEB-INF\\classes\\action folder and the CLASSPATH variable should also be set to this folder −" }, { "code": null, "e": 9009, "s": 8902, "text": "Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter −" }, { "code": null, "e": 9463, "s": 9009, "text": "<html>\n \n <head>\n <title>Using JavaBeans in JSP</title>\n </head>\n \n <body>\n <center>\n <h2>Using JavaBeans in JSP</h2>\n <jsp:useBean id = \"test\" class = \"action.TestBean\" />\n <jsp:setProperty name = \"test\" property = \"message\" \n value = \"Hello JSP...\" />\n \n <p>Got message....</p>\n <jsp:getProperty name = \"test\" property = \"message\" />\n </center>\n </body>\n</html>" }, { "code": null, "e": 9538, "s": 9463, "text": "Let us now try to access main.jsp, it would display the following result −" }, { "code": null, "e": 9593, "s": 9538, "text": "\nUsing JavaBeans in JSP\nGot message....\nHello JSP...\n\n" }, { "code": null, "e": 9759, "s": 9593, "text": "The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet." }, { "code": null, "e": 9807, "s": 9759, "text": "Following is the syntax of the forward action −" }, { "code": null, "e": 9846, "s": 9807, "text": "<jsp:forward page = \"Relative URL\" />\n" }, { "code": null, "e": 9933, "s": 9846, "text": "Following table lists out the required attributes associated with the forward action −" }, { "code": null, "e": 9938, "s": 9933, "text": "page" }, { "code": null, "e": 10051, "s": 9938, "text": "Should consist of a relative URL of another resource such as a static page, another JSP page, or a Java Servlet." }, { "code": null, "e": 10131, "s": 10051, "text": "Let us reuse the following two files (a) date.jsp and (b) main.jsp as follows −" }, { "code": null, "e": 10179, "s": 10131, "text": "Following is the content of the date.jsp file −" }, { "code": null, "e": 10246, "s": 10179, "text": "<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>" }, { "code": null, "e": 10294, "s": 10246, "text": "Following is the content of the main.jsp file −" }, { "code": null, "e": 10522, "s": 10294, "text": "<html>\n <head>\n <title>The include Action Example</title>\n </head>\n \n <body>\n <center>\n <h2>The include action Example</h2>\n <jsp:forward page = \"date.jsp\" />\n </center>\n </body>\n</html>" }, { "code": null, "e": 10655, "s": 10522, "text": "Let us now keep all these files in the root directory and try to access main.jsp. This would display result something like as below." }, { "code": null, "e": 10756, "s": 10655, "text": "Here it discarded the content from the main page and displayed the content from forwarded page only." }, { "code": null, "e": 10797, "s": 10756, "text": "\n Today's date: 12-Sep-2010 14:54:22\n\n" }, { "code": null, "e": 10952, "s": 10797, "text": "The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed." }, { "code": null, "e": 11109, "s": 10952, "text": "If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean." }, { "code": null, "e": 11297, "s": 11109, "text": "The plugin action has several attributes that correspond to common HTML tags used to format Java components. The <param> element can also be used to send parameters to the Applet or Bean." }, { "code": null, "e": 11358, "s": 11297, "text": "Following is the typical syntax of using the plugin action −" }, { "code": null, "e": 11659, "s": 11358, "text": "<jsp:plugin type = \"applet\" codebase = \"dirname\" code = \"MyApplet.class\"\n width = \"60\" height = \"80\">\n <jsp:param name = \"fontcolor\" value = \"red\" />\n <jsp:param name = \"background\" value = \"black\" />\n \n <jsp:fallback>\n Unable to initialize Java Plugin\n </jsp:fallback>\n \n</jsp:plugin>" }, { "code": null, "e": 11854, "s": 11659, "text": "You can try this action using some applet if you are interested. A new element, the <fallback> element, can be used to specify an error string to be sent to the user in case the component fails." }, { "code": null, "e": 11929, "s": 11854, "text": "The <jsp:element> Action\nThe <jsp:attribute> Action\nThe <jsp:body> Action\n" }, { "code": null, "e": 12179, "s": 11929, "text": "The <jsp:element>, <jsp:attribute> and <jsp:body> actions are used to define XML elements dynamically. The word dynamically is important, because it means that the XML elements can be generated at request time rather than statically at compile time." }, { "code": null, "e": 12246, "s": 12179, "text": "Following is a simple example to define XML elements dynamically −" }, { "code": null, "e": 12745, "s": 12246, "text": "<%@page language = \"java\" contentType = \"text/html\"%>\n<html xmlns = \"http://www.w3c.org/1999/xhtml\"\n xmlns:jsp = \"http://java.sun.com/JSP/Page\">\n \n <head><title>Generate XML Element</title></head>\n \n <body>\n <jsp:element name = \"xmlElement\">\n <jsp:attribute name = \"xmlElementAttr\">\n Value for the attribute\n </jsp:attribute>\n \n <jsp:body>\n Body for XML element\n </jsp:body>\n \n </jsp:element>\n </body>\n</html>" }, { "code": null, "e": 12802, "s": 12745, "text": "This would produce the following HTML code at run time −" }, { "code": null, "e": 13089, "s": 12802, "text": "<html xmlns = \"http://www.w3c.org/1999/xhtml\" xmlns:jsp = \"http://java.sun.com/JSP/Page\">\n <head><title>Generate XML Element</title></head>\n \n <body>\n <xmlElement xmlElementAttr = \"Value for the attribute\">\n Body for XML element\n </xmlElement>\n </body>\n</html>" }, { "code": null, "e": 13227, "s": 13089, "text": "The <jsp:text> action can be used to write the template text in JSP pages and documents. Following is the simple syntax for this action −" }, { "code": null, "e": 13263, "s": 13227, "text": "<jsp:text>Template data</jsp:text>\n" }, { "code": null, "e": 13657, "s": 13263, "text": "The body of the template cannot contain other elements; it can only contain text and EL expressions (Note − EL expressions are explained in a subsequent chapter). Note that in XML files, you cannot use expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section." }, { "code": null, "e": 13696, "s": 13657, "text": "<jsp:text><![CDATA[<br>]]></jsp:text>\n" }, { "code": null, "e": 13820, "s": 13696, "text": "If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the <jsp:text> element as follows −" }, { "code": null, "e": 14120, "s": 13820, "text": "<jsp:text><![CDATA[<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"DTD/xhtml1-strict.dtd\">]]></jsp:text>\n\n <head><title>jsp:text action</title></head>\n \n <body>\n <books><book><jsp:text> \n Welcome to JSP Programming\n </jsp:text></book></books>\n </body>\n</html>" }, { "code": null, "e": 14178, "s": 14120, "text": "Try the above example with and without <jsp:text> action." }, { "code": null, "e": 14213, "s": 14178, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 14228, "s": 14213, "text": " Chaand Sheikh" }, { "code": null, "e": 14263, "s": 14228, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 14278, "s": 14263, "text": " Chaand Sheikh" }, { "code": null, "e": 14313, "s": 14278, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14327, "s": 14313, "text": " Karthikeya T" }, { "code": null, "e": 14362, "s": 14327, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 14378, "s": 14362, "text": " TELCOMA Global" }, { "code": null, "e": 14411, "s": 14378, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 14427, "s": 14411, "text": " TELCOMA Global" }, { "code": null, "e": 14461, "s": 14427, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 14469, "s": 14461, "text": " Uplatz" }, { "code": null, "e": 14476, "s": 14469, "text": " Print" }, { "code": null, "e": 14487, "s": 14476, "text": " Add Notes" } ]
HTML <button> value Attribute
The value attribute of the <button> element is used to set the initial value of a button. You can set this in a <form>. Here, we will be showing an example without using a form. Following is the syntax − <button value="value"> Above, value is the initial value. Let us now see an example to implement value attribute in <button> − Live Demo <!DOCTYPE html> <html> <body> <p>Click below to get details about the learning content...</p></br></br> <button id = "button1" value = "Learning" onclick = "demo1()">Get Tutorials</button> <button id = "button2" value = "InterviewAnswers" onclick = "demo2()">Get InterviewQA</button> <p id = "myid"></p> <script> function demo1() { var val1 = document.getElementById("button1").value; document.getElementById("myid").innerHTML = val1; } function demo2() { var val1 = document.getElementById("button2").value; document.getElementById("myid").innerHTML = val1; } </script> </body> </html> This will produce the following output initially − The output is as follows when “Get Tutorials” button is clicked − The output is as follows when “Get InterviewQA” button is clicked − In the above example, we have created JavaScript functions to get the value in a variable. One of them is demo1() function demo1() { var val1 = document.getElementById("button1").value; document.getElementById("myid").innerHTML = val1; } The result of the above gets displayed on the click of a button. The onclick property is set to call the above function demo1() − <button id = "button1" value = "Learning" onclick = "demo1()"> Get Tutorials </button>
[ { "code": null, "e": 1240, "s": 1062, "text": "The value attribute of the <button> element is used to set the initial value of a button. You can set this in a <form>. Here, we will be showing an example without using a form." }, { "code": null, "e": 1266, "s": 1240, "text": "Following is the syntax −" }, { "code": null, "e": 1289, "s": 1266, "text": "<button value=\"value\">" }, { "code": null, "e": 1324, "s": 1289, "text": "Above, value is the initial value." }, { "code": null, "e": 1393, "s": 1324, "text": "Let us now see an example to implement value attribute in <button> −" }, { "code": null, "e": 1404, "s": 1393, "text": " Live Demo" }, { "code": null, "e": 2027, "s": 1404, "text": "<!DOCTYPE html>\n<html>\n<body>\n<p>Click below to get details about the learning content...</p></br></br>\n<button id = \"button1\" value = \"Learning\" onclick = \"demo1()\">Get Tutorials</button>\n<button id = \"button2\" value = \"InterviewAnswers\" onclick = \"demo2()\">Get InterviewQA</button>\n<p id = \"myid\"></p>\n<script>\n function demo1() {\n var val1 = document.getElementById(\"button1\").value;\n document.getElementById(\"myid\").innerHTML = val1;\n }\n function demo2() {\n var val1 = document.getElementById(\"button2\").value;\n document.getElementById(\"myid\").innerHTML = val1;\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2078, "s": 2027, "text": "This will produce the following output initially −" }, { "code": null, "e": 2144, "s": 2078, "text": "The output is as follows when “Get Tutorials” button is clicked −" }, { "code": null, "e": 2212, "s": 2144, "text": "The output is as follows when “Get InterviewQA” button is clicked −" }, { "code": null, "e": 2326, "s": 2212, "text": "In the above example, we have created JavaScript functions to get the value in a variable. One of them is demo1()" }, { "code": null, "e": 2456, "s": 2326, "text": "function demo1() {\n var val1 = document.getElementById(\"button1\").value;\n document.getElementById(\"myid\").innerHTML = val1;\n}" }, { "code": null, "e": 2586, "s": 2456, "text": "The result of the above gets displayed on the click of a button. The onclick property is set to call the above function demo1() −" }, { "code": null, "e": 2676, "s": 2586, "text": "<button id = \"button1\" value = \"Learning\" onclick = \"demo1()\">\n Get Tutorials\n</button>" } ]
How to create an unordered list with circle bullets in HTML?
To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles. For creating an unordered list with circle bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to add circle bullets to an unordered list. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to create an unordered list with circle bullets in HTML − Live Demo <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <h1>Developed Countries</h1> <p>The list of developed countries:</p> <ul style="list-style-type:circle"> <li>US</li> <li>Australia</li> <li>New Zealand</li> </ul> </body> </html>
[ { "code": null, "e": 1302, "s": 1062, "text": " To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles." }, { "code": null, "e": 1617, "s": 1302, "text": "For creating an unordered list with circle bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to add circle bullets to an unordered list. " }, { "code": null, "e": 1779, "s": 1617, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1875, "s": 1779, "text": "You can try to run the following code to create an unordered list with circle bullets in HTML −" }, { "code": null, "e": 1885, "s": 1875, "text": "Live Demo" }, { "code": null, "e": 2213, "s": 1885, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Unordered List</title>\n </head>\n <body>\n <h1>Developed Countries</h1>\n <p>The list of developed countries:</p>\n <ul style=\"list-style-type:circle\">\n <li>US</li>\n <li>Australia</li>\n <li>New Zealand</li>\n </ul>\n </body>\n</html>" } ]
15 Must-Know Python String Methods | by Soner Yıldırım | Towards Data Science
Python is a great language. It is relatively easy to learn and has an intuitive syntax. The rich selection of libraries also contribute to the popularity and success of Python. However, it is not just about the third party libraries. Base Python also provides numerous methods and functions to expedite and ease the typical tasks in data science. In this article, we will go over 15 built-in string methods in Python. You might already be familiar with some of them but we will also see some of the rare ones. The methods are quite self-explanatory so I will focus more on the examples to demonstrate how to use them rather than explaining what they do. It makes the first letter uppercase. txt = "python is awesome!"txt.capitalize()'Python is awesome!' It makes all the letters uppercase. txt = "Python is awesome!"txt.upper()'PYTHON IS AWESOME!' It makes all the letters lowercase. txt = "PYTHON IS AWESOME!"txt.lower()'python is awesome!' It checks if all the letters are uppercase. txt = "PYTHON IS AWESOME!"txt.isupper()True It checks if all the letters are lowercase txt = "PYTHON IS AWESOME!"txt.islower()False The following 3 methods are similar so I will do examples that include all of them. It checks if all the characters are numeric. It checks if all the characters are in the alphabet. It checks if all the characters are alphanumeric (i.e. letter or number). # Example 1txt = "Python"print(txt.isnumeric())Falseprint(txt.isalpha())Trueprint(txt.isalnum())True # Example 2txt = "2021"print(txt.isnumeric())Trueprint(txt.isalpha())Falseprint(txt.isalnum())True # Example 3txt = "Python2021"print(txt.isnumeric())Falseprint(txt.isalpha())Falseprint(txt.isalnum())True # Example 4txt = "Python-2021"print(txt.isnumeric())Falseprint(txt.isalpha())Falseprint(txt.isalnum())False It counts the number of occurrences of the given character in a string. txt = "Data science"txt.count("e")2 It returns the index of the first occurrence of the given character in a string. txt = "Data science"txt.find("a")1 We can also find the second or other occurrences of a character. txt.find("a", 2)3 If we pass a sequence of characters, the find method returns the index where the sequence starts. txt.find("sci")5 It checks if a string starts with the given character. We can use this method as a filter in a list comprehension. mylist = ["John", "Jane", "Emily", "Jack", "Ashley"]j_list = [name for name in mylist if name.startswith("J")]j_list['John', 'Jane', 'Jack'] It checks if a string ends with the given character. txt = "Python"txt.endswith("n")True Both the endswith and startswith methods are case sensitive. txt = "Python"txt.startswith("p")Falsetxt.startswith("P")True It replaces a string or a part of it with the given set of characters. txt = "Python is awesome!"txt = txt.replace("Python", "Data science")txt'Data science is awesome!' It splits a string at the occurrences of the specified character and returns a list that contains each part after splitting. txt = 'Data science is awesome!'txt.split()['Data', 'science', 'is', 'awesome!'] By default, it splits at whitespace but we can make it based on any character or set of characters. It partitions a string into 3 parts and returns a tuple that contains these parts. txt = "Python is awesome!"txt.partition("is")('Python ', 'is', ' awesome!')txt = "Python is awesome and it is easy to learn."txt.partition("and")('Python is awesome ', 'and', ' it is easy to learn.') The partition method returns exactly 3 parts. If there are multiple occurrences of the character used for partitioning, the first one is taken into account. txt = "Python and data science and machine learning"txt.partition("and")('Python ', 'and', ' data science and machine learning') We can also do a similar operation with the split method by limiting the number of splits. However, there are some differences. The split method returns a list The returned list does not include the characters used for splitting txt = "Python and data science and machine learning"txt.split("and", 1)['Python ', ' data science and machine learning'] Thanks Matheus Ferreira for reminding me one of the greatest strings methods: join. I also use the join method but I forgot to add it here. It deserves to get in the list as a bonus. The join method combines the strings in a collection into a single string. mylist = ["Jane", "John", "Matt", "James"]"-".join(mylist)'Jane-John-Matt-James' Let’s do an example with a tuple as well. mytuple = ("Data science", "Machine learning")" and ".join(mytuple)'Data science and Machine learning' When performing data science, we deal with textual data a lot. Moreover, the textual data requires much more preprocessing than plain numbers. Thankfully, Python’s built-in string methods are capable of performing such tasks efficiently and smoothly. Last but not least, if you are not a Medium member yet and plan to become one, I kindly ask you to do so using the following link. I will receive a portion from your membership fee with no additional cost to you. sonery.medium.com Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 348, "s": 171, "text": "Python is a great language. It is relatively easy to learn and has an intuitive syntax. The rich selection of libraries also contribute to the popularity and success of Python." }, { "code": null, "e": 518, "s": 348, "text": "However, it is not just about the third party libraries. Base Python also provides numerous methods and functions to expedite and ease the typical tasks in data science." }, { "code": null, "e": 681, "s": 518, "text": "In this article, we will go over 15 built-in string methods in Python. You might already be familiar with some of them but we will also see some of the rare ones." }, { "code": null, "e": 825, "s": 681, "text": "The methods are quite self-explanatory so I will focus more on the examples to demonstrate how to use them rather than explaining what they do." }, { "code": null, "e": 862, "s": 825, "text": "It makes the first letter uppercase." }, { "code": null, "e": 925, "s": 862, "text": "txt = \"python is awesome!\"txt.capitalize()'Python is awesome!'" }, { "code": null, "e": 961, "s": 925, "text": "It makes all the letters uppercase." }, { "code": null, "e": 1019, "s": 961, "text": "txt = \"Python is awesome!\"txt.upper()'PYTHON IS AWESOME!'" }, { "code": null, "e": 1055, "s": 1019, "text": "It makes all the letters lowercase." }, { "code": null, "e": 1113, "s": 1055, "text": "txt = \"PYTHON IS AWESOME!\"txt.lower()'python is awesome!'" }, { "code": null, "e": 1157, "s": 1113, "text": "It checks if all the letters are uppercase." }, { "code": null, "e": 1201, "s": 1157, "text": "txt = \"PYTHON IS AWESOME!\"txt.isupper()True" }, { "code": null, "e": 1244, "s": 1201, "text": "It checks if all the letters are lowercase" }, { "code": null, "e": 1289, "s": 1244, "text": "txt = \"PYTHON IS AWESOME!\"txt.islower()False" }, { "code": null, "e": 1373, "s": 1289, "text": "The following 3 methods are similar so I will do examples that include all of them." }, { "code": null, "e": 1418, "s": 1373, "text": "It checks if all the characters are numeric." }, { "code": null, "e": 1471, "s": 1418, "text": "It checks if all the characters are in the alphabet." }, { "code": null, "e": 1545, "s": 1471, "text": "It checks if all the characters are alphanumeric (i.e. letter or number)." }, { "code": null, "e": 1646, "s": 1545, "text": "# Example 1txt = \"Python\"print(txt.isnumeric())Falseprint(txt.isalpha())Trueprint(txt.isalnum())True" }, { "code": null, "e": 1745, "s": 1646, "text": "# Example 2txt = \"2021\"print(txt.isnumeric())Trueprint(txt.isalpha())Falseprint(txt.isalnum())True" }, { "code": null, "e": 1851, "s": 1745, "text": "# Example 3txt = \"Python2021\"print(txt.isnumeric())Falseprint(txt.isalpha())Falseprint(txt.isalnum())True" }, { "code": null, "e": 1959, "s": 1851, "text": "# Example 4txt = \"Python-2021\"print(txt.isnumeric())Falseprint(txt.isalpha())Falseprint(txt.isalnum())False" }, { "code": null, "e": 2031, "s": 1959, "text": "It counts the number of occurrences of the given character in a string." }, { "code": null, "e": 2067, "s": 2031, "text": "txt = \"Data science\"txt.count(\"e\")2" }, { "code": null, "e": 2148, "s": 2067, "text": "It returns the index of the first occurrence of the given character in a string." }, { "code": null, "e": 2183, "s": 2148, "text": "txt = \"Data science\"txt.find(\"a\")1" }, { "code": null, "e": 2248, "s": 2183, "text": "We can also find the second or other occurrences of a character." }, { "code": null, "e": 2266, "s": 2248, "text": "txt.find(\"a\", 2)3" }, { "code": null, "e": 2364, "s": 2266, "text": "If we pass a sequence of characters, the find method returns the index where the sequence starts." }, { "code": null, "e": 2381, "s": 2364, "text": "txt.find(\"sci\")5" }, { "code": null, "e": 2496, "s": 2381, "text": "It checks if a string starts with the given character. We can use this method as a filter in a list comprehension." }, { "code": null, "e": 2637, "s": 2496, "text": "mylist = [\"John\", \"Jane\", \"Emily\", \"Jack\", \"Ashley\"]j_list = [name for name in mylist if name.startswith(\"J\")]j_list['John', 'Jane', 'Jack']" }, { "code": null, "e": 2690, "s": 2637, "text": "It checks if a string ends with the given character." }, { "code": null, "e": 2726, "s": 2690, "text": "txt = \"Python\"txt.endswith(\"n\")True" }, { "code": null, "e": 2787, "s": 2726, "text": "Both the endswith and startswith methods are case sensitive." }, { "code": null, "e": 2849, "s": 2787, "text": "txt = \"Python\"txt.startswith(\"p\")Falsetxt.startswith(\"P\")True" }, { "code": null, "e": 2920, "s": 2849, "text": "It replaces a string or a part of it with the given set of characters." }, { "code": null, "e": 3019, "s": 2920, "text": "txt = \"Python is awesome!\"txt = txt.replace(\"Python\", \"Data science\")txt'Data science is awesome!'" }, { "code": null, "e": 3144, "s": 3019, "text": "It splits a string at the occurrences of the specified character and returns a list that contains each part after splitting." }, { "code": null, "e": 3225, "s": 3144, "text": "txt = 'Data science is awesome!'txt.split()['Data', 'science', 'is', 'awesome!']" }, { "code": null, "e": 3325, "s": 3225, "text": "By default, it splits at whitespace but we can make it based on any character or set of characters." }, { "code": null, "e": 3408, "s": 3325, "text": "It partitions a string into 3 parts and returns a tuple that contains these parts." }, { "code": null, "e": 3608, "s": 3408, "text": "txt = \"Python is awesome!\"txt.partition(\"is\")('Python ', 'is', ' awesome!')txt = \"Python is awesome and it is easy to learn.\"txt.partition(\"and\")('Python is awesome ', 'and', ' it is easy to learn.')" }, { "code": null, "e": 3765, "s": 3608, "text": "The partition method returns exactly 3 parts. If there are multiple occurrences of the character used for partitioning, the first one is taken into account." }, { "code": null, "e": 3894, "s": 3765, "text": "txt = \"Python and data science and machine learning\"txt.partition(\"and\")('Python ', 'and', ' data science and machine learning')" }, { "code": null, "e": 4022, "s": 3894, "text": "We can also do a similar operation with the split method by limiting the number of splits. However, there are some differences." }, { "code": null, "e": 4054, "s": 4022, "text": "The split method returns a list" }, { "code": null, "e": 4123, "s": 4054, "text": "The returned list does not include the characters used for splitting" }, { "code": null, "e": 4244, "s": 4123, "text": "txt = \"Python and data science and machine learning\"txt.split(\"and\", 1)['Python ', ' data science and machine learning']" }, { "code": null, "e": 4427, "s": 4244, "text": "Thanks Matheus Ferreira for reminding me one of the greatest strings methods: join. I also use the join method but I forgot to add it here. It deserves to get in the list as a bonus." }, { "code": null, "e": 4502, "s": 4427, "text": "The join method combines the strings in a collection into a single string." }, { "code": null, "e": 4583, "s": 4502, "text": "mylist = [\"Jane\", \"John\", \"Matt\", \"James\"]\"-\".join(mylist)'Jane-John-Matt-James'" }, { "code": null, "e": 4625, "s": 4583, "text": "Let’s do an example with a tuple as well." }, { "code": null, "e": 4728, "s": 4625, "text": "mytuple = (\"Data science\", \"Machine learning\")\" and \".join(mytuple)'Data science and Machine learning'" }, { "code": null, "e": 4979, "s": 4728, "text": "When performing data science, we deal with textual data a lot. Moreover, the textual data requires much more preprocessing than plain numbers. Thankfully, Python’s built-in string methods are capable of performing such tasks efficiently and smoothly." }, { "code": null, "e": 5192, "s": 4979, "text": "Last but not least, if you are not a Medium member yet and plan to become one, I kindly ask you to do so using the following link. I will receive a portion from your membership fee with no additional cost to you." }, { "code": null, "e": 5210, "s": 5192, "text": "sonery.medium.com" } ]
Transitive closure of a Graph
Transitive Closure it the reachability matrix to reach from vertex u to vertex v of a graph. One graph is given, we have to find a vertex v which is reachable from another vertex u, for all vertex pairs (u, v). The final matrix is the Boolean type. When there is a value 1 for vertex u to vertex v, it means that there is at least one path from u to v. Input: 1 1 0 1 0 1 1 0 0 0 1 1 0 0 0 1 Output: The matrix of transitive closure 1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1 transColsure(graph) Input: The given graph.Output: Transitive Closure matrix. Begin copy the adjacency matrix into another matrix named transMat for any vertex k in the graph, do for each vertex i in the graph, do for each vertex j in the graph, do transMat[i, j] := transMat[i, j] OR (transMat[i, k]) AND transMat[k, j]) done done done Display the transMat End <2>Example #include<iostream> #include<vector> #define NODE 4 using namespace std; /* int graph[NODE][NODE] = { {0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 0} }; */ int graph[NODE][NODE] = { {1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1} }; int result[NODE][NODE]; void transClosure() { for(int i = 0; i<NODE; i++) for(int j = 0; j<NODE; j++) result[i][j] = graph[i][j]; //initially copy the graph to the result matrix for(int k = 0; k<NODE; k++) for(int i = 0; i<NODE; i++) for(int j = 0; j<NODE; j++) result[i][j] = result[i][j] || (result[i][k] && result[k][j]); for(int i = 0; i<NODE; i++) { //print the result matrix for(int j = 0; j<NODE; j++) cout << result[i][j] << " "; cout << endl; } } int main() { transClosure(); } 1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1
[ { "code": null, "e": 1273, "s": 1062, "text": "Transitive Closure it the reachability matrix to reach from vertex u to vertex v of a graph. One graph is given, we have to find a vertex v which is reachable from another vertex u, for all vertex pairs (u, v)." }, { "code": null, "e": 1415, "s": 1273, "text": "The final matrix is the Boolean type. When there is a value 1 for vertex u to vertex v, it means that there is at least one path from u to v." }, { "code": null, "e": 1528, "s": 1415, "text": "Input:\n1 1 0 1\n0 1 1 0\n0 0 1 1\n0 0 0 1\n\nOutput:\nThe matrix of transitive closure\n1 1 1 1\n0 1 1 1\n0 0 1 1\n0 0 0 1" }, { "code": null, "e": 1548, "s": 1528, "text": "transColsure(graph)" }, { "code": null, "e": 1606, "s": 1548, "text": "Input: The given graph.Output: Transitive Closure matrix." }, { "code": null, "e": 1946, "s": 1606, "text": "Begin\n copy the adjacency matrix into another matrix named transMat\n for any vertex k in the graph, do\n for each vertex i in the graph, do\n for each vertex j in the graph, do\n transMat[i, j] := transMat[i, j] OR (transMat[i, k]) AND transMat[k, j])\n done\n done\n done\n Display the transMat\nEnd\n\n" }, { "code": null, "e": 1957, "s": 1946, "text": "<2>Example" }, { "code": null, "e": 2809, "s": 1957, "text": "#include<iostream>\n#include<vector>\n#define NODE 4\nusing namespace std;\n\n/* int graph[NODE][NODE] = {\n {0, 1, 1, 0},\n {0, 0, 1, 0},\n {1, 0, 0, 1},\n {0, 0, 0, 0}\n}; */\n\nint graph[NODE][NODE] = {\n {1, 1, 0, 1},\n {0, 1, 1, 0},\n {0, 0, 1, 1},\n {0, 0, 0, 1}\n};\n\nint result[NODE][NODE];\n\nvoid transClosure() {\n for(int i = 0; i<NODE; i++)\n for(int j = 0; j<NODE; j++)\n result[i][j] = graph[i][j]; //initially copy the graph to the result matrix\n for(int k = 0; k<NODE; k++)\n for(int i = 0; i<NODE; i++)\n for(int j = 0; j<NODE; j++)\n result[i][j] = result[i][j] || (result[i][k] && result[k][j]);\n for(int i = 0; i<NODE; i++) { //print the result matrix\n for(int j = 0; j<NODE; j++)\n cout << result[i][j] << \" \";\n cout << endl;\n }\n}\n\nint main() {\n transClosure();\n}" }, { "code": null, "e": 2841, "s": 2809, "text": "1 1 1 1\n0 1 1 1\n0 0 1 1\n0 0 0 1" } ]
{{ form.as_table }} – Render Django Forms as table
13 Feb, 2020 Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as table in the template. Illustration of {{ form.as_table }} using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput()) Now we need a View to render this form into a template. Let’s create a view, from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context) Finally, we will create the template where we need the form to be placed. In templates > home.html, <form action = "" method = "post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"></form> Here {{ form.as_table }} will render them as table cells wrapped in <tr> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/ Let’s check the source code whether the form is rendered as a table or not. By rendering as a table it is meant that all input fields will be enclosed in <tr> tags.Here is the demonstration, {{ form.as_p }} will render them wrapped in <p> tags {{ form.as_ul }} will render them wrapped in <li> tags NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2020" }, { "code": null, "e": 422, "s": 28, "text": "Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as table in the template." }, { "code": null, "e": 542, "s": 422, "text": "Illustration of {{ form.as_table }} using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 629, "s": 542, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 680, "s": 629, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 713, "s": 680, "text": "How to Create an App in Django ?" }, { "code": null, "e": 826, "s": 713, "text": "Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code" }, { "code": "from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = \"Enter 6 digit roll number\" ) password = forms.CharField(widget = forms.PasswordInput())", "e": 1183, "s": 826, "text": null }, { "code": null, "e": 1260, "s": 1183, "text": "Now we need a View to render this form into a template. Let’s create a view," }, { "code": "from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, \"home.html\", context)", "e": 1470, "s": 1260, "text": null }, { "code": null, "e": 1570, "s": 1470, "text": "Finally, we will create the template where we need the form to be placed. In templates > home.html," }, { "code": "<form action = \"\" method = \"post\"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type=\"submit\" value=\"Submit\"></form>", "e": 1722, "s": 1570, "text": null }, { "code": null, "e": 1884, "s": 1722, "text": "Here {{ form.as_table }} will render them as table cells wrapped in <tr> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/" }, { "code": null, "e": 2075, "s": 1884, "text": "Let’s check the source code whether the form is rendered as a table or not. By rendering as a table it is meant that all input fields will be enclosed in <tr> tags.Here is the demonstration," }, { "code": null, "e": 2128, "s": 2075, "text": "{{ form.as_p }} will render them wrapped in <p> tags" }, { "code": null, "e": 2183, "s": 2128, "text": "{{ form.as_ul }} will render them wrapped in <li> tags" }, { "code": null, "e": 2195, "s": 2183, "text": "NaveenArora" }, { "code": null, "e": 2208, "s": 2195, "text": "Django-forms" }, { "code": null, "e": 2222, "s": 2208, "text": "Python Django" }, { "code": null, "e": 2229, "s": 2222, "text": "Python" } ]
Python | Check if string matches regex list
03 Oct, 2019 Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let’s discuss a way in which this task can be performed. Method : Using join regex + loop + re.match()This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list. # Python3 code to demonstrate working of# Check if string matches regex list# Using join regex + loop + re.match()import re # initializing list test_list = ["gee*", "gf*", "df.*", "re"] # printing list print("The original list : " + str(test_list)) # initializing test_str test_str = "geeksforgeeks" # Check if string matches regex list# Using join regex + loop + re.match()temp = '(?:% s)' % '|'.join(test_list)res = Falseif re.match(temp, test_str): res = True # Printing resultprint("Does string match any of regex in list ? : " + str(res)) The original list : ['gee*', 'gf*', 'df.*', 're'] Does string match any of regex in list ? : True Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Oct, 2019" }, { "code": null, "e": 252, "s": 28, "text": "Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let’s discuss a way in which this task can be performed." }, { "code": null, "e": 539, "s": 252, "text": "Method : Using join regex + loop + re.match()This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list." }, { "code": "# Python3 code to demonstrate working of# Check if string matches regex list# Using join regex + loop + re.match()import re # initializing list test_list = [\"gee*\", \"gf*\", \"df.*\", \"re\"] # printing list print(\"The original list : \" + str(test_list)) # initializing test_str test_str = \"geeksforgeeks\" # Check if string matches regex list# Using join regex + loop + re.match()temp = '(?:% s)' % '|'.join(test_list)res = Falseif re.match(temp, test_str): res = True # Printing resultprint(\"Does string match any of regex in list ? : \" + str(res))", "e": 1091, "s": 539, "text": null }, { "code": null, "e": 1192, "s": 1091, "text": " \nThe original list : ['gee*', 'gf*', 'df.*', 're']\nDoes string match any of regex in list ? : True\n" }, { "code": null, "e": 1213, "s": 1192, "text": "Python list-programs" }, { "code": null, "e": 1220, "s": 1213, "text": "Python" }, { "code": null, "e": 1236, "s": 1220, "text": "Python Programs" } ]
Python – 3D Matrix to Coordinate List
02 Sep, 2020 Given a Matrix, row’s each element is list, pair each column to form coordinates. Input : test_list = [[[9, 2], [10, 3]], [[13, 6], [19, 7]]]Output : [(9, 10), (2, 3), (13, 19), (6, 7)]Explanation : Column Mapped Pairs. Input : test_list = [[[13, 6], [19, 7]]]Output : [(13, 19), (6, 7)]Explanation : Column Mapped Pairs. Method #1 : Using loop + zip() In this, we iterate for all the paired elements in inner tuples list, which is paired using zip(), and append the result list. Python3 # Python3 code to demonstrate working of # 3D Matrix to Coordinate List# Using loop + zip() # initializing listtest_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]] # printing original listprint("The original list is : " + str(test_list)) res = []for sub1, sub2 in test_list: # zip() used to form pairing for ele in zip(sub1, sub2): res.append(ele) # printing result print("Constructed Pairs : " + str(res)) The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]] Constructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)] Method #2 : Using list comprehension In this, we perform task of of above method in shorthand using list comprehension. Python3 # Python3 code to demonstrate working of # 3D Matrix to Coordinate List# Using loop + zip() # initializing listtest_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]] # printing original listprint("The original list is : " + str(test_list)) # list comprehension to perform task in shorthandres = [ele for sub1, sub2 in test_list for ele in zip(sub1, sub2)] # printing result print("Constructed Pairs : " + str(res)) The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]] Constructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 110, "s": 28, "text": "Given a Matrix, row’s each element is list, pair each column to form coordinates." }, { "code": null, "e": 248, "s": 110, "text": "Input : test_list = [[[9, 2], [10, 3]], [[13, 6], [19, 7]]]Output : [(9, 10), (2, 3), (13, 19), (6, 7)]Explanation : Column Mapped Pairs." }, { "code": null, "e": 350, "s": 248, "text": "Input : test_list = [[[13, 6], [19, 7]]]Output : [(13, 19), (6, 7)]Explanation : Column Mapped Pairs." }, { "code": null, "e": 381, "s": 350, "text": "Method #1 : Using loop + zip()" }, { "code": null, "e": 508, "s": 381, "text": "In this, we iterate for all the paired elements in inner tuples list, which is paired using zip(), and append the result list." }, { "code": null, "e": 516, "s": 508, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # 3D Matrix to Coordinate List# Using loop + zip() # initializing listtest_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]] # printing original listprint(\"The original list is : \" + str(test_list)) res = []for sub1, sub2 in test_list: # zip() used to form pairing for ele in zip(sub1, sub2): res.append(ele) # printing result print(\"Constructed Pairs : \" + str(res))", "e": 969, "s": 516, "text": null }, { "code": null, "e": 1137, "s": 969, "text": "The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]\nConstructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)]\n" }, { "code": null, "e": 1174, "s": 1137, "text": "Method #2 : Using list comprehension" }, { "code": null, "e": 1257, "s": 1174, "text": "In this, we perform task of of above method in shorthand using list comprehension." }, { "code": null, "e": 1265, "s": 1257, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # 3D Matrix to Coordinate List# Using loop + zip() # initializing listtest_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]] # printing original listprint(\"The original list is : \" + str(test_list)) # list comprehension to perform task in shorthandres = [ele for sub1, sub2 in test_list for ele in zip(sub1, sub2)] # printing result print(\"Constructed Pairs : \" + str(res))", "e": 1705, "s": 1265, "text": null }, { "code": null, "e": 1873, "s": 1705, "text": "The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]\nConstructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)]\n" }, { "code": null, "e": 1894, "s": 1873, "text": "Python list-programs" }, { "code": null, "e": 1901, "s": 1894, "text": "Python" }, { "code": null, "e": 1917, "s": 1901, "text": "Python Programs" } ]
How to traverse through all values for a given key in multimap?
12 Jul, 2021 Given a multimap and a key of the multimap, our task is to simply display the (key – value) pairs of the given key. In multimap we can have multiple (key – value) pair for the same key. Suppose our multimap contains key value 1 10 2 20 2 30 2 40 3 50 4 60 4 70 key : 2 key value 2 20 2 30 2 40 Like in unordered_map in C++ STL we cant fetch values like int key = 2; multimap map; // insert values in map cout << "Key : " << key; cout << "Value : " < second; Output : Key : 2 Value : 20 Because the above method will only return the first occurrence of the key present, This method fails if there are multiple (key – value) pairs for the same key.There are two ways by which we can achieve the expected results : Method 1 (Simple Traversal) Traverse through whole map and whenever the key is equal to given key we display the key-value pair. C++ Java Python3 C# Javascript // CPP program to find all values for a// given key.#include <bits/stdc++.h>using namespace std; int main(){ multimap <int, int> map; // insert the values in multimap map.insert(make_pair(1, 10)); map.insert(make_pair(2, 20)); map.insert(make_pair(2, 30)); map.insert(make_pair(2, 40)); map.insert(make_pair(3, 50)); map.insert(make_pair(4, 60)); map.insert(make_pair(4, 70)); int key = 2; for (auto itr = map.begin(); itr != map.end(); itr++) if (itr -> first == key) cout << itr -> first << " " << itr -> second << endl; return 0;} // JAVA program to find all values for a// given key.import java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} public static void main(String[] args){ HashSet <pair> map = new LinkedHashSet<>(); // add the values in multimap map.add(new pair(1, 10)); map.add(new pair(2, 20)); map.add(new pair(2, 30)); map.add(new pair(2, 40)); map.add(new pair(3, 50)); map.add(new pair(4, 60)); map.add(new pair(4, 70)); int key = 2; for (pair itr : map) if (itr.first == key) System.out.println(itr.first+ " " + itr.second);}} // This code is contributed by 29AjayKumar # Python program to find all values for a# given key.map = [] # insert the values in multimapmap.append((1, 10));map.append((2, 20));map.append((2, 30));map.append((2, 40));map.append((3, 50));map.append((4, 60));map.append((4, 70)); key = 2; for i in map: if i[0] == key: print(i[0],i[1]) # This code is contributed by shubhamsingh10 // C# program to find all values for a// given key.using System;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Driver codepublic static void Main(String[] args){ HashSet<pair> map = new HashSet<pair>(); //.Add the values in multimap map.Add(new pair(1, 10)); map.Add(new pair(2, 20)); map.Add(new pair(2, 30)); map.Add(new pair(2, 40)); map.Add(new pair(3, 50)); map.Add(new pair(4, 60)); map.Add(new pair(4, 70)); int key = 2; foreach (pair itr in map) if (itr.first == key) Console.WriteLine(itr.first+ " " + itr.second);}} // This code is contributed by Rajput-Ji <script> class pair{ constructor(first,second) { this.first=first; this.second=second; }} let map = new Set();// add the values in multimapmap.add(new pair(1, 10));map.add(new pair(2, 20));map.add(new pair(2, 30));map.add(new pair(2, 40));map.add(new pair(3, 50));map.add(new pair(4, 60));map.add(new pair(4, 70)); let key = 2;for (let itr of map.values()) if (itr.first == key) document.write(itr.first+ " " + itr.second+"<br>"); // This code is contributed by rag2127</script> Output: 2 20 2 30 2 40 Method 2(Using Binary Search)Find the lower_bound and upper_bound for the given key and traverse between them. lower_bound(key) : returns the iterator pointing to the first element which is greater than or equal to key. upper_bound(key) : returns the iterator pointing to the first element which is greater than key. key value 1 10 2 20 <-- lower_bound(20) 2 30 2 40 3 50 <-- upper_bound(20) 4 60 4 70 CPP #include <bits/stdc++.h>using namespace std; int main(){ multimap <int, int> map; // insert the values in multimap map.insert(make_pair(1, 10)); map.insert(make_pair(2, 20)); map.insert(make_pair(2, 30)); map.insert(make_pair(2, 40)); map.insert(make_pair(3, 50)); map.insert(make_pair(4, 60)); map.insert(make_pair(4, 70)); int key = 2; auto itr1 = map.lower_bound(key); auto itr2 = map.upper_bound(key); while (itr1 != itr2) { if (itr1 -> first == key) cout << itr1 -> first << " " << itr1 -> second << endl; itr1++; } return 0;} Output: 2 20 2 30 2 40 29AjayKumar Rajput-Ji rag2127 SHUBHAMSINGH10 cpp-multimap STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jul, 2021" }, { "code": null, "e": 270, "s": 52, "text": "Given a multimap and a key of the multimap, our task is to simply display the (key – value) pairs of the given key. In multimap we can have multiple (key – value) pair for the same key. Suppose our multimap contains " }, { "code": null, "e": 437, "s": 270, "text": "key value\n1 10\n2 20\n2 30\n2 40\n3 50\n4 60\n4 70\n\nkey : 2\nkey value\n2 20\n2 30\n2 40" }, { "code": null, "e": 498, "s": 437, "text": "Like in unordered_map in C++ STL we cant fetch values like " }, { "code": null, "e": 605, "s": 498, "text": "int key = 2;\nmultimap map;\n\n// insert values in map\ncout << \"Key : \" << key;\ncout << \"Value : \" < second;" }, { "code": null, "e": 616, "s": 605, "text": "Output : " }, { "code": null, "e": 635, "s": 616, "text": "Key : 2\nValue : 20" }, { "code": null, "e": 992, "s": 635, "text": "Because the above method will only return the first occurrence of the key present, This method fails if there are multiple (key – value) pairs for the same key.There are two ways by which we can achieve the expected results : Method 1 (Simple Traversal) Traverse through whole map and whenever the key is equal to given key we display the key-value pair. " }, { "code": null, "e": 996, "s": 992, "text": "C++" }, { "code": null, "e": 1001, "s": 996, "text": "Java" }, { "code": null, "e": 1009, "s": 1001, "text": "Python3" }, { "code": null, "e": 1012, "s": 1009, "text": "C#" }, { "code": null, "e": 1023, "s": 1012, "text": "Javascript" }, { "code": "// CPP program to find all values for a// given key.#include <bits/stdc++.h>using namespace std; int main(){ multimap <int, int> map; // insert the values in multimap map.insert(make_pair(1, 10)); map.insert(make_pair(2, 20)); map.insert(make_pair(2, 30)); map.insert(make_pair(2, 40)); map.insert(make_pair(3, 50)); map.insert(make_pair(4, 60)); map.insert(make_pair(4, 70)); int key = 2; for (auto itr = map.begin(); itr != map.end(); itr++) if (itr -> first == key) cout << itr -> first << \" \" << itr -> second << endl; return 0;}", "e": 1648, "s": 1023, "text": null }, { "code": "// JAVA program to find all values for a// given key.import java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} public static void main(String[] args){ HashSet <pair> map = new LinkedHashSet<>(); // add the values in multimap map.add(new pair(1, 10)); map.add(new pair(2, 20)); map.add(new pair(2, 30)); map.add(new pair(2, 40)); map.add(new pair(3, 50)); map.add(new pair(4, 60)); map.add(new pair(4, 70)); int key = 2; for (pair itr : map) if (itr.first == key) System.out.println(itr.first+ \" \" + itr.second);}} // This code is contributed by 29AjayKumar", "e": 2400, "s": 1648, "text": null }, { "code": "# Python program to find all values for a# given key.map = [] # insert the values in multimapmap.append((1, 10));map.append((2, 20));map.append((2, 30));map.append((2, 40));map.append((3, 50));map.append((4, 60));map.append((4, 70)); key = 2; for i in map: if i[0] == key: print(i[0],i[1]) # This code is contributed by shubhamsingh10", "e": 2747, "s": 2400, "text": null }, { "code": "// C# program to find all values for a// given key.using System;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Driver codepublic static void Main(String[] args){ HashSet<pair> map = new HashSet<pair>(); //.Add the values in multimap map.Add(new pair(1, 10)); map.Add(new pair(2, 20)); map.Add(new pair(2, 30)); map.Add(new pair(2, 40)); map.Add(new pair(3, 50)); map.Add(new pair(4, 60)); map.Add(new pair(4, 70)); int key = 2; foreach (pair itr in map) if (itr.first == key) Console.WriteLine(itr.first+ \" \" + itr.second);}} // This code is contributed by Rajput-Ji", "e": 3537, "s": 2747, "text": null }, { "code": "<script> class pair{ constructor(first,second) { this.first=first; this.second=second; }} let map = new Set();// add the values in multimapmap.add(new pair(1, 10));map.add(new pair(2, 20));map.add(new pair(2, 30));map.add(new pair(2, 40));map.add(new pair(3, 50));map.add(new pair(4, 60));map.add(new pair(4, 70)); let key = 2;for (let itr of map.values()) if (itr.first == key) document.write(itr.first+ \" \" + itr.second+\"<br>\"); // This code is contributed by rag2127</script>", "e": 4072, "s": 3537, "text": null }, { "code": null, "e": 4082, "s": 4072, "text": "Output: " }, { "code": null, "e": 4100, "s": 4082, "text": "2 20\n2 30\n2 40" }, { "code": null, "e": 4419, "s": 4100, "text": "Method 2(Using Binary Search)Find the lower_bound and upper_bound for the given key and traverse between them. lower_bound(key) : returns the iterator pointing to the first element which is greater than or equal to key. upper_bound(key) : returns the iterator pointing to the first element which is greater than key. " }, { "code": null, "e": 4564, "s": 4419, "text": "key value\n1 10\n2 20 <-- lower_bound(20)\n2 30\n2 40\n3 50 <-- upper_bound(20)\n4 60\n4 70" }, { "code": null, "e": 4570, "s": 4566, "text": "CPP" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ multimap <int, int> map; // insert the values in multimap map.insert(make_pair(1, 10)); map.insert(make_pair(2, 20)); map.insert(make_pair(2, 30)); map.insert(make_pair(2, 40)); map.insert(make_pair(3, 50)); map.insert(make_pair(4, 60)); map.insert(make_pair(4, 70)); int key = 2; auto itr1 = map.lower_bound(key); auto itr2 = map.upper_bound(key); while (itr1 != itr2) { if (itr1 -> first == key) cout << itr1 -> first << \" \" << itr1 -> second << endl; itr1++; } return 0;}", "e": 5218, "s": 4570, "text": null }, { "code": null, "e": 5228, "s": 5218, "text": "Output: " }, { "code": null, "e": 5246, "s": 5228, "text": "2 20\n2 30\n2 40" }, { "code": null, "e": 5260, "s": 5248, "text": "29AjayKumar" }, { "code": null, "e": 5270, "s": 5260, "text": "Rajput-Ji" }, { "code": null, "e": 5278, "s": 5270, "text": "rag2127" }, { "code": null, "e": 5293, "s": 5278, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 5306, "s": 5293, "text": "cpp-multimap" }, { "code": null, "e": 5310, "s": 5306, "text": "STL" }, { "code": null, "e": 5314, "s": 5310, "text": "C++" }, { "code": null, "e": 5318, "s": 5314, "text": "STL" }, { "code": null, "e": 5322, "s": 5318, "text": "CPP" } ]
Mathematics | Closure of Relations and Equivalence Relations
13 Dec, 2019 Prerequisite : Introduction to Relations, Representation of Relations Combining Relations : As we know that relations are just sets of ordered pairs, so all set operations apply to them as well. Two relations can be combined in several ways such as – Union – consists of all ordered pairs from both relations. Duplicate ordered pairs removed from Union. Intersection – consists of ordered pairs which are in both relations. Difference – consists of all ordered pairs only in , but not in . Symmetric Difference – consists of all ordered pairs which are either in or but not both. There is another way two relations can be combined that is analogous to the composition of functions. Composition – Let be a relation from to and be a relation from to , then the composite of and , denoted by , is the relation consisting of ordered pairs where and for which there exists an element such that and . Example – What is the composite of the relations and where is a relation from to with and is a relation from to with ? Solution – By computing all ordered pairs where the first element belongs to and the second element belongs to , we get – Composition of Relation on itself : A relation can be composed with itself to obtain a degree of separation between the elements of the set on which is defined. Let be a relation on the set . The powers where are defined recursively by - and . Theorem – Let be a relation on set A, represented by a di-graph. There is a path of length , where is a positive integer, from to if and only if . Important Note : A relation on set is transitive if and only if for Closure of Relations : Consider a relation on set . may or may not have a property , such as reflexivity, symmetry, or transitivity. If there is a relation with property containing such that is the subsetof every relation with property containing , then is called the closure of with respect to . We can obtain closures of relations with respect to property in the following ways – Reflexive Closure – is the diagonal relation on set . The reflexive closure of relation on set is .Symmetric Closure – Let be a relation on set , and let be the inverse of . The symmetric closure of relation on set is .Transitive Closure – Let be a relation on set . The connectivity relation is defined as – . The transitive closure of is . Reflexive Closure – is the diagonal relation on set . The reflexive closure of relation on set is . Symmetric Closure – Let be a relation on set , and let be the inverse of . The symmetric closure of relation on set is . Transitive Closure – Let be a relation on set . The connectivity relation is defined as – . The transitive closure of is . Example – Let be a relation on set with . Find the reflexive, symmetric, and transitive closure of R. Solution –For the given set, . So the reflexive closure of is For the symmetric closure we need the inverse of , which is.The symmetric closure of is- For the transitive closure, we need to find . we need to find until . We stop when this condition is achieved since finding higher powers of would be the same.Since, we stop the process.Transitive closure, – Equivalence Relations : Let be a relation on set . If is reflexive, symmetric, and transitive then it is said to be a equivalence relation.Consequently, two elements and related by an equivalence relation are said to be equivalent. Example – Show that the relation is an equivalence relation. is the congruence modulo function. It is true if and only if divides . Solution – To show that the relation is an equivalence relation we must prove that the relation is reflexive, symmetric and transitive. Reflexive – For any element , is divisible by .. So, congruence modulo is reflexive.Symmetric – For any two elements and , if or i.e. is divisible by , then is also divisible by .. So Congruence Modulo is symmetric.Transitive – For any three elements , , and if then-Adding both equations, . So, is transitive.Since the relation is reflexive, symmetric, and transitive, we conclude that is an equivalence relation.Equivalence Classes :Let be an equivalence relation on set .We know that if then and are said to be equivalent with respect to .The set of all elements that are related to an element of is called theequivalence class of . It is denoted by or simply if there is only onerelation to consider.Formally,Any element is said to be the representative of .Important Note : All the equivalence classes of a Relation on set are either equal or disjoint and their union gives the set .The equivalence classes are also called partitions since they are disjoint and their union gives the set on which the relation is definedExample : What are the equivalence classes of the relation Congruence Modulo ?Solution : Let and be two numbers such that . This means that the remainder obtained by dividing and with is the same.Possible values for the remainder- Therefore, there are equivalence classes – GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.1. GATE CS 2013, Question 12. GATE CS 2005, Question 423. GATE CS 2001, Question 24. GATE CS 2000, Question 28References –Composition of Relations – WikipediaDiscrete Mathematics and its Applications, by Kenneth H RosenThis article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Reflexive – For any element , is divisible by .. So, congruence modulo is reflexive. Symmetric – For any two elements and , if or i.e. is divisible by , then is also divisible by .. So Congruence Modulo is symmetric. Transitive – For any three elements , , and if then-Adding both equations, . So, is transitive. . So, is transitive. Since the relation is reflexive, symmetric, and transitive, we conclude that is an equivalence relation. Equivalence Classes : Let be an equivalence relation on set .We know that if then and are said to be equivalent with respect to . The set of all elements that are related to an element of is called theequivalence class of . It is denoted by or simply if there is only onerelation to consider.Formally, Any element is said to be the representative of .Important Note : All the equivalence classes of a Relation on set are either equal or disjoint and their union gives the set .The equivalence classes are also called partitions since they are disjoint and their union gives the set on which the relation is defined Example : What are the equivalence classes of the relation Congruence Modulo ? Solution : Let and be two numbers such that . This means that the remainder obtained by dividing and with is the same.Possible values for the remainder- Therefore, there are equivalence classes – GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. 1. GATE CS 2013, Question 12. GATE CS 2005, Question 423. GATE CS 2001, Question 24. GATE CS 2000, Question 28 References –Composition of Relations – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. VaibhavRai3 Discrete Mathematics Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Dec, 2019" }, { "code": null, "e": 122, "s": 52, "text": "Prerequisite : Introduction to Relations, Representation of Relations" }, { "code": null, "e": 144, "s": 122, "text": "Combining Relations :" }, { "code": null, "e": 303, "s": 144, "text": "As we know that relations are just sets of ordered pairs, so all set operations apply to them as well. Two relations can be combined in several ways such as –" }, { "code": null, "e": 407, "s": 303, "text": "Union – consists of all ordered pairs from both relations. Duplicate ordered pairs removed from Union." }, { "code": null, "e": 478, "s": 407, "text": "Intersection – consists of ordered pairs which are in both relations." }, { "code": null, "e": 545, "s": 478, "text": "Difference – consists of all ordered pairs only in , but not in ." }, { "code": null, "e": 638, "s": 545, "text": "Symmetric Difference – consists of all ordered pairs which are either in or but not both." }, { "code": null, "e": 740, "s": 638, "text": "There is another way two relations can be combined that is analogous to the composition of functions." }, { "code": null, "e": 963, "s": 740, "text": "Composition – Let be a relation from to and be a relation from to , then the composite of and , denoted by , is the relation consisting of ordered pairs where and for which there exists an element such that and ." }, { "code": null, "e": 1091, "s": 963, "text": "Example – What is the composite of the relations and where is a relation from to with and is a relation from to with ?" }, { "code": null, "e": 1214, "s": 1091, "text": "Solution – By computing all ordered pairs where the first element belongs to and the second element belongs to , we get –" }, { "code": null, "e": 1250, "s": 1214, "text": "Composition of Relation on itself :" }, { "code": null, "e": 1376, "s": 1250, "text": "A relation can be composed with itself to obtain a degree of separation between the elements of the set on which is defined." }, { "code": null, "e": 1464, "s": 1376, "text": "Let be a relation on the set .\nThe powers where are defined recursively by -\n and .\n" }, { "code": null, "e": 1615, "s": 1464, "text": "Theorem – Let be a relation on set A, represented by a di-graph. There is a path of length , where is a positive integer, from to if and only if ." }, { "code": null, "e": 1687, "s": 1615, "text": "Important Note : A relation on set is transitive if and only if for " }, { "code": null, "e": 1710, "s": 1687, "text": "Closure of Relations :" }, { "code": null, "e": 1822, "s": 1710, "text": "Consider a relation on set . may or may not have a property , such as reflexivity, symmetry, or transitivity." }, { "code": null, "e": 1992, "s": 1822, "text": "If there is a relation with property containing such that is the subsetof every relation with property containing , then is called the closure of with respect to ." }, { "code": null, "e": 2078, "s": 1992, "text": "We can obtain closures of relations with respect to property in the following ways –" }, { "code": null, "e": 2429, "s": 2078, "text": "Reflexive Closure – is the diagonal relation on set . The reflexive closure of relation on set is .Symmetric Closure – Let be a relation on set , and let be the inverse of . The symmetric closure of relation on set is .Transitive Closure – Let be a relation on set . The connectivity relation is defined as – . The transitive closure of is ." }, { "code": null, "e": 2532, "s": 2429, "text": "Reflexive Closure – is the diagonal relation on set . The reflexive closure of relation on set is ." }, { "code": null, "e": 2657, "s": 2532, "text": "Symmetric Closure – Let be a relation on set , and let be the inverse of . The symmetric closure of relation on set is ." }, { "code": null, "e": 2782, "s": 2657, "text": "Transitive Closure – Let be a relation on set . The connectivity relation is defined as – . The transitive closure of is ." }, { "code": null, "e": 2886, "s": 2782, "text": "Example – Let be a relation on set with . Find the reflexive, symmetric, and transitive closure of R." }, { "code": null, "e": 2950, "s": 2886, "text": "Solution –For the given set, . So the reflexive closure of is " }, { "code": null, "e": 3040, "s": 2950, "text": "For the symmetric closure we need the inverse of , which is.The symmetric closure of is-" }, { "code": null, "e": 3252, "s": 3040, "text": "For the transitive closure, we need to find . we need to find until . We stop when this condition is achieved since finding higher powers of would be the same.Since, we stop the process.Transitive closure, –" }, { "code": null, "e": 3276, "s": 3252, "text": "Equivalence Relations :" }, { "code": null, "e": 3488, "s": 3276, "text": "Let be a relation on set . If is reflexive, symmetric, and transitive then it is said to be a equivalence relation.Consequently, two elements and related by an equivalence relation are said to be equivalent." }, { "code": null, "e": 3623, "s": 3488, "text": "Example – Show that the relation is an equivalence relation. is the congruence modulo function. It is true if and only if divides ." }, { "code": null, "e": 3759, "s": 3623, "text": "Solution – To show that the relation is an equivalence relation we must prove that the relation is reflexive, symmetric and transitive." }, { "code": null, "e": 5992, "s": 3759, "text": "Reflexive – For any element , is divisible by .. So, congruence modulo is reflexive.Symmetric – For any two elements and , if or i.e. is divisible by , then is also divisible by .. So Congruence Modulo is symmetric.Transitive – For any three elements , , and if then-Adding both equations, . So, is transitive.Since the relation is reflexive, symmetric, and transitive, we conclude that is an equivalence relation.Equivalence Classes :Let be an equivalence relation on set .We know that if then and are said to be equivalent with respect to .The set of all elements that are related to an element of is called theequivalence class of . It is denoted by or simply if there is only onerelation to consider.Formally,Any element is said to be the representative of .Important Note : All the equivalence classes of a Relation on set are either equal or disjoint and their union gives the set .The equivalence classes are also called partitions since they are disjoint and their union gives the set on which the relation is definedExample : What are the equivalence classes of the relation Congruence Modulo ?Solution : Let and be two numbers such that . This means that the remainder obtained by dividing and with is the same.Possible values for the remainder- Therefore, there are equivalence classes – GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.1. GATE CS 2013, Question 12. GATE CS 2005, Question 423. GATE CS 2001, Question 24. GATE CS 2000, Question 28References –Composition of Relations – WikipediaDiscrete Mathematics and its Applications, by Kenneth H RosenThis article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 6079, "s": 5992, "text": "Reflexive – For any element , is divisible by .. So, congruence modulo is reflexive." }, { "code": null, "e": 6217, "s": 6079, "text": "Symmetric – For any two elements and , if or i.e. is divisible by , then is also divisible by .. So Congruence Modulo is symmetric." }, { "code": null, "e": 6319, "s": 6217, "text": "Transitive – For any three elements , , and if then-Adding both equations, . So, is transitive." }, { "code": null, "e": 6346, "s": 6324, "text": ". So, is transitive." }, { "code": null, "e": 6453, "s": 6346, "text": "Since the relation is reflexive, symmetric, and transitive, we conclude that is an equivalence relation." }, { "code": null, "e": 6475, "s": 6453, "text": "Equivalence Classes :" }, { "code": null, "e": 6587, "s": 6475, "text": "Let be an equivalence relation on set .We know that if then and are said to be equivalent with respect to ." }, { "code": null, "e": 6763, "s": 6587, "text": "The set of all elements that are related to an element of is called theequivalence class of . It is denoted by or simply if there is only onerelation to consider.Formally," }, { "code": null, "e": 7079, "s": 6763, "text": "Any element is said to be the representative of .Important Note : All the equivalence classes of a Relation on set are either equal or disjoint and their union gives the set .The equivalence classes are also called partitions since they are disjoint and their union gives the set on which the relation is defined" }, { "code": null, "e": 7158, "s": 7079, "text": "Example : What are the equivalence classes of the relation Congruence Modulo ?" }, { "code": null, "e": 7361, "s": 7158, "text": "Solution : Let and be two numbers such that . This means that the remainder obtained by dividing and with is the same.Possible values for the remainder- Therefore, there are equivalence classes – " }, { "code": null, "e": 7386, "s": 7361, "text": "GATE CS Corner Questions" }, { "code": null, "e": 7584, "s": 7386, "text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 7695, "s": 7584, "text": "1. GATE CS 2013, Question 12. GATE CS 2005, Question 423. GATE CS 2001, Question 24. GATE CS 2000, Question 28" }, { "code": null, "e": 7805, "s": 7695, "text": "References –Composition of Relations – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen" }, { "code": null, "e": 8107, "s": 7805, "text": "This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8232, "s": 8107, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8244, "s": 8232, "text": "VaibhavRai3" }, { "code": null, "e": 8265, "s": 8244, "text": "Discrete Mathematics" }, { "code": null, "e": 8289, "s": 8265, "text": "Engineering Mathematics" }, { "code": null, "e": 8297, "s": 8289, "text": "GATE CS" } ]
How to concatenate regex literals in JavaScript ?
05 Jun, 2020 Regex is a sequence of pattern that is used for matching with a pattern. While searching for data in a text, the search pattern is described for what we are searching for. It can be a single character or a more complex pattern. It can be used to perform all types of text searches. Regex has its own static and instance properties. Syntax: /pattern/modifiers Example: A regular expression. /gfg/g Where, gfg is a pattern (to be used in a search). g is a modifier (modifies the search to be case-insensitive). The concatenation of Regex in the programming world can be understood as combining text patternsto obtain a new text pattern, such as “Hello” + “World” is /HelloWorld/. Whenever RegExp() is called, it creates a new RegExp object. Example 1: This example creating an expression without actually using the Regex literal syntax. This allows you to make arbitrary string manipulation before it becomes a Regex object. <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width,initial-scale=1.0" /> <title> Concatenation of Regex </title> </head> <body> <h3>The concatenation of Regex </h3> <hr> <script> function gfg() { var segment_part = " GeeksforGeeks |" + " A computer science portal for geeks"; var pattern = new RegExp("GFG:" + /*comment here */ segment_part + /* that was defined just now */ "is a computer science portal"); document.write(pattern); } gfg(); </script></body> </html> Output: Example 2: If you have two Regex literals, you can concatenate them using a technique where it removes duplicates, but keep the unique values in order, joining both the regex literals. Example: /hello/y + / world/g would be /hello world/gy <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"/> <title> Concatenation of Regex </title></head> <body> <h3>Concatenation of Regex </h3> <hr> <script> function gfg() { var regex1 = /geeks/g; var regex2 = / for geeks/y; var flags = (regex1.flags + regex2.flags).split("") .sort().join("") .replace(/(.)(?=.*\1)/g, ""); var regex3 = new RegExp(regex1.source + regex2.source, flags); document.write(regex3); } gfg(); </script></body> </html> Output: HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 360, "s": 28, "text": "Regex is a sequence of pattern that is used for matching with a pattern. While searching for data in a text, the search pattern is described for what we are searching for. It can be a single character or a more complex pattern. It can be used to perform all types of text searches. Regex has its own static and instance properties." }, { "code": null, "e": 368, "s": 360, "text": "Syntax:" }, { "code": null, "e": 388, "s": 368, "text": "/pattern/modifiers\n" }, { "code": null, "e": 419, "s": 388, "text": "Example: A regular expression." }, { "code": null, "e": 426, "s": 419, "text": "/gfg/g" }, { "code": null, "e": 433, "s": 426, "text": "Where," }, { "code": null, "e": 476, "s": 433, "text": "gfg is a pattern (to be used in a search)." }, { "code": null, "e": 538, "s": 476, "text": "g is a modifier (modifies the search to be case-insensitive)." }, { "code": null, "e": 768, "s": 538, "text": "The concatenation of Regex in the programming world can be understood as combining text patternsto obtain a new text pattern, such as “Hello” + “World” is /HelloWorld/. Whenever RegExp() is called, it creates a new RegExp object." }, { "code": null, "e": 952, "s": 768, "text": "Example 1: This example creating an expression without actually using the Regex literal syntax. This allows you to make arbitrary string manipulation before it becomes a Regex object." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width,initial-scale=1.0\" /> <title> Concatenation of Regex </title> </head> <body> <h3>The concatenation of Regex </h3> <hr> <script> function gfg() { var segment_part = \" GeeksforGeeks |\" + \" A computer science portal for geeks\"; var pattern = new RegExp(\"GFG:\" + /*comment here */ segment_part + /* that was defined just now */ \"is a computer science portal\"); document.write(pattern); } gfg(); </script></body> </html>", "e": 1646, "s": 952, "text": null }, { "code": null, "e": 1654, "s": 1646, "text": "Output:" }, { "code": null, "e": 1839, "s": 1654, "text": "Example 2: If you have two Regex literals, you can concatenate them using a technique where it removes duplicates, but keep the unique values in order, joining both the regex literals." }, { "code": null, "e": 1894, "s": 1839, "text": "Example: /hello/y + / world/g would be /hello world/gy" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"/> <title> Concatenation of Regex </title></head> <body> <h3>Concatenation of Regex </h3> <hr> <script> function gfg() { var regex1 = /geeks/g; var regex2 = / for geeks/y; var flags = (regex1.flags + regex2.flags).split(\"\") .sort().join(\"\") .replace(/(.)(?=.*\\1)/g, \"\"); var regex3 = new RegExp(regex1.source + regex2.source, flags); document.write(regex3); } gfg(); </script></body> </html>", "e": 2626, "s": 1894, "text": null }, { "code": null, "e": 2634, "s": 2626, "text": "Output:" }, { "code": null, "e": 2644, "s": 2634, "text": "HTML-Misc" }, { "code": null, "e": 2660, "s": 2644, "text": "JavaScript-Misc" }, { "code": null, "e": 2667, "s": 2660, "text": "Picked" }, { "code": null, "e": 2672, "s": 2667, "text": "HTML" }, { "code": null, "e": 2683, "s": 2672, "text": "JavaScript" }, { "code": null, "e": 2700, "s": 2683, "text": "Web Technologies" }, { "code": null, "e": 2727, "s": 2700, "text": "Web technologies Questions" }, { "code": null, "e": 2732, "s": 2727, "text": "HTML" }, { "code": null, "e": 2830, "s": 2732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2854, "s": 2830, "text": "REST API (Introduction)" }, { "code": null, "e": 2891, "s": 2854, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2919, "s": 2891, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 2958, "s": 2919, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3008, "s": 2958, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3069, "s": 3008, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3141, "s": 3069, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3181, "s": 3141, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3223, "s": 3181, "text": "Roadmap to Learn JavaScript For Beginners" } ]
How to remove brackets from text file in Python ?
21 Feb, 2022 Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions. Syntax: # import re module for using regular expression import re patn = re.sub(pattern, repl, sentence) # pattern is the special RE expression for finding the brackets. # repl is a string which replaces with the selected things by pattern # RE is searched in sentence string The regex pattern used for performing our task: Note: Here, we have used 2 syntactic characters of regex for doing this- [...] is a character class that is used to match any one of the characters presents between them \ is used for matching the special characters for this, we have brackets as a special character Here is how it works: Example 1: Program for removing the brackets with regular expressions from the string Python3 # importing re module for creating# regex expressionimport re # string for passingtext = "Welcome to geeks for geeks [GFG] A (computer science portal)" # creating the regex pattern & use re.sub()# [\([{})\]] is a RE pattern for selecting# '{', '}', '[', ']', '(', ')' brackets.patn = re.sub(r"[\([{})\]]", "", text) print(patn) Output: Welcome to geeks for geeks GFG A computer science portal Now seems like our script is working well. Let’s try the same in a text file. Python enables us to handle files. Note: For more information, refer File handling in Python. Example 2: Program for removing brackets from the text file File Used: Python3 # importing re module for creating# regex expressionimport re # reading line by linewith open('data.txt', 'r') as f: # looping the para and iterating # each line text = f.read() # getting the pattern for [],(),{} # brackets and replace them to empty # string # creating the regex pattern & use re.sub() patn = re.sub(r"[\([{})\]]", "", text) print(patn) Output: Example 2: Appending the changes to a new text file File Used: Python3 # importing re module for creating# regex expressionimport re # reading line by linewith open('input.txt', 'r') as f: # store in text variable text = f.read() # getting the pattern for [],(),{} # brackets and replace them to empty string # creating the regex pattern & use re.sub() pattern = re.sub(r"[\([{})\]]", "", text) # Appending the changes in new file# It will create new file in the directory# and write the changes in the file.with open('output.txt', 'w') as my_file: my_file.write(pattern) Output: rs1686740 as5853535 Picked python-file-handling python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2022" }, { "code": null, "e": 228, "s": 28, "text": "Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions. " }, { "code": null, "e": 236, "s": 228, "text": "Syntax:" }, { "code": null, "e": 284, "s": 236, "text": "# import re module for using regular expression" }, { "code": null, "e": 294, "s": 284, "text": "import re" }, { "code": null, "e": 334, "s": 294, "text": "patn = re.sub(pattern, repl, sentence)" }, { "code": null, "e": 399, "s": 334, "text": "# pattern is the special RE expression for finding the brackets." }, { "code": null, "e": 469, "s": 399, "text": "# repl is a string which replaces with the selected things by pattern" }, { "code": null, "e": 505, "s": 469, "text": "# RE is searched in sentence string" }, { "code": null, "e": 553, "s": 505, "text": "The regex pattern used for performing our task:" }, { "code": null, "e": 626, "s": 553, "text": "Note: Here, we have used 2 syntactic characters of regex for doing this-" }, { "code": null, "e": 723, "s": 626, "text": "[...] is a character class that is used to match any one of the characters presents between them" }, { "code": null, "e": 819, "s": 723, "text": "\\ is used for matching the special characters for this, we have brackets as a special character" }, { "code": null, "e": 841, "s": 819, "text": "Here is how it works:" }, { "code": null, "e": 927, "s": 841, "text": "Example 1: Program for removing the brackets with regular expressions from the string" }, { "code": null, "e": 935, "s": 927, "text": "Python3" }, { "code": "# importing re module for creating# regex expressionimport re # string for passingtext = \"Welcome to geeks for geeks [GFG] A (computer science portal)\" # creating the regex pattern & use re.sub()# [\\([{})\\]] is a RE pattern for selecting# '{', '}', '[', ']', '(', ')' brackets.patn = re.sub(r\"[\\([{})\\]]\", \"\", text) print(patn)", "e": 1263, "s": 935, "text": null }, { "code": null, "e": 1271, "s": 1263, "text": "Output:" }, { "code": null, "e": 1328, "s": 1271, "text": "Welcome to geeks for geeks GFG A computer science portal" }, { "code": null, "e": 1442, "s": 1328, "text": "Now seems like our script is working well. Let’s try the same in a text file. Python enables us to handle files. " }, { "code": null, "e": 1501, "s": 1442, "text": "Note: For more information, refer File handling in Python." }, { "code": null, "e": 1561, "s": 1501, "text": "Example 2: Program for removing brackets from the text file" }, { "code": null, "e": 1573, "s": 1561, "text": "File Used: " }, { "code": null, "e": 1581, "s": 1573, "text": "Python3" }, { "code": "# importing re module for creating# regex expressionimport re # reading line by linewith open('data.txt', 'r') as f: # looping the para and iterating # each line text = f.read() # getting the pattern for [],(),{} # brackets and replace them to empty # string # creating the regex pattern & use re.sub() patn = re.sub(r\"[\\([{})\\]]\", \"\", text) print(patn)", "e": 1967, "s": 1581, "text": null }, { "code": null, "e": 1978, "s": 1970, "text": "Output:" }, { "code": null, "e": 2034, "s": 1982, "text": "Example 2: Appending the changes to a new text file" }, { "code": null, "e": 2047, "s": 2036, "text": "File Used:" }, { "code": null, "e": 2059, "s": 2051, "text": "Python3" }, { "code": "# importing re module for creating# regex expressionimport re # reading line by linewith open('input.txt', 'r') as f: # store in text variable text = f.read() # getting the pattern for [],(),{} # brackets and replace them to empty string # creating the regex pattern & use re.sub() pattern = re.sub(r\"[\\([{})\\]]\", \"\", text) # Appending the changes in new file# It will create new file in the directory# and write the changes in the file.with open('output.txt', 'w') as my_file: my_file.write(pattern)", "e": 2590, "s": 2059, "text": null }, { "code": null, "e": 2598, "s": 2590, "text": "Output:" }, { "code": null, "e": 2608, "s": 2598, "text": "rs1686740" }, { "code": null, "e": 2618, "s": 2608, "text": "as5853535" }, { "code": null, "e": 2625, "s": 2618, "text": "Picked" }, { "code": null, "e": 2646, "s": 2625, "text": "python-file-handling" }, { "code": null, "e": 2659, "s": 2646, "text": "python-regex" }, { "code": null, "e": 2666, "s": 2659, "text": "Python" } ]
How to Use Enum, Constructor, Instance Variable & Method in Java?
16 Sep, 2021 Enumerations serve the purpose of representing a group of named constants in a programming language. Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java, enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types). Note: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. Now coming to our problem description as it is to illustrate how to use enum Constructor, Instance Variable & Method in Java. So, for this solution, we will see the below example initializes enum using a constructor & totalPrice() method & displays values of enums. Example Java // Java program to Illustrate Usage of Enum// Constructor, Instance Variable & Method // Importing required classesimport java.io.*;import java.util.*; // Enumenum fruits { // Attributes associated to enum Apple(120), Kiwi(60), Banana(20), Orange(80); // internal data private int price; // Constructor fruits(int pr) { price = pr; } // Method int totalPrice() { return price; }} // Main classclass GFG { // main driver method public static void main(String[] args) { // Print statement System.out.println("Total price of fruits : "); // Iterating using enhanced for each loop for (fruits f : fruits.values()) // Print anddispaly the cost and perkg cost of // fruits System.out.println(f + " costs " + f.totalPrice() + " rupees per kg."); }} Total price of fruits : Apple costs 120 rupees per kg. Kiwi costs 60 rupees per kg. Banana costs 20 rupees per kg. Orange costs 80 rupees per kg. vsai5120 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Sep, 2021" }, { "code": null, "e": 601, "s": 28, "text": "Enumerations serve the purpose of representing a group of named constants in a programming language. Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java, enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types)." }, { "code": null, "e": 722, "s": 601, "text": "Note: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block." }, { "code": null, "e": 988, "s": 722, "text": "Now coming to our problem description as it is to illustrate how to use enum Constructor, Instance Variable & Method in Java. So, for this solution, we will see the below example initializes enum using a constructor & totalPrice() method & displays values of enums." }, { "code": null, "e": 996, "s": 988, "text": "Example" }, { "code": null, "e": 1001, "s": 996, "text": "Java" }, { "code": "// Java program to Illustrate Usage of Enum// Constructor, Instance Variable & Method // Importing required classesimport java.io.*;import java.util.*; // Enumenum fruits { // Attributes associated to enum Apple(120), Kiwi(60), Banana(20), Orange(80); // internal data private int price; // Constructor fruits(int pr) { price = pr; } // Method int totalPrice() { return price; }} // Main classclass GFG { // main driver method public static void main(String[] args) { // Print statement System.out.println(\"Total price of fruits : \"); // Iterating using enhanced for each loop for (fruits f : fruits.values()) // Print anddispaly the cost and perkg cost of // fruits System.out.println(f + \" costs \" + f.totalPrice() + \" rupees per kg.\"); }}", "e": 1915, "s": 1001, "text": null }, { "code": null, "e": 2062, "s": 1915, "text": "Total price of fruits : \nApple costs 120 rupees per kg.\nKiwi costs 60 rupees per kg.\nBanana costs 20 rupees per kg.\nOrange costs 80 rupees per kg." }, { "code": null, "e": 2071, "s": 2062, "text": "vsai5120" }, { "code": null, "e": 2078, "s": 2071, "text": "Picked" }, { "code": null, "e": 2102, "s": 2078, "text": "Technical Scripter 2020" }, { "code": null, "e": 2107, "s": 2102, "text": "Java" }, { "code": null, "e": 2121, "s": 2107, "text": "Java Programs" }, { "code": null, "e": 2140, "s": 2121, "text": "Technical Scripter" }, { "code": null, "e": 2145, "s": 2140, "text": "Java" } ]
Java Stream API – Filters
02 Nov, 2020 In this article, we will learn Java Stream Filter API. We will cover, 1. How stream filter API works. 2. Filter by Object Properties. 3. Filter by Index. 4. Filter by custom Object properties. Stream Filter API Filter API takes a Predicate. The predicate is a Functional Interface. It takes an argument of any type and returns Boolean. The element will be considered for the next API in the pipeline if the function returns true. Otherwise, the element is filtered out. Java // Java code for Stream filter// (Predicate predicate) to get a stream// consisting of the elements of this// stream that match the given predicate. import java.io.*;import java.util.stream.Stream; class StreamFilterExample { public static void main(String[] args) { // create a stream of strings Stream<String> myStream = Stream.of("Like", "and", "Share", "https://www.geeksforgeeks.org/"); // only string starting with "http://" will be // considered for next API(forEach) myStream.filter(x -> x.startsWith("https://")) .forEach(System.out::println); }} https://www.geeksforgeeks.org/ Filter by Object Properties Filter by Object properties uses java operators. The below example explains how to filter by properties of an object. Java // Java program to demonstrate // filter by Object properties import java.io.*;import java.util.stream.Stream; class FilterByObjectProperties { public static void filterByEvenElements() { // create integer array Integer[] myArray = new Integer[] { 1, 4, 5, 7, 9, 10 }; // create a stream and filter by // even numbers predicate Stream.of(myArray) .filter(x -> x % 2 == 0) .forEach(System.out::println); } public static void filterByStartsWith() { // create String array String[] myArray = new String[] { "stream", "is", "a", "sequence", "of", "elements", "like", "list" }; // create a stream and filter by // starting string predicate Stream<String> myStream = Stream.of(myArray); myStream.filter(x -> x.startsWith("s")) .forEach(System.out::println); } public static void filterByStartsWithVowelsRegex() { // create string array String[] myArray = "I am 24 years old and I want to be in Tier I company" .split(" "); // create a stream on myArray Stream<String> myStream = Stream.of(myArray); // filter by matching vowels regular expression myStream.filter(x -> x.matches("(a|e|i|o|u)\\w*")) .forEach(System.out::println); } public static void main(String[] args) { // filters a stream by even elements filterByEvenElements(); System.out.println("======"); // filters a stream by starting string filterByStartsWith(); System.out.println("======"); // filters a stream by starting vowel filterByStartsWithVowelsRegex(); }} 4 10 ====== stream sequence ====== am old and in Filter by Object Indices Filtering by indexes can be done in two ways. 1. Atomic Integers We need to use AtomicInteger because predicates expect final variables as parameters. As long as filter function(Predicate) returns boolean we can use any expression. Here, getAndIncrement() method of AtomicInteger increments the current value by 1 and returns final int value. Java // Java program to demonstrate // filter by Object Indices// using AtomicInteger import java.io.*;import java.util.stream.Stream;import java.util.concurrent.atomic.AtomicInteger; class FilterByObjectIndex { public static void filterByIndexUsingAtomic() { // create a string array String[] myArray = new String[] { "stream", "is", "a", "sequence", "of", "elements", "like", "list" }; // create a stream on myArray Stream<String> myStream = Stream.of(myArray); // create an AtomicInteger AtomicInteger i = new AtomicInteger(0); // increment the i value by 1 everytime // if it is even, print the current element myStream.filter(x -> i.getAndIncrement() % 2 == 0) .forEach(System.out::println); } public static void main(String[] args) { // filter by Object index filterByIndexUsingAtomic(); }} stream a of like 2. Intstream Approach We can use Intstream and map the array elements based on the index. Here first we create an Intstream of a range of numbers. Check if a number is even, then overwrite/map the integer with the array element. Java // Java program to demonstrate // filter by Object properties// using IntSteam Approach import java.io.*;import java.util.stream.IntStream;class FilterByObjectIndexUsingIntStream { public static void filterByIndexUsingStream() { // create an array of Strings String[] myArray = new String[] { "stream", "is", "a", "sequence", "of", "elements", "like", "list" }; // create instream on range of integers // filter by even integer and map // the integer to the Object of myArray IntStream.rangeClosed(0, myArray.length - 1) .filter(x -> x % 2 == 0) .mapToObj(x -> myArray[x]) .forEach(System.out::println); } public static void main(String[] args) { filterByIndexUsingStream(); }} stream a of like Filter by Custom Properties We can use any Java Object property for filtering. Here we are filtering by age. Java // Java program to demonstrate // filter by Custom Properties import java.io.*;import java.util.List;import java.util.Arrays;import java.util.stream.Stream;class CustomFiltering { // Employee class class Employee { // attributes of an Employee String name; int age; // constructor Employee(String name, int age) { this.name = name; this.age = age; } // Override toString to print // provided content when an Object // is printed @Override public String toString() { return "Employee [name=" + name + "]"; } } public static void filterByAge() { // create list of Employees List<Employee> myList = Arrays.asList( new GFG().new Employee("Ram", 25), new GFG().new Employee("Kumar", 40), new GFG().new Employee("Rakesh", 35)); // create a stream on the list // filter by age of an employee myList.stream() .filter(x -> x.age >= 35) .forEach(System.out::println); } public static void main(String[] args) { filterByAge(); }} Employee [name=Kumar] Employee [name=Rakesh] We can also create a custom function for filtering. The function must take a parameter and return a boolean value. Java // Java program to demonstrate// Custom filter import java.io.*;import java.util.stream.Stream;class CustomFilterExample { public static void filterByCustomProperties() { // create a string array String[] myArray = new String[] { "madam", "please", "refer", "link", "on", "racecar" }; // filter using a custom method Stream.of(myArray) .filter(x -> palindrome(x)) .forEach(System.out::println); } // checks if palindrome or not public static boolean palindrome(String s) { if (s.length() <= 1) return true; else return (s.charAt(0) == s.charAt(s.length() - 1)) && palindrome( s.substring(1, s.length() - 1)); } public static void main(String[] args) { filterByCustomProperties(); }} madam refer racecar java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2020" }, { "code": null, "e": 98, "s": 28, "text": "In this article, we will learn Java Stream Filter API. We will cover," }, { "code": null, "e": 130, "s": 98, "text": "1. How stream filter API works." }, { "code": null, "e": 162, "s": 130, "text": "2. Filter by Object Properties." }, { "code": null, "e": 182, "s": 162, "text": "3. Filter by Index." }, { "code": null, "e": 221, "s": 182, "text": "4. Filter by custom Object properties." }, { "code": null, "e": 239, "s": 221, "text": "Stream Filter API" }, { "code": null, "e": 498, "s": 239, "text": "Filter API takes a Predicate. The predicate is a Functional Interface. It takes an argument of any type and returns Boolean. The element will be considered for the next API in the pipeline if the function returns true. Otherwise, the element is filtered out." }, { "code": null, "e": 503, "s": 498, "text": "Java" }, { "code": "// Java code for Stream filter// (Predicate predicate) to get a stream// consisting of the elements of this// stream that match the given predicate. import java.io.*;import java.util.stream.Stream; class StreamFilterExample { public static void main(String[] args) { // create a stream of strings Stream<String> myStream = Stream.of(\"Like\", \"and\", \"Share\", \"https://www.geeksforgeeks.org/\"); // only string starting with \"http://\" will be // considered for next API(forEach) myStream.filter(x -> x.startsWith(\"https://\")) .forEach(System.out::println); }}", "e": 1152, "s": 503, "text": null }, { "code": null, "e": 1185, "s": 1152, "text": "https://www.geeksforgeeks.org/\n\n" }, { "code": null, "e": 1213, "s": 1185, "text": "Filter by Object Properties" }, { "code": null, "e": 1331, "s": 1213, "text": "Filter by Object properties uses java operators. The below example explains how to filter by properties of an object." }, { "code": null, "e": 1336, "s": 1331, "text": "Java" }, { "code": "// Java program to demonstrate // filter by Object properties import java.io.*;import java.util.stream.Stream; class FilterByObjectProperties { public static void filterByEvenElements() { // create integer array Integer[] myArray = new Integer[] { 1, 4, 5, 7, 9, 10 }; // create a stream and filter by // even numbers predicate Stream.of(myArray) .filter(x -> x % 2 == 0) .forEach(System.out::println); } public static void filterByStartsWith() { // create String array String[] myArray = new String[] { \"stream\", \"is\", \"a\", \"sequence\", \"of\", \"elements\", \"like\", \"list\" }; // create a stream and filter by // starting string predicate Stream<String> myStream = Stream.of(myArray); myStream.filter(x -> x.startsWith(\"s\")) .forEach(System.out::println); } public static void filterByStartsWithVowelsRegex() { // create string array String[] myArray = \"I am 24 years old and I want to be in Tier I company\" .split(\" \"); // create a stream on myArray Stream<String> myStream = Stream.of(myArray); // filter by matching vowels regular expression myStream.filter(x -> x.matches(\"(a|e|i|o|u)\\\\w*\")) .forEach(System.out::println); } public static void main(String[] args) { // filters a stream by even elements filterByEvenElements(); System.out.println(\"======\"); // filters a stream by starting string filterByStartsWith(); System.out.println(\"======\"); // filters a stream by starting vowel filterByStartsWithVowelsRegex(); }}", "e": 3149, "s": 1336, "text": null }, { "code": null, "e": 3200, "s": 3149, "text": "4\n10\n======\nstream\nsequence\n======\nam\nold\nand\nin\n\n" }, { "code": null, "e": 3225, "s": 3200, "text": "Filter by Object Indices" }, { "code": null, "e": 3271, "s": 3225, "text": "Filtering by indexes can be done in two ways." }, { "code": null, "e": 3290, "s": 3271, "text": "1. Atomic Integers" }, { "code": null, "e": 3568, "s": 3290, "text": "We need to use AtomicInteger because predicates expect final variables as parameters. As long as filter function(Predicate) returns boolean we can use any expression. Here, getAndIncrement() method of AtomicInteger increments the current value by 1 and returns final int value." }, { "code": null, "e": 3573, "s": 3568, "text": "Java" }, { "code": "// Java program to demonstrate // filter by Object Indices// using AtomicInteger import java.io.*;import java.util.stream.Stream;import java.util.concurrent.atomic.AtomicInteger; class FilterByObjectIndex { public static void filterByIndexUsingAtomic() { // create a string array String[] myArray = new String[] { \"stream\", \"is\", \"a\", \"sequence\", \"of\", \"elements\", \"like\", \"list\" }; // create a stream on myArray Stream<String> myStream = Stream.of(myArray); // create an AtomicInteger AtomicInteger i = new AtomicInteger(0); // increment the i value by 1 everytime // if it is even, print the current element myStream.filter(x -> i.getAndIncrement() % 2 == 0) .forEach(System.out::println); } public static void main(String[] args) { // filter by Object index filterByIndexUsingAtomic(); }}", "e": 4558, "s": 3573, "text": null }, { "code": null, "e": 4577, "s": 4558, "text": "stream\na\nof\nlike\n\n" }, { "code": null, "e": 4599, "s": 4577, "text": "2. Intstream Approach" }, { "code": null, "e": 4806, "s": 4599, "text": "We can use Intstream and map the array elements based on the index. Here first we create an Intstream of a range of numbers. Check if a number is even, then overwrite/map the integer with the array element." }, { "code": null, "e": 4811, "s": 4806, "text": "Java" }, { "code": "// Java program to demonstrate // filter by Object properties// using IntSteam Approach import java.io.*;import java.util.stream.IntStream;class FilterByObjectIndexUsingIntStream { public static void filterByIndexUsingStream() { // create an array of Strings String[] myArray = new String[] { \"stream\", \"is\", \"a\", \"sequence\", \"of\", \"elements\", \"like\", \"list\" }; // create instream on range of integers // filter by even integer and map // the integer to the Object of myArray IntStream.rangeClosed(0, myArray.length - 1) .filter(x -> x % 2 == 0) .mapToObj(x -> myArray[x]) .forEach(System.out::println); } public static void main(String[] args) { filterByIndexUsingStream(); }}", "e": 5671, "s": 4811, "text": null }, { "code": null, "e": 5690, "s": 5671, "text": "stream\na\nof\nlike\n\n" }, { "code": null, "e": 5718, "s": 5690, "text": "Filter by Custom Properties" }, { "code": null, "e": 5799, "s": 5718, "text": "We can use any Java Object property for filtering. Here we are filtering by age." }, { "code": null, "e": 5804, "s": 5799, "text": "Java" }, { "code": "// Java program to demonstrate // filter by Custom Properties import java.io.*;import java.util.List;import java.util.Arrays;import java.util.stream.Stream;class CustomFiltering { // Employee class class Employee { // attributes of an Employee String name; int age; // constructor Employee(String name, int age) { this.name = name; this.age = age; } // Override toString to print // provided content when an Object // is printed @Override public String toString() { return \"Employee [name=\" + name + \"]\"; } } public static void filterByAge() { // create list of Employees List<Employee> myList = Arrays.asList( new GFG().new Employee(\"Ram\", 25), new GFG().new Employee(\"Kumar\", 40), new GFG().new Employee(\"Rakesh\", 35)); // create a stream on the list // filter by age of an employee myList.stream() .filter(x -> x.age >= 35) .forEach(System.out::println); } public static void main(String[] args) { filterByAge(); }}", "e": 6986, "s": 5804, "text": null }, { "code": null, "e": 7033, "s": 6986, "text": "Employee [name=Kumar]\nEmployee [name=Rakesh]\n\n" }, { "code": null, "e": 7148, "s": 7033, "text": "We can also create a custom function for filtering. The function must take a parameter and return a boolean value." }, { "code": null, "e": 7153, "s": 7148, "text": "Java" }, { "code": "// Java program to demonstrate// Custom filter import java.io.*;import java.util.stream.Stream;class CustomFilterExample { public static void filterByCustomProperties() { // create a string array String[] myArray = new String[] { \"madam\", \"please\", \"refer\", \"link\", \"on\", \"racecar\" }; // filter using a custom method Stream.of(myArray) .filter(x -> palindrome(x)) .forEach(System.out::println); } // checks if palindrome or not public static boolean palindrome(String s) { if (s.length() <= 1) return true; else return (s.charAt(0) == s.charAt(s.length() - 1)) && palindrome( s.substring(1, s.length() - 1)); } public static void main(String[] args) { filterByCustomProperties(); }}", "e": 8051, "s": 7153, "text": null }, { "code": null, "e": 8073, "s": 8051, "text": "madam\nrefer\nracecar\n\n" }, { "code": null, "e": 8085, "s": 8073, "text": "java-stream" }, { "code": null, "e": 8090, "s": 8085, "text": "Java" }, { "code": null, "e": 8095, "s": 8090, "text": "Java" } ]
Set in Java
08 Jul, 2022 The set interface is present in java.util package and extends the Collection interface is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the set implementation namely SortedSet and NavigableSet. In the above image, the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree. Declaration: The Set interface is declared as: public interface Set extends Collection Creating Set Objects Since Set is an interface, objects cannot be created of the typeset. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. This type-safe set can be defined as: // Obj is the type of the object to be stored in Set Set<Obj> set = new HashSet<Obj> (); Let us discuss methods present in the Set interface provided below in a tabular format below as follows: Illustration: Sample Program to Illustrate Set interface Java // Java program Illustrating Set Interface // Importing utility classesimport java.util.*; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Demonstrating Set using HashSet // Declaring object of type String Set<String> hash_Set = new HashSet<String>(); // Adding elements to the Set // using add() method hash_Set.add("Geeks"); hash_Set.add("For"); hash_Set.add("Geeks"); hash_Set.add("Example"); hash_Set.add("Set"); // Printing elements of HashSet object System.out.println(hash_Set); }} [Set, Example, Geeks, For] Operations on the Set Interface The set interface allows the users to perform the basic mathematical operation on the set. Let’s take two arrays to understand these basic operations. Let set1 = [1, 3, 2, 4, 8, 9, 0] and set2 = [1, 3, 7, 5, 4, 0, 7, 5]. Then the possible operations on the sets are: 1. Intersection: This operation returns all the common elements from the given two sets. For the above two sets, the intersection would be: Intersection = [0, 1, 3, 4] 2. Union: This operation adds all the elements in one set with the other. For the above two sets, the union would be: Union = [0, 1, 2, 3, 4, 5, 7, 8, 9] 3. Difference: This operation removes all the values present in one set from the other set. For the above two sets, the difference would be: Difference = [2, 8, 9] Now let us implement the following operations as defined above as follows: Example: Java // Java Program Demonstrating Operations on the Set// such as Union, Intersection and Difference operations // Importing all utility classesimport java.util.*; // Main class public class SetExample { // Main driver method public static void main(String args[]) { // Creating an object of Set class // Declaring object of Integer type Set<Integer> a = new HashSet<Integer>(); // Adding all elements to List a.addAll(Arrays.asList( new Integer[] { 1, 3, 2, 4, 8, 9, 0 })); // Again declaring object of Set class // with reference to HashSet Set<Integer> b = new HashSet<Integer>(); b.addAll(Arrays.asList( new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 })); // To find union Set<Integer> union = new HashSet<Integer>(a); union.addAll(b); System.out.print("Union of the two Set"); System.out.println(union); // To find intersection Set<Integer> intersection = new HashSet<Integer>(a); intersection.retainAll(b); System.out.print("Intersection of the two Set"); System.out.println(intersection); // To find the symmetric difference Set<Integer> difference = new HashSet<Integer>(a); difference.removeAll(b); System.out.print("Difference of the two Set"); System.out.println(difference); }} Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9] Intersection of the two Set[0, 1, 3, 4] Difference of the two Set[2, 8, 9] After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. Since Set is an interface, it can be used only with a class that implements this interface. HashSet is one of the widely used classes which implements the Set interface. Now, let’s see how to perform a few frequently used operations on the HashSet. We are going to perform the following operations as follows: Adding elementsAccessing elementsRemoving elementsIterating elementsIterating through Set Adding elements Accessing elements Removing elements Iterating elements Iterating through Set Now let us discuss these operations individually as follows: Operations 1: Adding Elements In order to add an element to the Set, we can use the add() method. However, the insertion order is not retained in the Set. Internally, for every element, a hash is generated and the values are stored with respect to the generated hash. the values are compared and sorted in ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are accepted by the Set. Example Java // Java Program Demonstrating Working of Set by// Adding elements using add() method // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Set and // declaring object of type String Set<String> hs = new HashSet<String>(); // Adding elements to above object // using add() method hs.add("B"); hs.add("B"); hs.add("C"); hs.add("A"); // Printing the elements inside the Set object System.out.println(hs); }} [A, B, C] Operation 2: Accessing the Elements After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(). Example Java // Java code to demonstrate Working of Set by// Accessing the Elements og the Set object // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Set and // declaring object of type String Set<String> hs = new HashSet<String>(); // Elements are added using add() method // Later onwards we will show accessing the same // Custom input elements hs.add("A"); hs.add("B"); hs.add("C"); hs.add("A"); // Print the Set object elements System.out.println("Set is " + hs); // Declaring a string String check = "D"; // Check if the above string exists in // the SortedSet or not // using contains() method System.out.println("Contains " + check + " " + hs.contains(check)); }} Set is [A, B, C] Contains D false Operation 3: Removing the Values The values can be removed from the Set using the remove() method. Example Java // Java Program Demonstrating Working of Set by// Removing Element/s from the Set // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring object of Set of type String Set<String> hs = new HashSet<String>(); // Elements are added // using add() method // Custom input elements hs.add("A"); hs.add("B"); hs.add("C"); hs.add("B"); hs.add("D"); hs.add("E"); // Printing initial Set elements System.out.println("Initial HashSet " + hs); // Removing custom element // using remove() method hs.remove("B"); // Printing Set elements after removing an element // and printing updated Set elements System.out.println("After removing element " + hs); }} Initial HashSet [A, B, C, D, E] After removing element [A, C, D, E] Operation 4: Iterating through the Set There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop. Example Java // Java Program to Demonstrate Working of Set by // Iterating through the Elements // Importing utility classes import java.util.*; // Main class class GFG { // Main driver method public static void main(String[] args) { // Creating object of Set and declaring String type Set<String> hs = new HashSet<String>(); // Adding elements to Set // using add() method // Custom input elements hs.add("A"); hs.add("B"); hs.add("C"); hs.add("B"); hs.add("D"); hs.add("E"); // Iterating through the Set // via for-each loop for (String value : hs) // Printing all the values inside the object System.out.print(value + ", "); System.out.println(); }} A, B, C, D, E, Classes that implement the Set interface in Java Collections can be easily perceived from the image below as follows and are listed as follows: HashSet EnumSet LinkedHashSet TreeSet Class 1: HashSet HashSet class which is implemented in the collection framework is an inherent implementation of the hash table data structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s see how to create a set object using this class. Example Java // Java program Demonstrating Creation of Set object// Using the Hashset class // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of Set of type String Set<String> h = new HashSet<String>(); // Adding elements into the HashSet // using add() method // Custom input elements h.add("India"); h.add("Australia"); h.add("South Africa"); // Adding the duplicate element h.add("India"); // Displaying the HashSet System.out.println(h); // Removing items from HashSet // using remove() method h.remove("Australia"); System.out.println("Set after removing " + "Australia:" + h); // Iterating over hash set items System.out.println("Iterating over set:"); // Iterating through iterators Iterator<String> i = h.iterator(); // It holds true till there is a single element // remaining in the object while (i.hasNext()) System.out.println(i.next()); }} [South Africa, Australia, India] Set after removing Australia:[South Africa, India] Iterating over set: South Africa India Class 2: EnumSet EnumSet class which is implemented in the collections framework is one of the specialized implementations of the Set interface for use with the enumeration type. It is a high-performance set implementation, much faster than HashSet. All of the elements in an enum set must come from a single enumeration type that is specified when the set is created either explicitly or implicitly. Let’s see how to create a set object using this class. Example Java // Java program to demonstrate the// creation of the set object// using the EnumSet classimport java.util.*; enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }; public class GFG { public static void main(String[] args) { // Creating a set Set<Gfg> set1; // Adding the elements set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE, Gfg.LEARN, Gfg.CODE); System.out.println("Set 1: " + set1); }} Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ] Class 3: LinkedHashSet LinkedHashSet class which is implemented in the collections framework is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. Let’s see how to create a set object using this class. Example Java // Java program to demonstrate the// creation of Set object using// the LinkedHashset classimport java.util.*; class GFG { public static void main(String[] args) { Set<String> lh = new LinkedHashSet<String>(); // Adding elements into the LinkedHashSet // using add() lh.add("India"); lh.add("Australia"); lh.add("South Africa"); // Adding the duplicate // element lh.add("India"); // Displaying the LinkedHashSet System.out.println(lh); // Removing items from LinkedHashSet // using remove() lh.remove("Australia"); System.out.println("Set after removing " + "Australia:" + lh); // Iterating over linked hash set items System.out.println("Iterating over set:"); Iterator<String> i = lh.iterator(); while (i.hasNext()) System.out.println(i.next()); }} [India, Australia, South Africa] Set after removing Australia:[India, South Africa] Iterating over set: India South Africa Class 4: TreeSet TreeSet class which is implemented in the collections framework and implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can iterate in descending order using the method TreeSet.descendingIterator(). Let’s see how to create a set object using this class. Example Java // Java Program Demonstrating Creation of Set object// Using the TreeSet class // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a Set object and declaring it of String // type // with reference to TreeSet Set<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add("India"); ts.add("Australia"); ts.add("South Africa"); // Adding the duplicate // element ts.add("India"); // Displaying the TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() ts.remove("Australia"); System.out.println("Set after removing " + "Australia:" + ts); // Iterating over Tree set items System.out.println("Iterating over set:"); Iterator<String> i = ts.iterator(); while (i.hasNext()) System.out.println(i.next()); }} [Australia, India, South Africa] Set after removing Australia:[India, South Africa] Iterating over set: India South Africa ShreyasWaghmare nihat_-- the_last_king KaashyapMSK aadarsh baid manish bansal 1 surinderdawra388 simmytarika5 alisardari DaisyS sumitgumber28 Java - util package Java-Collections java-set Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initialize an ArrayList in Java Initializing a List in Java Generics in Java Java Programming Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 524, "s": 52, "text": "The set interface is present in java.util package and extends the Collection interface is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the set implementation namely SortedSet and NavigableSet." }, { "code": null, "e": 920, "s": 524, "text": "In the above image, the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree." }, { "code": null, "e": 967, "s": 920, "text": "Declaration: The Set interface is declared as:" }, { "code": null, "e": 1008, "s": 967, "text": "public interface Set extends Collection " }, { "code": null, "e": 1029, "s": 1008, "text": "Creating Set Objects" }, { "code": null, "e": 1347, "s": 1029, "text": "Since Set is an interface, objects cannot be created of the typeset. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. This type-safe set can be defined as:" }, { "code": null, "e": 1438, "s": 1347, "text": "// Obj is the type of the object to be stored in Set \nSet<Obj> set = new HashSet<Obj> (); " }, { "code": null, "e": 1543, "s": 1438, "text": "Let us discuss methods present in the Set interface provided below in a tabular format below as follows:" }, { "code": null, "e": 1600, "s": 1543, "text": "Illustration: Sample Program to Illustrate Set interface" }, { "code": null, "e": 1605, "s": 1600, "text": "Java" }, { "code": "// Java program Illustrating Set Interface // Importing utility classesimport java.util.*; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Demonstrating Set using HashSet // Declaring object of type String Set<String> hash_Set = new HashSet<String>(); // Adding elements to the Set // using add() method hash_Set.add(\"Geeks\"); hash_Set.add(\"For\"); hash_Set.add(\"Geeks\"); hash_Set.add(\"Example\"); hash_Set.add(\"Set\"); // Printing elements of HashSet object System.out.println(hash_Set); }}", "e": 2252, "s": 1605, "text": null }, { "code": null, "e": 2279, "s": 2252, "text": "[Set, Example, Geeks, For]" }, { "code": null, "e": 2311, "s": 2279, "text": "Operations on the Set Interface" }, { "code": null, "e": 2578, "s": 2311, "text": "The set interface allows the users to perform the basic mathematical operation on the set. Let’s take two arrays to understand these basic operations. Let set1 = [1, 3, 2, 4, 8, 9, 0] and set2 = [1, 3, 7, 5, 4, 0, 7, 5]. Then the possible operations on the sets are:" }, { "code": null, "e": 2718, "s": 2578, "text": "1. Intersection: This operation returns all the common elements from the given two sets. For the above two sets, the intersection would be:" }, { "code": null, "e": 2747, "s": 2718, "text": "Intersection = [0, 1, 3, 4] " }, { "code": null, "e": 2866, "s": 2747, "text": "2. Union: This operation adds all the elements in one set with the other. For the above two sets, the union would be: " }, { "code": null, "e": 2903, "s": 2866, "text": "Union = [0, 1, 2, 3, 4, 5, 7, 8, 9] " }, { "code": null, "e": 3045, "s": 2903, "text": "3. Difference: This operation removes all the values present in one set from the other set. For the above two sets, the difference would be: " }, { "code": null, "e": 3068, "s": 3045, "text": "Difference = [2, 8, 9]" }, { "code": null, "e": 3143, "s": 3068, "text": "Now let us implement the following operations as defined above as follows:" }, { "code": null, "e": 3152, "s": 3143, "text": "Example:" }, { "code": null, "e": 3157, "s": 3152, "text": "Java" }, { "code": "// Java Program Demonstrating Operations on the Set// such as Union, Intersection and Difference operations // Importing all utility classesimport java.util.*; // Main class public class SetExample { // Main driver method public static void main(String args[]) { // Creating an object of Set class // Declaring object of Integer type Set<Integer> a = new HashSet<Integer>(); // Adding all elements to List a.addAll(Arrays.asList( new Integer[] { 1, 3, 2, 4, 8, 9, 0 })); // Again declaring object of Set class // with reference to HashSet Set<Integer> b = new HashSet<Integer>(); b.addAll(Arrays.asList( new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 })); // To find union Set<Integer> union = new HashSet<Integer>(a); union.addAll(b); System.out.print(\"Union of the two Set\"); System.out.println(union); // To find intersection Set<Integer> intersection = new HashSet<Integer>(a); intersection.retainAll(b); System.out.print(\"Intersection of the two Set\"); System.out.println(intersection); // To find the symmetric difference Set<Integer> difference = new HashSet<Integer>(a); difference.removeAll(b); System.out.print(\"Difference of the two Set\"); System.out.println(difference); }}", "e": 4584, "s": 3157, "text": null }, { "code": null, "e": 4707, "s": 4584, "text": "Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9]\nIntersection of the two Set[0, 1, 3, 4]\nDifference of the two Set[2, 8, 9]" }, { "code": null, "e": 5142, "s": 4707, "text": "After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. Since Set is an interface, it can be used only with a class that implements this interface. HashSet is one of the widely used classes which implements the Set interface. Now, let’s see how to perform a few frequently used operations on the HashSet. We are going to perform the following operations as follows:" }, { "code": null, "e": 5232, "s": 5142, "text": "Adding elementsAccessing elementsRemoving elementsIterating elementsIterating through Set" }, { "code": null, "e": 5248, "s": 5232, "text": "Adding elements" }, { "code": null, "e": 5267, "s": 5248, "text": "Accessing elements" }, { "code": null, "e": 5285, "s": 5267, "text": "Removing elements" }, { "code": null, "e": 5304, "s": 5285, "text": "Iterating elements" }, { "code": null, "e": 5326, "s": 5304, "text": "Iterating through Set" }, { "code": null, "e": 5387, "s": 5326, "text": "Now let us discuss these operations individually as follows:" }, { "code": null, "e": 5417, "s": 5387, "text": "Operations 1: Adding Elements" }, { "code": null, "e": 5864, "s": 5417, "text": "In order to add an element to the Set, we can use the add() method. However, the insertion order is not retained in the Set. Internally, for every element, a hash is generated and the values are stored with respect to the generated hash. the values are compared and sorted in ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are accepted by the Set." }, { "code": null, "e": 5874, "s": 5864, "text": "Example " }, { "code": null, "e": 5879, "s": 5874, "text": "Java" }, { "code": "// Java Program Demonstrating Working of Set by// Adding elements using add() method // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Set and // declaring object of type String Set<String> hs = new HashSet<String>(); // Adding elements to above object // using add() method hs.add(\"B\"); hs.add(\"B\"); hs.add(\"C\"); hs.add(\"A\"); // Printing the elements inside the Set object System.out.println(hs); }}", "e": 6494, "s": 5879, "text": null }, { "code": null, "e": 6504, "s": 6494, "text": "[A, B, C]" }, { "code": null, "e": 6540, "s": 6504, "text": "Operation 2: Accessing the Elements" }, { "code": null, "e": 6646, "s": 6540, "text": "After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains()." }, { "code": null, "e": 6655, "s": 6646, "text": "Example " }, { "code": null, "e": 6660, "s": 6655, "text": "Java" }, { "code": "// Java code to demonstrate Working of Set by// Accessing the Elements og the Set object // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Set and // declaring object of type String Set<String> hs = new HashSet<String>(); // Elements are added using add() method // Later onwards we will show accessing the same // Custom input elements hs.add(\"A\"); hs.add(\"B\"); hs.add(\"C\"); hs.add(\"A\"); // Print the Set object elements System.out.println(\"Set is \" + hs); // Declaring a string String check = \"D\"; // Check if the above string exists in // the SortedSet or not // using contains() method System.out.println(\"Contains \" + check + \" \" + hs.contains(check)); }}", "e": 7615, "s": 6660, "text": null }, { "code": null, "e": 7649, "s": 7615, "text": "Set is [A, B, C]\nContains D false" }, { "code": null, "e": 7682, "s": 7649, "text": "Operation 3: Removing the Values" }, { "code": null, "e": 7748, "s": 7682, "text": "The values can be removed from the Set using the remove() method." }, { "code": null, "e": 7756, "s": 7748, "text": "Example" }, { "code": null, "e": 7761, "s": 7756, "text": "Java" }, { "code": "// Java Program Demonstrating Working of Set by// Removing Element/s from the Set // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring object of Set of type String Set<String> hs = new HashSet<String>(); // Elements are added // using add() method // Custom input elements hs.add(\"A\"); hs.add(\"B\"); hs.add(\"C\"); hs.add(\"B\"); hs.add(\"D\"); hs.add(\"E\"); // Printing initial Set elements System.out.println(\"Initial HashSet \" + hs); // Removing custom element // using remove() method hs.remove(\"B\"); // Printing Set elements after removing an element // and printing updated Set elements System.out.println(\"After removing element \" + hs); }}", "e": 8660, "s": 7761, "text": null }, { "code": null, "e": 8728, "s": 8660, "text": "Initial HashSet [A, B, C, D, E]\nAfter removing element [A, C, D, E]" }, { "code": null, "e": 8767, "s": 8728, "text": "Operation 4: Iterating through the Set" }, { "code": null, "e": 8871, "s": 8767, "text": "There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop." }, { "code": null, "e": 8880, "s": 8871, "text": "Example " }, { "code": null, "e": 8885, "s": 8880, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of Set by // Iterating through the Elements // Importing utility classes import java.util.*; // Main class class GFG { // Main driver method public static void main(String[] args) { // Creating object of Set and declaring String type Set<String> hs = new HashSet<String>(); // Adding elements to Set // using add() method // Custom input elements hs.add(\"A\"); hs.add(\"B\"); hs.add(\"C\"); hs.add(\"B\"); hs.add(\"D\"); hs.add(\"E\"); // Iterating through the Set // via for-each loop for (String value : hs) // Printing all the values inside the object System.out.print(value + \", \"); System.out.println(); }}", "e": 9692, "s": 8885, "text": null }, { "code": null, "e": 9708, "s": 9692, "text": "A, B, C, D, E, " }, { "code": null, "e": 9852, "s": 9708, "text": "Classes that implement the Set interface in Java Collections can be easily perceived from the image below as follows and are listed as follows:" }, { "code": null, "e": 9860, "s": 9852, "text": "HashSet" }, { "code": null, "e": 9868, "s": 9860, "text": "EnumSet" }, { "code": null, "e": 9882, "s": 9868, "text": "LinkedHashSet" }, { "code": null, "e": 9890, "s": 9882, "text": "TreeSet" }, { "code": null, "e": 9910, "s": 9892, "text": "Class 1: HashSet " }, { "code": null, "e": 10293, "s": 9910, "text": "HashSet class which is implemented in the collection framework is an inherent implementation of the hash table data structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s see how to create a set object using this class. " }, { "code": null, "e": 10301, "s": 10293, "text": "Example" }, { "code": null, "e": 10306, "s": 10301, "text": "Java" }, { "code": "// Java program Demonstrating Creation of Set object// Using the Hashset class // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of Set of type String Set<String> h = new HashSet<String>(); // Adding elements into the HashSet // using add() method // Custom input elements h.add(\"India\"); h.add(\"Australia\"); h.add(\"South Africa\"); // Adding the duplicate element h.add(\"India\"); // Displaying the HashSet System.out.println(h); // Removing items from HashSet // using remove() method h.remove(\"Australia\"); System.out.println(\"Set after removing \" + \"Australia:\" + h); // Iterating over hash set items System.out.println(\"Iterating over set:\"); // Iterating through iterators Iterator<String> i = h.iterator(); // It holds true till there is a single element // remaining in the object while (i.hasNext()) System.out.println(i.next()); }}", "e": 11483, "s": 10306, "text": null }, { "code": null, "e": 11606, "s": 11483, "text": "[South Africa, Australia, India]\nSet after removing Australia:[South Africa, India]\nIterating over set:\nSouth Africa\nIndia" }, { "code": null, "e": 11623, "s": 11606, "text": "Class 2: EnumSet" }, { "code": null, "e": 12063, "s": 11623, "text": "EnumSet class which is implemented in the collections framework is one of the specialized implementations of the Set interface for use with the enumeration type. It is a high-performance set implementation, much faster than HashSet. All of the elements in an enum set must come from a single enumeration type that is specified when the set is created either explicitly or implicitly. Let’s see how to create a set object using this class. " }, { "code": null, "e": 12071, "s": 12063, "text": "Example" }, { "code": null, "e": 12076, "s": 12071, "text": "Java" }, { "code": "// Java program to demonstrate the// creation of the set object// using the EnumSet classimport java.util.*; enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }; public class GFG { public static void main(String[] args) { // Creating a set Set<Gfg> set1; // Adding the elements set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE, Gfg.LEARN, Gfg.CODE); System.out.println(\"Set 1: \" + set1); }}", "e": 12534, "s": 12076, "text": null }, { "code": null, "e": 12573, "s": 12534, "text": "Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]" }, { "code": null, "e": 12596, "s": 12573, "text": "Class 3: LinkedHashSet" }, { "code": null, "e": 13046, "s": 12596, "text": "LinkedHashSet class which is implemented in the collections framework is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. Let’s see how to create a set object using this class. " }, { "code": null, "e": 13054, "s": 13046, "text": "Example" }, { "code": null, "e": 13059, "s": 13054, "text": "Java" }, { "code": "// Java program to demonstrate the// creation of Set object using// the LinkedHashset classimport java.util.*; class GFG { public static void main(String[] args) { Set<String> lh = new LinkedHashSet<String>(); // Adding elements into the LinkedHashSet // using add() lh.add(\"India\"); lh.add(\"Australia\"); lh.add(\"South Africa\"); // Adding the duplicate // element lh.add(\"India\"); // Displaying the LinkedHashSet System.out.println(lh); // Removing items from LinkedHashSet // using remove() lh.remove(\"Australia\"); System.out.println(\"Set after removing \" + \"Australia:\" + lh); // Iterating over linked hash set items System.out.println(\"Iterating over set:\"); Iterator<String> i = lh.iterator(); while (i.hasNext()) System.out.println(i.next()); }}", "e": 14002, "s": 13059, "text": null }, { "code": null, "e": 14125, "s": 14002, "text": "[India, Australia, South Africa]\nSet after removing Australia:[India, South Africa]\nIterating over set:\nIndia\nSouth Africa" }, { "code": null, "e": 14142, "s": 14125, "text": "Class 4: TreeSet" }, { "code": null, "e": 14617, "s": 14142, "text": "TreeSet class which is implemented in the collections framework and implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can iterate in descending order using the method TreeSet.descendingIterator(). Let’s see how to create a set object using this class." }, { "code": null, "e": 14625, "s": 14617, "text": "Example" }, { "code": null, "e": 14630, "s": 14625, "text": "Java" }, { "code": "// Java Program Demonstrating Creation of Set object// Using the TreeSet class // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a Set object and declaring it of String // type // with reference to TreeSet Set<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add(\"India\"); ts.add(\"Australia\"); ts.add(\"South Africa\"); // Adding the duplicate // element ts.add(\"India\"); // Displaying the TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() ts.remove(\"Australia\"); System.out.println(\"Set after removing \" + \"Australia:\" + ts); // Iterating over Tree set items System.out.println(\"Iterating over set:\"); Iterator<String> i = ts.iterator(); while (i.hasNext()) System.out.println(i.next()); }}", "e": 15709, "s": 14630, "text": null }, { "code": null, "e": 15832, "s": 15709, "text": "[Australia, India, South Africa]\nSet after removing Australia:[India, South Africa]\nIterating over set:\nIndia\nSouth Africa" }, { "code": null, "e": 15848, "s": 15832, "text": "ShreyasWaghmare" }, { "code": null, "e": 15857, "s": 15848, "text": "nihat_--" }, { "code": null, "e": 15871, "s": 15857, "text": "the_last_king" }, { "code": null, "e": 15883, "s": 15871, "text": "KaashyapMSK" }, { "code": null, "e": 15896, "s": 15883, "text": "aadarsh baid" }, { "code": null, "e": 15912, "s": 15896, "text": "manish bansal 1" }, { "code": null, "e": 15929, "s": 15912, "text": "surinderdawra388" }, { "code": null, "e": 15942, "s": 15929, "text": "simmytarika5" }, { "code": null, "e": 15953, "s": 15942, "text": "alisardari" }, { "code": null, "e": 15960, "s": 15953, "text": "DaisyS" }, { "code": null, "e": 15974, "s": 15960, "text": "sumitgumber28" }, { "code": null, "e": 15994, "s": 15974, "text": "Java - util package" }, { "code": null, "e": 16011, "s": 15994, "text": "Java-Collections" }, { "code": null, "e": 16020, "s": 16011, "text": "java-set" }, { "code": null, "e": 16025, "s": 16020, "text": "Java" }, { "code": null, "e": 16030, "s": 16025, "text": "Java" }, { "code": null, "e": 16047, "s": 16030, "text": "Java-Collections" }, { "code": null, "e": 16145, "s": 16047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16189, "s": 16145, "text": "Split() String method in Java with examples" }, { "code": null, "e": 16225, "s": 16189, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 16250, "s": 16225, "text": "Reverse a string in Java" }, { "code": null, "e": 16281, "s": 16250, "text": "How to iterate any Map in Java" }, { "code": null, "e": 16296, "s": 16281, "text": "Stream In Java" }, { "code": null, "e": 16320, "s": 16296, "text": "Singleton Class in Java" }, { "code": null, "e": 16352, "s": 16320, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 16380, "s": 16352, "text": "Initializing a List in Java" }, { "code": null, "e": 16397, "s": 16380, "text": "Generics in Java" } ]
How to Use Routing with React Navigation in React Native ?
03 Aug, 2021 Almost every mobile application requires navigating between different screens. React Native provides an elegant and easy-to-use library to add navigation to native applications: react-navigation. It is one of the most popular libraries used for routing and navigating in a React Native application. Transitioning between multiple screens is managed by Navigators. React Navigation allows various kinds of navigators, like Stack Navigators, Drawer Navigators, Tab Navigators, etc. Along with navigating between multiple screens, it can also be used for sharing data between them. Approach: We will be using the StackNavigator provided by React Navigation. It is used to allow transitions between screens wherein every new screen is placed on top of a stack. In our example, we will be creating 3 screens and transitioning between them using the StackNavigator. We will also learn how to pass data from one screen to another and display it in the screen header along with basic transitioning. Creating application and installing modules: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init react-navigation-routing Step 2: Now create a project by the following command. expo init react-navigation-routing Step 3: Now go into your project folder i.e. react-navigation-routingcd react-navigation-routing Step 3: Now go into your project folder i.e. react-navigation-routing cd react-navigation-routing Step 4: Install the required packages using the following command:npm install –save react-navigation react-navigation-stack react-native-reanimated react-native-gesture-handler react-native-screens react-native-vector-icons Step 4: Install the required packages using the following command: npm install –save react-navigation react-navigation-stack react-native-reanimated react-native-gesture-handler react-native-screens react-native-vector-icons Project Structure: The project directory should look like the following: Example: In this example, we will create 3 screens, namely, Home Screen, Profile Screen, and Settings Screen. We will use a Stack Navigator and configure it with some basic styles. We will also dynamically send data from one screen and display it as the header title on another screen (take input from the user on the Home Screen, pass it on to the Profile Screen, and display it on the Header of the Profile Screen. This file contains the basic Navigator setup. We will use the createStackNavigator() method provided by the react-navigation-stack library to create our stack navigator. Some basic styles are provided to all the 3 screens using the default navigation options. App.js import React from "react";import { createAppContainer } from "react-navigation";import { createStackNavigator } from "react-navigation-stack"; import HomeScreen from "./screens/HomeScreen";import ProfileScreen from "./screens/ProfileScreen";import SettingsScreen from "./screens/SettingsScreen"; const AppNavigator = createStackNavigator( { Home: HomeScreen, Profile: ProfileScreen, Settings: SettingsScreen, }, { defaultNavigationOptions: { headerStyle: { backgroundColor: "#006600", }, headerTintColor: "#FFF", }, }); const Navigator = createAppContainer(AppNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );} This is the first screen of our stack. In this screen, we will ask the user to provide a profile name as an input which we will pass to the “Profile” screen. HomeScreen.js import React, { useState } from "react";import { Text, View, TextInput, Button } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Home = (props) => { const [input, setInput] = useState(""); return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Home Screen!</Text> <Ionicons name="ios-home" size={80} color="#006600" /> <TextInput placeholder="Enter your profile" value={input} onChangeText={(value) => setInput(value)} /> <Button title="Go to Profile" color="#006600" onPress={() => props.navigation.navigate("Profile", { username: input }) } /> </View> );}; export default Home; This screen will receive the input given by the user in the Home Screen using the navData object and display it in its header. ProfileScreen.js import React from "react";import { Text, View, Button } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Profile = (props) => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Profile Screen!</Text> <Ionicons name="ios-person-circle-outline" size={80} color="#006600" /> <Button title="Go to Settings" color="#006600" onPress={() => props.navigation.navigate("Settings")} /> </View> );}; Profile.navigationOptions = (navData) => { return { headerTitle: navData.navigation.getParam("username"), };}; export default Profile; This is a simple screen with a button to go back to the Home Screen. SettingsScreen.js import React from "react";import { Text, View, Button } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Settings = (props) => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name="ios-settings-outline" size={80} color="#006600" /> <Button title="Go to Home" color="#006600" onPress={() => props.navigation.navigate("Home")} /> </View> );}; export default Settings; Step to run the application: Start the server by using the following command. expo start Output: Reference: https://reactnative.dev/docs/navigation Picked React-Native Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Node.js | fs.writeFileSync() Method Difference between var, let and const keywords in JavaScript What is web socket and how it is different from the HTTP? Difference between HTTP GET and POST Methods How to create a multi-page website using React.js ? How to position a div at the bottom of its container using CSS? JavaScript | promise resolve() Method Express.js res.render() Function JavaScript String includes() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 327, "s": 28, "text": "Almost every mobile application requires navigating between different screens. React Native provides an elegant and easy-to-use library to add navigation to native applications: react-navigation. It is one of the most popular libraries used for routing and navigating in a React Native application." }, { "code": null, "e": 607, "s": 327, "text": "Transitioning between multiple screens is managed by Navigators. React Navigation allows various kinds of navigators, like Stack Navigators, Drawer Navigators, Tab Navigators, etc. Along with navigating between multiple screens, it can also be used for sharing data between them." }, { "code": null, "e": 1019, "s": 607, "text": "Approach: We will be using the StackNavigator provided by React Navigation. It is used to allow transitions between screens wherein every new screen is placed on top of a stack. In our example, we will be creating 3 screens and transitioning between them using the StackNavigator. We will also learn how to pass data from one screen to another and display it in the screen header along with basic transitioning." }, { "code": null, "e": 1066, "s": 1021, "text": "Creating application and installing modules:" }, { "code": null, "e": 1163, "s": 1066, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 1237, "s": 1163, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 1261, "s": 1237, "text": "npm install -g expo-cli" }, { "code": null, "e": 1350, "s": 1261, "text": "Step 2: Now create a project by the following command.expo init react-navigation-routing" }, { "code": null, "e": 1405, "s": 1350, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 1440, "s": 1405, "text": "expo init react-navigation-routing" }, { "code": null, "e": 1537, "s": 1440, "text": "Step 3: Now go into your project folder i.e. react-navigation-routingcd react-navigation-routing" }, { "code": null, "e": 1607, "s": 1537, "text": "Step 3: Now go into your project folder i.e. react-navigation-routing" }, { "code": null, "e": 1635, "s": 1607, "text": "cd react-navigation-routing" }, { "code": null, "e": 1859, "s": 1635, "text": "Step 4: Install the required packages using the following command:npm install –save react-navigation react-navigation-stack react-native-reanimated react-native-gesture-handler react-native-screens react-native-vector-icons" }, { "code": null, "e": 1926, "s": 1859, "text": "Step 4: Install the required packages using the following command:" }, { "code": null, "e": 2084, "s": 1926, "text": "npm install –save react-navigation react-navigation-stack react-native-reanimated react-native-gesture-handler react-native-screens react-native-vector-icons" }, { "code": null, "e": 2157, "s": 2084, "text": "Project Structure: The project directory should look like the following:" }, { "code": null, "e": 2574, "s": 2157, "text": "Example: In this example, we will create 3 screens, namely, Home Screen, Profile Screen, and Settings Screen. We will use a Stack Navigator and configure it with some basic styles. We will also dynamically send data from one screen and display it as the header title on another screen (take input from the user on the Home Screen, pass it on to the Profile Screen, and display it on the Header of the Profile Screen." }, { "code": null, "e": 2835, "s": 2574, "text": "This file contains the basic Navigator setup. We will use the createStackNavigator() method provided by the react-navigation-stack library to create our stack navigator. Some basic styles are provided to all the 3 screens using the default navigation options. " }, { "code": null, "e": 2842, "s": 2835, "text": "App.js" }, { "code": "import React from \"react\";import { createAppContainer } from \"react-navigation\";import { createStackNavigator } from \"react-navigation-stack\"; import HomeScreen from \"./screens/HomeScreen\";import ProfileScreen from \"./screens/ProfileScreen\";import SettingsScreen from \"./screens/SettingsScreen\"; const AppNavigator = createStackNavigator( { Home: HomeScreen, Profile: ProfileScreen, Settings: SettingsScreen, }, { defaultNavigationOptions: { headerStyle: { backgroundColor: \"#006600\", }, headerTintColor: \"#FFF\", }, }); const Navigator = createAppContainer(AppNavigator); export default function App() { return ( <Navigator> <HomeScreen /> </Navigator> );}", "e": 3557, "s": 2842, "text": null }, { "code": null, "e": 3715, "s": 3557, "text": "This is the first screen of our stack. In this screen, we will ask the user to provide a profile name as an input which we will pass to the “Profile” screen." }, { "code": null, "e": 3729, "s": 3715, "text": "HomeScreen.js" }, { "code": "import React, { useState } from \"react\";import { Text, View, TextInput, Button } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Home = (props) => { const [input, setInput] = useState(\"\"); return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Home Screen!</Text> <Ionicons name=\"ios-home\" size={80} color=\"#006600\" /> <TextInput placeholder=\"Enter your profile\" value={input} onChangeText={(value) => setInput(value)} /> <Button title=\"Go to Profile\" color=\"#006600\" onPress={() => props.navigation.navigate(\"Profile\", { username: input }) } /> </View> );}; export default Home;", "e": 4511, "s": 3729, "text": null }, { "code": null, "e": 4639, "s": 4511, "text": "This screen will receive the input given by the user in the Home Screen using the navData object and display it in its header. " }, { "code": null, "e": 4656, "s": 4639, "text": "ProfileScreen.js" }, { "code": "import React from \"react\";import { Text, View, Button } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Profile = (props) => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Profile Screen!</Text> <Ionicons name=\"ios-person-circle-outline\" size={80} color=\"#006600\" /> <Button title=\"Go to Settings\" color=\"#006600\" onPress={() => props.navigation.navigate(\"Settings\")} /> </View> );}; Profile.navigationOptions = (navData) => { return { headerTitle: navData.navigation.getParam(\"username\"), };}; export default Profile;", "e": 5345, "s": 4656, "text": null }, { "code": null, "e": 5414, "s": 5345, "text": "This is a simple screen with a button to go back to the Home Screen." }, { "code": null, "e": 5432, "s": 5414, "text": "SettingsScreen.js" }, { "code": "import React from \"react\";import { Text, View, Button } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Settings = (props) => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Settings Screen!</Text> <Ionicons name=\"ios-settings-outline\" size={80} color=\"#006600\" /> <Button title=\"Go to Home\" color=\"#006600\" onPress={() => props.navigation.navigate(\"Home\")} /> </View> );}; export default Settings;", "e": 5994, "s": 5432, "text": null }, { "code": null, "e": 6072, "s": 5994, "text": "Step to run the application: Start the server by using the following command." }, { "code": null, "e": 6083, "s": 6072, "text": "expo start" }, { "code": null, "e": 6091, "s": 6083, "text": "Output:" }, { "code": null, "e": 6142, "s": 6091, "text": "Reference: https://reactnative.dev/docs/navigation" }, { "code": null, "e": 6149, "s": 6142, "text": "Picked" }, { "code": null, "e": 6162, "s": 6149, "text": "React-Native" }, { "code": null, "e": 6179, "s": 6162, "text": "Web Technologies" }, { "code": null, "e": 6277, "s": 6179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6316, "s": 6277, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 6352, "s": 6316, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 6413, "s": 6352, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6471, "s": 6413, "text": "What is web socket and how it is different from the HTTP?" }, { "code": null, "e": 6516, "s": 6471, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 6568, "s": 6516, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 6632, "s": 6568, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 6670, "s": 6632, "text": "JavaScript | promise resolve() Method" }, { "code": null, "e": 6703, "s": 6670, "text": "Express.js res.render() Function" } ]
Python Data Persistence - Quick Guide
During the course of using any software application, user provides some data to be processed. The data may be input, using a standard input device (keyboard) or other devices such as disk file, scanner, camera, network cable, WiFi connection, etc. Data so received, is stored in computer’s main memory (RAM) in the form of various data structures such as, variables and objects until the application is running. Thereafter, memory contents from RAM are erased. However, more often than not, it is desired that the values of variables and/or objects be stored in such a manner, that it can be retrieved whenever required, instead of again inputting the same data. The word ‘persistence’ means "the continuance of an effect after its cause is removed". The term data persistence means it continues to exist even after the application has ended. Thus, data stored in a non-volatile storage medium such as, a disk file is a persistent data storage. In this tutorial, we will explore various built-in and third party Python modules to store and retrieve data to/from various formats such as text file, CSV, JSON and XML files as well as relational and non-relational databases. Using Python’s built-in File object, it is possible to write string data to a disk file and read from it. Python’s standard library, provides modules to store and retrieve serialized data in various data structures such as JSON and XML. Python’s DB-API provides a standard way of interacting with relational databases. Other third party Python packages, present interfacing functionality with NOSQL databases such as MongoDB and Cassandra. This tutorial also introduces, ZODB database which is a persistence API for Python objects. Microsoft Excel format is a very popular data file format. In this tutorial, we will learn how to handle .xlsx file through Python. Python uses built-in input() and print() functions to perform standard input/output operations. The input() function reads bytes from a standard input stream device, i.e. keyboard. The print() function on the other hand, sends the data towards standard output stream device i.e. the display monitor. Python program interacts with these IO devices through standard stream objects stdin and stdout defined in sys module. The input() function is actually a wrapper around readline() method of sys.stdin object. All keystrokes from the input stream are received till ‘Enter’ key is pressed. >>> import sys >>> x=sys.stdin.readline() Welcome to TutorialsPoint >>> x 'Welcome to TutorialsPoint\n' Note that, readline() function leave a trailing ‘\n’ character. There is also a read() method which reads data from standard input stream till it is terminated by Ctrl+D character. >>> x=sys.stdin.read() Hello Welcome to TutorialsPoint >>> x 'Hello\nWelcome to TutorialsPoint\n' Similarly, print() is a convenience function emulating write() method of stdout object. >>> x='Welcome to TutorialsPoint\n' >>> sys.stdout.write(x) Welcome to TutorialsPoint 26 Just as stdin and stdout predefined stream objects, a Python program can read data from and send data to a disk file or a network socket. They are also streams. Any object that has read() method is an input stream. Any object that has write() method is an output stream. The communication with the stream is established by obtaining reference to the stream object with built-in open() function. This built-in function uses following arguments − f=open(name, mode, buffering) The name parameter, is name of disk file or byte string, mode is optional one-character string to specify the type of operation to be performed (read, write, append etc.) and buffering parameter is either 0, 1 or -1 indicating buffering is off, on or system default. File opening mode is enumerated as per table below. Default mode is ‘r’ R Open for reading (default) W Open for writing, truncating the file first X Create a new file and open it for writing A Open for writing, appending to the end of the file if it exists B Binary mode T Text mode (default) + Open a disk file for updating (reading and writing) In order to save data to file it must be opened with ‘w’ mode. f=open('test.txt','w') This file object acts as an output stream, and has access to write() method. The write() method sends a string to this object, and is stored in the file underlying it. string="Hello TutorialsPoint\n" f.write(string) It is important to close the stream, to ensure that any data remaining in buffer is completely transferred to it. file.close() Try and open ‘test.txt’ using any test editor (such as notepad) to confirm successful creation of file. To read contents of ‘test.txt’ programmatically, it must be opened in ‘r’ mode. f=open('test.txt','r') This object behaves as an input stream. Python can fetch data from the stream using read() method. string=f.read() print (string) Contents of the file are displayed on Python console. The File object also supports readline() method which is able to read string till it encounters EOF character. However, if same file is opened in ‘w’ mode to store additional text in it, earlier contents are erased. Whenever, a file is opened with write permission, it is treated as if it is a new file. To add data to an existing file, use ‘a’ for append mode. f=open('test.txt','a') f.write('Python Tutorials\n') The file now, has earlier as well as newly added string. The file object also supports writelines() method to write each string in a list object to the file. f=open('test.txt','a') lines=['Java Tutorials\n', 'DBMS tutorials\n', 'Mobile development tutorials\n'] f.writelines(lines) f.close() The readlines() method returns a list of strings, each representing a line in the file. It is also possible to read the file line by line until end of file is reached. f=open('test.txt','r') while True: line=f.readline() if line=='' : break print (line, end='') f.close() Hello TutorialsPoint Python Tutorials Java Tutorials DBMS tutorials Mobile development tutorials By default, read/write operation on a file object are performed on text string data. If we want to handle files of different other types such as media (mp3), executables (exe), pictures (jpg) etc., we need to add ‘b’ prefix to read/write mode. Following statement will convert a string to bytes and write in a file. f=open('test.bin', 'wb') data=b"Hello World" f.write(data) f.close() Conversion of text string to bytes is also possible using encode() function. data="Hello World".encode('utf-8') We need to use ‘rb’ mode to read binary file. Returned value of read() method is first decoded before printing. f=open('test.bin', 'rb') data=f.read() print (data.decode(encoding='utf-8')) In order to write integer data in a binary file, the integer object should be converted to bytes by to_bytes() method. n=25 n.to_bytes(8,'big') f=open('test.bin', 'wb') data=n.to_bytes(8,'big') f.write(data) To read back from a binary file, convert output of read() function to integer by from_bytes() function. f=open('test.bin', 'rb') data=f.read() n=int.from_bytes(data, 'big') print (n) For floating point data, we need to use struct module from Python’s standard library. import struct x=23.50 data=struct.pack('f',x) f=open('test.bin', 'wb') f.write(data) Unpacking the string from read() function, to retrieve the float data from binary file. f=open('test.bin', 'rb') data=f.read() x=struct.unpack('f', data) print (x) When a file is opened for writing (with ‘w’ or ‘a’), it is not possible, to read from it and vice versa. Doing so throws UnSupportedOperation error. We need to close the file before doing other operation. In order to perform both operations simultaneously, we have to add ‘+’ character in the mode parameter. Hence, ‘w+’ or ‘r+’ mode enables using write() as well as read() methods without closing a file. The File object also supports seek() function to rewind the stream to any desired byte position. f=open('test.txt','w+') f.write('Hello world') f.seek(0,0) data=f.read() print (data) f.close() Following table summarizes all the methods available to a file like object. close() Closes the file. A closed file cannot be read or written any more. flush() Flush the internal buffer. fileno() Returns the integer file descriptor. next() Returns the next line from the file each time it is being called. Use next() iterator in Python 3. read([size]) Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes). readline([size]) Reads one entire line from the file. A trailing newline character is kept in the string. readlines([sizehint]) Reads until EOF using readline() and returns a list containing the lines. seek(offset[, whence]) Sets the file's current position. 0-begin 1-current 2-end. seek(offset[, whence]) Sets the file's current position. 0-begin 1-current 2-end. tell() Returns the file's current position truncate([size]) Truncates the file's size. write(str) Writes a string to the file. There is no return value. In addition to File object returned by open() function, file IO operations can also be performed using Python's built-in library has os module that provides useful operating system dependent functions. These functions perform low level read/write operations on file. The open() function from os module is similar to the built-in open(). However, it doesn't return a file object but a file descriptor, a unique integer corresponding to file opened. File descriptor's values 0, 1 and 2 represent stdin, stdout, and stderr streams. Other files will be given incremental file descriptor from 2 onwards. As in case of open() built-in function, os.open() function also needs to specify file access mode. Following table lists various modes as defined in os module. os.O_RDONLY Open for reading only os.O_WRONLY Open for writing only os.O_RDWR Open for reading and writing os.O_NONBLOCK Do not block on open os.O_APPEND Append on each write os.O_CREAT Create file if it does not exist os.O_TRUNC Truncate size to 0 os.O_EXCL Error if create and file exists To open a new file for writing data in it, specify O_WRONLY as well as O_CREAT modes by inserting pipe (|) operator. The os.open() function returns a file descriptor. f=os.open("test.dat", os.O_WRONLY|os.O_CREAT) Note that, data is written to disk file in the form of byte string. Hence, a normal string is converted to byte string by using encode() function as earlier. data="Hello World".encode('utf-8') The write() function in os module accepts this byte string and file descriptor. os.write(f,data) Don’t forget to close the file using close() function. os.close(f) To read contents of a file using os.read() function, use following statements: f=os.open("test.dat", os.O_RDONLY) data=os.read(f,20) print (data.decode('utf-8')) Note that, the os.read() function needs file descriptor and number of bytes to be read (length of byte string). If you want to open a file for simultaneous read/write operations, use O_RDWR mode. Following table shows important file operation related functions in os module. os.close(fd) Close the file descriptor. os.open(file, flags[, mode]) Open the file and set various flags according to flags and possibly its mode according to mode. os.read(fd, n) Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned. os.write(fd, str) Write the string str to file descriptor fd. Return the number of bytes actually written. Python's built-in file object returned by Python's built-in open() function has one important shortcoming. When opened with 'w' mode, the write() method accepts only the string object. That means, if you have data represented in any non-string form, the object of either in built-in classes (numbers, dictionary, lists or tuples) or other user-defined classes, it cannot be written to file directly. Before writing, you need to convert it in its string representation. numbers=[10,20,30,40] file=open('numbers.txt','w') file.write(str(numbers)) file.close() For a binary file, argument to write() method must be a byte object. For example, the list of integers is converted to bytes by bytearray() function and then written to file. numbers=[10,20,30,40] data=bytearray(numbers) file.write(data) file.close() To read back data from the file in the respective data type, reverse conversion needs to be done. file=open('numbers.txt','rb') data=file.read() print (list(data)) This type of manual conversion, of an object to string or byte format (and vice versa) is very cumbersome and tedious. It is possible to store the state of a Python object in the form of byte stream directly to a file, or memory stream and retrieve to its original state. This process is called serialization and de-serialization. Python’s built in library contains various modules for serialization and deserialization process. pickle Python specific serialization library marshal Library used internally for serialization shelve Pythonic object persistence dbm library offering interface to Unix database csv library for storage and retrieval of Python data to CSV format json Library for serialization to universal JSON format Python’s terminology for serialization and deserialization is pickling and unpickling respectively. The pickle module in Python library, uses very Python specific data format. Hence, non-Python applications may not be able to deserialize pickled data properly. It is also advised not to unpickle data from un-authenticated source. The serialized (pickled) data can be stored in a byte string or a binary file. This module defines dumps() and loads() functions to pickle and unpickle data using byte string. For file based process, the module has dump() and load() function. Python’s pickle protocols are the conventions used in constructing and deconstructing Python objects to/from binary data. Currently, pickle module defines 5 different protocols as listed below − Protocol version 0 Original “human-readable” protocol backwards compatible with earlier versions. Protocol version 1 Old binary format also compatible with earlier versions of Python. Protocol version 2 Introduced in Python 2.3 provides efficient pickling of new-style classes. Protocol version 3 Added in Python 3.0. recommended when compatibility with other Python 3 versions is required. Protocol version 4 was added in Python 3.4. It adds support for very large objects The pickle module consists of dumps() function that returns a string representation of pickled data. from pickle import dump dct={"name":"Ravi", "age":23, "Gender":"M","marks":75} dctstring=dumps(dct) print (dctstring) b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x04\x00\x00\x00Raviq\x02X\x03\x00\x00\x00ageq\x03K\x17X\x06\x00\x00\x00Genderq\x04X\x01\x00\x00\x00Mq\x05X\x05\x00\x00\x00marksq\x06KKu. Use loads() function, to unpickle the string and obtain original dictionary object. from pickle import load dct=loads(dctstring) print (dct) {'name': 'Ravi', 'age': 23, 'Gender': 'M', 'marks': 75} Pickled objects can also be persistently stored in a disk file, using dump() function and retrieved using load() function. import pickle f=open("data.txt","wb") dct={"name":"Ravi", "age":23, "Gender":"M","marks":75} pickle.dump(dct,f) f.close() #to read import pickle f=open("data.txt","rb") d=pickle.load(f) print (d) f.close() The pickle module also provides, object oriented API for serialization mechanism in the form of Pickler and Unpickler classes. As mentioned above, just as built-in objects in Python, objects of user defined classes can also be persistently serialized in disk file. In following program, we define a User class with name and mobile number as its instance attributes. In addition to the __init__() constructor, the class overrides __str__() method that returns a string representation of its object. class User: def __init__(self,name, mob): self.name=name self.mobile=mob def __str__(self): return ('Name: {} mobile: {} '. format(self.name, self.mobile)) To pickle object of above class in a file we use pickler class and its dump()method. from pickle import Pickler user1=User('Rajani', '[email protected]', '1234567890') file=open('userdata','wb') Pickler(file).dump(user1) Pickler(file).dump(user2) file.close() Conversely, Unpickler class has load() method to retrieve serialized object as follows − from pickle import Unpickler file=open('usersdata','rb') user1=Unpickler(file).load() print (user1) Object serialization features of marshal module in Python’s standard library are similar to pickle module. However, this module is not used for general purpose data. On the other hand, it is used by Python itself for Python’s internal object serialization to support read/write operations on compiled versions of Python modules (.pyc files). The data format used by marshal module is not compatible across Python versions. Therefore, a compiled Python script (.pyc file) of one version most probably won’t execute on another. Just as pickle module, marshal module also defined load() and dump() functions for reading and writing marshalled objects from / to file. This function writes byte representation of supported Python object to a file. The file itself be a binary file with write permission This function reads the byte data from a binary file and converts it to Python object. Following example demonstrates use of dump() and load() functions to handle code objects of Python, which are used to store precompiled Python modules. The code uses built-in compile() function to build a code object out of a source string which embeds Python instructions. compile(source, file, mode) The file parameter should be the file from which the code was read. If it wasn’t read from a file pass any arbitrary string. The mode parameter is ‘exec’ if the source contains sequence of statements, ‘eval’ if there is a single expression or ‘single’ if it contains a single interactive statement. The compile code object is then stored in a .pyc file using dump() function. import marshal script = """ a=10 b=20 print ('addition=',a+b) """ code = compile(script, "script", "exec") f=open("a.pyc","wb") marshal.dump(code, f) f.close() To deserialize, the object from .pyc file use load() function. Since, it returns a code object, it can be run using exec(), another built-in function. import marshal f=open("a.pyc","rb") data=marshal.load(f) exec (data) The shelve module in Python’s standard library provides simple yet effective object persistence mechanism. The shelf object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems. The shelf dictionary has certain restrictions. Only string data type can be used as key in this special dictionary object, whereas any picklable Python object can be used as value. The shelve module defines three classes as follows − Shelf This is the base class for shelf implementations. It is initialized with dict-like object. BsdDbShelf This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods. DbfilenameShelf This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object. The open() function defined in shelve module which return a DbfilenameShelf object. open(filename, flag='c', protocol=None, writeback=False) The filename parameter is assigned to the database created. Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write). The serialization itself is governed by pickle protocol, default is none. Last parameter writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations, hence process may be slow. Following code creates a database and stores dictionary entries in it. import shelve s=shelve.open("test") s['name']="Ajay" s['age']=23 s['marks']=75 s.close() This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available − close() synchronise and close persistent dict object. sync() Write back all entries in the cache if shelf was opened with writeback set to True. get() returns value associated with key items() list of tuples – each tuple is key value pair keys() list of shelf keys pop() remove specified key and return the corresponding value. update() Update shelf from another dict/iterable values() list of shelf values To access value of a particular key in shelf − s=shelve.open('test') print (s['age']) #this will print 23 s['age']=25 print (s.get('age')) #this will print 25 s.pop('marks') #this will remove corresponding k-v pair As in a built-in dictionary object, the items(), keys() and values() methods return view objects. print (list(s.items())) [('name', 'Ajay'), ('age', 25), ('marks', 75)] print (list(s.keys())) ['name', 'age', 'marks'] print (list(s.values())) ['Ajay', 25, 75] To merge items of another dictionary with shelf use update() method. d={'salary':10000, 'designation':'manager'} s.update(d) print (list(s.items())) [('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')] The dbm package presents a dictionary like interface DBM style databases. DBM stands for DataBase Manager. This is used by UNIX (and UNIX like) operating system. The dbbm library is a simple database engine written by Ken Thompson. These databases use binary encoded string objects as key, as well as value. The database stores data by use of a single key (a primary key) in fixed-size buckets and uses hashing techniques to enable fast retrieval of the data by key. The dbm package contains following modules − dbm.gnu module is an interface to the DBM library version as implemented by the GNU project. dbm.gnu module is an interface to the DBM library version as implemented by the GNU project. dbm.ndbm module provides an interface to UNIX nbdm implementation. dbm.ndbm module provides an interface to UNIX nbdm implementation. dbm.dumb is used as a fallback option in the event, other dbm implementations are not found. This requires no external dependencies but is slower than others. dbm.dumb is used as a fallback option in the event, other dbm implementations are not found. This requires no external dependencies but is slower than others. >>> dbm.whichdb('mydbm.db') 'dbm.dumb' >>> import dbm >>> db=dbm.open('mydbm.db','n') >>> db['name']=Raj Deshmane' >>> db['address']='Kirtinagar Pune' >>> db['PIN']='431101' >>> db.close() The open() function allows mode these flags − 'r' Open existing database for reading only (default) 'w' Open existing database for reading and writing 'c' Open database for reading and writing, creating it if it doesn’t exist 'n' Always create a new, empty database, open for reading and writing The dbm object is a dictionary like object, just as shelf object. Hence, all dictionary operations can be performed. The dbm object can invoke get(), pop(), append() and update() methods. Following code opens 'mydbm.db' with 'r' flag and iterates over collection of key-value pairs. >>> db=dbm.open('mydbm.db','r') >>> for k,v in db.items(): print (k,v) b'name' : b'Raj Deshmane' b'address' : b'Kirtinagar Pune' b'PIN' : b'431101' CSV stands for comma separated values. This file format is a commonly used data format while exporting/importing data to/from spreadsheets and data tables in databases. The csv module was incorporated in Python’s standard library as a result of PEP 305. It presents classes and methods to perform read/write operations on CSV file as per recommendations of PEP 305. CSV is a preferred export data format by Microsoft’s Excel spreadsheet software. However, csv module can handle data represented by other dialects also. The CSV API interface consists of following writer and reader classes − This function in csv module returns a writer object that converts data into a delimited string and stores in a file object. The function needs a file object with write permission as a parameter. Every row written in the file issues a newline character. To prevent additional space between lines, newline parameter is set to ''. The writer class has following methods − This method writes items in an iterable (list, tuple or string), separating them by comma character. This method takes a list of iterables, as parameter and writes each item as a comma separated line of items in the file. Example Following example shows use of writer() function. First a file is opened in ‘w’ mode. This file is used to obtain writer object. Each tuple in list of tuples is then written to file using writerow() method. import csv persons=[('Lata',22,45),('Anil',21,56),('John',20,60)] csvfile=open('persons.csv','w', newline='') obj=csv.writer(csvfile) for person in persons: obj.writerow(person) csvfile.close() Output This will create ‘persons.csv’ file in current directory. It will show following data. Lata,22,45 Anil,21,56 John,20,60 Instead of iterating over the list to write each row individually, we can use writerows() method. csvfile=open('persons.csv','w', newline='') persons=[('Lata',22,45),('Anil',21,56),('John',20,60)] obj=csv.writer(csvfile) obj.writerows(persons) obj.close() This function returns a reader object which returns an iterator of lines in the csv file. Using the regular for loop, all lines in the file are displayed in following example − csvfile=open('persons.csv','r', newline='') obj=csv.reader(csvfile) for row in obj: print (row) ['Lata', '22', '45'] ['Anil', '21', '56'] ['John', '20', '60'] The reader object is an iterator. Hence, it supports next() function which can also be used to display all lines in csv file instead of a for loop. csvfile=open('persons.csv','r', newline='') obj=csv.reader(csvfile) while True: try: row=next(obj) print (row) except StopIteration: break As mentioned earlier, csv module uses Excel as its default dialect. The csv module also defines a dialect class. Dialect is set of standards used to implement CSV protocol. The list of dialects available can be obtained by list_dialects() function. >>> csv.list_dialects() ['excel', 'excel-tab', 'unix'] In addition to iterables, csv module can export a dictionary object to CSV file and read it to populate Python dictionary object. For this purpose, this module defines following classes − This function returns a DictWriter object. It is similar to writer object, but the rows are mapped to dictionary object. The function needs a file object with write permission and a list of keys used in dictionary as fieldnames parameter. This is used to write first line in the file as header. This method writes list of keys in dictionary as a comma separated line as first line in the file. In following example, a list of dictionary items is defined. Each item in the list is a dictionary. Using writrows() method, they are written to file in comma separated manner. persons=[ {'name':'Lata', 'age':22, 'marks':45}, {'name':'Anil', 'age':21, 'marks':56}, {'name':'John', 'age':20, 'marks':60} ] csvfile=open('persons.csv','w', newline='') fields=list(persons[0].keys()) obj=csv.DictWriter(csvfile, fieldnames=fields) obj.writeheader() obj.writerows(persons) csvfile.close() The persons.csv file shows following contents − name,age,marks Lata,22,45 Anil,21,56 John,20,60 This function returns a DictReader object from the underlying CSV file. As, in case of, reader object, this one is also an iterator, using which contents of the file are retrieved. csvfile=open('persons.csv','r', newline='') obj=csv.DictReader(csvfile) The class provides fieldnames attribute, returning the dictionary keys used as header of file. print (obj.fieldnames) ['name', 'age', 'marks'] Use loop over the DictReader object to fetch individual dictionary objects. for row in obj: print (row) This results in following output − OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')]) OrderedDict([('name', 'Anil'), ('age', '21'), ('marks', '56')]) OrderedDict([('name', 'John'), ('age', '20'), ('marks', '60')]) To convert OrderedDict object to normal dictionary, we have to first import OrderedDict from collections module. from collections import OrderedDict r=OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')]) dict(r) {'name': 'Lata', 'age': '22', 'marks': '45'} JSON stands for JavaScript Object Notation. It is a lightweight data interchange format. It is a language-independent and cross platform text format, supported by many programming languages. This format is used for data exchange between the web server and clients. JSON format is similar to pickle. However, pickle serialization is Python specific whereas JSON format is implemented by many languages hence has become universal standard. Functionality and interface of json module in Python’s standard library is similar to pickle and marshal modules. Just as in pickle module, the json module also provides dumps() and loads() function for serialization of Python object into JSON encoded string, and dump() and load() functions write and read serialized Python objects to/from file. dumps() − This function converts the object into JSON format. dumps() − This function converts the object into JSON format. loads() − This function converts a JSON string back to Python object. loads() − This function converts a JSON string back to Python object. Following example demonstrates basic usage of these functions − import json data=['Rakesh',{'marks':(50,60,70)}] s=json.dumps(data) json.loads(s) The dumps() function can take optional sort_keys argument. By default, it is False. If set to True, the dictionary keys appear in sorted order in the JSON string. The dumps() function has another optional parameter called indent which takes a number as value. It decides length of each segment of formatted representation of json string, similar to print output. The json module also has object oriented API corresponding to above functions. There are two classes defined in the module – JSONEncoder and JSONDecoder. Object of this class is encoder for Python data structures. Each Python data type is converted in corresponding JSON type as shown in following table − The JSONEncoder class is instantiated by JSONEncoder() constructor. Following important methods are defined in encoder class − encode() serializes Python object into JSON format iterencode() Encodes the object and returns an iterator yielding encoded form of each item in the object. indent Determines indent level of encoded string sort_keys is either true or false to make keys appear in sorted order or not. Check_circular if True, check for circular reference in container type object Following example encodes Python list object. e=json.JSONEncoder() e.encode(data) Object of this class helps in decoded in json string back to Python data structure. Main method in this class is decode(). Following example code retrieves Python list object from encoded string in earlier step. d=json.JSONDecoder() d.decode(s) The json module defines load() and dump() functions to write JSON data to a file like object – which may be a disk file or a byte stream and read data back from them. This function writes JSONed Python object data to a file. The file must be opened with ‘w’ mode. import json data=['Rakesh', {'marks': (50, 60, 70)}] fp=open('json.txt','w') json.dump(data,fp) fp.close() This code will create ‘json.txt’ in current directory. It shows the contents as follows − ["Rakesh", {"marks": [50, 60, 70]}] This function loads JSON data from the file and returns Python object from it. The file must be opened with read permission (should have ‘r’ mode). Example fp=open('json.txt','r') ret=json.load(fp) print (ret) fp.close() Output ['Rakesh', {'marks': [50, 60, 70]}] The json.tool module also has a command-line interface that validates data in file and prints JSON object in a pretty formatted manner. C:\python37>python -m json.tool json.txt [ "Rakesh", { "marks": [ 50, 60, 70 ] } ] XML is acronym for eXtensible Markup Language. It is a portable, open source and cross platform language very much like HTML or SGML and recommended by the World Wide Web Consortium. It is a well-known data interchange format, used by a large number of applications such as web services, office tools, and Service Oriented Architectures (SOA). XML format is both machine readable and human readable. Standard Python library's xml package consists of following modules for XML processing − xml.etree.ElementTree the ElementTree API, a simple and lightweight XML processor xml.dom the DOM API definition xml.dom.minidom a minimal DOM implementation xml.sax SAX2 interface implementation xml.parsers.expat the Expat parser binding Data in the XML document is arranged in a tree-like hierarchical format, starting with root and elements. Each element is a single node in the tree and has an attribute enclosed in <> and </> tags. One or more sub-elements may be assigned to each element. Following is a typical example of a XML document − <?xml version = "1.0" encoding = "iso-8859-1"?> <studentlist> <student> <name>Ratna</name> <subject>Physics</subject> <marks>85</marks> </student> <student> <name>Kiran</name> <subject>Maths</subject> <marks>100</marks> </student> <student> <name>Mohit</name> <subject>Biology</subject> <marks>92</marks> </student> </studentlist> While using ElementTree module, first step is to set up root element of the tree. Each Element has a tag and attrib which is a dict object. For the root element, an attrib is an empty dictionary. import xml.etree.ElementTree as xmlobj root=xmlobj.Element('studentList') Now, we can add one or more elements under root element. Each element object may have SubElements. Each subelement has an attribute and text property. student=xmlobj.Element('student') nm=xmlobj.SubElement(student, 'name') nm.text='name' subject=xmlobj.SubElement(student, 'subject') nm.text='Ratna' subject.text='Physics' marks=xmlobj.SubElement(student, 'marks') marks.text='85' This new element is appended to the root using append() method. root.append(student) Append as many elements as desired using above method. Finally, the root element object is written to a file. tree = xmlobj.ElementTree(root) file = open('studentlist.xml','wb') tree.write(file) file.close() Now, we see how to parse the XML file. For that, construct document tree giving its name as file parameter in ElementTree constructor. tree = xmlobj.ElementTree(file='studentlist.xml') The tree object has getroot() method to obtain root element and getchildren() returns a list of elements below it. root = tree.getroot() children = root.getchildren() A dictionary object corresponding to each sub element is constructed by iterating over sub-element collection of each child node. for child in children: student={} pairs = child.getchildren() for pair in pairs: product[pair.tag]=pair.text Each dictionary is then appended to a list returning original list of dictionary objects. SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX requires ContentHandler by subclassing xml.sax.ContentHandler. You register callbacks for events of interest and then, let the parser proceed through the document. SAX is useful when your documents are large or you have memory limitations as it parses the file as it reads it from disk as a result entire file is never stored in the memory. (DOM) API is a World Wide Web Consortium recommendation. In this case, entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX, not as fast as DOM, with large files. On the other hand, DOM can kill resources, if used on many small files. SAX is read-only, while DOM allows changes to the XML file. The plist format is mainly used by MAC OS X. These files are basically XML documents. They store and retrieve properties of an object. Python library contains plist module, that is used to read and write 'property list' files (they usually have .plist' extension). The plistlib module is more or less similar to other serialization libraries in the sense, it also provides dumps() and loads() functions for string representation of Python objects and load() and dump() functions for disk operation. Following dictionary object maintains property (key) and corresponding value − proplist = { "name" : "Ganesh", "designation":"manager", "dept":"accts", "salary" : {"basic":12000, "da":4000, "hra":800} } In order to write these properties in a disk file, we call dump() function in plist module. import plistlib fileName=open('salary.plist','wb') plistlib.dump(proplist, fileName) fileName.close() Conversely, to read back the property values, use load() function as follows − fp= open('salary.plist', 'rb') pl = plistlib.load(fp) print(pl) One major disadvantage of CSV, JSON, XML, etc., files is that they are not very useful for random access and transaction processing because they are largely unstructured in nature. Hence, it becomes very difficult to modify the contents. These flat files are not suitable for client-server environment as they lack asynchronous processing capability. Using unstructured data files leads to data redundancy and inconsistency. These problems can be overcome by using a relational database. A database is an organized collection of data to remove redundancy and inconsistency, and maintain data integrity. The relational database model is vastly popular. Its basic concept is to arrange data in entity table (called relation). The entity table structure provides one attribute whose value is unique for each row. Such an attribute is called 'primary key'. When primary key of one table appears in the structure of other tables, it is called 'Foreign key' and this forms the basis of the relationship between the two. Based on this model, there are many popular RDBMS products currently available − GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase SQLite SQLite is a lightweight relational database used in a wide variety of applications. It is a self-contained, serverless, zero-configuration, transactional SQL database engine. The entire database is a single file, that can be placed anywhere in the file system. It's an open-source software, with very small footprint, and zero configuration. It is popularly used in embedded devices, IOT and mobile apps. All relational databases use SQL for handling data in tables. However, earlier, each of these databases used to be connected with Python application with the help of Python module specific to the type of database. Hence, there was a lack of compatibility among them. If a user wanted to change to different database product, it would prove to be difficult. This incompatibility issue was addresses by raising 'Python Enhancement Proposal (PEP 248)' to recommend consistent interface to relational databases known as DB-API. Latest recommendations are called DB-API Version 2.0. (PEP 249) Python's standard library consists of the sqlite3 module which is a DB-API compliant module for handling the SQLite database through Python program. This chapter explains Python's connectivity with SQLite database. As mentioned earlier, Python has inbuilt support for SQLite database in the form of sqlite3 module. For other databases, respective DB-API compliant Python module will have to be installed with the help of pip utility. For example, to use MySQL database we need to install PyMySQL module. pip install pymysql Following steps are recommended in DB-API − Establish connection with the database using connect() function and obtain connection object. Establish connection with the database using connect() function and obtain connection object. Call cursor() method of connection object to get cursor object. Call cursor() method of connection object to get cursor object. Form a query string made up of a SQL statement to be executed. Form a query string made up of a SQL statement to be executed. Execute the desired query by invoking execute() method. Execute the desired query by invoking execute() method. Close the connection. Close the connection. import sqlite3 db=sqlite3.connect('test.db') Here, db is the connection object representing test.db. Note, that database will be created if it doesn’t exist already. The connection object db has following methods − cursor(): Returns a Cursor object which uses this Connection. commit(): Explicitly commits any pending transactions to the database. rollback(): This optional method causes a transaction to be rolled back to the starting point. close(): Closes the connection to the database permanently. A cursor acts as a handle for a given SQL query allowing the retrieval of one or more rows of the result. Cursor object is obtained from the connection to execute SQL queries using the following statement − cur=db.cursor() The cursor object has following methods defined − execute() Executes the SQL query in a string parameter. executemany() Executes the SQL query using a set of parameters in the list of tuples. fetchone() Fetches the next row from the query result set. fetchall() Fetches all remaining rows from the query result set. callproc() Calls a stored procedure. close() Closes the cursor object. Following code creates a table in test.db:- import sqlite3 db=sqlite3.connect('test.db') cur =db.cursor() cur.execute('''CREATE TABLE student ( StudentID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT (20) NOT NULL, age INTEGER, marks REAL);''') print ('table created successfully') db.close() Data integrity desired in a database is achieved by commit() and rollback() methods of the connection object. The SQL query string may be having an incorrect SQL query that can raise an exception, which should be properly handled. For that, the execute() statement is placed within the try block If it is successful, the result is persistently saved using the commit() method. If the query fails, the transaction is undone using the rollback() method. Following code executes INSERT query on the student table in test.db. import sqlite3 db=sqlite3.connect('test.db') qry="insert into student (name, age, marks) values('Abbas', 20, 80);" try: cur=db.cursor() cur.execute(qry) db.commit() print ("record added successfully") except: print ("error in query") db.rollback() db.close() If you want data in values clause of INSERT query to by dynamically provided by user input, use parameter substitution as recommended in Python DB-API. The ? character is used as a placeholder in the query string and provides the values in the form of a tuple in the execute() method. The following example inserts a record using the parameter substitution method. Name, age and marks are taken as input. import sqlite3 db=sqlite3.connect('test.db') nm=input('enter name') a=int(input('enter age')) m=int(input('enter marks')) qry="insert into student (name, age, marks) values(?,?,?);" try: cur=db.cursor() cur.execute(qry, (nm,a,m)) db.commit() print ("one record added successfully") except: print("error in operation") db.rollback() db.close() The sqlite3 module defines The executemany() method which is able to add multiple records at once. Data to be added should be given in a list of tuples, with each tuple containing one record. The list object is the parameter of the executemany() method, along with the query string. However, executemany() method is not supported by some of the other modules. The UPDATE query usually contains a logical expression specified by WHERE clause The query string in the execute() method should contain an UPDATE query syntax. To update the value of 'age' to 23 for name='Anil', define the string as below: qry="update student set age=23 where name='Anil';" To make the update process more dynamic, we use the parameter substitution method as described above. import sqlite3 db=sqlite3.connect('test.db') nm=input(‘enter name’) a=int(input(‘enter age’)) qry="update student set age=? where name=?;" try: cur=db.cursor() cur.execute(qry, (a, nm)) db.commit() print("record updated successfully") except: print("error in query") db.rollback() db.close() Similarly, DELETE operation is performed by calling execute() method with a string having SQL’s DELETE query syntax. Incidentally, DELETE query also usually contains a WHERE clause. import sqlite3 db=sqlite3.connect('test.db') nm=input(‘enter name’) qry="DELETE from student where name=?;" try: cur=db.cursor() cur.execute(qry, (nm,)) db.commit() print("record deleted successfully") except: print("error in operation") db.rollback() db.close() One of the important operations on a database table is retrieval of records from it. SQL provides SELECT query for the purpose. When a string containing SELECT query syntax is given to execute() method, a result set object is returned. There are two important methods with a cursor object using which one or many records from the result set can be retrieved. Fetches the next available record from the result set. It is a tuple consisting of values of each column of the fetched record. Fetches all remaining records in the form of a list of tuples. Each tuple corresponds to one record and contains values of each column in the table. Following example lists all records in student table import sqlite3 db=sqlite3.connect('test.db') 37 sql="SELECT * from student;" cur=db.cursor() cur.execute(sql) while True: record=cur.fetchone() if record==None: break print (record) db.close() If you plan to use a MySQL database instead of SQLite database, you need to install PyMySQL module as described above. All the steps in database connectivity process being same, since MySQL database is installed on a server, the connect() function needs the URL and login credentials. import pymysql con=pymysql.connect('localhost', 'root', '***') Only thing that may differ with SQLite is MySQL specific data types. Similarly, any ODBC compatible database can be used with Python by installing pyodbc module. Any relational database holds data in tables. The table structure defines data type of attributes which are basically of primary data types only which are mapped to corresponding built-in data types of Python. However, Python's user-defined objects can't be persistently stored and retrieved to/from SQL tables. This is a disparity between SQL types and object oriented programming languages such as Python. SQL doesn't have equivalent data type for others such as dict, tuple, list, or any user defined class. If you have to store an object in a relational database, it's instance attributes should be deconstructed into SQL data types first, before executing INSERT query. On the other hand, data retrieved from a SQL table is in primary types. A Python object of desired type will have to be constructed by using for use in Python script. This is where Object Relational Mappers are useful. An Object Relation Mapper (ORM) is an interface between a class and a SQL table. A Python class is mapped to a certain table in database, so that conversion between object and SQL types is automatically performed. The Students class written in Python code is mapped to Students table in the database. As a result, all CRUD operations are done by calling respective methods of the class. This eliminates need to execute hard coded SQL queries in Python script. ORM library thus acts as an abstraction layer over the raw SQL queries and can be of help in rapid application development. SQLAlchemy is a popular object relational mapper for Python. Any manipulation of state of model object is synchronized with its related row in the database table. SQLALchemy library includes ORM API and SQL Expression Language (SQLAlchemy Core). Expression language executes primitive constructs of the relational database directly. ORM is a high level and abstracted pattern of usage constructed on top of the SQL Expression Language. It can be said that ORM is an applied usage of the Expression Language. We shall discuss SQLAlchemy ORM API and use SQLite database in this topic. SQLAlchemy communicates with various types of databases through their respective DBAPI implementations using a dialect system. All dialects require that an appropriate DBAPI driver is installed. Dialects for following type of databases are included − Firebird Microsoft SQL Server MySQL Oracle PostgreSQL SQLite Sybase Installation of SQLAlchemy is easy and straightforward, using pip utility. pip install sqlalchemy To check if SQLalchemy is properly installed and its version, enter following on Python prompt − >>> import sqlalchemy >>>sqlalchemy.__version__ '1.3.11' Interactions with database are done through Engine object obtained as a return value of create_engine() function. engine =create_engine('sqlite:///mydb.sqlite') SQLite allows creation of in-memory database. SQLAlchemy engine for in-memory database is created as follows − from sqlalchemy import create_engine engine=create_engine('sqlite:///:memory:') If you intend to use MySQL database instead, use its DB-API module – pymysql and respective dialect driver. engine = create_engine('mysql+pymydsql://root@localhost/mydb') The create_engine has an optional echo argument. If set to true, the SQL queries generated by engine will be echoed on the terminal. SQLAlchemy contains declarative base class. It acts as a catalog of model classes and mapped tables. from sqlalchemy.ext.declarative import declarative_base base=declarative_base() Next step is to define a model class. It must be derived from base – object of declarative_base class as above. Set __tablename__ property to name of the table you want to be created in the database. Other attributes correspond to the fields. Each one is a Column object in SQLAlchemy and its data type is from one of the list below − BigInteger Boolean Date DateTime Float Integer Numeric SmallInteger String Text Time Following code is the model class named as Student that is mapped to Students table. #myclasses.py from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Numeric base=declarative_base() class Student(base): __tablename__='Students' StudentID=Column(Integer, primary_key=True) name=Column(String) age=Column(Integer) marks=Column(Numeric) To create a Students table that has a corresponding structure, execute create_all() method defined for base class. base.metadata.create_all(engine) We now have to declare an object of our Student class. All database transactions such as add, delete or retrieve data from database, etc., are handled by a Session object. from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) sessionobj = Session() Data stored in Student object is physically added in underlying table by session’s add() method. s1 = Student(name='Juhi', age=25, marks=200) sessionobj.add(s1) sessionobj.commit() Here, is the entire code for adding record in students table. As it is executed, corresponding SQL statement log is displayed on console. from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine from myclasses import Student, base engine = create_engine('sqlite:///college.db', echo=True) base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) sessionobj = Session() s1 = Student(name='Juhi', age=25, marks=200) sessionobj.add(s1) sessionobj.commit() CREATE TABLE "Students" ( "StudentID" INTEGER NOT NULL, name VARCHAR, age INTEGER, marks NUMERIC, PRIMARY KEY ("StudentID") ) INFO sqlalchemy.engine.base.Engine () INFO sqlalchemy.engine.base.Engine COMMIT INFO sqlalchemy.engine.base.Engine BEGIN (implicit) INFO sqlalchemy.engine.base.Engine INSERT INTO "Students" (name, age, marks) VALUES (?, ?, ?) INFO sqlalchemy.engine.base.Engine ('Juhi', 25, 200.0) INFO sqlalchemy.engine.base.Engine COMMIT The session object also provides add_all() method to insert more than one objects in a single transaction. sessionobj.add_all([s2,s3,s4,s5]) sessionobj.commit() Now that, records are added in the table, we would like to fetch from it just as SELECT query does. The session object has query() method to perform the task. Query object is returned by query() method on our Student model. qry=seesionobj.query(Student) Use the get() method of this Query object fetches object corresponding to given primary key. S1=qry.get(1) While this statement is executed, its corresponding SQL statement echoed on the console will be as follows − BEGIN (implicit) SELECT "Students"."StudentID" AS "Students_StudentID", "Students".name AS "Students_name", "Students".age AS "Students_age", "Students".marks AS "Students_marks" FROM "Students" WHERE "Products"."Students" = ? sqlalchemy.engine.base.Engine (1,) The query.all() method returns a list of all objects which can be traversed using a loop. from sqlalchemy import Column, Integer, String, Numeric from sqlalchemy import create_engine from myclasses import Student,base engine = create_engine('sqlite:///college.db', echo=True) base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) sessionobj = Session() qry=sessionobj.query(Students) rows=qry.all() for row in rows: print (row) Updating a record in the mapped table is very easy. All you have to do is fetch a record using get() method, assign a new value to desired attribute and then commit the changes using session object. Below we change marks of Juhi student to 100. S1=qry.get(1) S1.marks=100 sessionobj.commit() Deleting a record is just as easy, by deleting desired object from the session. S1=qry.get(1) Sessionobj.delete(S1) sessionobj.commit() MongoDB is a document oriented NoSQL database. It is a cross platform database distributed under server side public license. It uses JSON like documents as schema. In order to provide capability to store huge data, more than one physical servers (called shards) are interconnected, so that a horizontal scalability is achieved. MongoDB database consists of documents. A document is analogous to a row in a table of relational database. However, it doesn't have a particular schema. Document is a collection of key-value pairs - similar to dictionary. However, number of k-v pairs in each document may vary. Just as a table in relational database has a primary key, document in MongoDB database has a special key called "_id". Before we see how MongoDB database is used with Python, let us briefly understand how to install and start MongoDB. Community and commercial version of MongoDB is available. Community version can be downloaded from www.mongodb.com/download-center/community. Assuming that MongoDB is installed in c:\mongodb, the server can be invoked using following command. c:\mongodb\bin>mongod The MongoDB server is active at port number 22017 by default. Databases are stored in data/bin folder by default, although the location can be changed by –dbpath option. MongoDB has its own set of commands to be used in a MongoDB shell. To invoke shell, use Mongo command. x:\mongodb\bin>mongo A shell prompt similar to MySQL or SQLite shell prompt, appears before which native NoSQL commands can be executed. However, we are interested in connecting MongoDB database to Python. PyMongo module has been developed by MongoDB Inc itself to provide Python programming interface. Use well known pip utility to install PyMongo. pip3 install pymongo Assuming that MongoDB server is up and running (with mongod command) and is listening at port 22017, we first need to declare a MongoClient object. It controls all transactions between Python session and the database. from pymongo import MongoClient client=MongoClient() Use this client object to establish connection with MongoDB server. client = MongoClient('localhost', 27017) A new database is created with following command. db=client.newdb MongoDB database can have many collections, similar to tables in a relational database. A Collection object is created by Create_collection() function. db.create_collection('students') Now, we can add one or more documents in the collection as follows − from pymongo import MongoClient client=MongoClient() db=client.newdb db.create_collection("students") student=db['students'] studentlist=[{'studentID':1,'Name':'Juhi','age':20, 'marks'=100}, {'studentID':2,'Name':'dilip','age':20, 'marks'=110}, {'studentID':3,'Name':'jeevan','age':24, 'marks'=145}] student.insert_many(studentlist) client.close() To retrieve the documents (similar to SELECT query), we should use find() method. It returns a cursor with the help of which all documents can be obtained. students=db['students'] docs=students.find() for doc in docs: print (doc['Name'], doc['age'], doc['marks'] ) To find a particular document instead of all of them in a collection, we need to apply filter to find() method. The filter uses logical operators. MongoDB has its own set of logical operators as below − $eq equal to (==) $gt greater than (>) $gte greater than or equal to (>=) $in if equal to any value in array $lt less than (<) $lte less than or equal to (<=) $ne not equal to (!=) $nin if not equal to any value in array For example, we are interested in obtaining list of students older than 21 years. Using $gt operator in the filter for find() method as follows − students=db['students'] docs=students.find({'age':{'$gt':21}}) for doc in docs: print (doc.get('Name'), doc.get('age'), doc.get('marks')) PyMongo module provides update_one() and update_many() methods for modifying one document or more than one documents satisfying a specific filter expression. Let us update marks attribute of a document in which name is Juhi. from pymongo import MongoClient client=MongoClient() db=client.newdb doc=db.students.find_one({'Name': 'Juhi'}) db['students'].update_one({'Name': 'Juhi'},{"$set":{'marks':150}}) client.close() Cassandra is another popular NoSQL database. High scalability, consistency, and fault-tolerance - these are some of the important features of Cassandra. This is Column store database. The data is stored across many commodity servers. As a result, data highly available. Cassandra is a product from Apache Software foundation. Data is stored in distributed manner across multiple nodes. Each node is a single server consisting of keyspaces. Fundamental building block of Cassandra database is keyspace which can be considered analogous to a database. Data in one node of Cassandra, is replicated in other nodes over a peer-to-peer network of nodes. That makes Cassandra a foolproof database. The network is called a data center. Multiple data centers may be interconnected to form a cluster. Nature of replication is configured by setting Replication strategy and replication factor at the time of the creation of a keyspace. One keyspace may have more than one Column families – just as one database may contain multiple tables. Cassandra’s keyspace doesn’t have a predefined schema. It is possible that each row in a Cassandra table may have columns with different names and in variable numbers. Cassandra software is also available in two versions: community and enterprise. The latest enterprise version of Cassandra is available for download at https://cassandra.apache.org/download/. Community edition is found at https://academy.datastax.com/planet-cassandra/cassandra. Cassandra has its own query language called Cassandra Query Language (CQL). CQL queries can be executed from inside a CQLASH shell – similar to MySQL or SQLite shell. The CQL syntax appears similar to standard SQL. The Datastax community edition, also comes with a Develcenter IDE shown in following figure − Python module for working with Cassandra database is called Cassandra Driver. It is also developed by Apache foundation. This module contains an ORM API, as well as a core API similar in nature to DB-API for relational databases. Installation of Cassandra driver is easily done using pip utility. pip3 install cassandra-driver Interaction with Cassandra database, is done through Cluster object. Cassandra.cluster module defines Cluster class. We first need to declare Cluster object. from cassandra.cluster import Cluster clstr=Cluster() All transactions such as insert/update, etc., are performed by starting a session with a keyspace. session=clstr.connect() To create a new keyspace, use execute() method of session object. The execute() method takes a string argument which must be a query string. The CQL has CREATE KEYSPACE statement as follows. The complete code is as below − from cassandra.cluster import Cluster clstr=Cluster() session=clstr.connect() session.execute(“create keyspace mykeyspace with replication={ 'class': 'SimpleStrategy', 'replication_factor' : 3 };” Here, SimpleStrategy is a value for replication strategy and replication factor is set to 3. As mentioned earlier, a keyspace contains one or more tables. Each table is characterized by it data type. Python data types are automatically parsed with corresponding CQL data types according to following table − To create a table, use session object to execute CQL query for creating a table. from cassandra.cluster import Cluster clstr=Cluster() session=clstr.connect('mykeyspace') qry= ''' create table students ( studentID int, name text, age int, marks int, primary key(studentID) );''' session.execute(qry) The keyspace so created can be further used to insert rows. The CQL version of INSERT query is similar to SQL Insert statement. Following code inserts a row in students table. from cassandra.cluster import Cluster clstr=Cluster() session=clstr.connect('mykeyspace') session.execute("insert into students (studentID, name, age, marks) values (1, 'Juhi',20, 200);" As you would expect, SELECT statement is also used with Cassandra. In case of execute() method containing SELECT query string, it returns a result set object which can be traversed using a loop. from cassandra.cluster import Cluster clstr=Cluster() session=clstr.connect('mykeyspace') rows=session.execute("select * from students;") for row in rows: print (StudentID: {} Name:{} Age:{} price:{} Marks:{}' .format(row[0],row[1], row[2], row[3])) Cassandra’s SELECT query supports use of WHERE clause to apply filter on result set to be fetched. Traditional logical operators like <, > == etc. are recognized. To retrieve, only those rows from students table for names with age>20, the query string in execute() method should be as follows − rows=session.execute("select * from students WHERE age>20 allow filtering;") Note, the use of ALLOW FILTERING. The ALLOW FILTERING part of this statement allows to explicitly allow (some) queries that require filtering. Cassandra driver API defines following classes of Statement type in its cassendra.query module. A simple, unprepared CQL query contained in a query string. All examples above are examples of SimpleStatement. Multiple queries (such as INSERT, UPDATE, and DELETE) are put in a batch and executed at once. Each row is first converted as a SimpleStatement and then added in a batch. Let us put rows to be added in Students table in the form of list of tuples as follows − studentlist=[(1,'Juhi',20,100), ('2,'dilip',20, 110),(3,'jeevan',24,145)] To add above rows using BathStatement, run following script − from cassandra.query import SimpleStatement, BatchStatement batch=BatchStatement() for student in studentlist: batch.add(SimpleStatement("INSERT INTO students (studentID, name, age, marks) VALUES (%s, %s, %s %s)"), (student[0], student[1],student[2], student[3])) session.execute(batch) Prepared statement is like a parameterized query in DB-API. Its query string is saved by Cassandra for later use. The Session.prepare() method returns a PreparedStatement instance. For our students table, a PreparedStatement for INSERT query is as follows − stmt=session.prepare("INSERT INTO students (studentID, name, age, marks) VALUES (?,?,?)") Subsequently, it only needs to send the values of parameters to bind. For example − qry=stmt.bind([1,'Ram', 23,175]) Finally, execute the bound statement above. session.execute(qry) This reduces network traffic and CPU utilization because Cassandra does not have to re-parse the query each time. ZODB (Zope object Database) is database for storing Python objects. It is ACID compliant - feature not found in NOSQL databases. The ZODB is also open source, horizontally scalable and schema-free, like many NoSQL databases. However, it is not distributed and does not offer easy replication. It provides persistence mechanism for Python objects. It is a part of Zope Application server, but can also be independently used. ZODB was created by Jim Fulton of Zope Corporation. It started as simple Persistent Object System. Its current version is 5.5.0 and is written completely in Python. using an extended version of Python's built-in object persistence (pickle). Some of the main features of ZODB are − transactions history/undo transparently pluggable storage built-in caching multiversion concurrency control (MVCC) scalability across a network The ZODB is a hierarchical database. There is a root object, initialized when a database is created. The root object is used like a Python dictionary and it can contain other objects (which can be dictionary-like themselves). To store an object in the database, it’s enough to assign it to a new key inside its container. ZODB is useful for applications where data is hierarchical and there are likely to be more reads than writes. ZODB is an extension of pickle object. That's why it can be processed through Python script only. To install latest version of ZODB let use pip utility − pip install zodb Following dependencies are also installed − BTrees==4.6.1 cffi==1.13.2 persistent==4.5.1 pycparser==2.19 six==1.13.0 transaction==2.4.0 ZODB provides following storage options − This is the default. Everything stored in one big Data.fs file, which is essentially a transaction log. This stores one file per object revision. In this case, it does not require the Data.fs.index to be rebuilt on an unclean shutdown. This stores pickles in a relational database. PostgreSQL, MySQL and Oracle are supported. To create ZODB database we need a storage, a database and finally a connection. First step is to have storage object. import ZODB, ZODB.FileStorage storage = ZODB.FileStorage.FileStorage('mydata.fs') DB class uses this storage object to obtain database object. db = ZODB.DB(storage) Pass None to DB constructor to create in-memory database. Db=ZODB.DB(None) Finally, we establish connection with the database. conn=db.open() The connection object then gives you access to the ‘root’ of the database with the ‘root()’ method. The ‘root’ object is the dictionary that holds all of your persistent objects. root = conn.root() For example, we add a list of students to the root object as follows − root['students'] = ['Mary', 'Maya', 'Meet'] This change is not permanently saved in the database till we commit the transaction. import transaction transaction.commit() To store object of a user defined class, the class must be inherited from persistent.Persistent parent class. Subclassing Persistent class has its advantages as follows − The database will automatically track object changes made by setting attributes. The database will automatically track object changes made by setting attributes. Data will be saved in its own database record. Data will be saved in its own database record. You can save data that doesn’t subclass Persistent, but it will be stored in the database record of whatever persistent object references it. Non-persistent objects are owned by their containing persistent object and if multiple persistent objects refer to the same non-persistent subobject, they’ll get their own copies. You can save data that doesn’t subclass Persistent, but it will be stored in the database record of whatever persistent object references it. Non-persistent objects are owned by their containing persistent object and if multiple persistent objects refer to the same non-persistent subobject, they’ll get their own copies. Let use define a student class subclassing Persistent class as under − import persistent class student(persistent.Persistent): def __init__(self, name): self.name = name def __repr__(self): return str(self.name) To add object of this class, let us first set up the connection as described above. import ZODB, ZODB.FileStorage storage = ZODB.FileStorage.FileStorage('studentdata.fs') db = ZODB.DB(storage) conn=db.open() root = conn.root() Declare object an add to root and then commit the transaction s1=student("Akash") root['s1']=s1 import transaction transaction.commit() conn.close() List of all objects added to root can be retrieved as a view object with the help of items() method since root object is similar to built in dictionary. print (root.items()) ItemsView({'s1': Akash}) To fetch attribute of specific object from root, print (root['s1'].name) Akash The object can be easily updated. Since the ZODB API is a pure Python package, it doesn’t require any external SQL type language to be used. root['s1'].name='Abhishek' import transaction transaction.commit() The database will be updated instantly. Note that transaction class also defines abort() function which is similar to rollback() transaction control in SQL. Microsoft’s Excel is the most popular spreadsheet application. It has been in use since last more than 25 years. Later versions of Excel use Office Open XML (OOXML) file format. Hence, it has been possible to access spreadsheet files through other programming environments. OOXML is an ECMA standard file format. Python’s openpyxl package provides functionality to read/write Excel files with .xlsx extension. The openpyxl package uses class nomenclature that is similar to Microsoft Excel terminology. An Excel document is called as workbook and is saved with .xlsx extension in the file system. A workbook may have multiple worksheets. A worksheet presents a large grid of cells, each one of them can store either value or formula. Rows and columns that form the grid are numbered. Columns are identified by alphabets, A, B, C, ...., Z, AA, AB, and so on. Rows are numbered starting from 1. A typical Excel worksheet appears as follows − The pip utility is good enough to install openpyxl package. pip install openpyxl The Workbook class represents an empty workbook with one blank worksheet. We need to activate it so that some data can be added to the worksheet. from openpyxl import Workbook wb=Workbook() sheet1=wb.active sheet1.title='StudentList' As we know, a cell in worksheet is named as ColumnNameRownumber format. Accordingly, top left cell is A1. We assign a string to this cell as − sheet1['A1']= 'Student List' Alternately, use worksheet’s cell() method which uses row and column number to identify a cell. Call value property to cell object to assign a value. cell1=sheet1.cell(row=1, column=1) cell1.value='Student List' After populating worksheet with data, the workbook is saved by calling save() method of workbook object. wb.save('Student.xlsx') This workbook file is created in current working directory. Following Python script writes a list of tuples into a workbook document. Each tuple stores roll number, age and marks of student. from openpyxl import Workbook wb = Workbook() sheet1 = wb.active sheet1.title='Student List' sheet1.cell(column=1, row=1).value='Student List' studentlist=[('RollNo','Name', 'age', 'marks'),(1,'Juhi',20,100), (2,'dilip',20, 110) , (3,'jeevan',24,145)] for col in range(1,5): for row in range(1,5): sheet1.cell(column=col, row=1+row).value=studentlist[row-1][col-1] wb.save('students.xlsx') The workbook students.xlsx is saved in current working directory. If opened using Excel application, it appears as below − The openpyxl module offers load_workbook() function that helps in reading back data in the workbook document. from openpyxl import load_workbook wb=load_workbook('students.xlsx') You can now access value of any cell specified by row and column number. cell1=sheet1.cell(row=1, column=1) print (cell1.value) Student List Following code populates a list with work sheet data. from openpyxl import load_workbook wb=load_workbook('students.xlsx') sheet1 = wb['Student List'] studentlist=[] for row in range(1,5): stud=[] for col in range(1,5): val=sheet1.cell(column=col, row=1+row).value stud.append(val) studentlist.append(tuple(stud)) print (studentlist) [('RollNo', 'Name', 'age', 'marks'), (1, 'Juhi', 20, 100), (2, 'dilip', 20, 110), (3, 'jeevan', 24, 145)] One very important feature of Excel application is the formula. To assign formula to a cell, assign it to a string containing Excel’s formula syntax. Assign AVERAGE function to c6 cell having age. sheet1['C6']= 'AVERAGE(C3:C5)' Openpyxl module has Translate_formula() function to copy the formula across a range. Following program defines AVERAGE function in C6 and copies it to C7 that calculates average of marks. from openpyxl import load_workbook wb=load_workbook('students.xlsx') sheet1 = wb['Student List'] from openpyxl.formula.translate import Translator#copy formula sheet1['B6']='Average' sheet1['C6']='=AVERAGE(C3:C5)' sheet1['D6'] = Translator('=AVERAGE(C3:C5)', origin="C6").translate_formula("D6") wb.save('students.xlsx') The changed worksheet now appears as follows −
[ { "code": null, "e": 2737, "s": 2489, "text": "During the course of using any software application, user provides some data to be processed. The data may be input, using a standard input device (keyboard) or other devices such as disk file, scanner, camera, network cable, WiFi connection, etc." }, { "code": null, "e": 2950, "s": 2737, "text": "Data so received, is stored in computer’s main memory (RAM) in the form of various data structures such as, variables and objects until the application is running. Thereafter, memory contents from RAM are erased." }, { "code": null, "e": 3152, "s": 2950, "text": "However, more often than not, it is desired that the values of variables and/or objects be stored in such a manner, that it can be retrieved whenever required, instead of again inputting the same data." }, { "code": null, "e": 3434, "s": 3152, "text": "The word ‘persistence’ means \"the continuance of an effect after its cause is removed\". The term data persistence means it continues to exist even after the application has ended. Thus, data stored in a non-volatile storage medium such as, a disk file is a persistent data storage." }, { "code": null, "e": 3662, "s": 3434, "text": "In this tutorial, we will explore various built-in and third party Python modules to store and retrieve data to/from various formats such as text file, CSV, JSON and XML files as well as relational and non-relational databases." }, { "code": null, "e": 3899, "s": 3662, "text": "Using Python’s built-in File object, it is possible to write string data to a disk file and read from it. Python’s standard library, provides modules to store and retrieve serialized data in various data structures such as JSON and XML." }, { "code": null, "e": 4102, "s": 3899, "text": "Python’s DB-API provides a standard way of interacting with relational databases. Other third party Python packages, present interfacing functionality with NOSQL databases such as MongoDB and Cassandra." }, { "code": null, "e": 4326, "s": 4102, "text": "This tutorial also introduces, ZODB database which is a persistence API for Python objects. Microsoft Excel format is a very popular data file format. In this tutorial, we will learn how to handle .xlsx file through Python." }, { "code": null, "e": 4507, "s": 4326, "text": "Python uses built-in input() and print() functions to perform standard input/output operations. The input() function reads bytes from a standard input stream device, i.e. keyboard." }, { "code": null, "e": 4745, "s": 4507, "text": "The print() function on the other hand, sends the data towards standard output stream device i.e. the display monitor. Python program interacts with these IO devices through standard stream objects stdin and stdout defined in sys module." }, { "code": null, "e": 4913, "s": 4745, "text": "The input() function is actually a wrapper around readline() method of sys.stdin object. All keystrokes from the input stream are received till ‘Enter’ key is pressed." }, { "code": null, "e": 5017, "s": 4913, "text": ">>> import sys\n>>> x=sys.stdin.readline()\nWelcome to TutorialsPoint\n>>> x\n'Welcome to TutorialsPoint\\n'" }, { "code": null, "e": 5198, "s": 5017, "text": "Note that, readline() function leave a trailing ‘\\n’ character. There is also a read() method which reads data from standard input stream till it is terminated by Ctrl+D character." }, { "code": null, "e": 5296, "s": 5198, "text": ">>> x=sys.stdin.read()\nHello\nWelcome to TutorialsPoint\n>>> x\n'Hello\\nWelcome to TutorialsPoint\\n'" }, { "code": null, "e": 5384, "s": 5296, "text": "Similarly, print() is a convenience function emulating write() method of stdout object." }, { "code": null, "e": 5473, "s": 5384, "text": ">>> x='Welcome to TutorialsPoint\\n'\n>>> sys.stdout.write(x)\nWelcome to TutorialsPoint\n26" }, { "code": null, "e": 5868, "s": 5473, "text": "Just as stdin and stdout predefined stream objects, a Python program can read data from and send data to a disk file or a network socket. They are also streams. Any object that has read() method is an input stream. Any object that has write() method is an output stream. The communication with the stream is established by obtaining reference to the stream object with built-in open() function." }, { "code": null, "e": 5918, "s": 5868, "text": "This built-in function uses following arguments −" }, { "code": null, "e": 5949, "s": 5918, "text": "f=open(name, mode, buffering)\n" }, { "code": null, "e": 6216, "s": 5949, "text": "The name parameter, is name of disk file or byte string, mode is optional one-character string to specify the type of operation to be performed (read, write, append etc.) and buffering parameter is either 0, 1 or -1 indicating buffering is off, on or system default." }, { "code": null, "e": 6288, "s": 6216, "text": "File opening mode is enumerated as per table below. Default mode is ‘r’" }, { "code": null, "e": 6290, "s": 6288, "text": "R" }, { "code": null, "e": 6317, "s": 6290, "text": "Open for reading (default)" }, { "code": null, "e": 6319, "s": 6317, "text": "W" }, { "code": null, "e": 6363, "s": 6319, "text": "Open for writing, truncating the file first" }, { "code": null, "e": 6365, "s": 6363, "text": "X" }, { "code": null, "e": 6407, "s": 6365, "text": "Create a new file and open it for writing" }, { "code": null, "e": 6409, "s": 6407, "text": "A" }, { "code": null, "e": 6473, "s": 6409, "text": "Open for writing, appending to the end of the file if it exists" }, { "code": null, "e": 6475, "s": 6473, "text": "B" }, { "code": null, "e": 6487, "s": 6475, "text": "Binary mode" }, { "code": null, "e": 6489, "s": 6487, "text": "T" }, { "code": null, "e": 6509, "s": 6489, "text": "Text mode (default)" }, { "code": null, "e": 6511, "s": 6509, "text": "+" }, { "code": null, "e": 6563, "s": 6511, "text": "Open a disk file for updating (reading and writing)" }, { "code": null, "e": 6626, "s": 6563, "text": "In order to save data to file it must be opened with ‘w’ mode." }, { "code": null, "e": 6650, "s": 6626, "text": "f=open('test.txt','w')\n" }, { "code": null, "e": 6818, "s": 6650, "text": "This file object acts as an output stream, and has access to write() method. The write() method sends a string to this object, and is stored in the file underlying it." }, { "code": null, "e": 6867, "s": 6818, "text": "string=\"Hello TutorialsPoint\\n\"\nf.write(string)\n" }, { "code": null, "e": 6981, "s": 6867, "text": "It is important to close the stream, to ensure that any data remaining in buffer is completely transferred to it." }, { "code": null, "e": 6995, "s": 6981, "text": "file.close()\n" }, { "code": null, "e": 7099, "s": 6995, "text": "Try and open ‘test.txt’ using any test editor (such as notepad) to confirm successful creation of file." }, { "code": null, "e": 7179, "s": 7099, "text": "To read contents of ‘test.txt’ programmatically, it must be opened in ‘r’ mode." }, { "code": null, "e": 7203, "s": 7179, "text": "f=open('test.txt','r')\n" }, { "code": null, "e": 7302, "s": 7203, "text": "This object behaves as an input stream. Python can fetch data from the stream using read() method." }, { "code": null, "e": 7334, "s": 7302, "text": "string=f.read()\nprint (string)\n" }, { "code": null, "e": 7499, "s": 7334, "text": "Contents of the file are displayed on Python console. The File object also supports readline() method which is able to read string till it encounters EOF character." }, { "code": null, "e": 7750, "s": 7499, "text": "However, if same file is opened in ‘w’ mode to store additional text in it, earlier contents are erased. Whenever, a file is opened with write permission, it is treated as if it is a new file. To add data to an existing file, use ‘a’ for append mode." }, { "code": null, "e": 7804, "s": 7750, "text": "f=open('test.txt','a')\nf.write('Python Tutorials\\n')\n" }, { "code": null, "e": 7962, "s": 7804, "text": "The file now, has earlier as well as newly added string. The file object also supports writelines() method to write each string in a list object to the file." }, { "code": null, "e": 8097, "s": 7962, "text": "f=open('test.txt','a')\nlines=['Java Tutorials\\n', 'DBMS tutorials\\n', 'Mobile development tutorials\\n']\nf.writelines(lines)\nf.close()\n" }, { "code": null, "e": 8265, "s": 8097, "text": "The readlines() method returns a list of strings, each representing a line in the file. It is also possible to read the file line by line until end of file is reached." }, { "code": null, "e": 8378, "s": 8265, "text": "f=open('test.txt','r')\nwhile True:\n line=f.readline()\n if line=='' : break\n print (line, end='')\nf.close()" }, { "code": null, "e": 8476, "s": 8378, "text": "Hello TutorialsPoint\nPython Tutorials\nJava Tutorials\nDBMS tutorials\nMobile development tutorials\n" }, { "code": null, "e": 8720, "s": 8476, "text": "By default, read/write operation on a file object are performed on text string data. If we want to handle files of different other types such as media (mp3), executables (exe), pictures (jpg) etc., we need to add ‘b’ prefix to read/write mode." }, { "code": null, "e": 8792, "s": 8720, "text": "Following statement will convert a string to bytes and write in a file." }, { "code": null, "e": 8862, "s": 8792, "text": "f=open('test.bin', 'wb')\ndata=b\"Hello World\"\nf.write(data)\nf.close()\n" }, { "code": null, "e": 8939, "s": 8862, "text": "Conversion of text string to bytes is also possible using encode() function." }, { "code": null, "e": 8975, "s": 8939, "text": "data=\"Hello World\".encode('utf-8')\n" }, { "code": null, "e": 9087, "s": 8975, "text": "We need to use ‘rb’ mode to read binary file. Returned value of read() method is first decoded before printing." }, { "code": null, "e": 9164, "s": 9087, "text": "f=open('test.bin', 'rb')\ndata=f.read()\nprint (data.decode(encoding='utf-8'))" }, { "code": null, "e": 9283, "s": 9164, "text": "In order to write integer data in a binary file, the integer object should be converted to bytes by to_bytes() method." }, { "code": null, "e": 9372, "s": 9283, "text": "n=25\nn.to_bytes(8,'big')\nf=open('test.bin', 'wb')\ndata=n.to_bytes(8,'big')\nf.write(data)" }, { "code": null, "e": 9476, "s": 9372, "text": "To read back from a binary file, convert output of read() function to integer by from_bytes() function." }, { "code": null, "e": 9555, "s": 9476, "text": "f=open('test.bin', 'rb')\ndata=f.read()\nn=int.from_bytes(data, 'big')\nprint (n)" }, { "code": null, "e": 9641, "s": 9555, "text": "For floating point data, we need to use struct module from Python’s standard library." }, { "code": null, "e": 9726, "s": 9641, "text": "import struct\nx=23.50\ndata=struct.pack('f',x)\nf=open('test.bin', 'wb')\nf.write(data)" }, { "code": null, "e": 9814, "s": 9726, "text": "Unpacking the string from read() function, to retrieve the float data from binary file." }, { "code": null, "e": 9891, "s": 9814, "text": "f=open('test.bin', 'rb')\ndata=f.read()\nx=struct.unpack('f', data)\nprint (x)\n" }, { "code": null, "e": 10096, "s": 9891, "text": "When a file is opened for writing (with ‘w’ or ‘a’), it is not possible, to read from it and vice versa. Doing so throws UnSupportedOperation error. We need to close the file before doing other operation." }, { "code": null, "e": 10394, "s": 10096, "text": "In order to perform both operations simultaneously, we have to add ‘+’ character in the mode parameter. Hence, ‘w+’ or ‘r+’ mode enables using write() as well as read() methods without closing a file. The File object also supports seek() function to rewind the stream to any desired byte position." }, { "code": null, "e": 10490, "s": 10394, "text": "f=open('test.txt','w+')\nf.write('Hello world')\nf.seek(0,0)\ndata=f.read()\nprint (data)\nf.close()" }, { "code": null, "e": 10566, "s": 10490, "text": "Following table summarizes all the methods available to a file like object." }, { "code": null, "e": 10574, "s": 10566, "text": "close()" }, { "code": null, "e": 10641, "s": 10574, "text": "Closes the file. A closed file cannot be read or written any more." }, { "code": null, "e": 10649, "s": 10641, "text": "flush()" }, { "code": null, "e": 10676, "s": 10649, "text": "Flush the internal buffer." }, { "code": null, "e": 10685, "s": 10676, "text": "fileno()" }, { "code": null, "e": 10722, "s": 10685, "text": "Returns the integer file descriptor." }, { "code": null, "e": 10729, "s": 10722, "text": "next()" }, { "code": null, "e": 10828, "s": 10729, "text": "Returns the next line from the file each time it is being called. Use next() iterator in Python 3." }, { "code": null, "e": 10841, "s": 10828, "text": "read([size])" }, { "code": null, "e": 10937, "s": 10841, "text": "Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes)." }, { "code": null, "e": 10954, "s": 10937, "text": "readline([size])" }, { "code": null, "e": 11043, "s": 10954, "text": "Reads one entire line from the file. A trailing newline character is kept in the string." }, { "code": null, "e": 11065, "s": 11043, "text": "readlines([sizehint])" }, { "code": null, "e": 11139, "s": 11065, "text": "Reads until EOF using readline() and returns a list containing the lines." }, { "code": null, "e": 11162, "s": 11139, "text": "seek(offset[, whence])" }, { "code": null, "e": 11221, "s": 11162, "text": "Sets the file's current position. 0-begin 1-current 2-end." }, { "code": null, "e": 11244, "s": 11221, "text": "seek(offset[, whence])" }, { "code": null, "e": 11303, "s": 11244, "text": "Sets the file's current position. 0-begin 1-current 2-end." }, { "code": null, "e": 11310, "s": 11303, "text": "tell()" }, { "code": null, "e": 11346, "s": 11310, "text": "Returns the file's current position" }, { "code": null, "e": 11363, "s": 11346, "text": "truncate([size])" }, { "code": null, "e": 11390, "s": 11363, "text": "Truncates the file's size." }, { "code": null, "e": 11401, "s": 11390, "text": "write(str)" }, { "code": null, "e": 11456, "s": 11401, "text": "Writes a string to the file. There is no return value." }, { "code": null, "e": 11723, "s": 11456, "text": "In addition to File object returned by open() function, file IO operations can also be performed using Python's built-in library has os module that provides useful operating system dependent functions. These functions perform low level read/write operations on file." }, { "code": null, "e": 12055, "s": 11723, "text": "The open() function from os module is similar to the built-in open(). However, it doesn't return a file object but a file descriptor, a unique integer corresponding to file opened. File descriptor's values 0, 1 and 2 represent stdin, stdout, and stderr streams. Other files will be given incremental file descriptor from 2 onwards." }, { "code": null, "e": 12215, "s": 12055, "text": "As in case of open() built-in function, os.open() function also needs to specify file access mode. Following table lists various modes as defined in os module." }, { "code": null, "e": 12227, "s": 12215, "text": "os.O_RDONLY" }, { "code": null, "e": 12249, "s": 12227, "text": "Open for reading only" }, { "code": null, "e": 12261, "s": 12249, "text": "os.O_WRONLY" }, { "code": null, "e": 12283, "s": 12261, "text": "Open for writing only" }, { "code": null, "e": 12293, "s": 12283, "text": "os.O_RDWR" }, { "code": null, "e": 12322, "s": 12293, "text": "Open for reading and writing" }, { "code": null, "e": 12336, "s": 12322, "text": "os.O_NONBLOCK" }, { "code": null, "e": 12357, "s": 12336, "text": "Do not block on open" }, { "code": null, "e": 12369, "s": 12357, "text": "os.O_APPEND" }, { "code": null, "e": 12390, "s": 12369, "text": "Append on each write" }, { "code": null, "e": 12401, "s": 12390, "text": "os.O_CREAT" }, { "code": null, "e": 12434, "s": 12401, "text": "Create file if it does not exist" }, { "code": null, "e": 12445, "s": 12434, "text": "os.O_TRUNC" }, { "code": null, "e": 12464, "s": 12445, "text": "Truncate size to 0" }, { "code": null, "e": 12474, "s": 12464, "text": "os.O_EXCL" }, { "code": null, "e": 12506, "s": 12474, "text": "Error if create and file exists" }, { "code": null, "e": 12673, "s": 12506, "text": "To open a new file for writing data in it, specify O_WRONLY as well as O_CREAT modes by inserting pipe (|) operator. The os.open() function returns a file descriptor." }, { "code": null, "e": 12720, "s": 12673, "text": "f=os.open(\"test.dat\", os.O_WRONLY|os.O_CREAT)\n" }, { "code": null, "e": 12878, "s": 12720, "text": "Note that, data is written to disk file in the form of byte string. Hence, a normal string is converted to byte string by using encode() function as earlier." }, { "code": null, "e": 12914, "s": 12878, "text": "data=\"Hello World\".encode('utf-8')\n" }, { "code": null, "e": 12994, "s": 12914, "text": "The write() function in os module accepts this byte string and file descriptor." }, { "code": null, "e": 13012, "s": 12994, "text": "os.write(f,data)\n" }, { "code": null, "e": 13067, "s": 13012, "text": "Don’t forget to close the file using close() function." }, { "code": null, "e": 13080, "s": 13067, "text": "os.close(f)\n" }, { "code": null, "e": 13159, "s": 13080, "text": "To read contents of a file using os.read() function, use following statements:" }, { "code": null, "e": 13243, "s": 13159, "text": "f=os.open(\"test.dat\", os.O_RDONLY)\ndata=os.read(f,20)\nprint (data.decode('utf-8'))\n" }, { "code": null, "e": 13355, "s": 13243, "text": "Note that, the os.read() function needs file descriptor and number of bytes to be read (length of byte string)." }, { "code": null, "e": 13518, "s": 13355, "text": "If you want to open a file for simultaneous read/write operations, use O_RDWR mode. Following table shows important file operation related functions in os module." }, { "code": null, "e": 13531, "s": 13518, "text": "os.close(fd)" }, { "code": null, "e": 13558, "s": 13531, "text": "Close the file descriptor." }, { "code": null, "e": 13587, "s": 13558, "text": "os.open(file, flags[, mode])" }, { "code": null, "e": 13683, "s": 13587, "text": "Open the file and set various flags according to flags and possibly its mode according to mode." }, { "code": null, "e": 13698, "s": 13683, "text": "os.read(fd, n)" }, { "code": null, "e": 13875, "s": 13698, "text": "Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned." }, { "code": null, "e": 13893, "s": 13875, "text": "os.write(fd, str)" }, { "code": null, "e": 13982, "s": 13893, "text": "Write the string str to file descriptor fd. Return the number of bytes actually written." }, { "code": null, "e": 14167, "s": 13982, "text": "Python's built-in file object returned by Python's built-in open() function has one important shortcoming. When opened with 'w' mode, the write() method accepts only the string object." }, { "code": null, "e": 14451, "s": 14167, "text": "That means, if you have data represented in any non-string form, the object of either in built-in classes (numbers, dictionary, lists or tuples) or other user-defined classes, it cannot be written to file directly. Before writing, you need to convert it in its string representation." }, { "code": null, "e": 14549, "s": 14451, "text": "numbers=[10,20,30,40]\n file=open('numbers.txt','w')\n file.write(str(numbers))\n file.close()" }, { "code": null, "e": 14724, "s": 14549, "text": "For a binary file, argument to write() method must be a byte object. For example, the list of integers is converted to bytes by bytearray() function and then written to file." }, { "code": null, "e": 14809, "s": 14724, "text": "numbers=[10,20,30,40]\n data=bytearray(numbers)\n file.write(data)\n file.close()" }, { "code": null, "e": 14907, "s": 14809, "text": "To read back data from the file in the respective data type, reverse conversion needs to be done." }, { "code": null, "e": 14979, "s": 14907, "text": "file=open('numbers.txt','rb')\n data=file.read()\n print (list(data))" }, { "code": null, "e": 15310, "s": 14979, "text": "This type of manual conversion, of an object to string or byte format (and vice versa) is very cumbersome and tedious. It is possible to store the state of a Python object in the form of byte stream directly to a file, or memory stream and retrieve to its original state. This process is called serialization and de-serialization." }, { "code": null, "e": 15408, "s": 15310, "text": "Python’s built in library contains various modules for serialization and deserialization process." }, { "code": null, "e": 15415, "s": 15408, "text": "pickle" }, { "code": null, "e": 15453, "s": 15415, "text": "Python specific serialization library" }, { "code": null, "e": 15461, "s": 15453, "text": "marshal" }, { "code": null, "e": 15503, "s": 15461, "text": "Library used internally for serialization" }, { "code": null, "e": 15510, "s": 15503, "text": "shelve" }, { "code": null, "e": 15538, "s": 15510, "text": "Pythonic object persistence" }, { "code": null, "e": 15542, "s": 15538, "text": "dbm" }, { "code": null, "e": 15586, "s": 15542, "text": "library offering interface to Unix database" }, { "code": null, "e": 15590, "s": 15586, "text": "csv" }, { "code": null, "e": 15653, "s": 15590, "text": "library for storage and retrieval of Python data to CSV format" }, { "code": null, "e": 15658, "s": 15653, "text": "json" }, { "code": null, "e": 15709, "s": 15658, "text": "Library for serialization to universal JSON format" }, { "code": null, "e": 16040, "s": 15709, "text": "Python’s terminology for serialization and deserialization is pickling and unpickling respectively. The pickle module in Python library, uses very Python specific data format. Hence, non-Python applications may not be able to deserialize pickled data properly. It is also advised not to unpickle data from un-authenticated source." }, { "code": null, "e": 16283, "s": 16040, "text": "The serialized (pickled) data can be stored in a byte string or a binary file. This module defines dumps() and loads() functions to pickle and unpickle data using byte string. For file based process, the module has dump() and load() function." }, { "code": null, "e": 16478, "s": 16283, "text": "Python’s pickle protocols are the conventions used in constructing and deconstructing Python objects to/from binary data. Currently, pickle module defines 5 different protocols as listed below −" }, { "code": null, "e": 16497, "s": 16478, "text": "Protocol version 0" }, { "code": null, "e": 16576, "s": 16497, "text": "Original “human-readable” protocol backwards compatible with earlier versions." }, { "code": null, "e": 16595, "s": 16576, "text": "Protocol version 1" }, { "code": null, "e": 16662, "s": 16595, "text": "Old binary format also compatible with earlier versions of Python." }, { "code": null, "e": 16681, "s": 16662, "text": "Protocol version 2" }, { "code": null, "e": 16756, "s": 16681, "text": "Introduced in Python 2.3 provides efficient pickling of new-style classes." }, { "code": null, "e": 16775, "s": 16756, "text": "Protocol version 3" }, { "code": null, "e": 16869, "s": 16775, "text": "Added in Python 3.0. recommended when compatibility with other Python 3 versions is required." }, { "code": null, "e": 16888, "s": 16869, "text": "Protocol version 4" }, { "code": null, "e": 16952, "s": 16888, "text": "was added in Python 3.4. It adds support for very large objects" }, { "code": null, "e": 17053, "s": 16952, "text": "The pickle module consists of dumps() function that returns a string representation of pickled data." }, { "code": null, "e": 17171, "s": 17053, "text": "from pickle import dump\ndct={\"name\":\"Ravi\", \"age\":23, \"Gender\":\"M\",\"marks\":75}\ndctstring=dumps(dct)\nprint (dctstring)" }, { "code": null, "e": 17354, "s": 17171, "text": "b'\\x80\\x03}q\\x00(X\\x04\\x00\\x00\\x00nameq\\x01X\\x04\\x00\\x00\\x00Raviq\\x02X\\x03\\x00\\x00\\x00ageq\\x03K\\x17X\\x06\\x00\\x00\\x00Genderq\\x04X\\x01\\x00\\x00\\x00Mq\\x05X\\x05\\x00\\x00\\x00marksq\\x06KKu.\n" }, { "code": null, "e": 17438, "s": 17354, "text": "Use loads() function, to unpickle the string and obtain original dictionary object." }, { "code": null, "e": 17495, "s": 17438, "text": "from pickle import load\ndct=loads(dctstring)\nprint (dct)" }, { "code": null, "e": 17552, "s": 17495, "text": "{'name': 'Ravi', 'age': 23, 'Gender': 'M', 'marks': 75}\n" }, { "code": null, "e": 17675, "s": 17552, "text": "Pickled objects can also be persistently stored in a disk file, using dump() function and retrieved using load() function." }, { "code": null, "e": 17882, "s": 17675, "text": "import pickle\nf=open(\"data.txt\",\"wb\")\ndct={\"name\":\"Ravi\", \"age\":23, \"Gender\":\"M\",\"marks\":75}\npickle.dump(dct,f)\nf.close()\n\n#to read\nimport pickle\nf=open(\"data.txt\",\"rb\")\nd=pickle.load(f)\nprint (d)\nf.close()" }, { "code": null, "e": 18009, "s": 17882, "text": "The pickle module also provides, object oriented API for serialization mechanism in the form of Pickler and Unpickler classes." }, { "code": null, "e": 18380, "s": 18009, "text": "As mentioned above, just as built-in objects in Python, objects of user defined classes can also be persistently serialized in disk file. In following program, we define a User class with name and mobile number as its instance attributes. In addition to the __init__() constructor, the class overrides __str__() method that returns a string representation of its object." }, { "code": null, "e": 18554, "s": 18380, "text": "class User:\n def __init__(self,name, mob):\n self.name=name\n self.mobile=mob\n def __str__(self):\nreturn ('Name: {} mobile: {} '. format(self.name, self.mobile))" }, { "code": null, "e": 18639, "s": 18554, "text": "To pickle object of above class in a file we use pickler class and its dump()method." }, { "code": null, "e": 18810, "s": 18639, "text": "from pickle import Pickler\nuser1=User('Rajani', '[email protected]', '1234567890')\nfile=open('userdata','wb')\nPickler(file).dump(user1)\nPickler(file).dump(user2)\nfile.close()" }, { "code": null, "e": 18899, "s": 18810, "text": "Conversely, Unpickler class has load() method to retrieve serialized object as follows −" }, { "code": null, "e": 18999, "s": 18899, "text": "from pickle import Unpickler\nfile=open('usersdata','rb')\nuser1=Unpickler(file).load()\nprint (user1)" }, { "code": null, "e": 19341, "s": 18999, "text": "Object serialization features of marshal module in Python’s standard library are similar to pickle module. However, this module is not used for general purpose data. On the other hand, it is used by Python itself for Python’s internal object serialization to support read/write operations on compiled versions of Python modules (.pyc files)." }, { "code": null, "e": 19525, "s": 19341, "text": "The data format used by marshal module is not compatible across Python versions. Therefore, a compiled Python script (.pyc file) of one version most probably won’t execute on another." }, { "code": null, "e": 19663, "s": 19525, "text": "Just as pickle module, marshal module also defined load() and dump() functions for reading and writing marshalled objects from / to file." }, { "code": null, "e": 19797, "s": 19663, "text": "This function writes byte representation of supported Python object to a file. The file itself be a binary file with write permission" }, { "code": null, "e": 19884, "s": 19797, "text": "This function reads the byte data from a binary file and converts it to Python object." }, { "code": null, "e": 20036, "s": 19884, "text": "Following example demonstrates use of dump() and load() functions to handle code objects of Python, which are used to store precompiled Python modules." }, { "code": null, "e": 20158, "s": 20036, "text": "The code uses built-in compile() function to build a code object out of a source string which embeds Python instructions." }, { "code": null, "e": 20187, "s": 20158, "text": "compile(source, file, mode)\n" }, { "code": null, "e": 20312, "s": 20187, "text": "The file parameter should be the file from which the code was read. If it wasn’t read from a file pass any arbitrary string." }, { "code": null, "e": 20486, "s": 20312, "text": "The mode parameter is ‘exec’ if the source contains sequence of statements, ‘eval’ if there is a single expression or ‘single’ if it contains a single interactive statement." }, { "code": null, "e": 20563, "s": 20486, "text": "The compile code object is then stored in a .pyc file using dump() function." }, { "code": null, "e": 20723, "s": 20563, "text": "import marshal\nscript = \"\"\"\na=10\nb=20\nprint ('addition=',a+b)\n\"\"\"\ncode = compile(script, \"script\", \"exec\")\nf=open(\"a.pyc\",\"wb\")\nmarshal.dump(code, f)\nf.close()" }, { "code": null, "e": 20874, "s": 20723, "text": "To deserialize, the object from .pyc file use load() function. Since, it returns a code object, it can be run using exec(), another built-in function." }, { "code": null, "e": 20944, "s": 20874, "text": "import marshal\nf=open(\"a.pyc\",\"rb\")\ndata=marshal.load(f)\nexec (data)\n" }, { "code": null, "e": 21228, "s": 20944, "text": "The shelve module in Python’s standard library provides simple yet effective object persistence mechanism. The shelf object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems." }, { "code": null, "e": 21409, "s": 21228, "text": "The shelf dictionary has certain restrictions. Only string data type can be used as key in this special dictionary object, whereas any picklable Python object can be used as value." }, { "code": null, "e": 21462, "s": 21409, "text": "The shelve module defines three classes as follows −" }, { "code": null, "e": 21468, "s": 21462, "text": "Shelf" }, { "code": null, "e": 21559, "s": 21468, "text": "This is the base class for shelf implementations. It is initialized with dict-like object." }, { "code": null, "e": 21570, "s": 21559, "text": "BsdDbShelf" }, { "code": null, "e": 21724, "s": 21570, "text": "This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods." }, { "code": null, "e": 21740, "s": 21724, "text": "DbfilenameShelf" }, { "code": null, "e": 21853, "s": 21740, "text": "This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object." }, { "code": null, "e": 21937, "s": 21853, "text": "The open() function defined in shelve module which return a DbfilenameShelf object." }, { "code": null, "e": 21995, "s": 21937, "text": "open(filename, flag='c', protocol=None, writeback=False)\n" }, { "code": null, "e": 22198, "s": 21995, "text": "The filename parameter is assigned to the database created. Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write)." }, { "code": null, "e": 22454, "s": 22198, "text": "The serialization itself is governed by pickle protocol, default is none. Last parameter writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations, hence process may be slow." }, { "code": null, "e": 22525, "s": 22454, "text": "Following code creates a database and stores dictionary entries in it." }, { "code": null, "e": 22614, "s": 22525, "text": "import shelve\ns=shelve.open(\"test\")\ns['name']=\"Ajay\"\ns['age']=23\ns['marks']=75\ns.close()" }, { "code": null, "e": 22758, "s": 22614, "text": "This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available −" }, { "code": null, "e": 22766, "s": 22758, "text": "close()" }, { "code": null, "e": 22812, "s": 22766, "text": "synchronise and close persistent dict object." }, { "code": null, "e": 22819, "s": 22812, "text": "sync()" }, { "code": null, "e": 22903, "s": 22819, "text": "Write back all entries in the cache if shelf was opened with writeback set to True." }, { "code": null, "e": 22909, "s": 22903, "text": "get()" }, { "code": null, "e": 22943, "s": 22909, "text": "returns value associated with key" }, { "code": null, "e": 22951, "s": 22943, "text": "items()" }, { "code": null, "e": 22997, "s": 22951, "text": "list of tuples – each tuple is key value pair" }, { "code": null, "e": 23004, "s": 22997, "text": "keys()" }, { "code": null, "e": 23023, "s": 23004, "text": "list of shelf keys" }, { "code": null, "e": 23029, "s": 23023, "text": "pop()" }, { "code": null, "e": 23086, "s": 23029, "text": "remove specified key and return the corresponding value." }, { "code": null, "e": 23095, "s": 23086, "text": "update()" }, { "code": null, "e": 23135, "s": 23095, "text": "Update shelf from another dict/iterable" }, { "code": null, "e": 23144, "s": 23135, "text": "values()" }, { "code": null, "e": 23165, "s": 23144, "text": "list of shelf values" }, { "code": null, "e": 23212, "s": 23165, "text": "To access value of a particular key in shelf −" }, { "code": null, "e": 23383, "s": 23212, "text": "s=shelve.open('test')\nprint (s['age']) #this will print 23\n s['age']=25\nprint (s.get('age')) #this will print 25\ns.pop('marks') #this will remove corresponding k-v pair" }, { "code": null, "e": 23481, "s": 23383, "text": "As in a built-in dictionary object, the items(), keys() and values() methods return view objects." }, { "code": null, "e": 23646, "s": 23481, "text": "print (list(s.items()))\n[('name', 'Ajay'), ('age', 25), ('marks', 75)] \n\nprint (list(s.keys()))\n['name', 'age', 'marks']\n\nprint (list(s.values()))\n['Ajay', 25, 75]" }, { "code": null, "e": 23715, "s": 23646, "text": "To merge items of another dictionary with shelf use update() method." }, { "code": null, "e": 23875, "s": 23715, "text": "d={'salary':10000, 'designation':'manager'}\ns.update(d)\nprint (list(s.items()))\n\n[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]" }, { "code": null, "e": 24183, "s": 23875, "text": "The dbm package presents a dictionary like interface DBM style databases. DBM stands for DataBase Manager. This is used by UNIX (and UNIX like) operating system. The dbbm library is a simple database engine written by Ken Thompson. These databases use binary encoded string objects as key, as well as value." }, { "code": null, "e": 24342, "s": 24183, "text": "The database stores data by use of a single key (a primary key) in fixed-size buckets and uses hashing techniques to enable fast retrieval of the data by key." }, { "code": null, "e": 24387, "s": 24342, "text": "The dbm package contains following modules −" }, { "code": null, "e": 24480, "s": 24387, "text": "dbm.gnu module is an interface to the DBM library version as implemented by the GNU project." }, { "code": null, "e": 24573, "s": 24480, "text": "dbm.gnu module is an interface to the DBM library version as implemented by the GNU project." }, { "code": null, "e": 24640, "s": 24573, "text": "dbm.ndbm module provides an interface to UNIX nbdm implementation." }, { "code": null, "e": 24707, "s": 24640, "text": "dbm.ndbm module provides an interface to UNIX nbdm implementation." }, { "code": null, "e": 24866, "s": 24707, "text": "dbm.dumb is used as a fallback option in the event, other dbm implementations are not found. This requires no external dependencies but is slower than others." }, { "code": null, "e": 25025, "s": 24866, "text": "dbm.dumb is used as a fallback option in the event, other dbm implementations are not found. This requires no external dependencies but is slower than others." }, { "code": null, "e": 25214, "s": 25025, "text": ">>> dbm.whichdb('mydbm.db')\n'dbm.dumb'\n>>> import dbm\n>>> db=dbm.open('mydbm.db','n')\n>>> db['name']=Raj Deshmane'\n>>> db['address']='Kirtinagar Pune'\n>>> db['PIN']='431101'\n>>> db.close()" }, { "code": null, "e": 25260, "s": 25214, "text": "The open() function allows mode these flags −" }, { "code": null, "e": 25264, "s": 25260, "text": "'r'" }, { "code": null, "e": 25314, "s": 25264, "text": "Open existing database for reading only (default)" }, { "code": null, "e": 25318, "s": 25314, "text": "'w'" }, { "code": null, "e": 25365, "s": 25318, "text": "Open existing database for reading and writing" }, { "code": null, "e": 25369, "s": 25365, "text": "'c'" }, { "code": null, "e": 25440, "s": 25369, "text": "Open database for reading and writing, creating it if it doesn’t exist" }, { "code": null, "e": 25444, "s": 25440, "text": "'n'" }, { "code": null, "e": 25510, "s": 25444, "text": "Always create a new, empty database, open for reading and writing" }, { "code": null, "e": 25793, "s": 25510, "text": "The dbm object is a dictionary like object, just as shelf object. Hence, all dictionary operations can be performed. The dbm object can invoke get(), pop(), append() and update() methods. Following code opens 'mydbm.db' with 'r' flag and iterates over collection of key-value pairs." }, { "code": null, "e": 25944, "s": 25793, "text": ">>> db=dbm.open('mydbm.db','r')\n>>> for k,v in db.items():\n print (k,v)\nb'name' : b'Raj Deshmane'\nb'address' : b'Kirtinagar Pune'\nb'PIN' : b'431101'" }, { "code": null, "e": 26310, "s": 25944, "text": "CSV stands for comma separated values. This file format is a commonly used data format while exporting/importing data to/from spreadsheets and data tables in databases. The csv module was incorporated in Python’s standard library as a result of PEP 305. It presents classes and methods to perform read/write operations on CSV file as per recommendations of PEP 305." }, { "code": null, "e": 26463, "s": 26310, "text": "CSV is a preferred export data format by Microsoft’s Excel spreadsheet software. However, csv module can handle data represented by other dialects also." }, { "code": null, "e": 26535, "s": 26463, "text": "The CSV API interface consists of following writer and reader classes −" }, { "code": null, "e": 26863, "s": 26535, "text": "This function in csv module returns a writer object that converts data into a delimited string and stores in a file object. The function needs a file object with write permission as a parameter. Every row written in the file issues a newline character. To prevent additional space between lines, newline parameter is set to ''." }, { "code": null, "e": 26904, "s": 26863, "text": "The writer class has following methods −" }, { "code": null, "e": 27005, "s": 26904, "text": "This method writes items in an iterable (list, tuple or string), separating them by comma character." }, { "code": null, "e": 27126, "s": 27005, "text": "This method takes a list of iterables, as parameter and writes each item as a comma separated line of items in the file." }, { "code": null, "e": 27134, "s": 27126, "text": "Example" }, { "code": null, "e": 27341, "s": 27134, "text": "Following example shows use of writer() function. First a file is opened in ‘w’ mode. This file is used to obtain writer object. Each tuple in list of tuples is then written to file using writerow() method." }, { "code": null, "e": 27553, "s": 27341, "text": "import csv\n persons=[('Lata',22,45),('Anil',21,56),('John',20,60)]\n csvfile=open('persons.csv','w', newline='')\n obj=csv.writer(csvfile)\n for person in persons:\n obj.writerow(person)\ncsvfile.close()" }, { "code": null, "e": 27560, "s": 27553, "text": "Output" }, { "code": null, "e": 27647, "s": 27560, "text": "This will create ‘persons.csv’ file in current directory. It will show following data." }, { "code": null, "e": 27681, "s": 27647, "text": "Lata,22,45\nAnil,21,56\nJohn,20,60\n" }, { "code": null, "e": 27779, "s": 27681, "text": "Instead of iterating over the list to write each row individually, we can use writerows() method." }, { "code": null, "e": 27946, "s": 27779, "text": "csvfile=open('persons.csv','w', newline='')\npersons=[('Lata',22,45),('Anil',21,56),('John',20,60)]\n obj=csv.writer(csvfile)\n obj.writerows(persons)\n obj.close()" }, { "code": null, "e": 28123, "s": 27946, "text": "This function returns a reader object which returns an iterator of lines in the csv file. Using the regular for loop, all lines in the file are displayed in following example −" }, { "code": null, "e": 28231, "s": 28123, "text": "csvfile=open('persons.csv','r', newline='')\n obj=csv.reader(csvfile)\n for row in obj:\n print (row)" }, { "code": null, "e": 28295, "s": 28231, "text": "['Lata', '22', '45']\n['Anil', '21', '56']\n['John', '20', '60']\n" }, { "code": null, "e": 28443, "s": 28295, "text": "The reader object is an iterator. Hence, it supports next() function which can also be used to display all lines in csv file instead of a for loop." }, { "code": null, "e": 28612, "s": 28443, "text": "csvfile=open('persons.csv','r', newline='')\n obj=csv.reader(csvfile)\n while True:\n try:\n row=next(obj)\n print (row)\n except StopIteration:\n break" }, { "code": null, "e": 28861, "s": 28612, "text": "As mentioned earlier, csv module uses Excel as its default dialect. The csv module also defines a dialect class. Dialect is set of standards used to implement CSV protocol. The list of dialects available can be obtained by list_dialects() function." }, { "code": null, "e": 28917, "s": 28861, "text": ">>> csv.list_dialects()\n['excel', 'excel-tab', 'unix']\n" }, { "code": null, "e": 29105, "s": 28917, "text": "In addition to iterables, csv module can export a dictionary object to CSV file and read it to populate Python dictionary object. For this purpose, this module defines following classes −" }, { "code": null, "e": 29400, "s": 29105, "text": "This function returns a DictWriter object. It is similar to writer object, but the rows are mapped to dictionary object. The function needs a file object with write permission and a list of keys used in dictionary as fieldnames parameter. This is used to write first line in the file as header." }, { "code": null, "e": 29499, "s": 29400, "text": "This method writes list of keys in dictionary as a comma separated line as first line in the file." }, { "code": null, "e": 29676, "s": 29499, "text": "In following example, a list of dictionary items is defined. Each item in the list is a dictionary. Using writrows() method, they are written to file in comma separated manner." }, { "code": null, "e": 29994, "s": 29676, "text": "persons=[\n {'name':'Lata', 'age':22, 'marks':45}, \n {'name':'Anil', 'age':21, 'marks':56}, \n {'name':'John', 'age':20, 'marks':60}\n]\ncsvfile=open('persons.csv','w', newline='')\nfields=list(persons[0].keys())\nobj=csv.DictWriter(csvfile, fieldnames=fields)\nobj.writeheader()\nobj.writerows(persons)\ncsvfile.close()" }, { "code": null, "e": 30042, "s": 29994, "text": "The persons.csv file shows following contents −" }, { "code": null, "e": 30091, "s": 30042, "text": "name,age,marks\nLata,22,45\nAnil,21,56\nJohn,20,60\n" }, { "code": null, "e": 30272, "s": 30091, "text": "This function returns a DictReader object from the underlying CSV file. As, in case of, reader object, this one is also an iterator, using which contents of the file are retrieved." }, { "code": null, "e": 30345, "s": 30272, "text": "csvfile=open('persons.csv','r', newline='')\nobj=csv.DictReader(csvfile)\n" }, { "code": null, "e": 30440, "s": 30345, "text": "The class provides fieldnames attribute, returning the dictionary keys used as header of file." }, { "code": null, "e": 30489, "s": 30440, "text": "print (obj.fieldnames)\n['name', 'age', 'marks']\n" }, { "code": null, "e": 30565, "s": 30489, "text": "Use loop over the DictReader object to fetch individual dictionary objects." }, { "code": null, "e": 30597, "s": 30565, "text": "for row in obj:\n print (row)\n" }, { "code": null, "e": 30632, "s": 30597, "text": "This results in following output −" }, { "code": null, "e": 30825, "s": 30632, "text": "OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')])\nOrderedDict([('name', 'Anil'), ('age', '21'), ('marks', '56')])\nOrderedDict([('name', 'John'), ('age', '20'), ('marks', '60')])\n" }, { "code": null, "e": 30938, "s": 30825, "text": "To convert OrderedDict object to normal dictionary, we have to first import OrderedDict from collections module." }, { "code": null, "e": 31099, "s": 30938, "text": "from collections import OrderedDict\n r=OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')])\n dict(r)\n{'name': 'Lata', 'age': '22', 'marks': '45'}" }, { "code": null, "e": 31364, "s": 31099, "text": "JSON stands for JavaScript Object Notation. It is a lightweight data interchange format. It is a language-independent and cross platform text format, supported by many programming languages. This format is used for data exchange between the web server and clients." }, { "code": null, "e": 31651, "s": 31364, "text": "JSON format is similar to pickle. However, pickle serialization is Python specific whereas JSON format is implemented by many languages hence has become universal standard. Functionality and interface of json module in Python’s standard library is similar to pickle and marshal modules." }, { "code": null, "e": 31884, "s": 31651, "text": "Just as in pickle module, the json module also provides dumps() and loads() function for serialization of Python object into JSON encoded string, and dump() and load() functions write and read serialized Python objects to/from file." }, { "code": null, "e": 31946, "s": 31884, "text": "dumps() − This function converts the object into JSON format." }, { "code": null, "e": 32008, "s": 31946, "text": "dumps() − This function converts the object into JSON format." }, { "code": null, "e": 32078, "s": 32008, "text": "loads() − This function converts a JSON string back to Python object." }, { "code": null, "e": 32148, "s": 32078, "text": "loads() − This function converts a JSON string back to Python object." }, { "code": null, "e": 32212, "s": 32148, "text": "Following example demonstrates basic usage of these functions −" }, { "code": null, "e": 32300, "s": 32212, "text": "import json\n data=['Rakesh',{'marks':(50,60,70)}]\n s=json.dumps(data)\njson.loads(s)" }, { "code": null, "e": 32463, "s": 32300, "text": "The dumps() function can take optional sort_keys argument. By default, it is False. If set to True, the dictionary keys appear in sorted order in the JSON string." }, { "code": null, "e": 32663, "s": 32463, "text": "The dumps() function has another optional parameter called indent which takes a number as value. It decides length of each segment of formatted representation of json string, similar to print output." }, { "code": null, "e": 32817, "s": 32663, "text": "The json module also has object oriented API corresponding to above functions. There are two classes defined in the module – JSONEncoder and JSONDecoder." }, { "code": null, "e": 32969, "s": 32817, "text": "Object of this class is encoder for Python data structures. Each Python data type is converted in corresponding JSON type as shown in following table −" }, { "code": null, "e": 33096, "s": 32969, "text": "The JSONEncoder class is instantiated by JSONEncoder() constructor. Following important methods are defined in encoder class −" }, { "code": null, "e": 33105, "s": 33096, "text": "encode()" }, { "code": null, "e": 33147, "s": 33105, "text": "serializes Python object into JSON format" }, { "code": null, "e": 33160, "s": 33147, "text": "iterencode()" }, { "code": null, "e": 33253, "s": 33160, "text": "Encodes the object and returns an iterator yielding encoded form of each item in the object." }, { "code": null, "e": 33260, "s": 33253, "text": "indent" }, { "code": null, "e": 33302, "s": 33260, "text": "Determines indent level of encoded string" }, { "code": null, "e": 33312, "s": 33302, "text": "sort_keys" }, { "code": null, "e": 33380, "s": 33312, "text": "is either true or false to make keys appear in sorted order or not." }, { "code": null, "e": 33395, "s": 33380, "text": "Check_circular" }, { "code": null, "e": 33458, "s": 33395, "text": "if True, check for circular reference in container type object" }, { "code": null, "e": 33504, "s": 33458, "text": "Following example encodes Python list object." }, { "code": null, "e": 33541, "s": 33504, "text": "e=json.JSONEncoder()\ne.encode(data)\n" }, { "code": null, "e": 33753, "s": 33541, "text": "Object of this class helps in decoded in json string back to Python data structure. Main method in this class is decode(). Following example code retrieves Python list object from encoded string in earlier step." }, { "code": null, "e": 33786, "s": 33753, "text": "d=json.JSONDecoder()\nd.decode(s)" }, { "code": null, "e": 33953, "s": 33786, "text": "The json module defines load() and dump() functions to write JSON data to a file like object – which may be a disk file or a byte stream and read data back from them." }, { "code": null, "e": 34050, "s": 33953, "text": "This function writes JSONed Python object data to a file. The file must be opened with ‘w’ mode." }, { "code": null, "e": 34166, "s": 34050, "text": "import json\ndata=['Rakesh', {'marks': (50, 60, 70)}]\n fp=open('json.txt','w')\n json.dump(data,fp)\n fp.close()" }, { "code": null, "e": 34256, "s": 34166, "text": "This code will create ‘json.txt’ in current directory. It shows the contents as follows −" }, { "code": null, "e": 34293, "s": 34256, "text": "[\"Rakesh\", {\"marks\": [50, 60, 70]}]\n" }, { "code": null, "e": 34441, "s": 34293, "text": "This function loads JSON data from the file and returns Python object from it. The file must be opened with read permission (should have ‘r’ mode)." }, { "code": null, "e": 34449, "s": 34441, "text": "Example" }, { "code": null, "e": 34523, "s": 34449, "text": "fp=open('json.txt','r')\n ret=json.load(fp)\n print (ret)\n fp.close()" }, { "code": null, "e": 34530, "s": 34523, "text": "Output" }, { "code": null, "e": 34567, "s": 34530, "text": "['Rakesh', {'marks': [50, 60, 70]}]\n" }, { "code": null, "e": 34703, "s": 34567, "text": "The json.tool module also has a command-line interface that validates data in file and prints JSON object in a pretty formatted manner." }, { "code": null, "e": 34837, "s": 34703, "text": "C:\\python37>python -m json.tool json.txt\n[\n \"Rakesh\", \n {\n \"marks\": [\n 50,\n 60,\n 70\n ]\n }\n]" }, { "code": null, "e": 35020, "s": 34837, "text": "XML is acronym for eXtensible Markup Language. It is a portable, open source and cross platform language very much like HTML or SGML and recommended by the World Wide Web Consortium." }, { "code": null, "e": 35237, "s": 35020, "text": "It is a well-known data interchange format, used by a large number of applications such as web services, office tools, and Service Oriented Architectures (SOA). XML format is both machine readable and human readable." }, { "code": null, "e": 35326, "s": 35237, "text": "Standard Python library's xml package consists of following modules for XML processing −" }, { "code": null, "e": 35348, "s": 35326, "text": "xml.etree.ElementTree" }, { "code": null, "e": 35408, "s": 35348, "text": "the ElementTree API, a simple and lightweight XML processor" }, { "code": null, "e": 35416, "s": 35408, "text": "xml.dom" }, { "code": null, "e": 35439, "s": 35416, "text": "the DOM API definition" }, { "code": null, "e": 35455, "s": 35439, "text": "xml.dom.minidom" }, { "code": null, "e": 35484, "s": 35455, "text": "a minimal DOM implementation" }, { "code": null, "e": 35492, "s": 35484, "text": "xml.sax" }, { "code": null, "e": 35522, "s": 35492, "text": "SAX2 interface implementation" }, { "code": null, "e": 35540, "s": 35522, "text": "xml.parsers.expat" }, { "code": null, "e": 35565, "s": 35540, "text": "the Expat parser binding" }, { "code": null, "e": 35821, "s": 35565, "text": "Data in the XML document is arranged in a tree-like hierarchical format, starting with root and elements. Each element is a single node in the tree and has an attribute enclosed in <> and </> tags. One or more sub-elements may be assigned to each element." }, { "code": null, "e": 35872, "s": 35821, "text": "Following is a typical example of a XML document −" }, { "code": null, "e": 36275, "s": 35872, "text": "<?xml version = \"1.0\" encoding = \"iso-8859-1\"?>\n<studentlist>\n <student>\n <name>Ratna</name>\n <subject>Physics</subject>\n <marks>85</marks>\n </student>\n <student>\n <name>Kiran</name>\n <subject>Maths</subject>\n <marks>100</marks>\n </student>\n <student>\n <name>Mohit</name>\n <subject>Biology</subject>\n <marks>92</marks>\n </student>\n</studentlist>" }, { "code": null, "e": 36471, "s": 36275, "text": "While using ElementTree module, first step is to set up root element of the tree. Each Element has a tag and attrib which is a dict object. For the root element, an attrib is an empty dictionary." }, { "code": null, "e": 36546, "s": 36471, "text": "import xml.etree.ElementTree as xmlobj\nroot=xmlobj.Element('studentList')\n" }, { "code": null, "e": 36697, "s": 36546, "text": "Now, we can add one or more elements under root element. Each element object may have SubElements. Each subelement has an attribute and text property." }, { "code": null, "e": 36948, "s": 36697, "text": "student=xmlobj.Element('student')\n nm=xmlobj.SubElement(student, 'name')\n nm.text='name'\n subject=xmlobj.SubElement(student, 'subject')\n nm.text='Ratna'\n subject.text='Physics'\n marks=xmlobj.SubElement(student, 'marks')\n marks.text='85'" }, { "code": null, "e": 37012, "s": 36948, "text": "This new element is appended to the root using append() method." }, { "code": null, "e": 37034, "s": 37012, "text": "root.append(student)\n" }, { "code": null, "e": 37144, "s": 37034, "text": "Append as many elements as desired using above method. Finally, the root element object is written to a file." }, { "code": null, "e": 37251, "s": 37144, "text": "tree = xmlobj.ElementTree(root)\n file = open('studentlist.xml','wb')\n tree.write(file)\n file.close()" }, { "code": null, "e": 37386, "s": 37251, "text": "Now, we see how to parse the XML file. For that, construct document tree giving its name as file parameter in ElementTree constructor." }, { "code": null, "e": 37437, "s": 37386, "text": "tree = xmlobj.ElementTree(file='studentlist.xml')\n" }, { "code": null, "e": 37552, "s": 37437, "text": "The tree object has getroot() method to obtain root element and getchildren() returns a list of elements below it." }, { "code": null, "e": 37605, "s": 37552, "text": "root = tree.getroot()\nchildren = root.getchildren()\n" }, { "code": null, "e": 37735, "s": 37605, "text": "A dictionary object corresponding to each sub element is constructed by iterating over sub-element collection of each child node." }, { "code": null, "e": 37859, "s": 37735, "text": "for child in children:\n student={}\n pairs = child.getchildren()\n for pair in pairs:\n product[pair.tag]=pair.text" }, { "code": null, "e": 37949, "s": 37859, "text": "Each dictionary is then appended to a list returning original list of dictionary objects." }, { "code": null, "e": 38192, "s": 37949, "text": "SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX requires ContentHandler by subclassing xml.sax.ContentHandler. You register callbacks for events of interest and then, let the parser proceed through the document." }, { "code": null, "e": 38369, "s": 38192, "text": "SAX is useful when your documents are large or you have memory limitations as it parses the file as it reads it from disk as a result entire file is never stored in the memory." }, { "code": null, "e": 38573, "s": 38369, "text": "(DOM) API is a World Wide Web Consortium recommendation. In this case, entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document." }, { "code": null, "e": 38748, "s": 38573, "text": "SAX, not as fast as DOM, with large files. On the other hand, DOM can kill resources, if used on many small files. SAX is read-only, while DOM allows changes to the XML file." }, { "code": null, "e": 39013, "s": 38748, "text": "The plist format is mainly used by MAC OS X. These files are basically XML documents. They store and retrieve properties of an object. Python library contains plist module, that is used to read and write 'property list' files (they usually have .plist' extension)." }, { "code": null, "e": 39247, "s": 39013, "text": "The plistlib module is more or less similar to other serialization libraries in the sense, it also provides dumps() and loads() functions for string representation of Python objects and load() and dump() functions for disk operation." }, { "code": null, "e": 39326, "s": 39247, "text": "Following dictionary object maintains property (key) and corresponding value −" }, { "code": null, "e": 39462, "s": 39326, "text": "proplist = {\n \"name\" : \"Ganesh\",\n \"designation\":\"manager\",\n \"dept\":\"accts\",\n \"salary\" : {\"basic\":12000, \"da\":4000, \"hra\":800}\n}" }, { "code": null, "e": 39554, "s": 39462, "text": "In order to write these properties in a disk file, we call dump() function in plist module." }, { "code": null, "e": 39656, "s": 39554, "text": "import plistlib\nfileName=open('salary.plist','wb')\nplistlib.dump(proplist, fileName)\nfileName.close()" }, { "code": null, "e": 39735, "s": 39656, "text": "Conversely, to read back the property values, use load() function as follows −" }, { "code": null, "e": 39799, "s": 39735, "text": "fp= open('salary.plist', 'rb')\npl = plistlib.load(fp)\nprint(pl)" }, { "code": null, "e": 40037, "s": 39799, "text": "One major disadvantage of CSV, JSON, XML, etc., files is that they are not very useful for random access and transaction processing because they are largely unstructured in nature. Hence, it becomes very difficult to modify the contents." }, { "code": null, "e": 40224, "s": 40037, "text": "These flat files are not suitable for client-server environment as they lack asynchronous processing capability. Using unstructured data files leads to data redundancy and inconsistency." }, { "code": null, "e": 40451, "s": 40224, "text": "These problems can be overcome by using a relational database. A database is an organized collection of data to remove redundancy and inconsistency, and maintain data integrity. The relational database model is vastly popular." }, { "code": null, "e": 40652, "s": 40451, "text": "Its basic concept is to arrange data in entity table (called relation). The entity table structure provides one attribute whose value is unique for each row. Such an attribute is called 'primary key'." }, { "code": null, "e": 40894, "s": 40652, "text": "When primary key of one table appears in the structure of other tables, it is called 'Foreign key' and this forms the basis of the relationship between the two. Based on this model, there are many popular RDBMS products currently available −" }, { "code": null, "e": 40901, "s": 40894, "text": "GadFly" }, { "code": null, "e": 40906, "s": 40901, "text": "mSQL" }, { "code": null, "e": 40912, "s": 40906, "text": "MySQL" }, { "code": null, "e": 40923, "s": 40912, "text": "PostgreSQL" }, { "code": null, "e": 40949, "s": 40923, "text": "Microsoft SQL Server 2000" }, { "code": null, "e": 40958, "s": 40949, "text": "Informix" }, { "code": null, "e": 40968, "s": 40958, "text": "Interbase" }, { "code": null, "e": 40975, "s": 40968, "text": "Oracle" }, { "code": null, "e": 40982, "s": 40975, "text": "Sybase" }, { "code": null, "e": 40989, "s": 40982, "text": "SQLite" }, { "code": null, "e": 41394, "s": 40989, "text": "SQLite is a lightweight relational database used in a wide variety of applications. It is a self-contained, serverless, zero-configuration, transactional SQL database engine. The entire database is a single file, that can be placed anywhere in the file system. It's an open-source software, with very small footprint, and zero configuration. It is popularly used in embedded devices, IOT and mobile apps." }, { "code": null, "e": 41608, "s": 41394, "text": "All relational databases use SQL for handling data in tables. However, earlier, each of these databases used to be connected with Python application with the help of Python module specific to the type of database." }, { "code": null, "e": 41982, "s": 41608, "text": "Hence, there was a lack of compatibility among them. If a user wanted to change to different database product, it would prove to be difficult. This incompatibility issue was addresses by raising 'Python Enhancement Proposal (PEP 248)' to recommend consistent interface to relational databases known as DB-API. Latest recommendations are called DB-API Version 2.0. (PEP 249)" }, { "code": null, "e": 42197, "s": 41982, "text": "Python's standard library consists of the sqlite3 module which is a DB-API compliant module for handling the SQLite database through Python program. This chapter explains Python's connectivity with SQLite database." }, { "code": null, "e": 42486, "s": 42197, "text": "As mentioned earlier, Python has inbuilt support for SQLite database in the form of sqlite3 module. For other databases, respective DB-API compliant Python module will have to be installed with the help of pip utility. For example, to use MySQL database we need to install PyMySQL module." }, { "code": null, "e": 42507, "s": 42486, "text": "pip install pymysql\n" }, { "code": null, "e": 42551, "s": 42507, "text": "Following steps are recommended in DB-API −" }, { "code": null, "e": 42645, "s": 42551, "text": "Establish connection with the database using connect() function and obtain connection object." }, { "code": null, "e": 42739, "s": 42645, "text": "Establish connection with the database using connect() function and obtain connection object." }, { "code": null, "e": 42803, "s": 42739, "text": "Call cursor() method of connection object to get cursor object." }, { "code": null, "e": 42867, "s": 42803, "text": "Call cursor() method of connection object to get cursor object." }, { "code": null, "e": 42930, "s": 42867, "text": "Form a query string made up of a SQL statement to be executed." }, { "code": null, "e": 42993, "s": 42930, "text": "Form a query string made up of a SQL statement to be executed." }, { "code": null, "e": 43049, "s": 42993, "text": "Execute the desired query by invoking execute() method." }, { "code": null, "e": 43105, "s": 43049, "text": "Execute the desired query by invoking execute() method." }, { "code": null, "e": 43127, "s": 43105, "text": "Close the connection." }, { "code": null, "e": 43149, "s": 43127, "text": "Close the connection." }, { "code": null, "e": 43195, "s": 43149, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\n" }, { "code": null, "e": 43365, "s": 43195, "text": "Here, db is the connection object representing test.db. Note, that database will be created if it doesn’t exist already. The connection object db has following methods −" }, { "code": null, "e": 43375, "s": 43365, "text": "cursor():" }, { "code": null, "e": 43427, "s": 43375, "text": "Returns a Cursor object which uses this Connection." }, { "code": null, "e": 43437, "s": 43427, "text": "commit():" }, { "code": null, "e": 43498, "s": 43437, "text": "Explicitly commits any pending transactions to the database." }, { "code": null, "e": 43510, "s": 43498, "text": "rollback():" }, { "code": null, "e": 43593, "s": 43510, "text": "This optional method causes a transaction to be rolled back to the starting point." }, { "code": null, "e": 43602, "s": 43593, "text": "close():" }, { "code": null, "e": 43653, "s": 43602, "text": "Closes the connection to the database permanently." }, { "code": null, "e": 43860, "s": 43653, "text": "A cursor acts as a handle for a given SQL query allowing the retrieval of one or more rows of the result. Cursor object is obtained from the connection to execute SQL queries using the following statement −" }, { "code": null, "e": 43877, "s": 43860, "text": "cur=db.cursor()\n" }, { "code": null, "e": 43927, "s": 43877, "text": "The cursor object has following methods defined −" }, { "code": null, "e": 43937, "s": 43927, "text": "execute()" }, { "code": null, "e": 43983, "s": 43937, "text": "Executes the SQL query in a string parameter." }, { "code": null, "e": 43997, "s": 43983, "text": "executemany()" }, { "code": null, "e": 44069, "s": 43997, "text": "Executes the SQL query using a set of parameters in the list of tuples." }, { "code": null, "e": 44080, "s": 44069, "text": "fetchone()" }, { "code": null, "e": 44128, "s": 44080, "text": "Fetches the next row from the query result set." }, { "code": null, "e": 44139, "s": 44128, "text": "fetchall()" }, { "code": null, "e": 44193, "s": 44139, "text": "Fetches all remaining rows from the query result set." }, { "code": null, "e": 44204, "s": 44193, "text": "callproc()" }, { "code": null, "e": 44230, "s": 44204, "text": "Calls a stored procedure." }, { "code": null, "e": 44238, "s": 44230, "text": "close()" }, { "code": null, "e": 44264, "s": 44238, "text": "Closes the cursor object." }, { "code": null, "e": 44308, "s": 44264, "text": "Following code creates a table in test.db:-" }, { "code": null, "e": 44556, "s": 44308, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\ncur =db.cursor()\ncur.execute('''CREATE TABLE student (\nStudentID INTEGER PRIMARY KEY AUTOINCREMENT,\nname TEXT (20) NOT NULL,\nage INTEGER,\nmarks REAL);''')\nprint ('table created successfully')\ndb.close()" }, { "code": null, "e": 45008, "s": 44556, "text": "Data integrity desired in a database is achieved by commit() and rollback() methods of the connection object. The SQL query string may be having an incorrect SQL query that can raise an exception, which should be properly handled. For that, the execute() statement is placed within the try block If it is successful, the result is persistently saved using the commit() method. If the query fails, the transaction is undone using the rollback() method." }, { "code": null, "e": 45078, "s": 45008, "text": "Following code executes INSERT query on the student table in test.db." }, { "code": null, "e": 45352, "s": 45078, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\nqry=\"insert into student (name, age, marks) values('Abbas', 20, 80);\"\ntry:\n cur=db.cursor()\n cur.execute(qry)\n db.commit()\nprint (\"record added successfully\")\nexcept:\n print (\"error in query\")\n db.rollback()\ndb.close()" }, { "code": null, "e": 45757, "s": 45352, "text": "If you want data in values clause of INSERT query to by dynamically provided by user input, use parameter substitution as recommended in Python DB-API. The ? character is used as a placeholder in the query string and provides the values in the form of a tuple in the execute() method. The following example inserts a record using the parameter substitution method. Name, age and marks are taken as input." }, { "code": null, "e": 46118, "s": 45757, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\nnm=input('enter name')\na=int(input('enter age'))\nm=int(input('enter marks'))\nqry=\"insert into student (name, age, marks) values(?,?,?);\"\ntry:\n cur=db.cursor()\n cur.execute(qry, (nm,a,m))\n db.commit()\n print (\"one record added successfully\")\nexcept:\n print(\"error in operation\")\n db.rollback()\ndb.close()" }, { "code": null, "e": 46478, "s": 46118, "text": "The sqlite3 module defines The executemany() method which is able to add multiple records at once. Data to be added should be given in a list of tuples, with each tuple containing one record. The list object is the parameter of the executemany() method, along with the query string. However, executemany() method is not supported by some of the other modules." }, { "code": null, "e": 46719, "s": 46478, "text": "The UPDATE query usually contains a logical expression specified by WHERE clause The query string in the execute() method should contain an UPDATE query syntax. To update the value of 'age' to 23 for name='Anil', define the string as below:" }, { "code": null, "e": 46771, "s": 46719, "text": "qry=\"update student set age=23 where name='Anil';\"\n" }, { "code": null, "e": 46873, "s": 46771, "text": "To make the update process more dynamic, we use the parameter substitution method as described above." }, { "code": null, "e": 47183, "s": 46873, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\nnm=input(‘enter name’)\na=int(input(‘enter age’))\nqry=\"update student set age=? where name=?;\"\ntry:\n cur=db.cursor()\n cur.execute(qry, (a, nm))\n db.commit()\n print(\"record updated successfully\")\nexcept:\n print(\"error in query\")\n db.rollback()\ndb.close()" }, { "code": null, "e": 47365, "s": 47183, "text": "Similarly, DELETE operation is performed by calling execute() method with a string having SQL’s DELETE query syntax. Incidentally, DELETE query also usually contains a WHERE clause." }, { "code": null, "e": 47646, "s": 47365, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\nnm=input(‘enter name’)\nqry=\"DELETE from student where name=?;\"\ntry:\n cur=db.cursor()\n cur.execute(qry, (nm,))\n db.commit()\n print(\"record deleted successfully\")\nexcept:\n print(\"error in operation\")\n db.rollback()\ndb.close()" }, { "code": null, "e": 48005, "s": 47646, "text": "One of the important operations on a database table is retrieval of records from it. SQL provides SELECT query for the purpose. When a string containing SELECT query syntax is given to execute() method, a result set object is returned. There are two important methods with a cursor object using which one or many records from the result set can be retrieved." }, { "code": null, "e": 48133, "s": 48005, "text": "Fetches the next available record from the result set. It is a tuple consisting of values of each column of the fetched record." }, { "code": null, "e": 48282, "s": 48133, "text": "Fetches all remaining records in the form of a list of tuples. Each tuple corresponds to one record and contains values of each column in the table." }, { "code": null, "e": 48335, "s": 48282, "text": "Following example lists all records in student table" }, { "code": null, "e": 48543, "s": 48335, "text": "import sqlite3\ndb=sqlite3.connect('test.db')\n37\nsql=\"SELECT * from student;\"\ncur=db.cursor()\ncur.execute(sql)\nwhile True:\n record=cur.fetchone()\n if record==None:\n break\n print (record)\ndb.close()" }, { "code": null, "e": 48828, "s": 48543, "text": "If you plan to use a MySQL database instead of SQLite database, you need to install PyMySQL module as described above. All the steps in database connectivity process being same, since MySQL database is installed on a server, the connect() function needs the URL and login credentials." }, { "code": null, "e": 48892, "s": 48828, "text": "import pymysql\ncon=pymysql.connect('localhost', 'root', '***')\n" }, { "code": null, "e": 49054, "s": 48892, "text": "Only thing that may differ with SQLite is MySQL specific data types. Similarly, any ODBC compatible database can be used with Python by installing pyodbc module." }, { "code": null, "e": 49366, "s": 49054, "text": "Any relational database holds data in tables. The table structure defines data type of attributes which are basically of primary data types only which are mapped to corresponding built-in data types of Python. However, Python's user-defined objects can't be persistently stored and retrieved to/from SQL tables." }, { "code": null, "e": 49565, "s": 49366, "text": "This is a disparity between SQL types and object oriented programming languages such as Python. SQL doesn't have equivalent data type for others such as dict, tuple, list, or any user defined class." }, { "code": null, "e": 49948, "s": 49565, "text": "If you have to store an object in a relational database, it's instance attributes should be deconstructed into SQL data types first, before executing INSERT query. On the other hand, data retrieved from a SQL table is in primary types. A Python object of desired type will have to be constructed by using for use in Python script. This is where Object Relational Mappers are useful." }, { "code": null, "e": 50162, "s": 49948, "text": "An Object Relation Mapper (ORM) is an interface between a class and a SQL table. A Python class is mapped to a certain table in database, so that conversion between object and SQL types is automatically performed." }, { "code": null, "e": 50408, "s": 50162, "text": "The Students class written in Python code is mapped to Students table in the database. As a result, all CRUD operations are done by calling respective methods of the class. This eliminates need to execute hard coded SQL queries in Python script." }, { "code": null, "e": 50695, "s": 50408, "text": "ORM library thus acts as an abstraction layer over the raw SQL queries and can be of help in rapid application development. SQLAlchemy is a popular object relational mapper for Python. Any manipulation of state of model object is synchronized with its related row in the database table." }, { "code": null, "e": 50865, "s": 50695, "text": "SQLALchemy library includes ORM API and SQL Expression Language (SQLAlchemy Core). Expression language executes primitive constructs of the relational database directly." }, { "code": null, "e": 51115, "s": 50865, "text": "ORM is a high level and abstracted pattern of usage constructed on top of the SQL Expression Language. It can be said that ORM is an applied usage of the Expression Language. We shall discuss SQLAlchemy ORM API and use SQLite database in this topic." }, { "code": null, "e": 51366, "s": 51115, "text": "SQLAlchemy communicates with various types of databases through their respective DBAPI implementations using a dialect system. All dialects require that an appropriate DBAPI driver is installed. Dialects for following type of databases are included −" }, { "code": null, "e": 51375, "s": 51366, "text": "Firebird" }, { "code": null, "e": 51396, "s": 51375, "text": "Microsoft SQL Server" }, { "code": null, "e": 51402, "s": 51396, "text": "MySQL" }, { "code": null, "e": 51409, "s": 51402, "text": "Oracle" }, { "code": null, "e": 51420, "s": 51409, "text": "PostgreSQL" }, { "code": null, "e": 51427, "s": 51420, "text": "SQLite" }, { "code": null, "e": 51434, "s": 51427, "text": "Sybase" }, { "code": null, "e": 51509, "s": 51434, "text": "Installation of SQLAlchemy is easy and straightforward, using pip utility." }, { "code": null, "e": 51533, "s": 51509, "text": "pip install sqlalchemy\n" }, { "code": null, "e": 51630, "s": 51533, "text": "To check if SQLalchemy is properly installed and its version, enter following on Python prompt −" }, { "code": null, "e": 51688, "s": 51630, "text": ">>> import sqlalchemy\n>>>sqlalchemy.__version__\n'1.3.11'\n" }, { "code": null, "e": 51802, "s": 51688, "text": "Interactions with database are done through Engine object obtained as a return value of create_engine() function." }, { "code": null, "e": 51850, "s": 51802, "text": "engine =create_engine('sqlite:///mydb.sqlite')\n" }, { "code": null, "e": 51961, "s": 51850, "text": "SQLite allows creation of in-memory database. SQLAlchemy engine for in-memory database is created as follows −" }, { "code": null, "e": 52042, "s": 51961, "text": "from sqlalchemy import create_engine\nengine=create_engine('sqlite:///:memory:')\n" }, { "code": null, "e": 52150, "s": 52042, "text": "If you intend to use MySQL database instead, use its DB-API module – pymysql and respective dialect driver." }, { "code": null, "e": 52214, "s": 52150, "text": "engine = create_engine('mysql+pymydsql://root@localhost/mydb')\n" }, { "code": null, "e": 52347, "s": 52214, "text": "The create_engine has an optional echo argument. If set to true, the SQL queries generated by engine will be echoed on the terminal." }, { "code": null, "e": 52448, "s": 52347, "text": "SQLAlchemy contains declarative base class. It acts as a catalog of model classes and mapped tables." }, { "code": null, "e": 52529, "s": 52448, "text": "from sqlalchemy.ext.declarative import declarative_base\nbase=declarative_base()\n" }, { "code": null, "e": 52641, "s": 52529, "text": "Next step is to define a model class. It must be derived from base – object of declarative_base class as above." }, { "code": null, "e": 52864, "s": 52641, "text": "Set __tablename__ property to name of the table you want to be created in the database. Other attributes correspond to the fields. Each one is a Column object in SQLAlchemy and its data type is from one of the list below −" }, { "code": null, "e": 52875, "s": 52864, "text": "BigInteger" }, { "code": null, "e": 52883, "s": 52875, "text": "Boolean" }, { "code": null, "e": 52888, "s": 52883, "text": "Date" }, { "code": null, "e": 52897, "s": 52888, "text": "DateTime" }, { "code": null, "e": 52903, "s": 52897, "text": "Float" }, { "code": null, "e": 52911, "s": 52903, "text": "Integer" }, { "code": null, "e": 52919, "s": 52911, "text": "Numeric" }, { "code": null, "e": 52932, "s": 52919, "text": "SmallInteger" }, { "code": null, "e": 52939, "s": 52932, "text": "String" }, { "code": null, "e": 52944, "s": 52939, "text": "Text" }, { "code": null, "e": 52949, "s": 52944, "text": "Time" }, { "code": null, "e": 53034, "s": 52949, "text": "Following code is the model class named as Student that is mapped to Students table." }, { "code": null, "e": 53352, "s": 53034, "text": "#myclasses.py\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Numeric\nbase=declarative_base()\nclass Student(base):\n __tablename__='Students'\n StudentID=Column(Integer, primary_key=True)\n name=Column(String)\n age=Column(Integer)\n marks=Column(Numeric) " }, { "code": null, "e": 53467, "s": 53352, "text": "To create a Students table that has a corresponding structure, execute create_all() method defined for base class." }, { "code": null, "e": 53501, "s": 53467, "text": "base.metadata.create_all(engine)\n" }, { "code": null, "e": 53673, "s": 53501, "text": "We now have to declare an object of our Student class. All database transactions such as add, delete or retrieve data from database, etc., are handled by a Session object." }, { "code": null, "e": 53773, "s": 53673, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsessionobj = Session()\n" }, { "code": null, "e": 53870, "s": 53773, "text": "Data stored in Student object is physically added in underlying table by session’s add() method." }, { "code": null, "e": 53955, "s": 53870, "text": "s1 = Student(name='Juhi', age=25, marks=200)\nsessionobj.add(s1)\nsessionobj.commit()\n" }, { "code": null, "e": 54093, "s": 53955, "text": "Here, is the entire code for adding record in students table. As it is executed, corresponding SQL statement log is displayed on console." }, { "code": null, "e": 54488, "s": 54093, "text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nfrom myclasses import Student, base\nengine = create_engine('sqlite:///college.db', echo=True)\nbase.metadata.create_all(engine)\n\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsessionobj = Session()\ns1 = Student(name='Juhi', age=25, marks=200)\nsessionobj.add(s1)\nsessionobj.commit()" }, { "code": null, "e": 54952, "s": 54488, "text": "CREATE TABLE \"Students\" (\n \"StudentID\" INTEGER NOT NULL,\n name VARCHAR,\n age INTEGER,\n marks NUMERIC,\n PRIMARY KEY (\"StudentID\")\n)\nINFO sqlalchemy.engine.base.Engine ()\nINFO sqlalchemy.engine.base.Engine COMMIT\nINFO sqlalchemy.engine.base.Engine BEGIN (implicit)\nINFO sqlalchemy.engine.base.Engine INSERT INTO \"Students\" (name, age, marks) VALUES (?, ?, ?)\nINFO sqlalchemy.engine.base.Engine ('Juhi', 25, 200.0)\nINFO sqlalchemy.engine.base.Engine COMMIT" }, { "code": null, "e": 55059, "s": 54952, "text": "The session object also provides add_all() method to insert more than one objects in a single transaction." }, { "code": null, "e": 55114, "s": 55059, "text": "sessionobj.add_all([s2,s3,s4,s5])\nsessionobj.commit()\n" }, { "code": null, "e": 55338, "s": 55114, "text": "Now that, records are added in the table, we would like to fetch from it just as SELECT query does. The session object has query() method to perform the task. Query object is returned by query() method on our Student model." }, { "code": null, "e": 55369, "s": 55338, "text": "qry=seesionobj.query(Student)\n" }, { "code": null, "e": 55462, "s": 55369, "text": "Use the get() method of this Query object fetches object corresponding to given primary key." }, { "code": null, "e": 55477, "s": 55462, "text": "S1=qry.get(1)\n" }, { "code": null, "e": 55586, "s": 55477, "text": "While this statement is executed, its corresponding SQL statement echoed on the console will be as follows −" }, { "code": null, "e": 55856, "s": 55586, "text": "BEGIN (implicit)\nSELECT \"Students\".\"StudentID\" AS \"Students_StudentID\", \"Students\".name AS \n \"Students_name\", \"Students\".age AS \"Students_age\", \n \"Students\".marks AS \"Students_marks\"\nFROM \"Students\"\nWHERE \"Products\".\"Students\" = ?\nsqlalchemy.engine.base.Engine (1,)" }, { "code": null, "e": 55946, "s": 55856, "text": "The query.all() method returns a list of all objects which can be traversed using a loop." }, { "code": null, "e": 56342, "s": 55946, "text": "from sqlalchemy import Column, Integer, String, Numeric\nfrom sqlalchemy import create_engine\nfrom myclasses import Student,base\nengine = create_engine('sqlite:///college.db', echo=True)\nbase.metadata.create_all(engine)\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind=engine)\nsessionobj = Session()\nqry=sessionobj.query(Students)\nrows=qry.all()\nfor row in rows:\n print (row)" }, { "code": null, "e": 56587, "s": 56342, "text": "Updating a record in the mapped table is very easy. All you have to do is fetch a record using get() method, assign a new value to desired attribute and then commit the changes using session object. Below we change marks of Juhi student to 100." }, { "code": null, "e": 56634, "s": 56587, "text": "S1=qry.get(1)\nS1.marks=100\nsessionobj.commit()" }, { "code": null, "e": 56714, "s": 56634, "text": "Deleting a record is just as easy, by deleting desired object from the session." }, { "code": null, "e": 56770, "s": 56714, "text": "S1=qry.get(1)\nSessionobj.delete(S1)\nsessionobj.commit()" }, { "code": null, "e": 56934, "s": 56770, "text": "MongoDB is a document oriented NoSQL database. It is a cross platform database distributed under server side public license. It uses JSON like documents as schema." }, { "code": null, "e": 57138, "s": 56934, "text": "In order to provide capability to store huge data, more than one physical servers (called shards) are interconnected, so that a horizontal scalability is achieved. MongoDB database consists of documents." }, { "code": null, "e": 57496, "s": 57138, "text": "A document is analogous to a row in a table of relational database. However, it doesn't have a particular schema. Document is a collection of key-value pairs - similar to dictionary. However, number of k-v pairs in each document may vary. Just as a table in relational database has a primary key, document in MongoDB database has a special key called \"_id\"." }, { "code": null, "e": 57754, "s": 57496, "text": "Before we see how MongoDB database is used with Python, let us briefly understand how to install and start MongoDB. Community and commercial version of MongoDB is available. Community version can be downloaded from www.mongodb.com/download-center/community." }, { "code": null, "e": 57855, "s": 57754, "text": "Assuming that MongoDB is installed in c:\\mongodb, the server can be invoked using following command." }, { "code": null, "e": 57878, "s": 57855, "text": "c:\\mongodb\\bin>mongod\n" }, { "code": null, "e": 58048, "s": 57878, "text": "The MongoDB server is active at port number 22017 by default. Databases are stored in data/bin folder by default, although the location can be changed by –dbpath option." }, { "code": null, "e": 58151, "s": 58048, "text": "MongoDB has its own set of commands to be used in a MongoDB shell. To invoke shell, use Mongo command." }, { "code": null, "e": 58173, "s": 58151, "text": "x:\\mongodb\\bin>mongo\n" }, { "code": null, "e": 58358, "s": 58173, "text": "A shell prompt similar to MySQL or SQLite shell prompt, appears before which native NoSQL commands can be executed. However, we are interested in connecting MongoDB database to Python." }, { "code": null, "e": 58502, "s": 58358, "text": "PyMongo module has been developed by MongoDB Inc itself to provide Python programming interface. Use well known pip utility to install PyMongo." }, { "code": null, "e": 58524, "s": 58502, "text": "pip3 install pymongo\n" }, { "code": null, "e": 58742, "s": 58524, "text": "Assuming that MongoDB server is up and running (with mongod command) and is listening at port 22017, we first need to declare a MongoClient object. It controls all transactions between Python session and the database." }, { "code": null, "e": 58796, "s": 58742, "text": "from pymongo import MongoClient\nclient=MongoClient()\n" }, { "code": null, "e": 58864, "s": 58796, "text": "Use this client object to establish connection with MongoDB server." }, { "code": null, "e": 58906, "s": 58864, "text": "client = MongoClient('localhost', 27017)\n" }, { "code": null, "e": 58956, "s": 58906, "text": "A new database is created with following command." }, { "code": null, "e": 58973, "s": 58956, "text": "db=client.newdb\n" }, { "code": null, "e": 59125, "s": 58973, "text": "MongoDB database can have many collections, similar to tables in a relational database. A Collection object is created by Create_collection() function." }, { "code": null, "e": 59159, "s": 59125, "text": "db.create_collection('students')\n" }, { "code": null, "e": 59228, "s": 59159, "text": "Now, we can add one or more documents in the collection as follows −" }, { "code": null, "e": 59576, "s": 59228, "text": "from pymongo import MongoClient\nclient=MongoClient()\ndb=client.newdb\ndb.create_collection(\"students\")\nstudent=db['students']\nstudentlist=[{'studentID':1,'Name':'Juhi','age':20, 'marks'=100},\n{'studentID':2,'Name':'dilip','age':20, 'marks'=110},\n{'studentID':3,'Name':'jeevan','age':24, 'marks'=145}]\nstudent.insert_many(studentlist)\nclient.close()" }, { "code": null, "e": 59732, "s": 59576, "text": "To retrieve the documents (similar to SELECT query), we should use find() method. It returns a cursor with the help of which all documents can be obtained." }, { "code": null, "e": 59844, "s": 59732, "text": "students=db['students']\ndocs=students.find()\nfor doc in docs:\n print (doc['Name'], doc['age'], doc['marks'] )" }, { "code": null, "e": 60047, "s": 59844, "text": "To find a particular document instead of all of them in a collection, we need to apply filter to find() method. The filter uses logical operators. MongoDB has its own set of logical operators as below −" }, { "code": null, "e": 60051, "s": 60047, "text": "$eq" }, { "code": null, "e": 60065, "s": 60051, "text": "equal to (==)" }, { "code": null, "e": 60069, "s": 60065, "text": "$gt" }, { "code": null, "e": 60086, "s": 60069, "text": "greater than (>)" }, { "code": null, "e": 60091, "s": 60086, "text": "$gte" }, { "code": null, "e": 60121, "s": 60091, "text": "greater than or equal to (>=)" }, { "code": null, "e": 60125, "s": 60121, "text": "$in" }, { "code": null, "e": 60156, "s": 60125, "text": "if equal to any value in array" }, { "code": null, "e": 60160, "s": 60156, "text": "$lt" }, { "code": null, "e": 60174, "s": 60160, "text": "less than (<)" }, { "code": null, "e": 60179, "s": 60174, "text": "$lte" }, { "code": null, "e": 60206, "s": 60179, "text": "less than or equal to (<=)" }, { "code": null, "e": 60210, "s": 60206, "text": "$ne" }, { "code": null, "e": 60228, "s": 60210, "text": "not equal to (!=)" }, { "code": null, "e": 60233, "s": 60228, "text": "$nin" }, { "code": null, "e": 60268, "s": 60233, "text": "if not equal to any value in array" }, { "code": null, "e": 60414, "s": 60268, "text": "For example, we are interested in obtaining list of students older than 21 years. Using $gt operator in the filter for find() method as follows −" }, { "code": null, "e": 60555, "s": 60414, "text": "students=db['students']\ndocs=students.find({'age':{'$gt':21}})\nfor doc in docs:\n print (doc.get('Name'), doc.get('age'), doc.get('marks'))" }, { "code": null, "e": 60713, "s": 60555, "text": "PyMongo module provides update_one() and update_many() methods for modifying one document or more than one documents satisfying a specific filter expression." }, { "code": null, "e": 60780, "s": 60713, "text": "Let us update marks attribute of a document in which name is Juhi." }, { "code": null, "e": 60974, "s": 60780, "text": "from pymongo import MongoClient\nclient=MongoClient()\ndb=client.newdb\ndoc=db.students.find_one({'Name': 'Juhi'})\ndb['students'].update_one({'Name': 'Juhi'},{\"$set\":{'marks':150}})\nclient.close()" }, { "code": null, "e": 61244, "s": 60974, "text": "Cassandra is another popular NoSQL database. High scalability, consistency, and fault-tolerance - these are some of the important features of Cassandra. This is Column store database. The data is stored across many commodity servers. As a result, data highly available." }, { "code": null, "e": 61524, "s": 61244, "text": "Cassandra is a product from Apache Software foundation. Data is stored in distributed manner across multiple nodes. Each node is a single server consisting of keyspaces. Fundamental building block of Cassandra database is keyspace which can be considered analogous to a database." }, { "code": null, "e": 61899, "s": 61524, "text": "Data in one node of Cassandra, is replicated in other nodes over a peer-to-peer network of nodes. That makes Cassandra a foolproof database. The network is called a data center. Multiple data centers may be interconnected to form a cluster. Nature of replication is configured by setting Replication strategy and replication factor at the time of the creation of a keyspace." }, { "code": null, "e": 62171, "s": 61899, "text": "One keyspace may have more than one Column families – just as one database may contain multiple tables. Cassandra’s keyspace doesn’t have a predefined schema. It is possible that each row in a Cassandra table may have columns with different names and in variable numbers." }, { "code": null, "e": 62450, "s": 62171, "text": "Cassandra software is also available in two versions: community and enterprise. The latest enterprise version of Cassandra is available for download at https://cassandra.apache.org/download/. Community edition is found at https://academy.datastax.com/planet-cassandra/cassandra." }, { "code": null, "e": 62665, "s": 62450, "text": "Cassandra has its own query language called Cassandra Query Language (CQL). CQL queries can be executed from inside a CQLASH shell – similar to MySQL or SQLite shell. The CQL syntax appears similar to standard SQL." }, { "code": null, "e": 62759, "s": 62665, "text": "The Datastax community edition, also comes with a Develcenter IDE shown in following figure −" }, { "code": null, "e": 62989, "s": 62759, "text": "Python module for working with Cassandra database is called Cassandra Driver. It is also developed by Apache foundation. This module contains an ORM API, as well as a core API similar in nature to DB-API for relational databases." }, { "code": null, "e": 63056, "s": 62989, "text": "Installation of Cassandra driver is easily done using pip utility." }, { "code": null, "e": 63087, "s": 63056, "text": "pip3 install cassandra-driver\n" }, { "code": null, "e": 63245, "s": 63087, "text": "Interaction with Cassandra database, is done through Cluster object. Cassandra.cluster module defines Cluster class. We first need to declare Cluster object." }, { "code": null, "e": 63300, "s": 63245, "text": "from cassandra.cluster import Cluster\nclstr=Cluster()\n" }, { "code": null, "e": 63399, "s": 63300, "text": "All transactions such as insert/update, etc., are performed by starting a session with a keyspace." }, { "code": null, "e": 63424, "s": 63399, "text": "session=clstr.connect()\n" }, { "code": null, "e": 63647, "s": 63424, "text": "To create a new keyspace, use execute() method of session object. The execute() method takes a string argument which must be a query string. The CQL has CREATE KEYSPACE statement as follows. The complete code is as below −" }, { "code": null, "e": 63847, "s": 63647, "text": "from cassandra.cluster import Cluster\nclstr=Cluster()\nsession=clstr.connect()\nsession.execute(“create keyspace mykeyspace with replication={\n 'class': 'SimpleStrategy', 'replication_factor' : 3\n};”" }, { "code": null, "e": 64155, "s": 63847, "text": "Here, SimpleStrategy is a value for replication strategy and replication factor is set to 3. As mentioned earlier, a keyspace contains one or more tables. Each table is characterized by it data type. Python data types are automatically parsed with corresponding CQL data types according to following table −" }, { "code": null, "e": 64236, "s": 64155, "text": "To create a table, use session object to execute CQL query for creating a table." }, { "code": null, "e": 64470, "s": 64236, "text": "from cassandra.cluster import Cluster\nclstr=Cluster()\nsession=clstr.connect('mykeyspace')\nqry= '''\ncreate table students (\n studentID int,\n name text,\n age int,\n marks int,\n primary key(studentID)\n);'''\nsession.execute(qry)" }, { "code": null, "e": 64646, "s": 64470, "text": "The keyspace so created can be further used to insert rows. The CQL version of INSERT query is similar to SQL Insert statement. Following code inserts a row in students table." }, { "code": null, "e": 64837, "s": 64646, "text": "from cassandra.cluster import Cluster\nclstr=Cluster()\nsession=clstr.connect('mykeyspace')\nsession.execute(\"insert into students (studentID, name, age, marks) values \n (1, 'Juhi',20, 200);\"" }, { "code": null, "e": 65032, "s": 64837, "text": "As you would expect, SELECT statement is also used with Cassandra. In case of execute() method containing SELECT query string, it returns a result set object which can be traversed using a loop." }, { "code": null, "e": 65285, "s": 65032, "text": "from cassandra.cluster import Cluster\nclstr=Cluster()\nsession=clstr.connect('mykeyspace')\nrows=session.execute(\"select * from students;\")\nfor row in rows:\nprint (StudentID: {} Name:{} Age:{} price:{} Marks:{}'\n .format(row[0],row[1], row[2], row[3]))" }, { "code": null, "e": 65580, "s": 65285, "text": "Cassandra’s SELECT query supports use of WHERE clause to apply filter on result set to be fetched. Traditional logical operators like <, > == etc. are recognized. To retrieve, only those rows from students table for names with age>20, the query string in execute() method should be as follows −" }, { "code": null, "e": 65658, "s": 65580, "text": "rows=session.execute(\"select * from students WHERE age>20 allow filtering;\")\n" }, { "code": null, "e": 65801, "s": 65658, "text": "Note, the use of ALLOW FILTERING. The ALLOW FILTERING part of this statement allows to explicitly allow (some) queries that require filtering." }, { "code": null, "e": 65897, "s": 65801, "text": "Cassandra driver API defines following classes of Statement type in its cassendra.query module." }, { "code": null, "e": 66009, "s": 65897, "text": "A simple, unprepared CQL query contained in a query string. All examples above are examples of SimpleStatement." }, { "code": null, "e": 66180, "s": 66009, "text": "Multiple queries (such as INSERT, UPDATE, and DELETE) are put in a batch and executed at once. Each row is first converted as a SimpleStatement and then added in a batch." }, { "code": null, "e": 66269, "s": 66180, "text": "Let us put rows to be added in Students table in the form of list of tuples as follows −" }, { "code": null, "e": 66344, "s": 66269, "text": "studentlist=[(1,'Juhi',20,100), ('2,'dilip',20, 110),(3,'jeevan',24,145)]\n" }, { "code": null, "e": 66406, "s": 66344, "text": "To add above rows using BathStatement, run following script −" }, { "code": null, "e": 66709, "s": 66406, "text": "from cassandra.query import SimpleStatement, BatchStatement\nbatch=BatchStatement()\nfor student in studentlist:\n batch.add(SimpleStatement(\"INSERT INTO students \n (studentID, name, age, marks) VALUES\n (%s, %s, %s %s)\"), (student[0], student[1],student[2], student[3]))\nsession.execute(batch)" }, { "code": null, "e": 66890, "s": 66709, "text": "Prepared statement is like a parameterized query in DB-API. Its query string is saved by Cassandra for later use. The Session.prepare() method returns a PreparedStatement instance." }, { "code": null, "e": 66967, "s": 66890, "text": "For our students table, a PreparedStatement for INSERT query is as follows −" }, { "code": null, "e": 67058, "s": 66967, "text": "stmt=session.prepare(\"INSERT INTO students (studentID, name, age, marks) VALUES (?,?,?)\")\n" }, { "code": null, "e": 67142, "s": 67058, "text": "Subsequently, it only needs to send the values of parameters to bind. For example −" }, { "code": null, "e": 67176, "s": 67142, "text": "qry=stmt.bind([1,'Ram', 23,175])\n" }, { "code": null, "e": 67220, "s": 67176, "text": "Finally, execute the bound statement above." }, { "code": null, "e": 67242, "s": 67220, "text": "session.execute(qry)\n" }, { "code": null, "e": 67356, "s": 67242, "text": "This reduces network traffic and CPU utilization because Cassandra does not have to re-parse the query each time." }, { "code": null, "e": 67780, "s": 67356, "text": "ZODB (Zope object Database) is database for storing Python objects. It is ACID compliant - feature not found in NOSQL databases. The ZODB is also open source, horizontally scalable and schema-free, like many NoSQL databases. However, it is not distributed and does not offer easy replication. It provides persistence mechanism for Python objects. It is a part of Zope Application server, but can also be independently used." }, { "code": null, "e": 68021, "s": 67780, "text": "ZODB was created by Jim Fulton of Zope Corporation. It started as simple Persistent Object System. Its current version is 5.5.0 and is written completely in Python. using an extended version of Python's built-in object persistence (pickle)." }, { "code": null, "e": 68061, "s": 68021, "text": "Some of the main features of ZODB are −" }, { "code": null, "e": 68074, "s": 68061, "text": "transactions" }, { "code": null, "e": 68087, "s": 68074, "text": "history/undo" }, { "code": null, "e": 68119, "s": 68087, "text": "transparently pluggable storage" }, { "code": null, "e": 68136, "s": 68119, "text": "built-in caching" }, { "code": null, "e": 68176, "s": 68136, "text": "multiversion concurrency control (MVCC)" }, { "code": null, "e": 68205, "s": 68176, "text": "scalability across a network" }, { "code": null, "e": 68527, "s": 68205, "text": "The ZODB is a hierarchical database. There is a root object, initialized when a database is created. The root object is used like a Python dictionary and it can contain other objects (which can be dictionary-like themselves). To store an object in the database, it’s enough to assign it to a new key inside its container." }, { "code": null, "e": 68735, "s": 68527, "text": "ZODB is useful for applications where data is hierarchical and there are likely to be more reads than writes. ZODB is an extension of pickle object. That's why it can be processed through Python script only." }, { "code": null, "e": 68791, "s": 68735, "text": "To install latest version of ZODB let use pip utility −" }, { "code": null, "e": 68809, "s": 68791, "text": "pip install zodb\n" }, { "code": null, "e": 68853, "s": 68809, "text": "Following dependencies are also installed −" }, { "code": null, "e": 68867, "s": 68853, "text": "BTrees==4.6.1" }, { "code": null, "e": 68880, "s": 68867, "text": "cffi==1.13.2" }, { "code": null, "e": 68898, "s": 68880, "text": "persistent==4.5.1" }, { "code": null, "e": 68914, "s": 68898, "text": "pycparser==2.19" }, { "code": null, "e": 68926, "s": 68914, "text": "six==1.13.0" }, { "code": null, "e": 68945, "s": 68926, "text": "transaction==2.4.0" }, { "code": null, "e": 68987, "s": 68945, "text": "ZODB provides following storage options −" }, { "code": null, "e": 69091, "s": 68987, "text": "This is the default. Everything stored in one big Data.fs file, which is essentially a transaction log." }, { "code": null, "e": 69223, "s": 69091, "text": "This stores one file per object revision. In this case, it does not require the Data.fs.index to be rebuilt on an unclean shutdown." }, { "code": null, "e": 69313, "s": 69223, "text": "This stores pickles in a relational database. PostgreSQL, MySQL and Oracle are supported." }, { "code": null, "e": 69393, "s": 69313, "text": "To create ZODB database we need a storage, a database and finally a connection." }, { "code": null, "e": 69431, "s": 69393, "text": "First step is to have storage object." }, { "code": null, "e": 69514, "s": 69431, "text": "import ZODB, ZODB.FileStorage\nstorage = ZODB.FileStorage.FileStorage('mydata.fs')\n" }, { "code": null, "e": 69575, "s": 69514, "text": "DB class uses this storage object to obtain database object." }, { "code": null, "e": 69598, "s": 69575, "text": "db = ZODB.DB(storage)\n" }, { "code": null, "e": 69656, "s": 69598, "text": "Pass None to DB constructor to create in-memory database." }, { "code": null, "e": 69674, "s": 69656, "text": "Db=ZODB.DB(None)\n" }, { "code": null, "e": 69726, "s": 69674, "text": "Finally, we establish connection with the database." }, { "code": null, "e": 69742, "s": 69726, "text": "conn=db.open()\n" }, { "code": null, "e": 69921, "s": 69742, "text": "The connection object then gives you access to the ‘root’ of the database with the ‘root()’ method. The ‘root’ object is the dictionary that holds all of your persistent objects." }, { "code": null, "e": 69941, "s": 69921, "text": "root = conn.root()\n" }, { "code": null, "e": 70012, "s": 69941, "text": "For example, we add a list of students to the root object as follows −" }, { "code": null, "e": 70057, "s": 70012, "text": "root['students'] = ['Mary', 'Maya', 'Meet']\n" }, { "code": null, "e": 70142, "s": 70057, "text": "This change is not permanently saved in the database till we commit the transaction." }, { "code": null, "e": 70183, "s": 70142, "text": "import transaction\ntransaction.commit()\n" }, { "code": null, "e": 70293, "s": 70183, "text": "To store object of a user defined class, the class must be inherited from persistent.Persistent parent class." }, { "code": null, "e": 70354, "s": 70293, "text": "Subclassing Persistent class has its advantages as follows −" }, { "code": null, "e": 70435, "s": 70354, "text": "The database will automatically track object changes made by setting attributes." }, { "code": null, "e": 70516, "s": 70435, "text": "The database will automatically track object changes made by setting attributes." }, { "code": null, "e": 70563, "s": 70516, "text": "Data will be saved in its own database record." }, { "code": null, "e": 70610, "s": 70563, "text": "Data will be saved in its own database record." }, { "code": null, "e": 70932, "s": 70610, "text": "You can save data that doesn’t subclass Persistent, but it will be stored in the database record of whatever persistent object references it. Non-persistent objects are owned by their containing persistent object and if multiple persistent objects refer to the same non-persistent subobject, they’ll get their own copies." }, { "code": null, "e": 71254, "s": 70932, "text": "You can save data that doesn’t subclass Persistent, but it will be stored in the database record of whatever persistent object references it. Non-persistent objects are owned by their containing persistent object and if multiple persistent objects refer to the same non-persistent subobject, they’ll get their own copies." }, { "code": null, "e": 71325, "s": 71254, "text": "Let use define a student class subclassing Persistent class as under −" }, { "code": null, "e": 71487, "s": 71325, "text": "import persistent\n class student(persistent.Persistent):\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n return str(self.name)" }, { "code": null, "e": 71571, "s": 71487, "text": "To add object of this class, let us first set up the connection as described above." }, { "code": null, "e": 71714, "s": 71571, "text": "import ZODB, ZODB.FileStorage\nstorage = ZODB.FileStorage.FileStorage('studentdata.fs')\ndb = ZODB.DB(storage)\nconn=db.open()\nroot = conn.root()" }, { "code": null, "e": 71776, "s": 71714, "text": "Declare object an add to root and then commit the transaction" }, { "code": null, "e": 71863, "s": 71776, "text": "s1=student(\"Akash\")\nroot['s1']=s1\nimport transaction\ntransaction.commit()\nconn.close()" }, { "code": null, "e": 72016, "s": 71863, "text": "List of all objects added to root can be retrieved as a view object with the help of items() method since root object is similar to built in dictionary." }, { "code": null, "e": 72063, "s": 72016, "text": "print (root.items())\nItemsView({'s1': Akash})\n" }, { "code": null, "e": 72112, "s": 72063, "text": "To fetch attribute of specific object from root," }, { "code": null, "e": 72143, "s": 72112, "text": "print (root['s1'].name)\nAkash\n" }, { "code": null, "e": 72284, "s": 72143, "text": "The object can be easily updated. Since the ZODB API is a pure Python package, it doesn’t require any external SQL type language to be used." }, { "code": null, "e": 72352, "s": 72284, "text": "root['s1'].name='Abhishek'\nimport transaction\ntransaction.commit()\n" }, { "code": null, "e": 72509, "s": 72352, "text": "The database will be updated instantly. Note that transaction class also defines abort() function which is similar to rollback() transaction control in SQL." }, { "code": null, "e": 72783, "s": 72509, "text": "Microsoft’s Excel is the most popular spreadsheet application. It has been in use since last more than 25 years. Later versions of Excel use Office Open XML (OOXML) file format. Hence, it has been possible to access spreadsheet files through other programming environments." }, { "code": null, "e": 72919, "s": 72783, "text": "OOXML is an ECMA standard file format. Python’s openpyxl package provides functionality to read/write Excel files with .xlsx extension." }, { "code": null, "e": 73402, "s": 72919, "text": "The openpyxl package uses class nomenclature that is similar to Microsoft Excel terminology. An Excel document is called as workbook and is saved with .xlsx extension in the file system. A workbook may have multiple worksheets. A worksheet presents a large grid of cells, each one of them can store either value or formula. Rows and columns that form the grid are numbered. Columns are identified by alphabets, A, B, C, ...., Z, AA, AB, and so on. Rows are numbered starting from 1." }, { "code": null, "e": 73449, "s": 73402, "text": "A typical Excel worksheet appears as follows −" }, { "code": null, "e": 73509, "s": 73449, "text": "The pip utility is good enough to install openpyxl package." }, { "code": null, "e": 73531, "s": 73509, "text": "pip install openpyxl\n" }, { "code": null, "e": 73677, "s": 73531, "text": "The Workbook class represents an empty workbook with one blank worksheet. We need to activate it so that some data can be added to the worksheet." }, { "code": null, "e": 73765, "s": 73677, "text": "from openpyxl import Workbook\nwb=Workbook()\nsheet1=wb.active\nsheet1.title='StudentList'" }, { "code": null, "e": 73908, "s": 73765, "text": "As we know, a cell in worksheet is named as ColumnNameRownumber format. Accordingly, top left cell is A1. We assign a string to this cell as −" }, { "code": null, "e": 73938, "s": 73908, "text": "sheet1['A1']= 'Student List'\n" }, { "code": null, "e": 74088, "s": 73938, "text": "Alternately, use worksheet’s cell() method which uses row and column number to identify a cell. Call value property to cell object to assign a value." }, { "code": null, "e": 74151, "s": 74088, "text": "cell1=sheet1.cell(row=1, column=1)\ncell1.value='Student List'\n" }, { "code": null, "e": 74256, "s": 74151, "text": "After populating worksheet with data, the workbook is saved by calling save() method of workbook object." }, { "code": null, "e": 74281, "s": 74256, "text": "wb.save('Student.xlsx')\n" }, { "code": null, "e": 74341, "s": 74281, "text": "This workbook file is created in current working directory." }, { "code": null, "e": 74472, "s": 74341, "text": "Following Python script writes a list of tuples into a workbook document. Each tuple stores roll number, age and marks of student." }, { "code": null, "e": 74875, "s": 74472, "text": "from openpyxl import Workbook\nwb = Workbook()\nsheet1 = wb.active\nsheet1.title='Student List'\nsheet1.cell(column=1, row=1).value='Student List'\nstudentlist=[('RollNo','Name', 'age', 'marks'),(1,'Juhi',20,100), \n (2,'dilip',20, 110) , (3,'jeevan',24,145)]\nfor col in range(1,5):\n for row in range(1,5):\n sheet1.cell(column=col, row=1+row).value=studentlist[row-1][col-1]\nwb.save('students.xlsx')" }, { "code": null, "e": 74998, "s": 74875, "text": "The workbook students.xlsx is saved in current working directory. If opened using Excel application, it appears as below −" }, { "code": null, "e": 75108, "s": 74998, "text": "The openpyxl module offers load_workbook() function that helps in reading back data in the workbook document." }, { "code": null, "e": 75177, "s": 75108, "text": "from openpyxl import load_workbook\nwb=load_workbook('students.xlsx')" }, { "code": null, "e": 75250, "s": 75177, "text": "You can now access value of any cell specified by row and column number." }, { "code": null, "e": 75318, "s": 75250, "text": "cell1=sheet1.cell(row=1, column=1)\nprint (cell1.value)\nStudent List" }, { "code": null, "e": 75372, "s": 75318, "text": "Following code populates a list with work sheet data." }, { "code": null, "e": 75658, "s": 75372, "text": "from openpyxl import load_workbook\nwb=load_workbook('students.xlsx')\nsheet1 = wb['Student List']\nstudentlist=[]\nfor row in range(1,5):\n stud=[]\nfor col in range(1,5):\n val=sheet1.cell(column=col, row=1+row).value\nstud.append(val)\nstudentlist.append(tuple(stud))\nprint (studentlist)" }, { "code": null, "e": 75765, "s": 75658, "text": "[('RollNo', 'Name', 'age', 'marks'), (1, 'Juhi', 20, 100), (2, 'dilip', 20, 110), (3, 'jeevan', 24, 145)]\n" }, { "code": null, "e": 75962, "s": 75765, "text": "One very important feature of Excel application is the formula. To assign formula to a cell, assign it to a string containing Excel’s formula syntax. Assign AVERAGE function to c6 cell having age." }, { "code": null, "e": 75994, "s": 75962, "text": "sheet1['C6']= 'AVERAGE(C3:C5)'\n" }, { "code": null, "e": 76182, "s": 75994, "text": "Openpyxl module has Translate_formula() function to copy the formula across a range. Following program defines AVERAGE function in C6 and copies it to C7 that calculates average of marks." }, { "code": null, "e": 76504, "s": 76182, "text": "from openpyxl import load_workbook\nwb=load_workbook('students.xlsx')\n\nsheet1 = wb['Student List']\nfrom openpyxl.formula.translate import Translator#copy formula\nsheet1['B6']='Average'\nsheet1['C6']='=AVERAGE(C3:C5)'\nsheet1['D6'] = Translator('=AVERAGE(C3:C5)', origin=\"C6\").translate_formula(\"D6\")\nwb.save('students.xlsx')" } ]
Sort the given matrix
19 May, 2021 Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row ‘i’ is greater than or equal to the last element of row ‘i-1’.Examples: Input : mat[][] = { {5, 4, 7}, {1, 3, 8}, {2, 9, 6} } Output : 1 2 3 4 5 6 7 8 9 Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix. C++ Java Python3 C# Javascript // C++ implementation to sort the given matrix#include <bits/stdc++.h>using namespace std; #define SIZE 10 // function to sort the given matrixvoid sortMat(int mat[SIZE][SIZE], int n){ // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++];} // function to print the given matrixvoid printMat(int mat[SIZE][SIZE], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; }} // Driver program to test aboveint main(){ int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << "Original Matrix:\n"; printMat(mat, n); sortMat(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0;} // Java implementation to// sort the given matriximport java.io.*;import java.util.*; class GFG { static int SIZE = 10; // function to sort the given matrix static void sortMat(int mat[][], int n) { // temporary matrix of size n^2 int temp[] = new int[n * n]; int k = 0; // copy the elements of matrix // one by one into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] Arrays.sort(temp); // copy the elements of temp[] // one by one in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix static void printMat(int mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print( mat[i][j] + " "); System.out.println(); } } // Driver program to test above public static void main(String args[]) { int mat[][] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; System.out.println("Original Matrix:"); printMat(mat, n); sortMat(mat, n); System.out.println("Matrix After Sorting:"); printMat(mat, n); }} // This code is contributed by Nikita Tiwari. # Python3 implementation to sort# the given matrix SIZE = 10 # Function to sort the given matrixdef sortMat(mat, n) : # Temporary matrix of size n^2 temp = [0] * (n * n) k = 0 # Copy the elements of matrix # one by one into temp[] for i in range(0, n) : for j in range(0, n) : temp[k] = mat[i][j] k += 1 # sort temp[] temp.sort() # copy the elements of temp[] # one by one in mat[][] k = 0 for i in range(0, n) : for j in range(0, n) : mat[i][j] = temp[k] k += 1 # Function to print the given matrixdef printMat(mat, n) : for i in range(0, n) : for j in range( 0, n ) : print(mat[i][j] , end = " ") print() # Driver program to test abovemat = [ [ 5, 4, 7 ], [ 1, 3, 8 ], [ 2, 9, 6 ] ]n = 3 print( "Original Matrix:")printMat(mat, n) sortMat(mat, n) print("\nMatrix After Sorting:")printMat(mat, n) # This code is contributed by Nikita Tiwari. // C# implementation to// sort the given matrixusing System; class GFG { static int SIZE = 10; // function to sort the given matrix static void sortMat(int[, ] mat, int n) { // temporary matrix of size n^2 int[] temp = new int[n * n]; int k = 0; // copy the elements of matrix // one by one into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i, j]; // sort temp[] Array.Sort(temp); // copy the elements of temp[] // one by one in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i, j] = temp[k++]; } // function to print the given matrix static void printMat(int[, ] mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(mat[i, j] + " "); Console.WriteLine(); } } // Driver code public static void Main() { int[, ] mat = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; Console.WriteLine("Original Matrix:"); printMat(mat, n); sortMat(mat, n); Console.WriteLine("Matrix After Sorting:"); printMat(mat, n); }} // This code is contributed by Sam007 <script> // JavaScript implementation to sort// the given matrix let SIZE = 10 // function to sort the given matrixfunction sortMat(mat, n){ // temporary matrix of size n^2 let temp = new Array(n * n); let k = 0; // copy the elements of matrix one by one // into temp[] for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] temp.sort(); // copy the elements of temp[] one by one // in mat[][] k = 0; for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) mat[i][j] = temp[k++];} // function to print the given matrixfunction printMat(mat, n){ for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write( mat[i][j] + " "); document.write( "<br>"); }} // Driver program to test above let mat = [ [ 5, 4, 7 ], [ 1, 3, 8 ], [ 2, 9, 6 ] ]; let n = 3; document.write( "Original Matrix: " + "<br>"); printMat(mat, n); sortMat(mat, n); document.write( "<br>"); document.write( "\nMatrix After Sorting: " + "<br>"); printMat(mat, n); // This code is contributed by Manoj </script> Output: Original Matrix: 5 4 7 1 3 8 2 9 6 Matrix After Sorting: 1 2 3 4 5 6 7 8 9 Time Complexity: O(n2log2n). Auxiliary Space: O(n2). mank1083 Matrix Sorting Sorting Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 May, 2021" }, { "code": null, "e": 383, "s": 53, "text": "Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row ‘i’ is greater than or equal to the last element of row ‘i-1’.Examples: " }, { "code": null, "e": 522, "s": 383, "text": "Input : mat[][] = { {5, 4, 7},\n {1, 3, 8},\n {2, 9, 6} }\nOutput : 1 2 3\n 4 5 6\n 7 8 9" }, { "code": null, "e": 742, "s": 524, "text": "Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix. " }, { "code": null, "e": 746, "s": 742, "text": "C++" }, { "code": null, "e": 751, "s": 746, "text": "Java" }, { "code": null, "e": 759, "s": 751, "text": "Python3" }, { "code": null, "e": 762, "s": 759, "text": "C#" }, { "code": null, "e": 773, "s": 762, "text": "Javascript" }, { "code": "// C++ implementation to sort the given matrix#include <bits/stdc++.h>using namespace std; #define SIZE 10 // function to sort the given matrixvoid sortMat(int mat[SIZE][SIZE], int n){ // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++];} // function to print the given matrixvoid printMat(int mat[SIZE][SIZE], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << \" \"; cout << endl; }} // Driver program to test aboveint main(){ int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << \"Original Matrix:\\n\"; printMat(mat, n); sortMat(mat, n); cout << \"\\nMatrix After Sorting:\\n\"; printMat(mat, n); return 0;}", "e": 1957, "s": 773, "text": null }, { "code": "// Java implementation to// sort the given matriximport java.io.*;import java.util.*; class GFG { static int SIZE = 10; // function to sort the given matrix static void sortMat(int mat[][], int n) { // temporary matrix of size n^2 int temp[] = new int[n * n]; int k = 0; // copy the elements of matrix // one by one into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] Arrays.sort(temp); // copy the elements of temp[] // one by one in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix static void printMat(int mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print( mat[i][j] + \" \"); System.out.println(); } } // Driver program to test above public static void main(String args[]) { int mat[][] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; System.out.println(\"Original Matrix:\"); printMat(mat, n); sortMat(mat, n); System.out.println(\"Matrix After Sorting:\"); printMat(mat, n); }} // This code is contributed by Nikita Tiwari.", "e": 3447, "s": 1957, "text": null }, { "code": "# Python3 implementation to sort# the given matrix SIZE = 10 # Function to sort the given matrixdef sortMat(mat, n) : # Temporary matrix of size n^2 temp = [0] * (n * n) k = 0 # Copy the elements of matrix # one by one into temp[] for i in range(0, n) : for j in range(0, n) : temp[k] = mat[i][j] k += 1 # sort temp[] temp.sort() # copy the elements of temp[] # one by one in mat[][] k = 0 for i in range(0, n) : for j in range(0, n) : mat[i][j] = temp[k] k += 1 # Function to print the given matrixdef printMat(mat, n) : for i in range(0, n) : for j in range( 0, n ) : print(mat[i][j] , end = \" \") print() # Driver program to test abovemat = [ [ 5, 4, 7 ], [ 1, 3, 8 ], [ 2, 9, 6 ] ]n = 3 print( \"Original Matrix:\")printMat(mat, n) sortMat(mat, n) print(\"\\nMatrix After Sorting:\")printMat(mat, n) # This code is contributed by Nikita Tiwari.", "e": 4526, "s": 3447, "text": null }, { "code": "// C# implementation to// sort the given matrixusing System; class GFG { static int SIZE = 10; // function to sort the given matrix static void sortMat(int[, ] mat, int n) { // temporary matrix of size n^2 int[] temp = new int[n * n]; int k = 0; // copy the elements of matrix // one by one into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i, j]; // sort temp[] Array.Sort(temp); // copy the elements of temp[] // one by one in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i, j] = temp[k++]; } // function to print the given matrix static void printMat(int[, ] mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(mat[i, j] + \" \"); Console.WriteLine(); } } // Driver code public static void Main() { int[, ] mat = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; Console.WriteLine(\"Original Matrix:\"); printMat(mat, n); sortMat(mat, n); Console.WriteLine(\"Matrix After Sorting:\"); printMat(mat, n); }} // This code is contributed by Sam007", "e": 5891, "s": 4526, "text": null }, { "code": "<script> // JavaScript implementation to sort// the given matrix let SIZE = 10 // function to sort the given matrixfunction sortMat(mat, n){ // temporary matrix of size n^2 let temp = new Array(n * n); let k = 0; // copy the elements of matrix one by one // into temp[] for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] temp.sort(); // copy the elements of temp[] one by one // in mat[][] k = 0; for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) mat[i][j] = temp[k++];} // function to print the given matrixfunction printMat(mat, n){ for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write( mat[i][j] + \" \"); document.write( \"<br>\"); }} // Driver program to test above let mat = [ [ 5, 4, 7 ], [ 1, 3, 8 ], [ 2, 9, 6 ] ]; let n = 3; document.write( \"Original Matrix: \" + \"<br>\"); printMat(mat, n); sortMat(mat, n); document.write( \"<br>\"); document.write( \"\\nMatrix After Sorting: \" + \"<br>\"); printMat(mat, n); // This code is contributed by Manoj </script>", "e": 7086, "s": 5891, "text": null }, { "code": null, "e": 7096, "s": 7086, "text": "Output: " }, { "code": null, "e": 7172, "s": 7096, "text": "Original Matrix:\n5 4 7\n1 3 8\n2 9 6\n\nMatrix After Sorting:\n1 2 3\n4 5 6\n7 8 9" }, { "code": null, "e": 7226, "s": 7172, "text": "Time Complexity: O(n2log2n). Auxiliary Space: O(n2). " }, { "code": null, "e": 7235, "s": 7226, "text": "mank1083" }, { "code": null, "e": 7242, "s": 7235, "text": "Matrix" }, { "code": null, "e": 7250, "s": 7242, "text": "Sorting" }, { "code": null, "e": 7258, "s": 7250, "text": "Sorting" }, { "code": null, "e": 7265, "s": 7258, "text": "Matrix" } ]
Last non-zero digit of a factorial
05 Jun, 2022 Given a number n, find the last non-zero digit in n!.Examples: Input : n = 5 Output : 2 5! = 5 * 4 * 3 * 2 * 1 = 120 Last non-zero digit in 120 is 2. Input : n = 33 Output : 8 A Simple Solution is to first find n!, then find the last non-zero digit of n. This solution doesn’t work for even slightly large numbers due to arithmetic overflow.A Better Solution is based on the below recursive formula Let D(n) be the last non-zero digit in n! If tens digit (or second last digit) of n is odd D(n) = 4 * D(floor(n/5)) * D(Unit digit of n) If tens digit (or second last digit) of n is even D(n) = 6 * D(floor(n/5)) * D(Unit digit of n) Illustration of the formula: For the numbers less than 10 we can easily find the last non-zero digit by the above simple solution, i.e., first computing n!, then finding the last digit. D(1) = 1, D(2) = 2, D(3) = 6, D(4) = 4, D(5) = 2, D(6) = 2, D(7) = 4, D(8) = 2, D(9) = 8. D(1) to D(9) are assumed to be precomputed. Example 1: n = 27 [Second last digit is even]: D(27) = 6 * D(floor(27/5)) * D(7) = 6 * D(5) * D(7) = 6 * 2 * 4 = 48 Last non-zero digit is 8 Example 2: n = 33 [Second last digit is odd]: D(33) = 4 * D(floor(33/5)) * D(3) = 4 * D(6) * 6 = 4 * 2 * 6 = 48 Last non-zero digit is 8 How does the above formula work? The below explanation provides intuition behind the formula. Readers may refer Refer http://math.stackexchange.com/questions/130352/last-non-zero-digit-of-a-factorial for complete proof. 14! = 14 * 13 * 12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 Since we are asked about last non-zero digit, we remove all 5's and equal number of 2's from factors of 14!. We get following: 14! = 14 * 13 * 12 * 11 * 2 * 9 * 8 * 7 * 6 * 3 * 2 * 1 Now we can get last non-zero digit by multiplying last digits of above factors! In n! a number of 2’s are always more than a number of 5’s. To remove trailing 0’s, we remove 5’s and equal number of 2’s. Let a = floor(n/5), b = n % 5. After removing an equal number of 5’s and 2’s, we can reduce the problem from n! to 2a * a! * b! D(n) = 2a * D(a) * D(b)Implementation: C++ C Java Python3 C# PHP Javascript // C++ program to find last non-zero digit in n!#include<bits/stdc++.h>using namespace std; // Initialize values of last non-zero digit of// numbers from 0 to 9int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; int lastNon0Digit(int n){ if (n < 10) return dig[n]; // Check whether tens (or second last) digit // is odd or even // If n = 375, So n/10 = 37 and (n/10)%10 = 7 // Applying formula for even and odd cases. if (((n/10)%10)%2 == 0) return (6*lastNon0Digit(n/5)*dig[n%10]) % 10; else return (4*lastNon0Digit(n/5)*dig[n%10]) % 10;} // Driver codeint main(){ int n = 14; cout << lastNon0Digit(n); return 0;} // C program to find last non-zero digit in n!#include<stdio.h> // Initialize values of last non-zero digit of// numbers from 0 to 9int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; int lastNon0Digit(int n){ if (n < 10) return dig[n]; // Check whether tens (or second last) digit // is odd or even // If n = 375, So n/10 = 37 and (n/10)%10 = 7 // Applying formula for even and odd cases. if (((n/10) % 10) % 2 == 0) return (6*lastNon0Digit(n/5)*dig[n%10]) % 10; else return (4*lastNon0Digit(n/5)*dig[n%10]) % 10;} // Driver codeint main(){ int n = 14; printf("%d",lastNon0Digit(n)); return 0;} // This code is contributed by allwink45. // Java program to find last// non-zero digit in n! class GFG{ // Initialize values of last non-zero digit of // numbers from 0 to 9 static int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; static int lastNon0Digit(int n) { if (n < 10) return dig[n]; // Check whether tens (or second last) // digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 Applying formula for // even and odd cases. if (((n / 10) % 10) % 2 == 0) return (6 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; else return (4 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; } // Driver code public static void main (String[] args) { int n = 14; System.out.print(lastNon0Digit(n)); }}// This code is contributed by Anant Agarwal. # Python program to find# last non-zero digit in n! # Initialize values of# last non-zero digit of# numbers from 0 to 9dig= [1, 1, 2, 6, 4, 2, 2, 4, 2, 8] def lastNon0Digit(n): if (n < 10): return dig[n] # Check whether tens (or second last) digit # is odd or even # If n = 375, So n/10 = 37 and (n/10)%10 = 7 # Applying formula for even and odd cases. if (((n//10)%10)%2 == 0): return (6*lastNon0Digit(n//5)*dig[n%10]) % 10 else: return (4*lastNon0Digit(n//5)*dig[n%10]) % 10 return 0 # driver coden = 14 print(lastNon0Digit(n)) # This code is contributed# by Anant Agarwal. // C# program to find last// non-zero digit in n!using System; class GFG { // Initialize values of last non-zero // digit of numbers from 0 to 9 static int []dig = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; static int lastNon0Digit(int n) { if (n < 10) return dig[n]; // Check whether tens (or second // last) digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 Applying formula // for even and odd cases. if (((n / 10) % 10) % 2 == 0) return (6 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; else return (4 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; } // Driver code public static void Main () { int n = 14; Console.Write(lastNon0Digit(n)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to find last// non-zero digit in n! // Initialize values of// last non-zero digit of// numbers from 0 to 9$dig = array(1, 1, 2, 6, 4, 2, 2, 4, 2, 8); function lastNon0Digit($n){ global $dig; if ($n < 10) return $dig[$n]; // Check whether tens(or second // last) digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 // Applying formula for even // and odd cases. if ((($n / 10) % 10) % 2 == 0) return (6 * lastNon0Digit($n / 5) * $dig[$n % 10]) % 10; else return (4 * lastNon0Digit($n / 5) * $dig[$n % 10]) % 10;} // Driver code$n = 14;echo(lastNon0Digit($n)); // This code is contributed by Ajit.?> <script> // Javascript program to find // last non-zero digit in n! // Initialize values of last non-zero // digit of numbers from 0 to 9 let dig = [1, 1, 2, 6, 4, 2, 2, 4, 2, 8]; function lastNon0Digit(n) { if (n < 10) return dig[n]; // Check whether tens (or second // last) digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 Applying formula // for even and odd cases. if ((parseInt(n / 10, 10) % 10) % 2 == 0) return (6 * lastNon0Digit(parseInt(n / 5, 10)) * dig[n % 10]) % 10; else return (4 * lastNon0Digit(parseInt(n / 5, 10)) * dig[n % 10]) % 10; } let n = 14; document.write(lastNon0Digit(n)); </script> 2 A Simple Solution based on recursion having worst-case Time Complexity O(nLog(n)). Approach:- It is given that you have to find the last positive digit. Now a digit is made multiple of 10 if there are 2 and 5. They produce a number with last digit 0.Now what we can do is divide each array element into its shortest divisible form by 5 and increase count of such occurrences.Now divide each array element into its shortest divisible form by 2 and decrease count of such occurrences. This way we are not considering the multiplication of 2 and a 5 in our multiplication(number of 2’s present in multiplication result upto n is always more than number 0f 5’s).Multiply each number(after removing pairs of 2’s and 5’s) now and store just last digit by taking remainder by 10.Now call recursively for smaller numbers by (currentNumber – 1) as parameter. It is given that you have to find the last positive digit. Now a digit is made multiple of 10 if there are 2 and 5. They produce a number with last digit 0. Now what we can do is divide each array element into its shortest divisible form by 5 and increase count of such occurrences. Now divide each array element into its shortest divisible form by 2 and decrease count of such occurrences. This way we are not considering the multiplication of 2 and a 5 in our multiplication(number of 2’s present in multiplication result upto n is always more than number 0f 5’s). Multiply each number(after removing pairs of 2’s and 5’s) now and store just last digit by taking remainder by 10. Now call recursively for smaller numbers by (currentNumber – 1) as parameter. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Helper Function to return the rightmost non-zero digitvoid callMeFactorialLastDigit(int n, int result[], int sumOf5){ int number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5);} int lastNon0Digit(int n){ int result[] = { 1 }; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0];} int main(){ cout << lastNon0Digit(7) << endl; cout << lastNon0Digit(12) << endl; return 0;} // This code is contributed by rameshtravel07. #include <stdio.h> // Helper Function to return the rightmost non-zero digitvoid callMeFactorialLastDigit(int n, int result[], int sumOf5){int number = n; // assaigning to new variable.if (number == 1) return; // base case // To store the count of times 5 can // divide the number.while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++;} // Divide the number by // 2 as much as possiblewhile (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; sumOf5--;} /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1)callMeFactorialLastDigit(n - 1, result, sumOf5);} int lastNon0Digit(int n){int result[] = { 1 }; // single element arraycallMeFactorialLastDigit(n, result, 0);return result[0];} int main(){printf("%d\n",lastNon0Digit(7));printf("%d",lastNon0Digit(12));return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { // Helper Function to return the rightmost non-zero // digit public static void callMeFactorialLastDigit(int n, int[] result, int sumOf5) { int number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5); } public static int lastNon0Digit(int n) { int[] result = { 1 }; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0]; } public static void main(String[] args) { System.out.println(lastNon0Digit(7)); // 3040 System.out.println(lastNon0Digit(12)); // 479001600 }}//This code is contributed by KaaL-EL. # Helper Function to return the rightmost non-zero digitdef callMeFactorialLastDigit(n, result, sumOf5): number = n # assaigning to new variable. if number == 1: return # base case # To store the count of times 5 can # divide the number. while (number % 5 == 0): number = int(number / 5) # increase count of 5 sumOf5 += 1 # Divide the number by # 2 as much as possible while (sumOf5 != 0 and (number & 1) == 0): number >>= 1 # dividing the number by 2 sumOf5 -= 1 """multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.""" result[0] = (result[0] * (number % 10)) % 10 # calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5) def lastNon0Digit(n): result = [ 1 ] # single element array. callMeFactorialLastDigit(n, result, 0) return result[0] print(lastNon0Digit(7)) # 3040print(lastNon0Digit(12)) # 479001600 # This code is contributed by suresh07. using System;class GFG { // Helper Function to return the rightmost non-zero // digit static void callMeFactorialLastDigit(int n, int[] result, int sumOf5) { int number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5); } static int lastNon0Digit(int n) { int[] result = { 1 }; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0]; } static void Main() { Console.WriteLine(lastNon0Digit(7)); // 3040 Console.WriteLine(lastNon0Digit(12)); // 479001600 }} // This code is contributed by mukesh07. <script> // Helper Function to return the rightmost non-zero // digit function callMeFactorialLastDigit(n, result, sumOf5) { let number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5); } function lastNon0Digit(n) { let result = [ 1 ]; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0]; } document.write(lastNon0Digit(7) + "</br>"); // 3040 document.write(lastNon0Digit(12)); // 479001600 // This code is contributed by divyeshrabadiya07</script> 4 6 we used single element array (int[] result = {1}) instead of integer as Java is Strictly Pass by Value!. It does not allow pass by reference for primitive data types. That’s why I used a single element array so that the recursive function can change the value of variable(result here). If we would have taken (int result = 1) then this variable remain unaffected. This article is contributed by Niteesh kumar & KaaL-EL. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t divyesh072019 kaalel sweetyty divyeshrabadiya07 mukesh07 rameshtravel07 suresh07 allwink45 ridazouga factorial Modular Arithmetic Mathematical Recursion Mathematical Recursion Modular Arithmetic factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jun, 2022" }, { "code": null, "e": 117, "s": 52, "text": "Given a number n, find the last non-zero digit in n!.Examples: " }, { "code": null, "e": 233, "s": 117, "text": "Input : n = 5\nOutput : 2\n5! = 5 * 4 * 3 * 2 * 1 = 120\nLast non-zero digit in 120 is 2.\n\nInput : n = 33\nOutput : 8" }, { "code": null, "e": 459, "s": 235, "text": "A Simple Solution is to first find n!, then find the last non-zero digit of n. This solution doesn’t work for even slightly large numbers due to arithmetic overflow.A Better Solution is based on the below recursive formula " }, { "code": null, "e": 701, "s": 459, "text": "Let D(n) be the last non-zero digit in n!\nIf tens digit (or second last digit) of n is odd\n D(n) = 4 * D(floor(n/5)) * D(Unit digit of n) \nIf tens digit (or second last digit) of n is even\n D(n) = 6 * D(floor(n/5)) * D(Unit digit of n)" }, { "code": null, "e": 978, "s": 701, "text": "Illustration of the formula: For the numbers less than 10 we can easily find the last non-zero digit by the above simple solution, i.e., first computing n!, then finding the last digit. D(1) = 1, D(2) = 2, D(3) = 6, D(4) = 4, D(5) = 2, D(6) = 2, D(7) = 4, D(8) = 2, D(9) = 8. " }, { "code": null, "e": 1341, "s": 978, "text": "D(1) to D(9) are assumed to be precomputed.\n\nExample 1: n = 27 [Second last digit is even]:\nD(27) = 6 * D(floor(27/5)) * D(7)\n = 6 * D(5) * D(7)\n = 6 * 2 * 4 \n = 48\nLast non-zero digit is 8\n\nExample 2: n = 33 [Second last digit is odd]:\nD(33) = 4 * D(floor(33/5)) * D(3)\n = 4 * D(6) * 6\n = 4 * 2 * 6\n = 48\nLast non-zero digit is 8" }, { "code": null, "e": 1563, "s": 1341, "text": "How does the above formula work? The below explanation provides intuition behind the formula. Readers may refer Refer http://math.stackexchange.com/questions/130352/last-non-zero-digit-of-a-factorial for complete proof. " }, { "code": null, "e": 1945, "s": 1563, "text": "14! = 14 * 13 * 12 * 11 * 10 * 9 * 8 * 7 * \n 6 * 5 * 4 * 3 * 2 * 1\n\nSince we are asked about last non-zero digit, \nwe remove all 5's and equal number of 2's from\nfactors of 14!. We get following:\n\n14! = 14 * 13 * 12 * 11 * 2 * 9 * 8 * 7 *\n 6 * 3 * 2 * 1\n\nNow we can get last non-zero digit by multiplying\nlast digits of above factors!" }, { "code": null, "e": 2237, "s": 1945, "text": "In n! a number of 2’s are always more than a number of 5’s. To remove trailing 0’s, we remove 5’s and equal number of 2’s. Let a = floor(n/5), b = n % 5. After removing an equal number of 5’s and 2’s, we can reduce the problem from n! to 2a * a! * b! D(n) = 2a * D(a) * D(b)Implementation: " }, { "code": null, "e": 2241, "s": 2237, "text": "C++" }, { "code": null, "e": 2243, "s": 2241, "text": "C" }, { "code": null, "e": 2248, "s": 2243, "text": "Java" }, { "code": null, "e": 2256, "s": 2248, "text": "Python3" }, { "code": null, "e": 2259, "s": 2256, "text": "C#" }, { "code": null, "e": 2263, "s": 2259, "text": "PHP" }, { "code": null, "e": 2274, "s": 2263, "text": "Javascript" }, { "code": "// C++ program to find last non-zero digit in n!#include<bits/stdc++.h>using namespace std; // Initialize values of last non-zero digit of// numbers from 0 to 9int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; int lastNon0Digit(int n){ if (n < 10) return dig[n]; // Check whether tens (or second last) digit // is odd or even // If n = 375, So n/10 = 37 and (n/10)%10 = 7 // Applying formula for even and odd cases. if (((n/10)%10)%2 == 0) return (6*lastNon0Digit(n/5)*dig[n%10]) % 10; else return (4*lastNon0Digit(n/5)*dig[n%10]) % 10;} // Driver codeint main(){ int n = 14; cout << lastNon0Digit(n); return 0;}", "e": 2934, "s": 2274, "text": null }, { "code": "// C program to find last non-zero digit in n!#include<stdio.h> // Initialize values of last non-zero digit of// numbers from 0 to 9int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; int lastNon0Digit(int n){ if (n < 10) return dig[n]; // Check whether tens (or second last) digit // is odd or even // If n = 375, So n/10 = 37 and (n/10)%10 = 7 // Applying formula for even and odd cases. if (((n/10) % 10) % 2 == 0) return (6*lastNon0Digit(n/5)*dig[n%10]) % 10; else return (4*lastNon0Digit(n/5)*dig[n%10]) % 10;} // Driver codeint main(){ int n = 14; printf(\"%d\",lastNon0Digit(n)); return 0;} // This code is contributed by allwink45.", "e": 3622, "s": 2934, "text": null }, { "code": "// Java program to find last// non-zero digit in n! class GFG{ // Initialize values of last non-zero digit of // numbers from 0 to 9 static int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; static int lastNon0Digit(int n) { if (n < 10) return dig[n]; // Check whether tens (or second last) // digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 Applying formula for // even and odd cases. if (((n / 10) % 10) % 2 == 0) return (6 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; else return (4 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; } // Driver code public static void main (String[] args) { int n = 14; System.out.print(lastNon0Digit(n)); }}// This code is contributed by Anant Agarwal.", "e": 4507, "s": 3622, "text": null }, { "code": "# Python program to find# last non-zero digit in n! # Initialize values of# last non-zero digit of# numbers from 0 to 9dig= [1, 1, 2, 6, 4, 2, 2, 4, 2, 8] def lastNon0Digit(n): if (n < 10): return dig[n] # Check whether tens (or second last) digit # is odd or even # If n = 375, So n/10 = 37 and (n/10)%10 = 7 # Applying formula for even and odd cases. if (((n//10)%10)%2 == 0): return (6*lastNon0Digit(n//5)*dig[n%10]) % 10 else: return (4*lastNon0Digit(n//5)*dig[n%10]) % 10 return 0 # driver coden = 14 print(lastNon0Digit(n)) # This code is contributed# by Anant Agarwal.", "e": 5135, "s": 4507, "text": null }, { "code": "// C# program to find last// non-zero digit in n!using System; class GFG { // Initialize values of last non-zero // digit of numbers from 0 to 9 static int []dig = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8}; static int lastNon0Digit(int n) { if (n < 10) return dig[n]; // Check whether tens (or second // last) digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 Applying formula // for even and odd cases. if (((n / 10) % 10) % 2 == 0) return (6 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; else return (4 * lastNon0Digit(n / 5) * dig[n % 10]) % 10; } // Driver code public static void Main () { int n = 14; Console.Write(lastNon0Digit(n)); }} // This code is contributed by Nitin Mittal.", "e": 6021, "s": 5135, "text": null }, { "code": "<?php// PHP program to find last// non-zero digit in n! // Initialize values of// last non-zero digit of// numbers from 0 to 9$dig = array(1, 1, 2, 6, 4, 2, 2, 4, 2, 8); function lastNon0Digit($n){ global $dig; if ($n < 10) return $dig[$n]; // Check whether tens(or second // last) digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 // Applying formula for even // and odd cases. if ((($n / 10) % 10) % 2 == 0) return (6 * lastNon0Digit($n / 5) * $dig[$n % 10]) % 10; else return (4 * lastNon0Digit($n / 5) * $dig[$n % 10]) % 10;} // Driver code$n = 14;echo(lastNon0Digit($n)); // This code is contributed by Ajit.?>", "e": 6772, "s": 6021, "text": null }, { "code": "<script> // Javascript program to find // last non-zero digit in n! // Initialize values of last non-zero // digit of numbers from 0 to 9 let dig = [1, 1, 2, 6, 4, 2, 2, 4, 2, 8]; function lastNon0Digit(n) { if (n < 10) return dig[n]; // Check whether tens (or second // last) digit is odd or even // If n = 375, So n/10 = 37 and // (n/10)%10 = 7 Applying formula // for even and odd cases. if ((parseInt(n / 10, 10) % 10) % 2 == 0) return (6 * lastNon0Digit(parseInt(n / 5, 10)) * dig[n % 10]) % 10; else return (4 * lastNon0Digit(parseInt(n / 5, 10)) * dig[n % 10]) % 10; } let n = 14; document.write(lastNon0Digit(n)); </script>", "e": 7570, "s": 6772, "text": null }, { "code": null, "e": 7572, "s": 7570, "text": "2" }, { "code": null, "e": 7656, "s": 7572, "text": " A Simple Solution based on recursion having worst-case Time Complexity O(nLog(n))." }, { "code": null, "e": 7667, "s": 7656, "text": "Approach:-" }, { "code": null, "e": 8423, "s": 7667, "text": "It is given that you have to find the last positive digit. Now a digit is made multiple of 10 if there are 2 and 5. They produce a number with last digit 0.Now what we can do is divide each array element into its shortest divisible form by 5 and increase count of such occurrences.Now divide each array element into its shortest divisible form by 2 and decrease count of such occurrences. This way we are not considering the multiplication of 2 and a 5 in our multiplication(number of 2’s present in multiplication result upto n is always more than number 0f 5’s).Multiply each number(after removing pairs of 2’s and 5’s) now and store just last digit by taking remainder by 10.Now call recursively for smaller numbers by (currentNumber – 1) as parameter." }, { "code": null, "e": 8580, "s": 8423, "text": "It is given that you have to find the last positive digit. Now a digit is made multiple of 10 if there are 2 and 5. They produce a number with last digit 0." }, { "code": null, "e": 8706, "s": 8580, "text": "Now what we can do is divide each array element into its shortest divisible form by 5 and increase count of such occurrences." }, { "code": null, "e": 8990, "s": 8706, "text": "Now divide each array element into its shortest divisible form by 2 and decrease count of such occurrences. This way we are not considering the multiplication of 2 and a 5 in our multiplication(number of 2’s present in multiplication result upto n is always more than number 0f 5’s)." }, { "code": null, "e": 9105, "s": 8990, "text": "Multiply each number(after removing pairs of 2’s and 5’s) now and store just last digit by taking remainder by 10." }, { "code": null, "e": 9183, "s": 9105, "text": "Now call recursively for smaller numbers by (currentNumber – 1) as parameter." }, { "code": null, "e": 9235, "s": 9183, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 9239, "s": 9235, "text": "C++" }, { "code": null, "e": 9241, "s": 9239, "text": "C" }, { "code": null, "e": 9246, "s": 9241, "text": "Java" }, { "code": null, "e": 9254, "s": 9246, "text": "Python3" }, { "code": null, "e": 9257, "s": 9254, "text": "C#" }, { "code": null, "e": 9268, "s": 9257, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Helper Function to return the rightmost non-zero digitvoid callMeFactorialLastDigit(int n, int result[], int sumOf5){ int number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5);} int lastNon0Digit(int n){ int result[] = { 1 }; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0];} int main(){ cout << lastNon0Digit(7) << endl; cout << lastNon0Digit(12) << endl; return 0;} // This code is contributed by rameshtravel07.", "e": 10389, "s": 9268, "text": null }, { "code": "#include <stdio.h> // Helper Function to return the rightmost non-zero digitvoid callMeFactorialLastDigit(int n, int result[], int sumOf5){int number = n; // assaigning to new variable.if (number == 1) return; // base case // To store the count of times 5 can // divide the number.while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++;} // Divide the number by // 2 as much as possiblewhile (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; sumOf5--;} /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1)callMeFactorialLastDigit(n - 1, result, sumOf5);} int lastNon0Digit(int n){int result[] = { 1 }; // single element arraycallMeFactorialLastDigit(n, result, 0);return result[0];} int main(){printf(\"%d\\n\",lastNon0Digit(7));printf(\"%d\",lastNon0Digit(12));return 0;}", "e": 11384, "s": 10389, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { // Helper Function to return the rightmost non-zero // digit public static void callMeFactorialLastDigit(int n, int[] result, int sumOf5) { int number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5); } public static int lastNon0Digit(int n) { int[] result = { 1 }; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0]; } public static void main(String[] args) { System.out.println(lastNon0Digit(7)); // 3040 System.out.println(lastNon0Digit(12)); // 479001600 }}//This code is contributed by KaaL-EL.", "e": 12855, "s": 11384, "text": null }, { "code": "# Helper Function to return the rightmost non-zero digitdef callMeFactorialLastDigit(n, result, sumOf5): number = n # assaigning to new variable. if number == 1: return # base case # To store the count of times 5 can # divide the number. while (number % 5 == 0): number = int(number / 5) # increase count of 5 sumOf5 += 1 # Divide the number by # 2 as much as possible while (sumOf5 != 0 and (number & 1) == 0): number >>= 1 # dividing the number by 2 sumOf5 -= 1 \"\"\"multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.\"\"\" result[0] = (result[0] * (number % 10)) % 10 # calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5) def lastNon0Digit(n): result = [ 1 ] # single element array. callMeFactorialLastDigit(n, result, 0) return result[0] print(lastNon0Digit(7)) # 3040print(lastNon0Digit(12)) # 479001600 # This code is contributed by suresh07.", "e": 13908, "s": 12855, "text": null }, { "code": "using System;class GFG { // Helper Function to return the rightmost non-zero // digit static void callMeFactorialLastDigit(int n, int[] result, int sumOf5) { int number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5); } static int lastNon0Digit(int n) { int[] result = { 1 }; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0]; } static void Main() { Console.WriteLine(lastNon0Digit(7)); // 3040 Console.WriteLine(lastNon0Digit(12)); // 479001600 }} // This code is contributed by mukesh07.", "e": 15291, "s": 13908, "text": null }, { "code": "<script> // Helper Function to return the rightmost non-zero // digit function callMeFactorialLastDigit(n, result, sumOf5) { let number = n; // assaigning to new variable. if (number == 1) return; // base case // To store the count of times 5 can // divide the number. while (number % 5 == 0) { number /= 5; // increase count of 5 sumOf5++; } // Divide the number by // 2 as much as possible while (sumOf5 != 0 && (number & 1) == 0) { number >>= 1; // dividing the number by 2 sumOf5--; } /*multiplied result and current number(after removing pairs) and do modular division to get the last digit of the resultant number.*/ result[0] = (result[0] * (number % 10)) % 10; // calling again for (currentNumber - 1) callMeFactorialLastDigit(n - 1, result, sumOf5); } function lastNon0Digit(n) { let result = [ 1 ]; // single element array. callMeFactorialLastDigit(n, result, 0); return result[0]; } document.write(lastNon0Digit(7) + \"</br>\"); // 3040 document.write(lastNon0Digit(12)); // 479001600 // This code is contributed by divyeshrabadiya07</script>", "e": 16595, "s": 15291, "text": null }, { "code": null, "e": 16599, "s": 16595, "text": "4\n6" }, { "code": null, "e": 16963, "s": 16599, "text": "we used single element array (int[] result = {1}) instead of integer as Java is Strictly Pass by Value!. It does not allow pass by reference for primitive data types. That’s why I used a single element array so that the recursive function can change the value of variable(result here). If we would have taken (int result = 1) then this variable remain unaffected." }, { "code": null, "e": 17395, "s": 16963, "text": "This article is contributed by Niteesh kumar & KaaL-EL. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17408, "s": 17395, "text": "nitin mittal" }, { "code": null, "e": 17414, "s": 17408, "text": "jit_t" }, { "code": null, "e": 17428, "s": 17414, "text": "divyesh072019" }, { "code": null, "e": 17435, "s": 17428, "text": "kaalel" }, { "code": null, "e": 17444, "s": 17435, "text": "sweetyty" }, { "code": null, "e": 17462, "s": 17444, "text": "divyeshrabadiya07" }, { "code": null, "e": 17471, "s": 17462, "text": "mukesh07" }, { "code": null, "e": 17486, "s": 17471, "text": "rameshtravel07" }, { "code": null, "e": 17495, "s": 17486, "text": "suresh07" }, { "code": null, "e": 17505, "s": 17495, "text": "allwink45" }, { "code": null, "e": 17515, "s": 17505, "text": "ridazouga" }, { "code": null, "e": 17525, "s": 17515, "text": "factorial" }, { "code": null, "e": 17544, "s": 17525, "text": "Modular Arithmetic" }, { "code": null, "e": 17557, "s": 17544, "text": "Mathematical" }, { "code": null, "e": 17567, "s": 17557, "text": "Recursion" }, { "code": null, "e": 17580, "s": 17567, "text": "Mathematical" }, { "code": null, "e": 17590, "s": 17580, "text": "Recursion" }, { "code": null, "e": 17609, "s": 17590, "text": "Modular Arithmetic" }, { "code": null, "e": 17619, "s": 17609, "text": "factorial" } ]
Modular Division
27 May, 2022 Given three positive numbers a, b and m. Compute a/b under modulo m. The task is basically to find a number c such that (b * c) % m = a % m.Examples: Input : a = 8, b = 4, m = 5 Output : 2 Input : a = 8, b = 3, m = 5 Output : 1 Note that (1*3)%5 is same as 8%5 Input : a = 11, b = 4, m = 5 Output : 4 Note that (4*4)%5 is same as 11%5 Following articles are prerequisites for this. Modular multiplicative inverse Extended Euclidean algorithms Can we always do modular division? The answer is “NO”. First of all, like ordinary arithmetic, division by 0 is not defined. For example, 4/0 is not allowed. In modular arithmetic, not only 4/0 is not allowed, but 4/12 under modulo 6 is also not allowed. The reason is, 12 is congruent to 0 when modulus is 6.When is modular division defined? Modular division is defined when modular inverse of the divisor exists. The inverse of an integer ‘x’ is another integer ‘y’ such that (x*y) % m = 1 where m is the modulus. When does inverse exist? As discussed here, inverse a number ‘a’ exists under modulo ‘m’ if ‘a’ and ‘m’ are co-prime, i.e., GCD of them is 1.How to find modular division? The task is to compute a/b under modulo m. 1) First check if inverse of b under modulo m exists or not. a) If inverse doesn't exists (GCD of b and m is not 1), print "Division not defined" b) Else return "(inverse * a) % m" C++ C Java Python3 C# Javascript PHP // C++ program to do modular division#include<iostream>using namespace std; // C++ function for extended Euclidean Algorithmint gcdExtended(int a, int b, int *x, int *y); // Function to find modulo inverse of b. It returns// -1 when inverse doesn'tint modInverse(int b, int m){ int x, y; // used in extended GCD algorithm int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x%m + m) % m;} // Function to compute a/b under modulo mvoid modDivide(int a, int b, int m){ a = a % m; int inv = modInverse(b, m); if (inv == -1) cout << "Division not defined"; else cout << "Result of division is " << (inv * a) % m;} // C function for extended Euclidean Algorithm (used to// find modular inverse.int gcdExtended(int a, int b, int *x, int *y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b%a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b/a) * x1; *y = x1; return gcd;} // Driver Programint main(){ int a = 8, b = 3, m = 5; modDivide(a, b, m); return 0;} //this code is contributed by khushboogoyal499 // C program to do modular division#include <stdio.h> // C function for extended Euclidean Algorithmint gcdExtended(int a, int b, int *x, int *y); // Function to find modulo inverse of b. It returns// -1 when inverse doesn'tint modInverse(int b, int m){ int x, y; // used in extended GCD algorithm int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x%m + m) % m;} // Function to compute a/b under modulo mvoid modDivide(int a, int b, int m){ a = a % m; int inv = modInverse(b, m); if (inv == -1) printf ("Division not defined"); else { int c = (inv * a) % m ; printf ("Result of division is %d", c) ; }} // C function for extended Euclidean Algorithm (used to// find modular inverse.int gcdExtended(int a, int b, int *x, int *y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b%a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b/a) * x1; *y = x1; return gcd;} // Driver Programint main(){ int a = 8, b = 3, m = 5; modDivide(a, b, m); return 0;} // java program to do modular division import java.io.*;import java.lang.Math; public class GFG { static int gcd(int a,int b){ if (b == 0){ return a; } return gcd(b, a % b); } // Function to find modulo inverse of b. It returns // -1 when inverse doesn't // modInverse works for prime m static int modInverse(int b,int m){ int g = gcd(b, m) ; if (g != 1) return -1; else { //If b and m are relatively prime, //then modulo inverse is b^(m-2) mode m return (int)Math.pow(b, m - 2) % m; } } // Function to compute a/b under modulo m static void modDivide(int a,int b,int m){ a = a % m; int inv = modInverse(b,m); if(inv == -1){ System.out.println("Division not defined"); } else{ System.out.println("Result of Division is " + ((inv*a) % m)); } } // Driver Program public static void main(String[] args) { int a = 8; int b = 3; int m = 5; modDivide(a, b, m); }} // The code is contributed by Gautam goel (gautamgoel962) # Python3 program to do modular divisionimport math # Function to find modulo inverse of b. It returns# -1 when inverse doesn't# modInverse works for prime mdef modInverse(b,m): g = math.gcd(b, m) if (g != 1): # print("Inverse doesn't exist") return -1 else: # If b and m are relatively prime, # then modulo inverse is b^(m-2) mode m return pow(b, m - 2, m) # Function to compute a/b under modulo mdef modDivide(a,b,m): a = a % m inv = modInverse(b,m) if(inv == -1): print("Division not defined") else: print("Result of Division is ",(inv*a) % m) # Driver Programa = 8b = 3m = 5modDivide(a, b, m) # This code is Contributed by HarendraSingh22 using System; // C# program to do modular divisionclass GFG { // Recursive Function to find // GCD of two numbers static int gcd(int a,int b){ if (b == 0){ return a; } return gcd(b, a % b); } // Function to find modulo inverse of b. It returns // -1 when inverse doesn't // modInverse works for prime m static int modInverse(int b,int m){ int g = gcd(b, m) ; if (g != 1){ return -1; } else { //If b and m are relatively prime, //then modulo inverse is b^(m-2) mode m return (int)Math.Pow(b, m - 2) % m; } } // Function to compute a/b under modulo m static void modDivide(int a,int b,int m){ a = a % m; int inv = modInverse(b,m); if(inv == -1){ Console.WriteLine("Division not defined"); } else{ Console.WriteLine("Result of Division is " + ((inv*a) % m)); } } // Driver Code static void Main() { int a = 8; int b = 3; int m = 5; modDivide(a, b, m); }} // The code is contributed by Gautam goel (gautamgoel962) <script>// JS program to do modular divisionfunction gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} // Function to find modulo inverse of b. It returns// -1 when inverse doesn't// modInverse works for prime mfunction modInverse(b,m){ g = gcd(b, m) ; if (g != 1) return -1; else { //If b and m are relatively prime, //then modulo inverse is b^(m-2) mode m return Math.pow(b, m - 2, m); }} // Function to compute a/b under modulo mfunction modDivide(a,b,m){ a = a % m; inv = modInverse(b,m); if(inv == -1) document.write("Division not defined"); else document.write("Result of Division is ",(inv*a) % m);} // Driver Programa = 8;b = 3;m = 5;modDivide(a, b, m); // This code is Contributed by phasing17</script> <?php// PHP program to do modular division // Function to find modulo inverse of b.// It returns -1 when inverse doesn'tfunction modInverse($b, $m){ $x = 0; $y = 0; // used in extended GCD algorithm $g = gcdExtended($b, $m, $x, $y); // Return -1 if b and m are not co-prime if ($g != 1) return -1; // m is added to handle negative x return ($x % $m + $m) % $m;} // Function to compute a/b under modulo mfunction modDivide($a, $b, $m){ $a = $a % $m; $inv = modInverse($b, $m); if ($inv == -1) echo "Division not defined"; else echo "Result of division is " . ($inv * $a) % $m;} // function for extended Euclidean Algorithm// (used to find modular inverse.function gcdExtended($a, $b, &$x, &$y){ // Base Case if ($a == 0) { $x = 0; $y = 1; return $b; } $x1 = 0; $y1 = 0; // To store results of recursive call $gcd = gcdExtended($b % $a, $a, $x1, $y1); // Update x and y using results of // recursive call $x = $y1 - (int)($b / $a) * $x1; $y = $x1; return $gcd;} // Driver Code$a = 8;$b = 3;$m = 5;modDivide($a, $b, $m); // This code is contributed by mits?> Output: Result of division is 1 Modular division is different from addition, subtraction and multiplication. One difference is division doesn’t always exist (as discussed above). Following is another difference. Below equations are valid (a * b) % m = ((a % m) * (b % m)) % m (a + b) % m = ((a % m) + (b % m)) % m // m is added to handle negative numbers (a - b + m) % m = ((a % m) - (b % m) + m) % m But, (a / b) % m may NOT be same as ((a % m)/(b % m)) % m For example, a = 10, b = 5, m = 5. (a / b) % m is 2, but ((a % m) / (b % m)) % m is not defined. References: http://www.doc.ic.ac.uk/~mrh/330tutor/ch03.htmlThis article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar dungeonmaster10110 khushboogoyal499 mayunitp phasing17 gautamgoel962 Modular Arithmetic Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 54, "s": 26, "text": "\n27 May, 2022" }, { "code": null, "e": 205, "s": 54, "text": "Given three positive numbers a, b and m. Compute a/b under modulo m. The task is basically to find a number c such that (b * c) % m = a % m.Examples: " }, { "code": null, "e": 398, "s": 205, "text": "Input : a = 8, b = 4, m = 5\nOutput : 2\n\nInput : a = 8, b = 3, m = 5\nOutput : 1\nNote that (1*3)%5 is same as 8%5\n\nInput : a = 11, b = 4, m = 5\nOutput : 4\nNote that (4*4)%5 is same as 11%5" }, { "code": null, "e": 1194, "s": 398, "text": "Following articles are prerequisites for this. Modular multiplicative inverse Extended Euclidean algorithms Can we always do modular division? The answer is “NO”. First of all, like ordinary arithmetic, division by 0 is not defined. For example, 4/0 is not allowed. In modular arithmetic, not only 4/0 is not allowed, but 4/12 under modulo 6 is also not allowed. The reason is, 12 is congruent to 0 when modulus is 6.When is modular division defined? Modular division is defined when modular inverse of the divisor exists. The inverse of an integer ‘x’ is another integer ‘y’ such that (x*y) % m = 1 where m is the modulus. When does inverse exist? As discussed here, inverse a number ‘a’ exists under modulo ‘m’ if ‘a’ and ‘m’ are co-prime, i.e., GCD of them is 1.How to find modular division? " }, { "code": null, "e": 1440, "s": 1194, "text": "The task is to compute a/b under modulo m.\n1) First check if inverse of b under modulo m exists or not. \n a) If inverse doesn't exists (GCD of b and m is not 1), \n print \"Division not defined\"\n b) Else return \"(inverse * a) % m\" " }, { "code": null, "e": 1446, "s": 1442, "text": "C++" }, { "code": null, "e": 1448, "s": 1446, "text": "C" }, { "code": null, "e": 1453, "s": 1448, "text": "Java" }, { "code": null, "e": 1461, "s": 1453, "text": "Python3" }, { "code": null, "e": 1464, "s": 1461, "text": "C#" }, { "code": null, "e": 1475, "s": 1464, "text": "Javascript" }, { "code": null, "e": 1479, "s": 1475, "text": "PHP" }, { "code": "// C++ program to do modular division#include<iostream>using namespace std; // C++ function for extended Euclidean Algorithmint gcdExtended(int a, int b, int *x, int *y); // Function to find modulo inverse of b. It returns// -1 when inverse doesn'tint modInverse(int b, int m){ int x, y; // used in extended GCD algorithm int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x%m + m) % m;} // Function to compute a/b under modulo mvoid modDivide(int a, int b, int m){ a = a % m; int inv = modInverse(b, m); if (inv == -1) cout << \"Division not defined\"; else cout << \"Result of division is \" << (inv * a) % m;} // C function for extended Euclidean Algorithm (used to// find modular inverse.int gcdExtended(int a, int b, int *x, int *y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b%a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b/a) * x1; *y = x1; return gcd;} // Driver Programint main(){ int a = 8, b = 3, m = 5; modDivide(a, b, m); return 0;} //this code is contributed by khushboogoyal499", "e": 2792, "s": 1479, "text": null }, { "code": "// C program to do modular division#include <stdio.h> // C function for extended Euclidean Algorithmint gcdExtended(int a, int b, int *x, int *y); // Function to find modulo inverse of b. It returns// -1 when inverse doesn'tint modInverse(int b, int m){ int x, y; // used in extended GCD algorithm int g = gcdExtended(b, m, &x, &y); // Return -1 if b and m are not co-prime if (g != 1) return -1; // m is added to handle negative x return (x%m + m) % m;} // Function to compute a/b under modulo mvoid modDivide(int a, int b, int m){ a = a % m; int inv = modInverse(b, m); if (inv == -1) printf (\"Division not defined\"); else { int c = (inv * a) % m ; printf (\"Result of division is %d\", c) ; }} // C function for extended Euclidean Algorithm (used to// find modular inverse.int gcdExtended(int a, int b, int *x, int *y){ // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b%a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b/a) * x1; *y = x1; return gcd;} // Driver Programint main(){ int a = 8, b = 3, m = 5; modDivide(a, b, m); return 0;}", "e": 4062, "s": 2792, "text": null }, { "code": "// java program to do modular division import java.io.*;import java.lang.Math; public class GFG { static int gcd(int a,int b){ if (b == 0){ return a; } return gcd(b, a % b); } // Function to find modulo inverse of b. It returns // -1 when inverse doesn't // modInverse works for prime m static int modInverse(int b,int m){ int g = gcd(b, m) ; if (g != 1) return -1; else { //If b and m are relatively prime, //then modulo inverse is b^(m-2) mode m return (int)Math.pow(b, m - 2) % m; } } // Function to compute a/b under modulo m static void modDivide(int a,int b,int m){ a = a % m; int inv = modInverse(b,m); if(inv == -1){ System.out.println(\"Division not defined\"); } else{ System.out.println(\"Result of Division is \" + ((inv*a) % m)); } } // Driver Program public static void main(String[] args) { int a = 8; int b = 3; int m = 5; modDivide(a, b, m); }} // The code is contributed by Gautam goel (gautamgoel962)", "e": 5248, "s": 4062, "text": null }, { "code": "# Python3 program to do modular divisionimport math # Function to find modulo inverse of b. It returns# -1 when inverse doesn't# modInverse works for prime mdef modInverse(b,m): g = math.gcd(b, m) if (g != 1): # print(\"Inverse doesn't exist\") return -1 else: # If b and m are relatively prime, # then modulo inverse is b^(m-2) mode m return pow(b, m - 2, m) # Function to compute a/b under modulo mdef modDivide(a,b,m): a = a % m inv = modInverse(b,m) if(inv == -1): print(\"Division not defined\") else: print(\"Result of Division is \",(inv*a) % m) # Driver Programa = 8b = 3m = 5modDivide(a, b, m) # This code is Contributed by HarendraSingh22", "e": 5962, "s": 5248, "text": null }, { "code": "using System; // C# program to do modular divisionclass GFG { // Recursive Function to find // GCD of two numbers static int gcd(int a,int b){ if (b == 0){ return a; } return gcd(b, a % b); } // Function to find modulo inverse of b. It returns // -1 when inverse doesn't // modInverse works for prime m static int modInverse(int b,int m){ int g = gcd(b, m) ; if (g != 1){ return -1; } else { //If b and m are relatively prime, //then modulo inverse is b^(m-2) mode m return (int)Math.Pow(b, m - 2) % m; } } // Function to compute a/b under modulo m static void modDivide(int a,int b,int m){ a = a % m; int inv = modInverse(b,m); if(inv == -1){ Console.WriteLine(\"Division not defined\"); } else{ Console.WriteLine(\"Result of Division is \" + ((inv*a) % m)); } } // Driver Code static void Main() { int a = 8; int b = 3; int m = 5; modDivide(a, b, m); }} // The code is contributed by Gautam goel (gautamgoel962)", "e": 7003, "s": 5962, "text": null }, { "code": "<script>// JS program to do modular divisionfunction gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} // Function to find modulo inverse of b. It returns// -1 when inverse doesn't// modInverse works for prime mfunction modInverse(b,m){ g = gcd(b, m) ; if (g != 1) return -1; else { //If b and m are relatively prime, //then modulo inverse is b^(m-2) mode m return Math.pow(b, m - 2, m); }} // Function to compute a/b under modulo mfunction modDivide(a,b,m){ a = a % m; inv = modInverse(b,m); if(inv == -1) document.write(\"Division not defined\"); else document.write(\"Result of Division is \",(inv*a) % m);} // Driver Programa = 8;b = 3;m = 5;modDivide(a, b, m); // This code is Contributed by phasing17</script>", "e": 7803, "s": 7003, "text": null }, { "code": "<?php// PHP program to do modular division // Function to find modulo inverse of b.// It returns -1 when inverse doesn'tfunction modInverse($b, $m){ $x = 0; $y = 0; // used in extended GCD algorithm $g = gcdExtended($b, $m, $x, $y); // Return -1 if b and m are not co-prime if ($g != 1) return -1; // m is added to handle negative x return ($x % $m + $m) % $m;} // Function to compute a/b under modulo mfunction modDivide($a, $b, $m){ $a = $a % $m; $inv = modInverse($b, $m); if ($inv == -1) echo \"Division not defined\"; else echo \"Result of division is \" . ($inv * $a) % $m;} // function for extended Euclidean Algorithm// (used to find modular inverse.function gcdExtended($a, $b, &$x, &$y){ // Base Case if ($a == 0) { $x = 0; $y = 1; return $b; } $x1 = 0; $y1 = 0; // To store results of recursive call $gcd = gcdExtended($b % $a, $a, $x1, $y1); // Update x and y using results of // recursive call $x = $y1 - (int)($b / $a) * $x1; $y = $x1; return $gcd;} // Driver Code$a = 8;$b = 3;$m = 5;modDivide($a, $b, $m); // This code is contributed by mits?>", "e": 8996, "s": 7803, "text": null }, { "code": null, "e": 9005, "s": 8996, "text": "Output: " }, { "code": null, "e": 9029, "s": 9005, "text": "Result of division is 1" }, { "code": null, "e": 9211, "s": 9029, "text": "Modular division is different from addition, subtraction and multiplication. One difference is division doesn’t always exist (as discussed above). Following is another difference. " }, { "code": null, "e": 9591, "s": 9211, "text": "Below equations are valid\n(a * b) % m = ((a % m) * (b % m)) % m\n(a + b) % m = ((a % m) + (b % m)) % m\n\n// m is added to handle negative numbers\n(a - b + m) % m = ((a % m) - (b % m) + m) % m \n\nBut, \n(a / b) % m may NOT be same as ((a % m)/(b % m)) % m\n\nFor example, a = 10, b = 5, m = 5. \n (a / b) % m is 2, but ((a % m) / (b % m)) % m \n is not defined." }, { "code": null, "e": 9821, "s": 9591, "text": "References: http://www.doc.ic.ac.uk/~mrh/330tutor/ch03.htmlThis article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 9834, "s": 9821, "text": "Mithun Kumar" }, { "code": null, "e": 9853, "s": 9834, "text": "dungeonmaster10110" }, { "code": null, "e": 9870, "s": 9853, "text": "khushboogoyal499" }, { "code": null, "e": 9879, "s": 9870, "text": "mayunitp" }, { "code": null, "e": 9889, "s": 9879, "text": "phasing17" }, { "code": null, "e": 9903, "s": 9889, "text": "gautamgoel962" }, { "code": null, "e": 9922, "s": 9903, "text": "Modular Arithmetic" }, { "code": null, "e": 9935, "s": 9922, "text": "Mathematical" }, { "code": null, "e": 9948, "s": 9935, "text": "Mathematical" }, { "code": null, "e": 9967, "s": 9948, "text": "Modular Arithmetic" }, { "code": null, "e": 10065, "s": 9967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10095, "s": 10065, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 10138, "s": 10095, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 10198, "s": 10138, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 10213, "s": 10198, "text": "C++ Data Types" }, { "code": null, "e": 10237, "s": 10213, "text": "Merge two sorted arrays" }, { "code": null, "e": 10256, "s": 10237, "text": "Coin Change | DP-7" }, { "code": null, "e": 10277, "s": 10256, "text": "Operators in C / C++" }, { "code": null, "e": 10291, "s": 10277, "text": "Prime Numbers" }, { "code": null, "e": 10333, "s": 10291, "text": "Program to find GCD or HCF of two numbers" } ]
HTML5 - Web messaging
Web messaging is the ability to send realtime messages from the server to the client browser. It overrides the cross domain communication problem in different domains, protocols or ports For example, you want to send the data from your page to ad container which is placed at iframe or voice-versa, in this scenario, Browser throws a security exception. With web messaging we can pass the data across as a message event. Message events fires Cross-document messaging, channel messaging, server-sent events and web sockets.it has described by Message Event interface. data Contains string data origin Contains Domain name and port lastEventId Contains unique identifier for the current message event. source Contains to A reference to the originating document’s window ports Contains the data which is sent by any message port Before send cross document message, we need to create a new web browsing context either by creating new iframe or new window. We can send the data using with postMessage() and it has two arguments. They are as − message − The message to send targetOrigin − Origin name Sending message from iframe to button var iframe = document.querySelector('iframe'); var button = document.querySelector('button'); var clickHandler = function() { iframe.contentWindow.postMessage('The message to send.', 'https://www.tutorialspoint.com); } button.addEventListener('click',clickHandler,false); Receiving a cross-document message in the receiving document var messageEventHandler = function(event){ // check that the origin is one we want. if(event.origin == 'https://www.tutorialspoint.com') { alert(event.data); } } window.addEventListener('message', messageEventHandler,false); Two-way communication between the browsing contexts is called channel messaging. It is useful for communication across multiple origins. While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context. postMessage() − Post the message throw channel postMessage() − Post the message throw channel start() − It sends the data start() − It sends the data close() − It close the ports close() − It close the ports In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM. var loadHandler = function() { var mc, portMessageHandler; mc = new MessageChannel(); window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2]); portMessageHandler = function(portMsgEvent) { alert( portMsgEvent.data ); } mc.port1.addEventListener('message', portMessageHandler, false); mc.port1.start(); } window.addEventListener('DOMContentLoaded', loadHandler, false); Above code, it is taking the data from port 2, now it will pass the data to second iframe var loadHandler = function() { var iframes, messageHandler; iframes = window.frames; messageHandler = function(messageEvent) { if( messageEvent.ports.length > 0 ) { // transfer the port to iframe[1] iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports); } } window.addEventListener('message',messageHandler,false); } window.addEventListener('DOMContentLoaded',loadHandler,false); Now second document handles the data by using the portMsgHandler function. var loadHandler() { // Define our message handler function var messageHandler = function(messageEvent) { // Our form submission handler var formHandler = function() { var msg = 'add <[email protected]> to game circle.';
[ { "code": null, "e": 2929, "s": 2742, "text": "Web messaging is the ability to send realtime messages from the server to the client browser. It overrides the cross domain communication problem in different domains, protocols or ports" }, { "code": null, "e": 3163, "s": 2929, "text": "For example, you want to send the data from your page to ad container which is placed at iframe or voice-versa, in this scenario, Browser throws a security exception. With web messaging we can pass the data across as a message event." }, { "code": null, "e": 3309, "s": 3163, "text": "Message events fires Cross-document messaging, channel messaging, server-sent events and web sockets.it has described by Message Event interface." }, { "code": null, "e": 3314, "s": 3309, "text": "data" }, { "code": null, "e": 3335, "s": 3314, "text": "Contains string data" }, { "code": null, "e": 3342, "s": 3335, "text": "origin" }, { "code": null, "e": 3372, "s": 3342, "text": "Contains Domain name and port" }, { "code": null, "e": 3384, "s": 3372, "text": "lastEventId" }, { "code": null, "e": 3442, "s": 3384, "text": "Contains unique identifier for the current message event." }, { "code": null, "e": 3449, "s": 3442, "text": "source" }, { "code": null, "e": 3510, "s": 3449, "text": "Contains to A reference to the originating document’s window" }, { "code": null, "e": 3516, "s": 3510, "text": "ports" }, { "code": null, "e": 3568, "s": 3516, "text": "Contains the data which is sent by any message port" }, { "code": null, "e": 3780, "s": 3568, "text": "Before send cross document message, we need to create a new web browsing context either by creating new iframe or new window. We can send the data using with postMessage() and it has two arguments. They are as −" }, { "code": null, "e": 3810, "s": 3780, "text": "message − The message to send" }, { "code": null, "e": 3837, "s": 3810, "text": "targetOrigin − Origin name" }, { "code": null, "e": 3875, "s": 3837, "text": "Sending message from iframe to button" }, { "code": null, "e": 4157, "s": 3875, "text": "var iframe = document.querySelector('iframe');\nvar button = document.querySelector('button');\n\nvar clickHandler = function() {\n iframe.contentWindow.postMessage('The message to send.',\n 'https://www.tutorialspoint.com);\n}\nbutton.addEventListener('click',clickHandler,false);" }, { "code": null, "e": 4218, "s": 4157, "text": "Receiving a cross-document message in the receiving document" }, { "code": null, "e": 4462, "s": 4218, "text": "var messageEventHandler = function(event){\n \n // check that the origin is one we want.\n if(event.origin == 'https://www.tutorialspoint.com') {\n alert(event.data);\n }\n}\nwindow.addEventListener('message', messageEventHandler,false);" }, { "code": null, "e": 4599, "s": 4462, "text": "Two-way communication between the browsing contexts is called channel messaging. It is useful for communication across multiple origins." }, { "code": null, "e": 4725, "s": 4599, "text": "While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context." }, { "code": null, "e": 4772, "s": 4725, "text": "postMessage() − Post the message throw channel" }, { "code": null, "e": 4819, "s": 4772, "text": "postMessage() − Post the message throw channel" }, { "code": null, "e": 4847, "s": 4819, "text": "start() − It sends the data" }, { "code": null, "e": 4875, "s": 4847, "text": "start() − It sends the data" }, { "code": null, "e": 4904, "s": 4875, "text": "close() − It close the ports" }, { "code": null, "e": 4933, "s": 4904, "text": "close() − It close the ports" }, { "code": null, "e": 5081, "s": 4933, "text": "In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM." }, { "code": null, "e": 5509, "s": 5081, "text": "var loadHandler = function() {\n var mc, portMessageHandler;\n mc = new MessageChannel();\n window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2]);\n \n portMessageHandler = function(portMsgEvent) {\n alert( portMsgEvent.data );\n }\n \n mc.port1.addEventListener('message', portMessageHandler, false);\n mc.port1.start();\n}\nwindow.addEventListener('DOMContentLoaded', loadHandler, false);" }, { "code": null, "e": 5599, "s": 5509, "text": "Above code, it is taking the data from port 2, now it will pass the data to second iframe" }, { "code": null, "e": 6066, "s": 5599, "text": "var loadHandler = function() {\n var iframes, messageHandler;\n iframes = window.frames;\n \n messageHandler = function(messageEvent) {\n \n if( messageEvent.ports.length > 0 ) {\n \n // transfer the port to iframe[1]\n iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports);\n }\n }\n window.addEventListener('message',messageHandler,false);\n}\nwindow.addEventListener('DOMContentLoaded',loadHandler,false);" }, { "code": null, "e": 6141, "s": 6066, "text": "Now second document handles the data by using the portMsgHandler function." } ]
Pre-Processing in Natural Language Machine Learning | by Kendall Fortney | Towards Data Science
It is easy to forget how much data is stored in the conversations we have every day. With the evolution of the digital landscape, tapping into text, or Natural Language Processing (NLP), is a growing field in artificial intelligence and machine learning. This article covers the common pre-processing concepts applied to NLP problems. Text can come in a variety of forms from a list of individual words, to sentences to multiple paragraphs with special characters (like tweets for example). Like any data science problem, understand the questions that are being asked will inform what steps may be employed to transform words into numerical features that work with machine learning algorithms. When I was a kid sci-fi almost always had a computer that you could bark orders and have them understood and sometime, but not always, executed. At the time the technology seemed far away in the future but today I carry a phone in my pocket that is smaller and more powerful than any of those imagined. The history of speech-to-text is a complicated and long but was the seed for much of NPL. Early efforts required large amounts of manually coded vocabulary and linguistic rules. The first automatic translations from English to Russian in 1954 at Georgetown were limited to a handful of sentences. By 1964 the first chatbot ELIZA was created at MIT. Built on pattern matching and substitution it mimicked the therapy process by asking open-ended questions. While it seemed to replicate awareness, it had no true contextualization of the conversation. Even with these limited capabilities many were surprised by how human the interactions felt. Much of the growth in the field really started in the 1980's with the introduction of machine learning algorithms. Researchers moved from the more rigid Transformational Grammar models into looser probabilistic relationships described in Cache Language Models which allowed more rapid scaling and handled unfamiliar inputs with greater ease. Through the 90's the exponential increase of computing power helped forge advancement but it wasn’t until 2006 when IBM’s Watson went on Jeopardy that the progress of computer intelligence was visible to the general public. For me it was the introduction of Siri on the iPhone in 2011 that made me realize the potential. The current NLP landscape could easily be its own article. Unprecedented investment from private companies and a general open source attitude has expanded something that was largely exclusive to much larger audience and application. One fascinating example is in the field of translations where Google is working on translating any language on the fly (even if some of the bugs in the user experience needs to be worked out). betanews.com None of the magic described above happens without a lot of work on the back end. Transforming text into something an algorithm can digest it a complicated process. There are four different parts: Cleaning consist of getting rid of the less useful parts of text through stopword removal, dealing with capitalization and characters and other details. Annotation consists of the application of a scheme to texts. Annotations may include structural markup and part-of-speech tagging. Normalization consists of the translation (mapping) of terms in the scheme or linguistic reductions through Stemming, Lemmazation and other forms of standardization. Analysis consists of statistically probing, manipulating and generalizing from the dataset for feature analysis. There are a variety of pre-processing methods. The list below is far from exclusive but it does give an idea of where to start. It is important to realize, like with all data problems, converting anything into a format for machine learning reduces it to a generalized state which means losing some of the fidelity of the data along the way. The true art is understand the pros and cons to each to carefully chose the right methods. Text often has a variety of capitalization reflecting the beginning of sentences, proper nouns emphasis. The most common approach is to reduce everything to lower case for simplicity but it is important to remember that some words, like “US” to “us”, can change meanings when reduced to the lower case. A majority of the words in a given text are connecting parts of a sentence rather than showing subjects, objects or intent. Word like “the” or “and” cab be removed by comparing text to a list of stopword. IN:['He', 'did', 'not', 'try', 'to', 'navigate', 'after', 'the', 'first', 'bold', 'flight', ',', 'for', 'the', 'reaction', 'had', 'taken', 'something', 'out', 'of', 'his', 'soul', '.']OUT:['try', 'navigate', 'first', 'bold', 'flight', ',', 'reaction', 'taken', 'something', 'soul', '.'] In the example above it reduced the list of 23 words to 11, but it is important to note that the word “not” was dropped which depending on what I am working on could be a large problem. One might created their own stopword dictionary manually or utilize prebuilt libraries depending on the sensitivity required. Tokenization describes splitting paragraphs into sentences, or sentences into individual words. For the former Sentence Boundary Disambiguation (SBD) can be applied to create a list of individual sentences. This relies on a pre-trained, language specific algorithms like the Punkt Models from NLTK. Sentences can be split into individual words and punctuation through a similar process. Most commonly this split across white spaces, for example: IN:"He did not try to navigate after the first bold flight, for the reaction had taken something out of his soul."OUT:['He', 'did', 'not', 'try', 'to', 'navigate', 'after', 'the', 'first', 'bold', 'flight', ',', 'for', 'the', 'reaction', 'had', 'taken', 'something', 'out', 'of', 'his', 'soul', '.'] There are occasions that this can cause problems when a word is abbreviated, truncated or is possessive. Proper nouns may also suffer in the case of names that use punctuation (like O’Neil). Understand parts of speech can make difference in determining the meaning of a sentence. Part of Speech (POS) often requires look at the proceeding and following words and combined with either a rule-based or stochastic method. It can than be combined with other processes for more feature engineering. IN:['And', 'from', 'their', 'high', 'summits', ',', 'one', 'by', 'one', ',', 'drop', 'everlasting', 'dews', '.']OUT:[('And', 'CC'), ('from', 'IN'), ('their', 'PRP$'), ('high', 'JJ'), ('summits', 'NNS'), (',', ','), ('one', 'CD'), ('by', 'IN'), ('one', 'CD'), (',', ','), ('drop', 'NN'), ('everlasting', 'VBG'), ('dews', 'NNS'), ('.', '.')]Definitions of Parts of Speech('their', 'PRP$') PRP$: pronoun, possessive her his mine my our ours their thy your Much of natural language machine learning is about sentiment of the text. Stemming is a process where words are reduced to a root by removing inflection through dropping unnecessary characters, usually a suffix. There are several stemming models, including Porter and Snowball. The results can be used to identify relationships and commonalities across large datasets. IN:["It never once occurred to me that the fumbling might be a mere mistake."]OUT: ['it', 'never', 'onc', 'occur', 'to', 'me', 'that', 'the', 'fumbl', 'might', 'be', 'a', 'mere', 'mistake.'], It is easy to see where reductions may produce a “root” word that isn’t an actual word. This doesn’t necessarily adversely affect its efficiency, but there is a danger of “overstemming” were words like “universe” and “university” are reduced to the same root of “univers”. Lemmazation is an alternative approach from stemming to removing inflection. By determining the part of speech and utilizing WordNet’s lexical database of English, lemmazation can get better results. The stemmed form of leafs is: leafThe stemmed form of leaves is: leavThe lemmatized form of leafs is: leafThe lemmatized form of leaves is: leaf Lemmazation is a more intensive and therefor slower process, but more accurate. Stemming may be more useful in queries for databases whereas lemmazation may work much better when trying to determine text sentiment. Perhaps one of the more basic tools for feature engineering, adding word count, sentence count, punctuation counts and Industry specific word counts can greatly help in prediction or classification. There are multiple statistical approaches whose relevance are heavily dependent on context. Word embedding is the modern way of representing words as vectors. The aim of word embedding is to redefine the high dimensional word features into low dimensional feature vectors. In other words it represents words at an X and Y vector coordinate where related words, based on a corpus of relationships, are placed closer together. Word2Vec and GloVe are the most common models to convert text to vectors. While this is far from a comprehensive list, preparing text is a complicated art which requires choosing the optimal tools given both the data and the question you are asking. Many pre-built libraries and services are there to help but some may require manually mapping terms and words. Once a dataset is ready supervised and unsupervised machine learning techniques can be applied. From my initial experiments, which will be it’s own article, there is a sharp difference in applying preprocessing techniques on a single string compared to large dataframes. Tuning the steps for optimal efficiency will be key to remain flexible in the face of scaling. Clap if you liked the article, follow if you are interested to see more on Natural Language Processing!
[ { "code": null, "e": 507, "s": 172, "text": "It is easy to forget how much data is stored in the conversations we have every day. With the evolution of the digital landscape, tapping into text, or Natural Language Processing (NLP), is a growing field in artificial intelligence and machine learning. This article covers the common pre-processing concepts applied to NLP problems." }, { "code": null, "e": 866, "s": 507, "text": "Text can come in a variety of forms from a list of individual words, to sentences to multiple paragraphs with special characters (like tweets for example). Like any data science problem, understand the questions that are being asked will inform what steps may be employed to transform words into numerical features that work with machine learning algorithms." }, { "code": null, "e": 1259, "s": 866, "text": "When I was a kid sci-fi almost always had a computer that you could bark orders and have them understood and sometime, but not always, executed. At the time the technology seemed far away in the future but today I carry a phone in my pocket that is smaller and more powerful than any of those imagined. The history of speech-to-text is a complicated and long but was the seed for much of NPL." }, { "code": null, "e": 1466, "s": 1259, "text": "Early efforts required large amounts of manually coded vocabulary and linguistic rules. The first automatic translations from English to Russian in 1954 at Georgetown were limited to a handful of sentences." }, { "code": null, "e": 1812, "s": 1466, "text": "By 1964 the first chatbot ELIZA was created at MIT. Built on pattern matching and substitution it mimicked the therapy process by asking open-ended questions. While it seemed to replicate awareness, it had no true contextualization of the conversation. Even with these limited capabilities many were surprised by how human the interactions felt." }, { "code": null, "e": 2154, "s": 1812, "text": "Much of the growth in the field really started in the 1980's with the introduction of machine learning algorithms. Researchers moved from the more rigid Transformational Grammar models into looser probabilistic relationships described in Cache Language Models which allowed more rapid scaling and handled unfamiliar inputs with greater ease." }, { "code": null, "e": 2475, "s": 2154, "text": "Through the 90's the exponential increase of computing power helped forge advancement but it wasn’t until 2006 when IBM’s Watson went on Jeopardy that the progress of computer intelligence was visible to the general public. For me it was the introduction of Siri on the iPhone in 2011 that made me realize the potential." }, { "code": null, "e": 2901, "s": 2475, "text": "The current NLP landscape could easily be its own article. Unprecedented investment from private companies and a general open source attitude has expanded something that was largely exclusive to much larger audience and application. One fascinating example is in the field of translations where Google is working on translating any language on the fly (even if some of the bugs in the user experience needs to be worked out)." }, { "code": null, "e": 2914, "s": 2901, "text": "betanews.com" }, { "code": null, "e": 3110, "s": 2914, "text": "None of the magic described above happens without a lot of work on the back end. Transforming text into something an algorithm can digest it a complicated process. There are four different parts:" }, { "code": null, "e": 3263, "s": 3110, "text": "Cleaning consist of getting rid of the less useful parts of text through stopword removal, dealing with capitalization and characters and other details." }, { "code": null, "e": 3394, "s": 3263, "text": "Annotation consists of the application of a scheme to texts. Annotations may include structural markup and part-of-speech tagging." }, { "code": null, "e": 3560, "s": 3394, "text": "Normalization consists of the translation (mapping) of terms in the scheme or linguistic reductions through Stemming, Lemmazation and other forms of standardization." }, { "code": null, "e": 3673, "s": 3560, "text": "Analysis consists of statistically probing, manipulating and generalizing from the dataset for feature analysis." }, { "code": null, "e": 4105, "s": 3673, "text": "There are a variety of pre-processing methods. The list below is far from exclusive but it does give an idea of where to start. It is important to realize, like with all data problems, converting anything into a format for machine learning reduces it to a generalized state which means losing some of the fidelity of the data along the way. The true art is understand the pros and cons to each to carefully chose the right methods." }, { "code": null, "e": 4408, "s": 4105, "text": "Text often has a variety of capitalization reflecting the beginning of sentences, proper nouns emphasis. The most common approach is to reduce everything to lower case for simplicity but it is important to remember that some words, like “US” to “us”, can change meanings when reduced to the lower case." }, { "code": null, "e": 4613, "s": 4408, "text": "A majority of the words in a given text are connecting parts of a sentence rather than showing subjects, objects or intent. Word like “the” or “and” cab be removed by comparing text to a list of stopword." }, { "code": null, "e": 4900, "s": 4613, "text": "IN:['He', 'did', 'not', 'try', 'to', 'navigate', 'after', 'the', 'first', 'bold', 'flight', ',', 'for', 'the', 'reaction', 'had', 'taken', 'something', 'out', 'of', 'his', 'soul', '.']OUT:['try', 'navigate', 'first', 'bold', 'flight', ',', 'reaction', 'taken', 'something', 'soul', '.']" }, { "code": null, "e": 5212, "s": 4900, "text": "In the example above it reduced the list of 23 words to 11, but it is important to note that the word “not” was dropped which depending on what I am working on could be a large problem. One might created their own stopword dictionary manually or utilize prebuilt libraries depending on the sensitivity required." }, { "code": null, "e": 5511, "s": 5212, "text": "Tokenization describes splitting paragraphs into sentences, or sentences into individual words. For the former Sentence Boundary Disambiguation (SBD) can be applied to create a list of individual sentences. This relies on a pre-trained, language specific algorithms like the Punkt Models from NLTK." }, { "code": null, "e": 5658, "s": 5511, "text": "Sentences can be split into individual words and punctuation through a similar process. Most commonly this split across white spaces, for example:" }, { "code": null, "e": 5958, "s": 5658, "text": "IN:\"He did not try to navigate after the first bold flight, for the reaction had taken something out of his soul.\"OUT:['He', 'did', 'not', 'try', 'to', 'navigate', 'after', 'the', 'first', 'bold', 'flight', ',', 'for', 'the', 'reaction', 'had', 'taken', 'something', 'out', 'of', 'his', 'soul', '.']" }, { "code": null, "e": 6149, "s": 5958, "text": "There are occasions that this can cause problems when a word is abbreviated, truncated or is possessive. Proper nouns may also suffer in the case of names that use punctuation (like O’Neil)." }, { "code": null, "e": 6452, "s": 6149, "text": "Understand parts of speech can make difference in determining the meaning of a sentence. Part of Speech (POS) often requires look at the proceeding and following words and combined with either a rule-based or stochastic method. It can than be combined with other processes for more feature engineering." }, { "code": null, "e": 6908, "s": 6452, "text": "IN:['And', 'from', 'their', 'high', 'summits', ',', 'one', 'by', 'one', ',', 'drop', 'everlasting', 'dews', '.']OUT:[('And', 'CC'), ('from', 'IN'), ('their', 'PRP$'), ('high', 'JJ'), ('summits', 'NNS'), (',', ','), ('one', 'CD'), ('by', 'IN'), ('one', 'CD'), (',', ','), ('drop', 'NN'), ('everlasting', 'VBG'), ('dews', 'NNS'), ('.', '.')]Definitions of Parts of Speech('their', 'PRP$') PRP$: pronoun, possessive her his mine my our ours their thy your" }, { "code": null, "e": 7277, "s": 6908, "text": "Much of natural language machine learning is about sentiment of the text. Stemming is a process where words are reduced to a root by removing inflection through dropping unnecessary characters, usually a suffix. There are several stemming models, including Porter and Snowball. The results can be used to identify relationships and commonalities across large datasets." }, { "code": null, "e": 7477, "s": 7277, "text": "IN:[\"It never once occurred to me that the fumbling might be a mere mistake.\"]OUT: ['it', 'never', 'onc', 'occur', 'to', 'me', 'that', 'the', 'fumbl', 'might', 'be', 'a', 'mere', 'mistake.']," }, { "code": null, "e": 7750, "s": 7477, "text": "It is easy to see where reductions may produce a “root” word that isn’t an actual word. This doesn’t necessarily adversely affect its efficiency, but there is a danger of “overstemming” were words like “universe” and “university” are reduced to the same root of “univers”." }, { "code": null, "e": 7950, "s": 7750, "text": "Lemmazation is an alternative approach from stemming to removing inflection. By determining the part of speech and utilizing WordNet’s lexical database of English, lemmazation can get better results." }, { "code": null, "e": 8095, "s": 7950, "text": "The stemmed form of leafs is: leafThe stemmed form of leaves is: leavThe lemmatized form of leafs is: leafThe lemmatized form of leaves is: leaf" }, { "code": null, "e": 8310, "s": 8095, "text": "Lemmazation is a more intensive and therefor slower process, but more accurate. Stemming may be more useful in queries for databases whereas lemmazation may work much better when trying to determine text sentiment." }, { "code": null, "e": 8601, "s": 8310, "text": "Perhaps one of the more basic tools for feature engineering, adding word count, sentence count, punctuation counts and Industry specific word counts can greatly help in prediction or classification. There are multiple statistical approaches whose relevance are heavily dependent on context." }, { "code": null, "e": 9008, "s": 8601, "text": "Word embedding is the modern way of representing words as vectors. The aim of word embedding is to redefine the high dimensional word features into low dimensional feature vectors. In other words it represents words at an X and Y vector coordinate where related words, based on a corpus of relationships, are placed closer together. Word2Vec and GloVe are the most common models to convert text to vectors." }, { "code": null, "e": 9295, "s": 9008, "text": "While this is far from a comprehensive list, preparing text is a complicated art which requires choosing the optimal tools given both the data and the question you are asking. Many pre-built libraries and services are there to help but some may require manually mapping terms and words." }, { "code": null, "e": 9661, "s": 9295, "text": "Once a dataset is ready supervised and unsupervised machine learning techniques can be applied. From my initial experiments, which will be it’s own article, there is a sharp difference in applying preprocessing techniques on a single string compared to large dataframes. Tuning the steps for optimal efficiency will be key to remain flexible in the face of scaling." } ]
Conditionally assign a value without using conditional and arithmetic operators - GeeksforGeeks
28 Jan, 2022 Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked: If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'. Note: – You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /). Examples : Input : a = 5 , b = 10, x = 1 Output : y = 10 Input : a = 5, b = 10 , x = 0 Output : y = 5 Asked in: Google Interview Solution 1: An Idea is to simply store both ‘a’ and ‘b’ in an array at 0th and 1st index respectively. Then store value to ‘y’ by taking ‘x’ as an index. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C/C++ program to assign value to y according// to value of x #include <iostream>using namespace std; // Function to assign value to y according// to value of xint assignValue(int a, int b, int x){ int y; int arr[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y;} // Driver codeint main(){ int a = 5; int b = 10; int x = 0; cout << "Value assigned to 'y' is " << assignValue(a, b, x); return 0;} // Java program to assign value to y according// to value of x public class GFG { static int assignValue(int a, int b, int x) { int y; int arr[] = new int[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y; } // Driver Method public static void main(String[] args) { int a = 5; int b = 10; int x = 0; System.out.println("Value assigned to 'y' is " + assignValue(a, b, x)); }} # Python 3 program to assign value to# y according to value of x # Function to assign value to y# according to value of x def assignValue(a, b, x): arr = [0] * 2 # Store both values in an array # value 'a' at 0th index arr[0] = a # Value 'b' at 1th index arr[1] = b # Assign value to 'y' taking 'x' # as index y = arr[x] return y # Driver codeif __name__ == "__main__": a = 5 b = 10 x = 0 print("Value assigned to 'y' is", assignValue(a, b, x)) # This code is contributed by ita_c // C# program to assign value to y according// to value of xusing System; public class GFG { static int assignValue(int a, int b, int x) { int y; int[] arr = new int[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' // as index y = arr[x]; return y; } // Driver Code public static void Main() { int a = 5; int b = 10; int x = 0; Console.Write("Value assigned to " + "'y' is " + assignValue(a, b, x)); }} // This code is contributed by nitin mittal. <?php// PHP program to assign value// to y according to value of x // Function to assign value// to y according to value of xfunction assignValue($a, $b, $x){ $y; $arr = array(0, 0); // Store both values in an array // value 'a' at 0th index $arr[0] = $a; // Value 'b' at 1th index $arr[1] = $b; // Assign value to 'y' // taking 'x' as index $y = $arr[$x]; return $y;} // Driver code$a = 5;$b = 10;$x = 0; echo "Value assigned to 'y' is " . assignValue($a, $b, $x); // This code is contributed by Anuj_67?> <script>// javascript program to assign value to y according// to value of x function assignValue(a , b , x) { var y; var arr = Array(2); // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y; } // Driver Method var a = 5; var b = 10; var x = 0; document.write("Value assigned to 'y' is " + assignValue(a, b, x)); // This code is contributed by todaysgaurav</script> Value assigned to 'y' is 5 Solution 2: Using bitwise AND operator. C++ Java Python3 C# Javascript // C/C++ program to assign value to y according// to value of x #include <iostream>using namespace std; // Driver Codeint main(){ int a = 5; int b = 10; int x = 1; int y; if (x & 1) y = b; else y = a; cout << "Value assigned to 'y' is " << y << endl; return 0;} // Java program to assign value to y according// to value of ximport java.io.*;class GFG{ // Driver Code public static void main (String[] args) { int a = 5; int b = 10; int x = 1; int y; if ((x & 1) != 0) y = b; else y = a; System.out.println("Value assigned to 'y' is " + y); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to assign value to y# according to value of x # Driver Codea = 5b = 10x = 1y = 0 if ((x & 1) != 0): y = belse: y = a print("Value assigned to 'y' is ", y) # This code is contributed by ab2127 // C# program to assign value to y according// to value of xusing System;public class GFG{ // Driver Code static public void Main () { int a = 5; int b = 10; int x = 1; int y; if ((x & 1) != 0) y = b; else y = a; Console.WriteLine("Value assigned to 'y' is " + y); }} // This code is contributed by rag2127 <script> // Javascript program to assign value to y according// to value of x // Driver Code var a = 5; var b = 10; var x = 1; var y; if ((x & 1) != 0) y = b; else y = a; document.write("Value assigned to 'y' is " + y); // This code contributed by Rajput-Ji </script> Value assigned to 'y' is 10 Reference: https://www.careercup.com/question?id=5135296679116800 This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m ukasp satishkale17 avanitrachhadiya2155 rag2127 todaysgaurav Rajput-Ji ab2127 swayambhusamiksha1 23620uday2021 amartyaghoshgfg CBSE - Class 11 school-programming C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Map in C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects Constructors in C++ Bitwise Operators in C/C++ Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Copy Constructor in C++ vector erase() and clear() in C++
[ { "code": null, "e": 24215, "s": 24187, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24334, "s": 24215, "text": "Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked:" }, { "code": null, "e": 24441, "s": 24334, "text": "If 'x' is 0, \n Assign value 'a' to variable 'y' \nElse (If 'x' is 1)\n Assign value 'b' to variable 'y'." }, { "code": null, "e": 24575, "s": 24441, "text": "Note: – You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /)." }, { "code": null, "e": 24587, "s": 24575, "text": "Examples : " }, { "code": null, "e": 24682, "s": 24587, "text": "Input : a = 5 , b = 10, x = 1\nOutput : y = 10\n\nInput : a = 5, b = 10 , x = 0\nOutput : y = 5" }, { "code": null, "e": 24710, "s": 24682, "text": "Asked in: Google Interview " }, { "code": null, "e": 24722, "s": 24710, "text": "Solution 1:" }, { "code": null, "e": 24865, "s": 24722, "text": "An Idea is to simply store both ‘a’ and ‘b’ in an array at 0th and 1st index respectively. Then store value to ‘y’ by taking ‘x’ as an index." }, { "code": null, "e": 24916, "s": 24865, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24920, "s": 24916, "text": "C++" }, { "code": null, "e": 24925, "s": 24920, "text": "Java" }, { "code": null, "e": 24933, "s": 24925, "text": "Python3" }, { "code": null, "e": 24936, "s": 24933, "text": "C#" }, { "code": null, "e": 24940, "s": 24936, "text": "PHP" }, { "code": null, "e": 24951, "s": 24940, "text": "Javascript" }, { "code": "// C/C++ program to assign value to y according// to value of x #include <iostream>using namespace std; // Function to assign value to y according// to value of xint assignValue(int a, int b, int x){ int y; int arr[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y;} // Driver codeint main(){ int a = 5; int b = 10; int x = 0; cout << \"Value assigned to 'y' is \" << assignValue(a, b, x); return 0;}", "e": 25535, "s": 24951, "text": null }, { "code": "// Java program to assign value to y according// to value of x public class GFG { static int assignValue(int a, int b, int x) { int y; int arr[] = new int[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y; } // Driver Method public static void main(String[] args) { int a = 5; int b = 10; int x = 0; System.out.println(\"Value assigned to 'y' is \" + assignValue(a, b, x)); }}", "e": 26188, "s": 25535, "text": null }, { "code": "# Python 3 program to assign value to# y according to value of x # Function to assign value to y# according to value of x def assignValue(a, b, x): arr = [0] * 2 # Store both values in an array # value 'a' at 0th index arr[0] = a # Value 'b' at 1th index arr[1] = b # Assign value to 'y' taking 'x' # as index y = arr[x] return y # Driver codeif __name__ == \"__main__\": a = 5 b = 10 x = 0 print(\"Value assigned to 'y' is\", assignValue(a, b, x)) # This code is contributed by ita_c", "e": 26729, "s": 26188, "text": null }, { "code": "// C# program to assign value to y according// to value of xusing System; public class GFG { static int assignValue(int a, int b, int x) { int y; int[] arr = new int[2]; // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' // as index y = arr[x]; return y; } // Driver Code public static void Main() { int a = 5; int b = 10; int x = 0; Console.Write(\"Value assigned to \" + \"'y' is \" + assignValue(a, b, x)); }} // This code is contributed by nitin mittal.", "e": 27429, "s": 26729, "text": null }, { "code": "<?php// PHP program to assign value// to y according to value of x // Function to assign value// to y according to value of xfunction assignValue($a, $b, $x){ $y; $arr = array(0, 0); // Store both values in an array // value 'a' at 0th index $arr[0] = $a; // Value 'b' at 1th index $arr[1] = $b; // Assign value to 'y' // taking 'x' as index $y = $arr[$x]; return $y;} // Driver code$a = 5;$b = 10;$x = 0; echo \"Value assigned to 'y' is \" . assignValue($a, $b, $x); // This code is contributed by Anuj_67?>", "e": 27980, "s": 27429, "text": null }, { "code": "<script>// javascript program to assign value to y according// to value of x function assignValue(a , b , x) { var y; var arr = Array(2); // Store both values in an array // value 'a' at 0th index arr[0] = a; // Value 'b' at 1th index arr[1] = b; // Assign value to 'y' taking 'x' as index y = arr[x]; return y; } // Driver Method var a = 5; var b = 10; var x = 0; document.write(\"Value assigned to 'y' is \" + assignValue(a, b, x)); // This code is contributed by todaysgaurav</script>", "e": 28593, "s": 27980, "text": null }, { "code": null, "e": 28620, "s": 28593, "text": "Value assigned to 'y' is 5" }, { "code": null, "e": 28633, "s": 28620, "text": "Solution 2: " }, { "code": null, "e": 28661, "s": 28633, "text": "Using bitwise AND operator." }, { "code": null, "e": 28665, "s": 28661, "text": "C++" }, { "code": null, "e": 28670, "s": 28665, "text": "Java" }, { "code": null, "e": 28678, "s": 28670, "text": "Python3" }, { "code": null, "e": 28681, "s": 28678, "text": "C#" }, { "code": null, "e": 28692, "s": 28681, "text": "Javascript" }, { "code": "// C/C++ program to assign value to y according// to value of x #include <iostream>using namespace std; // Driver Codeint main(){ int a = 5; int b = 10; int x = 1; int y; if (x & 1) y = b; else y = a; cout << \"Value assigned to 'y' is \" << y << endl; return 0;}", "e": 28993, "s": 28692, "text": null }, { "code": "// Java program to assign value to y according// to value of ximport java.io.*;class GFG{ // Driver Code public static void main (String[] args) { int a = 5; int b = 10; int x = 1; int y; if ((x & 1) != 0) y = b; else y = a; System.out.println(\"Value assigned to 'y' is \" + y); }} // This code is contributed by avanitrachhadiya2155", "e": 29365, "s": 28993, "text": null }, { "code": "# Python3 program to assign value to y# according to value of x # Driver Codea = 5b = 10x = 1y = 0 if ((x & 1) != 0): y = belse: y = a print(\"Value assigned to 'y' is \", y) # This code is contributed by ab2127", "e": 29581, "s": 29365, "text": null }, { "code": "// C# program to assign value to y according// to value of xusing System;public class GFG{ // Driver Code static public void Main () { int a = 5; int b = 10; int x = 1; int y; if ((x & 1) != 0) y = b; else y = a; Console.WriteLine(\"Value assigned to 'y' is \" + y); }} // This code is contributed by rag2127", "e": 29925, "s": 29581, "text": null }, { "code": "<script> // Javascript program to assign value to y according// to value of x // Driver Code var a = 5; var b = 10; var x = 1; var y; if ((x & 1) != 0) y = b; else y = a; document.write(\"Value assigned to 'y' is \" + y); // This code contributed by Rajput-Ji </script>", "e": 30273, "s": 29925, "text": null }, { "code": null, "e": 30301, "s": 30273, "text": "Value assigned to 'y' is 10" }, { "code": null, "e": 30367, "s": 30301, "text": "Reference: https://www.careercup.com/question?id=5135296679116800" }, { "code": null, "e": 30796, "s": 30367, "text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30811, "s": 30798, "text": "nitin mittal" }, { "code": null, "e": 30816, "s": 30811, "text": "vt_m" }, { "code": null, "e": 30822, "s": 30816, "text": "ukasp" }, { "code": null, "e": 30835, "s": 30822, "text": "satishkale17" }, { "code": null, "e": 30856, "s": 30835, "text": "avanitrachhadiya2155" }, { "code": null, "e": 30864, "s": 30856, "text": "rag2127" }, { "code": null, "e": 30877, "s": 30864, "text": "todaysgaurav" }, { "code": null, "e": 30887, "s": 30877, "text": "Rajput-Ji" }, { "code": null, "e": 30894, "s": 30887, "text": "ab2127" }, { "code": null, "e": 30913, "s": 30894, "text": "swayambhusamiksha1" }, { "code": null, "e": 30927, "s": 30913, "text": "23620uday2021" }, { "code": null, "e": 30943, "s": 30927, "text": "amartyaghoshgfg" }, { "code": null, "e": 30959, "s": 30943, "text": "CBSE - Class 11" }, { "code": null, "e": 30978, "s": 30959, "text": "school-programming" }, { "code": null, "e": 30982, "s": 30978, "text": "C++" }, { "code": null, "e": 30986, "s": 30982, "text": "CPP" }, { "code": null, "e": 31084, "s": 30986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31093, "s": 31084, "text": "Comments" }, { "code": null, "e": 31106, "s": 31093, "text": "Old Comments" }, { "code": null, "e": 31149, "s": 31106, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 31168, "s": 31149, "text": "Inheritance in C++" }, { "code": null, "e": 31192, "s": 31168, "text": "C++ Classes and Objects" }, { "code": null, "e": 31212, "s": 31192, "text": "Constructors in C++" }, { "code": null, "e": 31239, "s": 31212, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 31267, "s": 31239, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31295, "s": 31267, "text": "Operator Overloading in C++" }, { "code": null, "e": 31330, "s": 31295, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 31354, "s": 31330, "text": "Copy Constructor in C++" } ]
How to implement Dictionary with Python3? - GeeksforGeeks
04 Dec, 2019 This program uses python’s container called dictionary (in dictionary a key is associated with some information). This program will take a word as input and returns the meaning of that word.Python3 should be installed in your system. If it not installed, install it from this link. Always try to install the latest version. I made a text file in which word and its meaning is stored in python’s dictionary formatExample : data = {"geek" : "engage in or discuss computer-related tasks obsessively or with great attention to technical detail."} Here if we call “geek” from data then this will return its meaning “engage in or discuss computer-related tasks obsessively or with great attention to technical detail.”. This python program allow you to fetch the data of this text file and give the meaning. # Python3 Code for implementing# dictionary # importing json libraryimport json # importing get_close_matches function from difflib libraryfrom difflib import get_close_matches # loading datadata = json.load(open("data.txt")) # defining function meaningdef meaning(w): # converting all the letters of "w" to lower case w = w.lower() # checking if "w" is in data if w in data: return data[w] # if word is not in data then get close match of the word elif len(get_close_matches(w, data.keys())) > 0: # asking user for his feedback # get_close_matches returns a list of the best # “good enough” matches choosing first close # match "get_close_matches(w, data.keys())[0]" yn = input("Did you mean % s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0]) if yn == "Y": return data[get_close_matches(w, data.keys())[0]] elif yn == "N": return "The word doesn't exist in our data." else: return "We didn't understand your entry." else: return "The word doesn't exist in our data." # asking word from user to get the meaningword = input("Enter word: ") # storing return value in "output"output = meaning(word) # if output type is list then print all element of the listif type(output) == list: for item in output: print(item) # if output type is not "list" then print output onlyelse: print(output) How to run? Download this data file and save it in the same folder where your python code file is saved.Make sure that both the file(data file and the code file) are in same folder.Open command prompt in that folder to do so press shift then right click in mouse.Run the python code using cmd(command prompt).Input the word whose meaning is to be searched.Output will be your result. Video DemonstrationVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/ujjuDictionary-1.mp400:0000:0003:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes arrow_drop_upSave Download this data file and save it in the same folder where your python code file is saved. Make sure that both the file(data file and the code file) are in same folder. Open command prompt in that folder to do so press shift then right click in mouse. Run the python code using cmd(command prompt). Input the word whose meaning is to be searched. Output will be your result. Video DemonstrationVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/ujjuDictionary-1.mp400:0000:0003:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes arrow_drop_upSave Video Demonstration Akanksha_Rai python-string GBlog Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 DSA Sheet by Love Babbar 6 Best IDE's For Python in 2022 A Freshers Guide To Programming ML | Underfitting and Overfitting Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24619, "s": 24591, "text": "\n04 Dec, 2019" }, { "code": null, "e": 24943, "s": 24619, "text": "This program uses python’s container called dictionary (in dictionary a key is associated with some information). This program will take a word as input and returns the meaning of that word.Python3 should be installed in your system. If it not installed, install it from this link. Always try to install the latest version." }, { "code": null, "e": 25041, "s": 24943, "text": "I made a text file in which word and its meaning is stored in python’s dictionary formatExample :" }, { "code": null, "e": 25164, "s": 25041, "text": "data = {\"geek\" : \"engage in or discuss computer-related tasks \nobsessively or with great attention to technical detail.\"}\n" }, { "code": null, "e": 25335, "s": 25164, "text": "Here if we call “geek” from data then this will return its meaning “engage in or discuss computer-related tasks obsessively or with great attention to technical detail.”." }, { "code": null, "e": 25423, "s": 25335, "text": "This python program allow you to fetch the data of this text file and give the meaning." }, { "code": "# Python3 Code for implementing# dictionary # importing json libraryimport json # importing get_close_matches function from difflib libraryfrom difflib import get_close_matches # loading datadata = json.load(open(\"data.txt\")) # defining function meaningdef meaning(w): # converting all the letters of \"w\" to lower case w = w.lower() # checking if \"w\" is in data if w in data: return data[w] # if word is not in data then get close match of the word elif len(get_close_matches(w, data.keys())) > 0: # asking user for his feedback # get_close_matches returns a list of the best # “good enough” matches choosing first close # match \"get_close_matches(w, data.keys())[0]\" yn = input(\"Did you mean % s instead? Enter Y if yes, or N if no: \" % get_close_matches(w, data.keys())[0]) if yn == \"Y\": return data[get_close_matches(w, data.keys())[0]] elif yn == \"N\": return \"The word doesn't exist in our data.\" else: return \"We didn't understand your entry.\" else: return \"The word doesn't exist in our data.\" # asking word from user to get the meaningword = input(\"Enter word: \") # storing return value in \"output\"output = meaning(word) # if output type is list then print all element of the listif type(output) == list: for item in output: print(item) # if output type is not \"list\" then print output onlyelse: print(output)", "e": 26912, "s": 25423, "text": null }, { "code": null, "e": 26924, "s": 26912, "text": "How to run?" }, { "code": null, "e": 27503, "s": 26924, "text": "Download this data file and save it in the same folder where your python code file is saved.Make sure that both the file(data file and the code file) are in same folder.Open command prompt in that folder to do so press shift then right click in mouse.Run the python code using cmd(command prompt).Input the word whose meaning is to be searched.Output will be your result. Video DemonstrationVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/ujjuDictionary-1.mp400:0000:0003:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27596, "s": 27503, "text": "Download this data file and save it in the same folder where your python code file is saved." }, { "code": null, "e": 27674, "s": 27596, "text": "Make sure that both the file(data file and the code file) are in same folder." }, { "code": null, "e": 27757, "s": 27674, "text": "Open command prompt in that folder to do so press shift then right click in mouse." }, { "code": null, "e": 27804, "s": 27757, "text": "Run the python code using cmd(command prompt)." }, { "code": null, "e": 27852, "s": 27804, "text": "Input the word whose meaning is to be searched." }, { "code": null, "e": 28087, "s": 27852, "text": "Output will be your result. Video DemonstrationVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/ujjuDictionary-1.mp400:0000:0003:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28109, "s": 28089, "text": "Video Demonstration" }, { "code": null, "e": 28122, "s": 28109, "text": "Akanksha_Rai" }, { "code": null, "e": 28136, "s": 28122, "text": "python-string" }, { "code": null, "e": 28142, "s": 28136, "text": "GBlog" }, { "code": null, "e": 28149, "s": 28142, "text": "Python" }, { "code": null, "e": 28168, "s": 28149, "text": "Technical Scripter" }, { "code": null, "e": 28266, "s": 28168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28275, "s": 28266, "text": "Comments" }, { "code": null, "e": 28288, "s": 28275, "text": "Old Comments" }, { "code": null, "e": 28344, "s": 28288, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28369, "s": 28344, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 28401, "s": 28369, "text": "6 Best IDE's For Python in 2022" }, { "code": null, "e": 28433, "s": 28401, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 28467, "s": 28433, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28495, "s": 28467, "text": "Read JSON file using Python" }, { "code": null, "e": 28545, "s": 28495, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28567, "s": 28545, "text": "Python map() function" } ]
Bootstrap - Glyphicons
This chapter will discuss about Glyphicons, its use and some examples. Bootstrap bundles 200 glyphs in font format. Let us now understand what Glyphicons are. Glyphicons are icon fonts which you can use in your web projects. Glyphicons Halflings are not free and require licensing, however their creator has made them available for Bootstrap projects free of cost. Now that we have downloaded Bootstrap 3.x version and understand its directory structure from the chapter Environment Setup, glyphicons can be found within the fonts folder. This contains the following files − glyphicons-halflings-regular.eot glyphicons-halflings-regular.svg glyphicons-halflings-regular.ttf glyphicons-halflings-regular.woff Associated CSS rules are present within bootstrap.css and bootstrap-min.css files within css folder of dist folder. You can see the available glyphicons at this link GLYPHICONS. To use the icons, simply use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding. <span class = "glyphicon glyphicon-search"></span> The following example demonstrates this − <p> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-sort-by-attributes"></span> </button> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-sort-by-attributes-alt"></span> </button> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-sort-by-order"></span> </button> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-sort-by-order-alt"></span> </button> </p> <button type = "button" class = "btn btn-default btn-lg"> <span class = "glyphicon glyphicon-user"></span> User </button> <button type = "button" class = "btn btn-default btn-sm"> <span class = "glyphicon glyphicon-user"></span> User </button> <button type ="button" class = "btn btn-default btn-xs"> <span class = "glyphicon glyphicon-user"></span> User </button> 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3490, "s": 3331, "text": "This chapter will discuss about Glyphicons, its use and some examples. Bootstrap bundles 200 glyphs in font format. Let us now understand what Glyphicons are." }, { "code": null, "e": 3696, "s": 3490, "text": "Glyphicons are icon fonts which you can use in your web projects. Glyphicons Halflings are not free and require licensing, however their creator has made them available for Bootstrap projects free of cost." }, { "code": null, "e": 3907, "s": 3696, "text": "Now that we have downloaded Bootstrap 3.x version and understand its directory structure from the chapter Environment Setup, glyphicons can be found within the fonts folder. This contains the following files −" }, { "code": null, "e": 3940, "s": 3907, "text": "glyphicons-halflings-regular.eot" }, { "code": null, "e": 3973, "s": 3940, "text": "glyphicons-halflings-regular.svg" }, { "code": null, "e": 4006, "s": 3973, "text": "glyphicons-halflings-regular.ttf" }, { "code": null, "e": 4040, "s": 4006, "text": "glyphicons-halflings-regular.woff" }, { "code": null, "e": 4218, "s": 4040, "text": "Associated CSS rules are present within bootstrap.css and bootstrap-min.css files within css folder of dist folder. You can see the available glyphicons at this link GLYPHICONS." }, { "code": null, "e": 4360, "s": 4218, "text": "To use the icons, simply use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding." }, { "code": null, "e": 4411, "s": 4360, "text": "<span class = \"glyphicon glyphicon-search\"></span>" }, { "code": null, "e": 4453, "s": 4411, "text": "The following example demonstrates this −" }, { "code": null, "e": 5416, "s": 4453, "text": "<p>\n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-sort-by-attributes\"></span>\n </button>\n \n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-sort-by-attributes-alt\"></span>\n </button>\n \n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-sort-by-order\"></span>\n </button>\n \n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-sort-by-order-alt\"></span>\n </button>\n</p>\n\n<button type = \"button\" class = \"btn btn-default btn-lg\">\n <span class = \"glyphicon glyphicon-user\"></span>\n \n User\n</button>\n\n<button type = \"button\" class = \"btn btn-default btn-sm\">\n <span class = \"glyphicon glyphicon-user\"></span> \n \n User\n</button>\n\n<button type =\"button\" class = \"btn btn-default btn-xs\">\n <span class = \"glyphicon glyphicon-user\"></span> \n \n User\n</button>" }, { "code": null, "e": 5463, "s": 5430, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5477, "s": 5463, "text": " Anadi Sharma" }, { "code": null, "e": 5512, "s": 5477, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5529, "s": 5512, "text": " Frahaan Hussain" }, { "code": null, "e": 5566, "s": 5529, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 5594, "s": 5566, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5627, "s": 5594, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 5639, "s": 5627, "text": " Azaz Patel" }, { "code": null, "e": 5674, "s": 5639, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5691, "s": 5674, "text": " Muhammad Ismail" }, { "code": null, "e": 5724, "s": 5691, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 5744, "s": 5724, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 5751, "s": 5744, "text": " Print" }, { "code": null, "e": 5762, "s": 5751, "text": " Add Notes" } ]
Difference between Normal def defined function and Lambda - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss the difference between normal def defined function and lambda in Python. In python, def defined functions are commonly used because of their simplicity. The def defined functions do not return anything if not explicitly returned whereas the lambda function does return an object. The def functions must be declared in the namespace. The def functions can perform any python task including multiple conditions, nested conditions or loops of any level, printing, importing libraries, raising Exceptions, etc. Example: Python3 # Define function to calculate cube root# using def keyword def calculate_cube_root(x): return x**(1/3) # Call the def function to calculate cube# root and print itprint(calculate_cube_root(27)) # Define function to check if language is present in# language list using def keywordlanguages = ['Sanskrut', 'English', 'French', 'German'] def check_language(x): if x in languages: return True return False # Call the def function to check if keyword 'English'# is present in the languages list and print itprint(check_language('English')) Output: 3.0 True The lambda functions can be used without any declaration in the namespace. The lambda functions defined above are like single-line functions. These functions do not have parenthesis like the def defined functions but instead, take parameters after the lambda keyword as shown above. There is no return keyword defined explicitly because the lambda function does return an object by default. Example: Python3 # Define function using lambda for cube rootcube_root= lambda x: x**(1/3) # Call the lambda functionprint(cube_root(27)) languages = ['Sanskrut', 'English', 'French', 'German'] # Define function using lambdal_check_language = lambda x: True if x in languages else False # Call the lambda functionprint(l_check_language('Sanskrut')) Output: 3.0 True def defined functions lambda functions Easy to interpret Interpretation might be tricky Can consists of any number of execution statements inside the function definition The limited operation can be performed using lambda functions To return an object from the function, return should be explicitly defined No need of using the return statement Execution time is relatively slower for the same operation performed using lambda functions Execution time of the program is fast for the same operation Defined using the keyword def and holds a function name in the local namespace Defined using the keyword lambda and does not compulsorily hold a function name in the local namespace Picked Python-Functions python-lambda Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n19 Dec, 2021" }, { "code": null, "e": 24398, "s": 24292, "text": "In this article, we will discuss the difference between normal def defined function and lambda in Python." }, { "code": null, "e": 24833, "s": 24398, "text": "In python, def defined functions are commonly used because of their simplicity. The def defined functions do not return anything if not explicitly returned whereas the lambda function does return an object. The def functions must be declared in the namespace. The def functions can perform any python task including multiple conditions, nested conditions or loops of any level, printing, importing libraries, raising Exceptions, etc. " }, { "code": null, "e": 24842, "s": 24833, "text": "Example:" }, { "code": null, "e": 24850, "s": 24842, "text": "Python3" }, { "code": "# Define function to calculate cube root# using def keyword def calculate_cube_root(x): return x**(1/3) # Call the def function to calculate cube# root and print itprint(calculate_cube_root(27)) # Define function to check if language is present in# language list using def keywordlanguages = ['Sanskrut', 'English', 'French', 'German'] def check_language(x): if x in languages: return True return False # Call the def function to check if keyword 'English'# is present in the languages list and print itprint(check_language('English'))", "e": 25407, "s": 24850, "text": null }, { "code": null, "e": 25415, "s": 25407, "text": "Output:" }, { "code": null, "e": 25424, "s": 25415, "text": "3.0\nTrue" }, { "code": null, "e": 25815, "s": 25424, "text": "The lambda functions can be used without any declaration in the namespace. The lambda functions defined above are like single-line functions. These functions do not have parenthesis like the def defined functions but instead, take parameters after the lambda keyword as shown above. There is no return keyword defined explicitly because the lambda function does return an object by default." }, { "code": null, "e": 25824, "s": 25815, "text": "Example:" }, { "code": null, "e": 25832, "s": 25824, "text": "Python3" }, { "code": "# Define function using lambda for cube rootcube_root= lambda x: x**(1/3) # Call the lambda functionprint(cube_root(27)) languages = ['Sanskrut', 'English', 'French', 'German'] # Define function using lambdal_check_language = lambda x: True if x in languages else False # Call the lambda functionprint(l_check_language('Sanskrut'))", "e": 26172, "s": 25832, "text": null }, { "code": null, "e": 26180, "s": 26172, "text": "Output:" }, { "code": null, "e": 26189, "s": 26180, "text": "3.0\nTrue" }, { "code": null, "e": 26211, "s": 26189, "text": "def defined functions" }, { "code": null, "e": 26228, "s": 26211, "text": "lambda functions" }, { "code": null, "e": 26246, "s": 26228, "text": "Easy to interpret" }, { "code": null, "e": 26277, "s": 26246, "text": "Interpretation might be tricky" }, { "code": null, "e": 26359, "s": 26277, "text": "Can consists of any number of execution statements inside the function definition" }, { "code": null, "e": 26421, "s": 26359, "text": "The limited operation can be performed using lambda functions" }, { "code": null, "e": 26496, "s": 26421, "text": "To return an object from the function, return should be explicitly defined" }, { "code": null, "e": 26534, "s": 26496, "text": "No need of using the return statement" }, { "code": null, "e": 26626, "s": 26534, "text": "Execution time is relatively slower for the same operation performed using lambda functions" }, { "code": null, "e": 26687, "s": 26626, "text": "Execution time of the program is fast for the same operation" }, { "code": null, "e": 26766, "s": 26687, "text": "Defined using the keyword def and holds a function name in the local namespace" }, { "code": null, "e": 26869, "s": 26766, "text": "Defined using the keyword lambda and does not compulsorily hold a function name in the local namespace" }, { "code": null, "e": 26876, "s": 26869, "text": "Picked" }, { "code": null, "e": 26893, "s": 26876, "text": "Python-Functions" }, { "code": null, "e": 26907, "s": 26893, "text": "python-lambda" }, { "code": null, "e": 26914, "s": 26907, "text": "Python" }, { "code": null, "e": 27012, "s": 26914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27044, "s": 27012, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27086, "s": 27044, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27142, "s": 27086, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27184, "s": 27142, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27206, "s": 27184, "text": "Defaultdict in Python" }, { "code": null, "e": 27261, "s": 27206, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27292, "s": 27261, "text": "Python | os.path.join() method" }, { "code": null, "e": 27331, "s": 27292, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27360, "s": 27331, "text": "Create a directory in Python" } ]
Python Program that Displays which Letters are in the First String but not in the Second
When it is required to display the letters that are present in the first string but not in the second string, two string inputs are taken from user. The ‘set’ is used to find the difference between the two strings. Python comes with a datatype known as ‘set’. This ‘set’ contains elements that are unique only. The set is useful in performing operations such as intersection, difference, union and symmetric difference. Below is a demonstration for the same − Live Demo my_str_1 = input("Enter the first string...") my_str_2 = input("Enter the second string...") my_result = list(set(my_str_1)-set(my_str_2)) print("The letters in first string but not in second string :") for i in my_result: print(i) Enter the first string...Jane Enter the second string...Wane The letters in first string but not in second string : J Two strings are taken as input from the user. They are converted to a set, and their difference is computed. This difference is converted to a list. This value is assigned to a variable. This is iterated over, and displayed on the console.
[ { "code": null, "e": 1277, "s": 1062, "text": "When it is required to display the letters that are present in the first string but not in the second string, two string inputs are taken from user. The ‘set’ is used to find the difference between the two strings." }, { "code": null, "e": 1373, "s": 1277, "text": "Python comes with a datatype known as ‘set’. This ‘set’ contains elements that are unique only." }, { "code": null, "e": 1482, "s": 1373, "text": "The set is useful in performing operations such as intersection, difference, union and symmetric difference." }, { "code": null, "e": 1522, "s": 1482, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1533, "s": 1522, "text": " Live Demo" }, { "code": null, "e": 1768, "s": 1533, "text": "my_str_1 = input(\"Enter the first string...\")\nmy_str_2 = input(\"Enter the second string...\")\nmy_result = list(set(my_str_1)-set(my_str_2))\nprint(\"The letters in first string but not in second string :\")\nfor i in my_result:\n print(i)" }, { "code": null, "e": 1886, "s": 1768, "text": "Enter the first string...Jane\nEnter the second string...Wane\nThe letters in first string but not in second string :\nJ" }, { "code": null, "e": 1932, "s": 1886, "text": "Two strings are taken as input from the user." }, { "code": null, "e": 1995, "s": 1932, "text": "They are converted to a set, and their difference is computed." }, { "code": null, "e": 2035, "s": 1995, "text": "This difference is converted to a list." }, { "code": null, "e": 2073, "s": 2035, "text": "This value is assigned to a variable." }, { "code": null, "e": 2126, "s": 2073, "text": "This is iterated over, and displayed on the console." } ]
A Gentle Introduction on Market Basket Analysis — Association Rules | by Susan Li | Towards Data Science
Market Basket Analysis is one of the key techniques used by large retailers to uncover associations between items. It works by looking for combinations of items that occur together frequently in transactions. To put it another way, it allows retailers to identify relationships between the items that people buy. Association Rules are widely used to analyze retail basket or transaction data, and are intended to identify strong rules discovered in transaction data using measures of interestingness, based on the concept of strong rules. An example of Association Rules Assume there are 100 customers 10 of them bought milk, 8 bought butter and 6 bought both of them. bought milk => bought butter support = P(Milk & Butter) = 6/100 = 0.06 confidence = support/P(Butter) = 0.06/0.08 = 0.75 lift = confidence/P(Milk) = 0.75/0.10 = 7.5 Note: this example is extremely small. In practice, a rule needs the support of several hundred transactions, before it can be considered statistically significant, and datasets often contain thousands or millions of transactions. Ok, enough for the theory, let’s get to the code. The dataset we are using today comes from UCI Machine Learning repository. The dataset is called “Online Retail” and can be found here. It contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered online retailer. library(tidyverse)library(readxl)library(knitr)library(ggplot2)library(lubridate)library(arules)library(arulesViz)library(plyr) retail <- read_excel('Online_retail.xlsx')retail <- retail[complete.cases(retail), ]retail <- retail %>% mutate(Description = as.factor(Description))retail <- retail %>% mutate(Country = as.factor(Country))retail$Date <- as.Date(retail$InvoiceDate)retail$Time <- format(retail$InvoiceDate,"%H:%M:%S")retail$InvoiceNo <- as.numeric(as.character(retail$InvoiceNo))glimpse(retail) After preprocessing, the dataset includes 406,829 records and 10 fields: InvoiceNo, StockCode, Description, Quantity, InvoiceDate, UnitPrice, CustomerID, Country, Date, Time. What time do people often purchase online? In order to find the answer to this question, we need to extract “hour” from the time column. retail$Time <- as.factor(retail$Time)a <- hms(as.character(retail$Time))retail$Time = hour(a)retail %>% ggplot(aes(x=Time)) + geom_histogram(stat="count",fill="indianred") There is a clear bias between the hour of day and order volume. Most orders happened between 10:00–15:00. How many items each customer buy? detach("package:plyr", unload=TRUE)retail %>% group_by(InvoiceNo) %>% summarize(n_items = mean(Quantity)) %>% ggplot(aes(x=n_items))+ geom_histogram(fill="indianred", bins = 100000) + geom_rug()+ coord_cartesian(xlim=c(0,80)) People mostly purchased less than 10 items (less than 10 items in each invoice). Top 10 best sellers tmp <- retail %>% group_by(StockCode, Description) %>% summarize(count = n()) %>% arrange(desc(count))tmp <- head(tmp, n=10)tmptmp %>% ggplot(aes(x=reorder(Description,count), y=count))+ geom_bar(stat="identity",fill="indian red")+ coord_flip() Before using any rule mining algorithm, we need to transform the data from the data frame format, into transactions such that we have all the items bought together in one row. For example, this is the format we need: retail_sorted <- retail[order(retail$CustomerID),]library(plyr)itemList <- ddply(retail,c("CustomerID","Date"), function(df1)paste(df1$Description, collapse = ",")) The function ddply() accepts a data frame, splits it into pieces based on one or more factors, computes on the pieces, and then returns the results as a data frame. We use “,” to separate different items. We only need item transactions, so remove customerID and Date columns. itemList$CustomerID <- NULLitemList$Date <- NULLcolnames(itemList) <- c("items") Write the data fram to a csv file and check whether our transaction format is correct. write.csv(itemList,"market_basket.csv", quote = FALSE, row.names = TRUE) Perfect! Now we have our transaction dataset, and it shows the matrix of items being bought together. We don’t actually see how often they are bought together, and we don’t see rules either. But we are going to find out. Let’s have a closer look at how many transactions we have and what they are. tr <- read.transactions('market_basket.csv', format = 'basket', sep=',')trsummary(tr) We see 19,296 transactions, and this is the number of rows as well. There are 7,881 items — remember items are the product descriptions in our original dataset. Transactions here are the collections or subsets of these 7,881 items. The summary gives us some useful information: density: The percentage of non-empty cells in the sparse matrix. In another words, the total number of items that are purchased divided by the total number of possible items in that matrix. We can calculate how many items were purchased using density like so: 19296 X 7881 X 0.0022 The most frequent items should be the same as our results in Figure 3. Looking at the size of the transactions: 2247 transactions were for just 1 item, 1147 transactions for 2 items, all the way up to the biggest transaction: 1 transaction for 420 items. This indicates that most customers buy a small number of items in each transaction. The distribution of the data is right skewed. Let’s have a look at the item frequency plot, which should be in aligned with Figure 3. itemFrequencyPlot(tr, topN=20, type='absolute') We use the Apriori algorithm in Arules library to mine frequent itemsets and association rules. The algorithm employs level-wise search for frequent itemsets. We pass supp=0.001 and conf=0.8 to return all the rules that have a support of at least 0.1% and confidence of at least 80%. We sort the rules by decreasing confidence. Have a look at the summary of the rules. rules <- apriori(tr, parameter = list(supp=0.001, conf=0.8))rules <- sort(rules, by='confidence', decreasing = TRUE)summary(rules) The summary of the rules gives us some very interesting information: The number of rules: 89,697. The distribution of rules by length: a length of 6 items has the most rules. The summary of quality measures: ranges of support, confidence, and lift. The information on data mining: total data mined, and the minimum parameters we set earlier. We have 89,697 rules. I don’t want to print them all, so let’s inspect the top 10. inspect(rules[1:10]) The interpretation is pretty straight forward: 100% customers who bought “WOBBLY CHICKEN” also bought “DECORATION”. 100% customers who bought “BLACK TEA” also bought “SUGAR JAR”. And plot these top 10 rules. topRules <- rules[1:10]plot(topRules) plot(topRules, method="graph") plot(topRules, method = "grouped") In this post, we have learned how to perform Market Basket Analysis in R and how to interpret the results. If you want to implement them in Python, Mlxtend is a Python library that has an implementation of the Apriori algorithm for this sort of application. You can find an introduction tutorial here. If you would like the R Markdown file used to make this blog post, you can find here. reference: R and Data Mining
[ { "code": null, "e": 485, "s": 172, "text": "Market Basket Analysis is one of the key techniques used by large retailers to uncover associations between items. It works by looking for combinations of items that occur together frequently in transactions. To put it another way, it allows retailers to identify relationships between the items that people buy." }, { "code": null, "e": 711, "s": 485, "text": "Association Rules are widely used to analyze retail basket or transaction data, and are intended to identify strong rules discovered in transaction data using measures of interestingness, based on the concept of strong rules." }, { "code": null, "e": 743, "s": 711, "text": "An example of Association Rules" }, { "code": null, "e": 774, "s": 743, "text": "Assume there are 100 customers" }, { "code": null, "e": 841, "s": 774, "text": "10 of them bought milk, 8 bought butter and 6 bought both of them." }, { "code": null, "e": 870, "s": 841, "text": "bought milk => bought butter" }, { "code": null, "e": 912, "s": 870, "text": "support = P(Milk & Butter) = 6/100 = 0.06" }, { "code": null, "e": 962, "s": 912, "text": "confidence = support/P(Butter) = 0.06/0.08 = 0.75" }, { "code": null, "e": 1006, "s": 962, "text": "lift = confidence/P(Milk) = 0.75/0.10 = 7.5" }, { "code": null, "e": 1237, "s": 1006, "text": "Note: this example is extremely small. In practice, a rule needs the support of several hundred transactions, before it can be considered statistically significant, and datasets often contain thousands or millions of transactions." }, { "code": null, "e": 1287, "s": 1237, "text": "Ok, enough for the theory, let’s get to the code." }, { "code": null, "e": 1547, "s": 1287, "text": "The dataset we are using today comes from UCI Machine Learning repository. The dataset is called “Online Retail” and can be found here. It contains all the transactions occurring between 01/12/2010 and 09/12/2011 for a UK-based and registered online retailer." }, { "code": null, "e": 1675, "s": 1547, "text": "library(tidyverse)library(readxl)library(knitr)library(ggplot2)library(lubridate)library(arules)library(arulesViz)library(plyr)" }, { "code": null, "e": 2053, "s": 1675, "text": "retail <- read_excel('Online_retail.xlsx')retail <- retail[complete.cases(retail), ]retail <- retail %>% mutate(Description = as.factor(Description))retail <- retail %>% mutate(Country = as.factor(Country))retail$Date <- as.Date(retail$InvoiceDate)retail$Time <- format(retail$InvoiceDate,\"%H:%M:%S\")retail$InvoiceNo <- as.numeric(as.character(retail$InvoiceNo))glimpse(retail)" }, { "code": null, "e": 2228, "s": 2053, "text": "After preprocessing, the dataset includes 406,829 records and 10 fields: InvoiceNo, StockCode, Description, Quantity, InvoiceDate, UnitPrice, CustomerID, Country, Date, Time." }, { "code": null, "e": 2271, "s": 2228, "text": "What time do people often purchase online?" }, { "code": null, "e": 2365, "s": 2271, "text": "In order to find the answer to this question, we need to extract “hour” from the time column." }, { "code": null, "e": 2541, "s": 2365, "text": "retail$Time <- as.factor(retail$Time)a <- hms(as.character(retail$Time))retail$Time = hour(a)retail %>% ggplot(aes(x=Time)) + geom_histogram(stat=\"count\",fill=\"indianred\")" }, { "code": null, "e": 2647, "s": 2541, "text": "There is a clear bias between the hour of day and order volume. Most orders happened between 10:00–15:00." }, { "code": null, "e": 2681, "s": 2647, "text": "How many items each customer buy?" }, { "code": null, "e": 2916, "s": 2681, "text": "detach(\"package:plyr\", unload=TRUE)retail %>% group_by(InvoiceNo) %>% summarize(n_items = mean(Quantity)) %>% ggplot(aes(x=n_items))+ geom_histogram(fill=\"indianred\", bins = 100000) + geom_rug()+ coord_cartesian(xlim=c(0,80))" }, { "code": null, "e": 2997, "s": 2916, "text": "People mostly purchased less than 10 items (less than 10 items in each invoice)." }, { "code": null, "e": 3017, "s": 2997, "text": "Top 10 best sellers" }, { "code": null, "e": 3272, "s": 3017, "text": "tmp <- retail %>% group_by(StockCode, Description) %>% summarize(count = n()) %>% arrange(desc(count))tmp <- head(tmp, n=10)tmptmp %>% ggplot(aes(x=reorder(Description,count), y=count))+ geom_bar(stat=\"identity\",fill=\"indian red\")+ coord_flip()" }, { "code": null, "e": 3489, "s": 3272, "text": "Before using any rule mining algorithm, we need to transform the data from the data frame format, into transactions such that we have all the items bought together in one row. For example, this is the format we need:" }, { "code": null, "e": 3700, "s": 3489, "text": "retail_sorted <- retail[order(retail$CustomerID),]library(plyr)itemList <- ddply(retail,c(\"CustomerID\",\"Date\"), function(df1)paste(df1$Description, collapse = \",\"))" }, { "code": null, "e": 3905, "s": 3700, "text": "The function ddply() accepts a data frame, splits it into pieces based on one or more factors, computes on the pieces, and then returns the results as a data frame. We use “,” to separate different items." }, { "code": null, "e": 3976, "s": 3905, "text": "We only need item transactions, so remove customerID and Date columns." }, { "code": null, "e": 4057, "s": 3976, "text": "itemList$CustomerID <- NULLitemList$Date <- NULLcolnames(itemList) <- c(\"items\")" }, { "code": null, "e": 4144, "s": 4057, "text": "Write the data fram to a csv file and check whether our transaction format is correct." }, { "code": null, "e": 4217, "s": 4144, "text": "write.csv(itemList,\"market_basket.csv\", quote = FALSE, row.names = TRUE)" }, { "code": null, "e": 4438, "s": 4217, "text": "Perfect! Now we have our transaction dataset, and it shows the matrix of items being bought together. We don’t actually see how often they are bought together, and we don’t see rules either. But we are going to find out." }, { "code": null, "e": 4515, "s": 4438, "text": "Let’s have a closer look at how many transactions we have and what they are." }, { "code": null, "e": 4601, "s": 4515, "text": "tr <- read.transactions('market_basket.csv', format = 'basket', sep=',')trsummary(tr)" }, { "code": null, "e": 4833, "s": 4601, "text": "We see 19,296 transactions, and this is the number of rows as well. There are 7,881 items — remember items are the product descriptions in our original dataset. Transactions here are the collections or subsets of these 7,881 items." }, { "code": null, "e": 4879, "s": 4833, "text": "The summary gives us some useful information:" }, { "code": null, "e": 5161, "s": 4879, "text": "density: The percentage of non-empty cells in the sparse matrix. In another words, the total number of items that are purchased divided by the total number of possible items in that matrix. We can calculate how many items were purchased using density like so: 19296 X 7881 X 0.0022" }, { "code": null, "e": 5232, "s": 5161, "text": "The most frequent items should be the same as our results in Figure 3." }, { "code": null, "e": 5500, "s": 5232, "text": "Looking at the size of the transactions: 2247 transactions were for just 1 item, 1147 transactions for 2 items, all the way up to the biggest transaction: 1 transaction for 420 items. This indicates that most customers buy a small number of items in each transaction." }, { "code": null, "e": 5546, "s": 5500, "text": "The distribution of the data is right skewed." }, { "code": null, "e": 5634, "s": 5546, "text": "Let’s have a look at the item frequency plot, which should be in aligned with Figure 3." }, { "code": null, "e": 5682, "s": 5634, "text": "itemFrequencyPlot(tr, topN=20, type='absolute')" }, { "code": null, "e": 5841, "s": 5682, "text": "We use the Apriori algorithm in Arules library to mine frequent itemsets and association rules. The algorithm employs level-wise search for frequent itemsets." }, { "code": null, "e": 5966, "s": 5841, "text": "We pass supp=0.001 and conf=0.8 to return all the rules that have a support of at least 0.1% and confidence of at least 80%." }, { "code": null, "e": 6010, "s": 5966, "text": "We sort the rules by decreasing confidence." }, { "code": null, "e": 6051, "s": 6010, "text": "Have a look at the summary of the rules." }, { "code": null, "e": 6182, "s": 6051, "text": "rules <- apriori(tr, parameter = list(supp=0.001, conf=0.8))rules <- sort(rules, by='confidence', decreasing = TRUE)summary(rules)" }, { "code": null, "e": 6251, "s": 6182, "text": "The summary of the rules gives us some very interesting information:" }, { "code": null, "e": 6280, "s": 6251, "text": "The number of rules: 89,697." }, { "code": null, "e": 6357, "s": 6280, "text": "The distribution of rules by length: a length of 6 items has the most rules." }, { "code": null, "e": 6431, "s": 6357, "text": "The summary of quality measures: ranges of support, confidence, and lift." }, { "code": null, "e": 6524, "s": 6431, "text": "The information on data mining: total data mined, and the minimum parameters we set earlier." }, { "code": null, "e": 6607, "s": 6524, "text": "We have 89,697 rules. I don’t want to print them all, so let’s inspect the top 10." }, { "code": null, "e": 6628, "s": 6607, "text": "inspect(rules[1:10])" }, { "code": null, "e": 6675, "s": 6628, "text": "The interpretation is pretty straight forward:" }, { "code": null, "e": 6744, "s": 6675, "text": "100% customers who bought “WOBBLY CHICKEN” also bought “DECORATION”." }, { "code": null, "e": 6807, "s": 6744, "text": "100% customers who bought “BLACK TEA” also bought “SUGAR JAR”." }, { "code": null, "e": 6836, "s": 6807, "text": "And plot these top 10 rules." }, { "code": null, "e": 6874, "s": 6836, "text": "topRules <- rules[1:10]plot(topRules)" }, { "code": null, "e": 6905, "s": 6874, "text": "plot(topRules, method=\"graph\")" }, { "code": null, "e": 6940, "s": 6905, "text": "plot(topRules, method = \"grouped\")" }, { "code": null, "e": 7242, "s": 6940, "text": "In this post, we have learned how to perform Market Basket Analysis in R and how to interpret the results. If you want to implement them in Python, Mlxtend is a Python library that has an implementation of the Apriori algorithm for this sort of application. You can find an introduction tutorial here." }, { "code": null, "e": 7328, "s": 7242, "text": "If you would like the R Markdown file used to make this blog post, you can find here." } ]
Ionic - Header
The Ionic header bar is located on top of the screen. It can contain title, icons, buttons or some other elements on top of it. There are predefined classes of headers that you can use. You can check all of it in this tutorial. The main class for all the bars you might use in your app is bar. This class will always be applied to all the bars in your app. All bar subclasses will use the prefix – bar. If you want to create a header, you need to add bar-header after your main bar class. Open your www/index.html file and add the header class inside your body tag. We are adding a header to the index.html body because we want it to be available on every screen in the app. Since bar-header class has default (white) styling applied, we will add the title on top of it, so you can differentiate it from the rest of your screen. <div class = "bar bar-header"> <h1 class = "title">Header</h1> </div> The above code will produce the following screen − If you want to style your header, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as prefix to your color class. Since we are styling the header bar, the prefix class will be bar and the color class that we want to use in this example is positive (blue). <div class = "bar bar-header bar-positive"> <h1 class = "title">Header</h1> </div> The above code will produce the following screen − You can use any of the following nine classes to give a color of your choice to your app header − We can add other elements inside the header. The following code is an example to add a menu button and a home button inside a header. We will also add icons on top of our header buttons. <div class = "bar bar-header bar-positive"> <button class = "button icon ion-navicon"></button> <h1 class = "title">Header Buttons</h1> <button class = "button icon ion-home"></button> </div> The above code will produce the following screen − You can create a sub header that will be located just below the header bar. The following example will show how to add a header and a sub header to your app. Here, we have styled the sub header with an "assertive" (red) color class. <div class = "bar bar-header bar-positive"> <button class = "button icon ion-navicon"></button> <h1 class = "title">Header Buttons</h1> <button class = "button icon ion-home"></button> </div> <div class = "bar bar-subheader bar-assertive"> <h2 class = "title">Sub Header</h2> </div> The above code will produce the following screen − When your route is changed to any of the app screens, you will notice that the header and the sub header are covering some content as shown in the screenshot below. To fix this you need to add a ‘has-header’ or a ‘has-subheader’ class to the ion-content tags of your screens. Open one of your HTML files from www/templates and add the has-subheader class to the ion-content. If you only use header in your app, you will need to add the has-header class instead. <ion-content class = "padding has-subheader"> The above code will produce the following screen − 16 Lectures 2.5 hours Frahaan Hussain 185 Lectures 46.5 hours Nikhil Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2691, "s": 2463, "text": "The Ionic header bar is located on top of the screen. It can contain title, icons, buttons or some other elements on top of it. There are predefined classes of headers that you can use. You can check all of it in this tutorial." }, { "code": null, "e": 2866, "s": 2691, "text": "The main class for all the bars you might use in your app is bar. This class will always be applied to all the bars in your app. All bar subclasses will use the prefix – bar." }, { "code": null, "e": 3138, "s": 2866, "text": "If you want to create a header, you need to add bar-header after your main bar class. Open your www/index.html file and add the header class inside your body tag. We are adding a header to the index.html body because we want it to be available on every screen in the app." }, { "code": null, "e": 3292, "s": 3138, "text": "Since bar-header class has default (white) styling applied, we will add the title on top of it, so you can differentiate it from the rest of your screen." }, { "code": null, "e": 3365, "s": 3292, "text": "<div class = \"bar bar-header\">\n <h1 class = \"title\">Header</h1>\n</div>" }, { "code": null, "e": 3416, "s": 3365, "text": "The above code will produce the following screen −" }, { "code": null, "e": 3749, "s": 3416, "text": "If you want to style your header, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as prefix to your color class. Since we are styling the header bar, the prefix class will be bar and the color class that we want to use in this example is positive (blue)." }, { "code": null, "e": 3835, "s": 3749, "text": "<div class = \"bar bar-header bar-positive\">\n <h1 class = \"title\">Header</h1>\n</div>" }, { "code": null, "e": 3886, "s": 3835, "text": "The above code will produce the following screen −" }, { "code": null, "e": 3984, "s": 3886, "text": "You can use any of the following nine classes to give a color of your choice to your app header −" }, { "code": null, "e": 4171, "s": 3984, "text": "We can add other elements inside the header. The following code is an example to add a menu button and a home button inside a header. We will also add icons on top of our header buttons." }, { "code": null, "e": 4372, "s": 4171, "text": "<div class = \"bar bar-header bar-positive\">\n <button class = \"button icon ion-navicon\"></button>\n <h1 class = \"title\">Header Buttons</h1>\n <button class = \"button icon ion-home\"></button>\n</div>" }, { "code": null, "e": 4423, "s": 4372, "text": "The above code will produce the following screen −" }, { "code": null, "e": 4656, "s": 4423, "text": "You can create a sub header that will be located just below the header bar. The following example will show how to add a header and a sub header to your app. Here, we have styled the sub header with an \"assertive\" (red) color class." }, { "code": null, "e": 4952, "s": 4656, "text": "<div class = \"bar bar-header bar-positive\">\n <button class = \"button icon ion-navicon\"></button>\n <h1 class = \"title\">Header Buttons</h1>\n <button class = \"button icon ion-home\"></button>\n</div>\n\n<div class = \"bar bar-subheader bar-assertive\">\n <h2 class = \"title\">Sub Header</h2>\n</div>" }, { "code": null, "e": 5003, "s": 4952, "text": "The above code will produce the following screen −" }, { "code": null, "e": 5168, "s": 5003, "text": "When your route is changed to any of the app screens, you will notice that the header and the sub header are covering some content as shown in the screenshot below." }, { "code": null, "e": 5465, "s": 5168, "text": "To fix this you need to add a ‘has-header’ or a ‘has-subheader’ class to the ion-content tags of your screens. Open one of your HTML files from www/templates and add the has-subheader class to the ion-content. If you only use header in your app, you will need to add the has-header class instead." }, { "code": null, "e": 5512, "s": 5465, "text": "<ion-content class = \"padding has-subheader\">\n" }, { "code": null, "e": 5563, "s": 5512, "text": "The above code will produce the following screen −" }, { "code": null, "e": 5598, "s": 5563, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5615, "s": 5598, "text": " Frahaan Hussain" }, { "code": null, "e": 5652, "s": 5615, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 5668, "s": 5652, "text": " Nikhil Agarwal" }, { "code": null, "e": 5675, "s": 5668, "text": " Print" }, { "code": null, "e": 5686, "s": 5675, "text": " Add Notes" } ]
Comments in MATLAB - GeeksforGeeks
20 Aug, 2020 Comments are generic English sentences, mostly written in a program to explain what it does or what a piece of code is supposed to do. More specifically, information that programmer should be concerned with and it has nothing to do with the logic of the code. They are completely ignored by the compiler and are thus never reflected on to the input. In MATLAB, comments are of two types: Single-line Comments Block Comments Spanning MUltiple Lines Single-line comments are comments that require only one line. They are usually drafted to explain what a single line of code does or what it is supposed to produce so that it can help someone to refer to the source code. Use % operator for adding single-line comments. This can be written in a separate line or appended to code on the same line. Syntax : % single line comment Example : MATLAB disp("Below is the comment using %"); % this is a comment Output : Below is the comment using % To make a block comment just put a ‘%{‘ in the starting of the block and ‘%}’ at the end of the block. Syntax: %{ multiline comment %} Example : MATLAB disp("Below is the block comment using %"); %{ this is a comment using % %} Output : Below is the block comment using % Commenting part of a statement spanning multiple lines uses ellipsis (...). Example : MATLAB %{a = [1 2 3]b = 5%} x = ['Matlab is a '...'programming langauge'......'invented by Cleve Moler'...', it is user friendly'] Output : Matlab is a programming language, it is user friendly To comment out the lines of code in a script, press Ctrl + R, to uncomment them press Ctrl + T. MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Copying Files to and from Docker Containers Principal Component Analysis with Python Fuzzy Logic | Introduction OpenCV - Overview Classifying data using Support Vector Machines(SVMs) in Python Getting Started with System Design Mounting a Volume Inside Docker Container Q-Learning in Python How to create a REST API using Java Spring Boot Basics of API Testing Using Postman
[ { "code": null, "e": 23837, "s": 23809, "text": "\n20 Aug, 2020" }, { "code": null, "e": 24187, "s": 23837, "text": "Comments are generic English sentences, mostly written in a program to explain what it does or what a piece of code is supposed to do. More specifically, information that programmer should be concerned with and it has nothing to do with the logic of the code. They are completely ignored by the compiler and are thus never reflected on to the input." }, { "code": null, "e": 24225, "s": 24187, "text": "In MATLAB, comments are of two types:" }, { "code": null, "e": 24246, "s": 24225, "text": "Single-line Comments" }, { "code": null, "e": 24261, "s": 24246, "text": "Block Comments" }, { "code": null, "e": 24285, "s": 24261, "text": "Spanning MUltiple Lines" }, { "code": null, "e": 24631, "s": 24285, "text": "Single-line comments are comments that require only one line. They are usually drafted to explain what a single line of code does or what it is supposed to produce so that it can help someone to refer to the source code. Use % operator for adding single-line comments. This can be written in a separate line or appended to code on the same line." }, { "code": null, "e": 24640, "s": 24631, "text": "Syntax :" }, { "code": null, "e": 24663, "s": 24640, "text": "% single line comment\n" }, { "code": null, "e": 24673, "s": 24663, "text": "Example :" }, { "code": null, "e": 24680, "s": 24673, "text": "MATLAB" }, { "code": "disp(\"Below is the comment using %\"); % this is a comment", "e": 24738, "s": 24680, "text": null }, { "code": null, "e": 24747, "s": 24738, "text": "Output :" }, { "code": null, "e": 24777, "s": 24747, "text": "Below is the comment using %\n" }, { "code": null, "e": 24880, "s": 24777, "text": "To make a block comment just put a ‘%{‘ in the starting of the block and ‘%}’ at the end of the block." }, { "code": null, "e": 24889, "s": 24880, "text": "Syntax: " }, { "code": null, "e": 24914, "s": 24889, "text": "%{\nmultiline\ncomment\n%}\n" }, { "code": null, "e": 24924, "s": 24914, "text": "Example :" }, { "code": null, "e": 24931, "s": 24924, "text": "MATLAB" }, { "code": "disp(\"Below is the block comment using %\"); %{ this is a comment using % %}", "e": 25007, "s": 24931, "text": null }, { "code": null, "e": 25016, "s": 25007, "text": "Output :" }, { "code": null, "e": 25052, "s": 25016, "text": "Below is the block comment using %\n" }, { "code": null, "e": 25129, "s": 25052, "text": "Commenting part of a statement spanning multiple lines uses ellipsis (...). " }, { "code": null, "e": 25139, "s": 25129, "text": "Example :" }, { "code": null, "e": 25146, "s": 25139, "text": "MATLAB" }, { "code": "%{a = [1 2 3]b = 5%} x = ['Matlab is a '...'programming langauge'......'invented by Cleve Moler'...', it is user friendly']", "e": 25271, "s": 25146, "text": null }, { "code": null, "e": 25280, "s": 25271, "text": "Output :" }, { "code": null, "e": 25334, "s": 25280, "text": "Matlab is a programming language, it is user friendly" }, { "code": null, "e": 25431, "s": 25334, "text": "To comment out the lines of code in a script, press Ctrl + R, to uncomment them press Ctrl + T. " }, { "code": null, "e": 25438, "s": 25431, "text": "MATLAB" }, { "code": null, "e": 25464, "s": 25438, "text": "Advanced Computer Subject" }, { "code": null, "e": 25562, "s": 25464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25571, "s": 25562, "text": "Comments" }, { "code": null, "e": 25584, "s": 25571, "text": "Old Comments" }, { "code": null, "e": 25628, "s": 25584, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 25669, "s": 25628, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 25696, "s": 25669, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 25714, "s": 25696, "text": "OpenCV - Overview" }, { "code": null, "e": 25777, "s": 25714, "text": "Classifying data using Support Vector Machines(SVMs) in Python" }, { "code": null, "e": 25812, "s": 25777, "text": "Getting Started with System Design" }, { "code": null, "e": 25854, "s": 25812, "text": "Mounting a Volume Inside Docker Container" }, { "code": null, "e": 25875, "s": 25854, "text": "Q-Learning in Python" }, { "code": null, "e": 25923, "s": 25875, "text": "How to create a REST API using Java Spring Boot" } ]
How to write C functions that modify head pointer of a Linked List? - GeeksforGeeks
09 Nov, 2021 Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other operation that access/update data of nodes It is generally easy to decide the prototype of functions of this category. We can always pass the head pointer as an argument and traverse/update the list. For example, the following function that adds x to data members of all nodes. C void addXtoList(struct Node *node, int x){ while(node != NULL) { node->data = node->data + x; node = node->next; }} 2) Functions that modify the head pointer: Examples include, inserting a node at the beginning (head pointer is always modified in this function), inserting a node at the end (head pointer is modified only when the first node is being inserted), deleting a given node (head pointer is modified when the deleted node is the first node). There may be different ways to update the head pointer in these functions. Let us discuss these ways using the following simple problem: “Given a linked list, write a function deleteFirst() that deletes the first node of a given linked list. For example, if the list is 1->2->3->4, then it should be modified to 2->3->4”The algorithm to solve the problem is a simple 3 step process: (a) Store the head pointer (b) change the head pointer to point to the next node (c) delete the previous head node. Following are different ways to update the head pointer in deleteFirst() so that the list is updated everywhere. 2.1) Make head pointer global: We can make the head pointer global so that it can be accessed and updated in our function. Following is C code that uses a global head pointer. C // global head pointerstruct Node *head = NULL; // function to delete first node: uses approach 2.1// See http://ideone.com/ClfQB for complete program and outputvoid deleteFirst(){ if(head != NULL) { // store the old value of head pointer struct Node *temp = head; // Change head pointer to point to next node head = head->next; // delete memory allocated for the previous head node free(temp); }} See this for a complete running program that uses the above function. This is not a recommended way as it has many problems like the following: a) head is globally accessible, so it can be modified anywhere in your project and may lead to unpredictable results. b) If there are multiple linked lists, then multiple global head pointers with different names are needed. See this to know all reasons why should we avoid global variables in our projects. 2.2) Return head pointer: We can write deletefirst() in such a way that it returns the modified head pointer. Whoever is using this function, has to use the returned value to update the head node. C // function to delete first node: uses approach 2.2// See http://ideone.com/P5oLe for complete program and outputstruct Node *deleteFirst(struct Node *head){ if(head != NULL) { // store the old value of head pointer struct Node *temp = head; // Change head pointer to point to next node head = head->next; // delete memory allocated for the previous head node free(temp); } return head;} See this for complete program and output. This approach is much better than the previous 1. There is only one issue with this, if the user misses assigning the returned value to the head, then things become messy. C/C++ compilers allow calling a function without assigning the returned value. C head = deleteFirst(head); // proper use of deleteFirst()deleteFirst(head); // improper use of deleteFirst(), allowed by compiler 2.3) Use Double Pointer: This approach follows the simple C rule: if you want to modify the local variable of one function inside another function, pass a pointer to that variable. So we can pass the pointer to the head pointer to modify the head pointer in our deletefirst() function. C // function to delete first node: uses approach 2.3// See http://ideone.com/9GwTb for complete program and outputvoid deleteFirst(struct Node **head_ref){ if(*head_ref != NULL) { // store the old value of pointer to head pointer struct Node *temp = *head_ref; // Change head pointer to point to next node *head_ref = (*head_ref)->next; // delete memory allocated for the previous head node free(temp); }} See this for complete program and output. This approach seems to be the best among all three as there are fewer chances of having problems. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. niharikatanwar61 cpp-double-pointer cpp-pointer Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Singly Linked List | Insertion Delete a node in a Doubly Linked List Swap nodes in a linked list without swapping data Given a linked list which is sorted, how will you insert in sorted way Circular Linked List | Set 2 (Traversal) Insert a node at a specific position in a linked list Program to implement Singly Linked List in C++ using class Priority Queue using Linked List Insertion Sort for Singly Linked List Real-time application of Data Structures
[ { "code": null, "e": 24958, "s": 24930, "text": "\n09 Nov, 2021" }, { "code": null, "e": 25110, "s": 24958, "text": "Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories:" }, { "code": null, "e": 25583, "s": 25110, "text": "1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other operation that access/update data of nodes It is generally easy to decide the prototype of functions of this category. We can always pass the head pointer as an argument and traverse/update the list. For example, the following function that adds x to data members of all nodes." }, { "code": null, "e": 25585, "s": 25583, "text": "C" }, { "code": "void addXtoList(struct Node *node, int x){ while(node != NULL) { node->data = node->data + x; node = node->next; }} ", "e": 25727, "s": 25585, "text": null }, { "code": null, "e": 26200, "s": 25727, "text": "2) Functions that modify the head pointer: Examples include, inserting a node at the beginning (head pointer is always modified in this function), inserting a node at the end (head pointer is modified only when the first node is being inserted), deleting a given node (head pointer is modified when the deleted node is the first node). There may be different ways to update the head pointer in these functions. Let us discuss these ways using the following simple problem:" }, { "code": null, "e": 26563, "s": 26200, "text": "“Given a linked list, write a function deleteFirst() that deletes the first node of a given linked list. For example, if the list is 1->2->3->4, then it should be modified to 2->3->4”The algorithm to solve the problem is a simple 3 step process: (a) Store the head pointer (b) change the head pointer to point to the next node (c) delete the previous head node. " }, { "code": null, "e": 26676, "s": 26563, "text": "Following are different ways to update the head pointer in deleteFirst() so that the list is updated everywhere." }, { "code": null, "e": 26852, "s": 26676, "text": "2.1) Make head pointer global: We can make the head pointer global so that it can be accessed and updated in our function. Following is C code that uses a global head pointer." }, { "code": null, "e": 26854, "s": 26852, "text": "C" }, { "code": "// global head pointerstruct Node *head = NULL; // function to delete first node: uses approach 2.1// See http://ideone.com/ClfQB for complete program and outputvoid deleteFirst(){ if(head != NULL) { // store the old value of head pointer struct Node *temp = head; // Change head pointer to point to next node head = head->next; // delete memory allocated for the previous head node free(temp); }}", "e": 27309, "s": 26854, "text": null }, { "code": null, "e": 27379, "s": 27309, "text": "See this for a complete running program that uses the above function." }, { "code": null, "e": 27678, "s": 27379, "text": "This is not a recommended way as it has many problems like the following: a) head is globally accessible, so it can be modified anywhere in your project and may lead to unpredictable results. b) If there are multiple linked lists, then multiple global head pointers with different names are needed." }, { "code": null, "e": 27762, "s": 27678, "text": "See this to know all reasons why should we avoid global variables in our projects. " }, { "code": null, "e": 27960, "s": 27762, "text": "2.2) Return head pointer: We can write deletefirst() in such a way that it returns the modified head pointer. Whoever is using this function, has to use the returned value to update the head node. " }, { "code": null, "e": 27962, "s": 27960, "text": "C" }, { "code": "// function to delete first node: uses approach 2.2// See http://ideone.com/P5oLe for complete program and outputstruct Node *deleteFirst(struct Node *head){ if(head != NULL) { // store the old value of head pointer struct Node *temp = head; // Change head pointer to point to next node head = head->next; // delete memory allocated for the previous head node free(temp); } return head;}", "e": 28401, "s": 27962, "text": null }, { "code": null, "e": 28695, "s": 28401, "text": "See this for complete program and output. This approach is much better than the previous 1. There is only one issue with this, if the user misses assigning the returned value to the head, then things become messy. C/C++ compilers allow calling a function without assigning the returned value. " }, { "code": null, "e": 28697, "s": 28695, "text": "C" }, { "code": "head = deleteFirst(head); // proper use of deleteFirst()deleteFirst(head); // improper use of deleteFirst(), allowed by compiler", "e": 28828, "s": 28697, "text": null }, { "code": null, "e": 29115, "s": 28828, "text": "2.3) Use Double Pointer: This approach follows the simple C rule: if you want to modify the local variable of one function inside another function, pass a pointer to that variable. So we can pass the pointer to the head pointer to modify the head pointer in our deletefirst() function. " }, { "code": null, "e": 29117, "s": 29115, "text": "C" }, { "code": "// function to delete first node: uses approach 2.3// See http://ideone.com/9GwTb for complete program and outputvoid deleteFirst(struct Node **head_ref){ if(*head_ref != NULL) { // store the old value of pointer to head pointer struct Node *temp = *head_ref; // Change head pointer to point to next node *head_ref = (*head_ref)->next; // delete memory allocated for the previous head node free(temp); }}", "e": 29569, "s": 29117, "text": null }, { "code": null, "e": 29835, "s": 29569, "text": "See this for complete program and output. This approach seems to be the best among all three as there are fewer chances of having problems. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29852, "s": 29835, "text": "niharikatanwar61" }, { "code": null, "e": 29871, "s": 29852, "text": "cpp-double-pointer" }, { "code": null, "e": 29883, "s": 29871, "text": "cpp-pointer" }, { "code": null, "e": 29895, "s": 29883, "text": "Linked List" }, { "code": null, "e": 29907, "s": 29895, "text": "Linked List" }, { "code": null, "e": 30005, "s": 29907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30045, "s": 30005, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 30083, "s": 30045, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 30133, "s": 30083, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 30204, "s": 30133, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 30245, "s": 30204, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 30299, "s": 30245, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 30358, "s": 30299, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 30391, "s": 30358, "text": "Priority Queue using Linked List" }, { "code": null, "e": 30429, "s": 30391, "text": "Insertion Sort for Singly Linked List" } ]
Graph Minimum Spanning Tree - GeeksforGeeks
19 Nov, 2018 v1 \ v2 \ v3 \ v4 . . . vn there is one counter example when the graph has only one edge. In that case, the two values are same. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies Get Hired With GeeksforGeeks and Win Exciting Rewards! Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? How to Replace Values in a List in Python? How to Concat Two Columns Into One With the Existing Column Name in MySQL?
[ { "code": null, "e": 27610, "s": 27582, "text": "\n19 Nov, 2018" }, { "code": null, "e": 27736, "s": 27610, "text": "v1\n \\\n v2\n \\\n v3\n \\\n v4\n .\n .\n .\n vn\n " }, { "code": null, "e": 27850, "s": 27736, "text": "there is one counter example when the graph has only one edge. \n In that case, the two values are same. " }, { "code": null, "e": 27948, "s": 27850, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 28001, "s": 27948, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28056, "s": 28001, "text": "Get Hired With GeeksforGeeks and Win Exciting Rewards!" }, { "code": null, "e": 28117, "s": 28056, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28155, "s": 28117, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28217, "s": 28155, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28297, "s": 28217, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 28338, "s": 28297, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28418, "s": 28338, "text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?" }, { "code": null, "e": 28461, "s": 28418, "text": "How to Replace Values in a List in Python?" } ]
A definitive guide to effect size | by Eryk Lewinson | Towards Data Science
As a data scientist, you will most likely come across the effect size while working on some kind of A/B testing. A possible scenario is that the company wants to make a change to the product (be it a website, mobile app, etc.) and your task is to make sure that the change will — to some degree of certainty — result in better performance in terms of the specified KPI. This is when hypothesis testing comes into play. However, a statistical test can only inform about the likelihood that an effect exists. By effect, I simply mean a difference — it can just be a difference in either direction, but it can also be a more precise variant of a hypothesis stating that one sample is actually better/worse than the other one (in terms of the given metric). And to know how big the effect is, we need to calculate the effect size. In this article, I will provide a brief theoretical introduction to the effect size and then show some practical examples of how to calculate it in Python. Formally, the effect size is the quantified magnitude of a phenomenon we are investigating. As mentioned before, statistical tests result in the probability of observing an effect, however, they do not specify how big the effect actually is. This can lead to situations in which we detect a statistically significant effect, but it is actually so small that for the practical case (business) it is negligible and not interesting at all. Additionally, when planning A/B tests, we want to estimate the expected duration of the test. This is connected to the topic of power analysis, which I covered in another article. To quickly summarize it, in order to calculate the required sample size, we need to specify three things: the significance level, the power of the test, and the effect size. Keeping the other two constant, the smaller the effect size, the harder it is to detect it with some kind of certainty, thus the larger is the required sample size for the statistical test. In general, there are potentially hundreds of different measures of the effect size, each one with some advantages and drawbacks. In this article, I will present only a selection of the most popular ones. Before diving deeper into the rabbit hole, the measures of the effect size can be grouped into 3 categories, based on their approach to defining the effect. The groups are: Metrics based on the correlation Metrics based on differences (for example, between means) Metrics for categorical variables The first two families cover continuous random variables, while the last one is used for categorical/binary features. To give a real-life example, we could apply the first two to a metric such as time spent in an app (in minutes), while the third family could be used for conversion or retention — expressed as a boolean. I will describe some of the measures of effect size below, together with the Python implementation. In this part, I will describe more in detail a few examples from each of the effect size families and show how to calculate them in Python using popular libraries. Of course, we could just as well code these functions ourselves, but I do believe there is no need for reinventing the wheel. As the first step, we need to import the required libraries: The name of this group (also known as the “r family”) comes from the measure of association between two variables — correlation. And by far the most popular measure of correlation is the Pearson’s correlation coefficient (Pearson’s r). Before diving into the metrics, we will generate some random, correlated variables coming from the multivariate Normal distribution. They have different means, so we can actually detect some effect, while we keep the variance at 1 for simplicity. Remember that the more random observations we generate, the more their distribution will resemble the one we specified. Pearson’s r This should not come as a surprise, as the name of the family is based on this metric. Pearson’s correlation coefficient measures the degree of linear association between two real-valued variables. The metric is unit-free and is expressed as a number in the range of [-1, 1]. For brevity, I will only describe the interpretation of extreme cases: a value of -1 indicates a perfect negative relationship between variables, a value of 0 indicates no linear relationship, a value of 1 indicates a perfect positive relationship. As this is one of the most commonly used metrics in general, there are many ways to calculate the correlation coefficient in Python: pearsonr in scipy.stats — in addition to the correlation coefficient, we also receive the p-value of the correlation test. Quoting the documentation: “The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.” stats.pearsonr(x[:,0], x[:,1])# (0.6023670412294826, 0.0) numpy.corrcoef — returns the correlation matrix, use rowvar to indicate whether the observations of the random variables are stored in rows or columns. np.corrcoef(x, rowvar=False)# array([[1. , 0.60236704],# [0.60236704, 1. ]]) the corr method of a pandas DataFrame/Series. pingouin’s corr function — by default it returns the Pearson’s r coefficient (other measures of correlation are also available). In contrast to scipy, the function returns a bit more detailed results of the correlation test. We can also use the one-sided variant of the test. pg.corr(x[:, 0], x[:, 1]) Coefficient of determination (R2) The second measure of the effect size in this family is the coefficient of determination, also known as R2. It states what proportion of the dependent variable’s variance is explained (predictable) by the independent variable(s). In other words, it is a measure of how well the observed outcomes are replicated by the model. There are several definitions of the coefficient of determination, however, the most relevant one for us right now is the one connected to Pearson’s r. When using simple linear regression (with one dependent variable) with the intercept included, the coefficient of determination is simply the square of the Pearson's r. If there are more dependent variables, the R2 is the square of the coefficient of multiple correlation. In either of the mentioned cases, the coefficient of determination normally covers the range between 0 and 1. However, if another definition is used, the values can become negative as well. Due to the fact that we square the correlation coefficient, the coefficient of determination does not convey any information about the direction of the correlation. We can calculate the coefficient of determination by running simple linear regression and inspecting the reported value: using pingouin: pg.linear_regression(x[:, 0], x[:, 1]) using statsmodels: In both cases, the coefficient of determination is close to 0.36, which is the square of the correlation coefficient (0.6). Eta-squared (η2) The last considered metric in this family is the eta-squared. It is a ratio of variance explained in the dependent variable by a predictor while controlling for other predictors, which makes it similar to the r2. where SS stands for the sum of squares. η2 is a biased estimator of the population’s variance explained by the model, as it only estimates the effect size in the considered sample. This means that eta-squared will always overestimate the actual effect size, although this bias becomes smaller as the sample size grows. Eta-squared also shares the weakness of r2 — each additional variable automatically increases the value of η2. To calculate eta-squared in Python, we can use the pingouin library: pg.compute_effsize(x[:, 0], x[:, 1], eftype='eta-square')# 0.057968511053166284 Additionally, the library contains a useful function called convert_effsize, which allows us to convert the effect size measured by Pearson’s r or Cohen’s d into, among others, eta-squared. The second family is called the difference family, after perhaps the most common method of measuring the effect size — calculating the difference between the mean values of the samples. Usually, that difference is also standardized by dividing it by the standard deviation (of either or both populations). In practice, the population values are not known and have to be estimated from sample statistics. That is why there are multiple methods for calculating the effect size as the difference between means — they differ in terms of which sample statistics they use. On a side note, such a form of estimating the effect size resembles calculating the t-statistic, with the difference being dividing the standard deviation by the square root of n in the t-statistic’s denominator. Unlike the t-statistic, the effect size aims to estimate a population-level value and is not affected by the sample size. This family is also known as the “d family”, named after the most common method of estimating the effect size as a difference between means — Cohen’s d. Before diving into the metrics, we define two random variables coming from the Normal distribution. We use different means and standard deviations to make sure that the variables differ enough to obtain reasonable effect sizes. Cohen’s d Cohen’s d measures the difference between the means of two variables. The difference is expressed in terms of the number of standard deviations, hence the division in the formula. Cohen’s d is defined as: where s is the pooled standard deviation and s_1, s_2 are standard deviations of the two independent samples. Note: Some sources use a different formulation of the pooled standard deviation and do not include the -2 in the denominator. The most common interpretation of the magnitude of the effect size is as follows: Small Effect Size: d=0.2 Medium Effect Size: d=0.5 Large Effect Size: d=0.8 Cohen’s d is very frequently used in estimating the required sample size for an A/B test. In general, a lower value of Cohen’s d indicates the necessity of a larger sample size and vice versa. The easiest way to calculate the Cohen’s d in Python is to use the the pingouin library: pg.compute_effsize(x, y, eftype='cohen')# -0.5661743543595718 Glass’ Δ is very similar to Cohen’s d, with the difference that the standard deviation of the second sample (the control group in an A/B test) is used instead of the pooled standard deviation. The rationale for using only the standard deviation of the control group was based on the fact that if we were to compare multiple treatment groups to the same control, this way we would have the common denominator in all the cases. pg.compute_effsize(x, y, eftype='glass')# -0.6664041092152272 Hedge’s g Cohen’s d is a biased estimator of the population-level effect size, especially for small samples (n < 20). That is why Hedge’s g corrects for that by multiplying the Cohen’s d by a correction factor (based on the gamma functions): pg.compute_effsize(x, y, eftype='hedges')# -0.5661722311818571 We can see that the difference between Cohen’s d and Hedge’s g is very small. It would be more pronounced for smaller sample sizes. This family is used for estimating the effect size of categorical (and in some simpler cases — binary) random variables. We generate the random variables for this section by running the following snippet: φ (phi coefficient) The phi coefficient is a measure of association between two binary variables introduced by Karl Pearson, and is related to the chi-squared statistic of a 2x2 contingency table. In machine learning terms, a contingency table is basically the same as the confusion matrix. Two binary random variables are positively associated when most of the data falls along the diagonal of the contingency table (think about true positives and true negatives). Conversely, the variables are negatively associated when most of the data falls off the diagonal (think about false positives and false negatives). As a matter of fact, the Pearson’s correlation coefficient (r) calculated for two binary variables will result in the phi coefficient (we will prove that in Python). However, the range of the phi coefficient is different from the correlation coefficient, especially when at least one of the variables takes more than two values. What is more, in machine learning we see the increasing popularity of the Matthews correlation coefficient as a measure of evaluating the performance of classification models. In fact, the MCC is nothing else as Pearson’s phi coefficient. Phi/MCC considers all the elements of the confusion matrix/contingency table, that is why it is considered a balanced evaluation metric that can also be used in cases of class imbalance. Running the code results in the following output: Phi coefficient: 0.000944Matthews Correlation: 0.000944Pearson's r: 0.000944 Cramér’s V Cramér’s V is another measure of association between categorical variables (not restricted to the binary case). where k and r stand for the number of columns and rows in the contingency table and φ is the phi coefficient as calculated above. Cramér’s V takes a value in the range of 0 (no association between the variables) and 1 (complete association). Note that for the case of a 2x2 contingency table (two binary variables), Cramér’s V is equal to the phi coefficient, as we will soon see in practice. The most common interpretation of the magnitude of the Cramér’s V is as follows: Small Effect Size: V ≤ 0.2 Medium Effect Size: 0.2 < V ≤ 0.6 Large Effect Size: 0.6 < V Cramer's V: 0.000944 We have indeed obtained the same value as in the case of the phi coefficient. Cohen’s w Cohen suggested another measure of the effect size, which “increases with the degree of discrepancy between the distribution specified by the alternate hypothesis and that which represents the null hypothesis” (for more details, see page 216 in [1]). In this case, we are dealing with proportions (so fractions of all observations), in contrast to the contingency tables for the previous metrics. where: p_{0i} — the proportion in cell i under the null hypothesis, p_{1i} — the proportion in cell i under the alternative hypothesis, m — number of cells. The effect size measured by Cohen’s w is considered small for values close to 0.1, medium for around 0.3, and large for around 0.5. Cohen's w: 0.173820 Cohen’s h Another measure used for comparing proportions from two independent samples is Cohen’s h, defined as follows: where p_1 stands for the proportion of the positive cases in the first sample. To assess the magnitude of the effect size, the author suggests the same range of indicative values as in the case of Cohen’s d. Cohen's h: 0.174943 Odds Ratio The effect size measured by the odds ratio is computed by noting that the odds of an event happening in the treatment group are X times higher/lower than in the control group. Odds Ratio: 1.374506 The odds of an event (for example conversion) happening are ~1.37 times higher in the x group than in the y one, which is in line with the probabilities provided while generating the data. The last metric is quite interesting, because — as the name suggests — it aims to express the effect size in a plain language understood by everyone. Also, it does not belong to the families mentioned above. The authors described this metric in [2] as: the probability that a score sampled at random from one distribution will be greater than a score sampled from some other distribution. To make the description as clear as possible, I will paraphrase the example mentioned in the paper. Imagine that we have a sample of heights of adult men and women, and the CLES is 0.8. This would mean that in 80% of randomly selected pairs, the man will be higher than the women. Or to put it differently, in 8 out of 10 blind dates, the man will be higher than the woman. In this article, I introduced different measures of the effect size and showed how to calculate them in Python. Knowing these, or at the very least one key metric per family, will definitely come in handy while planning A/B tests using the frequentist approach. You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. In case you found this article interesting, you might also like: towardsdatascience.com towardsdatascience.com towardsdatascience.com [1] Cohen, J. (2013). Statistical power analysis for the behavioral sciences. Academic press. [2] McGraw, K. O., & Wong, S. P. (1992). A common language effect size statistic. Psychological Bulletin, 111(2), 361–365. https://doi.org/10.1037/0033-2909.111.2.361
[ { "code": null, "e": 417, "s": 47, "text": "As a data scientist, you will most likely come across the effect size while working on some kind of A/B testing. A possible scenario is that the company wants to make a change to the product (be it a website, mobile app, etc.) and your task is to make sure that the change will — to some degree of certainty — result in better performance in terms of the specified KPI." }, { "code": null, "e": 874, "s": 417, "text": "This is when hypothesis testing comes into play. However, a statistical test can only inform about the likelihood that an effect exists. By effect, I simply mean a difference — it can just be a difference in either direction, but it can also be a more precise variant of a hypothesis stating that one sample is actually better/worse than the other one (in terms of the given metric). And to know how big the effect is, we need to calculate the effect size." }, { "code": null, "e": 1030, "s": 874, "text": "In this article, I will provide a brief theoretical introduction to the effect size and then show some practical examples of how to calculate it in Python." }, { "code": null, "e": 1467, "s": 1030, "text": "Formally, the effect size is the quantified magnitude of a phenomenon we are investigating. As mentioned before, statistical tests result in the probability of observing an effect, however, they do not specify how big the effect actually is. This can lead to situations in which we detect a statistically significant effect, but it is actually so small that for the practical case (business) it is negligible and not interesting at all." }, { "code": null, "e": 2011, "s": 1467, "text": "Additionally, when planning A/B tests, we want to estimate the expected duration of the test. This is connected to the topic of power analysis, which I covered in another article. To quickly summarize it, in order to calculate the required sample size, we need to specify three things: the significance level, the power of the test, and the effect size. Keeping the other two constant, the smaller the effect size, the harder it is to detect it with some kind of certainty, thus the larger is the required sample size for the statistical test." }, { "code": null, "e": 2389, "s": 2011, "text": "In general, there are potentially hundreds of different measures of the effect size, each one with some advantages and drawbacks. In this article, I will present only a selection of the most popular ones. Before diving deeper into the rabbit hole, the measures of the effect size can be grouped into 3 categories, based on their approach to defining the effect. The groups are:" }, { "code": null, "e": 2422, "s": 2389, "text": "Metrics based on the correlation" }, { "code": null, "e": 2480, "s": 2422, "text": "Metrics based on differences (for example, between means)" }, { "code": null, "e": 2514, "s": 2480, "text": "Metrics for categorical variables" }, { "code": null, "e": 2836, "s": 2514, "text": "The first two families cover continuous random variables, while the last one is used for categorical/binary features. To give a real-life example, we could apply the first two to a metric such as time spent in an app (in minutes), while the third family could be used for conversion or retention — expressed as a boolean." }, { "code": null, "e": 2936, "s": 2836, "text": "I will describe some of the measures of effect size below, together with the Python implementation." }, { "code": null, "e": 3226, "s": 2936, "text": "In this part, I will describe more in detail a few examples from each of the effect size families and show how to calculate them in Python using popular libraries. Of course, we could just as well code these functions ourselves, but I do believe there is no need for reinventing the wheel." }, { "code": null, "e": 3287, "s": 3226, "text": "As the first step, we need to import the required libraries:" }, { "code": null, "e": 3523, "s": 3287, "text": "The name of this group (also known as the “r family”) comes from the measure of association between two variables — correlation. And by far the most popular measure of correlation is the Pearson’s correlation coefficient (Pearson’s r)." }, { "code": null, "e": 3770, "s": 3523, "text": "Before diving into the metrics, we will generate some random, correlated variables coming from the multivariate Normal distribution. They have different means, so we can actually detect some effect, while we keep the variance at 1 for simplicity." }, { "code": null, "e": 3890, "s": 3770, "text": "Remember that the more random observations we generate, the more their distribution will resemble the one we specified." }, { "code": null, "e": 3902, "s": 3890, "text": "Pearson’s r" }, { "code": null, "e": 4249, "s": 3902, "text": "This should not come as a surprise, as the name of the family is based on this metric. Pearson’s correlation coefficient measures the degree of linear association between two real-valued variables. The metric is unit-free and is expressed as a number in the range of [-1, 1]. For brevity, I will only describe the interpretation of extreme cases:" }, { "code": null, "e": 4324, "s": 4249, "text": "a value of -1 indicates a perfect negative relationship between variables," }, { "code": null, "e": 4371, "s": 4324, "text": "a value of 0 indicates no linear relationship," }, { "code": null, "e": 4427, "s": 4371, "text": "a value of 1 indicates a perfect positive relationship." }, { "code": null, "e": 4560, "s": 4427, "text": "As this is one of the most commonly used metrics in general, there are many ways to calculate the correlation coefficient in Python:" }, { "code": null, "e": 4896, "s": 4560, "text": "pearsonr in scipy.stats — in addition to the correlation coefficient, we also receive the p-value of the correlation test. Quoting the documentation: “The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.”" }, { "code": null, "e": 4954, "s": 4896, "text": "stats.pearsonr(x[:,0], x[:,1])# (0.6023670412294826, 0.0)" }, { "code": null, "e": 5106, "s": 4954, "text": "numpy.corrcoef — returns the correlation matrix, use rowvar to indicate whether the observations of the random variables are stored in rows or columns." }, { "code": null, "e": 5204, "s": 5106, "text": "np.corrcoef(x, rowvar=False)# array([[1. , 0.60236704],# [0.60236704, 1. ]])" }, { "code": null, "e": 5250, "s": 5204, "text": "the corr method of a pandas DataFrame/Series." }, { "code": null, "e": 5526, "s": 5250, "text": "pingouin’s corr function — by default it returns the Pearson’s r coefficient (other measures of correlation are also available). In contrast to scipy, the function returns a bit more detailed results of the correlation test. We can also use the one-sided variant of the test." }, { "code": null, "e": 5552, "s": 5526, "text": "pg.corr(x[:, 0], x[:, 1])" }, { "code": null, "e": 5586, "s": 5552, "text": "Coefficient of determination (R2)" }, { "code": null, "e": 5911, "s": 5586, "text": "The second measure of the effect size in this family is the coefficient of determination, also known as R2. It states what proportion of the dependent variable’s variance is explained (predictable) by the independent variable(s). In other words, it is a measure of how well the observed outcomes are replicated by the model." }, { "code": null, "e": 6336, "s": 5911, "text": "There are several definitions of the coefficient of determination, however, the most relevant one for us right now is the one connected to Pearson’s r. When using simple linear regression (with one dependent variable) with the intercept included, the coefficient of determination is simply the square of the Pearson's r. If there are more dependent variables, the R2 is the square of the coefficient of multiple correlation." }, { "code": null, "e": 6691, "s": 6336, "text": "In either of the mentioned cases, the coefficient of determination normally covers the range between 0 and 1. However, if another definition is used, the values can become negative as well. Due to the fact that we square the correlation coefficient, the coefficient of determination does not convey any information about the direction of the correlation." }, { "code": null, "e": 6812, "s": 6691, "text": "We can calculate the coefficient of determination by running simple linear regression and inspecting the reported value:" }, { "code": null, "e": 6828, "s": 6812, "text": "using pingouin:" }, { "code": null, "e": 6867, "s": 6828, "text": "pg.linear_regression(x[:, 0], x[:, 1])" }, { "code": null, "e": 6886, "s": 6867, "text": "using statsmodels:" }, { "code": null, "e": 7010, "s": 6886, "text": "In both cases, the coefficient of determination is close to 0.36, which is the square of the correlation coefficient (0.6)." }, { "code": null, "e": 7027, "s": 7010, "text": "Eta-squared (η2)" }, { "code": null, "e": 7240, "s": 7027, "text": "The last considered metric in this family is the eta-squared. It is a ratio of variance explained in the dependent variable by a predictor while controlling for other predictors, which makes it similar to the r2." }, { "code": null, "e": 7670, "s": 7240, "text": "where SS stands for the sum of squares. η2 is a biased estimator of the population’s variance explained by the model, as it only estimates the effect size in the considered sample. This means that eta-squared will always overestimate the actual effect size, although this bias becomes smaller as the sample size grows. Eta-squared also shares the weakness of r2 — each additional variable automatically increases the value of η2." }, { "code": null, "e": 7739, "s": 7670, "text": "To calculate eta-squared in Python, we can use the pingouin library:" }, { "code": null, "e": 7819, "s": 7739, "text": "pg.compute_effsize(x[:, 0], x[:, 1], eftype='eta-square')# 0.057968511053166284" }, { "code": null, "e": 8009, "s": 7819, "text": "Additionally, the library contains a useful function called convert_effsize, which allows us to convert the effect size measured by Pearson’s r or Cohen’s d into, among others, eta-squared." }, { "code": null, "e": 8315, "s": 8009, "text": "The second family is called the difference family, after perhaps the most common method of measuring the effect size — calculating the difference between the mean values of the samples. Usually, that difference is also standardized by dividing it by the standard deviation (of either or both populations)." }, { "code": null, "e": 8576, "s": 8315, "text": "In practice, the population values are not known and have to be estimated from sample statistics. That is why there are multiple methods for calculating the effect size as the difference between means — they differ in terms of which sample statistics they use." }, { "code": null, "e": 8911, "s": 8576, "text": "On a side note, such a form of estimating the effect size resembles calculating the t-statistic, with the difference being dividing the standard deviation by the square root of n in the t-statistic’s denominator. Unlike the t-statistic, the effect size aims to estimate a population-level value and is not affected by the sample size." }, { "code": null, "e": 9064, "s": 8911, "text": "This family is also known as the “d family”, named after the most common method of estimating the effect size as a difference between means — Cohen’s d." }, { "code": null, "e": 9292, "s": 9064, "text": "Before diving into the metrics, we define two random variables coming from the Normal distribution. We use different means and standard deviations to make sure that the variables differ enough to obtain reasonable effect sizes." }, { "code": null, "e": 9302, "s": 9292, "text": "Cohen’s d" }, { "code": null, "e": 9507, "s": 9302, "text": "Cohen’s d measures the difference between the means of two variables. The difference is expressed in terms of the number of standard deviations, hence the division in the formula. Cohen’s d is defined as:" }, { "code": null, "e": 9617, "s": 9507, "text": "where s is the pooled standard deviation and s_1, s_2 are standard deviations of the two independent samples." }, { "code": null, "e": 9743, "s": 9617, "text": "Note: Some sources use a different formulation of the pooled standard deviation and do not include the -2 in the denominator." }, { "code": null, "e": 9825, "s": 9743, "text": "The most common interpretation of the magnitude of the effect size is as follows:" }, { "code": null, "e": 9850, "s": 9825, "text": "Small Effect Size: d=0.2" }, { "code": null, "e": 9876, "s": 9850, "text": "Medium Effect Size: d=0.5" }, { "code": null, "e": 9901, "s": 9876, "text": "Large Effect Size: d=0.8" }, { "code": null, "e": 10094, "s": 9901, "text": "Cohen’s d is very frequently used in estimating the required sample size for an A/B test. In general, a lower value of Cohen’s d indicates the necessity of a larger sample size and vice versa." }, { "code": null, "e": 10183, "s": 10094, "text": "The easiest way to calculate the Cohen’s d in Python is to use the the pingouin library:" }, { "code": null, "e": 10245, "s": 10183, "text": "pg.compute_effsize(x, y, eftype='cohen')# -0.5661743543595718" }, { "code": null, "e": 10438, "s": 10245, "text": "Glass’ Δ is very similar to Cohen’s d, with the difference that the standard deviation of the second sample (the control group in an A/B test) is used instead of the pooled standard deviation." }, { "code": null, "e": 10671, "s": 10438, "text": "The rationale for using only the standard deviation of the control group was based on the fact that if we were to compare multiple treatment groups to the same control, this way we would have the common denominator in all the cases." }, { "code": null, "e": 10733, "s": 10671, "text": "pg.compute_effsize(x, y, eftype='glass')# -0.6664041092152272" }, { "code": null, "e": 10743, "s": 10733, "text": "Hedge’s g" }, { "code": null, "e": 10975, "s": 10743, "text": "Cohen’s d is a biased estimator of the population-level effect size, especially for small samples (n < 20). That is why Hedge’s g corrects for that by multiplying the Cohen’s d by a correction factor (based on the gamma functions):" }, { "code": null, "e": 11038, "s": 10975, "text": "pg.compute_effsize(x, y, eftype='hedges')# -0.5661722311818571" }, { "code": null, "e": 11170, "s": 11038, "text": "We can see that the difference between Cohen’s d and Hedge’s g is very small. It would be more pronounced for smaller sample sizes." }, { "code": null, "e": 11375, "s": 11170, "text": "This family is used for estimating the effect size of categorical (and in some simpler cases — binary) random variables. We generate the random variables for this section by running the following snippet:" }, { "code": null, "e": 11395, "s": 11375, "text": "φ (phi coefficient)" }, { "code": null, "e": 11666, "s": 11395, "text": "The phi coefficient is a measure of association between two binary variables introduced by Karl Pearson, and is related to the chi-squared statistic of a 2x2 contingency table. In machine learning terms, a contingency table is basically the same as the confusion matrix." }, { "code": null, "e": 11989, "s": 11666, "text": "Two binary random variables are positively associated when most of the data falls along the diagonal of the contingency table (think about true positives and true negatives). Conversely, the variables are negatively associated when most of the data falls off the diagonal (think about false positives and false negatives)." }, { "code": null, "e": 12318, "s": 11989, "text": "As a matter of fact, the Pearson’s correlation coefficient (r) calculated for two binary variables will result in the phi coefficient (we will prove that in Python). However, the range of the phi coefficient is different from the correlation coefficient, especially when at least one of the variables takes more than two values." }, { "code": null, "e": 12557, "s": 12318, "text": "What is more, in machine learning we see the increasing popularity of the Matthews correlation coefficient as a measure of evaluating the performance of classification models. In fact, the MCC is nothing else as Pearson’s phi coefficient." }, { "code": null, "e": 12744, "s": 12557, "text": "Phi/MCC considers all the elements of the confusion matrix/contingency table, that is why it is considered a balanced evaluation metric that can also be used in cases of class imbalance." }, { "code": null, "e": 12794, "s": 12744, "text": "Running the code results in the following output:" }, { "code": null, "e": 12871, "s": 12794, "text": "Phi coefficient: 0.000944Matthews Correlation: 0.000944Pearson's r: 0.000944" }, { "code": null, "e": 12883, "s": 12871, "text": "Cramér’s V" }, { "code": null, "e": 12996, "s": 12883, "text": "Cramér’s V is another measure of association between categorical variables (not restricted to the binary case)." }, { "code": null, "e": 13126, "s": 12996, "text": "where k and r stand for the number of columns and rows in the contingency table and φ is the phi coefficient as calculated above." }, { "code": null, "e": 13391, "s": 13126, "text": "Cramér’s V takes a value in the range of 0 (no association between the variables) and 1 (complete association). Note that for the case of a 2x2 contingency table (two binary variables), Cramér’s V is equal to the phi coefficient, as we will soon see in practice." }, { "code": null, "e": 13473, "s": 13391, "text": "The most common interpretation of the magnitude of the Cramér’s V is as follows:" }, { "code": null, "e": 13500, "s": 13473, "text": "Small Effect Size: V ≤ 0.2" }, { "code": null, "e": 13534, "s": 13500, "text": "Medium Effect Size: 0.2 < V ≤ 0.6" }, { "code": null, "e": 13561, "s": 13534, "text": "Large Effect Size: 0.6 < V" }, { "code": null, "e": 13582, "s": 13561, "text": "Cramer's V: 0.000944" }, { "code": null, "e": 13660, "s": 13582, "text": "We have indeed obtained the same value as in the case of the phi coefficient." }, { "code": null, "e": 13670, "s": 13660, "text": "Cohen’s w" }, { "code": null, "e": 14067, "s": 13670, "text": "Cohen suggested another measure of the effect size, which “increases with the degree of discrepancy between the distribution specified by the alternate hypothesis and that which represents the null hypothesis” (for more details, see page 216 in [1]). In this case, we are dealing with proportions (so fractions of all observations), in contrast to the contingency tables for the previous metrics." }, { "code": null, "e": 14074, "s": 14067, "text": "where:" }, { "code": null, "e": 14135, "s": 14074, "text": "p_{0i} — the proportion in cell i under the null hypothesis," }, { "code": null, "e": 14203, "s": 14135, "text": "p_{1i} — the proportion in cell i under the alternative hypothesis," }, { "code": null, "e": 14224, "s": 14203, "text": "m — number of cells." }, { "code": null, "e": 14356, "s": 14224, "text": "The effect size measured by Cohen’s w is considered small for values close to 0.1, medium for around 0.3, and large for around 0.5." }, { "code": null, "e": 14376, "s": 14356, "text": "Cohen's w: 0.173820" }, { "code": null, "e": 14386, "s": 14376, "text": "Cohen’s h" }, { "code": null, "e": 14496, "s": 14386, "text": "Another measure used for comparing proportions from two independent samples is Cohen’s h, defined as follows:" }, { "code": null, "e": 14704, "s": 14496, "text": "where p_1 stands for the proportion of the positive cases in the first sample. To assess the magnitude of the effect size, the author suggests the same range of indicative values as in the case of Cohen’s d." }, { "code": null, "e": 14724, "s": 14704, "text": "Cohen's h: 0.174943" }, { "code": null, "e": 14735, "s": 14724, "text": "Odds Ratio" }, { "code": null, "e": 14911, "s": 14735, "text": "The effect size measured by the odds ratio is computed by noting that the odds of an event happening in the treatment group are X times higher/lower than in the control group." }, { "code": null, "e": 14932, "s": 14911, "text": "Odds Ratio: 1.374506" }, { "code": null, "e": 15121, "s": 14932, "text": "The odds of an event (for example conversion) happening are ~1.37 times higher in the x group than in the y one, which is in line with the probabilities provided while generating the data." }, { "code": null, "e": 15374, "s": 15121, "text": "The last metric is quite interesting, because — as the name suggests — it aims to express the effect size in a plain language understood by everyone. Also, it does not belong to the families mentioned above. The authors described this metric in [2] as:" }, { "code": null, "e": 15510, "s": 15374, "text": "the probability that a score sampled at random from one distribution will be greater than a score sampled from some other distribution." }, { "code": null, "e": 15884, "s": 15510, "text": "To make the description as clear as possible, I will paraphrase the example mentioned in the paper. Imagine that we have a sample of heights of adult men and women, and the CLES is 0.8. This would mean that in 80% of randomly selected pairs, the man will be higher than the women. Or to put it differently, in 8 out of 10 blind dates, the man will be higher than the woman." }, { "code": null, "e": 16146, "s": 15884, "text": "In this article, I introduced different measures of the effect size and showed how to calculate them in Python. Knowing these, or at the very least one key metric per family, will definitely come in handy while planning A/B tests using the frequentist approach." }, { "code": null, "e": 16308, "s": 16146, "text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments." }, { "code": null, "e": 16373, "s": 16308, "text": "In case you found this article interesting, you might also like:" }, { "code": null, "e": 16396, "s": 16373, "text": "towardsdatascience.com" }, { "code": null, "e": 16419, "s": 16396, "text": "towardsdatascience.com" }, { "code": null, "e": 16442, "s": 16419, "text": "towardsdatascience.com" }, { "code": null, "e": 16536, "s": 16442, "text": "[1] Cohen, J. (2013). Statistical power analysis for the behavioral sciences. Academic press." } ]
How to read a numerical data or file in Python with numpy? - GeeksforGeeks
12 Aug, 2021 Prerequisites: Numpy NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different formats of file : The data can be saved in a txt file where each line has a new data point. The data can be stored in a CSV(comma separated values) file. The data can be also stored in TSV(tab separated values) file. There are multiple ways of storing data in files and the above ones are some of the most used formats for storing numerical data. To achieve our required functionality numpy’s loadtxt() function will be used. Syntax: numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0) Parameters:fname : File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.dtype : Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array.delimiter : The string used to separate values. By default, this is any whitespace.converters : A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Default: None.skiprows : Skip the first skiprows lines; default: 0. Returns: ndarray Import module Load file Read numeric data Print data retrieved. Given below are some implementation for various file formats: Link to download data files used : Link1 : gfg_example1.txt Link2 : gfg_example2.csv Link3 : gfg_example3.tsv Link4 : gfg_example4.csv Example 1: Reading numerical data from text file Python3 # Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in pythonfilename = 'gfg_example1.txt' # Loading file data into numpy array and storing it in variable called data_collecteddata_collected = np.loadtxt(filename) # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}') Output : Output of Example 1 Example 2: Reading numerical data from CSV file. Python3 # Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in python# This is a comma separated values filefilename = 'gfg_example2.csv' # Loading file data into numpy array and storing it in variable.# We use a delimiter that basically tells the code that at every ',' we encounter,# we need to treat it as a new data point.# The data type of the variables is set to be int using dtype parameter.data_collected = np.loadtxt(filename, delimiter=',', dtype=int) # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}') Output : Output of Example 2 Example 3: Reading from tsv file Python3 # Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in python# Thisfilename = 'gfg_example3.tsv' # Loading file data into numpy array and storing it in variable called data_collected# We use a delimiter that basically tells the code that at every ',' we encounter,# we need to treat it as a new data point.data_collected = np.loadtxt(filename, delimiter='\t') # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}') Output : Output of Example 3 Example 4: Select only particular rows and skip some rows Python3 # Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in pythonfilename = 'gfg_example4.csv' # Loading file data into numpy array and storing it in variable called data_collecteddata_collected = np.loadtxt( filename, skiprows=1, usecols=[0, 1], delimiter=',') # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}') Output : Output of Example 4 kk773572498 Picked Python numpy-io Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n12 Aug, 2021" }, { "code": null, "e": 24234, "s": 24212, "text": "Prerequisites: Numpy " }, { "code": null, "e": 24464, "s": 24234, "text": "NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy." }, { "code": null, "e": 24525, "s": 24464, "text": "Numerical data can be present in different formats of file :" }, { "code": null, "e": 24599, "s": 24525, "text": "The data can be saved in a txt file where each line has a new data point." }, { "code": null, "e": 24661, "s": 24599, "text": "The data can be stored in a CSV(comma separated values) file." }, { "code": null, "e": 24724, "s": 24661, "text": "The data can be also stored in TSV(tab separated values) file." }, { "code": null, "e": 24933, "s": 24724, "text": "There are multiple ways of storing data in files and the above ones are some of the most used formats for storing numerical data. To achieve our required functionality numpy’s loadtxt() function will be used." }, { "code": null, "e": 25073, "s": 24933, "text": "Syntax: numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)" }, { "code": null, "e": 25784, "s": 25073, "text": "Parameters:fname : File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.dtype : Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array.delimiter : The string used to separate values. By default, this is any whitespace.converters : A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Default: None.skiprows : Skip the first skiprows lines; default: 0." }, { "code": null, "e": 25801, "s": 25784, "text": "Returns: ndarray" }, { "code": null, "e": 25815, "s": 25801, "text": "Import module" }, { "code": null, "e": 25825, "s": 25815, "text": "Load file" }, { "code": null, "e": 25843, "s": 25825, "text": "Read numeric data" }, { "code": null, "e": 25865, "s": 25843, "text": "Print data retrieved." }, { "code": null, "e": 25927, "s": 25865, "text": "Given below are some implementation for various file formats:" }, { "code": null, "e": 25963, "s": 25927, "text": "Link to download data files used : " }, { "code": null, "e": 25988, "s": 25963, "text": "Link1 : gfg_example1.txt" }, { "code": null, "e": 26013, "s": 25988, "text": "Link2 : gfg_example2.csv" }, { "code": null, "e": 26038, "s": 26013, "text": "Link3 : gfg_example3.tsv" }, { "code": null, "e": 26063, "s": 26038, "text": "Link4 : gfg_example4.csv" }, { "code": null, "e": 26112, "s": 26063, "text": "Example 1: Reading numerical data from text file" }, { "code": null, "e": 26120, "s": 26112, "text": "Python3" }, { "code": "# Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in pythonfilename = 'gfg_example1.txt' # Loading file data into numpy array and storing it in variable called data_collecteddata_collected = np.loadtxt(filename) # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}')", "e": 26555, "s": 26120, "text": null }, { "code": null, "e": 26565, "s": 26555, "text": "Output : " }, { "code": null, "e": 26585, "s": 26565, "text": "Output of Example 1" }, { "code": null, "e": 26634, "s": 26585, "text": "Example 2: Reading numerical data from CSV file." }, { "code": null, "e": 26642, "s": 26634, "text": "Python3" }, { "code": "# Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in python# This is a comma separated values filefilename = 'gfg_example2.csv' # Loading file data into numpy array and storing it in variable.# We use a delimiter that basically tells the code that at every ',' we encounter,# we need to treat it as a new data point.# The data type of the variables is set to be int using dtype parameter.data_collected = np.loadtxt(filename, delimiter=',', dtype=int) # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}')", "e": 27317, "s": 26642, "text": null }, { "code": null, "e": 27327, "s": 27317, "text": "Output : " }, { "code": null, "e": 27347, "s": 27327, "text": "Output of Example 2" }, { "code": null, "e": 27380, "s": 27347, "text": "Example 3: Reading from tsv file" }, { "code": null, "e": 27388, "s": 27380, "text": "Python3" }, { "code": "# Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in python# Thisfilename = 'gfg_example3.tsv' # Loading file data into numpy array and storing it in variable called data_collected# We use a delimiter that basically tells the code that at every ',' we encounter,# we need to treat it as a new data point.data_collected = np.loadtxt(filename, delimiter='\\t') # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}')", "e": 27969, "s": 27388, "text": null }, { "code": null, "e": 27979, "s": 27969, "text": "Output : " }, { "code": null, "e": 27999, "s": 27979, "text": "Output of Example 3" }, { "code": null, "e": 28057, "s": 27999, "text": "Example 4: Select only particular rows and skip some rows" }, { "code": null, "e": 28065, "s": 28057, "text": "Python3" }, { "code": "# Importing libraries that will be usedimport numpy as np # Setting name of the file that the data is to be extracted from in pythonfilename = 'gfg_example4.csv' # Loading file data into numpy array and storing it in variable called data_collecteddata_collected = np.loadtxt( filename, skiprows=1, usecols=[0, 1], delimiter=',') # Printing data storedprint(data_collected) # Type of dataprint( f'Stored in : {type(data_collected)} and data type is : {data_collected.dtype}')", "e": 28547, "s": 28065, "text": null }, { "code": null, "e": 28557, "s": 28547, "text": "Output : " }, { "code": null, "e": 28577, "s": 28557, "text": "Output of Example 4" }, { "code": null, "e": 28589, "s": 28577, "text": "kk773572498" }, { "code": null, "e": 28596, "s": 28589, "text": "Picked" }, { "code": null, "e": 28612, "s": 28596, "text": "Python numpy-io" }, { "code": null, "e": 28625, "s": 28612, "text": "Python-numpy" }, { "code": null, "e": 28632, "s": 28625, "text": "Python" }, { "code": null, "e": 28730, "s": 28632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28739, "s": 28730, "text": "Comments" }, { "code": null, "e": 28752, "s": 28739, "text": "Old Comments" }, { "code": null, "e": 28784, "s": 28752, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28839, "s": 28784, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28895, "s": 28839, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28934, "s": 28895, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28976, "s": 28934, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29018, "s": 28976, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29049, "s": 29018, "text": "Python | os.path.join() method" }, { "code": null, "e": 29071, "s": 29049, "text": "Defaultdict in Python" }, { "code": null, "e": 29100, "s": 29071, "text": "Create a directory in Python" } ]
XML parsing in Python?
Python XML parser parser provides one of the easiest ways to read and extract useful information from the XML file. In this short tutorial we are going to see how we can parse XML file, modify and create XML documents using python ElementTree XML API. Python ElementTree API is one of the easiest way to extract, parse and transform XML data. So let’s get started using python XML parser using ElementTree: First we are going to create a new XML file with an element and a sub-element. #Import required library import xml.etree.ElementTree as xml def createXML(filename): # Start with the root element root = xml.Element("users") children1 = xml.Element("user") root.append(children1) tree = xml.ElementTree(root) with open(filename, "wb") as fh: tree.write(fh) if __name__ == "__main__": createXML("testXML.xml") Once we run above program, a new file is created named “textXML.xml” in our current default working directory: Which contains contents something like: <users><user /></users> Please note while writing the file, we have used the ‘wb’ mode .i.e. write the file in binary mode. Let’s give some values to the XML elements in our above program: #Import required library import xml.etree.ElementTree as xml def createXML(filename): # Start with the root element root = xml.Element("users") children1 = xml.Element("user") root.append(children1) userId1 = xml.SubElement(children1, "Id") userId1.text = "hello" userName1 = xml.SubElement(children1, "Name") userName1.text = "Rajesh" tree = xml.ElementTree(root) with open(filename, "wb") as fh: tree.write(fh) if __name__ == "__main__": createXML("testXML.xml") After running the above program, we’ll see that new elements are added with values, something like: <users> <user> <Id>hello</Id> <Name>Rajesh</Name> </user> </users> Above output looks ok. Now let’s start editing files: Let’s add some bit of data into from a file in our existing program. newdata.xml <users> <user> <id>1a</id> <name>Rajesh</name> <salary>NA</salary> </user> <user> <id>2b</id> <name>TutorialsPoint</name> <salary>NA</salary> </user> <user> <id>3c</id> <name>Others</name> <salary>NA</salary> </user> </users> Above is our current xml file, let’s try to update the salary of each users: #Import required library import xml.etree.ElementTree as ET def updateET(filename): # Start with the root element tree = ET.ElementTree(file=filename) root = tree.getroot() for salary in root.iter('salary'): salary.text = '500000' tree = ET.ElementTree(root) with open("newdata.xml", "wb") as fh: tree.write(fh) if __name__ == "__main__": updateET("newdata.xml") So we see the salary is changed from ‘NA’ to ‘500000’. Now let’s write another program which will parse XML data present in the file and print the data. #Import required library import xml.etree.cElementTree as ET def parseXML(file_name): # Parse XML with ElementTree tree = ET.ElementTree(file=file_name) print(tree.getroot()) root = tree.getroot() print("tag=%s, attrib=%s" % (root.tag, root.attrib)) # get the information via the children! print("-" * 25) print("Iterating using getchildren()") print("-" * 25) users = root.getchildren() for user in users: user_children = user.getchildren() for user_child in user_children: print("%s=%s" % (user_child.tag, user_child.text)) if __name__ == "__main__": parseXML("newdata.xml") <Element 'users' at 0x0551A5A0> tag = users, attrib = {} ------------------------- Iterating using getchildren() ------------------------- id = 1a name = Rajesh salary = 500000 id = 2b name = TutorialsPoint salary = 500000 id = 3c name = Others salary = 500000
[ { "code": null, "e": 1314, "s": 1062, "text": "Python XML parser parser provides one of the easiest ways to read and extract useful information from the XML file. In this short tutorial we are going to see how we can parse XML file, modify and create XML documents using python ElementTree XML API." }, { "code": null, "e": 1405, "s": 1314, "text": "Python ElementTree API is one of the easiest way to extract, parse and transform XML data." }, { "code": null, "e": 1469, "s": 1405, "text": "So let’s get started using python XML parser using ElementTree:" }, { "code": null, "e": 1548, "s": 1469, "text": "First we are going to create a new XML file with an element and a sub-element." }, { "code": null, "e": 1906, "s": 1548, "text": "#Import required library\nimport xml.etree.ElementTree as xml\n\ndef createXML(filename):\n # Start with the root element\n root = xml.Element(\"users\")\n children1 = xml.Element(\"user\")\n root.append(children1)\n\n tree = xml.ElementTree(root)\n with open(filename, \"wb\") as fh:\n tree.write(fh)\n\nif __name__ == \"__main__\":\n createXML(\"testXML.xml\")" }, { "code": null, "e": 2017, "s": 1906, "text": "Once we run above program, a new file is created named “textXML.xml” in our current default working directory:" }, { "code": null, "e": 2057, "s": 2017, "text": "Which contains contents something like:" }, { "code": null, "e": 2081, "s": 2057, "text": "<users><user /></users>" }, { "code": null, "e": 2181, "s": 2081, "text": "Please note while writing the file, we have used the ‘wb’ mode .i.e. write the file in binary mode." }, { "code": null, "e": 2246, "s": 2181, "text": "Let’s give some values to the XML elements in our above program:" }, { "code": null, "e": 2752, "s": 2246, "text": "#Import required library\nimport xml.etree.ElementTree as xml\n\ndef createXML(filename):\n # Start with the root element\n root = xml.Element(\"users\")\n children1 = xml.Element(\"user\")\n root.append(children1)\n\n userId1 = xml.SubElement(children1, \"Id\")\n userId1.text = \"hello\"\n\n userName1 = xml.SubElement(children1, \"Name\")\n userName1.text = \"Rajesh\"\n\n tree = xml.ElementTree(root)\n with open(filename, \"wb\") as fh:\n tree.write(fh)\n\nif __name__ == \"__main__\":\n createXML(\"testXML.xml\")" }, { "code": null, "e": 2852, "s": 2752, "text": "After running the above program, we’ll see that new elements are added with values, something like:" }, { "code": null, "e": 2937, "s": 2852, "text": "<users>\n <user>\n <Id>hello</Id>\n <Name>Rajesh</Name>\n </user>\n</users>" }, { "code": null, "e": 2960, "s": 2937, "text": "Above output looks ok." }, { "code": null, "e": 2991, "s": 2960, "text": "Now let’s start editing files:" }, { "code": null, "e": 3060, "s": 2991, "text": "Let’s add some bit of data into from a file in our existing program." }, { "code": null, "e": 3072, "s": 3060, "text": "newdata.xml" }, { "code": null, "e": 3370, "s": 3072, "text": "<users>\n <user>\n <id>1a</id>\n <name>Rajesh</name>\n <salary>NA</salary>\n </user>\n <user>\n <id>2b</id>\n <name>TutorialsPoint</name>\n <salary>NA</salary>\n </user>\n <user>\n <id>3c</id>\n <name>Others</name>\n <salary>NA</salary>\n </user>\n</users>" }, { "code": null, "e": 3447, "s": 3370, "text": "Above is our current xml file, let’s try to update the salary of each users:" }, { "code": null, "e": 3847, "s": 3447, "text": "#Import required library\nimport xml.etree.ElementTree as ET\n\ndef updateET(filename):\n # Start with the root element\n tree = ET.ElementTree(file=filename)\n root = tree.getroot()\n\n for salary in root.iter('salary'):\n salary.text = '500000'\n\n tree = ET.ElementTree(root)\n with open(\"newdata.xml\", \"wb\") as fh:\n tree.write(fh)\n\nif __name__ == \"__main__\":\n updateET(\"newdata.xml\")" }, { "code": null, "e": 3902, "s": 3847, "text": "So we see the salary is changed from ‘NA’ to ‘500000’." }, { "code": null, "e": 4000, "s": 3902, "text": "Now let’s write another program which will parse XML data present in the file and print the data." }, { "code": null, "e": 4637, "s": 4000, "text": "#Import required library\nimport xml.etree.cElementTree as ET\n\ndef parseXML(file_name):\n # Parse XML with ElementTree\n tree = ET.ElementTree(file=file_name)\n print(tree.getroot())\n root = tree.getroot()\n print(\"tag=%s, attrib=%s\" % (root.tag, root.attrib))\n\n # get the information via the children!\n print(\"-\" * 25)\n print(\"Iterating using getchildren()\")\n print(\"-\" * 25)\n users = root.getchildren()\n for user in users:\n user_children = user.getchildren()\n for user_child in user_children:\n print(\"%s=%s\" % (user_child.tag, user_child.text))\n\nif __name__ == \"__main__\":\n parseXML(\"newdata.xml\")" }, { "code": null, "e": 4898, "s": 4637, "text": "<Element 'users' at 0x0551A5A0>\ntag = users, attrib = {}\n-------------------------\nIterating using getchildren()\n-------------------------\nid = 1a\nname = Rajesh\nsalary = 500000\nid = 2b\nname = TutorialsPoint\nsalary = 500000\nid = 3c\nname = Others\nsalary = 500000" } ]
Selenium Webdriver - Handling Checkboxes
We can handle checkboxes with Selenium webdriver. A checkbox is represented by input tagname in the html code and its type attribute should have the value as checkbox. The methods to handle the checkboxes are listed below − Click − Used to check a checkbox. Click − Used to check a checkbox. is_selected − Used to check if a checkbox is checked or not. It returns a boolean value, true is returned in case a checkbox is checked. is_selected − Used to check if a checkbox is checked or not. It returns a boolean value, true is returned in case a checkbox is checked. Let us see the html code of a checkbox, which is as follows − The code implementation for handling checkboxes is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://the-internet.herokuapp.com/checkboxes") #identify element l = driver.find_element_by_xpath("//input[@type='checkbox']") l.click() if l.is_selected(): print('Checkbox is checked') else: print('Checkbox is not checked') #close driver driver.close() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the message - Checkbox is checked is printed since the is_selected method applied on the checkbox returned true value. 46 Lectures 5.5 hours Aditya Dua 296 Lectures 146 hours Arun Motoori 411 Lectures 38.5 hours In28Minutes Official 22 Lectures 7 hours Arun Motoori 118 Lectures 17 hours Arun Motoori 278 Lectures 38.5 hours Lets Kode It Print Add Notes Bookmark this page
[ { "code": null, "e": 2371, "s": 2203, "text": "We can handle checkboxes with Selenium webdriver. A checkbox is represented by input tagname in the html code and its type attribute should have the value as checkbox." }, { "code": null, "e": 2427, "s": 2371, "text": "The methods to handle the checkboxes are listed below −" }, { "code": null, "e": 2461, "s": 2427, "text": "Click − Used to check a checkbox." }, { "code": null, "e": 2495, "s": 2461, "text": "Click − Used to check a checkbox." }, { "code": null, "e": 2632, "s": 2495, "text": "is_selected − Used to check if a checkbox is checked or not. It returns a boolean value, true is returned in case a checkbox is checked." }, { "code": null, "e": 2769, "s": 2632, "text": "is_selected − Used to check if a checkbox is checked or not. It returns a boolean value, true is returned in case a checkbox is checked." }, { "code": null, "e": 2831, "s": 2769, "text": "Let us see the html code of a checkbox, which is as follows −" }, { "code": null, "e": 2895, "s": 2831, "text": "The code implementation for handling checkboxes is as follows −" }, { "code": null, "e": 3326, "s": 2895, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://the-internet.herokuapp.com/checkboxes\")\n#identify element\nl = driver.find_element_by_xpath(\"//input[@type='checkbox']\")\nl.click()\nif l.is_selected():\n print('Checkbox is checked')\nelse:\n print('Checkbox is not checked')\n#close driver\ndriver.close()" }, { "code": null, "e": 3565, "s": 3326, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the message - Checkbox is checked is printed since the is_selected method applied on the checkbox returned true value." }, { "code": null, "e": 3600, "s": 3565, "text": "\n 46 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3612, "s": 3600, "text": " Aditya Dua" }, { "code": null, "e": 3648, "s": 3612, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 3662, "s": 3648, "text": " Arun Motoori" }, { "code": null, "e": 3699, "s": 3662, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 3721, "s": 3699, "text": " In28Minutes Official" }, { "code": null, "e": 3754, "s": 3721, "text": "\n 22 Lectures \n 7 hours \n" }, { "code": null, "e": 3768, "s": 3754, "text": " Arun Motoori" }, { "code": null, "e": 3803, "s": 3768, "text": "\n 118 Lectures \n 17 hours \n" }, { "code": null, "e": 3817, "s": 3803, "text": " Arun Motoori" }, { "code": null, "e": 3854, "s": 3817, "text": "\n 278 Lectures \n 38.5 hours \n" }, { "code": null, "e": 3868, "s": 3854, "text": " Lets Kode It" }, { "code": null, "e": 3875, "s": 3868, "text": " Print" }, { "code": null, "e": 3886, "s": 3875, "text": " Add Notes" } ]
How to check if a value exists in an R data frame or not?
There are many small objectives that helps us to achieve a greater objective in data analysis. One such small objective is checking if a value exists in the data set or not. In R, we have many objects for data set such as data frame, matrix, data.table object etc. If we want to check if a value exists in an R data frame then any function can be used. Consider the below data frame: Live Demo > set.seed(3654) > x1<-rpois(20,5) > x2<-rpois(20,8) > x3<-rpois(20,10) > x4<-rpois(20,3) > df1<-data.frame(x1,x2,x3,x4) > df1 x1 x2 x3 x4 1 4 5 16 2 2 5 4 15 2 3 6 6 13 3 4 2 6 7 4 5 5 4 9 4 6 6 8 9 5 7 5 6 12 3 8 4 5 8 7 9 2 9 12 1 10 6 7 6 1 11 3 4 9 3 12 2 5 5 3 13 3 7 7 4 14 4 7 8 2 15 6 12 9 1 16 8 4 15 1 17 5 8 10 4 18 3 12 11 2 19 3 8 12 3 20 8 13 11 1 Checking whether a particular value exists in df1 or not: > any(df1==4) [1] TRUE > any(df1==5) [1] TRUE > any(df1==20) [1] FALSE > any(df1==8) [1] TRUE > any(df1==15) [1] TRUE > any(df1==12) [1] TRUE Let’s have a look at another example: Live Demo > S1<-sample(LETTERS[1:10],20,replace=TRUE) > S2<-sample(LETTERS[21:26],20,replace=TRUE) > df2<-data.frame(S1,S2) > df2 S1 S2 1 G W 2 C V 3 J W 4 E Y 5 H W 6 H V 7 H U 8 C W 9 A W 10 J W 11 J U 12 D V 13 C U 14 J W 15 G U 16 E X 17 D Y 18 B X 19 E U 20 I U > any(df2=="A") [1] TRUE > any(df2=="B") [1] TRUE > any(df2=="C") [1] TRUE > any(df2=="c") [1] FALSE > any(df2=="e") [1] FALSE > any(df2=="F") [1] FALSE > any(df2=="J") [1] TRUE > any(df2=="M") [1] FALSE > any(df2=="N") [1] FALSE
[ { "code": null, "e": 1415, "s": 1062, "text": "There are many small objectives that helps us to achieve a greater objective in data analysis. One such small objective is checking if a value exists in the data set or not. In R, we have many objects for data set such as data frame, matrix, data.table object etc. If we want to check if a value exists in an R data frame then any function can be used." }, { "code": null, "e": 1446, "s": 1415, "text": "Consider the below data frame:" }, { "code": null, "e": 1456, "s": 1446, "text": "Live Demo" }, { "code": null, "e": 1583, "s": 1456, "text": "> set.seed(3654)\n> x1<-rpois(20,5)\n> x2<-rpois(20,8)\n> x3<-rpois(20,10)\n> x4<-rpois(20,3)\n> df1<-data.frame(x1,x2,x3,x4)\n> df1" }, { "code": null, "e": 1877, "s": 1583, "text": " x1 x2 x3 x4\n1 4 5 16 2\n2 5 4 15 2\n3 6 6 13 3\n4 2 6 7 4\n5 5 4 9 4\n6 6 8 9 5\n7 5 6 12 3\n8 4 5 8 7\n9 2 9 12 1\n10 6 7 6 1\n11 3 4 9 3\n12 2 5 5 3\n13 3 7 7 4\n14 4 7 8 2\n15 6 12 9 1\n16 8 4 15 1\n17 5 8 10 4\n18 3 12 11 2\n19 3 8 12 3\n20 8 13 11 1" }, { "code": null, "e": 1935, "s": 1877, "text": "Checking whether a particular value exists in df1 or not:" }, { "code": null, "e": 2077, "s": 1935, "text": "> any(df1==4)\n[1] TRUE\n> any(df1==5)\n[1] TRUE\n> any(df1==20)\n[1] FALSE\n> any(df1==8)\n[1] TRUE\n> any(df1==15)\n[1] TRUE\n> any(df1==12)\n[1] TRUE" }, { "code": null, "e": 2115, "s": 2077, "text": "Let’s have a look at another example:" }, { "code": null, "e": 2125, "s": 2115, "text": "Live Demo" }, { "code": null, "e": 2245, "s": 2125, "text": "> S1<-sample(LETTERS[1:10],20,replace=TRUE)\n> S2<-sample(LETTERS[21:26],20,replace=TRUE)\n> df2<-data.frame(S1,S2)\n> df2" }, { "code": null, "e": 2393, "s": 2245, "text": " S1 S2\n1 G W\n2 C V\n3 J W\n4 E Y\n5 H W\n6 H V\n7 H U\n8 C W\n9 A W\n10 J W\n11 J U\n12 D V\n13 C U\n14 J W\n15 G U\n16 E X\n17 D Y\n18 B X\n19 E U\n20 I U" }, { "code": null, "e": 2623, "s": 2393, "text": "> any(df2==\"A\")\n[1] TRUE\n> any(df2==\"B\")\n[1] TRUE\n> any(df2==\"C\")\n[1] TRUE\n> any(df2==\"c\")\n[1] FALSE\n> any(df2==\"e\")\n[1] FALSE\n> any(df2==\"F\")\n[1] FALSE\n> any(df2==\"J\")\n[1] TRUE\n> any(df2==\"M\")\n[1] FALSE\n> any(df2==\"N\")\n[1] FALSE" } ]
How to wait for a keypress in R ? - GeeksforGeeks
17 Jun, 2021 R Programming language is robust and user-friendly, as it displays annotations and contexts for the desired input streams. We can pause the execution of a script and wait for the enter key to be pressed by the user into the console. This can be done using various standard methods in base R. In order to prompt to print on the console after the Enter key is pressed, we can use the readline() method in base R. The readline() method in R language reads a line from the terminal. The output is returned as a character vector of length one. The leading, as well as the trailing spaces, are stripped from the returned output. Syntax: readline(prompt = “”) prompt – the string displayed upon prompting the user for input. Mostly terminates with a ” ” (space) character. Example: R # read line readline(prompt="Press [enter] to proceed") Output The invisible method in R is used to return a (temporarily) invisible copy of an object. It returns an arbitrary object which assigns the values but does not print it on the console when they are not assigned. Syntax: invisible (x) Example: R # read line invisible(readline(prompt="Press [enter] to proceed")) Output scan() method in base R is used to scan and read data into the working space. It read the input data into a vector or list or from file object establishing the file connection stream. This method fails when we enter any character string, that cannot be treated as a number. Example: R str <- "Press [enter] to proceed"print (str) # scan a new numbernum <- scan(n=1) Output Picked R-Functions R-Input/Output R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Logistic Regression in R Programming How to change the order of bars in bar chart in R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Data Visualization in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25455, "s": 25162, "text": "R Programming language is robust and user-friendly, as it displays annotations and contexts for the desired input streams. We can pause the execution of a script and wait for the enter key to be pressed by the user into the console. This can be done using various standard methods in base R. " }, { "code": null, "e": 25786, "s": 25455, "text": "In order to prompt to print on the console after the Enter key is pressed, we can use the readline() method in base R. The readline() method in R language reads a line from the terminal. The output is returned as a character vector of length one. The leading, as well as the trailing spaces, are stripped from the returned output." }, { "code": null, "e": 25794, "s": 25786, "text": "Syntax:" }, { "code": null, "e": 25816, "s": 25794, "text": "readline(prompt = “”)" }, { "code": null, "e": 25929, "s": 25816, "text": "prompt – the string displayed upon prompting the user for input. Mostly terminates with a ” ” (space) character." }, { "code": null, "e": 25938, "s": 25929, "text": "Example:" }, { "code": null, "e": 25940, "s": 25938, "text": "R" }, { "code": "# read line readline(prompt=\"Press [enter] to proceed\")", "e": 25996, "s": 25940, "text": null }, { "code": null, "e": 26003, "s": 25996, "text": "Output" }, { "code": null, "e": 26213, "s": 26003, "text": "The invisible method in R is used to return a (temporarily) invisible copy of an object. It returns an arbitrary object which assigns the values but does not print it on the console when they are not assigned." }, { "code": null, "e": 26221, "s": 26213, "text": "Syntax:" }, { "code": null, "e": 26235, "s": 26221, "text": "invisible (x)" }, { "code": null, "e": 26244, "s": 26235, "text": "Example:" }, { "code": null, "e": 26246, "s": 26244, "text": "R" }, { "code": "# read line invisible(readline(prompt=\"Press [enter] to proceed\"))", "e": 26313, "s": 26246, "text": null }, { "code": null, "e": 26320, "s": 26313, "text": "Output" }, { "code": null, "e": 26595, "s": 26320, "text": "scan() method in base R is used to scan and read data into the working space. It read the input data into a vector or list or from file object establishing the file connection stream. This method fails when we enter any character string, that cannot be treated as a number. " }, { "code": null, "e": 26604, "s": 26595, "text": "Example:" }, { "code": null, "e": 26606, "s": 26604, "text": "R" }, { "code": "str <- \"Press [enter] to proceed\"print (str) # scan a new numbernum <- scan(n=1)", "e": 26688, "s": 26606, "text": null }, { "code": null, "e": 26695, "s": 26688, "text": "Output" }, { "code": null, "e": 26702, "s": 26695, "text": "Picked" }, { "code": null, "e": 26714, "s": 26702, "text": "R-Functions" }, { "code": null, "e": 26729, "s": 26714, "text": "R-Input/Output" }, { "code": null, "e": 26740, "s": 26729, "text": "R Language" }, { "code": null, "e": 26838, "s": 26740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26847, "s": 26838, "text": "Comments" }, { "code": null, "e": 26860, "s": 26847, "text": "Old Comments" }, { "code": null, "e": 26912, "s": 26860, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26950, "s": 26912, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26985, "s": 26950, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27043, "s": 26985, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27092, "s": 27043, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27129, "s": 27092, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27181, "s": 27129, "text": "How to change the order of bars in bar chart in R ?" }, { "code": null, "e": 27231, "s": 27181, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27274, "s": 27231, "text": "Replace Specific Characters in String in R" } ]
Python | Morphological Operations in Image Processing (Closing) | Set-2
25 Apr, 2022 In the previous article, the Opening operator was specified which was applying the erosion operation after dilation. It helps in removing the internal noise in the image. Closing is similar to the opening operation. In closing operation, the basic premise is that the closing is opening performed in reverse. It is defined simply as a dilation followed by an erosion using the same structuring element used in the opening operation. Syntax: cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel) Parameters:-> image: Input Image array.-> cv2.MORPH_CLOSE: Applying the Morphological Closing operation.-> kernel: Structuring element. Below is the Python code explaining Closing Morphological Operation – Python3 # Python program to illustrate# Closing morphological operation# on an image # organizing imports import cv2 import numpy as np # return video from the first webcam on your computer. screenRead = cv2.VideoCapture(0) # loop runs if capturing has been initialized.while(1): # reads frames from a camera _, image = screenRead.read() # Converts to HSV color space, OCV reads colors as BGR # frame is converted to hsv hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # defining the range of masking blue1 = np.array([110, 50, 50]) blue2 = np.array([130, 255, 255]) # initializing the mask to be # convoluted over input image mask = cv2.inRange(hsv, blue1, blue2) # passing the bitwise_and over # each pixel convoluted res = cv2.bitwise_and(image, image, mask = mask) # defining the kernel i.e. Structuring element kernel = np.ones((5, 5), np.uint8) # defining the closing function # over the image and structuring element closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # The mask and closing operation # is shown in the window cv2.imshow('Mask', mask) cv2.imshow('Closing', closing) # Wait for 'a' key to stop the program if cv2.waitKey(1) & 0xFF == ord('a'): break # De-allocate any associated memory usage cv2.destroyAllWindows() # Close the window / Release webcam screenRead.release() Input Frame: Mask: Output: anikakapoor awdheshkumar2 Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Apr, 2022" }, { "code": null, "e": 461, "s": 28, "text": "In the previous article, the Opening operator was specified which was applying the erosion operation after dilation. It helps in removing the internal noise in the image. Closing is similar to the opening operation. In closing operation, the basic premise is that the closing is opening performed in reverse. It is defined simply as a dilation followed by an erosion using the same structuring element used in the opening operation." }, { "code": null, "e": 518, "s": 461, "text": "Syntax: cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)" }, { "code": null, "e": 654, "s": 518, "text": "Parameters:-> image: Input Image array.-> cv2.MORPH_CLOSE: Applying the Morphological Closing operation.-> kernel: Structuring element." }, { "code": null, "e": 724, "s": 654, "text": "Below is the Python code explaining Closing Morphological Operation –" }, { "code": null, "e": 732, "s": 724, "text": "Python3" }, { "code": "# Python program to illustrate# Closing morphological operation# on an image # organizing imports import cv2 import numpy as np # return video from the first webcam on your computer. screenRead = cv2.VideoCapture(0) # loop runs if capturing has been initialized.while(1): # reads frames from a camera _, image = screenRead.read() # Converts to HSV color space, OCV reads colors as BGR # frame is converted to hsv hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # defining the range of masking blue1 = np.array([110, 50, 50]) blue2 = np.array([130, 255, 255]) # initializing the mask to be # convoluted over input image mask = cv2.inRange(hsv, blue1, blue2) # passing the bitwise_and over # each pixel convoluted res = cv2.bitwise_and(image, image, mask = mask) # defining the kernel i.e. Structuring element kernel = np.ones((5, 5), np.uint8) # defining the closing function # over the image and structuring element closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # The mask and closing operation # is shown in the window cv2.imshow('Mask', mask) cv2.imshow('Closing', closing) # Wait for 'a' key to stop the program if cv2.waitKey(1) & 0xFF == ord('a'): break # De-allocate any associated memory usage cv2.destroyAllWindows() # Close the window / Release webcam screenRead.release()", "e": 2163, "s": 732, "text": null }, { "code": null, "e": 2176, "s": 2163, "text": "Input Frame:" }, { "code": null, "e": 2182, "s": 2176, "text": "Mask:" }, { "code": null, "e": 2190, "s": 2182, "text": "Output:" }, { "code": null, "e": 2202, "s": 2190, "text": "anikakapoor" }, { "code": null, "e": 2216, "s": 2202, "text": "awdheshkumar2" }, { "code": null, "e": 2233, "s": 2216, "text": "Image-Processing" }, { "code": null, "e": 2240, "s": 2233, "text": "OpenCV" }, { "code": null, "e": 2247, "s": 2240, "text": "Python" }, { "code": null, "e": 2345, "s": 2247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2363, "s": 2345, "text": "Python Dictionary" }, { "code": null, "e": 2405, "s": 2363, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2427, "s": 2405, "text": "Enumerate() in Python" }, { "code": null, "e": 2462, "s": 2427, "text": "Read a file line by line in Python" }, { "code": null, "e": 2488, "s": 2462, "text": "Python String | replace()" }, { "code": null, "e": 2520, "s": 2488, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2549, "s": 2520, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2579, "s": 2549, "text": "Iterate over a list in Python" }, { "code": null, "e": 2606, "s": 2579, "text": "Python Classes and Objects" } ]
MongoDB: Getting Started
07 Sep, 2021 Introduction to MongoDB Terminologies: A MongoDB Database can be called as the container for all the collections. Collection is a bunch of MongoDB documents. It is similar to tables in RDBMS. Document is made of fields. It is similar to a tuple in RDBMS, but it has dynamic schema here. Documents of the same collection need not have the same set of fields Getting Started After you install MongoDB, you can see all the installed file inside C:\ProgramFiles\MongoDB\ (default location). In the C:\Program Files\MongoDB\Server\3.2\bin directory, there are a bunch of executables and a short-description about them would be: mongo: The Command Line Interface to interact with the db. mongod: This is the database. Sets up the server. mongodump: It dumps out the Binary of the Database(BSON) mongoexport: Exports the document to Json, CSV format mongoimport: To import some data into the DB. mongorestore: to restore anything that you’ve exported. mongostat: Statistics of databases Now, you can start running the MongoDB Server. Fire up a Command Prompt and go to the location where MongoDB executables are installed (C:\Program Files\MongoDB\Server\3.2\bin\ but this path might change in future). Just type “mongod” and it will pop an error saying the path \data\db doesn’t exist: This means that the default path of storage C:\data\db was not found. So you can make a directory C:\data\db on your own or with the mkdir command. You can also change the default path by the switch –dbpath <path> with the “mongod” command. After making this directory, run the “mongod” command again and it will start the server on the port 27017. Now, we need to start our client. So, open up another terminal and change the directory to the MongoDB path. Just type “mongo” and your client would be up, trying to connect to the server. This would be the CLI to interact and administer the databases. This shell is kind-of a JS console. You can try in different JS commands to check that out. Since our client is up, we can now start working on the database. We can see that the database in use is named as “test”. You can see the databases using “see dbs” and switch to other databases like “local” by typing “use <dbname>”. Note that there are no existing collections. This can be seen by typing the command “show collections”. Let’s start by adding some data into our database. We can create a collection by the method db.createCollection(name, { size : ..., capped : ..., max : ... } ) But we have created a randomly generated json file( of employee data) and we would import it onto our database by typing mongoimport --jsonArray --db test --collection employee_data < C:\mongoJson\employee_data.json This would import the Employee data json document referred by the path given in the collection named “employee_data” of database “test”. Now to ensure the collection is imported you can type “show collections” in the shell. You can use methods like count(), find(), findOne() to do some very basic queries with your document. You can see that in every document there is a field called “_id” which was not provided in the data imported. The reason is that MongoDB provides a default “_id” (if not provided explicitly) which is a 12 byte hexadecimal number which assures the uniqueness of every document. You can even change this “_id” field but this is not recommended. Indexing: You can also use indexing if your query returns more than one document. For example, db.employee_data.find() returns all the documents in the collection but if you just want the 7th one then, just do db.employee_data.find()[6] and it will return the specific document. [Note : Indexing starts from 0 here]. Projections: Let’s say for a query you want only some specific details and not the whole set of detail in the document. You can use projections for this. After your query object just make the needed fields as 1 and others would be assumed as 0 automatically. But remember that the “_id” field is always assumed to be 1 implicitly and if you don’t want to see the ugly looking “_id” field, then you need to say this in your projection by “_id : 0” Queries: 1. Find the number of employees with company “GEEKS FOR GEEKS” > db.employee_data.find( { company= “GEEKS FOR GEEKS” } ).count() 2. Show the detail of all the employees named “Sandeep Jain” > db.employee_data.find( { name: “Sandeep Jain” } Here, all the documents which matches with the given name would show up. 3. Show the age, gender and email, but not “_id” of the employee named “Harshit Gupta”. (Assume that there is only one employee named Harshit Gupta). Usage of Projections > db.employee_data.find( { name: “Harshit Gupta” }, { _id:0, age:1, gender:1, email:1 } ) We can also store the output of queries into variables and then make interesting queries with them too. 4. Print the name of all the female employees. > var femaleEmp = db.employee_data.find( { gender: “female” } ) for ( var i = 0 ; i < femaleEmp.count() ; i++){ print ( femaleEmp[i].name) } > db.employee_data.find( { gender: "female" }, { _id:0, name:1 } ) Note that the 1st solution just prints out the names while 2nd one prints it in Object Format. Article By Harshit Gupta: Kolkata based Harshit Gupta is an active blogger having keen interest in writing about algorithms,technical blogs, stories, and personal life experiences. Besides being passionate about writing, he also loves coding and dancing. Currently working in AMD, he is an active blog contributor at GeeksforGeeks. You can reach him at harshitguptablog.wordpress.com. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gulshankumarar231 MongoDB GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Sep, 2021" }, { "code": null, "e": 80, "s": 54, "text": "Introduction to MongoDB " }, { "code": null, "e": 171, "s": 80, "text": "Terminologies: A MongoDB Database can be called as the container for all the collections. " }, { "code": null, "e": 249, "s": 171, "text": "Collection is a bunch of MongoDB documents. It is similar to tables in RDBMS." }, { "code": null, "e": 414, "s": 249, "text": "Document is made of fields. It is similar to a tuple in RDBMS, but it has dynamic schema here. Documents of the same collection need not have the same set of fields" }, { "code": null, "e": 431, "s": 414, "text": "Getting Started " }, { "code": null, "e": 682, "s": 431, "text": "After you install MongoDB, you can see all the installed file inside C:\\ProgramFiles\\MongoDB\\ (default location). In the C:\\Program Files\\MongoDB\\Server\\3.2\\bin directory, there are a bunch of executables and a short-description about them would be: " }, { "code": null, "e": 1039, "s": 682, "text": "mongo: The Command Line Interface to interact with the db.\nmongod: This is the database. Sets up the server.\nmongodump: It dumps out the Binary of the Database(BSON)\nmongoexport: Exports the document to Json, CSV format\nmongoimport: To import some data into the DB.\nmongorestore: to restore anything that you’ve exported.\nmongostat: Statistics of databases" }, { "code": null, "e": 1340, "s": 1039, "text": "Now, you can start running the MongoDB Server. Fire up a Command Prompt and go to the location where MongoDB executables are installed (C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\ but this path might change in future). Just type “mongod” and it will pop an error saying the path \\data\\db doesn’t exist: " }, { "code": null, "e": 1691, "s": 1340, "text": "This means that the default path of storage C:\\data\\db was not found. So you can make a directory C:\\data\\db on your own or with the mkdir command. You can also change the default path by the switch –dbpath <path> with the “mongod” command. After making this directory, run the “mongod” command again and it will start the server on the port 27017. " }, { "code": null, "e": 1882, "s": 1691, "text": "Now, we need to start our client. So, open up another terminal and change the directory to the MongoDB path. Just type “mongo” and your client would be up, trying to connect to the server. " }, { "code": null, "e": 2273, "s": 1882, "text": "This would be the CLI to interact and administer the databases. This shell is kind-of a JS console. You can try in different JS commands to check that out. Since our client is up, we can now start working on the database. We can see that the database in use is named as “test”. You can see the databases using “see dbs” and switch to other databases like “local” by typing “use <dbname>”. " }, { "code": null, "e": 2378, "s": 2273, "text": "Note that there are no existing collections. This can be seen by typing the command “show collections”. " }, { "code": null, "e": 2539, "s": 2378, "text": "Let’s start by adding some data into our database. We can create a collection by the method db.createCollection(name, { size : ..., capped : ..., max : ... } ) " }, { "code": null, "e": 2662, "s": 2539, "text": "But we have created a randomly generated json file( of employee data) and we would import it onto our database by typing " }, { "code": null, "e": 2758, "s": 2662, "text": "mongoimport --jsonArray --db test --collection employee_data < \nC:\\mongoJson\\employee_data.json" }, { "code": null, "e": 2896, "s": 2758, "text": "This would import the Employee data json document referred by the path given in the collection named “employee_data” of database “test”. " }, { "code": null, "e": 3429, "s": 2896, "text": "Now to ensure the collection is imported you can type “show collections” in the shell. You can use methods like count(), find(), findOne() to do some very basic queries with your document. You can see that in every document there is a field called “_id” which was not provided in the data imported. The reason is that MongoDB provides a default “_id” (if not provided explicitly) which is a 12 byte hexadecimal number which assures the uniqueness of every document. You can even change this “_id” field but this is not recommended. " }, { "code": null, "e": 3747, "s": 3429, "text": "Indexing: You can also use indexing if your query returns more than one document. For example, db.employee_data.find() returns all the documents in the collection but if you just want the 7th one then, just do db.employee_data.find()[6] and it will return the specific document. [Note : Indexing starts from 0 here]. " }, { "code": null, "e": 4195, "s": 3747, "text": "Projections: Let’s say for a query you want only some specific details and not the whole set of detail in the document. You can use projections for this. After your query object just make the needed fields as 1 and others would be assumed as 0 automatically. But remember that the “_id” field is always assumed to be 1 implicitly and if you don’t want to see the ugly looking “_id” field, then you need to say this in your projection by “_id : 0” " }, { "code": null, "e": 4205, "s": 4195, "text": "Queries: " }, { "code": null, "e": 4269, "s": 4205, "text": "1. Find the number of employees with company “GEEKS FOR GEEKS” " }, { "code": null, "e": 4335, "s": 4269, "text": "> db.employee_data.find( { company= “GEEKS FOR GEEKS” } ).count()" }, { "code": null, "e": 4398, "s": 4335, "text": "2. Show the detail of all the employees named “Sandeep Jain” " }, { "code": null, "e": 4448, "s": 4398, "text": "> db.employee_data.find( { name: “Sandeep Jain” }" }, { "code": null, "e": 4522, "s": 4448, "text": "Here, all the documents which matches with the given name would show up. " }, { "code": null, "e": 4694, "s": 4522, "text": "3. Show the age, gender and email, but not “_id” of the employee named “Harshit Gupta”. (Assume that there is only one employee named Harshit Gupta). Usage of Projections " }, { "code": null, "e": 4784, "s": 4694, "text": "> db.employee_data.find( { name: “Harshit Gupta” }, { _id:0, age:1, gender:1, email:1 } )" }, { "code": null, "e": 4889, "s": 4784, "text": "We can also store the output of queries into variables and then make interesting queries with them too. " }, { "code": null, "e": 4938, "s": 4889, "text": "4. Print the name of all the female employees. " }, { "code": null, "e": 5147, "s": 4938, "text": "> var femaleEmp = db.employee_data.find( { gender: “female” } )\nfor ( var i = 0 ; i < femaleEmp.count() ; i++){\nprint ( femaleEmp[i].name)\n} \n> db.employee_data.find( { gender: \"female\" }, { _id:0, name:1 } )" }, { "code": null, "e": 5243, "s": 5147, "text": "Note that the 1st solution just prints out the names while 2nd one prints it in Object Format. " }, { "code": null, "e": 5629, "s": 5243, "text": "Article By Harshit Gupta: Kolkata based Harshit Gupta is an active blogger having keen interest in writing about algorithms,technical blogs, stories, and personal life experiences. Besides being passionate about writing, he also loves coding and dancing. Currently working in AMD, he is an active blog contributor at GeeksforGeeks. You can reach him at harshitguptablog.wordpress.com. " }, { "code": null, "e": 5755, "s": 5629, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5773, "s": 5755, "text": "gulshankumarar231" }, { "code": null, "e": 5781, "s": 5773, "text": "MongoDB" }, { "code": null, "e": 5787, "s": 5781, "text": "GBlog" } ]
How to Install a Python Module?
06 Oct, 2021 A module helps you to arrange your Python code logically. The code is easier to understand and use when it is organized into modules. You can bind and reference a module, which is a Python object with arbitrarily named attributes. A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. A module can be imported by multiple programs for their application, hence a single code can be used by multiple programs to get done with their functionalities faster and reliably. Check pip is installed or not: To check whether pip is installed or not, run the following command in windows using the command prompt: pip --version Output: Note: If the pip is not installed then refer to the article How to install PIP on Windows ? Output version should be equal or greater than 19 version, If not use the following command to update pip: pip install --upgrade pip wheel Output: To install the pip package use the following command to install the required package: pip install <packagename> To install the packages from the other resources, use the following command : pip install -e git+<https://github.com/myrepo.git#egg=packagename> To upgrade the packages that are already installed, use the following command: pip install --upgrade <packagename> To uninstall a package that is already installed, use the following command: pip uninstall <packagename> Make sure that you have pip installed. Type the below command in your terminal verify if the pip is installed or not. python3 -m pip --version Note: If the pip is not installed then refer to the article How to install PIP in Linux? How to install pip in macOS ? To update the installed pip and setup tools copies use the following command: python -m pip install --upgrade pip setuptools wheel Type the below command to install the module using pip. python3 -m pip install "ProjectName" To install the specific version of the module use the following command: python3 -m pip install "ProjectName==2.2" To install the version of a module in between any two numbers: python3 -m pip install "ProjectName>=2,<3" To install a specific compatible version of full length: python3 -m pip install "ProjectName~=2.2.3" To upgrade the project version use the following command: python3 -m pip install --upgrade ProjectName To install a required module that is in the text document: python3 -m pip install -r requirements.txt To install the directories that are present in the local system use the following command: python3 -m pip install --no-index --find-links=file:///local/dir/ ProjectName python3 -m pip install --no-index --find-links=/local/dir/ ProjectName python3 -m pip install --no-index --find-links=relative/dir/ProjectName The majority of Python packages are now designed to work with pip. If you have a kit that isn’t compatible, you’ll have to install it manually. Install the kit by downloading it and then extracting it to a local directory. If the kit has its own set of installation instructions, obey them, if the package is not present there then use the following command to install the package using the command manually: python <FILE_NAME>.py install how-to-install Picked Python-pip How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers? How to Install Git in VS Code? Installation of Node.js on Linux Installation of Node.js on Windows How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 260, "s": 28, "text": "A module helps you to arrange your Python code logically. The code is easier to understand and use when it is organized into modules. You can bind and reference a module, which is a Python object with arbitrarily named attributes. " }, { "code": null, "e": 603, "s": 260, "text": "A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. A module can be imported by multiple programs for their application, hence a single code can be used by multiple programs to get done with their functionalities faster and reliably." }, { "code": null, "e": 739, "s": 603, "text": "Check pip is installed or not: To check whether pip is installed or not, run the following command in windows using the command prompt:" }, { "code": null, "e": 754, "s": 739, "text": "pip --version " }, { "code": null, "e": 762, "s": 754, "text": "Output:" }, { "code": null, "e": 854, "s": 762, "text": "Note: If the pip is not installed then refer to the article How to install PIP on Windows ?" }, { "code": null, "e": 961, "s": 854, "text": "Output version should be equal or greater than 19 version, If not use the following command to update pip:" }, { "code": null, "e": 993, "s": 961, "text": "pip install --upgrade pip wheel" }, { "code": null, "e": 1001, "s": 993, "text": "Output:" }, { "code": null, "e": 1087, "s": 1001, "text": "To install the pip package use the following command to install the required package:" }, { "code": null, "e": 1114, "s": 1087, "text": "pip install <packagename> " }, { "code": null, "e": 1192, "s": 1114, "text": "To install the packages from the other resources, use the following command :" }, { "code": null, "e": 1259, "s": 1192, "text": "pip install -e git+<https://github.com/myrepo.git#egg=packagename>" }, { "code": null, "e": 1338, "s": 1259, "text": "To upgrade the packages that are already installed, use the following command:" }, { "code": null, "e": 1374, "s": 1338, "text": "pip install --upgrade <packagename>" }, { "code": null, "e": 1451, "s": 1374, "text": "To uninstall a package that is already installed, use the following command:" }, { "code": null, "e": 1479, "s": 1451, "text": "pip uninstall <packagename>" }, { "code": null, "e": 1597, "s": 1479, "text": "Make sure that you have pip installed. Type the below command in your terminal verify if the pip is installed or not." }, { "code": null, "e": 1622, "s": 1597, "text": "python3 -m pip --version" }, { "code": null, "e": 1682, "s": 1622, "text": "Note: If the pip is not installed then refer to the article" }, { "code": null, "e": 1711, "s": 1682, "text": "How to install PIP in Linux?" }, { "code": null, "e": 1741, "s": 1711, "text": "How to install pip in macOS ?" }, { "code": null, "e": 1819, "s": 1741, "text": "To update the installed pip and setup tools copies use the following command:" }, { "code": null, "e": 1872, "s": 1819, "text": "python -m pip install --upgrade pip setuptools wheel" }, { "code": null, "e": 1928, "s": 1872, "text": "Type the below command to install the module using pip." }, { "code": null, "e": 1965, "s": 1928, "text": "python3 -m pip install \"ProjectName\"" }, { "code": null, "e": 2038, "s": 1965, "text": "To install the specific version of the module use the following command:" }, { "code": null, "e": 2080, "s": 2038, "text": "python3 -m pip install \"ProjectName==2.2\"" }, { "code": null, "e": 2143, "s": 2080, "text": "To install the version of a module in between any two numbers:" }, { "code": null, "e": 2186, "s": 2143, "text": "python3 -m pip install \"ProjectName>=2,<3\"" }, { "code": null, "e": 2243, "s": 2186, "text": "To install a specific compatible version of full length:" }, { "code": null, "e": 2287, "s": 2243, "text": "python3 -m pip install \"ProjectName~=2.2.3\"" }, { "code": null, "e": 2345, "s": 2287, "text": "To upgrade the project version use the following command:" }, { "code": null, "e": 2390, "s": 2345, "text": "python3 -m pip install --upgrade ProjectName" }, { "code": null, "e": 2449, "s": 2390, "text": "To install a required module that is in the text document:" }, { "code": null, "e": 2492, "s": 2449, "text": "python3 -m pip install -r requirements.txt" }, { "code": null, "e": 2583, "s": 2492, "text": "To install the directories that are present in the local system use the following command:" }, { "code": null, "e": 2804, "s": 2583, "text": "python3 -m pip install --no-index --find-links=file:///local/dir/ ProjectName\npython3 -m pip install --no-index --find-links=/local/dir/ ProjectName\npython3 -m pip install --no-index --find-links=relative/dir/ProjectName" }, { "code": null, "e": 2948, "s": 2804, "text": "The majority of Python packages are now designed to work with pip. If you have a kit that isn’t compatible, you’ll have to install it manually." }, { "code": null, "e": 3213, "s": 2948, "text": "Install the kit by downloading it and then extracting it to a local directory. If the kit has its own set of installation instructions, obey them, if the package is not present there then use the following command to install the package using the command manually:" }, { "code": null, "e": 3243, "s": 3213, "text": "python <FILE_NAME>.py install" }, { "code": null, "e": 3258, "s": 3243, "text": "how-to-install" }, { "code": null, "e": 3265, "s": 3258, "text": "Picked" }, { "code": null, "e": 3276, "s": 3265, "text": "Python-pip" }, { "code": null, "e": 3283, "s": 3276, "text": "How To" }, { "code": null, "e": 3302, "s": 3283, "text": "Installation Guide" }, { "code": null, "e": 3309, "s": 3302, "text": "Python" }, { "code": null, "e": 3407, "s": 3309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3456, "s": 3407, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 3498, "s": 3456, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 3537, "s": 3498, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 3591, "s": 3537, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 3622, "s": 3591, "text": "How to Install Git in VS Code?" }, { "code": null, "e": 3655, "s": 3622, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3690, "s": 3655, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3732, "s": 3690, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 3771, "s": 3732, "text": "How to Install and Use NVM on Windows?" } ]
How to Create a Wave Image for a Background using HTML and CSS ?
23 Jan, 2022 This type of background creates uniqueness on your webpage by avoiding regular rectangular sized background or header. The following header design will show your creativity. This design can be achieved in two ways: Using ::before and ::after selector on a div element in CSS. Using SVG in HTML. Example: This example uses ::before and ::after selector on a div element to create a wave image for background. html <!DOCTYPE html><html> <head> <title> How to Create a Wave Image for a Background using CSS? </title> <style> .wave { position: absolute; top: 0px; left: 0px; right: 0px; height: 70px; width: 100%; background: dodgerblue; z-index: -1; } .wave::before { content: ""; display: block; position: absolute; border-radius: 100% 90%; width: 51%; height: 75px; background-color: white; right: 0px; top: 35px; } .wave::after { content: ""; display: block; position: absolute; border-radius: 100% 90%; width: 51%; height: 75px; background-color: dodgerblue; left: -8px; top: 25px; } </style></head> <body style="text-align:center;"> <h1 style="color:forestgreen;"> Geeks For Geeks </h1> <div class="wave"></div></body> </html> Output: The problem of using before and after is as we have to define their position in pixels thus as the screen height changes its shape changes and so it is not that proper as it seems. So, for that purpose we use SVG in CSS.Example: This example uses SVG to design a wave image for background. html <!DOCTYPE html><html> <head> <title> How to Create a Wave Image for a Background using CSS? </title> <style> svg { display: inline-block; position: absolute; top: 0; left: 0; z-index: -1; } .container { display: inline-block; position: absolute; width: 100%; padding-bottom: 100%; vertical-align: middle; overflow: hidden; top: 0; left: 0; } body { overflow: hidden; } </style></head> <body style="text-align:center;"> <h1 style="color:lawngreen;"> Geeks For Geeks </h1> <div class="container"> <!-- Creating a SVG image --> <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet"> <path d="M0, 100 C150, 200 350, 0 500, 100 L500, 00 L0, 0 Z" style="stroke:none; fill:dodgerblue;"> </path> </svg> </div></body> </html> Output: Example: This example uses SVG to design a wave image for background. html <!DOCTYPE html><html> <head> <title> How to Create a Wave Image for a Background using CSS? </title> <style> svg { display: inline-block; position: absolute; top: 0; left: 0; } .container { display: inline-block; position: absolute; width: 100%; padding-bottom: 100%; vertical-align: middle; overflow: hidden; top: 0; left: 0; } body { overflow: hidden; } </style></head> <body style="text-align:center;"> <h1 style="color:white;"> Geeks For Geeks </h1> <div class="container"> <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet" style="z-index: -2;"> <path d="M0, 100 C150, 200 350, 0 500, 100 L500, 00 L0, 0 Z" style="stroke: none; fill:rgba(30, 144, 225, 0.5);"> </path> </svg> </div> <div class="container"> <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet" style="z-index:-1;"> <path d="M0, 80 C300, 0 400, 300 500, 50 L500, 00 L0, 0 Z" style="stroke: none; fill:rgba(153, 50, 204, 0.5);"> </path> </svg> </div> <div class="container"> <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet" style="z-index:-3;"> <path d="M0, 100 C150, 300 350, 0 500, 100 L500, 00 L0, 0 Z" style="stroke: none; fill:rgba(220, 20, 60, 0.5);"> </path> </svg> </div></body> </html> Output: adnanirshad158 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Create a Responsive Navbar using ReactJS Build a Survey Form using HTML and CSS Make a div horizontally scrollable using CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jan, 2022" }, { "code": null, "e": 271, "s": 54, "text": "This type of background creates uniqueness on your webpage by avoiding regular rectangular sized background or header. The following header design will show your creativity. This design can be achieved in two ways: " }, { "code": null, "e": 332, "s": 271, "text": "Using ::before and ::after selector on a div element in CSS." }, { "code": null, "e": 351, "s": 332, "text": "Using SVG in HTML." }, { "code": null, "e": 465, "s": 351, "text": "Example: This example uses ::before and ::after selector on a div element to create a wave image for background. " }, { "code": null, "e": 470, "s": 465, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to Create a Wave Image for a Background using CSS? </title> <style> .wave { position: absolute; top: 0px; left: 0px; right: 0px; height: 70px; width: 100%; background: dodgerblue; z-index: -1; } .wave::before { content: \"\"; display: block; position: absolute; border-radius: 100% 90%; width: 51%; height: 75px; background-color: white; right: 0px; top: 35px; } .wave::after { content: \"\"; display: block; position: absolute; border-radius: 100% 90%; width: 51%; height: 75px; background-color: dodgerblue; left: -8px; top: 25px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:forestgreen;\"> Geeks For Geeks </h1> <div class=\"wave\"></div></body> </html>", "e": 1573, "s": 470, "text": null }, { "code": null, "e": 1583, "s": 1573, "text": "Output: " }, { "code": null, "e": 1875, "s": 1583, "text": "The problem of using before and after is as we have to define their position in pixels thus as the screen height changes its shape changes and so it is not that proper as it seems. So, for that purpose we use SVG in CSS.Example: This example uses SVG to design a wave image for background. " }, { "code": null, "e": 1880, "s": 1875, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to Create a Wave Image for a Background using CSS? </title> <style> svg { display: inline-block; position: absolute; top: 0; left: 0; z-index: -1; } .container { display: inline-block; position: absolute; width: 100%; padding-bottom: 100%; vertical-align: middle; overflow: hidden; top: 0; left: 0; } body { overflow: hidden; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:lawngreen;\"> Geeks For Geeks </h1> <div class=\"container\"> <!-- Creating a SVG image --> <svg viewBox=\"0 0 500 500\" preserveAspectRatio=\"xMinYMin meet\"> <path d=\"M0, 100 C150, 200 350, 0 500, 100 L500, 00 L0, 0 Z\" style=\"stroke:none; fill:dodgerblue;\"> </path> </svg> </div></body> </html>", "e": 2966, "s": 1880, "text": null }, { "code": null, "e": 2976, "s": 2966, "text": "Output: " }, { "code": null, "e": 3048, "s": 2976, "text": "Example: This example uses SVG to design a wave image for background. " }, { "code": null, "e": 3053, "s": 3048, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to Create a Wave Image for a Background using CSS? </title> <style> svg { display: inline-block; position: absolute; top: 0; left: 0; } .container { display: inline-block; position: absolute; width: 100%; padding-bottom: 100%; vertical-align: middle; overflow: hidden; top: 0; left: 0; } body { overflow: hidden; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:white;\"> Geeks For Geeks </h1> <div class=\"container\"> <svg viewBox=\"0 0 500 500\" preserveAspectRatio=\"xMinYMin meet\" style=\"z-index: -2;\"> <path d=\"M0, 100 C150, 200 350, 0 500, 100 L500, 00 L0, 0 Z\" style=\"stroke: none; fill:rgba(30, 144, 225, 0.5);\"> </path> </svg> </div> <div class=\"container\"> <svg viewBox=\"0 0 500 500\" preserveAspectRatio=\"xMinYMin meet\" style=\"z-index:-1;\"> <path d=\"M0, 80 C300, 0 400, 300 500, 50 L500, 00 L0, 0 Z\" style=\"stroke: none; fill:rgba(153, 50, 204, 0.5);\"> </path> </svg> </div> <div class=\"container\"> <svg viewBox=\"0 0 500 500\" preserveAspectRatio=\"xMinYMin meet\" style=\"z-index:-3;\"> <path d=\"M0, 100 C150, 300 350, 0 500, 100 L500, 00 L0, 0 Z\" style=\"stroke: none; fill:rgba(220, 20, 60, 0.5);\"> </path> </svg> </div></body> </html>", "e": 4869, "s": 3053, "text": null }, { "code": null, "e": 4879, "s": 4869, "text": "Output: " }, { "code": null, "e": 4896, "s": 4881, "text": "adnanirshad158" }, { "code": null, "e": 4905, "s": 4896, "text": "CSS-Misc" }, { "code": null, "e": 4915, "s": 4905, "text": "HTML-Misc" }, { "code": null, "e": 4919, "s": 4915, "text": "CSS" }, { "code": null, "e": 4924, "s": 4919, "text": "HTML" }, { "code": null, "e": 4941, "s": 4924, "text": "Web Technologies" }, { "code": null, "e": 4968, "s": 4941, "text": "Web technologies Questions" }, { "code": null, "e": 4973, "s": 4968, "text": "HTML" }, { "code": null, "e": 5071, "s": 4973, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5110, "s": 5071, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 5149, "s": 5110, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 5190, "s": 5149, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 5229, "s": 5190, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 5274, "s": 5229, "text": "Make a div horizontally scrollable using CSS" }, { "code": null, "e": 5298, "s": 5274, "text": "REST API (Introduction)" }, { "code": null, "e": 5351, "s": 5298, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5411, "s": 5351, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5472, "s": 5411, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]