title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Car Model Classification. In this post I will show the result for... | by Weng Seng | Towards Data Science
In this post I will show the result for car model classification with ResNet ( Residual Neutral Network). I use Python and Pytorch to build the model. The steps were similar to my previous flower species classifier project so I will brief about some key steps and the result. You can check my github repo here. I download the Stanford car dataset from Kaggle by using Kaggle API and save in my google drive. # The Kaggle API client expects this file to be in ~/.kaggle,!mkdir -p ~/.kaggle!cp kaggle.json ~/.kaggle/# This permissions change avoids a warning on Kaggle tool startup.!chmod 600 ~/.kaggle/kaggle.json#mount my gdrivefrom google.colab import drivedrive.mount('/content/drive')#download the dataset!kaggle datasets download -d jutrera/stanford-car-dataset-by-classes-folder#unzip the file!unzip stanford-car-dataset-by-classes-folder.zip The Cars dataset contains 16,185 images of 196 classes of cars. The data is split into 8,144 training images and 8,041 testing images. Transfer learning make use of the knowledge gained while solving one problem and applying it to a different but related problem.The pre-trained model here is ResNet( Residual Neutral Network). Artificial Neural Network predicts the outcome by learn through the examples and previous experiences. Artificial Neural Network computations carried out in parallel and create their own representation of information which they receive during the learning time. In the artificial Neural Network, just add in one more layer which is convolutional layer. For further explanation about ResNet architectures you can refer here. Back to our case here, we got 196 classes of cars as the total number of outputs so we need change the output layer into 196. num_ftrs = model.fc.in_featuresmodel.fc = nn.Linear(num_ftrs, 196) I have try few parameter and keep running epochs for quite a few times. In the end with 10 epochs it give us 77.72% validation accuracy give me the best so far I tried. The training process really time consuming just need to be patient. Cheer! Let see what it actually did!! For the Mercedes-Benz S-Class Sedan 2012 the model predicted Mercedes-Benz E-Class Sedan 2012 which is inaccurate. The Mercedes-Benz S-Class Sedan 2012 also didn’t appear in the top 5 predicted classes.BMW X6 SUV 2012 predicted semi-correctly because it appeared in third top classes. It supposed be the top classes in the prediction result not the Ford Fiesta Sedan 2012. Hyundai Veloster Hatchback 2012 and Volkswagen Golf Hatchback 2012 were well predicted with more than 30%. Both are BMW 3 Series Sedan 2012 just the different is the angle view. The left image is front view and the right image is rear view. Surprisingly both different view of BMW 3 predicted correctly. The top 5 prediction result in the left side was very good because it predicted the top 5 classes were all BMW. In the right side result also good, BMW appeared in the top 3. However, in this case BMW M5 Sedan 2010 does not performing, it got all top 5 prediction classes wrong. Any BMW car model did not show up in the result. In this case both model were SUV models and predicted correctly.
[ { "code": null, "e": 447, "s": 171, "text": "In this post I will show the result for car model classification with ResNet ( Residual Neutral Network). I use Python and Pytorch to build the model. The steps were similar to my previous flower species classifier project so I will brief about some key steps and the result." }, { "code": null, "e": 482, "s": 447, "text": "You can check my github repo here." }, { "code": null, "e": 579, "s": 482, "text": "I download the Stanford car dataset from Kaggle by using Kaggle API and save in my google drive." }, { "code": null, "e": 1019, "s": 579, "text": "# The Kaggle API client expects this file to be in ~/.kaggle,!mkdir -p ~/.kaggle!cp kaggle.json ~/.kaggle/# This permissions change avoids a warning on Kaggle tool startup.!chmod 600 ~/.kaggle/kaggle.json#mount my gdrivefrom google.colab import drivedrive.mount('/content/drive')#download the dataset!kaggle datasets download -d jutrera/stanford-car-dataset-by-classes-folder#unzip the file!unzip stanford-car-dataset-by-classes-folder.zip" }, { "code": null, "e": 1154, "s": 1019, "text": "The Cars dataset contains 16,185 images of 196 classes of cars. The data is split into 8,144 training images and 8,041 testing images." }, { "code": null, "e": 1347, "s": 1154, "text": "Transfer learning make use of the knowledge gained while solving one problem and applying it to a different but related problem.The pre-trained model here is ResNet( Residual Neutral Network)." }, { "code": null, "e": 1700, "s": 1347, "text": "Artificial Neural Network predicts the outcome by learn through the examples and previous experiences. Artificial Neural Network computations carried out in parallel and create their own representation of information which they receive during the learning time. In the artificial Neural Network, just add in one more layer which is convolutional layer." }, { "code": null, "e": 1771, "s": 1700, "text": "For further explanation about ResNet architectures you can refer here." }, { "code": null, "e": 1897, "s": 1771, "text": "Back to our case here, we got 196 classes of cars as the total number of outputs so we need change the output layer into 196." }, { "code": null, "e": 1964, "s": 1897, "text": "num_ftrs = model.fc.in_featuresmodel.fc = nn.Linear(num_ftrs, 196)" }, { "code": null, "e": 2208, "s": 1964, "text": "I have try few parameter and keep running epochs for quite a few times. In the end with 10 epochs it give us 77.72% validation accuracy give me the best so far I tried. The training process really time consuming just need to be patient. Cheer!" }, { "code": null, "e": 2239, "s": 2208, "text": "Let see what it actually did!!" }, { "code": null, "e": 2612, "s": 2239, "text": "For the Mercedes-Benz S-Class Sedan 2012 the model predicted Mercedes-Benz E-Class Sedan 2012 which is inaccurate. The Mercedes-Benz S-Class Sedan 2012 also didn’t appear in the top 5 predicted classes.BMW X6 SUV 2012 predicted semi-correctly because it appeared in third top classes. It supposed be the top classes in the prediction result not the Ford Fiesta Sedan 2012." }, { "code": null, "e": 2719, "s": 2612, "text": "Hyundai Veloster Hatchback 2012 and Volkswagen Golf Hatchback 2012 were well predicted with more than 30%." }, { "code": null, "e": 3091, "s": 2719, "text": "Both are BMW 3 Series Sedan 2012 just the different is the angle view. The left image is front view and the right image is rear view. Surprisingly both different view of BMW 3 predicted correctly. The top 5 prediction result in the left side was very good because it predicted the top 5 classes were all BMW. In the right side result also good, BMW appeared in the top 3." }, { "code": null, "e": 3244, "s": 3091, "text": "However, in this case BMW M5 Sedan 2010 does not performing, it got all top 5 prediction classes wrong. Any BMW car model did not show up in the result." } ]
Set Pandas dataframe background Color and font color in Python - GeeksforGeeks
06 Aug, 2021 As we know, the basic idea behind styling is to make more impactful for the end-user readability. We can make changes like the color and format of the data visualized in order to communicate insight more efficiently. For the more impactful visualization on the pandas DataFrame, generally, we DataFrame.style property, which returns styler object having a number of useful methods for formatting and visualizing the data frames. df.style.set_properties: By using this, we can use inbuilt functionality to manipulate data frame styling from font color to background color. Python3 # Importing the necessary libraries -->import pandas as pdimport numpy as np # Seeding random data from numpynp.random.seed(24) # Making the DataFramedf = pd.DataFrame({'A': np.linspace(1, 10, 10)})df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) # DataFrame without any stylingprint("Original DataFrame:\n")print(df)print("\nModified Stlying DataFrame:")df.style.set_properties(**{'background-color': 'black', 'color': 'green'}) Output: df.style.set_properties df.style.highlight_null : With the help of this, we can highlight the missing or null values inside the data frame. Python3 # Replacing the locating value by NaN (Not a Number)df.iloc[0, 3] = np.nandf.iloc[2, 3] = np.nandf.iloc[4, 2] = np.nandf.iloc[7, 4] = np.nan # Highlight the NaN values in DataFrameprint("\nModified Stlying DataFrame:")df.style.highlight_null(null_color='red') Output: df.style.highlight_null df.style.highlight_min : For highlighting the minimum value in each column throughout the data frame. Python3 # Highlight the Min values in each columnprint("\nModified Stlying DataFrame:")df.style.highlight_min(axis=0) Output: df.style.highlight_min df.style.highlight_max : For highlighting the maximum value in each column throughout the data frame. Python3 # Highlight the Max values in each columnprint("\nModified Stlying DataFrame:")df.style.highlight_max(axis=0) Output: df.style.highlight_max We can modify DataFrame using a user-defined function: With the help of this function, we can customizing the font color of positive data values inside the data frame. Python3 # function for set text color of positive# values in Dataframesdef color_positive_green(val): """ Takes a scalar and returns a string with the css property `'color: green'` for positive strings, black otherwise. """ if val > 0: color = 'green' else: color = 'black' return 'color: %s' % color df.style.applymap(color_positive_green) Output: User-Defined Function Using color palette for gradient fill in DataFrame: By importing the light palette of colors from the seaborn library, we can map the color gradient for the background of the data frame. Python3 # Import seaborn libraryimport seaborn as sns # Declaring the cm variable by the# color palette from seaborncm = sns.light_palette("green", as_cmap=True) # Visualizing the DataFrame with set precisionprint("\nModified Stlying DataFrame:")df.style.background_gradient(cmap=cm).set_precision(2) Output: Seaborn Color Palette Using color palette with highlight null or missing values: Here, we highlight the NaN values in red color with gradient color palette of seaborn. Python3 # Highlight the NaN values in DataFrame# using seaborn color paletteprint("\nModified Stlying DataFrame:")df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red') Output: Seaborn Color Palette with highlight_null Assemble Seaborn properties with DataFrame.style property: Customizing the seaborn color palette with highlight properties of a data frame for more impactful data visualization. Python3 # Highlight the NaN values in DataFrame# using seaborn color palette as well as# min('lighblue') and max('blue') values# in each columnprint("\nModified Stlying DataFrame:")df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red').highlight_min(axis=0, color='lightblue').highlight_max(axis=0, color='blue') Output: Seaborn Color Palette with diff. highlight properties sooda367 saurabh1990aror pandas-dataframe-program Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26357, "s": 26329, "text": "\n06 Aug, 2021" }, { "code": null, "e": 26786, "s": 26357, "text": "As we know, the basic idea behind styling is to make more impactful for the end-user readability. We can make changes like the color and format of the data visualized in order to communicate insight more efficiently. For the more impactful visualization on the pandas DataFrame, generally, we DataFrame.style property, which returns styler object having a number of useful methods for formatting and visualizing the data frames." }, { "code": null, "e": 26929, "s": 26786, "text": "df.style.set_properties: By using this, we can use inbuilt functionality to manipulate data frame styling from font color to background color." }, { "code": null, "e": 26937, "s": 26929, "text": "Python3" }, { "code": "# Importing the necessary libraries -->import pandas as pdimport numpy as np # Seeding random data from numpynp.random.seed(24) # Making the DataFramedf = pd.DataFrame({'A': np.linspace(1, 10, 10)})df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) # DataFrame without any stylingprint(\"Original DataFrame:\\n\")print(df)print(\"\\nModified Stlying DataFrame:\")df.style.set_properties(**{'background-color': 'black', 'color': 'green'})", "e": 27465, "s": 26937, "text": null }, { "code": null, "e": 27474, "s": 27465, "text": "Output: " }, { "code": null, "e": 27498, "s": 27474, "text": "df.style.set_properties" }, { "code": null, "e": 27614, "s": 27498, "text": "df.style.highlight_null : With the help of this, we can highlight the missing or null values inside the data frame." }, { "code": null, "e": 27622, "s": 27614, "text": "Python3" }, { "code": "# Replacing the locating value by NaN (Not a Number)df.iloc[0, 3] = np.nandf.iloc[2, 3] = np.nandf.iloc[4, 2] = np.nandf.iloc[7, 4] = np.nan # Highlight the NaN values in DataFrameprint(\"\\nModified Stlying DataFrame:\")df.style.highlight_null(null_color='red')", "e": 27882, "s": 27622, "text": null }, { "code": null, "e": 27891, "s": 27882, "text": "Output: " }, { "code": null, "e": 27915, "s": 27891, "text": "df.style.highlight_null" }, { "code": null, "e": 28018, "s": 27915, "text": "df.style.highlight_min : For highlighting the minimum value in each column throughout the data frame." }, { "code": null, "e": 28026, "s": 28018, "text": "Python3" }, { "code": "# Highlight the Min values in each columnprint(\"\\nModified Stlying DataFrame:\")df.style.highlight_min(axis=0)", "e": 28136, "s": 28026, "text": null }, { "code": null, "e": 28145, "s": 28136, "text": "Output: " }, { "code": null, "e": 28168, "s": 28145, "text": "df.style.highlight_min" }, { "code": null, "e": 28270, "s": 28168, "text": "df.style.highlight_max : For highlighting the maximum value in each column throughout the data frame." }, { "code": null, "e": 28278, "s": 28270, "text": "Python3" }, { "code": "# Highlight the Max values in each columnprint(\"\\nModified Stlying DataFrame:\")df.style.highlight_max(axis=0)", "e": 28388, "s": 28278, "text": null }, { "code": null, "e": 28397, "s": 28388, "text": "Output: " }, { "code": null, "e": 28420, "s": 28397, "text": "df.style.highlight_max" }, { "code": null, "e": 28588, "s": 28420, "text": "We can modify DataFrame using a user-defined function: With the help of this function, we can customizing the font color of positive data values inside the data frame." }, { "code": null, "e": 28596, "s": 28588, "text": "Python3" }, { "code": "# function for set text color of positive# values in Dataframesdef color_positive_green(val): \"\"\" Takes a scalar and returns a string with the css property `'color: green'` for positive strings, black otherwise. \"\"\" if val > 0: color = 'green' else: color = 'black' return 'color: %s' % color df.style.applymap(color_positive_green)", "e": 28967, "s": 28596, "text": null }, { "code": null, "e": 28976, "s": 28967, "text": "Output: " }, { "code": null, "e": 28998, "s": 28976, "text": "User-Defined Function" }, { "code": null, "e": 29185, "s": 28998, "text": "Using color palette for gradient fill in DataFrame: By importing the light palette of colors from the seaborn library, we can map the color gradient for the background of the data frame." }, { "code": null, "e": 29193, "s": 29185, "text": "Python3" }, { "code": "# Import seaborn libraryimport seaborn as sns # Declaring the cm variable by the# color palette from seaborncm = sns.light_palette(\"green\", as_cmap=True) # Visualizing the DataFrame with set precisionprint(\"\\nModified Stlying DataFrame:\")df.style.background_gradient(cmap=cm).set_precision(2)", "e": 29486, "s": 29193, "text": null }, { "code": null, "e": 29495, "s": 29486, "text": "Output: " }, { "code": null, "e": 29517, "s": 29495, "text": "Seaborn Color Palette" }, { "code": null, "e": 29663, "s": 29517, "text": "Using color palette with highlight null or missing values: Here, we highlight the NaN values in red color with gradient color palette of seaborn." }, { "code": null, "e": 29671, "s": 29663, "text": "Python3" }, { "code": "# Highlight the NaN values in DataFrame# using seaborn color paletteprint(\"\\nModified Stlying DataFrame:\")df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red')", "e": 29854, "s": 29671, "text": null }, { "code": null, "e": 29863, "s": 29854, "text": "Output: " }, { "code": null, "e": 29905, "s": 29863, "text": "Seaborn Color Palette with highlight_null" }, { "code": null, "e": 30083, "s": 29905, "text": "Assemble Seaborn properties with DataFrame.style property: Customizing the seaborn color palette with highlight properties of a data frame for more impactful data visualization." }, { "code": null, "e": 30091, "s": 30083, "text": "Python3" }, { "code": "# Highlight the NaN values in DataFrame# using seaborn color palette as well as# min('lighblue') and max('blue') values# in each columnprint(\"\\nModified Stlying DataFrame:\")df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red').highlight_min(axis=0, color='lightblue').highlight_max(axis=0, color='blue')", "e": 30418, "s": 30091, "text": null }, { "code": null, "e": 30427, "s": 30418, "text": "Output: " }, { "code": null, "e": 30481, "s": 30427, "text": "Seaborn Color Palette with diff. highlight properties" }, { "code": null, "e": 30492, "s": 30483, "text": "sooda367" }, { "code": null, "e": 30508, "s": 30492, "text": "saurabh1990aror" }, { "code": null, "e": 30533, "s": 30508, "text": "pandas-dataframe-program" }, { "code": null, "e": 30557, "s": 30533, "text": "Python pandas-dataFrame" }, { "code": null, "e": 30580, "s": 30557, "text": "Python Pandas-exercise" }, { "code": null, "e": 30594, "s": 30580, "text": "Python-pandas" }, { "code": null, "e": 30601, "s": 30594, "text": "Python" }, { "code": null, "e": 30699, "s": 30601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30717, "s": 30699, "text": "Python Dictionary" }, { "code": null, "e": 30752, "s": 30717, "text": "Read a file line by line in Python" }, { "code": null, "e": 30784, "s": 30752, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30806, "s": 30784, "text": "Enumerate() in Python" }, { "code": null, "e": 30836, "s": 30806, "text": "Iterate over a list in Python" }, { "code": null, "e": 30862, "s": 30836, "text": "Python String | replace()" }, { "code": null, "e": 30891, "s": 30862, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30935, "s": 30891, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30971, "s": 30935, "text": "Convert integer to string in Python" } ]
std::swap_ranges in C++ - GeeksforGeeks
25 Jul, 2017 std::swap is used for swapping of elements between two containers. One of its variation is std::swap_ranges, which as the name suggests is used for swapping the elements within a range. It simply exchanges the values of each of the elements in the range [first1, last1) with those of their respective elements in the range beginning at first2. If we look at its internal working, we will find that this function itself uses std::swap(). Syntax: std::swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2); Here, first1, last1 and first2 are forward iterators. Returns: It returns an iterator to the last element swapped in the second sequence. // C++ program to demonstrate // the use of std::swap_ranges#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ // Declaring first vector vector<int> v1; int i; // v1 contains 0 1 2 3 4 5 6 7 8 9 for (i = 0; i < 10; ++i) { v1.push_back(i); } // Declaring second vector // v2 contains 100 100 100 100 100 vector<int> v2(5, 100); // Performing swap std::swap_ranges(v1.begin() + 3, v1.begin() + 7, v2.begin()); // Displaying v1 after swapping for (i = 0; i < 10; ++i) { cout << v1[i] << " "; } cout << "\n"; // Displaying v2 after swapping for (i = 0; i < 5; ++i) { cout << v2[i] << " "; } return 0;} Output: 0 1 2 100 100 100 100 7 8 9 3 4 5 6 100 Here, in this program we have swapped elements from v1 starting at v1.begin()+3 till v1.begin()+7, with the values starting from v2.begin(), so in place of swapping the whole vector, we have performed swapping in a range. Where can it be used ?It can be used when we have to find whether a given container contains the same element in its first half as well as in the second half as well, i.e., whether both the halves are identical to each other or not. // C++ program to demonstrate // the use of std::swap_ranges#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ // Here 5 is the central element and the two halves // on its either side contain the same elements 1 2 3 4 vector<int> v1 = { 1, 2, 3, 4, 5, 1, 2, 3, 4 }; int i; // Declaring second vector and making it equal to v1 vector<int> v2 = v1; // Here there is no central element and the two halves // are 1 2 3 4 and 1 2 3 5 which are different vector<int> v3 = { 1, 2, 3, 4, 1, 2, 3, 5 }; // Declaring fourth vector and making it equal to v3 vector<int> v4 = v3; // Performing swap between two halves of vector v1 if (v1.size() % 2 == 0) std::swap_ranges(v1.begin(), v1.begin() + (v1.size() / 2), v1.begin() + v1.size() / 2); else std::swap_ranges(v1.begin(), v1.begin() + v1.size() / 2, v1.begin() + (v1.size() / 2) + 1); if (v1 == v2) { cout << "Yes"; } else { cout << "No"; } // Now, Performing swap between two halves of vector v3 if (v3.size() % 2 == 0) std::swap_ranges(v3.begin(), v3.begin() + (v3.size() / 2), v3.begin() + v3.size() / 2); else std::swap_ranges(v3.begin(), v3.begin() + v3.size() / 2, v3.begin() + (v3.size() / 2) + 1); cout << "\n"; if (v3 == v4) { cout << "Yes"; } else { cout << "No"; } return 0;} Output: Yes No Explanation of code: Here, in this code, we have declared a vector and then assigned it to another vector, and then in the first vector, we are swapping values in the first half with the second half depending upon whether it contains odd no. of elements or not. If after swapping the values, the new first vector is same as second vector (old first vector), this means that both the halves are same. So, in the first vector 1 2 3 4 5 1 2 3 4, it contains same element in both the halves, so Yes is printed, whereas in second vector 1 2 3 4 1 2 3 5, second half contains one different element than first half, i.e., 4 in place of 5, so No is printed. Time Complexity: It is linear in the distance between first and last. This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-algorithm-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++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25369, "s": 25341, "text": "\n25 Jul, 2017" }, { "code": null, "e": 25555, "s": 25369, "text": "std::swap is used for swapping of elements between two containers. One of its variation is std::swap_ranges, which as the name suggests is used for swapping the elements within a range." }, { "code": null, "e": 25806, "s": 25555, "text": "It simply exchanges the values of each of the elements in the range [first1, last1) with those of their respective elements in the range beginning at first2. If we look at its internal working, we will find that this function itself uses std::swap()." }, { "code": null, "e": 25814, "s": 25806, "text": "Syntax:" }, { "code": null, "e": 26065, "s": 25814, "text": "std::swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,\n ForwardIterator2 first2);\n\nHere, first1, last1 and first2 are forward iterators.\nReturns: It returns an iterator to the last element swapped in the second sequence.\n" }, { "code": "// C++ program to demonstrate // the use of std::swap_ranges#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ // Declaring first vector vector<int> v1; int i; // v1 contains 0 1 2 3 4 5 6 7 8 9 for (i = 0; i < 10; ++i) { v1.push_back(i); } // Declaring second vector // v2 contains 100 100 100 100 100 vector<int> v2(5, 100); // Performing swap std::swap_ranges(v1.begin() + 3, v1.begin() + 7, v2.begin()); // Displaying v1 after swapping for (i = 0; i < 10; ++i) { cout << v1[i] << \" \"; } cout << \"\\n\"; // Displaying v2 after swapping for (i = 0; i < 5; ++i) { cout << v2[i] << \" \"; } return 0;}", "e": 26822, "s": 26065, "text": null }, { "code": null, "e": 26830, "s": 26822, "text": "Output:" }, { "code": null, "e": 26871, "s": 26830, "text": "0 1 2 100 100 100 100 7 8 9\n3 4 5 6 100\n" }, { "code": null, "e": 27093, "s": 26871, "text": "Here, in this program we have swapped elements from v1 starting at v1.begin()+3 till v1.begin()+7, with the values starting from v2.begin(), so in place of swapping the whole vector, we have performed swapping in a range." }, { "code": null, "e": 27326, "s": 27093, "text": "Where can it be used ?It can be used when we have to find whether a given container contains the same element in its first half as well as in the second half as well, i.e., whether both the halves are identical to each other or not." }, { "code": "// C++ program to demonstrate // the use of std::swap_ranges#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ // Here 5 is the central element and the two halves // on its either side contain the same elements 1 2 3 4 vector<int> v1 = { 1, 2, 3, 4, 5, 1, 2, 3, 4 }; int i; // Declaring second vector and making it equal to v1 vector<int> v2 = v1; // Here there is no central element and the two halves // are 1 2 3 4 and 1 2 3 5 which are different vector<int> v3 = { 1, 2, 3, 4, 1, 2, 3, 5 }; // Declaring fourth vector and making it equal to v3 vector<int> v4 = v3; // Performing swap between two halves of vector v1 if (v1.size() % 2 == 0) std::swap_ranges(v1.begin(), v1.begin() + (v1.size() / 2), v1.begin() + v1.size() / 2); else std::swap_ranges(v1.begin(), v1.begin() + v1.size() / 2, v1.begin() + (v1.size() / 2) + 1); if (v1 == v2) { cout << \"Yes\"; } else { cout << \"No\"; } // Now, Performing swap between two halves of vector v3 if (v3.size() % 2 == 0) std::swap_ranges(v3.begin(), v3.begin() + (v3.size() / 2), v3.begin() + v3.size() / 2); else std::swap_ranges(v3.begin(), v3.begin() + v3.size() / 2, v3.begin() + (v3.size() / 2) + 1); cout << \"\\n\"; if (v3 == v4) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}", "e": 28863, "s": 27326, "text": null }, { "code": null, "e": 28871, "s": 28863, "text": "Output:" }, { "code": null, "e": 28879, "s": 28871, "text": "Yes\nNo\n" }, { "code": null, "e": 29279, "s": 28879, "text": "Explanation of code: Here, in this code, we have declared a vector and then assigned it to another vector, and then in the first vector, we are swapping values in the first half with the second half depending upon whether it contains odd no. of elements or not. If after swapping the values, the new first vector is same as second vector (old first vector), this means that both the halves are same." }, { "code": null, "e": 29529, "s": 29279, "text": "So, in the first vector 1 2 3 4 5 1 2 3 4, it contains same element in both the halves, so Yes is printed, whereas in second vector 1 2 3 4 1 2 3 5, second half contains one different element than first half, i.e., 4 in place of 5, so No is printed." }, { "code": null, "e": 29599, "s": 29529, "text": "Time Complexity: It is linear in the distance between first and last." }, { "code": null, "e": 29902, "s": 29599, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30027, "s": 29902, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30049, "s": 30027, "text": "cpp-algorithm-library" }, { "code": null, "e": 30053, "s": 30049, "text": "STL" }, { "code": null, "e": 30057, "s": 30053, "text": "C++" }, { "code": null, "e": 30061, "s": 30057, "text": "STL" }, { "code": null, "e": 30065, "s": 30061, "text": "CPP" }, { "code": null, "e": 30163, "s": 30065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30191, "s": 30163, "text": "Operator Overloading in C++" }, { "code": null, "e": 30211, "s": 30191, "text": "Polymorphism in C++" }, { "code": null, "e": 30235, "s": 30211, "text": "Sorting a vector in C++" }, { "code": null, "e": 30268, "s": 30235, "text": "Friend class and function in C++" }, { "code": null, "e": 30293, "s": 30268, "text": "std::string class in C++" }, { "code": null, "e": 30337, "s": 30293, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 30382, "s": 30337, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 30406, "s": 30382, "text": "Inline Functions in C++" }, { "code": null, "e": 30459, "s": 30406, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Angular10 isPlatformServer() Function - GeeksforGeeks
02 Jun, 2021 In this article, we are going to see what is isPlatformServer in Angular 10 and how to use it. The isPlatformServer is used to get a platform id that represents a server platform Syntax: isPlatformServer(platformId); NgModule: Module used by isPlatformServer is: CommonModule Return Value: returns a Boolean Value stating whether a platform id represents a server platform. Approach: Create the angular app to be used Import isPlatformServer from @angular/core to the project. In app.component.ts define the object which holds the Boolean value. serve the angular app using ng serve to see the output Example 1: app.component.ts import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformServer }from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { isServer: boolean; constructor( @Inject(PLATFORM_ID) platformId: Object) { this.isServer = isPlatformServer(platformId); console.log(this.isServer); } } Output: Example 2: app.component.ts import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformServer } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { isServer: boolean; constructor( @Inject(PLATFORM_ID) platformId: Object) { this.isServer = isPlatformServer(platformId); } } ”>app.component.html” <div *ngIf = 'isServer==false'> platform id does not represents a server platform.</div> Output: Reference: https://angular.io/api/common/isPlatformServer Angular10 AngularJS-Function AngularJS Misc Web Technologies Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Messages Component vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 26354, "s": 26326, "text": "\n02 Jun, 2021" }, { "code": null, "e": 26449, "s": 26354, "text": "In this article, we are going to see what is isPlatformServer in Angular 10 and how to use it." }, { "code": null, "e": 26533, "s": 26449, "text": "The isPlatformServer is used to get a platform id that represents a server platform" }, { "code": null, "e": 26541, "s": 26533, "text": "Syntax:" }, { "code": null, "e": 26571, "s": 26541, "text": "isPlatformServer(platformId);" }, { "code": null, "e": 26617, "s": 26571, "text": "NgModule: Module used by isPlatformServer is:" }, { "code": null, "e": 26630, "s": 26617, "text": "CommonModule" }, { "code": null, "e": 26728, "s": 26630, "text": "Return Value: returns a Boolean Value stating whether a platform id represents a server platform." }, { "code": null, "e": 26739, "s": 26728, "text": "Approach: " }, { "code": null, "e": 26773, "s": 26739, "text": "Create the angular app to be used" }, { "code": null, "e": 26832, "s": 26773, "text": "Import isPlatformServer from @angular/core to the project." }, { "code": null, "e": 26901, "s": 26832, "text": "In app.component.ts define the object which holds the Boolean value." }, { "code": null, "e": 26956, "s": 26901, "text": "serve the angular app using ng serve to see the output" }, { "code": null, "e": 26967, "s": 26956, "text": "Example 1:" }, { "code": null, "e": 26984, "s": 26967, "text": "app.component.ts" }, { "code": "import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformServer }from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { isServer: boolean; constructor( @Inject(PLATFORM_ID) platformId: Object) { this.isServer = isPlatformServer(platformId); console.log(this.isServer); } }", "e": 27451, "s": 26984, "text": null }, { "code": null, "e": 27459, "s": 27451, "text": "Output:" }, { "code": null, "e": 27470, "s": 27459, "text": "Example 2:" }, { "code": null, "e": 27487, "s": 27470, "text": "app.component.ts" }, { "code": "import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformServer } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { isServer: boolean; constructor( @Inject(PLATFORM_ID) platformId: Object) { this.isServer = isPlatformServer(platformId); } }", "e": 27922, "s": 27487, "text": null }, { "code": null, "e": 27944, "s": 27922, "text": "”>app.component.html”" }, { "code": "<div *ngIf = 'isServer==false'> platform id does not represents a server platform.</div>", "e": 28034, "s": 27944, "text": null }, { "code": null, "e": 28042, "s": 28034, "text": "Output:" }, { "code": null, "e": 28100, "s": 28042, "text": "Reference: https://angular.io/api/common/isPlatformServer" }, { "code": null, "e": 28110, "s": 28100, "text": "Angular10" }, { "code": null, "e": 28129, "s": 28110, "text": "AngularJS-Function" }, { "code": null, "e": 28139, "s": 28129, "text": "AngularJS" }, { "code": null, "e": 28144, "s": 28139, "text": "Misc" }, { "code": null, "e": 28161, "s": 28144, "text": "Web Technologies" }, { "code": null, "e": 28166, "s": 28161, "text": "Misc" }, { "code": null, "e": 28171, "s": 28166, "text": "Misc" }, { "code": null, "e": 28269, "s": 28171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28304, "s": 28269, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28339, "s": 28304, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28363, "s": 28339, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28416, "s": 28363, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28451, "s": 28416, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 28505, "s": 28451, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 28546, "s": 28505, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 28607, "s": 28546, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 28641, "s": 28607, "text": "How to write Regular Expressions?" } ]
How to get a list of parameter names inside Python function?
To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo. import inspect def aMethod(arg1, arg2): pass print(inspect.getargspec(aMethod)) def foo(a,b,c=4, *arglist, **keywords): pass print(inspect.getargspec(foo)) ArgSpec(args=['arg1', 'arg2'], varargs=None, keywords=None, defaults=None) ArgSpec(args=['a', 'b', 'c'], varargs='arglist', keywords='keywords', defaults=(4,))
[ { "code": null, "e": 1205, "s": 1062, "text": "To extract the number and names of the arguments from a function or function[something] to return (\"arg1\", \"arg2\"), we use the inspect module." }, { "code": null, "e": 1324, "s": 1205, "text": "The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo." }, { "code": null, "e": 1480, "s": 1324, "text": "import inspect\ndef aMethod(arg1, arg2): pass\nprint(inspect.getargspec(aMethod))\ndef foo(a,b,c=4, *arglist, **keywords): pass\nprint(inspect.getargspec(foo))" }, { "code": null, "e": 1640, "s": 1480, "text": "ArgSpec(args=['arg1', 'arg2'], varargs=None, keywords=None, defaults=None)\nArgSpec(args=['a', 'b', 'c'], varargs='arglist', keywords='keywords', defaults=(4,))" } ]
Finding the End Index of the Specified Range in C# - GeeksforGeeks
28 Jun, 2021 The Range Structure is introduced in C# 8.0. It represents a range that has a start and end indexes. You are allowed to find the end index of the given ranges with the help of End Property provided by the Range struct.Syntax: public property Index End { Index get(); }; Here, Index represents the end index.Example 1: CSharp // C# program to illustrate the use// of End property of Range structusing System; namespace range_example { class Program { static void Main(string[] args) { // Creating range // using Range Constructor var r1 = new Range(0, 5); // Creating range // using range operator Range r2 = 3..7; // Finding the last index // of r1 and r2 ranges // Using End property var res1 = r1.End; Console.WriteLine("End index of r1 range: " + res1); var res2 = r2.End; Console.WriteLine("End index of r2 range: " + res2); }}} Output: End index of r1 range: 5 End index of r2 range: 7 Example 2: CSharp // C# program to illustrate how to use// End property of Range structureusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] arr = new string[8] {"Archery", "Badminton", "Cricket", "Bowling", "Boxing", "Curling", "Tennis", "Skateboarding"}; // Creating ranges // Using Range(Index, Index) // Constructor var r1 = new Range(0, 3); var r2 = new Range(4, 7); // Finding the last index // of the specified range // Using End property var res1 = r1.End; var res2 = r2.End; Console.WriteLine("End Index of Range {0} is {1}"+ " and the item is {2}", r1, res1, arr[res1]); Console.WriteLine("End Index of Range {0} is {1} and"+ " the item is {2}", r2, res2, arr[res2]); }}} Output: End Index of Range 0..3 is 3 and the item is Bowling End Index of Range 4..7 is 7 and the item is Skateboarding saurabh1990aror CSharp-8.0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Delegates Introduction to .NET Framework C# | Data Types Difference between Ref and Out keywords in C#
[ { "code": null, "e": 24742, "s": 24714, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24970, "s": 24742, "text": "The Range Structure is introduced in C# 8.0. It represents a range that has a start and end indexes. You are allowed to find the end index of the given ranges with the help of End Property provided by the Range struct.Syntax: " }, { "code": null, "e": 25014, "s": 24970, "text": "public property Index End { Index get(); };" }, { "code": null, "e": 25063, "s": 25014, "text": "Here, Index represents the end index.Example 1: " }, { "code": null, "e": 25070, "s": 25063, "text": "CSharp" }, { "code": "// C# program to illustrate the use// of End property of Range structusing System; namespace range_example { class Program { static void Main(string[] args) { // Creating range // using Range Constructor var r1 = new Range(0, 5); // Creating range // using range operator Range r2 = 3..7; // Finding the last index // of r1 and r2 ranges // Using End property var res1 = r1.End; Console.WriteLine(\"End index of r1 range: \" + res1); var res2 = r2.End; Console.WriteLine(\"End index of r2 range: \" + res2); }}}", "e": 25683, "s": 25070, "text": null }, { "code": null, "e": 25692, "s": 25683, "text": "Output: " }, { "code": null, "e": 25742, "s": 25692, "text": "End index of r1 range: 5\nEnd index of r2 range: 7" }, { "code": null, "e": 25754, "s": 25742, "text": "Example 2: " }, { "code": null, "e": 25761, "s": 25754, "text": "CSharp" }, { "code": "// C# program to illustrate how to use// End property of Range structureusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] arr = new string[8] {\"Archery\", \"Badminton\", \"Cricket\", \"Bowling\", \"Boxing\", \"Curling\", \"Tennis\", \"Skateboarding\"}; // Creating ranges // Using Range(Index, Index) // Constructor var r1 = new Range(0, 3); var r2 = new Range(4, 7); // Finding the last index // of the specified range // Using End property var res1 = r1.End; var res2 = r2.End; Console.WriteLine(\"End Index of Range {0} is {1}\"+ \" and the item is {2}\", r1, res1, arr[res1]); Console.WriteLine(\"End Index of Range {0} is {1} and\"+ \" the item is {2}\", r2, res2, arr[res2]); }}}", "e": 26680, "s": 25761, "text": null }, { "code": null, "e": 26689, "s": 26680, "text": "Output: " }, { "code": null, "e": 26801, "s": 26689, "text": "End Index of Range 0..3 is 3 and the item is Bowling\nEnd Index of Range 4..7 is 7 and the item is Skateboarding" }, { "code": null, "e": 26819, "s": 26803, "text": "saurabh1990aror" }, { "code": null, "e": 26830, "s": 26819, "text": "CSharp-8.0" }, { "code": null, "e": 26833, "s": 26830, "text": "C#" }, { "code": null, "e": 26931, "s": 26833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26940, "s": 26931, "text": "Comments" }, { "code": null, "e": 26953, "s": 26940, "text": "Old Comments" }, { "code": null, "e": 26981, "s": 26953, "text": "C# Dictionary with examples" }, { "code": null, "e": 27004, "s": 26981, "text": "C# | Method Overriding" }, { "code": null, "e": 27026, "s": 27004, "text": "C# | Class and Object" }, { "code": null, "e": 27044, "s": 27026, "text": "C# | Constructors" }, { "code": null, "e": 27084, "s": 27044, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27107, "s": 27084, "text": "Extension Method in C#" }, { "code": null, "e": 27122, "s": 27107, "text": "C# | Delegates" }, { "code": null, "e": 27153, "s": 27122, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27169, "s": 27153, "text": "C# | Data Types" } ]
Time Series Analysis with Facebook Prophet: How it works and How to use it | by Mitchell Krieger | Towards Data Science
Time series data can be difficult and frustrating to work with, and the various algorithms that generate models can be quite finicky and hard to tune. This is particularly true if you are working with data that has multiple seasonalities. In addition, traditional time series models like SARIMAX have many stringent data requirements like stationarity and equally spaced values. Other time series models like Recurring Neural Networks with Long-Short Term Memory (RNN-LSTM) can be highly complex and difficult to work with if you don’t have a significant level of understanding about neural network architecture. So for the average data analyst, there is a high barrier of entry to time series analysis. So in 2017, a few researchers at Facebook published a paper called, “Forecasting at Scale” which introduced the open-source project Facebook Prophet, giving quick, powerful, and accessible time-series modeling to data analysts and data scientists everywhere. To further explore Facebook Prophet, I’m going to first summarize the math behind it and then go over how to use it in Python (although it can also be implemented in R). Facebook Prophet is an open-source algorithm for generating time-series models that uses a few old ideas with some new twists. It is particularly good at modeling time series that have multiple seasonalities and doesn’t face some of the above drawbacks of other algorithms. At its core is the sum of three functions of time plus an error term: growthg(t), seasonality s(t), holidays h(t) , and error e_t : The growth function models the overall trend of the data. The old idea should be familiar to anyone with a basic knowledge of linear and logistic functions. The new idea incorporated into Facebook prophet is that the growth trend can be present at all points in the data or can be altered at what Prophet calls “changepoints”. Changepoints are moments in the data where the data shifts direction. Using new COVID-19 cases as an example, it could be due to new cases beginning to fall after hitting a peak once a vaccine is introduced. Or it could be a sudden pick up of cases when a new strain is introduced into the population and so on. Prophet can automatically detect change points or you can set them yourself. You can also adjust the power the change points have in altering the growth function and the amount of data taken into account in automatic changepoint detection. The growth function has three main options: Linear Growth: This is the default setting for Prophet. It uses a set of piecewise linear equations with differing slopes between change points. When linear growth is used, the growth term will look similar to the classic y = mx + b from middle school, except the slope(m) and offset(b) are variable and will change value at each changepoint. Logistic Growth: This setting is useful when your time series has a cap or a floor in which the values you are modeling becomes saturated and can’t surpass a maximum or minimum value (think carrying capacity). When logistic growth is used, the growth term will look similar to a typical equation for a logistic curve (see below), except it the carrying capacity (C) will vary as a function of time and the growth rate (k) and the offset(m) are variable and will change value at each change point. Flat: Lastly, you can choose a flat trend when there is no growth over time (but there still may be seasonality). If set to flat the growth function will be a constant value. The seasonality function is simply a Fourier Series as a function of time. If you are unfamiliar with Fourier Series, an easy way to think about it is the sum of many successive sines and cosines. Each sine and cosine term is multiplied by some coefficient. This sum can approximate nearly any curve or in the case of Facebook Prophet, the seasonality (cyclical pattern) in our data. All together it looks like this: If the above is difficult to decipher, I recommend this simple breakdown of the Fourier Series or this video on the intuition behind the Fourier series. If you are still struggling to understand the Fourier series, do not worry. You can still use Facebook Prophet because Prophet will automatically detect an optimal number of terms in the series, also known as the Fourier order. Or if you are confident in your understanding and want more nuance, you can also choose the Fourier order based on the needs of your particular data set. The higher the order the more terms in the series. You can also choose between additive and multiplicative seasonality. The holiday function allows Facebook Prophet to adjust forecasting when a holiday or major event may change the forecast. It takes a list of dates (there are built-in dates of US holidays or you can define your own dates) and when each date is present in the forecast adds or subtracts value from the forecast from the growth and seasonality terms based on historical data on the identified holiday dates. You can also identify a range of days around dates (think the time between Christmas/New Years, holiday weekends, thanksgiving’s association with Black Friday/Cyber Monday, etc). It can be implemented in R or Python, but we’ll focus on use in Python in this blog. You’ll need at least Python 3.7. To install: $pip install pystan$pip install fbprophet After reading in data and cleaning using pandas, you are almost ready to use Facebook Prophet. However, Facebook Prophet requires that the dates of your time series are located in a column titled ds and the values of the series in a column titled y. Note that if you are using logistic growth you’ll also need to add additional cap and floor columns with the maximum and minimum values of the possible growth at each specific time entry in the time series. For demonstration, we’ll use new COVID-19 cases tracked by the New York Times on Github. First, we read and prepare the data in the form above. It doesn’t seem like there is logistic growth here so we’ll just focus on creating the ds and y columns: Facebook Prophet operates similarly to scikit-learn, so first we instantiate the model, then call .fit(ts) passing the time series through it. When calling .predict(ts), Prophet outputs a lot of information. Luckily, the developers added a method called .make_future_dataframe(periods = 10) that will easily collect all of the output in an organized way. This method outputs an empty pandas dataframe that we will fill with the forecast using the .predict(ts)method. The forecast will contain a prediction for every historical value present in the dataset plus additional forecasts for the number of periods passed through the method (in the case above 10). There are many columns of useful information in this future dataframe but the most important ones are: ds contains the timestamp entry of the forecast yhat contains the forecasted value of the time series yhat_lower contains the bottom of the confidence interval for the forecast yhat_upper contains the bottom of the confidence interval for the forecast A .plot() function is also provided for easy plotting of the original data, the forecast and the confidence interval of the model. In this first iteration of the model we will allow Prophet to automatically choose the hyperparameters: This outputs the following plotted forecast: You can also add lines to reveal detected changepoints to the above plot by adding the following code: Seems pretty decent, considering we didn’t tune any hyperparameters! Prophet picked up on a weekly seasonality of newly reported cases (probably due to differing weekend hours of testing sites) and an overall upward trend. It also added change points when during the summer and fall to better model the large increase in the rate of new cases. However, it doesn’t visually seem like a great model overall and misses many key trends in the original data. So we’ll need to tune it to get a better assessment of what is going on. Let’s fix some of the key problems our above model has: Misses the downturn: Prophet was unable to incorporate the downturn in new COVID cases after the new year. This is because the default setting for the range of data points considered when identifying changepoints is the first 80% of data in the time series. We can fix this by setting changepoint_range = 1 when instantiating the model which will incorporate 100% of the data. In other situations, it may be good to keep the changepoint range at 80% or lower to ensure that the model doesn’t overfit your data and can understand the last 20% on its own. But, in this case, because we are just trying to accurately model what has happened so far, we’ll allow the adjustment to 100%. Strength of changepoints: While its great prophet was able to create change points, it visually seems like some of the changepoints are quite weak in impact on the model, or possibly there aren’t enough changepoints. The changepoint_prior_scale and the n_changepoints hyperparameters allow us to adjust this. By default, changepoint_prior_scale it is set to 0.05, increasing this value allows the automatic detection of more change points and decreases it allows for less. Alternatively, we can specify a number of changepoints to detect using n_changepoints or list the changepoints ourselves using changepoints. Be careful with this, as too many changepoints may cause overfitting. Possible overfitting due to seasonality: While it's cool that it picked up on the weekly seasonality of new cases, in this particular context it's more important to understand the overall trend of cases to possibly predict when the pandemic will end. Prophet has built-in hyperparameters to allow you to adjust daily, weekly and yearly seasonality. So we can fix this by setting weekly_seasonality = False. Alternatively, we could try to create our own custom seasonality and adjust the Fourier order using the.add_seasonality()method or we could dampen the automatic seasonality using the seasonality_prior_scale hyperparameter. However, in this case, it might be a little overkill to use either of those options Running the model again with these changes yields: Wow! With three small changes to the hyperparameters, we have a pretty accurate model of the behavior of new COVID cases over the past year. In this model, it predicts that cases will be near zero in early March. This is probably unlikely, as cases will probably decrease asymptotically. Facebook Prophet is easy to use, fast, and doesn’t face many of the challenges that some other kinds of time-series modeling algorithms face (my favorite is that you can have missing values!). The API also includes documentation on how to use walk forward and cross validation, incorporate exogenous variables, and more. You can also check out this GitHub repository for the Jupyter Notebooks containing the code used in this blog.
[ { "code": null, "e": 1010, "s": 47, "text": "Time series data can be difficult and frustrating to work with, and the various algorithms that generate models can be quite finicky and hard to tune. This is particularly true if you are working with data that has multiple seasonalities. In addition, traditional time series models like SARIMAX have many stringent data requirements like stationarity and equally spaced values. Other time series models like Recurring Neural Networks with Long-Short Term Memory (RNN-LSTM) can be highly complex and difficult to work with if you don’t have a significant level of understanding about neural network architecture. So for the average data analyst, there is a high barrier of entry to time series analysis. So in 2017, a few researchers at Facebook published a paper called, “Forecasting at Scale” which introduced the open-source project Facebook Prophet, giving quick, powerful, and accessible time-series modeling to data analysts and data scientists everywhere." }, { "code": null, "e": 1180, "s": 1010, "text": "To further explore Facebook Prophet, I’m going to first summarize the math behind it and then go over how to use it in Python (although it can also be implemented in R)." }, { "code": null, "e": 1586, "s": 1180, "text": "Facebook Prophet is an open-source algorithm for generating time-series models that uses a few old ideas with some new twists. It is particularly good at modeling time series that have multiple seasonalities and doesn’t face some of the above drawbacks of other algorithms. At its core is the sum of three functions of time plus an error term: growthg(t), seasonality s(t), holidays h(t) , and error e_t :" }, { "code": null, "e": 1913, "s": 1586, "text": "The growth function models the overall trend of the data. The old idea should be familiar to anyone with a basic knowledge of linear and logistic functions. The new idea incorporated into Facebook prophet is that the growth trend can be present at all points in the data or can be altered at what Prophet calls “changepoints”." }, { "code": null, "e": 2465, "s": 1913, "text": "Changepoints are moments in the data where the data shifts direction. Using new COVID-19 cases as an example, it could be due to new cases beginning to fall after hitting a peak once a vaccine is introduced. Or it could be a sudden pick up of cases when a new strain is introduced into the population and so on. Prophet can automatically detect change points or you can set them yourself. You can also adjust the power the change points have in altering the growth function and the amount of data taken into account in automatic changepoint detection." }, { "code": null, "e": 2509, "s": 2465, "text": "The growth function has three main options:" }, { "code": null, "e": 2852, "s": 2509, "text": "Linear Growth: This is the default setting for Prophet. It uses a set of piecewise linear equations with differing slopes between change points. When linear growth is used, the growth term will look similar to the classic y = mx + b from middle school, except the slope(m) and offset(b) are variable and will change value at each changepoint." }, { "code": null, "e": 3349, "s": 2852, "text": "Logistic Growth: This setting is useful when your time series has a cap or a floor in which the values you are modeling becomes saturated and can’t surpass a maximum or minimum value (think carrying capacity). When logistic growth is used, the growth term will look similar to a typical equation for a logistic curve (see below), except it the carrying capacity (C) will vary as a function of time and the growth rate (k) and the offset(m) are variable and will change value at each change point." }, { "code": null, "e": 3524, "s": 3349, "text": "Flat: Lastly, you can choose a flat trend when there is no growth over time (but there still may be seasonality). If set to flat the growth function will be a constant value." }, { "code": null, "e": 3941, "s": 3524, "text": "The seasonality function is simply a Fourier Series as a function of time. If you are unfamiliar with Fourier Series, an easy way to think about it is the sum of many successive sines and cosines. Each sine and cosine term is multiplied by some coefficient. This sum can approximate nearly any curve or in the case of Facebook Prophet, the seasonality (cyclical pattern) in our data. All together it looks like this:" }, { "code": null, "e": 4094, "s": 3941, "text": "If the above is difficult to decipher, I recommend this simple breakdown of the Fourier Series or this video on the intuition behind the Fourier series." }, { "code": null, "e": 4596, "s": 4094, "text": "If you are still struggling to understand the Fourier series, do not worry. You can still use Facebook Prophet because Prophet will automatically detect an optimal number of terms in the series, also known as the Fourier order. Or if you are confident in your understanding and want more nuance, you can also choose the Fourier order based on the needs of your particular data set. The higher the order the more terms in the series. You can also choose between additive and multiplicative seasonality." }, { "code": null, "e": 5181, "s": 4596, "text": "The holiday function allows Facebook Prophet to adjust forecasting when a holiday or major event may change the forecast. It takes a list of dates (there are built-in dates of US holidays or you can define your own dates) and when each date is present in the forecast adds or subtracts value from the forecast from the growth and seasonality terms based on historical data on the identified holiday dates. You can also identify a range of days around dates (think the time between Christmas/New Years, holiday weekends, thanksgiving’s association with Black Friday/Cyber Monday, etc)." }, { "code": null, "e": 5311, "s": 5181, "text": "It can be implemented in R or Python, but we’ll focus on use in Python in this blog. You’ll need at least Python 3.7. To install:" }, { "code": null, "e": 5353, "s": 5311, "text": "$pip install pystan$pip install fbprophet" }, { "code": null, "e": 5810, "s": 5353, "text": "After reading in data and cleaning using pandas, you are almost ready to use Facebook Prophet. However, Facebook Prophet requires that the dates of your time series are located in a column titled ds and the values of the series in a column titled y. Note that if you are using logistic growth you’ll also need to add additional cap and floor columns with the maximum and minimum values of the possible growth at each specific time entry in the time series." }, { "code": null, "e": 6059, "s": 5810, "text": "For demonstration, we’ll use new COVID-19 cases tracked by the New York Times on Github. First, we read and prepare the data in the form above. It doesn’t seem like there is logistic growth here so we’ll just focus on creating the ds and y columns:" }, { "code": null, "e": 6820, "s": 6059, "text": "Facebook Prophet operates similarly to scikit-learn, so first we instantiate the model, then call .fit(ts) passing the time series through it. When calling .predict(ts), Prophet outputs a lot of information. Luckily, the developers added a method called .make_future_dataframe(periods = 10) that will easily collect all of the output in an organized way. This method outputs an empty pandas dataframe that we will fill with the forecast using the .predict(ts)method. The forecast will contain a prediction for every historical value present in the dataset plus additional forecasts for the number of periods passed through the method (in the case above 10). There are many columns of useful information in this future dataframe but the most important ones are:" }, { "code": null, "e": 6868, "s": 6820, "text": "ds contains the timestamp entry of the forecast" }, { "code": null, "e": 6922, "s": 6868, "text": "yhat contains the forecasted value of the time series" }, { "code": null, "e": 6997, "s": 6922, "text": "yhat_lower contains the bottom of the confidence interval for the forecast" }, { "code": null, "e": 7072, "s": 6997, "text": "yhat_upper contains the bottom of the confidence interval for the forecast" }, { "code": null, "e": 7307, "s": 7072, "text": "A .plot() function is also provided for easy plotting of the original data, the forecast and the confidence interval of the model. In this first iteration of the model we will allow Prophet to automatically choose the hyperparameters:" }, { "code": null, "e": 7352, "s": 7307, "text": "This outputs the following plotted forecast:" }, { "code": null, "e": 7455, "s": 7352, "text": "You can also add lines to reveal detected changepoints to the above plot by adding the following code:" }, { "code": null, "e": 7982, "s": 7455, "text": "Seems pretty decent, considering we didn’t tune any hyperparameters! Prophet picked up on a weekly seasonality of newly reported cases (probably due to differing weekend hours of testing sites) and an overall upward trend. It also added change points when during the summer and fall to better model the large increase in the rate of new cases. However, it doesn’t visually seem like a great model overall and misses many key trends in the original data. So we’ll need to tune it to get a better assessment of what is going on." }, { "code": null, "e": 8038, "s": 7982, "text": "Let’s fix some of the key problems our above model has:" }, { "code": null, "e": 8720, "s": 8038, "text": "Misses the downturn: Prophet was unable to incorporate the downturn in new COVID cases after the new year. This is because the default setting for the range of data points considered when identifying changepoints is the first 80% of data in the time series. We can fix this by setting changepoint_range = 1 when instantiating the model which will incorporate 100% of the data. In other situations, it may be good to keep the changepoint range at 80% or lower to ensure that the model doesn’t overfit your data and can understand the last 20% on its own. But, in this case, because we are just trying to accurately model what has happened so far, we’ll allow the adjustment to 100%." }, { "code": null, "e": 9404, "s": 8720, "text": "Strength of changepoints: While its great prophet was able to create change points, it visually seems like some of the changepoints are quite weak in impact on the model, or possibly there aren’t enough changepoints. The changepoint_prior_scale and the n_changepoints hyperparameters allow us to adjust this. By default, changepoint_prior_scale it is set to 0.05, increasing this value allows the automatic detection of more change points and decreases it allows for less. Alternatively, we can specify a number of changepoints to detect using n_changepoints or list the changepoints ourselves using changepoints. Be careful with this, as too many changepoints may cause overfitting." }, { "code": null, "e": 10118, "s": 9404, "text": "Possible overfitting due to seasonality: While it's cool that it picked up on the weekly seasonality of new cases, in this particular context it's more important to understand the overall trend of cases to possibly predict when the pandemic will end. Prophet has built-in hyperparameters to allow you to adjust daily, weekly and yearly seasonality. So we can fix this by setting weekly_seasonality = False. Alternatively, we could try to create our own custom seasonality and adjust the Fourier order using the.add_seasonality()method or we could dampen the automatic seasonality using the seasonality_prior_scale hyperparameter. However, in this case, it might be a little overkill to use either of those options" }, { "code": null, "e": 10169, "s": 10118, "text": "Running the model again with these changes yields:" }, { "code": null, "e": 10457, "s": 10169, "text": "Wow! With three small changes to the hyperparameters, we have a pretty accurate model of the behavior of new COVID cases over the past year. In this model, it predicts that cases will be near zero in early March. This is probably unlikely, as cases will probably decrease asymptotically." } ]
open() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); The new file descriptor is set to remain open across an execve(2) (i.e., the FD_CLOEXEC file descriptor flag described in fcntl(2) is initially disabled). The file offset is set to the beginning of the file (see lseek(2)). A call to open() creates a new open file description, an entry in the system-wide table of open files. This entry records the file offset and the file status flags (modifiable via the fcntl() F_SETFL operation). A file descriptor is a reference to one of these entries; this reference is unaffected if pathname is subsequently removed or modified to refer to a different file. The new open file description is initially not shared with any other process, but sharing may arise via fork(2). The parameter flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively. In addition, zero or more file creation flags and file status flags can be bitwise-or’d in flags. The file creation flags are O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC. The file status flags are all of the remaining flags listed below. The distinction between these two groups of flags is that the file status flags can be retrieved and (in some cases) modified using fcntl(2). The full list of file creation flags and file status flags is as follows: A semantically similar (but deprecated) interface for block devices is described in raw(8). The argument mode specifies the permissions to use in case a new file is created. It is modified by the process’s umask in the usual way: the permissions of the created file are (mode & ~umask). Note that this mode only applies to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor. creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC. On NFS file systems with UID mapping enabled, open() may return a file descriptor but e.g. read(2) requests are denied with EACCES. This is because the client performs open() by checking the permissions, but UID mapping is performed by the server upon read and write requests. If the file is newly created, its st_atime, st_ctime, st_mtime fields (respectively, time of last access, time of last status change, and time of last modification; see stat(2)) are set to the current time, and so are the st_ctime and st_mtime fields of the parent directory. Otherwise, if the file is modified because of the O_TRUNC flag, its st_ctime and st_mtime fields are set to the current time. The (undefined) effect of O_RDONLY | O_TRUNC varies among implementations. On many systems the file is actually truncated. The O_DIRECT flag was introduced in SGI IRIX, where it has alignment restrictions similar to those of Linux 2.4. IRIX has also a fcntl(2) call to query appropriate alignments, and sizes. FreeBSD 4.x introduced a flag of same name, but without alignment restrictions. Support was added under Linux in kernel version 2.4.10. Older Linux kernels simply ignore this flag. One may have to define the _GNU_SOURCE macro to get its definition. Currently, it is not possible to enable signal-driven I/O by specifying O_ASYNC when calling open(); use fcntl(2) to enable this flag. POSIX provides for three different variants of synchronised I/O, corresponding to the flags O_SYNC, O_DSYNC and O_RSYNC. Currently (2.1.130) these are all synonymous under Linux. close (2) close (2) dup (2) dup (2) fcntl (2) fcntl (2) link (2) link (2) lseek (2) lseek (2) mknod (2) mknod (2) mount (2) mount (2) mmap (2) mmap (2) openat (2) openat (2) path_resolution (2) path_resolution (2) read (2) read (2) socket (2) socket (2) stat (2) stat (2) umask (2) umask (2) unlink (2) unlink (2) write (2) write (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2536, "s": 2319, "text": "#include <sys/types.h> \n#include <sys/stat.h> \n#include <fcntl.h> \n\nint open(const char *pathname, int flags); \nint open(const char *pathname, int flags, mode_t mode); \nint creat(const char *pathname, mode_t mode); \n" }, { "code": null, "e": 2686, "s": 2536, "text": "\nint open(const char *pathname, int flags); \nint open(const char *pathname, int flags, mode_t mode); \nint creat(const char *pathname, mode_t mode); \n" }, { "code": null, "e": 2911, "s": 2686, "text": "\nThe new file descriptor is set to remain open across an\nexecve(2)\n(i.e., the\nFD_CLOEXEC file descriptor flag described in\nfcntl(2)\nis initially disabled).\nThe file offset is set to the beginning of the file (see\nlseek(2)).\n" }, { "code": null, "e": 3403, "s": 2911, "text": "\nA call to\nopen() creates a new\nopen file description, an entry in the system-wide table of open files.\nThis entry records the file offset and the file status flags\n(modifiable via the\nfcntl() F_SETFL operation).\nA file descriptor is a reference to one of these entries;\nthis reference is unaffected if\npathname is subsequently removed or modified to refer to a different file.\nThe new open file description is initially not shared\nwith any other process,\nbut sharing may arise via\nfork(2).\n" }, { "code": null, "e": 3587, "s": 3403, "text": "\nThe parameter\nflags must include one of the following\naccess modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write,\nrespectively.\n" }, { "code": null, "e": 4038, "s": 3587, "text": "\nIn addition, zero or more file creation flags and file status flags\ncan be\nbitwise-or’d in\nflags. The\nfile creation flags are\nO_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC. The\nfile status flags are all of the remaining flags listed below.\nThe distinction between these two groups of flags is that\nthe file status flags can be retrieved and (in some cases)\nmodified using\nfcntl(2).\nThe full list of file creation flags and file status flags is as follows:\n" }, { "code": null, "e": 4132, "s": 4038, "text": "\nA semantically similar (but deprecated) interface for block devices\nis described in\nraw(8).\n" }, { "code": null, "e": 4502, "s": 4134, "text": "\nThe argument\nmode specifies the permissions to use in case a new file is created. It is\nmodified by the process’s\numask in the usual way: the permissions of the created file are\n(mode & ~umask). Note that this mode only applies to future accesses of the\nnewly created file; the\nopen() call that creates a read-only file may well return a read/write\nfile descriptor.\n" }, { "code": null, "e": 4582, "s": 4502, "text": "\ncreat() is equivalent to\nopen() with\nflags equal to\nO_CREAT|O_WRONLY|O_TRUNC. " }, { "code": null, "e": 4861, "s": 4582, "text": "\nOn NFS file systems with UID mapping enabled, open() may\nreturn a file descriptor but e.g. read(2) requests are denied\nwith EACCES.\nThis is because the client performs open() by checking the\npermissions, but UID mapping is performed by the server upon\nread and write requests.\n" }, { "code": null, "e": 5265, "s": 4861, "text": "\nIf the file is newly created, its st_atime, st_ctime, st_mtime fields\n(respectively, time of last access, time of last status change, and\ntime of last modification; see\nstat(2))\nare set\nto the current time, and so are the st_ctime and st_mtime fields of the\nparent directory.\nOtherwise, if the file is modified because of the O_TRUNC flag,\nits st_ctime and st_mtime fields are set to the current time.\n" }, { "code": null, "e": 5390, "s": 5265, "text": "\nThe (undefined) effect of\nO_RDONLY | O_TRUNC varies among implementations. On many systems the file is actually\ntruncated.\n" }, { "code": null, "e": 5831, "s": 5390, "text": "\nThe\nO_DIRECT flag was introduced in SGI IRIX, where it has alignment restrictions\nsimilar to those of Linux 2.4. IRIX has also a fcntl(2) call to\nquery appropriate alignments, and sizes. FreeBSD 4.x introduced\na flag of same name, but without alignment restrictions.\nSupport was added under Linux in kernel version 2.4.10.\nOlder Linux kernels simply ignore this flag.\nOne may have to define the\n_GNU_SOURCE macro to get its definition.\n" }, { "code": null, "e": 5968, "s": 5831, "text": "\nCurrently, it is not possible to enable signal-driven\nI/O by specifying\nO_ASYNC when calling\nopen(); use\nfcntl(2)\nto enable this flag.\n" }, { "code": null, "e": 6150, "s": 5968, "text": "\nPOSIX provides for three different variants of synchronised I/O,\ncorresponding to the flags O_SYNC, O_DSYNC and\nO_RSYNC. Currently (2.1.130) these are all synonymous under Linux.\n" }, { "code": null, "e": 6160, "s": 6150, "text": "close (2)" }, { "code": null, "e": 6170, "s": 6160, "text": "close (2)" }, { "code": null, "e": 6178, "s": 6170, "text": "dup (2)" }, { "code": null, "e": 6186, "s": 6178, "text": "dup (2)" }, { "code": null, "e": 6196, "s": 6186, "text": "fcntl (2)" }, { "code": null, "e": 6206, "s": 6196, "text": "fcntl (2)" }, { "code": null, "e": 6215, "s": 6206, "text": "link (2)" }, { "code": null, "e": 6224, "s": 6215, "text": "link (2)" }, { "code": null, "e": 6234, "s": 6224, "text": "lseek (2)" }, { "code": null, "e": 6244, "s": 6234, "text": "lseek (2)" }, { "code": null, "e": 6254, "s": 6244, "text": "mknod (2)" }, { "code": null, "e": 6264, "s": 6254, "text": "mknod (2)" }, { "code": null, "e": 6274, "s": 6264, "text": "mount (2)" }, { "code": null, "e": 6284, "s": 6274, "text": "mount (2)" }, { "code": null, "e": 6293, "s": 6284, "text": "mmap (2)" }, { "code": null, "e": 6302, "s": 6293, "text": "mmap (2)" }, { "code": null, "e": 6313, "s": 6302, "text": "openat (2)" }, { "code": null, "e": 6324, "s": 6313, "text": "openat (2)" }, { "code": null, "e": 6344, "s": 6324, "text": "path_resolution (2)" }, { "code": null, "e": 6364, "s": 6344, "text": "path_resolution (2)" }, { "code": null, "e": 6373, "s": 6364, "text": "read (2)" }, { "code": null, "e": 6382, "s": 6373, "text": "read (2)" }, { "code": null, "e": 6393, "s": 6382, "text": "socket (2)" }, { "code": null, "e": 6404, "s": 6393, "text": "socket (2)" }, { "code": null, "e": 6413, "s": 6404, "text": "stat (2)" }, { "code": null, "e": 6422, "s": 6413, "text": "stat (2)" }, { "code": null, "e": 6432, "s": 6422, "text": "umask (2)" }, { "code": null, "e": 6442, "s": 6432, "text": "umask (2)" }, { "code": null, "e": 6453, "s": 6442, "text": "unlink (2)" }, { "code": null, "e": 6464, "s": 6453, "text": "unlink (2)" }, { "code": null, "e": 6474, "s": 6464, "text": "write (2)" }, { "code": null, "e": 6484, "s": 6474, "text": "write (2)" }, { "code": null, "e": 6501, "s": 6484, "text": "\nAdvertisements\n" }, { "code": null, "e": 6536, "s": 6501, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 6564, "s": 6536, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6598, "s": 6564, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6615, "s": 6598, "text": " Frahaan Hussain" }, { "code": null, "e": 6648, "s": 6615, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 6659, "s": 6648, "text": " Pradeep D" }, { "code": null, "e": 6694, "s": 6659, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6710, "s": 6694, "text": " Musab Zayadneh" }, { "code": null, "e": 6743, "s": 6710, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 6755, "s": 6743, "text": " GUHARAJANM" }, { "code": null, "e": 6787, "s": 6755, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 6795, "s": 6787, "text": " Uplatz" }, { "code": null, "e": 6802, "s": 6795, "text": " Print" }, { "code": null, "e": 6813, "s": 6802, "text": " Add Notes" } ]
C Program to read contents of Whole File - GeeksforGeeks
03 Dec, 2021 C programming language supports four pre-defined functions to read contents from a file, defined in stdio.h header file: fgetc()– This function is used to read a single character from the file.fgets()– This function is used to read strings from files.fscanf()– This function is used to read the block of raw bytes from files. This is used to read binary files.fread()– This function is used to read formatted input from a file. fgetc()– This function is used to read a single character from the file. fgets()– This function is used to read strings from files. fscanf()– This function is used to read the block of raw bytes from files. This is used to read binary files. fread()– This function is used to read formatted input from a file. Steps To Read A File: Open a file using the function fopen() and store the reference of the file in a FILE pointer. Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread(). File close the file using the function fclose(). Let’s begin discussing each of these functions in detail. fgetc() fgetc() reads characters pointed by the function pointer at that time. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the next character. This function returns a constant EOF (-1) when there is no content to read or an unsuccessful read. Syntax: int fgetc(FILE *ptr); Approach: This program reads the whole content of the file, using this function by reading characters one by one. Do-While loop will be used which will read character until it reaches and of file. When it reaches end it returns EOF character (-1). Using EOF:Below is the C program to implement the above approach- C // C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver codeint main(){ FILE* ptr; char ch; // Opening file in reading mode ptr = fopen("test.txt", "r"); if (NULL == ptr) { printf("file can't be opened \n"); } printf("content of this file are \n"); // Printing what is written in file // character by character using loop. do { ch = fgetc(ptr); printf("%c", ch); // Checking if character is not EOF. // If it is EOF stop eading. } while (ch != EOF); // Closing the file fclose(ptr); return 0;} Input File: GeeksforGeeks | A computer science portal for geeks Output: In the above code, the approach is to read one character from the file and check if it is not EOF, if it is not then print it and if it is then stop reading. Using feof():feof() function takes file pointer as argument and returns true if pointer reaches the end of the file. Syntax: int feof(FILE *ptr); Approach: In this approach, a character is read using fgetc(). Using feof() function check for end of file. since feof() returns true after it reaches the end. Use logical NOT operator(!) so that when it reaches end condition become false and loop stop. Below is the C program to implement the above approach: C // C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver codeint main(){ FILE* ptr; char ch; ptr = fopen("test.txt", "r"); if (NULL == ptr) { printf("file can't be opened \n"); } printf("content of this file are \n"); while (!feof(ptr)) { ch = fgetc(ptr); printf("%c", ch); } fclose(ptr); return 0;} Input File: GeeksforGeeks | A computer science portal for geeks Output: fgets() fgets() reads one string at a time from the file. fgets() returns a string if it is successfully read by function or returns NULL if can not read. Syntax: char * fgets(char *str, int size, FILE * ptr); Here, str: It is string in which fgets() store string after reading it from file.size: It is maximum characters to read from stream.ptr: It is file pointer. Approach: In this approach, the contents of the file are read one character at a time until we reach the end of the file. When we reach the end of the file fgets() can’t read and returns NULL and the program will stop reading. Below is the C program to implement the above approach: C // C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver codeint main(){ FILE* ptr; char str[50]; ptr = fopen("test.txt", "a+"); if (NULL == ptr) { printf("file can't be opened \n"); } printf("content of this file are \n"); while (fgets(str, 50, ptr) != NULL) { printf("%s", str); } fclose(ptr); return 0;} Input File: GeeksforGeeks | A computer science portal for geeks Output: fscanf() fscanf() reads formatted input from a stream. Syntax: int fscanf(FILE *ptr, const char *format, ...) Approach: fscanf reads formatted data from the files and stores it in variables. The data in the buffer is printed on the console till the end of the file is reached. C++ // C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ FILE* ptr = fopen("abc.txt", "r"); if (ptr == NULL) { printf("no such file."); return 0; } /* Assuming that test.txt has content in below format NAME AGE CITY abc 12 hyderbad bef 25 delhi cce 65 bangalore */ char buf[100]; while (fscanf(ptr, "%*s %*s %s ", buf) == 1) printf("%s\n", buf); return 0;} Output: fread() fread() makes it easier to read blocks of data from a file. For instance, in the case of reading a structure from the file, it becomes an easy job to read using fread. Syntax: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) ptr: This is the pointer to a block of memory with a minimum size of size*nmemb bytes.size: This is the size in bytes of each element to be read.nmemb: This is the number of elements, each one with a size of size bytes.stream: This is the pointer to a FILE object that specifies an input stream. Approach: It first, reads the count number of objects, each one with a size of size bytes from the given input stream. The total amount of bytes reads if successful is (size*count). According to the no. of characters read, the indicator file position is incremented. If the objects read are not trivially copy-able, then the behavior is undefined and if the value of size or count is equal to zero, then this program will simply return 0. C++ // C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure to store// course detailsstruct Course { char cname[30]; char sdate[30];}; // Driver codeint main(){ FILE* of; of = fopen("test.txt", "w"); if (of == NULL) { fprintf(stderr, "\nError to open the file\n"); exit(1); } struct Course inp1 = { "Algorithms", "30OCT" }; struct Course inp2 = { "DataStructures", "28SEPT" }; struct Course inp3 = { "Programming", "1NOV" }; fwrite(&inp1, sizeof(struct Course), 1, of); fwrite(&inp2, sizeof(struct Course), 1, of); fwrite(&inp3, sizeof(struct Course), 1, of); if (fwrite != 0) printf("Contents to file written successfully !\n"); else printf("Error writing file !\n"); fclose(of); // File pointer to read from file FILE* inf; struct Course inp; inf = fopen("test.txt", "r"); if (inf == NULL) { fprintf(stderr, "\nError to open the file\n"); exit(1); } while (fread(&inp, sizeof(struct Course), 1, inf)) printf("Course Name = %s Started = %s\n", inp.cname, inp.sdate); fclose(inf);} Output: simmytarika5 anikakapoor C-File Handling C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Producer Consumer Problem in C C program to find the length of a string C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Regular expressions in C Hamming code Implementation in C/C++ Handling multiple clients on server with multithreading using Socket Programming in C/C++ Exit codes in C/C++ with Examples C Hello World Program Conditional wait and signal in multi-threading Lamport's logical clock
[ { "code": null, "e": 24956, "s": 24928, "text": "\n03 Dec, 2021" }, { "code": null, "e": 25077, "s": 24956, "text": "C programming language supports four pre-defined functions to read contents from a file, defined in stdio.h header file:" }, { "code": null, "e": 25384, "s": 25077, "text": "fgetc()– This function is used to read a single character from the file.fgets()– This function is used to read strings from files.fscanf()– This function is used to read the block of raw bytes from files. This is used to read binary files.fread()– This function is used to read formatted input from a file." }, { "code": null, "e": 25457, "s": 25384, "text": "fgetc()– This function is used to read a single character from the file." }, { "code": null, "e": 25516, "s": 25457, "text": "fgets()– This function is used to read strings from files." }, { "code": null, "e": 25626, "s": 25516, "text": "fscanf()– This function is used to read the block of raw bytes from files. This is used to read binary files." }, { "code": null, "e": 25694, "s": 25626, "text": "fread()– This function is used to read formatted input from a file." }, { "code": null, "e": 25716, "s": 25694, "text": "Steps To Read A File:" }, { "code": null, "e": 25810, "s": 25716, "text": "Open a file using the function fopen() and store the reference of the file in a FILE pointer." }, { "code": null, "e": 25905, "s": 25810, "text": "Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread()." }, { "code": null, "e": 25954, "s": 25905, "text": "File close the file using the function fclose()." }, { "code": null, "e": 26012, "s": 25954, "text": "Let’s begin discussing each of these functions in detail." }, { "code": null, "e": 26020, "s": 26012, "text": "fgetc()" }, { "code": null, "e": 26330, "s": 26020, "text": "fgetc() reads characters pointed by the function pointer at that time. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the next character. This function returns a constant EOF (-1) when there is no content to read or an unsuccessful read." }, { "code": null, "e": 26338, "s": 26330, "text": "Syntax:" }, { "code": null, "e": 26360, "s": 26338, "text": "int fgetc(FILE *ptr);" }, { "code": null, "e": 26370, "s": 26360, "text": "Approach:" }, { "code": null, "e": 26474, "s": 26370, "text": "This program reads the whole content of the file, using this function by reading characters one by one." }, { "code": null, "e": 26557, "s": 26474, "text": "Do-While loop will be used which will read character until it reaches and of file." }, { "code": null, "e": 26609, "s": 26557, "text": "When it reaches end it returns EOF character (-1)." }, { "code": null, "e": 26675, "s": 26609, "text": "Using EOF:Below is the C program to implement the above approach-" }, { "code": null, "e": 26677, "s": 26675, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver codeint main(){ FILE* ptr; char ch; // Opening file in reading mode ptr = fopen(\"test.txt\", \"r\"); if (NULL == ptr) { printf(\"file can't be opened \\n\"); } printf(\"content of this file are \\n\"); // Printing what is written in file // character by character using loop. do { ch = fgetc(ptr); printf(\"%c\", ch); // Checking if character is not EOF. // If it is EOF stop eading. } while (ch != EOF); // Closing the file fclose(ptr); return 0;}", "e": 27311, "s": 26677, "text": null }, { "code": null, "e": 27323, "s": 27311, "text": "Input File:" }, { "code": null, "e": 27375, "s": 27323, "text": "GeeksforGeeks | A computer science portal for geeks" }, { "code": null, "e": 27383, "s": 27375, "text": "Output:" }, { "code": null, "e": 27541, "s": 27383, "text": "In the above code, the approach is to read one character from the file and check if it is not EOF, if it is not then print it and if it is then stop reading." }, { "code": null, "e": 27659, "s": 27541, "text": "Using feof():feof() function takes file pointer as argument and returns true if pointer reaches the end of the file. " }, { "code": null, "e": 27667, "s": 27659, "text": "Syntax:" }, { "code": null, "e": 27688, "s": 27667, "text": "int feof(FILE *ptr);" }, { "code": null, "e": 27698, "s": 27688, "text": "Approach:" }, { "code": null, "e": 27751, "s": 27698, "text": "In this approach, a character is read using fgetc()." }, { "code": null, "e": 27848, "s": 27751, "text": "Using feof() function check for end of file. since feof() returns true after it reaches the end." }, { "code": null, "e": 27942, "s": 27848, "text": "Use logical NOT operator(!) so that when it reaches end condition become false and loop stop." }, { "code": null, "e": 27998, "s": 27942, "text": "Below is the C program to implement the above approach:" }, { "code": null, "e": 28000, "s": 27998, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver codeint main(){ FILE* ptr; char ch; ptr = fopen(\"test.txt\", \"r\"); if (NULL == ptr) { printf(\"file can't be opened \\n\"); } printf(\"content of this file are \\n\"); while (!feof(ptr)) { ch = fgetc(ptr); printf(\"%c\", ch); } fclose(ptr); return 0;}", "e": 28410, "s": 28000, "text": null }, { "code": null, "e": 28422, "s": 28410, "text": "Input File:" }, { "code": null, "e": 28474, "s": 28422, "text": "GeeksforGeeks | A computer science portal for geeks" }, { "code": null, "e": 28482, "s": 28474, "text": "Output:" }, { "code": null, "e": 28490, "s": 28482, "text": "fgets()" }, { "code": null, "e": 28638, "s": 28490, "text": "fgets() reads one string at a time from the file. fgets() returns a string if it is successfully read by function or returns NULL if can not read. " }, { "code": null, "e": 28646, "s": 28638, "text": "Syntax:" }, { "code": null, "e": 28693, "s": 28646, "text": "char * fgets(char *str, int size, FILE * ptr);" }, { "code": null, "e": 28851, "s": 28693, "text": "Here, str: It is string in which fgets() store string after reading it from file.size: It is maximum characters to read from stream.ptr: It is file pointer." }, { "code": null, "e": 28861, "s": 28851, "text": "Approach:" }, { "code": null, "e": 28973, "s": 28861, "text": "In this approach, the contents of the file are read one character at a time until we reach the end of the file." }, { "code": null, "e": 29078, "s": 28973, "text": "When we reach the end of the file fgets() can’t read and returns NULL and the program will stop reading." }, { "code": null, "e": 29135, "s": 29078, "text": "Below is the C program to implement the above approach: " }, { "code": null, "e": 29137, "s": 29135, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver codeint main(){ FILE* ptr; char str[50]; ptr = fopen(\"test.txt\", \"a+\"); if (NULL == ptr) { printf(\"file can't be opened \\n\"); } printf(\"content of this file are \\n\"); while (fgets(str, 50, ptr) != NULL) { printf(\"%s\", str); } fclose(ptr); return 0;}", "e": 29548, "s": 29137, "text": null }, { "code": null, "e": 29560, "s": 29548, "text": "Input File:" }, { "code": null, "e": 29612, "s": 29560, "text": "GeeksforGeeks | A computer science portal for geeks" }, { "code": null, "e": 29620, "s": 29612, "text": "Output:" }, { "code": null, "e": 29629, "s": 29620, "text": "fscanf()" }, { "code": null, "e": 29675, "s": 29629, "text": "fscanf() reads formatted input from a stream." }, { "code": null, "e": 29683, "s": 29675, "text": "Syntax:" }, { "code": null, "e": 29731, "s": 29683, "text": "int fscanf(FILE *ptr, const char *format, ...) " }, { "code": null, "e": 29741, "s": 29731, "text": "Approach:" }, { "code": null, "e": 29812, "s": 29741, "text": "fscanf reads formatted data from the files and stores it in variables." }, { "code": null, "e": 29898, "s": 29812, "text": "The data in the buffer is printed on the console till the end of the file is reached." }, { "code": null, "e": 29902, "s": 29898, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ FILE* ptr = fopen(\"abc.txt\", \"r\"); if (ptr == NULL) { printf(\"no such file.\"); return 0; } /* Assuming that test.txt has content in below format NAME AGE CITY abc 12 hyderbad bef 25 delhi cce 65 bangalore */ char buf[100]; while (fscanf(ptr, \"%*s %*s %s \", buf) == 1) printf(\"%s\\n\", buf); return 0;}", "e": 30394, "s": 29902, "text": null }, { "code": null, "e": 30402, "s": 30394, "text": "Output:" }, { "code": null, "e": 30410, "s": 30402, "text": "fread()" }, { "code": null, "e": 30579, "s": 30410, "text": "fread() makes it easier to read blocks of data from a file. For instance, in the case of reading a structure from the file, it becomes an easy job to read using fread. " }, { "code": null, "e": 30587, "s": 30579, "text": "Syntax:" }, { "code": null, "e": 30652, "s": 30587, "text": "size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)" }, { "code": null, "e": 30948, "s": 30652, "text": "ptr: This is the pointer to a block of memory with a minimum size of size*nmemb bytes.size: This is the size in bytes of each element to be read.nmemb: This is the number of elements, each one with a size of size bytes.stream: This is the pointer to a FILE object that specifies an input stream." }, { "code": null, "e": 30958, "s": 30948, "text": "Approach:" }, { "code": null, "e": 31068, "s": 30958, "text": "It first, reads the count number of objects, each one with a size of size bytes from the given input stream. " }, { "code": null, "e": 31132, "s": 31068, "text": "The total amount of bytes reads if successful is (size*count). " }, { "code": null, "e": 31218, "s": 31132, "text": "According to the no. of characters read, the indicator file position is incremented. " }, { "code": null, "e": 31390, "s": 31218, "text": "If the objects read are not trivially copy-able, then the behavior is undefined and if the value of size or count is equal to zero, then this program will simply return 0." }, { "code": null, "e": 31394, "s": 31390, "text": "C++" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure to store// course detailsstruct Course { char cname[30]; char sdate[30];}; // Driver codeint main(){ FILE* of; of = fopen(\"test.txt\", \"w\"); if (of == NULL) { fprintf(stderr, \"\\nError to open the file\\n\"); exit(1); } struct Course inp1 = { \"Algorithms\", \"30OCT\" }; struct Course inp2 = { \"DataStructures\", \"28SEPT\" }; struct Course inp3 = { \"Programming\", \"1NOV\" }; fwrite(&inp1, sizeof(struct Course), 1, of); fwrite(&inp2, sizeof(struct Course), 1, of); fwrite(&inp3, sizeof(struct Course), 1, of); if (fwrite != 0) printf(\"Contents to file written successfully !\\n\"); else printf(\"Error writing file !\\n\"); fclose(of); // File pointer to read from file FILE* inf; struct Course inp; inf = fopen(\"test.txt\", \"r\"); if (inf == NULL) { fprintf(stderr, \"\\nError to open the file\\n\"); exit(1); } while (fread(&inp, sizeof(struct Course), 1, inf)) printf(\"Course Name = %s Started = %s\\n\", inp.cname, inp.sdate); fclose(inf);}", "e": 32722, "s": 31394, "text": null }, { "code": null, "e": 32730, "s": 32722, "text": "Output:" }, { "code": null, "e": 32743, "s": 32730, "text": "simmytarika5" }, { "code": null, "e": 32755, "s": 32743, "text": "anikakapoor" }, { "code": null, "e": 32771, "s": 32755, "text": "C-File Handling" }, { "code": null, "e": 32782, "s": 32771, "text": "C Programs" }, { "code": null, "e": 32880, "s": 32782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32889, "s": 32880, "text": "Comments" }, { "code": null, "e": 32902, "s": 32889, "text": "Old Comments" }, { "code": null, "e": 32933, "s": 32902, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 32974, "s": 32933, "text": "C program to find the length of a string" }, { "code": null, "e": 33045, "s": 32974, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 33070, "s": 33045, "text": "Regular expressions in C" }, { "code": null, "e": 33107, "s": 33070, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 33197, "s": 33107, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 33231, "s": 33197, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 33253, "s": 33231, "text": "C Hello World Program" }, { "code": null, "e": 33300, "s": 33253, "text": "Conditional wait and signal in multi-threading" } ]
Divide Two Integers in C++
Suppose we have two integers dividend and divisor. We have to divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing the dividend by divisor. The integer division should truncate toward zero. Both of the inputs are integers So if the given inputs are dividend = 7, divisor = -3, then output will be -2. To solve this, we will follow these steps − Taking two arguments x and y it indicates x divides y if x < -Infinity and y = 1, then return infinity a := |x|, b := |y| and ans := 0 while a – b >= 0p := 0while a – (left shifted b (left shifted 1 p times)) >= 0p := p + 1a := a – (left shift b, p times)ans := ans + left shift 1 p times p := 0 while a – (left shifted b (left shifted 1 p times)) >= 0p := p + 1 p := p + 1 a := a – (left shift b, p times) ans := ans + left shift 1 p times if x > 0 is true and y > 0 is also true, then return ans, otherwise return (– ans) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int divide(int l, int y) { if(l <= INT_MIN && y == -1)return INT_MAX; lli a = labs(l); lli b = labs(y); lli ans = 0; while(a-b >= 0){ int x = 0; while(a-(b << 1 << x) >= 0){ x++; } a -= b<<x; ans += 1<<x; } return (l>0)== (y>0)?ans:-ans; } }; main(){ Solution ob; cout << ob.divide(40, 3); } 40 3 13
[ { "code": null, "e": 1344, "s": 1062, "text": "Suppose we have two integers dividend and divisor. We have to divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing the dividend by divisor. The integer division should truncate toward zero. Both of the inputs are integers" }, { "code": null, "e": 1423, "s": 1344, "text": "So if the given inputs are dividend = 7, divisor = -3, then output will be -2." }, { "code": null, "e": 1467, "s": 1423, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1521, "s": 1467, "text": "Taking two arguments x and y it indicates x divides y" }, { "code": null, "e": 1570, "s": 1521, "text": "if x < -Infinity and y = 1, then return infinity" }, { "code": null, "e": 1602, "s": 1570, "text": "a := |x|, b := |y| and ans := 0" }, { "code": null, "e": 1756, "s": 1602, "text": "while a – b >= 0p := 0while a – (left shifted b (left shifted 1 p times)) >= 0p := p + 1a := a – (left shift b, p times)ans := ans + left shift 1 p times" }, { "code": null, "e": 1763, "s": 1756, "text": "p := 0" }, { "code": null, "e": 1830, "s": 1763, "text": "while a – (left shifted b (left shifted 1 p times)) >= 0p := p + 1" }, { "code": null, "e": 1841, "s": 1830, "text": "p := p + 1" }, { "code": null, "e": 1874, "s": 1841, "text": "a := a – (left shift b, p times)" }, { "code": null, "e": 1908, "s": 1874, "text": "ans := ans + left shift 1 p times" }, { "code": null, "e": 1991, "s": 1908, "text": "if x > 0 is true and y > 0 is also true, then return ans, otherwise return (– ans)" }, { "code": null, "e": 2061, "s": 1991, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2072, "s": 2061, "text": " Live Demo" }, { "code": null, "e": 2573, "s": 2072, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\npublic:\n int divide(int l, int y) {\n if(l <= INT_MIN && y == -1)return INT_MAX;\n lli a = labs(l);\n lli b = labs(y);\n lli ans = 0;\n while(a-b >= 0){\n int x = 0;\n while(a-(b << 1 << x) >= 0){\n x++;\n }\n a -= b<<x;\n ans += 1<<x;\n }\n return (l>0)== (y>0)?ans:-ans;\n }\n};\nmain(){\n Solution ob;\n cout << ob.divide(40, 3);\n}" }, { "code": null, "e": 2578, "s": 2573, "text": "40\n3" }, { "code": null, "e": 2581, "s": 2578, "text": "13" } ]
Bitwise Operators in Java - GeeksforGeeks
09 May, 2022 Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operators Arithmetic Operators Unary Operators Assignment Operator Relational Operators Logical Operators Ternary Operator Bitwise Operators Shift Operators This article explains all that one needs to know regarding Bitwise Operators. Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees. Now let’s look at each one of the bitwise operators in Java: 1. Bitwise OR (|) This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0. Example: a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise OR Operation of 5 and 7 0101 | 0111 ________ 0111 = 7 (In decimal) 2. Bitwise AND (&) This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0. Example: a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise AND Operation of 5 and 7 0101 & 0111 ________ 0101 = 5 (In decimal) 3. Bitwise XOR (^) This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if corresponding bits are different, it gives 1, else it shows 0. Example: a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise XOR Operation of 5 and 7 0101 ^ 0111 ________ 0010 = 2 (In decimal) 4. Bitwise Complement (~) This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement representation of the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. Example: a = 5 = 0101 (In Binary) Bitwise Complement Operation of 5 ~ 0101 ________ 1010 = 10 (In decimal) Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of 10 will be -6. Java // Java program to illustrate// bitwise operators public class operators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 = 5 System.out.println("a&b = " + (a & b)); // bitwise or // 0101 | 0111=0111 = 7 System.out.println("a|b = " + (a | b)); // bitwise xor // 0101 ^ 0111=0010 = 2 System.out.println("a^b = " + (a ^ b)); // bitwise not // ~00000000 00000000 00000000 00000101=11111111 11111111 11111111 11111010 // will give 1's complement (32 bit) of 5 = -6 System.out.println("~a = " + ~a); // can also be combined with // assignment operator to provide shorthand // assignment // a=a&b a &= b; System.out.println("a= " + a); }} a&b = 5 a|b = 7 a^b = 2 ~a = -6 a= 5 Bit-Shift Operators (Shift Operators) Shift 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. Syntax: number shift_op number_of_places_to_shift; Types of Shift Operators: Shift Operators are further divided into 4 types. These are: Signed Right shift operator (>>)Unsigned Right shift operator (>>>)Left shift operatorUnsigned Left shift operator (<<<) Signed Right shift operator (>>) Unsigned Right shift operator (>>>) Left shift operator Unsigned Left shift operator (<<<) Note: For more detail about the Shift Operators in Java, refer Shift Operator in Java. mikestahr infovasukv vinaysaini97 vidhyashankarmadheswaraswamy sk944795 sooda367 nishkarshgandhi cvpatel92 java-basics Java-Operators school-programming Java Java-Operators Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Stream In Java Reverse a string in Java Arrays.sort() in Java with examples How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java Generics in Java
[ { "code": null, "e": 30746, "s": 30718, "text": "\n09 May, 2022" }, { "code": null, "e": 31078, "s": 30746, "text": "Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: " }, { "code": null, "e": 31218, "s": 31078, "text": "Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operators" }, { "code": null, "e": 31239, "s": 31218, "text": "Arithmetic Operators" }, { "code": null, "e": 31255, "s": 31239, "text": "Unary Operators" }, { "code": null, "e": 31275, "s": 31255, "text": "Assignment Operator" }, { "code": null, "e": 31296, "s": 31275, "text": "Relational Operators" }, { "code": null, "e": 31314, "s": 31296, "text": "Logical Operators" }, { "code": null, "e": 31331, "s": 31314, "text": "Ternary Operator" }, { "code": null, "e": 31349, "s": 31331, "text": "Bitwise Operators" }, { "code": null, "e": 31365, "s": 31349, "text": "Shift Operators" }, { "code": null, "e": 31444, "s": 31365, "text": "This article explains all that one needs to know regarding Bitwise Operators. " }, { "code": null, "e": 31688, "s": 31444, "text": "Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees. " }, { "code": null, "e": 31750, "s": 31688, "text": "Now let’s look at each one of the bitwise operators in Java: " }, { "code": null, "e": 31769, "s": 31750, "text": "1. Bitwise OR (|) " }, { "code": null, "e": 31927, "s": 31769, "text": "This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0. " }, { "code": null, "e": 31936, "s": 31927, "text": "Example:" }, { "code": null, "e": 32069, "s": 31936, "text": "a = 5 = 0101 (In Binary)\nb = 7 = 0111 (In Binary)\n\nBitwise OR Operation of 5 and 7\n 0101\n| 0111\n ________\n 0111 = 7 (In decimal) " }, { "code": null, "e": 32088, "s": 32069, "text": "2. Bitwise AND (&)" }, { "code": null, "e": 32239, "s": 32088, "text": "This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0. " }, { "code": null, "e": 32248, "s": 32239, "text": "Example:" }, { "code": null, "e": 32382, "s": 32248, "text": "a = 5 = 0101 (In Binary)\nb = 7 = 0111 (In Binary)\n\nBitwise AND Operation of 5 and 7\n 0101\n& 0111\n ________\n 0101 = 5 (In decimal) " }, { "code": null, "e": 32402, "s": 32382, "text": "3. Bitwise XOR (^) " }, { "code": null, "e": 32570, "s": 32402, "text": "This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if corresponding bits are different, it gives 1, else it shows 0. " }, { "code": null, "e": 32579, "s": 32570, "text": "Example:" }, { "code": null, "e": 32713, "s": 32579, "text": "a = 5 = 0101 (In Binary)\nb = 7 = 0111 (In Binary)\n\nBitwise XOR Operation of 5 and 7\n 0101\n^ 0111\n ________\n 0010 = 2 (In decimal) " }, { "code": null, "e": 32739, "s": 32713, "text": "4. Bitwise Complement (~)" }, { "code": null, "e": 32941, "s": 32739, "text": "This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement representation of the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. " }, { "code": null, "e": 32950, "s": 32941, "text": "Example:" }, { "code": null, "e": 33055, "s": 32950, "text": "a = 5 = 0101 (In Binary)\n\nBitwise Complement Operation of 5\n\n~ 0101\n ________\n 1010 = 10 (In decimal) " }, { "code": null, "e": 33150, "s": 33055, "text": "Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of 10 will be -6." }, { "code": null, "e": 33155, "s": 33150, "text": "Java" }, { "code": "// Java program to illustrate// bitwise operators public class operators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 = 5 System.out.println(\"a&b = \" + (a & b)); // bitwise or // 0101 | 0111=0111 = 7 System.out.println(\"a|b = \" + (a | b)); // bitwise xor // 0101 ^ 0111=0010 = 2 System.out.println(\"a^b = \" + (a ^ b)); // bitwise not // ~00000000 00000000 00000000 00000101=11111111 11111111 11111111 11111010 // will give 1's complement (32 bit) of 5 = -6 System.out.println(\"~a = \" + ~a); // can also be combined with // assignment operator to provide shorthand // assignment // a=a&b a &= b; System.out.println(\"a= \" + a); }}", "e": 34025, "s": 33155, "text": null }, { "code": null, "e": 34062, "s": 34025, "text": "a&b = 5\na|b = 7\na^b = 2\n~a = -6\na= 5" }, { "code": null, "e": 34101, "s": 34062, "text": "Bit-Shift Operators (Shift Operators) " }, { "code": null, "e": 34306, "s": 34101, "text": "Shift 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. " }, { "code": null, "e": 34315, "s": 34306, "text": "Syntax: " }, { "code": null, "e": 34359, "s": 34315, "text": " number shift_op number_of_places_to_shift;" }, { "code": null, "e": 34385, "s": 34359, "text": "Types of Shift Operators:" }, { "code": null, "e": 34446, "s": 34385, "text": "Shift Operators are further divided into 4 types. These are:" }, { "code": null, "e": 34567, "s": 34446, "text": "Signed Right shift operator (>>)Unsigned Right shift operator (>>>)Left shift operatorUnsigned Left shift operator (<<<)" }, { "code": null, "e": 34600, "s": 34567, "text": "Signed Right shift operator (>>)" }, { "code": null, "e": 34636, "s": 34600, "text": "Unsigned Right shift operator (>>>)" }, { "code": null, "e": 34656, "s": 34636, "text": "Left shift operator" }, { "code": null, "e": 34691, "s": 34656, "text": "Unsigned Left shift operator (<<<)" }, { "code": null, "e": 34778, "s": 34691, "text": "Note: For more detail about the Shift Operators in Java, refer Shift Operator in Java." }, { "code": null, "e": 34788, "s": 34778, "text": "mikestahr" }, { "code": null, "e": 34799, "s": 34788, "text": "infovasukv" }, { "code": null, "e": 34812, "s": 34799, "text": "vinaysaini97" }, { "code": null, "e": 34841, "s": 34812, "text": "vidhyashankarmadheswaraswamy" }, { "code": null, "e": 34850, "s": 34841, "text": "sk944795" }, { "code": null, "e": 34859, "s": 34850, "text": "sooda367" }, { "code": null, "e": 34875, "s": 34859, "text": "nishkarshgandhi" }, { "code": null, "e": 34885, "s": 34875, "text": "cvpatel92" }, { "code": null, "e": 34897, "s": 34885, "text": "java-basics" }, { "code": null, "e": 34912, "s": 34897, "text": "Java-Operators" }, { "code": null, "e": 34931, "s": 34912, "text": "school-programming" }, { "code": null, "e": 34936, "s": 34931, "text": "Java" }, { "code": null, "e": 34951, "s": 34936, "text": "Java-Operators" }, { "code": null, "e": 34956, "s": 34951, "text": "Java" }, { "code": null, "e": 35054, "s": 34956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35098, "s": 35054, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35113, "s": 35098, "text": "Stream In Java" }, { "code": null, "e": 35138, "s": 35113, "text": "Reverse a string in Java" }, { "code": null, "e": 35174, "s": 35138, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 35205, "s": 35174, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35237, "s": 35205, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 35261, "s": 35237, "text": "Singleton Class in Java" }, { "code": null, "e": 35289, "s": 35261, "text": "Initializing a List in Java" }, { "code": null, "e": 35335, "s": 35289, "text": "Different ways of Reading a text file in Java" } ]
Difference between collection and collections in java
Java collection framework is used to manipulate the collection of the object. Collection framework contains multiple wrapper classes , convenience class , classes for legacy implementation like vector and Hashtable, collection interfaces and etc. Collection is an interface in the java collection framework. It is divided into two parts − Java util collection - It contains classes such as Set , queue , List and etc. Java util map - It contains classes such as Map , sortedMap and etc. On the other hand , Collections is the one the utility class. Main purpose of this class is to provide convenience method to the developers. This class has only static methods that operate on and return collection. The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null. 1 Basic It is an interface in Java collection framework It is a utility class in Collection framework 2 Static Methods It doesn't has all static methods It has all static method 3 Operation It is used to store list of object in a single object It is used to operate on collection. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) { // List List list = new ArrayList(); list.add("HCL"); list.add("DELL"); // Sorting List in ascending order according to the natural ordering Collections.sort(list); list.forEach(System.out::println); } }
[ { "code": null, "e": 1313, "s": 1062, "text": "Java collection framework is used to manipulate the collection of the object. Collection framework contains multiple wrapper classes , convenience class , classes for legacy implementation like vector and Hashtable, collection interfaces and etc. " }, { "code": null, "e": 1405, "s": 1313, "text": "Collection is an interface in the java collection framework. It is divided into two parts −" }, { "code": null, "e": 1484, "s": 1405, "text": "Java util collection - It contains classes such as Set , queue , List and etc." }, { "code": null, "e": 1553, "s": 1484, "text": "Java util map - It contains classes such as Map , sortedMap and etc." }, { "code": null, "e": 1890, "s": 1553, "text": "On the other hand , Collections is the one the utility class. Main purpose of this class is to provide convenience method to the developers. This class has only static methods that operate on and return collection. The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null." }, { "code": null, "e": 1892, "s": 1890, "text": "1" }, { "code": null, "e": 1899, "s": 1892, "text": "Basic " }, { "code": null, "e": 1949, "s": 1899, "text": " It is an interface in Java collection framework " }, { "code": null, "e": 1996, "s": 1949, "text": "It is a utility class in Collection framework " }, { "code": null, "e": 1998, "s": 1996, "text": "2" }, { "code": null, "e": 2014, "s": 1998, "text": "Static Methods " }, { "code": null, "e": 2049, "s": 2014, "text": "It doesn't has all static methods " }, { "code": null, "e": 2075, "s": 2049, "text": "It has all static method " }, { "code": null, "e": 2077, "s": 2075, "text": "3" }, { "code": null, "e": 2088, "s": 2077, "text": "Operation " }, { "code": null, "e": 2144, "s": 2088, "text": "It is used to store list of object in a single object " }, { "code": null, "e": 2181, "s": 2144, "text": "It is used to operate on collection." }, { "code": null, "e": 2575, "s": 2181, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\npublic class Main {\n public static void main(String[] args) {\n // List\n List list = new ArrayList();\n list.add(\"HCL\");\n list.add(\"DELL\");\n // Sorting List in ascending order according to the natural ordering\n Collections.sort(list);\n list.forEach(System.out::println);\n }\n}" } ]
Trapezoidal Rule for definite integral
Definite integrals can be solved using this trapezoidal rule. To integrate a function f(x) between the range a to b is basically finding the area below the curve from point x = a to x = b. To find that area, we can divide the area into n trapezoids, and the width of each trapezoid is h, so we can say that (b - a) = nh. When the number of trapezoids increases, the result of area calculation will be more accurate. To solve integrals, we will follow this formula. Here h is the width of the interval, and n is the number of intervals. We can find the h by using Input: The function f(x): 1-exp(-x/2.0) and limits of the integration: 0, 1. The number of intervals: 20 Output: The answer is: 0.21302 integrateTrapezoidal(a, b, n) Input: Lower and upper limit, and the number of integrals n. Output: The result of integration. Begin h := (b - a)/n sum := f(a) + f(b) for i := 1 to n, do sum := sum + f(a + ih) done return sum End #include<iostream> #include<cmath> using namespace std; float mathFunc(float x) { return (1-exp(-x/2.0)); //the function 1 - e^(-x/2) } float integrate(float a, float b, int n) { float h, sum; int i; h = (b-a)/n; //calculate the distance between two interval sum = (mathFunc(a)+mathFunc(b))/2; //initial sum using f(a) and f(b) for(i = 1; i<n; i++) { sum += mathFunc(a+i*h); } return (h*sum); //The result of integration } main() { float result, lowLim, upLim; int interval; cout << "Enter Lower Limit, Upper Limit and interval: "; cin >>lowLim >>upLim >>interval; result = integrate(lowLim, upLim, interval); cout << "The answer is: " << result; } Enter Lower Limit, Upper Limit and interval: 0 1 20 The answer is: 0.21302
[ { "code": null, "e": 1252, "s": 1062, "text": "Definite integrals can be solved using this trapezoidal rule. To integrate a function f(x) between the range a to b is basically finding the area below the curve from point x = a to x = b. " }, { "code": null, "e": 1528, "s": 1252, "text": "To find that area, we can divide the area into n trapezoids, and the width of each trapezoid is h, so we can say that (b - a) = nh. When the number of trapezoids increases, the result of area calculation will be more accurate. To solve integrals, we will follow this formula." }, { "code": null, "e": 1627, "s": 1528, "text": "Here h is the width of the interval, and n is the number of intervals. We can find the h by using " }, { "code": null, "e": 1763, "s": 1627, "text": "Input:\nThe function f(x): 1-exp(-x/2.0) and limits of the integration: 0, 1. The number of intervals: 20\nOutput:\nThe answer is: 0.21302" }, { "code": null, "e": 1793, "s": 1763, "text": "integrateTrapezoidal(a, b, n)" }, { "code": null, "e": 1854, "s": 1793, "text": "Input: Lower and upper limit, and the number of integrals n." }, { "code": null, "e": 1889, "s": 1854, "text": "Output: The result of integration." }, { "code": null, "e": 2013, "s": 1889, "text": "Begin\n h := (b - a)/n\n sum := f(a) + f(b)\n for i := 1 to n, do\n sum := sum + f(a + ih)\n done\n return sum\nEnd" }, { "code": null, "e": 2723, "s": 2013, "text": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\nfloat mathFunc(float x) {\n return (1-exp(-x/2.0)); //the function 1 - e^(-x/2)\n}\n\nfloat integrate(float a, float b, int n) {\n float h, sum;\n int i;\n h = (b-a)/n; //calculate the distance between two interval\n sum = (mathFunc(a)+mathFunc(b))/2; //initial sum using f(a) and f(b)\n\n for(i = 1; i<n; i++) {\n sum += mathFunc(a+i*h);\n }\n return (h*sum); //The result of integration\n}\n\nmain() {\n float result, lowLim, upLim;\n int interval;\n cout << \"Enter Lower Limit, Upper Limit and interval: \"; cin >>lowLim >>upLim >>interval;\n result = integrate(lowLim, upLim, interval);\n cout << \"The answer is: \" << result;\n}" }, { "code": null, "e": 2798, "s": 2723, "text": "Enter Lower Limit, Upper Limit and interval: 0 1 20\nThe answer is: 0.21302" } ]
QlikView - Data Transformation
Data Transformation is the process of modifying the existing data to a new data format. It can also involve filtering out or adding some specific values to the existing data set. QlikView can carry out data transformation after reading it to its memory and using many in-built functions. Let us consider the following input data, which represents the sales figures of each month. This is stored as a csv file with name quarterly_sales.csv Month,SalesVolume March,2145 April,2458 May,1245 Sales Values in Q2 June,5124 July,7421 August,2584 Sales Values in Q3 September,5314 October,7846 November,6532 December,4625 January,8547 February,3265 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option form the "Data from Files" tab and browse for the file quarterlt_sales.csv. Click next. The next screen prompts us to choose some data transformation. Click on the button Enable Transformation Step. In this step, we will select the transformation to eliminate the rows, which describe the quarter. We select Garbage → delete marked and select the two rows, which are not required. Click Next. After selecting the type of Transformation and the rows to be removed, the next screen prompts us for any further transformation like selecting a where clause or adding any Prefixes. We will ignore this step and click Finish. The Load script for the above data after all the transformation steps are complete is given below. The transformed data can be displayed by using a Table Box sheet object. The steps to create it are given below. Next, we choose the fields for the Table Box. The Table Box now displays the data in the sheet. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3210, "s": 2920, "text": "Data Transformation is the process of modifying the existing data to a new data format. It can also involve filtering out or adding some specific values to the existing data set. QlikView can carry out data transformation after reading it to its memory and using many in-built functions. " }, { "code": null, "e": 3361, "s": 3210, "text": "Let us consider the following input data, which represents the sales figures of each month. This is stored as a csv file with name quarterly_sales.csv" }, { "code": null, "e": 3564, "s": 3361, "text": "Month,SalesVolume\nMarch,2145\nApril,2458\nMay,1245\nSales Values in Q2\nJune,5124\nJuly,7421\nAugust,2584\nSales Values in Q3\nSeptember,5314\nOctober,7846\nNovember,6532\nDecember,4625\nJanuary,8547\nFebruary,3265\n" }, { "code": null, "e": 3818, "s": 3564, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option form the \"Data from Files\" tab and browse for the file quarterlt_sales.csv. Click next." }, { "code": null, "e": 3929, "s": 3818, "text": "The next screen prompts us to choose some data transformation. Click on the button Enable Transformation Step." }, { "code": null, "e": 4123, "s": 3929, "text": "In this step, we will select the transformation to eliminate the rows, which describe the quarter. We select Garbage → delete marked and select the two rows, which are not required. Click Next." }, { "code": null, "e": 4349, "s": 4123, "text": "After selecting the type of Transformation and the rows to be removed, the next screen prompts us for any further transformation like selecting a where clause or adding any Prefixes. We will ignore this step and click Finish." }, { "code": null, "e": 4448, "s": 4349, "text": "The Load script for the above data after all the transformation steps are complete is given\nbelow." }, { "code": null, "e": 4561, "s": 4448, "text": "The transformed data can be displayed by using a Table Box sheet object. The steps to create it are given below." }, { "code": null, "e": 4607, "s": 4561, "text": "Next, we choose the fields for the Table Box." }, { "code": null, "e": 4657, "s": 4607, "text": "The Table Box now displays the data in the sheet." }, { "code": null, "e": 4690, "s": 4657, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 4703, "s": 4690, "text": " Arthur Fong" }, { "code": null, "e": 4710, "s": 4703, "text": " Print" }, { "code": null, "e": 4721, "s": 4710, "text": " Add Notes" } ]
Difference between Natural join and Cross join in SQL
03 May, 2020 1. Natural Join :Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the tables but only one copy of each common column. Example:Consider the two tables given below: Consider the given query SELECT * FROM Student S NATURAL JOIN Marks M; Output : 2. Cross Join :Cross Join will produce cross or Cartesian product of two tables if there is no condition specifies. The resulting table will contain all the attributes of both the tables including duplicate or common columns also. Example:Consider the above two tables and the query is given below: SELECT * FROM Student S CROSS JOIN Marks M; Output: Difference between Natural JOIN and CROSS JOIN in SQL DBMS-Join DBMS Difference Between GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 May, 2020" }, { "code": null, "e": 257, "s": 54, "text": "1. Natural Join :Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the tables but only one copy of each common column." }, { "code": null, "e": 302, "s": 257, "text": "Example:Consider the two tables given below:" }, { "code": null, "e": 327, "s": 302, "text": "Consider the given query" }, { "code": null, "e": 374, "s": 327, "text": "SELECT * \nFROM Student S NATURAL JOIN Marks M;" }, { "code": null, "e": 383, "s": 374, "text": "Output :" }, { "code": null, "e": 614, "s": 383, "text": "2. Cross Join :Cross Join will produce cross or Cartesian product of two tables if there is no condition specifies. The resulting table will contain all the attributes of both the tables including duplicate or common columns also." }, { "code": null, "e": 682, "s": 614, "text": "Example:Consider the above two tables and the query is given below:" }, { "code": null, "e": 728, "s": 682, "text": "SELECT * \nFROM Student S CROSS JOIN Marks M; " }, { "code": null, "e": 736, "s": 728, "text": "Output:" }, { "code": null, "e": 790, "s": 736, "text": "Difference between Natural JOIN and CROSS JOIN in SQL" }, { "code": null, "e": 800, "s": 790, "text": "DBMS-Join" }, { "code": null, "e": 805, "s": 800, "text": "DBMS" }, { "code": null, "e": 824, "s": 805, "text": "Difference Between" }, { "code": null, "e": 832, "s": 824, "text": "GATE CS" }, { "code": null, "e": 837, "s": 832, "text": "DBMS" } ]
Maximum length subsequence with difference between adjacent elements as either 0 or 1
30 Apr, 2021 Given an array of n integers. The problem is to find maximum length of the subsequence with difference between adjacent elements as either 0 or 1.Examples: Input : arr[] = {2, 5, 6, 3, 7, 6, 5, 8} Output : 5 The subsequence is {5, 6, 7, 6, 5}. Input : arr[] = {-2, -1, 5, -1, 4, 0, 3} Output : 4 The subsequence is {-2, -1, -1, 0}. Source: Expedia Interview Experience | Set 12 The solution to this problem closely resembles the Longest Increasing Subsequence problem. The only difference is that here we have to check whether the absolute difference between the adjacent elements of the subsequence is either 0 or 1. C++ Java Python3 C# PHP Javascript // C++ implementation to find maximum length// subsequence with difference between adjacent// elements as either 0 or 1#include <bits/stdc++.h>using namespace std; // function to find maximum length subsequence// with difference between adjacent elements as// either 0 or 1int maxLenSub(int arr[], int n){ int mls[n], max = 0; // Initialize mls[] values for all indexes for (int i=0; i<n; i++) mls[i] = 1; // Compute optimized maximum length subsequence // values in bottom up manner for (int i=1; i<n; i++) for (int j=0; j<i; j++) if (abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (int i=0; i<n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } // Driver program to test aboveint main(){ int arr[] = {2, 5, 6, 3, 7, 6, 5, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum length subsequence = " << maxLenSub(arr, n); return 0;} // JAVA Code for Maximum length subsequence// with difference between adjacent elements// as either 0 or 1import java.util.*; class GFG { // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 public static int maxLenSub(int arr[], int n) { int mls[] = new int[n], max = 0; // Initialize mls[] values for all indexes for (int i = 0; i < n; i++) mls[i] = 1; // Compute optimized maximum length // subsequence values in bottom up manner for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (Math.abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (int i = 0; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {2, 5, 6, 3, 7, 6, 5, 8}; int n = arr.length; System.out.println("Maximum length subsequence = "+ maxLenSub(arr, n)); }} // This code is contributed by Arnav Kr. Mandal. # Python implementation to find maximum length# subsequence with difference between adjacent# elements as either 0 or 1 # function to find maximum length subsequence# with difference between adjacent elements as# either 0 or 1def maxLenSub( arr, n): mls=[] max = 0 #Initialize mls[] values for all indexes for i in range(n): mls.append(1) #Compute optimized maximum length subsequence # values in bottom up manner for i in range(n): for j in range(i): if (abs(arr[i] - arr[j]) <= 1 and mls[i] < mls[j] + 1): mls[i] = mls[j] + 1 # Store maximum of all 'mls' values in 'max' for i in range(n): if (max < mls[i]): max = mls[i] #required maximum length subsequence return max #Driver program to test abovearr = [2, 5, 6, 3, 7, 6, 5, 8]n = len(arr)print("Maximum length subsequence = ",maxLenSub(arr, n)) #This code is contributed by "Abhishek Sharma 44" // C# Code for Maximum length subsequence// with difference between adjacent elements// as either 0 or 1using System; class GFG { // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 public static int maxLenSub(int[] arr, int n) { int[] mls = new int[n]; int max = 0; // Initialize mls[] values for all indexes for (int i = 0; i < n; i++) mls[i] = 1; // Compute optimized maximum length // subsequence values in bottom up manner for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (Math.Abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (int i = 0; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } /* Driver program to test above function */ public static void Main() { int[] arr = { 2, 5, 6, 3, 7, 6, 5, 8 }; int n = arr.Length; Console.Write("Maximum length subsequence = " + maxLenSub(arr, n)); }} // This code is contributed by Sam007 <?php// PHP implementation to find maximum length// subsequence with difference between adjacent// elements as either 0 or 1 // function to find maximum length subsequence// with difference between adjacent elements as// either 0 or 1function maxLenSub($arr, $n){ $mls = array(); $max = 0; // Initialize mls[] values // for all indexes for($i = 0; $i < $n; $i++) $mls[$i] = 1; // Compute optimized maximum // length subsequence // values in bottom up manner for ($i = 1; $i < $n; $i++) for ( $j = 0; $j < $i; $j++) if (abs($arr[$i] - $arr[$j]) <= 1 and $mls[$i] < $mls[$j] + 1) $mls[$i] = $mls[$j] + 1; // Store maximum of all // 'mls' values in 'max' for($i = 0; $i < $n; $i++) if ($max < $mls[$i]) $max = $mls[$i]; // required maximum // length subsequence return $max; } // Driver Code $arr = array(2, 5, 6, 3, 7, 6, 5, 8); $n = count($arr); echo "Maximum length subsequence = " , maxLenSub($arr, $n); // This code is contributed by anuj_67.?> <script> // Javascript Code for// Maximum length subsequence// with difference between// adjacent elements// as either 0 or 1 // function to find maximum // length subsequence // with difference between // adjacent elements as // either 0 or 1 function maxLenSub(arr, n) { let mls = new Array(n).fill(1), max = 0; // Initialize mls[] values for all indexes for (let i = 0; i < n; i++) mls[i] = 1; // Compute optimized maximum length // subsequence values in bottom up manner for (let i = 1; i < n; i++) for (let j = 0; j < i; j++) if (Math.abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (let i = 0; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } // driver program let arr = [2, 5, 6, 3, 7, 6, 5, 8]; let n = arr.length; document.write("Maximum length subsequence = "+ maxLenSub(arr, n)); </script> Output: Maximum length subsequence = 5 Time Complexity: O(n2) Auxiliary Space: O(n)Maximum length subsequence with difference between adjacent elements as either 0 or 1 | Set 2This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m sanjoy_62 Expedia LIS Dynamic Programming Expedia Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Apr, 2021" }, { "code": null, "e": 210, "s": 52, "text": "Given an array of n integers. The problem is to find maximum length of the subsequence with difference between adjacent elements as either 0 or 1.Examples: " }, { "code": null, "e": 387, "s": 210, "text": "Input : arr[] = {2, 5, 6, 3, 7, 6, 5, 8}\nOutput : 5\nThe subsequence is {5, 6, 7, 6, 5}.\n\nInput : arr[] = {-2, -1, 5, -1, 4, 0, 3}\nOutput : 4\nThe subsequence is {-2, -1, -1, 0}." }, { "code": null, "e": 434, "s": 387, "text": "Source: Expedia Interview Experience | Set 12 " }, { "code": null, "e": 675, "s": 434, "text": "The solution to this problem closely resembles the Longest Increasing Subsequence problem. The only difference is that here we have to check whether the absolute difference between the adjacent elements of the subsequence is either 0 or 1. " }, { "code": null, "e": 679, "s": 675, "text": "C++" }, { "code": null, "e": 684, "s": 679, "text": "Java" }, { "code": null, "e": 692, "s": 684, "text": "Python3" }, { "code": null, "e": 695, "s": 692, "text": "C#" }, { "code": null, "e": 699, "s": 695, "text": "PHP" }, { "code": null, "e": 710, "s": 699, "text": "Javascript" }, { "code": "// C++ implementation to find maximum length// subsequence with difference between adjacent// elements as either 0 or 1#include <bits/stdc++.h>using namespace std; // function to find maximum length subsequence// with difference between adjacent elements as// either 0 or 1int maxLenSub(int arr[], int n){ int mls[n], max = 0; // Initialize mls[] values for all indexes for (int i=0; i<n; i++) mls[i] = 1; // Compute optimized maximum length subsequence // values in bottom up manner for (int i=1; i<n; i++) for (int j=0; j<i; j++) if (abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (int i=0; i<n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } // Driver program to test aboveint main(){ int arr[] = {2, 5, 6, 3, 7, 6, 5, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum length subsequence = \" << maxLenSub(arr, n); return 0;}", "e": 1820, "s": 710, "text": null }, { "code": "// JAVA Code for Maximum length subsequence// with difference between adjacent elements// as either 0 or 1import java.util.*; class GFG { // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 public static int maxLenSub(int arr[], int n) { int mls[] = new int[n], max = 0; // Initialize mls[] values for all indexes for (int i = 0; i < n; i++) mls[i] = 1; // Compute optimized maximum length // subsequence values in bottom up manner for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (Math.abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (int i = 0; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {2, 5, 6, 3, 7, 6, 5, 8}; int n = arr.length; System.out.println(\"Maximum length subsequence = \"+ maxLenSub(arr, n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 3202, "s": 1820, "text": null }, { "code": "# Python implementation to find maximum length# subsequence with difference between adjacent# elements as either 0 or 1 # function to find maximum length subsequence# with difference between adjacent elements as# either 0 or 1def maxLenSub( arr, n): mls=[] max = 0 #Initialize mls[] values for all indexes for i in range(n): mls.append(1) #Compute optimized maximum length subsequence # values in bottom up manner for i in range(n): for j in range(i): if (abs(arr[i] - arr[j]) <= 1 and mls[i] < mls[j] + 1): mls[i] = mls[j] + 1 # Store maximum of all 'mls' values in 'max' for i in range(n): if (max < mls[i]): max = mls[i] #required maximum length subsequence return max #Driver program to test abovearr = [2, 5, 6, 3, 7, 6, 5, 8]n = len(arr)print(\"Maximum length subsequence = \",maxLenSub(arr, n)) #This code is contributed by \"Abhishek Sharma 44\"", "e": 4179, "s": 3202, "text": null }, { "code": "// C# Code for Maximum length subsequence// with difference between adjacent elements// as either 0 or 1using System; class GFG { // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 public static int maxLenSub(int[] arr, int n) { int[] mls = new int[n]; int max = 0; // Initialize mls[] values for all indexes for (int i = 0; i < n; i++) mls[i] = 1; // Compute optimized maximum length // subsequence values in bottom up manner for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (Math.Abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (int i = 0; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } /* Driver program to test above function */ public static void Main() { int[] arr = { 2, 5, 6, 3, 7, 6, 5, 8 }; int n = arr.Length; Console.Write(\"Maximum length subsequence = \" + maxLenSub(arr, n)); }} // This code is contributed by Sam007", "e": 5477, "s": 4179, "text": null }, { "code": "<?php// PHP implementation to find maximum length// subsequence with difference between adjacent// elements as either 0 or 1 // function to find maximum length subsequence// with difference between adjacent elements as// either 0 or 1function maxLenSub($arr, $n){ $mls = array(); $max = 0; // Initialize mls[] values // for all indexes for($i = 0; $i < $n; $i++) $mls[$i] = 1; // Compute optimized maximum // length subsequence // values in bottom up manner for ($i = 1; $i < $n; $i++) for ( $j = 0; $j < $i; $j++) if (abs($arr[$i] - $arr[$j]) <= 1 and $mls[$i] < $mls[$j] + 1) $mls[$i] = $mls[$j] + 1; // Store maximum of all // 'mls' values in 'max' for($i = 0; $i < $n; $i++) if ($max < $mls[$i]) $max = $mls[$i]; // required maximum // length subsequence return $max; } // Driver Code $arr = array(2, 5, 6, 3, 7, 6, 5, 8); $n = count($arr); echo \"Maximum length subsequence = \" , maxLenSub($arr, $n); // This code is contributed by anuj_67.?>", "e": 6599, "s": 5477, "text": null }, { "code": "<script> // Javascript Code for// Maximum length subsequence// with difference between// adjacent elements// as either 0 or 1 // function to find maximum // length subsequence // with difference between // adjacent elements as // either 0 or 1 function maxLenSub(arr, n) { let mls = new Array(n).fill(1), max = 0; // Initialize mls[] values for all indexes for (let i = 0; i < n; i++) mls[i] = 1; // Compute optimized maximum length // subsequence values in bottom up manner for (let i = 1; i < n; i++) for (let j = 0; j < i; j++) if (Math.abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1) mls[i] = mls[j] + 1; // Store maximum of all 'mls' values in 'max' for (let i = 0; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } // driver program let arr = [2, 5, 6, 3, 7, 6, 5, 8]; let n = arr.length; document.write(\"Maximum length subsequence = \"+ maxLenSub(arr, n)); </script>", "e": 7841, "s": 6599, "text": null }, { "code": null, "e": 7851, "s": 7841, "text": "Output: " }, { "code": null, "e": 7882, "s": 7851, "text": "Maximum length subsequence = 5" }, { "code": null, "e": 8440, "s": 7882, "text": "Time Complexity: O(n2) Auxiliary Space: O(n)Maximum length subsequence with difference between adjacent elements as either 0 or 1 | Set 2This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8445, "s": 8440, "text": "vt_m" }, { "code": null, "e": 8455, "s": 8445, "text": "sanjoy_62" }, { "code": null, "e": 8463, "s": 8455, "text": "Expedia" }, { "code": null, "e": 8467, "s": 8463, "text": "LIS" }, { "code": null, "e": 8487, "s": 8467, "text": "Dynamic Programming" }, { "code": null, "e": 8495, "s": 8487, "text": "Expedia" }, { "code": null, "e": 8515, "s": 8495, "text": "Dynamic Programming" } ]
Python | Pandas Timestamp.today
27 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.today() function return the current time in the local timezone. This differs from datetime.today() in that it can be localized to a passed timezone. Syntax :Timestamp.today(cls, tz=None) Parameters :tz : Timezone to localize to Return : today’s time Example #1: Use Timestamp.today() function to return the current time in the local timezone. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.today() function to return the current time in the local timezone. # return current timets.today() Output : As we can see in the output, the Timestamp.today() function has returned the current time in the local timezone. Example #2: Use Timestamp.today() function to return the current time in the local timezone. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.today() function to return the current time in the local timezone. # return current timets.today() Output : As we can see in the output, the Timestamp.today() function has returned the current time in the local timezone. Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 408, "s": 242, "text": "Pandas Timestamp.today() function return the current time in the local timezone. This differs from datetime.today() in that it can be localized to a passed timezone." }, { "code": null, "e": 446, "s": 408, "text": "Syntax :Timestamp.today(cls, tz=None)" }, { "code": null, "e": 487, "s": 446, "text": "Parameters :tz : Timezone to localize to" }, { "code": null, "e": 509, "s": 487, "text": "Return : today’s time" }, { "code": null, "e": 602, "s": 509, "text": "Example #1: Use Timestamp.today() function to return the current time in the local timezone." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 831, "s": 602, "text": null }, { "code": null, "e": 840, "s": 831, "text": "Output :" }, { "code": null, "e": 937, "s": 840, "text": "Now we will use the Timestamp.today() function to return the current time in the local timezone." }, { "code": "# return current timets.today()", "e": 969, "s": 937, "text": null }, { "code": null, "e": 978, "s": 969, "text": "Output :" }, { "code": null, "e": 1091, "s": 978, "text": "As we can see in the output, the Timestamp.today() function has returned the current time in the local timezone." }, { "code": null, "e": 1184, "s": 1091, "text": "Example #2: Use Timestamp.today() function to return the current time in the local timezone." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 1412, "s": 1184, "text": null }, { "code": null, "e": 1421, "s": 1412, "text": "Output :" }, { "code": null, "e": 1518, "s": 1421, "text": "Now we will use the Timestamp.today() function to return the current time in the local timezone." }, { "code": "# return current timets.today()", "e": 1550, "s": 1518, "text": null }, { "code": null, "e": 1559, "s": 1550, "text": "Output :" }, { "code": null, "e": 1672, "s": 1559, "text": "As we can see in the output, the Timestamp.today() function has returned the current time in the local timezone." }, { "code": null, "e": 1696, "s": 1672, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 1710, "s": 1696, "text": "Python-pandas" }, { "code": null, "e": 1717, "s": 1710, "text": "Python" }, { "code": null, "e": 1815, "s": 1717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1847, "s": 1815, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1874, "s": 1847, "text": "Python Classes and Objects" }, { "code": null, "e": 1895, "s": 1874, "text": "Python OOPs Concepts" }, { "code": null, "e": 1918, "s": 1895, "text": "Introduction To PYTHON" }, { "code": null, "e": 1949, "s": 1918, "text": "Python | os.path.join() method" }, { "code": null, "e": 2005, "s": 1949, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2047, "s": 2005, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2089, "s": 2047, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2128, "s": 2089, "text": "Python | Get unique values from a list" } ]
Stream dropWhile() method in Java with examples
25 Apr, 2019 The dropWhile(java.util.function.Predicate) method returns two different types of stream depending upon whether the stream is ordered or not. If the stream is ordered then a stream of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate is returned by method else a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate. In the case of the ordered stream, the longest prefix is a contiguous sequence of elements of this stream that match the predicate passed as a parameter to this method. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate. In the case of the unordered stream, some elements of this stream match the given predicate and behaviour of this operation becomes nondeterministic; so this method is free to drop any subset of matching elements.There may be some cases when all elements of this stream match the given predicate then this method will drop all elements and the result is an empty stream irrespective of order of Stream and when no elements of the stream match the given predicate then no elements are dropped and the result is the same as the input stream. Syntax: default Stream<T> dropWhile(Predicate<T> predicate) Parameters: This method accepts a single parameter predicate which is a non-interfering, stateless predicate to apply to elements to determine the longest prefix of elements. Return value: This method returns the new stream. Below programs illustrate dropWhile(java.util.function.Predicate) method: Program 1: // Java program to demonstrate// Stream.dropWhile methodimport java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // create a stream of numbers from 1 to 10 Stream<Integer> stream = Stream.of(4, 4, 4, 5, 6, 7, 8, 9, 10); // apply dropWhile to drop all the numbers // matches passed predicate List<Integer> list = stream.dropWhile(number -> (number / 4 == 1)) .collect(Collectors.toList()); // print list System.out.println(list); }} The output printed on console of IDE is shown below.Output: Program 2: // Java program to demonstrate// Stream.dropWhile method import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // create a stream of names Stream<String> stream = Stream.of("aman", "amar", "suraj", "suvam", "Zahafuj"); // apply dropWhile to drop all the names // matches passed predicate List<String> list = stream.dropWhile(name -> (name.charAt(0) == 'a')) .collect(Collectors.toList()); // print list System.out.println(list); }} The output printed on console is shown below.Output: References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#dropWhile(java.util.function.Predicate) Java - util package Java-Functions 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": "\n25 Apr, 2019" }, { "code": null, "e": 170, "s": 28, "text": "The dropWhile(java.util.function.Predicate) method returns two different types of stream depending upon whether the stream is ordered or not." }, { "code": null, "e": 483, "s": 170, "text": "If the stream is ordered then a stream of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate is returned by method else a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate." }, { "code": null, "e": 830, "s": 483, "text": "In the case of the ordered stream, the longest prefix is a contiguous sequence of elements of this stream that match the predicate passed as a parameter to this method. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate." }, { "code": null, "e": 1370, "s": 830, "text": "In the case of the unordered stream, some elements of this stream match the given predicate and behaviour of this operation becomes nondeterministic; so this method is free to drop any subset of matching elements.There may be some cases when all elements of this stream match the given predicate then this method will drop all elements and the result is an empty stream irrespective of order of Stream and when no elements of the stream match the given predicate then no elements are dropped and the result is the same as the input stream." }, { "code": null, "e": 1378, "s": 1370, "text": "Syntax:" }, { "code": null, "e": 1431, "s": 1378, "text": "default Stream<T> dropWhile(Predicate<T> predicate)\n" }, { "code": null, "e": 1606, "s": 1431, "text": "Parameters: This method accepts a single parameter predicate which is a non-interfering, stateless predicate to apply to elements to determine the longest prefix of elements." }, { "code": null, "e": 1656, "s": 1606, "text": "Return value: This method returns the new stream." }, { "code": null, "e": 1730, "s": 1656, "text": "Below programs illustrate dropWhile(java.util.function.Predicate) method:" }, { "code": null, "e": 1741, "s": 1730, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Stream.dropWhile methodimport java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // create a stream of numbers from 1 to 10 Stream<Integer> stream = Stream.of(4, 4, 4, 5, 6, 7, 8, 9, 10); // apply dropWhile to drop all the numbers // matches passed predicate List<Integer> list = stream.dropWhile(number -> (number / 4 == 1)) .collect(Collectors.toList()); // print list System.out.println(list); }}", "e": 2369, "s": 1741, "text": null }, { "code": null, "e": 2429, "s": 2369, "text": "The output printed on console of IDE is shown below.Output:" }, { "code": null, "e": 2440, "s": 2429, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Stream.dropWhile method import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // create a stream of names Stream<String> stream = Stream.of(\"aman\", \"amar\", \"suraj\", \"suvam\", \"Zahafuj\"); // apply dropWhile to drop all the names // matches passed predicate List<String> list = stream.dropWhile(name -> (name.charAt(0) == 'a')) .collect(Collectors.toList()); // print list System.out.println(list); }}", "e": 3095, "s": 2440, "text": null }, { "code": null, "e": 3148, "s": 3095, "text": "The output printed on console is shown below.Output:" }, { "code": null, "e": 3272, "s": 3148, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#dropWhile(java.util.function.Predicate)" }, { "code": null, "e": 3292, "s": 3272, "text": "Java - util package" }, { "code": null, "e": 3307, "s": 3292, "text": "Java-Functions" }, { "code": null, "e": 3319, "s": 3307, "text": "java-stream" }, { "code": null, "e": 3324, "s": 3319, "text": "Java" }, { "code": null, "e": 3329, "s": 3324, "text": "Java" } ]
VAX Architecture
22 Mar, 2022 VAX Architecture was designed to increase the compatibility by improving the hardware of the earlier designed machines. As VAX architecture is an example of the CISC (Complex Instruction Set Computers) therefore there are large and complicated instruction sets used in the system. Memory: VAX architecture consists of 8- bit bytes memory. Two consecutive bytes form a word, four bytes form a longword, eight bytes form a quadword, sixteen bytes form an octaword. All VAX programs operates on Virtual Address Space (232 bytes). The Virtual Address Space is divided into two spaces:System SpaceProcess SpaceRegisters: VAX architecture have 16 general-purpose registers from R0 to R15. Some of these registers have special name and use. Memory: VAX architecture consists of 8- bit bytes memory. Two consecutive bytes form a word, four bytes form a longword, eight bytes form a quadword, sixteen bytes form an octaword. All VAX programs operates on Virtual Address Space (232 bytes). The Virtual Address Space is divided into two spaces:System SpaceProcess Space System Space Process Space Registers: VAX architecture have 16 general-purpose registers from R0 to R15. Some of these registers have special name and use. AP - Argument Pointer FP - Frame Pointer SP - Stack Pointer PC - Program Counter Data Formats:Integers are stored as Binary numbers in byte, word, longword, quadword or octaword.Characters are represented using 8-bit ASCII codes.Floating points are represented using four different floating-point formats of length ranging from 4 to 16 bytes.Instruction Formats: VAX machine architecture use a variable-length instruction format. Each instruction consists of an operand code (1 or 2 bytes) followed by up to six operand specifier, depending on the type of instruction.Addressing Modes: VAX architecture use a large number of addressing modes. There are number of modes available such as register mode, register deferred mode, autoincrement and autodecrement mode. There are also base relative addressing modes, with displacement fields of different lengths. Program counter relative mode is also used to deal with PC register.Instruction Set: In VAX systems instruction mnemonics are formed by combining following elements:Prefix: A Prefix specifies the type of operation.Suffix: A Suffix specifies the data type of the operands.Modifier: A modifier specifies the number of operand involved.Input and Output: I/O device controller are used to implement I/O on VAX architecture. Each controller has a set of control/status. The portion of the space into which the device controller register are mapped is called I/O space. Data Formats:Integers are stored as Binary numbers in byte, word, longword, quadword or octaword.Characters are represented using 8-bit ASCII codes.Floating points are represented using four different floating-point formats of length ranging from 4 to 16 bytes. Integers are stored as Binary numbers in byte, word, longword, quadword or octaword. Characters are represented using 8-bit ASCII codes. Floating points are represented using four different floating-point formats of length ranging from 4 to 16 bytes. Instruction Formats: VAX machine architecture use a variable-length instruction format. Each instruction consists of an operand code (1 or 2 bytes) followed by up to six operand specifier, depending on the type of instruction. Addressing Modes: VAX architecture use a large number of addressing modes. There are number of modes available such as register mode, register deferred mode, autoincrement and autodecrement mode. There are also base relative addressing modes, with displacement fields of different lengths. Program counter relative mode is also used to deal with PC register. Instruction Set: In VAX systems instruction mnemonics are formed by combining following elements:Prefix: A Prefix specifies the type of operation.Suffix: A Suffix specifies the data type of the operands.Modifier: A modifier specifies the number of operand involved. Prefix: A Prefix specifies the type of operation. Suffix: A Suffix specifies the data type of the operands. Modifier: A modifier specifies the number of operand involved. Input and Output: I/O device controller are used to implement I/O on VAX architecture. Each controller has a set of control/status. The portion of the space into which the device controller register are mapped is called I/O space. simmytarika5 Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Control Characters Direct Access Media (DMA) Controller in Computer Architecture Logical and Physical Address in Operating System Computer Organization | RISC and CISC Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Memory Hierarchy Design and its Characteristics Programmable peripheral interface 8255 Architecture of 8085 microprocessor Interrupts Write Through and Write Back in Cache
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2022" }, { "code": null, "e": 309, "s": 28, "text": "VAX Architecture was designed to increase the compatibility by improving the hardware of the earlier designed machines. As VAX architecture is an example of the CISC (Complex Instruction Set Computers) therefore there are large and complicated instruction sets used in the system." }, { "code": null, "e": 765, "s": 309, "text": "Memory: VAX architecture consists of 8- bit bytes memory. Two consecutive bytes form a word, four bytes form a longword, eight bytes form a quadword, sixteen bytes form an octaword. All VAX programs operates on Virtual Address Space (232 bytes). The Virtual Address Space is divided into two spaces:System SpaceProcess SpaceRegisters: VAX architecture have 16 general-purpose registers from R0 to R15. Some of these registers have special name and use. " }, { "code": null, "e": 1090, "s": 765, "text": "Memory: VAX architecture consists of 8- bit bytes memory. Two consecutive bytes form a word, four bytes form a longword, eight bytes form a quadword, sixteen bytes form an octaword. All VAX programs operates on Virtual Address Space (232 bytes). The Virtual Address Space is divided into two spaces:System SpaceProcess Space" }, { "code": null, "e": 1103, "s": 1090, "text": "System Space" }, { "code": null, "e": 1117, "s": 1103, "text": "Process Space" }, { "code": null, "e": 1249, "s": 1117, "text": "Registers: VAX architecture have 16 general-purpose registers from R0 to R15. Some of these registers have special name and use. " }, { "code": null, "e": 1331, "s": 1249, "text": "AP - Argument Pointer\nFP - Frame Pointer\nSP - Stack Pointer\nPC - Program Counter " }, { "code": null, "e": 2672, "s": 1331, "text": "Data Formats:Integers are stored as Binary numbers in byte, word, longword, quadword or octaword.Characters are represented using 8-bit ASCII codes.Floating points are represented using four different floating-point formats of length ranging from 4 to 16 bytes.Instruction Formats: VAX machine architecture use a variable-length instruction format. Each instruction consists of an operand code (1 or 2 bytes) followed by up to six operand specifier, depending on the type of instruction.Addressing Modes: VAX architecture use a large number of addressing modes. There are number of modes available such as register mode, register deferred mode, autoincrement and autodecrement mode. There are also base relative addressing modes, with displacement fields of different lengths. Program counter relative mode is also used to deal with PC register.Instruction Set: In VAX systems instruction mnemonics are formed by combining following elements:Prefix: A Prefix specifies the type of operation.Suffix: A Suffix specifies the data type of the operands.Modifier: A modifier specifies the number of operand involved.Input and Output: I/O device controller are used to implement I/O on VAX architecture. Each controller has a set of control/status. The portion of the space into which the device controller register are mapped is called I/O space." }, { "code": null, "e": 2934, "s": 2672, "text": "Data Formats:Integers are stored as Binary numbers in byte, word, longword, quadword or octaword.Characters are represented using 8-bit ASCII codes.Floating points are represented using four different floating-point formats of length ranging from 4 to 16 bytes." }, { "code": null, "e": 3019, "s": 2934, "text": "Integers are stored as Binary numbers in byte, word, longword, quadword or octaword." }, { "code": null, "e": 3071, "s": 3019, "text": "Characters are represented using 8-bit ASCII codes." }, { "code": null, "e": 3185, "s": 3071, "text": "Floating points are represented using four different floating-point formats of length ranging from 4 to 16 bytes." }, { "code": null, "e": 3412, "s": 3185, "text": "Instruction Formats: VAX machine architecture use a variable-length instruction format. Each instruction consists of an operand code (1 or 2 bytes) followed by up to six operand specifier, depending on the type of instruction." }, { "code": null, "e": 3771, "s": 3412, "text": "Addressing Modes: VAX architecture use a large number of addressing modes. There are number of modes available such as register mode, register deferred mode, autoincrement and autodecrement mode. There are also base relative addressing modes, with displacement fields of different lengths. Program counter relative mode is also used to deal with PC register." }, { "code": null, "e": 4037, "s": 3771, "text": "Instruction Set: In VAX systems instruction mnemonics are formed by combining following elements:Prefix: A Prefix specifies the type of operation.Suffix: A Suffix specifies the data type of the operands.Modifier: A modifier specifies the number of operand involved." }, { "code": null, "e": 4087, "s": 4037, "text": "Prefix: A Prefix specifies the type of operation." }, { "code": null, "e": 4145, "s": 4087, "text": "Suffix: A Suffix specifies the data type of the operands." }, { "code": null, "e": 4208, "s": 4145, "text": "Modifier: A modifier specifies the number of operand involved." }, { "code": null, "e": 4439, "s": 4208, "text": "Input and Output: I/O device controller are used to implement I/O on VAX architecture. Each controller has a set of control/status. The portion of the space into which the device controller register are mapped is called I/O space." }, { "code": null, "e": 4452, "s": 4439, "text": "simmytarika5" }, { "code": null, "e": 4489, "s": 4452, "text": "Computer Organization & Architecture" }, { "code": null, "e": 4587, "s": 4489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4606, "s": 4587, "text": "Control Characters" }, { "code": null, "e": 4668, "s": 4606, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 4717, "s": 4668, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 4755, "s": 4717, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 4850, "s": 4755, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 4898, "s": 4850, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 4937, "s": 4898, "text": "Programmable peripheral interface 8255" }, { "code": null, "e": 4973, "s": 4937, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 4984, "s": 4973, "text": "Interrupts" } ]
Create a Table in a PDF Using Java
04 Nov, 2020 The creation of a table in a PDF using Java is done by installing the document class. While instantiating this class, pass a PdfDocument object as a parameter to its constructor. Then, to feature a table to the document, instantiate the Table class, and add this object to the document using the add() method. Note: External jar files are required to perform operations on PDF. Below is an example PDF adding a table in a pdf using java with all the steps: Java // Adding table in a pdf using javaimport com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Cell;import com.itextpdf.layout.element.Table; public class AddingTableToPDF { public static void main(String args[]) throws Exception { String file = "C:/EXAMPLES/itextExamples/addingTableToPDF.pdf"; // Step-1 Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); // Step-2 Creating a Document object Document doc = new Document(pdfDoc); // Step-3 Creating a table Table table = new Table(2); // Step-4 Adding cells to the table table.addCell(new Cell().add("Name")); table.addCell(new Cell().add("Raju")); table.addCell(new Cell().add("Id")); table.addCell(new Cell().add("1001")); table.addCell(new Cell().add("Designation")); table.addCell(new Cell().add("Programmer")); // Step-6 Adding Table to document doc.add(table); // Step-7 Closing the document doc.close(); System.out.println("Table created successfully.."); }} Output: Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Nov, 2020" }, { "code": null, "e": 364, "s": 54, "text": "The creation of a table in a PDF using Java is done by installing the document class. While instantiating this class, pass a PdfDocument object as a parameter to its constructor. Then, to feature a table to the document, instantiate the Table class, and add this object to the document using the add() method." }, { "code": null, "e": 432, "s": 364, "text": "Note: External jar files are required to perform operations on PDF." }, { "code": null, "e": 511, "s": 432, "text": "Below is an example PDF adding a table in a pdf using java with all the steps:" }, { "code": null, "e": 516, "s": 511, "text": "Java" }, { "code": "// Adding table in a pdf using javaimport com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Cell;import com.itextpdf.layout.element.Table; public class AddingTableToPDF { public static void main(String args[]) throws Exception { String file = \"C:/EXAMPLES/itextExamples/addingTableToPDF.pdf\"; // Step-1 Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); // Step-2 Creating a Document object Document doc = new Document(pdfDoc); // Step-3 Creating a table Table table = new Table(2); // Step-4 Adding cells to the table table.addCell(new Cell().add(\"Name\")); table.addCell(new Cell().add(\"Raju\")); table.addCell(new Cell().add(\"Id\")); table.addCell(new Cell().add(\"1001\")); table.addCell(new Cell().add(\"Designation\")); table.addCell(new Cell().add(\"Programmer\")); // Step-6 Adding Table to document doc.add(table); // Step-7 Closing the document doc.close(); System.out.println(\"Table created successfully..\"); }}", "e": 1745, "s": 516, "text": null }, { "code": null, "e": 1753, "s": 1745, "text": "Output:" }, { "code": null, "e": 1758, "s": 1753, "text": "Java" }, { "code": null, "e": 1772, "s": 1758, "text": "Java Programs" }, { "code": null, "e": 1777, "s": 1772, "text": "Java" } ]
Python | os.strerror() method
22 May, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.strerror() method in Python is used to get the error message corresponding to the error code. Syntax: os.strerror(code) Parameter:code: A integer value that denotes the error code Return Type: This method returns a string representing the error message corresponding to the specified error code. # Python program to explain os.strerror() method # importing os module import os # Get the error message # corresponding to # error code 1code = 1error = os.strerror(code) # Print the error message # corresponding to # error code 1print("Error message corresponding to error code % d:" % code, error) # Get the error message # corresponding to # error code 5code = 5error = os.strerror(code) # Print the error message # corresponding to # error code 5print("Error message corresponding to error code % d:" % code, error) Error message corresponding to error code 1: Operation not permitted Error Message corresponding to error code 5: Input/output error Code #2: Printing first 20 errors # Python program to explain os.strerror() method # importing os module import os # Get the error message # corresponding to the# first 20 error codesn = 20 for i in range(1, n + 1) error = os.strerror(code) print("Error code % d:" % i, error) Error code 1: Operation not permitted Error code 2: No such file or directory Error code 3: No such process Error code 4: Interrupted system call Error code 5: Input/output error Error code 6: No such device or address Error code 7: Argument list too long Error code 8: Exec format error Error code 9: Bad file descriptor Error code 10: No child processes Error code 11: Resource temporarily unavailable Error code 12: Cannot allocate memory Error code 13: Permission denied Error code 14: Bad address Error code 15: Block device required Error code 16: Device or resource busy Error code 17: File exists Error code 18: Invalid cross-device link Error code 19: No such device Error code 20: Not a directory Code #3: Checking error message for an invalid error code # Python program to explain os.strerror() method # importing os module import os # Get the error message # corresponding to # error code 200code = 200error = os.strerror(code) # Print the error message # corresponding to # error code 200print("Error message corresponding to error code % d:" % code, error) # Get the error message # corresponding to # error code 300code = 300error = os.strerror(code) # Print the error message # corresponding to # error code 300print("Error message corresponding to error code % d:" % code, error) # os.strerror() will return# An unknown error# in case specified code# is invalid Error message corresponding to error code 200: Unknown error 200 Error message corresponding to error code 300: Unknown error 300 python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 May, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 442, "s": 247, "text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system." }, { "code": null, "e": 539, "s": 442, "text": "os.strerror() method in Python is used to get the error message corresponding to the error code." }, { "code": null, "e": 565, "s": 539, "text": "Syntax: os.strerror(code)" }, { "code": null, "e": 625, "s": 565, "text": "Parameter:code: A integer value that denotes the error code" }, { "code": null, "e": 741, "s": 625, "text": "Return Type: This method returns a string representing the error message corresponding to the specified error code." }, { "code": "# Python program to explain os.strerror() method # importing os module import os # Get the error message # corresponding to # error code 1code = 1error = os.strerror(code) # Print the error message # corresponding to # error code 1print(\"Error message corresponding to error code % d:\" % code, error) # Get the error message # corresponding to # error code 5code = 5error = os.strerror(code) # Print the error message # corresponding to # error code 5print(\"Error message corresponding to error code % d:\" % code, error)", "e": 1270, "s": 741, "text": null }, { "code": null, "e": 1404, "s": 1270, "text": "Error message corresponding to error code 1: Operation not permitted\nError Message corresponding to error code 5: Input/output error\n" }, { "code": null, "e": 1438, "s": 1404, "text": "Code #2: Printing first 20 errors" }, { "code": "# Python program to explain os.strerror() method # importing os module import os # Get the error message # corresponding to the# first 20 error codesn = 20 for i in range(1, n + 1) error = os.strerror(code) print(\"Error code % d:\" % i, error)", "e": 1693, "s": 1438, "text": null }, { "code": null, "e": 2401, "s": 1693, "text": "Error code 1: Operation not permitted\nError code 2: No such file or directory\nError code 3: No such process\nError code 4: Interrupted system call\nError code 5: Input/output error\nError code 6: No such device or address\nError code 7: Argument list too long\nError code 8: Exec format error\nError code 9: Bad file descriptor\nError code 10: No child processes\nError code 11: Resource temporarily unavailable\nError code 12: Cannot allocate memory\nError code 13: Permission denied\nError code 14: Bad address\nError code 15: Block device required\nError code 16: Device or resource busy\nError code 17: File exists\nError code 18: Invalid cross-device link\nError code 19: No such device\nError code 20: Not a directory\n" }, { "code": null, "e": 2459, "s": 2401, "text": "Code #3: Checking error message for an invalid error code" }, { "code": "# Python program to explain os.strerror() method # importing os module import os # Get the error message # corresponding to # error code 200code = 200error = os.strerror(code) # Print the error message # corresponding to # error code 200print(\"Error message corresponding to error code % d:\" % code, error) # Get the error message # corresponding to # error code 300code = 300error = os.strerror(code) # Print the error message # corresponding to # error code 300print(\"Error message corresponding to error code % d:\" % code, error) # os.strerror() will return# An unknown error# in case specified code# is invalid", "e": 3087, "s": 2459, "text": null }, { "code": null, "e": 3218, "s": 3087, "text": "Error message corresponding to error code 200: Unknown error 200\nError message corresponding to error code 300: Unknown error 300\n" }, { "code": null, "e": 3235, "s": 3218, "text": "python-os-module" }, { "code": null, "e": 3242, "s": 3235, "text": "Python" } ]
Scala Map filter() method with example
13 Aug, 2019 The filter() method is utilized to select all elements of the map which satisfies a stated predicate. Method Definition: def filter(p: ((A, B))=> Boolean): Map[A, B] Return Type: It returns a new map consisting all the elements of the map which satisfies the given predicate. Example #1: // Scala program of filter()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map("geeks" -> 5, "for" -> 3) // Applying filter method val result = m1.filter(x => x._1 == "geeks" && x._2 == 5) // Displays output println(result) }} Map(geeks -> 5) Example #2: // Scala program of filter()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map("geeks" -> 5, "for" -> 3) // Applying filter method val result = m1.filter(x => x._1 == "for" && x._2 == 5) // Displays output println(result) }} Map() Here, an empty map is returned as none of the elements satisfy the stated predicate. Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Lists Scala Constructors Operators in Scala Scala | Arrays How to Install Scala with VSCode? Inheritance in Scala Enumeration in Scala Scala | Option Break statement in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2019" }, { "code": null, "e": 130, "s": 28, "text": "The filter() method is utilized to select all elements of the map which satisfies a stated predicate." }, { "code": null, "e": 194, "s": 130, "text": "Method Definition: def filter(p: ((A, B))=> Boolean): Map[A, B]" }, { "code": null, "e": 304, "s": 194, "text": "Return Type: It returns a new map consisting all the elements of the map which satisfies the given predicate." }, { "code": null, "e": 316, "s": 304, "text": "Example #1:" }, { "code": "// Scala program of filter()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3) // Applying filter method val result = m1.filter(x => x._1 == \"geeks\" && x._2 == 5) // Displays output println(result) }}", "e": 697, "s": 316, "text": null }, { "code": null, "e": 714, "s": 697, "text": "Map(geeks -> 5)\n" }, { "code": null, "e": 726, "s": 714, "text": "Example #2:" }, { "code": "// Scala program of filter()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3) // Applying filter method val result = m1.filter(x => x._1 == \"for\" && x._2 == 5) // Displays output println(result) }}", "e": 1105, "s": 726, "text": null }, { "code": null, "e": 1112, "s": 1105, "text": "Map()\n" }, { "code": null, "e": 1197, "s": 1112, "text": "Here, an empty map is returned as none of the elements satisfy the stated predicate." }, { "code": null, "e": 1203, "s": 1197, "text": "Scala" }, { "code": null, "e": 1213, "s": 1203, "text": "Scala-Map" }, { "code": null, "e": 1226, "s": 1213, "text": "Scala-Method" }, { "code": null, "e": 1232, "s": 1226, "text": "Scala" }, { "code": null, "e": 1330, "s": 1232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1356, "s": 1330, "text": "Class and Object in Scala" }, { "code": null, "e": 1368, "s": 1356, "text": "Scala Lists" }, { "code": null, "e": 1387, "s": 1368, "text": "Scala Constructors" }, { "code": null, "e": 1406, "s": 1387, "text": "Operators in Scala" }, { "code": null, "e": 1421, "s": 1406, "text": "Scala | Arrays" }, { "code": null, "e": 1455, "s": 1421, "text": "How to Install Scala with VSCode?" }, { "code": null, "e": 1476, "s": 1455, "text": "Inheritance in Scala" }, { "code": null, "e": 1497, "s": 1476, "text": "Enumeration in Scala" }, { "code": null, "e": 1512, "s": 1497, "text": "Scala | Option" } ]
Flutter – Expanded Widget
23 Oct, 2020 Expanded widget in flutter comes in handy when we want a child widget or children widgets to take all the available space along the main-axis (for Row the main axis is horizontal & vertical for Column). Expanded widget can be taken as the child of Row, Column, and Flex. And in case if we don’t want to give equal spaces to our children widgets we can distribute the available space as our will using flex factor. Expanded widget is similar to the Flexible widget in flutter, with its fit property set to FlexFit.tight as default. Expanded widget is basically a shorthand of Flexible widget. But if you are planning to build responsive apps or web apps, then you should definitely switch to Flexible to get more fit options. const Expanded( {Key? key, int flex: 1, required Widget child} ) child: This property sets the widget tree to be placed inside the Expanded widget. Expanded widget can be taken as the child of Row, Column, and Flex. debugTypicalAncestorWidgetClass: This property takes Type as a parameter to set the ParentData for error messages. fit: This property controls how the child widget fills the available space. There are two options given by flutter, the first is FlexFit.tight which sets the child to fill the space available to it and the second is FlexFit.loose which allows the child widget to be as large as the available space. flex: If we decide to distribute the available space unevenly among the children widgets then we use the flex factor to do the same. Example 1: In this example, Expanded widget used inside a Column, and below it is the app in which Expanded widget is not used, to show the difference in UI. Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeksforgeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, )), body: Center( child: Column( children: <Widget>[ Container( child: Center( child: Text( 'First widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.blue, height: 100, width: 200, ), Expanded( child: Container( child: Center( child: Text( 'Second widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.amber, width: 200, ), ), Container( child: Center( child: Text( 'Third widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.orange, height: 100, width: 200, ), ], )), ), debugShowCheckedModeBanner: false, ));} Output: Explanation: In this app first we have created a simple app bar using the AppBar widget with a leading menu IconButton. The background color of the app bar is set to greenAccent[400] and the title is a Text widget holding ‘Geeksforgeeks‘ as the text. The parent widget in the body of the app is Center with its three children widget being Container. Each of the Containers has Text as their child specifying their names. First and third containers have been assigned a height of 200 and a width of 100 with the background color being blue and pink respectively. The Second Container is a child widget to Expanded, which gives it the ability to take all the available space between the first and the second Container widgets. Similar to the first and third Containers this also has a width of 100. The background color for this is teal. And one thing to notice is we haven’t specified height for this container as it will take all the space available to it, and even if we specify a height to it, that will be overwritten by the Expanded widget. Output: Below is the code snippet of the second Container. ... Container( child: Center( child: Text( 'Second widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.amber, width: 200, height: 100, ), ... This is how UI will look if we do not use the Expanded widget for the second Container in the Column. Note that we need to specify height in this case. Example 2: In this example, the Expanded widget is used as a child to Row. And next to it is the app without Expanded widget, to show the difference in the UI. Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeksforgeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, )), body: Center( child: Row( children: <Widget>[ Container( child: Center( child: Text( 'First widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.blue, height: 200, width: 100, ), Expanded( child: Container( child: Center( child: Text( 'Second widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.amber, height: 200, ), ), Container( child: Center( child: Text( 'Third widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.pink, height: 200, width: 100, ), ], )), ), debugShowCheckedModeBanner: false, ));} Output: Explanation: This app is also similar to the app in the first example except for the part the parent widget in the app body is Row instead of Column, with each Container having a height of 100. The width assigned to the first and third Containers is 200. The second Container in this app is a child to Expanded widget, which gives it the ability to take all the space between the first and the third Containers. Again we have not set any width to the second container as it won’t count. Output: This is the code snippet of the second container. ... Container( child: Center( child: Text( 'Second widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.amber, width: 100, height: 200, ), ... This is how the user interface chance if we remove the Expanded widget from being the parent of the second Container. Here also we have explicitly specified the width of the second Container. android Flutter Flutter-widgets Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Oct, 2020" }, { "code": null, "e": 778, "s": 52, "text": "Expanded widget in flutter comes in handy when we want a child widget or children widgets to take all the available space along the main-axis (for Row the main axis is horizontal & vertical for Column). Expanded widget can be taken as the child of Row, Column, and Flex. And in case if we don’t want to give equal spaces to our children widgets we can distribute the available space as our will using flex factor. Expanded widget is similar to the Flexible widget in flutter, with its fit property set to FlexFit.tight as default. Expanded widget is basically a shorthand of Flexible widget. But if you are planning to build responsive apps or web apps, then you should definitely switch to Flexible to get more fit options." }, { "code": null, "e": 845, "s": 778, "text": "const Expanded(\n{Key? key,\nint flex: 1,\nrequired Widget child}\n)\n\n" }, { "code": null, "e": 996, "s": 845, "text": "child: This property sets the widget tree to be placed inside the Expanded widget. Expanded widget can be taken as the child of Row, Column, and Flex." }, { "code": null, "e": 1111, "s": 996, "text": "debugTypicalAncestorWidgetClass: This property takes Type as a parameter to set the ParentData for error messages." }, { "code": null, "e": 1410, "s": 1111, "text": "fit: This property controls how the child widget fills the available space. There are two options given by flutter, the first is FlexFit.tight which sets the child to fill the space available to it and the second is FlexFit.loose which allows the child widget to be as large as the available space." }, { "code": null, "e": 1543, "s": 1410, "text": "flex: If we decide to distribute the available space unevenly among the children widgets then we use the flex factor to do the same." }, { "code": null, "e": 1701, "s": 1543, "text": "Example 1: In this example, Expanded widget used inside a Column, and below it is the app in which Expanded widget is not used, to show the difference in UI." }, { "code": null, "e": 1706, "s": 1701, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeksforgeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, )), body: Center( child: Column( children: <Widget>[ Container( child: Center( child: Text( 'First widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.blue, height: 100, width: 200, ), Expanded( child: Container( child: Center( child: Text( 'Second widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.amber, width: 200, ), ), Container( child: Center( child: Text( 'Third widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.orange, height: 100, width: 200, ), ], )), ), debugShowCheckedModeBanner: false, ));}", "e": 3164, "s": 1706, "text": null }, { "code": null, "e": 3172, "s": 3164, "text": "Output:" }, { "code": null, "e": 4217, "s": 3172, "text": "Explanation: In this app first we have created a simple app bar using the AppBar widget with a leading menu IconButton. The background color of the app bar is set to greenAccent[400] and the title is a Text widget holding ‘Geeksforgeeks‘ as the text. The parent widget in the body of the app is Center with its three children widget being Container. Each of the Containers has Text as their child specifying their names. First and third containers have been assigned a height of 200 and a width of 100 with the background color being blue and pink respectively. The Second Container is a child widget to Expanded, which gives it the ability to take all the available space between the first and the second Container widgets. Similar to the first and third Containers this also has a width of 100. The background color for this is teal. And one thing to notice is we haven’t specified height for this container as it will take all the space available to it, and even if we specify a height to it, that will be overwritten by the Expanded widget." }, { "code": null, "e": 4225, "s": 4217, "text": "Output:" }, { "code": null, "e": 4276, "s": 4225, "text": "Below is the code snippet of the second Container." }, { "code": null, "e": 4630, "s": 4276, "text": "...\n Container(\n child: Center(\n child: Text(\n 'Second widget',\n style: TextStyle(\n color: Colors.white,\n ),\n ),\n ),\n color: Colors.amber,\n width: 200,\n height: 100,\n ),\n...\n\n" }, { "code": null, "e": 4782, "s": 4630, "text": "This is how UI will look if we do not use the Expanded widget for the second Container in the Column. Note that we need to specify height in this case." }, { "code": null, "e": 4942, "s": 4782, "text": "Example 2: In this example, the Expanded widget is used as a child to Row. And next to it is the app without Expanded widget, to show the difference in the UI." }, { "code": null, "e": 4947, "s": 4942, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeksforgeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, )), body: Center( child: Row( children: <Widget>[ Container( child: Center( child: Text( 'First widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.blue, height: 200, width: 100, ), Expanded( child: Container( child: Center( child: Text( 'Second widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.amber, height: 200, ), ), Container( child: Center( child: Text( 'Third widget', style: TextStyle( color: Colors.white, ), ), ), color: Colors.pink, height: 200, width: 100, ), ], )), ), debugShowCheckedModeBanner: false, ));}", "e": 6401, "s": 4947, "text": null }, { "code": null, "e": 6409, "s": 6401, "text": "Output:" }, { "code": null, "e": 6896, "s": 6409, "text": "Explanation: This app is also similar to the app in the first example except for the part the parent widget in the app body is Row instead of Column, with each Container having a height of 100. The width assigned to the first and third Containers is 200. The second Container in this app is a child to Expanded widget, which gives it the ability to take all the space between the first and the third Containers. Again we have not set any width to the second container as it won’t count." }, { "code": null, "e": 6904, "s": 6896, "text": "Output:" }, { "code": null, "e": 6954, "s": 6904, "text": "This is the code snippet of the second container." }, { "code": null, "e": 7308, "s": 6954, "text": "...\n Container(\n child: Center(\n child: Text(\n 'Second widget',\n style: TextStyle(\n color: Colors.white,\n ),\n ),\n ),\n color: Colors.amber,\n width: 100,\n height: 200,\n ),\n...\n\n" }, { "code": null, "e": 7500, "s": 7308, "text": "This is how the user interface chance if we remove the Expanded widget from being the parent of the second Container. Here also we have explicitly specified the width of the second Container." }, { "code": null, "e": 7508, "s": 7500, "text": "android" }, { "code": null, "e": 7516, "s": 7508, "text": "Flutter" }, { "code": null, "e": 7532, "s": 7516, "text": "Flutter-widgets" }, { "code": null, "e": 7540, "s": 7532, "text": "Android" }, { "code": null, "e": 7545, "s": 7540, "text": "Dart" }, { "code": null, "e": 7553, "s": 7545, "text": "Flutter" }, { "code": null, "e": 7561, "s": 7553, "text": "Android" } ]
ios eof() function in C++ with Examples
02 Sep, 2019 The eof() method of ios class in C++ is used to check if the stream is has raised any EOF (End Of File) error. It means that this function will check if this stream has its eofbit set. Syntax: bool eof() const; Parameters: This method does not accept any parameter. Return Value: This method returns true if the stream has eofbit set, else false. Example 1: // C++ code to demonstrate// the working of eof() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; // Using eof() function bool isEOF = ss.eof(); // print result cout << "is stream eof: " << isEOF << endl; return 0;} is stream eof: 0 Example 2: // C++ code to demonstrate// the working of eof() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; ss.clear(ss.eofbit); // Using eof() function bool isEOF = ss.eof(); // print result cout << "is stream eof: " << isEOF << endl; return 0;} is stream eof: 1 Reference: hhttp://www.cplusplus.com/reference/ios/ios/eof/ CPP-Functions cpp-ios C++ CPP 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, 2019" }, { "code": null, "e": 213, "s": 28, "text": "The eof() method of ios class in C++ is used to check if the stream is has raised any EOF (End Of File) error. It means that this function will check if this stream has its eofbit set." }, { "code": null, "e": 221, "s": 213, "text": "Syntax:" }, { "code": null, "e": 240, "s": 221, "text": "bool eof() const;\n" }, { "code": null, "e": 295, "s": 240, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 376, "s": 295, "text": "Return Value: This method returns true if the stream has eofbit set, else false." }, { "code": null, "e": 387, "s": 376, "text": "Example 1:" }, { "code": "// C++ code to demonstrate// the working of eof() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; // Using eof() function bool isEOF = ss.eof(); // print result cout << \"is stream eof: \" << isEOF << endl; return 0;}", "e": 687, "s": 387, "text": null }, { "code": null, "e": 705, "s": 687, "text": "is stream eof: 0\n" }, { "code": null, "e": 716, "s": 705, "text": "Example 2:" }, { "code": "// C++ code to demonstrate// the working of eof() function #include <bits/stdc++.h>using namespace std; int main(){ // Stream stringstream ss; ss.clear(ss.eofbit); // Using eof() function bool isEOF = ss.eof(); // print result cout << \"is stream eof: \" << isEOF << endl; return 0;}", "e": 1040, "s": 716, "text": null }, { "code": null, "e": 1058, "s": 1040, "text": "is stream eof: 1\n" }, { "code": null, "e": 1118, "s": 1058, "text": "Reference: hhttp://www.cplusplus.com/reference/ios/ios/eof/" }, { "code": null, "e": 1132, "s": 1118, "text": "CPP-Functions" }, { "code": null, "e": 1140, "s": 1132, "text": "cpp-ios" }, { "code": null, "e": 1144, "s": 1140, "text": "C++" }, { "code": null, "e": 1148, "s": 1144, "text": "CPP" } ]
Range Keyword in Golang
28 Jun, 2021 In Golang Range keyword is used in different kinds of data structures in order to iterates over elements. The range keyword is mainly used in for loops in order to iterate over all the elements of a map, slice, channel, or an array. When it iterates over the elements of an array and slices then it returns the index of the element in an integer form. And when it iterates over the elements of a map then it returns the key of the subsequent key-value pair. Moreover, range can either returns one value or two values. Lets see what range returns while iterating over different kind of collections in Golang. Array or slice: The first value returned in case of array or slice is index and the second value is element. String: The first value returned in string is index and the second value is rune int. Map: The first value returned in map is key and the second value is the value of the key-value pair in map. Channel: The first value returned in channel is element and the second value is none. Now, let’s see some examples to illustrate the usage of range keyword in Golang. Example 1: // Golang Program to illustrate the usage// of range keyword over items of an// array in Golang package main import "fmt" // main functionfunc main() { // Array of odd numbers odd := [7]int{1, 3, 5, 7, 9, 11, 13} // using range keyword with for loop to // iterate over the array elements for i, item := range odd { // Prints index and the elements fmt.Printf("odd[%d] = %d \n", i, item) }} Output: odd[0] = 1 odd[1] = 3 odd[2] = 5 odd[3] = 7 odd[4] = 9 odd[5] = 11 odd[6] = 13 Here, all the elements are printed with their respective index. Example 2: // Golang Program to illustrate the usage of// range keyword over string in Golang package main import "fmt" // Constructing main functionfunc main() { // taking a string var string = "GeeksforGeeks" // using range keyword with for loop to // iterate over the string for i, item := range string { // Prints index of all the // characters in the string fmt.Printf("string[%d] = %d \n", i, item) }} Output: string[0] = 71 string[1] = 101 string[2] = 101 string[3] = 107 string[4] = 115 string[5] = 102 string[6] = 111 string[7] = 114 string[8] = 71 string[9] = 101 string[10] = 101 string[11] = 107 string[12] = 115 Here, the items printed is the rune, that is int32 ASCII value of the stated characters that forms string. Example 3: // Golang Program to illustrate the usage of// range keyword over maps in Golang package main import "fmt" // main functionfunc main() { // Creating map of student ranks student_rank_map := map[string]int{"Nidhi": 3, "Nisha": 2, "Rohit": 1} // Printing map using keys only for student := range student_rank_map { fmt.Println("Rank of", student, "is: ", student_rank_map[student]) } // Printing maps using key-value pair for student, rank := range student_rank_map { fmt.Println("Rank of", student, "is: ", rank) }} Output: Rank of Nidhi is: 3 Rank of Nisha is: 2 Rank of Rohit is: 1 Rank of Nidhi is: 3 Rank of Nisha is: 2 Rank of Rohit is: 1 So, here at first the output is printed only using key then again output is printed using both key and value. anikakapoor Go-Keywords Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 636, "s": 28, "text": "In Golang Range keyword is used in different kinds of data structures in order to iterates over elements. The range keyword is mainly used in for loops in order to iterate over all the elements of a map, slice, channel, or an array. When it iterates over the elements of an array and slices then it returns the index of the element in an integer form. And when it iterates over the elements of a map then it returns the key of the subsequent key-value pair. Moreover, range can either returns one value or two values. Lets see what range returns while iterating over different kind of collections in Golang." }, { "code": null, "e": 745, "s": 636, "text": "Array or slice: The first value returned in case of array or slice is index and the second value is element." }, { "code": null, "e": 831, "s": 745, "text": "String: The first value returned in string is index and the second value is rune int." }, { "code": null, "e": 939, "s": 831, "text": "Map: The first value returned in map is key and the second value is the value of the key-value pair in map." }, { "code": null, "e": 1025, "s": 939, "text": "Channel: The first value returned in channel is element and the second value is none." }, { "code": null, "e": 1106, "s": 1025, "text": "Now, let’s see some examples to illustrate the usage of range keyword in Golang." }, { "code": null, "e": 1117, "s": 1106, "text": "Example 1:" }, { "code": "// Golang Program to illustrate the usage// of range keyword over items of an// array in Golang package main import \"fmt\" // main functionfunc main() { // Array of odd numbers odd := [7]int{1, 3, 5, 7, 9, 11, 13} // using range keyword with for loop to // iterate over the array elements for i, item := range odd { // Prints index and the elements fmt.Printf(\"odd[%d] = %d \\n\", i, item) }}", "e": 1542, "s": 1117, "text": null }, { "code": null, "e": 1550, "s": 1542, "text": "Output:" }, { "code": null, "e": 1630, "s": 1550, "text": "odd[0] = 1\nodd[1] = 3\nodd[2] = 5\nodd[3] = 7\nodd[4] = 9\nodd[5] = 11\nodd[6] = 13\n" }, { "code": null, "e": 1694, "s": 1630, "text": "Here, all the elements are printed with their respective index." }, { "code": null, "e": 1705, "s": 1694, "text": "Example 2:" }, { "code": "// Golang Program to illustrate the usage of// range keyword over string in Golang package main import \"fmt\" // Constructing main functionfunc main() { // taking a string var string = \"GeeksforGeeks\" // using range keyword with for loop to // iterate over the string for i, item := range string { // Prints index of all the // characters in the string fmt.Printf(\"string[%d] = %d \\n\", i, item) }}", "e": 2144, "s": 1705, "text": null }, { "code": null, "e": 2152, "s": 2144, "text": "Output:" }, { "code": null, "e": 2374, "s": 2152, "text": "string[0] = 71 \nstring[1] = 101 \nstring[2] = 101 \nstring[3] = 107 \nstring[4] = 115 \nstring[5] = 102 \nstring[6] = 111 \nstring[7] = 114 \nstring[8] = 71 \nstring[9] = 101 \nstring[10] = 101 \nstring[11] = 107 \nstring[12] = 115\n" }, { "code": null, "e": 2481, "s": 2374, "text": "Here, the items printed is the rune, that is int32 ASCII value of the stated characters that forms string." }, { "code": null, "e": 2492, "s": 2481, "text": "Example 3:" }, { "code": "// Golang Program to illustrate the usage of// range keyword over maps in Golang package main import \"fmt\" // main functionfunc main() { // Creating map of student ranks student_rank_map := map[string]int{\"Nidhi\": 3, \"Nisha\": 2, \"Rohit\": 1} // Printing map using keys only for student := range student_rank_map { fmt.Println(\"Rank of\", student, \"is: \", student_rank_map[student]) } // Printing maps using key-value pair for student, rank := range student_rank_map { fmt.Println(\"Rank of\", student, \"is: \", rank) }}", "e": 3094, "s": 2492, "text": null }, { "code": null, "e": 3102, "s": 3094, "text": "Output:" }, { "code": null, "e": 3229, "s": 3102, "text": "Rank of Nidhi is: 3\nRank of Nisha is: 2\nRank of Rohit is: 1\nRank of Nidhi is: 3\nRank of Nisha is: 2\nRank of Rohit is: 1\n" }, { "code": null, "e": 3339, "s": 3229, "text": "So, here at first the output is printed only using key then again output is printed using both key and value." }, { "code": null, "e": 3351, "s": 3339, "text": "anikakapoor" }, { "code": null, "e": 3363, "s": 3351, "text": "Go-Keywords" }, { "code": null, "e": 3370, "s": 3363, "text": "Picked" }, { "code": null, "e": 3382, "s": 3370, "text": "Go Language" } ]
C# | Add an object to the end of Collection<T>
01 Feb, 2019 Collection<T>.Add(T) method is used to add an object to the end of the Collection<T>. Syntax : public void Add (T item); Here, item is the object to be added to the end of the Collection<T>. The value can be null for reference types. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to add an object to// the end of the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // Displaying the number of elements in Collection Console.WriteLine("The number of elements in myColl are : " + myColl.Count); // Displaying the elements in Collection Console.WriteLine("The elements in myColl are : "); foreach(string str in myColl) { Console.WriteLine(str); } }} Output: The number of elements in myColl are : 5 The elements in myColl are : A B C D E Example 2: // C# code to add an object to// the end of the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the number of elements in Collection Console.WriteLine("The number of elements in myColl are : " + myColl.Count); // Displaying the elements in Collection Console.WriteLine("The elements in myColl are : "); foreach(int i in myColl) { Console.WriteLine(i); } }} Output: The number of elements in myColl are : 4 The elements in myColl are : 2 3 4 5 Note: Collection<T> accepts null as a valid value for reference types and allows duplicate elements. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.add?view=netframework-4.7.2 CSharp-Collection-Class CSharp-Collections.ObjectModel-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class C# | .NET Framework (Basic Architecture and Component Stack) HashSet in C# with Examples Lambda Expressions in C# Switch Statement in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 114, "s": 28, "text": "Collection<T>.Add(T) method is used to add an object to the end of the Collection<T>." }, { "code": null, "e": 123, "s": 114, "text": "Syntax :" }, { "code": null, "e": 150, "s": 123, "text": "public void Add (T item);\n" }, { "code": null, "e": 263, "s": 150, "text": "Here, item is the object to be added to the end of the Collection<T>. The value can be null for reference types." }, { "code": null, "e": 343, "s": 263, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 354, "s": 343, "text": "Example 1:" }, { "code": "// C# code to add an object to// the end of the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // Displaying the number of elements in Collection Console.WriteLine(\"The number of elements in myColl are : \" + myColl.Count); // Displaying the elements in Collection Console.WriteLine(\"The elements in myColl are : \"); foreach(string str in myColl) { Console.WriteLine(str); } }}", "e": 1191, "s": 354, "text": null }, { "code": null, "e": 1199, "s": 1191, "text": "Output:" }, { "code": null, "e": 1281, "s": 1199, "text": "The number of elements in myColl are : 5\nThe elements in myColl are : \nA\nB\nC\nD\nE\n" }, { "code": null, "e": 1292, "s": 1281, "text": "Example 2:" }, { "code": "// C# code to add an object to// the end of the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the number of elements in Collection Console.WriteLine(\"The number of elements in myColl are : \" + myColl.Count); // Displaying the elements in Collection Console.WriteLine(\"The elements in myColl are : \"); foreach(int i in myColl) { Console.WriteLine(i); } }}", "e": 2080, "s": 1292, "text": null }, { "code": null, "e": 2088, "s": 2080, "text": "Output:" }, { "code": null, "e": 2168, "s": 2088, "text": "The number of elements in myColl are : 4\nThe elements in myColl are : \n2\n3\n4\n5\n" }, { "code": null, "e": 2174, "s": 2168, "text": "Note:" }, { "code": null, "e": 2269, "s": 2174, "text": "Collection<T> accepts null as a valid value for reference types and allows duplicate elements." }, { "code": null, "e": 2303, "s": 2269, "text": "This method is an O(1) operation." }, { "code": null, "e": 2314, "s": 2303, "text": "Reference:" }, { "code": null, "e": 2430, "s": 2314, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.add?view=netframework-4.7.2" }, { "code": null, "e": 2454, "s": 2430, "text": "CSharp-Collection-Class" }, { "code": null, "e": 2495, "s": 2454, "text": "CSharp-Collections.ObjectModel-Namespace" }, { "code": null, "e": 2509, "s": 2495, "text": "CSharp-method" }, { "code": null, "e": 2512, "s": 2509, "text": "C#" }, { "code": null, "e": 2610, "s": 2512, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2653, "s": 2610, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2702, "s": 2653, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2725, "s": 2702, "text": "Extension Method in C#" }, { "code": null, "e": 2741, "s": 2725, "text": "C# | List Class" }, { "code": null, "e": 2802, "s": 2741, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2830, "s": 2802, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2855, "s": 2830, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2878, "s": 2855, "text": "Switch Statement in C#" }, { "code": null, "e": 2900, "s": 2878, "text": "Partial Classes in C#" } ]
Flutter – RichText Widget
06 Jun, 2022 The RichText widget is used to display text that uses various different styles. The displayed text is described using a tree of TextSpan objects, each of which has its own associated style that is used for that subtree. Depending on the layout constraints the text might break across multiple lines or might all be displayed on the same line. Syntax: RichText( {Key key, @required InlineSpan text, TextAlign textAlign: TextAlign.start, TextDirection textDirection, bool softWrap: true, TextOverflow overflow: TextOverflow.clip, double textScaleFactor: 1.0, int maxLines, Locale locale, StrutStyle strutStyle, TextWidthBasis textWidthBasis: TextWidthBasis.parent, TextHeightBehavior textHeightBehavior, children: The widgets below this widget in the tree. hashCode: The hash code for this object. key: Controls how one widget replaces another widget in the tree. runtimeType: A representation of the runtime type of the object. text: The text to display in this widget. textAlign: How the text should be aligned horizontally. local: This property takes in Locale class as the object. It controls the font used for the text depending on the language used. maxLines: The maxLines property takes in an int value as the object. It controls the maximum number of lines that can be there for the text to expand and wrap. overflow: TextOverflow enum is the object given to its class it controls the text in case of overflow. softWrap: This property takes in a boolean value as the object. If it is set to false the gulphs in the text become wider. textDirection: This property takes in TextDirection class as the object to decide the direction of the text. It can be either from left-to-right or right-to-left. textHightBehaviour: TextHeightBehavior class is the object given to this property. It controls how the text will be highlighted. textScaleFactor: This property is taken in a double value as the object to determine the relative size of the font. textWidthBasis: TextWidthBasis enum is the object of this property. It controls the width of a single line of text being measured. Example: Dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { const MyHomePAGE({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: RichText( // Controls visual overflow overflow: TextOverflow.clip, // Controls how the text should be aligned horizontally textAlign: TextAlign.end, // Control the text direction textDirection: TextDirection.rtl, // Whether the text should break at soft line breaks softWrap: true, // Maximum number of lines for the text to span maxLines: 1, // The number of font pixels for each logical pixel textScaleFactor: 1, text: TextSpan( text: 'Hello ', style: DefaultTextStyle.of(context).style, children: const <TextSpan>[ TextSpan( text: 'Geeks', style: TextStyle(fontWeight: FontWeight.bold)), ], ), )), backgroundColor: Colors.lightBlue[50], ); }} class MyClip extends CustomClipper<Rect> { @override Rect getClip(Size size) { return const Rect.fromLTWH(0, 0, 100, 100); } @override bool shouldReclip(oldClipper) { return false; }} Output: Output explanation: Create a stateless widget as the main widget of the app.Define a class representing the home screen using a stateful widget.Define the appbar inside a scaffold widget.Place the Richtext widget in the center. Create a stateless widget as the main widget of the app. Define a class representing the home screen using a stateful widget. Define the appbar inside a scaffold widget. Place the Richtext widget in the center. ankit_kumar_ android Flutter Flutter-widgets Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jun, 2022" }, { "code": null, "e": 397, "s": 54, "text": "The RichText widget is used to display text that uses various different styles. The displayed text is described using a tree of TextSpan objects, each of which has its own associated style that is used for that subtree. Depending on the layout constraints the text might break across multiple lines or might all be displayed on the same line." }, { "code": null, "e": 405, "s": 397, "text": "Syntax:" }, { "code": null, "e": 766, "s": 405, "text": "RichText(\n{Key key,\n@required InlineSpan text,\nTextAlign textAlign: TextAlign.start, \nTextDirection textDirection, \nbool softWrap: true, \nTextOverflow overflow: \nTextOverflow.clip, \ndouble textScaleFactor: 1.0, \nint maxLines, \nLocale locale, \nStrutStyle strutStyle, \nTextWidthBasis textWidthBasis: TextWidthBasis.parent, \nTextHeightBehavior textHeightBehavior," }, { "code": null, "e": 819, "s": 766, "text": "children: The widgets below this widget in the tree." }, { "code": null, "e": 860, "s": 819, "text": "hashCode: The hash code for this object." }, { "code": null, "e": 926, "s": 860, "text": "key: Controls how one widget replaces another widget in the tree." }, { "code": null, "e": 991, "s": 926, "text": "runtimeType: A representation of the runtime type of the object." }, { "code": null, "e": 1033, "s": 991, "text": "text: The text to display in this widget." }, { "code": null, "e": 1089, "s": 1033, "text": "textAlign: How the text should be aligned horizontally." }, { "code": null, "e": 1218, "s": 1089, "text": "local: This property takes in Locale class as the object. It controls the font used for the text depending on the language used." }, { "code": null, "e": 1378, "s": 1218, "text": "maxLines: The maxLines property takes in an int value as the object. It controls the maximum number of lines that can be there for the text to expand and wrap." }, { "code": null, "e": 1481, "s": 1378, "text": "overflow: TextOverflow enum is the object given to its class it controls the text in case of overflow." }, { "code": null, "e": 1604, "s": 1481, "text": "softWrap: This property takes in a boolean value as the object. If it is set to false the gulphs in the text become wider." }, { "code": null, "e": 1767, "s": 1604, "text": "textDirection: This property takes in TextDirection class as the object to decide the direction of the text. It can be either from left-to-right or right-to-left." }, { "code": null, "e": 1896, "s": 1767, "text": "textHightBehaviour: TextHeightBehavior class is the object given to this property. It controls how the text will be highlighted." }, { "code": null, "e": 2012, "s": 1896, "text": "textScaleFactor: This property is taken in a double value as the object to determine the relative size of the font." }, { "code": null, "e": 2143, "s": 2012, "text": "textWidthBasis: TextWidthBasis enum is the object of this property. It controls the width of a single line of text being measured." }, { "code": null, "e": 2152, "s": 2143, "text": "Example:" }, { "code": null, "e": 2157, "s": 2152, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { const MyHomePAGE({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: RichText( // Controls visual overflow overflow: TextOverflow.clip, // Controls how the text should be aligned horizontally textAlign: TextAlign.end, // Control the text direction textDirection: TextDirection.rtl, // Whether the text should break at soft line breaks softWrap: true, // Maximum number of lines for the text to span maxLines: 1, // The number of font pixels for each logical pixel textScaleFactor: 1, text: TextSpan( text: 'Hello ', style: DefaultTextStyle.of(context).style, children: const <TextSpan>[ TextSpan( text: 'Geeks', style: TextStyle(fontWeight: FontWeight.bold)), ], ), )), backgroundColor: Colors.lightBlue[50], ); }} class MyClip extends CustomClipper<Rect> { @override Rect getClip(Size size) { return const Rect.fromLTWH(0, 0, 100, 100); } @override bool shouldReclip(oldClipper) { return false; }}", "e": 4108, "s": 2157, "text": null }, { "code": null, "e": 4116, "s": 4108, "text": "Output:" }, { "code": null, "e": 4136, "s": 4116, "text": "Output explanation:" }, { "code": null, "e": 4344, "s": 4136, "text": "Create a stateless widget as the main widget of the app.Define a class representing the home screen using a stateful widget.Define the appbar inside a scaffold widget.Place the Richtext widget in the center." }, { "code": null, "e": 4401, "s": 4344, "text": "Create a stateless widget as the main widget of the app." }, { "code": null, "e": 4470, "s": 4401, "text": "Define a class representing the home screen using a stateful widget." }, { "code": null, "e": 4514, "s": 4470, "text": "Define the appbar inside a scaffold widget." }, { "code": null, "e": 4555, "s": 4514, "text": "Place the Richtext widget in the center." }, { "code": null, "e": 4568, "s": 4555, "text": "ankit_kumar_" }, { "code": null, "e": 4576, "s": 4568, "text": "android" }, { "code": null, "e": 4584, "s": 4576, "text": "Flutter" }, { "code": null, "e": 4600, "s": 4584, "text": "Flutter-widgets" }, { "code": null, "e": 4605, "s": 4600, "text": "Dart" } ]
Software Testing | Functional Testing
08 May, 2019 Functional Testing is a type of Software Testing in which the system is tested against the functional requirements and specifications. Functional testing ensures that the requirements or specifications are properly satisfied by the application. This type of testing is particularly concerned with the result of processing. It focuses on simulation of actual system usage but does not develop any system structure assumptions. It is basically defined as a type of testing which verifies that each function of the software application works in conformance with the requirement and specification. This testing is not concerned about the source code of the application. Each functionality of the software application is tested by providing appropriate test input, expecting the output and comparing the actual output with the expected output. This testing focuses on checking of user interface, APIs, database, security, client or server application and functionality of the Application Under Test. Functional testing can be manual or automated. Functional Testing Process:Functional testing involves the following steps: Identify function that is to be performed.Create input data based on the specifications of function.Determine the output based on the specifications of function.Execute the test case.Compare the actual and expected output. Identify function that is to be performed. Create input data based on the specifications of function. Determine the output based on the specifications of function. Execute the test case. Compare the actual and expected output. Major Functional Testing Techniques: Unit Testing Integration Testing Smoke Testing User Acceptance Testing Interface Testing Usability Testing System Testing Regression Testing Functional Testing Tools: 1. Selenium 2. QTP 3. JUnit 4. SoapUI 5. Watir Advantages of Functional Testing: It ensures to deliver a bug-free product. It ensures to deliver a high-quality product. No assumptions about the structure of the system. This testing is focused on the specifications as per the customer usage. Disadvantages of Functional Testing: There are high chances of performing redundant testing. Logical errors can be missed out in the product. If the requirement is not complete then performing this testing becomes difficult. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 May, 2019" }, { "code": null, "e": 479, "s": 53, "text": "Functional Testing is a type of Software Testing in which the system is tested against the functional requirements and specifications. Functional testing ensures that the requirements or specifications are properly satisfied by the application. This type of testing is particularly concerned with the result of processing. It focuses on simulation of actual system usage but does not develop any system structure assumptions." }, { "code": null, "e": 1048, "s": 479, "text": "It is basically defined as a type of testing which verifies that each function of the software application works in conformance with the requirement and specification. This testing is not concerned about the source code of the application. Each functionality of the software application is tested by providing appropriate test input, expecting the output and comparing the actual output with the expected output. This testing focuses on checking of user interface, APIs, database, security, client or server application and functionality of the Application Under Test." }, { "code": null, "e": 1095, "s": 1048, "text": "Functional testing can be manual or automated." }, { "code": null, "e": 1171, "s": 1095, "text": "Functional Testing Process:Functional testing involves the following steps:" }, { "code": null, "e": 1394, "s": 1171, "text": "Identify function that is to be performed.Create input data based on the specifications of function.Determine the output based on the specifications of function.Execute the test case.Compare the actual and expected output." }, { "code": null, "e": 1437, "s": 1394, "text": "Identify function that is to be performed." }, { "code": null, "e": 1496, "s": 1437, "text": "Create input data based on the specifications of function." }, { "code": null, "e": 1558, "s": 1496, "text": "Determine the output based on the specifications of function." }, { "code": null, "e": 1581, "s": 1558, "text": "Execute the test case." }, { "code": null, "e": 1621, "s": 1581, "text": "Compare the actual and expected output." }, { "code": null, "e": 1658, "s": 1621, "text": "Major Functional Testing Techniques:" }, { "code": null, "e": 1671, "s": 1658, "text": "Unit Testing" }, { "code": null, "e": 1691, "s": 1671, "text": "Integration Testing" }, { "code": null, "e": 1705, "s": 1691, "text": "Smoke Testing" }, { "code": null, "e": 1729, "s": 1705, "text": "User Acceptance Testing" }, { "code": null, "e": 1747, "s": 1729, "text": "Interface Testing" }, { "code": null, "e": 1765, "s": 1747, "text": "Usability Testing" }, { "code": null, "e": 1780, "s": 1765, "text": "System Testing" }, { "code": null, "e": 1799, "s": 1780, "text": "Regression Testing" }, { "code": null, "e": 1825, "s": 1799, "text": "Functional Testing Tools:" }, { "code": null, "e": 1873, "s": 1825, "text": "1. Selenium\n2. QTP\n3. JUnit\n4. SoapUI\n5. Watir " }, { "code": null, "e": 1907, "s": 1873, "text": "Advantages of Functional Testing:" }, { "code": null, "e": 1949, "s": 1907, "text": "It ensures to deliver a bug-free product." }, { "code": null, "e": 1995, "s": 1949, "text": "It ensures to deliver a high-quality product." }, { "code": null, "e": 2045, "s": 1995, "text": "No assumptions about the structure of the system." }, { "code": null, "e": 2118, "s": 2045, "text": "This testing is focused on the specifications as per the customer usage." }, { "code": null, "e": 2155, "s": 2118, "text": "Disadvantages of Functional Testing:" }, { "code": null, "e": 2211, "s": 2155, "text": "There are high chances of performing redundant testing." }, { "code": null, "e": 2260, "s": 2211, "text": "Logical errors can be missed out in the product." }, { "code": null, "e": 2343, "s": 2260, "text": "If the requirement is not complete then performing this testing becomes difficult." }, { "code": null, "e": 2360, "s": 2343, "text": "Software Testing" }, { "code": null, "e": 2381, "s": 2360, "text": "Software Engineering" } ]
Groovy - toString()
The method is used to get a String object representing the value of the Number Object. If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned. If the method takes two arguments, then a String representation of the first argument in the radix specified by the second argument will be returned. String toString() static String toString(int i) i − An int for which string representation would be returned. toString() − This returns a String object representing the value of this Integer. toString() − This returns a String object representing the value of this Integer. toString(int i) − This returns a String object representing the specified integer. toString(int i) − This returns a String object representing the specified integer. Following is an example of the usage of this method − class Example { static void main(String[] args) { Integer x = 5; System.out.println(x.toString()); System.out.println(Integer.toString(12)); } } When we run the above program, we will get the following result − 5 12 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2238, "text": "The method is used to get a String object representing the value of the Number Object." }, { "code": null, "e": 2462, "s": 2325, "text": "If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned." }, { "code": null, "e": 2612, "s": 2462, "text": "If the method takes two arguments, then a String representation of the first argument in the radix specified by the second argument will be returned." }, { "code": null, "e": 2662, "s": 2612, "text": "String toString() \nstatic String toString(int i)\n" }, { "code": null, "e": 2724, "s": 2662, "text": "i − An int for which string representation would be returned." }, { "code": null, "e": 2806, "s": 2724, "text": "toString() − This returns a String object representing the value of this Integer." }, { "code": null, "e": 2888, "s": 2806, "text": "toString() − This returns a String object representing the value of this Integer." }, { "code": null, "e": 2971, "s": 2888, "text": "toString(int i) − This returns a String object representing the specified integer." }, { "code": null, "e": 3054, "s": 2971, "text": "toString(int i) − This returns a String object representing the specified integer." }, { "code": null, "e": 3108, "s": 3054, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 3285, "s": 3108, "text": "class Example { \n static void main(String[] args) { \n Integer x = 5;\n\t\t\n System.out.println(x.toString()); \n System.out.println(Integer.toString(12)); \n } \n}" }, { "code": null, "e": 3351, "s": 3285, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 3359, "s": 3351, "text": "5 \n12 \n" }, { "code": null, "e": 3392, "s": 3359, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 3410, "s": 3392, "text": " Krishna Sakinala" }, { "code": null, "e": 3445, "s": 3410, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3463, "s": 3445, "text": " Packt Publishing" }, { "code": null, "e": 3470, "s": 3463, "text": " Print" }, { "code": null, "e": 3481, "s": 3470, "text": " Add Notes" } ]
Erlang - Data Types
In any programming language, you need to use several variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory to store the value associated with that variable. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Erlang offers a wide variety of built-in data types. Following is a list of data types which are defined in Erlang − Number − In Erlang, there are 2 types of numeric literals which are integers and floats. Number − In Erlang, there are 2 types of numeric literals which are integers and floats. Atom − An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @. Atom − An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @. Boolean − Boolean data types in Erlang are the two reserved atoms: true and false. Boolean − Boolean data types in Erlang are the two reserved atoms: true and false. Bit String − A bit string is used to store an area of un-typed memory. Bit String − A bit string is used to store an area of un-typed memory. Tuple − A tuple is a compound data type with a fixed number of terms. Each Term in the tuple is called as an element. The number of elements is said to be the size of the tuple. Tuple − A tuple is a compound data type with a fixed number of terms. Each Term in the tuple is called as an element. The number of elements is said to be the size of the tuple. Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. The key and value parts of the pair are called elements. The number of association pairs is said to be the size of the map. Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. The key and value parts of the pair are called elements. The number of association pairs is said to be the size of the map. List − A list is a compound data type with a variable number of terms. Each term in the list is called an element. The number of elements is said to be the length of the list. List − A list is a compound data type with a variable number of terms. Each term in the list is called an element. The number of elements is said to be the length of the list. Note − You will be surprised to see that you cannot see the String type anywhere in the list above. That’s because there is no string data type exclusively defined in Erlang. But we will see how we can work with strings in a subsequent chapter. Following are the examples of how each data type can be used. Again each data type will be discussed in detail in the ensuing chapters. This is just to get you acquainted with a brief description of the above-mentioned data types. An example of how the number data type can be used is shown in the following program. This program shows the addition of 2 Integers. Example -module(helloworld). -export([start/0]). start() -> io:fwrite("~w",[1+1]). The output of the above program will be − Output 2 Atoms should begin with a lowercase letter and can contain lowercase and uppercase characters, digits, underscore (_) and the “at” sign (@). We can also enclose an atom in single quotes. An example of how the atom data type can be used is shown in the following program. In this program, we are creating an atom which is called atom1. Example -module(helloworld). -export([start/0]). start() -> io:fwrite(atom1). The output of the above program will be − Output atom1 An example of how the Boolean data type can be used is shown in the following program. This example does a comparison between 2 integers and prints the resultant Boolean to the console. Example -module(helloworld). -export([start/0]). start() -> io:fwrite(2 =< 3). The output of the above program will be − Output true An example of how the Bit String data type can be used is shown in the following program. This program defines a Bit String consisting of 2 bits. The binary_to_list is an inbuilt function defined in Erlang which can be used to convert a Bit String to a list. Example -module(helloworld). -export([start/0]). start() -> Bin1 = <<10,20>>, X = binary_to_list(Bin1), io:fwrite("~w",[X]). The output of the above program will be − Output [10,20] An example of how the Tuple data type can be used is shown in the following program. Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Erlang, which can be used to determine the size of the tuple. Example -module(helloworld). -export([start/0]). start() -> P = {john,24,{june,25}} , io:fwrite("~w",[tuple_size(P)]). The output of the above program will be − Output 3 An example of how the Map data type can be used is shown in the following program. Here we are defining a Map M1 which has 2 mappings. The map_size is an inbuilt function defined in Erlang, which can be used to determine the size of the map. Example -module(helloworld). -export([start/0]). start() -> M1 = #{name=>john,age=>25}, io:fwrite("~w",[map_size(M1)]). The output of the above program will be − Output 2 An example of how the List data type can be used is shown in the following program. Here we are defining a List L which has 3 items. The length is an inbuilt function defined in Erlang, which can be used to determine the size of the list. Example -module(helloworld). -export([start/0]). start() -> L = [10,20,30] , io:fwrite("~w",[length(L)]). The output of the above program will be − Output 3 Print Add Notes Bookmark this page
[ { "code": null, "e": 2602, "s": 2301, "text": "In any programming language, you need to use several variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory to store the value associated with that variable." }, { "code": null, "e": 2868, "s": 2602, "text": "You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory." }, { "code": null, "e": 2985, "s": 2868, "text": "Erlang offers a wide variety of built-in data types. Following is a list of data types which are defined in Erlang −" }, { "code": null, "e": 3074, "s": 2985, "text": "Number − In Erlang, there are 2 types of numeric literals which are integers and floats." }, { "code": null, "e": 3163, "s": 3074, "text": "Number − In Erlang, there are 2 types of numeric literals which are integers and floats." }, { "code": null, "e": 3394, "s": 3163, "text": "Atom − An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @." }, { "code": null, "e": 3625, "s": 3394, "text": "Atom − An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @." }, { "code": null, "e": 3708, "s": 3625, "text": "Boolean − Boolean data types in Erlang are the two reserved atoms: true and false." }, { "code": null, "e": 3791, "s": 3708, "text": "Boolean − Boolean data types in Erlang are the two reserved atoms: true and false." }, { "code": null, "e": 3862, "s": 3791, "text": "Bit String − A bit string is used to store an area of un-typed memory." }, { "code": null, "e": 3933, "s": 3862, "text": "Bit String − A bit string is used to store an area of un-typed memory." }, { "code": null, "e": 4111, "s": 3933, "text": "Tuple − A tuple is a compound data type with a fixed number of terms. Each Term in the tuple is called as an element. The number of elements is said to be the size of the tuple." }, { "code": null, "e": 4289, "s": 4111, "text": "Tuple − A tuple is a compound data type with a fixed number of terms. Each Term in the tuple is called as an element. The number of elements is said to be the size of the tuple." }, { "code": null, "e": 4568, "s": 4289, "text": "Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. The key and value parts of the pair are called elements. The number of association pairs is said to be the size of the map." }, { "code": null, "e": 4847, "s": 4568, "text": "Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. The key and value parts of the pair are called elements. The number of association pairs is said to be the size of the map." }, { "code": null, "e": 5023, "s": 4847, "text": "List − A list is a compound data type with a variable number of terms. Each term in the list is called an element. The number of elements is said to be the length of the list." }, { "code": null, "e": 5199, "s": 5023, "text": "List − A list is a compound data type with a variable number of terms. Each term in the list is called an element. The number of elements is said to be the length of the list." }, { "code": null, "e": 5444, "s": 5199, "text": "Note − You will be surprised to see that you cannot see the String type anywhere in the list above. That’s because there is no string data type exclusively defined in Erlang. But we will see how we can work with strings in a subsequent chapter." }, { "code": null, "e": 5675, "s": 5444, "text": "Following are the examples of how each data type can be used. Again each data type will be discussed in detail in the ensuing chapters. This is just to get you acquainted with a brief description of the above-mentioned data types." }, { "code": null, "e": 5808, "s": 5675, "text": "An example of how the number data type can be used is shown in the following program. This program shows the addition of 2 Integers." }, { "code": null, "e": 5816, "s": 5808, "text": "Example" }, { "code": null, "e": 5895, "s": 5816, "text": "-module(helloworld).\n-export([start/0]).\n\nstart() ->\n io:fwrite(\"~w\",[1+1])." }, { "code": null, "e": 5937, "s": 5895, "text": "The output of the above program will be −" }, { "code": null, "e": 5944, "s": 5937, "text": "Output" }, { "code": null, "e": 5947, "s": 5944, "text": "2\n" }, { "code": null, "e": 6134, "s": 5947, "text": "Atoms should begin with a lowercase letter and can contain lowercase and uppercase characters, digits, underscore (_) and the “at” sign (@). We can also enclose an atom in single quotes." }, { "code": null, "e": 6282, "s": 6134, "text": "An example of how the atom data type can be used is shown in the following program. In this program, we are creating an atom which is called atom1." }, { "code": null, "e": 6290, "s": 6282, "text": "Example" }, { "code": null, "e": 6364, "s": 6290, "text": "-module(helloworld).\n-export([start/0]).\n\nstart() ->\n io:fwrite(atom1)." }, { "code": null, "e": 6406, "s": 6364, "text": "The output of the above program will be −" }, { "code": null, "e": 6413, "s": 6406, "text": "Output" }, { "code": null, "e": 6420, "s": 6413, "text": "atom1\n" }, { "code": null, "e": 6606, "s": 6420, "text": "An example of how the Boolean data type can be used is shown in the following program. This example does a comparison between 2 integers and prints the resultant Boolean to the console." }, { "code": null, "e": 6614, "s": 6606, "text": "Example" }, { "code": null, "e": 6689, "s": 6614, "text": "-module(helloworld).\n-export([start/0]).\n\nstart() ->\n io:fwrite(2 =< 3)." }, { "code": null, "e": 6731, "s": 6689, "text": "The output of the above program will be −" }, { "code": null, "e": 6738, "s": 6731, "text": "Output" }, { "code": null, "e": 6744, "s": 6738, "text": "true\n" }, { "code": null, "e": 7003, "s": 6744, "text": "An example of how the Bit String data type can be used is shown in the following program. This program defines a Bit String consisting of 2 bits. The binary_to_list is an inbuilt function defined in Erlang which can be used to convert a Bit String to a list." }, { "code": null, "e": 7011, "s": 7003, "text": "Example" }, { "code": null, "e": 7138, "s": 7011, "text": "-module(helloworld).\n-export([start/0]).\n\nstart() ->\n Bin1 = <<10,20>>,\n X = binary_to_list(Bin1),\n io:fwrite(\"~w\",[X])." }, { "code": null, "e": 7180, "s": 7138, "text": "The output of the above program will be −" }, { "code": null, "e": 7187, "s": 7180, "text": "Output" }, { "code": null, "e": 7196, "s": 7187, "text": "[10,20]\n" }, { "code": null, "e": 7281, "s": 7196, "text": "An example of how the Tuple data type can be used is shown in the following program." }, { "code": null, "e": 7442, "s": 7281, "text": "Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Erlang, which can be used to determine the size of the tuple." }, { "code": null, "e": 7450, "s": 7442, "text": "Example" }, { "code": null, "e": 7572, "s": 7450, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n P = {john,24,{june,25}} , \n io:fwrite(\"~w\",[tuple_size(P)])." }, { "code": null, "e": 7614, "s": 7572, "text": "The output of the above program will be −" }, { "code": null, "e": 7621, "s": 7614, "text": "Output" }, { "code": null, "e": 7624, "s": 7621, "text": "3\n" }, { "code": null, "e": 7707, "s": 7624, "text": "An example of how the Map data type can be used is shown in the following program." }, { "code": null, "e": 7866, "s": 7707, "text": "Here we are defining a Map M1 which has 2 mappings. The map_size is an inbuilt function defined in Erlang, which can be used to determine the size of the map." }, { "code": null, "e": 7874, "s": 7866, "text": "Example" }, { "code": null, "e": 7997, "s": 7874, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n M1 = #{name=>john,age=>25}, \n io:fwrite(\"~w\",[map_size(M1)])." }, { "code": null, "e": 8039, "s": 7997, "text": "The output of the above program will be −" }, { "code": null, "e": 8046, "s": 8039, "text": "Output" }, { "code": null, "e": 8049, "s": 8046, "text": "2\n" }, { "code": null, "e": 8133, "s": 8049, "text": "An example of how the List data type can be used is shown in the following program." }, { "code": null, "e": 8288, "s": 8133, "text": "Here we are defining a List L which has 3 items. The length is an inbuilt function defined in Erlang, which can be used to determine the size of the list." }, { "code": null, "e": 8296, "s": 8288, "text": "Example" }, { "code": null, "e": 8405, "s": 8296, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n L = [10,20,30] , \n io:fwrite(\"~w\",[length(L)])." }, { "code": null, "e": 8447, "s": 8405, "text": "The output of the above program will be −" }, { "code": null, "e": 8454, "s": 8447, "text": "Output" }, { "code": null, "e": 8457, "s": 8454, "text": "3\n" }, { "code": null, "e": 8464, "s": 8457, "text": " Print" }, { "code": null, "e": 8475, "s": 8464, "text": " Add Notes" } ]
Solid Gauge Chart in Pygal - GeeksforGeeks
10 Jul, 2020 Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. Gauges are the popular charts which help for dashboards, they anticipate a number in a range at a glance. It can use colored bands, hands, and combinations to display multiple values and their relation to a numeric scale. Syntax: gauge = pygal.SolidGauge() Example 1: Python3 # importing pygalimport pygal # creating the chart objectSolid_Gauge = pygal.SolidGauge(inner_radius = 0.75) # naming the titleSolid_Gauge.title = 'Solid Gauge Chart' # Random dataSolid_Gauge.add('A', [{'value': 1000, 'max_value': 5000}])Solid_Gauge.add('B', [{'value': 12, 'max_value': 20}])Solid_Gauge.add('C', [{'value': 99, 'max_value': 100}]) Solid_Gauge Output: Example 2: Python3 # importing pygalimport pygal # creating the chart objectSolid_Gauge = pygal.SolidGauge(inner_radius = 0.75, half_pie = True) # naming the titleSolid_Gauge.title = 'Solid Gauge Chart' # Random dataSolid_Gauge.add('A', [{'value': 1000, 'max_value': 5000}])Solid_Gauge.add('B', [{'value': 12, 'max_value': 20}])Solid_Gauge.add('C', [{'value': 99, 'max_value': 100}]) Solid_Gauge Output: Data Visualization Python pygal-chart Python-pygal Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26135, "s": 26107, "text": "\n10 Jul, 2020" }, { "code": null, "e": 26413, "s": 26135, "text": "Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write." }, { "code": null, "e": 26635, "s": 26413, "text": "Gauges are the popular charts which help for dashboards, they anticipate a number in a range at a glance. It can use colored bands, hands, and combinations to display multiple values and their relation to a numeric scale." }, { "code": null, "e": 26643, "s": 26635, "text": "Syntax:" }, { "code": null, "e": 26671, "s": 26643, "text": "gauge = pygal.SolidGauge()\n" }, { "code": null, "e": 26682, "s": 26671, "text": "Example 1:" }, { "code": null, "e": 26690, "s": 26682, "text": "Python3" }, { "code": "# importing pygalimport pygal # creating the chart objectSolid_Gauge = pygal.SolidGauge(inner_radius = 0.75) # naming the titleSolid_Gauge.title = 'Solid Gauge Chart' # Random dataSolid_Gauge.add('A', [{'value': 1000, 'max_value': 5000}])Solid_Gauge.add('B', [{'value': 12, 'max_value': 20}])Solid_Gauge.add('C', [{'value': 99, 'max_value': 100}]) Solid_Gauge", "e": 27059, "s": 26690, "text": null }, { "code": null, "e": 27067, "s": 27059, "text": "Output:" }, { "code": null, "e": 27078, "s": 27067, "text": "Example 2:" }, { "code": null, "e": 27086, "s": 27078, "text": "Python3" }, { "code": "# importing pygalimport pygal # creating the chart objectSolid_Gauge = pygal.SolidGauge(inner_radius = 0.75, half_pie = True) # naming the titleSolid_Gauge.title = 'Solid Gauge Chart' # Random dataSolid_Gauge.add('A', [{'value': 1000, 'max_value': 5000}])Solid_Gauge.add('B', [{'value': 12, 'max_value': 20}])Solid_Gauge.add('C', [{'value': 99, 'max_value': 100}]) Solid_Gauge", "e": 27503, "s": 27086, "text": null }, { "code": null, "e": 27511, "s": 27503, "text": "Output:" }, { "code": null, "e": 27530, "s": 27511, "text": "Data Visualization" }, { "code": null, "e": 27549, "s": 27530, "text": "Python pygal-chart" }, { "code": null, "e": 27562, "s": 27549, "text": "Python-pygal" }, { "code": null, "e": 27569, "s": 27562, "text": "Python" }, { "code": null, "e": 27667, "s": 27569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27685, "s": 27667, "text": "Python Dictionary" }, { "code": null, "e": 27720, "s": 27685, "text": "Read a file line by line in Python" }, { "code": null, "e": 27752, "s": 27720, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27774, "s": 27752, "text": "Enumerate() in Python" }, { "code": null, "e": 27816, "s": 27774, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27846, "s": 27816, "text": "Iterate over a list in Python" }, { "code": null, "e": 27872, "s": 27846, "text": "Python String | replace()" }, { "code": null, "e": 27916, "s": 27872, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27945, "s": 27916, "text": "*args and **kwargs in Python" } ]
Unique rows in boolean matrix | Practice | GeeksforGeeks
Given a binary matrix your task is to find all unique rows of the given matrix. Example 1: Input: row = 3, col = 4 M[][] = {{1 1 0 1},{1 0 0 1},{1 1 0 1}} Output: 1 1 0 1 $1 0 0 1 $ Explanation: Above the matrix of size 3x4 looks like 1 1 0 1 1 0 0 1 1 1 0 1 The two unique rows are 1 1 0 1 and 1 0 0 1 . Your Task: You only need to implement the given function uniqueRow(). The function takes three arguments the first argument is a matrix M and the next two arguments are row and col denoting the rows and columns of the matrix. The function should return the list of the unique row of the martrix. Do not read input, instead use the arguments given in the function. Note: The drivers code print the rows "$" separated. Expected Time Complexity: O(row * col) Expected Auxiliary Space: O(row * col) Constraints: 1<=row,col<=40 0<=M[][]<=1 0 chowdasandeepin 8 hours def uniqueRow(row, col, matrix): #complete the function l=[] c=0 while c<row*col: x=matrix[c:c+col] if x not in l: l.append(x) c+=col return l +1 bhardwajji1 week ago vector<vector<int>> uniqueRow(int mat[MAX][MAX],int row,int col) { unordered_set<string>map; vector<vector<int>>ans; for(int i=0 ;i<row ; i++){ string temp= ""; vector<int>vec; for(int j=0 ;j<col ; j++){ temp+=to_string(mat[i][j]); vec.push_back(mat[i][j]); } if(map.find(temp) == map.end()){ ans.push_back(vec); map.insert(temp); } } return ans; } +1 milindprajapatmst191 month ago 1st Solution Using set: Time Complexity: O(row x col) Space Complexity: O(row x col) # define ll long long vector<vector<int>> uniqueRow(int M[MAX][MAX], int row, int col) { unordered_set<ll> S; vector<vector<int>> arr; for (int i = 0; i < row; i++) { ll _sum = 0; vector<int> _arr; for (int j = 0; j < col; j++) { _sum *= 2; _sum += M[i][j]; _arr.push_back(M[i][j]); } if (S.find(_sum) == S.end()) arr.push_back(_arr); S.insert(_sum); } return arr; } 2nd Solution Using Trie: Time Complexity: O(row x col) Space Complexity: O(row x col) class Node { public: bool end; Node *left, *right; Node() { this->end = false; this->left = nullptr; this->right = nullptr; } }; class Trie { public: Node *root; vector<vector<int>> unique; void insert(int arr[], int n) { vector<int> _arr; Node *curr = root; for (int i = 0; i < n; i++) { _arr.push_back(arr[i]); if (arr[i]) { if (!curr->right) curr->right = new Node(); curr = curr->right; } else { if (!curr->left) curr->left = new Node(); curr = curr->left; } } if (!curr->end) { curr->end = true; unique.push_back(_arr); } } Trie() { this->root = new Node(); } }; vector<vector<int>> uniqueRow(int M[MAX][MAX], int row, int col) { Trie T; for (int i = 0; i < row; i++) T.insert(M[i], col); return T.unique; } 0 sunilsaikumar1 month ago 2 Solutions Using Trie+DFS And Set In Python Using Trie+DFS class TrieNode: def __init__(self): self.NodeLinks = {} self.Count = 0 class Trie: def __init__(self): self.Root = TrieNode() def insertRow(self,Row): Node = self.Root for bit in Row: if(bit not in Node.NodeLinks): Node.NodeLinks[bit] = TrieNode() Node = Node.NodeLinks[bit] Node.Count += 1 def printUnique(self,Row): Node = self.Root for bit in Row: Node = Node.NodeLinks[bit] if(Node.Count != 0): Node.Count = 0 return True return False def uniqueRow(row, col, matrix): Tr = Trie() subMat = [] for i in range(0,len(matrix),col): subMat.append(matrix[i:i+col]) FinRes = [] for Row in subMat: Tr.insertRow(Row) for Row in subMat: if(Tr.printUnique(Row)): FinRes.append(Row) return FinRes Using Set def uniqueRow(row, col, matrix): Set,Res = set(),[] for i in range(0,len(matrix),col): subMat = matrix[i:i+col] if(tuple(subMat) not in Set): Res.append(subMat) Set.add(tuple(subMat)) return Res 0 visitant2 months ago vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col) { //Your code here vector <vector <int>> a; unordered_set <string> c; for(int i=0; i< row; i++) { string s = ""; vector <int> b; for(int j=0;j<col; j++) { if(M[i][j] == 0) { s.push_back('a'); } else { s.push_back('b'); } b.push_back(M[i][j]); } if(c.find(s) == c.end()) { c.insert(s); a.push_back(b); } } return a; } +2 aloksinghbais022 months ago C++ solution using trie having time complexity as O(row*(2*col)) and space complexity as O(row*col) is as follows :- Execution Time :- 0.0 / 1.0 sec struct Node{ Node *links[2] = {nullptr}; bool flag = false; bool containsKey(int x){ return links[x] != nullptr; } void put(int x,Node *node){ links[x] = node; } Node* getKey(int x){ return links[x]; } void setEnd(){ flag = true; } bool isEnd(){ return (flag); }}; class trie{ private: Node *root; public: trie(){ root = new Node(); } void insert(vector<int> arr){ Node *node = root; for(int i = 0; i < arr.size(); i++){ if(!node->containsKey(arr[i])){ node->put(arr[i],new Node()); } node = node->getKey(arr[i]); } node->setEnd(); } bool search(vector<int> arr){ Node *node = root; for(int i = 0; i < arr.size(); i++){ if(!node->containsKey(arr[i])){ return (false); } node = node->getKey(arr[i]); } return node->isEnd(); }}; vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col){ trie tri; vector<vector<int>> ans; for(int i = 0; i < row; i++){ vector<int> v; for(int j = 0; j < col; j++){ v.push_back(M[i][j]); } if(tri.search(v)) continue; tri.insert(v); ans.push_back(v); } return (ans);} 0 sequeirahansel2 months ago My solution using a trie: typedef struct Node{ struct Node* arr[2]; bool flag; Node(){ for(int i=0;i<2;i++){ arr[i] = NULL; } flag = false; } }Node; class Trie{ public: bool isPresent(Node* node, int arr[], int n){ for(int i=0;i<n;i++){ int idx = arr[i]; if(!node->arr[idx]){ return false; } node = node->arr[idx]; } return node->flag; } void insert(Node* node, int arr[], int n){ for(int i=0;i<n;i++){ int idx = arr[i]; if(!node->arr[idx]){ node->arr[idx] = new Node(); } node = node->arr[idx]; } node->flag = true; } }; /*You are required to complete this function*/ vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col) { //Your code here Trie t; Node* root = new Node(); vector<vector<int>> res; for(int i=0;i<row;i++){ if(!t.isPresent(root, M[i], col)){ t.insert(root, M[i], col); vector<int> inner(M[i], M[i]+col); res.push_back(inner); } } return res; } +2 himanshujain4572 months ago Simple Java Solution Using Trie: class GfG{ static class TrieNode{ int wordend=0; TrieNode child[]=new TrieNode[2]; TrieNode() { for(int i=0;i<2;i++) { child[i]=null; } } } static TrieNode root=new TrieNode(); static void BuildTrie(int a[][],int r, int c) { for(int i=0;i<r;i++) { TrieNode temp=root; for(int j=0;j<c;j++) { if(temp.child[a[i][j]]==null) { temp.child[a[i][j]]=new TrieNode(); } temp=temp.child[a[i][j]]; } temp.wordend=1; } } public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c) { ArrayList<ArrayList<Integer>>ans=new ArrayList<ArrayList<Integer>>(); BuildTrie(a,r,c); for(int i=0;i<r;i++) { ArrayList<Integer>t=new ArrayList<Integer>(); TrieNode temp=root; for(int j=0;j<c;j++) { temp=temp.child[a[i][j]]; t.add(a[i][j]); } if(temp.wordend==1) { ans.add(t); temp.wordend=0; } } return ans; }} 0 himanshujain4572 months ago Simple Java Solution Using HashSet: class GfG{ public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c) { ArrayList<ArrayList<Integer>>ans=new ArrayList<>(); Set<ArrayList<Integer>>st=new HashSet<>(); for(int i=0;i<r;i++) { ArrayList<Integer>ap=new ArrayList<>(); for(int j=0;j<c;j++) { ap.add(a[i][j]); } if(!st.contains(ap)) { st.add(ap); ans.add(ap); } } return ans; }} 0 himanshujain457 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 319, "s": 238, "text": "Given a binary matrix your task is to find all unique rows of the given matrix. " }, { "code": null, "e": 330, "s": 319, "text": "Example 1:" }, { "code": null, "e": 546, "s": 330, "text": "Input:\nrow = 3, col = 4 \nM[][] = {{1 1 0 1},{1 0 0 1},{1 1 0 1}}\nOutput: 1 1 0 1 $1 0 0 1 $\nExplanation: Above the matrix of size 3x4\nlooks like\n1 1 0 1\n1 0 0 1\n1 1 0 1\nThe two unique rows are 1 1 0 1 and\n1 0 0 1 .\n" }, { "code": null, "e": 910, "s": 546, "text": "Your Task:\nYou only need to implement the given function uniqueRow(). The function takes three arguments the first argument is a matrix M and the next two arguments are row and col denoting the rows and columns of the matrix. The function should return the list of the unique row of the martrix. Do not read input, instead use the arguments given in the function." }, { "code": null, "e": 963, "s": 910, "text": "Note: The drivers code print the rows \"$\" separated." }, { "code": null, "e": 1041, "s": 963, "text": "Expected Time Complexity: O(row * col)\nExpected Auxiliary Space: O(row * col)" }, { "code": null, "e": 1081, "s": 1041, "text": "Constraints:\n1<=row,col<=40\n0<=M[][]<=1" }, { "code": null, "e": 1083, "s": 1081, "text": "0" }, { "code": null, "e": 1107, "s": 1083, "text": "chowdasandeepin 8 hours" }, { "code": null, "e": 1298, "s": 1107, "text": "def uniqueRow(row, col, matrix): #complete the function l=[] c=0 while c<row*col: x=matrix[c:c+col] if x not in l: l.append(x) c+=col return l " }, { "code": null, "e": 1301, "s": 1298, "text": "+1" }, { "code": null, "e": 1322, "s": 1301, "text": "bhardwajji1 week ago" }, { "code": null, "e": 1802, "s": 1322, "text": "vector<vector<int>> uniqueRow(int mat[MAX][MAX],int row,int col)\n{\n unordered_set<string>map;\n vector<vector<int>>ans;\n \n for(int i=0 ;i<row ; i++){\n string temp= \"\";\n vector<int>vec;\n for(int j=0 ;j<col ; j++){\n temp+=to_string(mat[i][j]);\n vec.push_back(mat[i][j]);\n }\n if(map.find(temp) == map.end()){\n ans.push_back(vec);\n map.insert(temp);\n }\n }\n \n return ans;\n \n}" }, { "code": null, "e": 1805, "s": 1802, "text": "+1" }, { "code": null, "e": 1836, "s": 1805, "text": "milindprajapatmst191 month ago" }, { "code": null, "e": 3528, "s": 1836, "text": "1st Solution Using set:\nTime Complexity: O(row x col)\nSpace Complexity: O(row x col)\n\n# define ll long long\nvector<vector<int>> uniqueRow(int M[MAX][MAX], int row, int col) {\n unordered_set<ll> S;\n vector<vector<int>> arr;\n for (int i = 0; i < row; i++) {\n ll _sum = 0;\n vector<int> _arr;\n for (int j = 0; j < col; j++) {\n _sum *= 2;\n _sum += M[i][j];\n _arr.push_back(M[i][j]);\n }\n if (S.find(_sum) == S.end())\n arr.push_back(_arr);\n S.insert(_sum);\n }\n return arr;\n}\n\n2nd Solution Using Trie:\nTime Complexity: O(row x col)\nSpace Complexity: O(row x col)\n\nclass Node {\npublic:\n bool end;\n Node *left, *right;\n Node() {\n this->end = false;\n this->left = nullptr; this->right = nullptr;\n }\n};\n\nclass Trie {\npublic:\n Node *root;\n vector<vector<int>> unique;\n void insert(int arr[], int n) {\n vector<int> _arr;\n Node *curr = root;\n for (int i = 0; i < n; i++) {\n _arr.push_back(arr[i]);\n if (arr[i]) {\n if (!curr->right)\n curr->right = new Node();\n curr = curr->right;\n }\n else {\n if (!curr->left)\n curr->left = new Node();\n curr = curr->left;\n }\n }\n if (!curr->end) {\n curr->end = true;\n unique.push_back(_arr);\n }\n }\n Trie() {\n this->root = new Node();\n }\n};\n\nvector<vector<int>> uniqueRow(int M[MAX][MAX], int row, int col) {\n Trie T;\n for (int i = 0; i < row; i++)\n T.insert(M[i], col);\n return T.unique;\n}" }, { "code": null, "e": 3530, "s": 3528, "text": "0" }, { "code": null, "e": 3555, "s": 3530, "text": "sunilsaikumar1 month ago" }, { "code": null, "e": 3600, "s": 3555, "text": "2 Solutions Using Trie+DFS And Set In Python" }, { "code": null, "e": 3617, "s": 3602, "text": "Using Trie+DFS" }, { "code": null, "e": 4537, "s": 3619, "text": "class TrieNode:\n def __init__(self):\n self.NodeLinks = {}\n self.Count = 0\nclass Trie:\n def __init__(self):\n self.Root = TrieNode()\n \n def insertRow(self,Row):\n Node = self.Root\n for bit in Row:\n if(bit not in Node.NodeLinks):\n Node.NodeLinks[bit] = TrieNode()\n Node = Node.NodeLinks[bit]\n Node.Count += 1\n \n def printUnique(self,Row):\n Node = self.Root\n for bit in Row:\n Node = Node.NodeLinks[bit]\n if(Node.Count != 0):\n Node.Count = 0 \n return True\n return False\n \ndef uniqueRow(row, col, matrix):\n Tr = Trie()\n subMat = []\n for i in range(0,len(matrix),col):\n subMat.append(matrix[i:i+col])\n FinRes = []\n for Row in subMat:\n Tr.insertRow(Row)\n for Row in subMat:\n if(Tr.printUnique(Row)):\n FinRes.append(Row)\n return FinRes" }, { "code": null, "e": 4549, "s": 4539, "text": "Using Set" }, { "code": null, "e": 4791, "s": 4551, "text": "def uniqueRow(row, col, matrix):\n Set,Res = set(),[]\n for i in range(0,len(matrix),col):\n subMat = matrix[i:i+col]\n if(tuple(subMat) not in Set):\n Res.append(subMat)\n Set.add(tuple(subMat))\n return Res" }, { "code": null, "e": 4793, "s": 4791, "text": "0" }, { "code": null, "e": 4814, "s": 4793, "text": "visitant2 months ago" }, { "code": null, "e": 5326, "s": 4814, "text": "vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col)\n{\n//Your code here\nvector <vector <int>> a;\nunordered_set <string> c;\n\n\nfor(int i=0; i< row; i++)\n{\n string s = \"\";\n vector <int> b;\n for(int j=0;j<col; j++)\n {\n if(M[i][j] == 0)\n {\n s.push_back('a');\n }\n else \n {\n s.push_back('b');\n }\n b.push_back(M[i][j]);\n }\n if(c.find(s) == c.end())\n {\n c.insert(s);\n a.push_back(b);\n }\n}\n\nreturn a;\n}" }, { "code": null, "e": 5329, "s": 5326, "text": "+2" }, { "code": null, "e": 5357, "s": 5329, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 5475, "s": 5357, "text": "C++ solution using trie having time complexity as O(row*(2*col)) and space complexity as O(row*col) is as follows :- " }, { "code": null, "e": 5509, "s": 5477, "text": "Execution Time :- 0.0 / 1.0 sec" }, { "code": null, "e": 5845, "s": 5511, "text": "struct Node{ Node *links[2] = {nullptr}; bool flag = false; bool containsKey(int x){ return links[x] != nullptr; } void put(int x,Node *node){ links[x] = node; } Node* getKey(int x){ return links[x]; } void setEnd(){ flag = true; } bool isEnd(){ return (flag); }};" }, { "code": null, "e": 6476, "s": 5845, "text": "class trie{ private: Node *root; public: trie(){ root = new Node(); } void insert(vector<int> arr){ Node *node = root; for(int i = 0; i < arr.size(); i++){ if(!node->containsKey(arr[i])){ node->put(arr[i],new Node()); } node = node->getKey(arr[i]); } node->setEnd(); } bool search(vector<int> arr){ Node *node = root; for(int i = 0; i < arr.size(); i++){ if(!node->containsKey(arr[i])){ return (false); } node = node->getKey(arr[i]); } return node->isEnd(); }};" }, { "code": null, "e": 6818, "s": 6476, "text": "vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col){ trie tri; vector<vector<int>> ans; for(int i = 0; i < row; i++){ vector<int> v; for(int j = 0; j < col; j++){ v.push_back(M[i][j]); } if(tri.search(v)) continue; tri.insert(v); ans.push_back(v); } return (ans);}" }, { "code": null, "e": 6820, "s": 6818, "text": "0" }, { "code": null, "e": 6847, "s": 6820, "text": "sequeirahansel2 months ago" }, { "code": null, "e": 6873, "s": 6847, "text": "My solution using a trie:" }, { "code": null, "e": 8153, "s": 6873, "text": "typedef struct Node{\n struct Node* arr[2];\n bool flag;\n Node(){\n for(int i=0;i<2;i++){\n arr[i] = NULL;\n }\n flag = false;\n }\n}Node;\n\nclass Trie{\n public:\n \n bool isPresent(Node* node, int arr[], int n){\n for(int i=0;i<n;i++){\n int idx = arr[i];\n if(!node->arr[idx]){\n return false;\n }\n node = node->arr[idx];\n }\n return node->flag;\n }\n \n void insert(Node* node, int arr[], int n){\n for(int i=0;i<n;i++){\n int idx = arr[i];\n if(!node->arr[idx]){\n node->arr[idx] = new Node();\n } \n node = node->arr[idx];\n }\n node->flag = true;\n }\n \n};\n\n\n/*You are required to complete this function*/\nvector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col)\n{\n//Your code here\n Trie t;\n Node* root = new Node();\n vector<vector<int>> res;\n for(int i=0;i<row;i++){\n if(!t.isPresent(root, M[i], col)){\n t.insert(root, M[i], col);\n vector<int> inner(M[i], M[i]+col);\n res.push_back(inner);\n }\n }\n \n return res;\n}" }, { "code": null, "e": 8156, "s": 8153, "text": "+2" }, { "code": null, "e": 8184, "s": 8156, "text": "himanshujain4572 months ago" }, { "code": null, "e": 8217, "s": 8184, "text": "Simple Java Solution Using Trie:" }, { "code": null, "e": 9449, "s": 8217, "text": "class GfG{ static class TrieNode{ int wordend=0; TrieNode child[]=new TrieNode[2]; TrieNode() { for(int i=0;i<2;i++) { child[i]=null; } } } static TrieNode root=new TrieNode(); static void BuildTrie(int a[][],int r, int c) { for(int i=0;i<r;i++) { TrieNode temp=root; for(int j=0;j<c;j++) { if(temp.child[a[i][j]]==null) { temp.child[a[i][j]]=new TrieNode(); } temp=temp.child[a[i][j]]; } temp.wordend=1; } } public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c) { ArrayList<ArrayList<Integer>>ans=new ArrayList<ArrayList<Integer>>(); BuildTrie(a,r,c); for(int i=0;i<r;i++) { ArrayList<Integer>t=new ArrayList<Integer>(); TrieNode temp=root; for(int j=0;j<c;j++) { temp=temp.child[a[i][j]]; t.add(a[i][j]); } if(temp.wordend==1) { ans.add(t); temp.wordend=0; } } return ans; }}" }, { "code": null, "e": 9453, "s": 9451, "text": "0" }, { "code": null, "e": 9481, "s": 9453, "text": "himanshujain4572 months ago" }, { "code": null, "e": 9517, "s": 9481, "text": "Simple Java Solution Using HashSet:" }, { "code": null, "e": 10042, "s": 9517, "text": "class GfG{ public static ArrayList<ArrayList<Integer>> uniqueRow(int a[][],int r, int c) { ArrayList<ArrayList<Integer>>ans=new ArrayList<>(); Set<ArrayList<Integer>>st=new HashSet<>(); for(int i=0;i<r;i++) { ArrayList<Integer>ap=new ArrayList<>(); for(int j=0;j<c;j++) { ap.add(a[i][j]); } if(!st.contains(ap)) { st.add(ap); ans.add(ap); } } return ans; }}" }, { "code": null, "e": 10044, "s": 10042, "text": "0" }, { "code": null, "e": 10060, "s": 10044, "text": "himanshujain457" }, { "code": null, "e": 10086, "s": 10060, "text": "This comment was deleted." }, { "code": null, "e": 10232, "s": 10086, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 10268, "s": 10232, "text": " Login to access your submissions. " }, { "code": null, "e": 10278, "s": 10268, "text": "\nProblem\n" }, { "code": null, "e": 10288, "s": 10278, "text": "\nContest\n" }, { "code": null, "e": 10351, "s": 10288, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10499, "s": 10351, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 10707, "s": 10499, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 10813, "s": 10707, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Difference between Abstract Class and Interface in C# - GeeksforGeeks
28 Jan, 2022 An abstract class is a way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically used to define a base class in the class hierarchy. Example: // C# program to illustrate the// concept of abstract classusing System; // abstract class 'G'public abstract class G { // abstract method 'gfg1()' public abstract void gfg1();} // class 'G' inherit// in child class 'G1'public class G1 : G { // abstract method 'gfg1()' // declare here with // 'override' keyword public override void gfg1() { Console.WriteLine("Class name is G1"); }} // class 'G' inherit in// another child class 'G2'public class G2 : G { // same as the previous class public override void gfg1() { Console.WriteLine("Class name is G2"); }} // Driver Classpublic class main_method { // Main Method public static void Main() { // 'obj' is object of class // 'G' class ' // G' cannot // be instantiate G obj; // instantiate class 'G1' obj = new G1(); // call 'gfg1()' of class 'G1' obj.gfg1(); // instantiate class 'G2' obj = new G2(); // call 'gfg1()' of class 'G2' obj.gfg1(); }} Output : Class name is G1 Class name is G2 Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of interface’s members will be given by the class who implements the interface implicitly or explicitly. Example: // C# program to illustrate the// concept of interfaceusing System; // A simple interfaceinterface interface1 { // method having only declaration // not definition void show();} // A class that implements the interface.class MyClass : interface1 { // providing the body part of function public void show() { Console.WriteLine("Welcome to GeeksforGeeks!!!"); } // Main Method public static void Main(String[] args) { // Creating object MyClass obj1 = new MyClass(); // calling method obj1.show(); }} Output: Welcome to GeeksforGeeks!!! beki914 CSharp-Interfaces CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Delegates Introduction to .NET Framework C# | Data Types HashSet in C# with Examples C# | Replace() Method Different ways to sort an array in descending order in C# Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
[ { "code": null, "e": 24132, "s": 24104, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24476, "s": 24132, "text": "An abstract class is a way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically used to define a base class in the class hierarchy." }, { "code": null, "e": 24485, "s": 24476, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of abstract classusing System; // abstract class 'G'public abstract class G { // abstract method 'gfg1()' public abstract void gfg1();} // class 'G' inherit// in child class 'G1'public class G1 : G { // abstract method 'gfg1()' // declare here with // 'override' keyword public override void gfg1() { Console.WriteLine(\"Class name is G1\"); }} // class 'G' inherit in// another child class 'G2'public class G2 : G { // same as the previous class public override void gfg1() { Console.WriteLine(\"Class name is G2\"); }} // Driver Classpublic class main_method { // Main Method public static void Main() { // 'obj' is object of class // 'G' class ' // G' cannot // be instantiate G obj; // instantiate class 'G1' obj = new G1(); // call 'gfg1()' of class 'G1' obj.gfg1(); // instantiate class 'G2' obj = new G2(); // call 'gfg1()' of class 'G2' obj.gfg1(); }}", "e": 25559, "s": 24485, "text": null }, { "code": null, "e": 25568, "s": 25559, "text": "Output :" }, { "code": null, "e": 25604, "s": 25568, "text": "Class name is G1\nClass name is G2\n" }, { "code": null, "e": 25884, "s": 25604, "text": "Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of interface’s members will be given by the class who implements the interface implicitly or explicitly." }, { "code": null, "e": 25893, "s": 25884, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of interfaceusing System; // A simple interfaceinterface interface1 { // method having only declaration // not definition void show();} // A class that implements the interface.class MyClass : interface1 { // providing the body part of function public void show() { Console.WriteLine(\"Welcome to GeeksforGeeks!!!\"); } // Main Method public static void Main(String[] args) { // Creating object MyClass obj1 = new MyClass(); // calling method obj1.show(); }}", "e": 26472, "s": 25893, "text": null }, { "code": null, "e": 26480, "s": 26472, "text": "Output:" }, { "code": null, "e": 26508, "s": 26480, "text": "Welcome to GeeksforGeeks!!!" }, { "code": null, "e": 26516, "s": 26508, "text": "beki914" }, { "code": null, "e": 26534, "s": 26516, "text": "CSharp-Interfaces" }, { "code": null, "e": 26545, "s": 26534, "text": "CSharp-OOP" }, { "code": null, "e": 26548, "s": 26545, "text": "C#" }, { "code": null, "e": 26646, "s": 26548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26655, "s": 26646, "text": "Comments" }, { "code": null, "e": 26668, "s": 26655, "text": "Old Comments" }, { "code": null, "e": 26696, "s": 26668, "text": "C# Dictionary with examples" }, { "code": null, "e": 26736, "s": 26696, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 26759, "s": 26736, "text": "Extension Method in C#" }, { "code": null, "e": 26774, "s": 26759, "text": "C# | Delegates" }, { "code": null, "e": 26805, "s": 26774, "text": "Introduction to .NET Framework" }, { "code": null, "e": 26821, "s": 26805, "text": "C# | Data Types" }, { "code": null, "e": 26849, "s": 26821, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26871, "s": 26849, "text": "C# | Replace() Method" }, { "code": null, "e": 26929, "s": 26871, "text": "Different ways to sort an array in descending order in C#" } ]
C++ Program to Delete the First Node in a given Singly Linked List
A linked list is a linear data structure that has multiple nodes that are connected with each other. Each node consists of two fields – Data Field and the address of the next node. Let us assume we have a singly linked list and we need to delete the first node from this linked list. For example, Input 1 − 4 → 3 → 2 → 1 Output − 3 → 2 → 1 → Explanation − ‘4’ is the first node in the given singly linked list. After deleting the first node, the linked list will be 3→2→1. Input 2 − 1 → 2 → 3 → Output − 2 → 3 → Explanation − After deleting the first node ‘1’, the linked list will be 2 → 3. Initially, we have a linked list that consists of nodes. Each node contains the data and address to the next node. After inserting the data in the linked list, we will create a function to delete the first node. Thus, we will create a temporary pointer that initially points to the head and move the head to the next node. Now delete the temporary node and return the linked list. A function deleteAthead(node*&head) takes the pointer to the head and deletes the first node of the linked list. A function deleteAthead(node*&head) takes the pointer to the head and deletes the first node of the linked list. Create a temporary pointer that initially points to the head. Create a temporary pointer that initially points to the head. Head moves to the next node. Head moves to the next node. Delete the temporary pointer. Delete the temporary pointer. Return the linked list. Return the linked list. #include<iostream> using namespace std; int main(){ class node{ public: int data; node*next; node(int d){ data=d; node*next=NULL; } }; void insertAtFirstNode(node*&head, int data){ node*n= new node(data); n->next= head; head=n; } void print(node*head){ while(head!=NULL){ cout<<head->data<<"->"; head=head->next; } cout<<endl; } void deleteAtFirst(node*&head){ if(head==NULL){ return; } node*temp=head; head= head->next; delete temp; return; } int main(){ node*head= NULL; insertAtFirstNode(head,1); insertAtFirstNode(head,2); insertAtFirstNode(head,3); insertAtFirstNode(head,4); deleteAtFirst(head); print(head); } Running the above code will generate the output as, 3 → 2 → 1 → Since the given singly linked list is 4 → 3 → 2 → 1 →, after deleting the first node which is 4, the linked list will become, 3 → 2 → 1 →
[ { "code": null, "e": 1243, "s": 1062, "text": "A linked list is a linear data structure that has multiple nodes that are connected with each other. Each node consists of two fields – Data Field and the address of the next node." }, { "code": null, "e": 1359, "s": 1243, "text": "Let us assume we have a singly linked list and we need to delete the first node from this linked list. For example," }, { "code": null, "e": 1383, "s": 1359, "text": "Input 1 − 4 → 3 → 2 → 1" }, { "code": null, "e": 1404, "s": 1383, "text": "Output − 3 → 2 → 1 →" }, { "code": null, "e": 1535, "s": 1404, "text": "Explanation − ‘4’ is the first node in the given singly linked list. After deleting the first node, the linked list will be 3→2→1." }, { "code": null, "e": 1557, "s": 1535, "text": "Input 2 − 1 → 2 → 3 →" }, { "code": null, "e": 1574, "s": 1557, "text": "Output − 2 → 3 →" }, { "code": null, "e": 1654, "s": 1574, "text": "Explanation − After deleting the first node ‘1’, the linked list will be 2 → 3." }, { "code": null, "e": 1866, "s": 1654, "text": "Initially, we have a linked list that consists of nodes. Each node contains the data and address to the next node. After inserting the data in the linked list, we will create a function to delete the first node." }, { "code": null, "e": 2035, "s": 1866, "text": "Thus, we will create a temporary pointer that initially points to the head and move the head to the next node. Now delete the temporary node and return the linked list." }, { "code": null, "e": 2148, "s": 2035, "text": "A function deleteAthead(node*&head) takes the pointer to the head and deletes the first node of the linked list." }, { "code": null, "e": 2261, "s": 2148, "text": "A function deleteAthead(node*&head) takes the pointer to the head and deletes the first node of the linked list." }, { "code": null, "e": 2323, "s": 2261, "text": "Create a temporary pointer that initially points to the head." }, { "code": null, "e": 2385, "s": 2323, "text": "Create a temporary pointer that initially points to the head." }, { "code": null, "e": 2414, "s": 2385, "text": "Head moves to the next node." }, { "code": null, "e": 2443, "s": 2414, "text": "Head moves to the next node." }, { "code": null, "e": 2473, "s": 2443, "text": "Delete the temporary pointer." }, { "code": null, "e": 2503, "s": 2473, "text": "Delete the temporary pointer." }, { "code": null, "e": 2527, "s": 2503, "text": "Return the linked list." }, { "code": null, "e": 2551, "s": 2527, "text": "Return the linked list." }, { "code": null, "e": 3288, "s": 2551, "text": "#include<iostream>\nusing namespace std;\nint main(){\nclass node{\n public:\n int data;\n node*next;\n node(int d){\n data=d;\n node*next=NULL;\n }\n};\nvoid insertAtFirstNode(node*&head, int data){\n node*n= new node(data);\n n->next= head;\n head=n;\n}\nvoid print(node*head){\n while(head!=NULL){\n cout<<head->data<<\"->\";\n head=head->next;\n }\n cout<<endl;\n}\nvoid deleteAtFirst(node*&head){\n if(head==NULL){\n return;\n }\n node*temp=head;\n head= head->next;\n delete temp;\n return;\n}\nint main(){\n node*head= NULL;\n insertAtFirstNode(head,1);\n insertAtFirstNode(head,2);\n insertAtFirstNode(head,3);\n insertAtFirstNode(head,4);\n deleteAtFirst(head);\n print(head);\n}" }, { "code": null, "e": 3340, "s": 3288, "text": "Running the above code will generate the output as," }, { "code": null, "e": 3352, "s": 3340, "text": "3 → 2 → 1 →" }, { "code": null, "e": 3490, "s": 3352, "text": "Since the given singly linked list is 4 → 3 → 2 → 1 →, after deleting the first node which is 4, the linked list will become, 3 → 2 → 1 →" } ]
Python | Pandas dataframe.mod() - GeeksforGeeks
23 Jul, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.mod() function returns modulo of dataframe and other, element-wise (binary operator mod). This function is essentially same as the Dataframe % other, but with support to substitute a fill_value for missing data in one of the inputs. This function can be used with either a series or a dataframe. Syntax: DataFrame.mod(other, axis=’columns’, level=None, fill_value=None) Parameters : Other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex level fill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missingReturns : result : DataFrame Example #1: Use mod() function to find the modulo of each value in the dataframe withe a constant. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf Lets use the dataframe.mod() function to find the modulo of dataframe with 3 Python3 # find mod of dataframe values with 3df.mod(3) Output : Example #2: Use mod() function to find the modulo with a series over the column axis. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf Let’s create the series object Python3 # create a seriessr = pd.Series([3, 2, 4, 5]) # setting its column index similar to the dataframesr.index =["A", "B", "C", "D"] # print the seriessr Lets use the dataframe.mod() function to find the modulo of dataframe with series Python3 # find mod of dataframe values with series# axis = 1 indicates column axisdf.mod(sr, axis = 1) Output : sagar0719kumar Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Jul, 2021" }, { "code": null, "e": 24819, "s": 24292, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.mod() function returns modulo of dataframe and other, element-wise (binary operator mod). This function is essentially same as the Dataframe % other, but with support to substitute a fill_value for missing data in one of the inputs. This function can be used with either a series or a dataframe. " }, { "code": null, "e": 25352, "s": 24819, "text": "Syntax: DataFrame.mod(other, axis=’columns’, level=None, fill_value=None) Parameters : Other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex level fill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missingReturns : result : DataFrame " }, { "code": null, "e": 25452, "s": 25352, "text": "Example #1: Use mod() function to find the modulo of each value in the dataframe withe a constant. " }, { "code": null, "e": 25460, "s": 25452, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf", "e": 25717, "s": 25460, "text": null }, { "code": null, "e": 25796, "s": 25717, "text": "Lets use the dataframe.mod() function to find the modulo of dataframe with 3 " }, { "code": null, "e": 25804, "s": 25796, "text": "Python3" }, { "code": "# find mod of dataframe values with 3df.mod(3)", "e": 25851, "s": 25804, "text": null }, { "code": null, "e": 25862, "s": 25851, "text": "Output : " }, { "code": null, "e": 25952, "s": 25862, "text": " Example #2: Use mod() function to find the modulo with a series over the column axis. " }, { "code": null, "e": 25960, "s": 25952, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf", "e": 26217, "s": 25960, "text": null }, { "code": null, "e": 26249, "s": 26217, "text": "Let’s create the series object " }, { "code": null, "e": 26257, "s": 26249, "text": "Python3" }, { "code": "# create a seriessr = pd.Series([3, 2, 4, 5]) # setting its column index similar to the dataframesr.index =[\"A\", \"B\", \"C\", \"D\"] # print the seriessr", "e": 26406, "s": 26257, "text": null }, { "code": null, "e": 26490, "s": 26406, "text": "Lets use the dataframe.mod() function to find the modulo of dataframe with series " }, { "code": null, "e": 26498, "s": 26490, "text": "Python3" }, { "code": "# find mod of dataframe values with series# axis = 1 indicates column axisdf.mod(sr, axis = 1)", "e": 26593, "s": 26498, "text": null }, { "code": null, "e": 26604, "s": 26593, "text": "Output : " }, { "code": null, "e": 26621, "s": 26606, "text": "sagar0719kumar" }, { "code": null, "e": 26645, "s": 26621, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26677, "s": 26645, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 26691, "s": 26677, "text": "Python-pandas" }, { "code": null, "e": 26698, "s": 26691, "text": "Python" }, { "code": null, "e": 26796, "s": 26698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26805, "s": 26796, "text": "Comments" }, { "code": null, "e": 26818, "s": 26805, "text": "Old Comments" }, { "code": null, "e": 26850, "s": 26818, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26905, "s": 26850, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26961, "s": 26905, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27003, "s": 26961, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27045, "s": 27003, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27084, "s": 27045, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27106, "s": 27084, "text": "Defaultdict in Python" }, { "code": null, "e": 27127, "s": 27106, "text": "Python OOPs Concepts" }, { "code": null, "e": 27158, "s": 27127, "text": "Python | os.path.join() method" } ]
How to control PC from anywhere using Python? - GeeksforGeeks
12 Jul, 2021 Prerequisite – Socket programming in Python In this solution, we use the concept of Socket Programming for establishing communication between two computers. Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are the endpoints built for sending and receiving data and it is a combination of IP address and port. We will import the socket module to use Socket Programming in Python. The following are the methods required to build the solution: Methods in Socket Module: Other Socket Methods: So we have to develop two python programs one is master.py (server)and another is slave.py (client), using master.py we can control the system having slave.py program. To control the pc from anywhere using python please the follow the step mentioned below: Step 1: Create and Execute the “master.py” in one terminal Python3 import timeimport socketimport sysimport os # Initialize s to sockets = socket.socket() # Initialize the hosthost = socket.gethostname() # Initialize the portport = 8080 # Bind the socket with port and hosts.bind(('', port)) print("waiting for connections...") # listening for connectionss.listen() # accepting the incoming connectionsconn, addr = s.accept() print(addr, "is connected to server") # take command as inputcommand = input(str("Enter Command :")) conn.send(command.encode()) print("Command has been sent successfully.") # receive the confirmationdata = conn.recv(1024) if data: print("command received and executed successfully.") Step 2: Create and Execute the “slave.py” is another terminal Python3 import timeimport socketimport sysimport os # Initialize s to sockets = socket.socket() # Initialize the hosthost = "127.0.0.1" # Initialize the portport = 8080 # bind the socket with port and hosts.connect((host, port)) print("Connected to Server.") # receive the command from master programcommand = s.recv(1024)command = command.decode() # match the command and execute it on slave systemif command == "open": print("Command is :", command) s.send("Command received".encode()) # you can give batch file as input here os.system('ls') Output: terminal running master.py terminal running slave.py adnanirshad158 saurabh1990aror sooda367 Python-socket Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25689, "s": 25661, "text": "\n12 Jul, 2021" }, { "code": null, "e": 25733, "s": 25689, "text": "Prerequisite – Socket programming in Python" }, { "code": null, "e": 25847, "s": 25733, "text": "In this solution, we use the concept of Socket Programming for establishing communication between two computers. " }, { "code": null, "e": 26189, "s": 25847, "text": "Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are the endpoints built for sending and receiving data and it is a combination of IP address and port. We will import the socket module to use Socket Programming in Python. The following are the methods required to build the solution:" }, { "code": null, "e": 26215, "s": 26189, "text": "Methods in Socket Module:" }, { "code": null, "e": 26237, "s": 26215, "text": "Other Socket Methods:" }, { "code": null, "e": 26494, "s": 26237, "text": "So we have to develop two python programs one is master.py (server)and another is slave.py (client), using master.py we can control the system having slave.py program. To control the pc from anywhere using python please the follow the step mentioned below:" }, { "code": null, "e": 26553, "s": 26494, "text": "Step 1: Create and Execute the “master.py” in one terminal" }, { "code": null, "e": 26561, "s": 26553, "text": "Python3" }, { "code": "import timeimport socketimport sysimport os # Initialize s to sockets = socket.socket() # Initialize the hosthost = socket.gethostname() # Initialize the portport = 8080 # Bind the socket with port and hosts.bind(('', port)) print(\"waiting for connections...\") # listening for connectionss.listen() # accepting the incoming connectionsconn, addr = s.accept() print(addr, \"is connected to server\") # take command as inputcommand = input(str(\"Enter Command :\")) conn.send(command.encode()) print(\"Command has been sent successfully.\") # receive the confirmationdata = conn.recv(1024) if data: print(\"command received and executed successfully.\")", "e": 27208, "s": 26561, "text": null }, { "code": null, "e": 27270, "s": 27208, "text": "Step 2: Create and Execute the “slave.py” is another terminal" }, { "code": null, "e": 27278, "s": 27270, "text": "Python3" }, { "code": "import timeimport socketimport sysimport os # Initialize s to sockets = socket.socket() # Initialize the hosthost = \"127.0.0.1\" # Initialize the portport = 8080 # bind the socket with port and hosts.connect((host, port)) print(\"Connected to Server.\") # receive the command from master programcommand = s.recv(1024)command = command.decode() # match the command and execute it on slave systemif command == \"open\": print(\"Command is :\", command) s.send(\"Command received\".encode()) # you can give batch file as input here os.system('ls')", "e": 27831, "s": 27278, "text": null }, { "code": null, "e": 27839, "s": 27831, "text": "Output:" }, { "code": null, "e": 27866, "s": 27839, "text": "terminal running master.py" }, { "code": null, "e": 27892, "s": 27866, "text": "terminal running slave.py" }, { "code": null, "e": 27907, "s": 27892, "text": "adnanirshad158" }, { "code": null, "e": 27923, "s": 27907, "text": "saurabh1990aror" }, { "code": null, "e": 27932, "s": 27923, "text": "sooda367" }, { "code": null, "e": 27946, "s": 27932, "text": "Python-socket" }, { "code": null, "e": 27953, "s": 27946, "text": "Python" }, { "code": null, "e": 28051, "s": 27953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28083, "s": 28051, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28125, "s": 28083, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28167, "s": 28125, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28223, "s": 28167, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28250, "s": 28223, "text": "Python Classes and Objects" }, { "code": null, "e": 28281, "s": 28250, "text": "Python | os.path.join() method" }, { "code": null, "e": 28310, "s": 28281, "text": "Create a directory in Python" }, { "code": null, "e": 28332, "s": 28310, "text": "Defaultdict in Python" }, { "code": null, "e": 28371, "s": 28332, "text": "Python | Get unique values from a list" } ]
How to escape single quotes in MySQL?
We can escape single quotes with the help of the SELECT statement. For instance, when single quotes are encountered in a name, eg. “Carol’s”. Let us see the syntax. SELECT ‘SomeValue’; Here is an example that display how to include text with single quotes. mysql> SELECT 'Carol\'s Taylor.'; The following is the output. +-------------------+ | Carol's Taylor | +-------------------+ | Carol's Taylor | +-------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1204, "s": 1062, "text": "We can escape single quotes with the help of the SELECT statement. For instance, when single quotes are encountered in a name, eg. “Carol’s”." }, { "code": null, "e": 1227, "s": 1204, "text": "Let us see the syntax." }, { "code": null, "e": 1247, "s": 1227, "text": "SELECT ‘SomeValue’;" }, { "code": null, "e": 1319, "s": 1247, "text": "Here is an example that display how to include text with single quotes." }, { "code": null, "e": 1353, "s": 1319, "text": "mysql> SELECT 'Carol\\'s Taylor.';" }, { "code": null, "e": 1382, "s": 1353, "text": "The following is the output." }, { "code": null, "e": 1516, "s": 1382, "text": "+-------------------+\n| Carol's Taylor |\n+-------------------+\n| Carol's Taylor |\n+-------------------+\n1 row in set (0.00 sec)" } ]
How to extract data from a string with Python Regular Expressions?
The following code extracts data like first_id, second_id, category from given strings import re s = 'TS001B01.JPG' match = re.match(r'(TS\d+)([A|B])(\d+)\.JPG', s) first_id = match.group(1) category = match.group(2) second_id = match.group(3) print first_id print category print second_id This gives output TS001 B 01
[ { "code": null, "e": 1149, "s": 1062, "text": "The following code extracts data like first_id, second_id, category from given strings" }, { "code": null, "e": 1352, "s": 1149, "text": "import re\ns = 'TS001B01.JPG'\nmatch = re.match(r'(TS\\d+)([A|B])(\\d+)\\.JPG', s)\nfirst_id = match.group(1)\ncategory = match.group(2)\nsecond_id = match.group(3)\nprint first_id\nprint category\nprint second_id" }, { "code": null, "e": 1370, "s": 1352, "text": "This gives output" }, { "code": null, "e": 1381, "s": 1370, "text": "TS001\nB\n01" } ]
How to remove a list of characters in string in Python?
The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example: >>> "Hello people".replace("e", "") "Hllo popl" If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example: >>> import re >>> re.sub("e|l", "", "Hello people") "Ho pop" If you already have the characters you want to remove in a list, you can use join() to create the regex as well. For Example, >>> import re >>> char_list = ['a', 'e', 'i', 'o', 'u'] >>> re.sub("|".join(char_list), "", "Hello people") "Hll ppl" Note: You can also use the [] to create group of characters to replace in regex.
[ { "code": null, "e": 1250, "s": 1062, "text": "The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:" }, { "code": null, "e": 1298, "s": 1250, "text": ">>> \"Hello people\".replace(\"e\", \"\")\n\"Hllo popl\"" }, { "code": null, "e": 1536, "s": 1298, "text": "If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by \"|\" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:" }, { "code": null, "e": 1597, "s": 1536, "text": ">>> import re\n>>> re.sub(\"e|l\", \"\", \"Hello people\")\n\"Ho pop\"" }, { "code": null, "e": 1723, "s": 1597, "text": "If you already have the characters you want to remove in a list, you can use join() to create the regex as well. For Example," }, { "code": null, "e": 1841, "s": 1723, "text": ">>> import re\n>>> char_list = ['a', 'e', 'i', 'o', 'u']\n>>> re.sub(\"|\".join(char_list), \"\", \"Hello people\")\n\"Hll ppl\"" }, { "code": null, "e": 1922, "s": 1841, "text": "Note: You can also use the [] to create group of characters to replace in regex." } ]
C# | Exception - GeeksforGeeks
07 Jan, 2020 An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the program’s instructions. Sometimes during the execution of the program, the user may face the possibility that the program may crash or show an unexpected event during its runtime execution. This unwanted event is known as Exception and it generally gives the indication regarding something wrong within the code. Example: To show the occurrence of exception during divide by zero operation as follows: // C# program to illustrate the exceptionusing System;class Geeks { // Main Method static void Main(string[] args) { // taking two integer value int A = 12; int B = 0; // divide by zero error int c = A / B; Console.Write("Value of C is " + c); }} Runtime Error: Unhandled Exception:System.DivideByZeroException: Attempted to divide by zero.at Geeks.Main (System.String[] args) <0x4068cd50 + 0x0000c> in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide by zero.at Geeks.Main (System.String[] args) <0x4068cd50 + 0x0000c> in :0 Difference between Errors and Exception Errors: Errors are unexpected issues that may arise during computer program execution. Errors cannot be handled. All Errors are exceptions. Exceptions: Exceptions are unexpected events that may arise during run-time. Exceptions can be handled using try-catch mechanisms. All exceptions are not errors. Exception Hierarchy In C#, all the exceptions are derived from the base class Exception which gets further divided into two branches as ApplicationException and another one is SystemException. SystemException is a base class for all CLR or program code generated errors. ApplicationException is a base class for all application related exceptions. All the exception classes are directly or indirectly derived from the Exception class. In case of ApplicationException, the user may create its own exception types and classes. But SystemException contains all the known exception types such as DivideByZeroException or NullReferenceException etc. Different Exception Classes: There are different kinds of exceptions which can be generated in C# program: Divide By Zero exception: It occurs when the user attempts to divide by zero Out of Memory exceptions: It occurs when then the program tries to use excessive memory Index out of bound Exception: Accessing the array element or index which is not present in it. Stackoverflow Exception: Mainly caused due to infinite recursion process Null Reference Exception : Occurs when the user attempts to reference an object which is of NULL type......and many more. .....and many more. Properties of the Exception Class: The Exception class has many properties which help the user to get information about the exception during the exception. Data: This property helps to get the information about the arbitrary data which is held by the property in the key-value pairs. TargetSite: This property helps to get the name of the method where the exception will throw. Message: This property helps to provide the details about the main cause of the exception occurrence. HelpLink: This property helps to hold the URL for a particular exception. StackTrace: This property helps to provide the information about where the error occurred. InnerException: This property helps to provide the information about the series of exceptions that might have occurred. nidhi_biet troumel CSharp-Exception-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Delegates Introduction to .NET Framework C# | Data Types Difference between Ref and Out keywords in C# C# | Replace() Method C# | Abstract Classes
[ { "code": null, "e": 24556, "s": 24528, "text": "\n07 Jan, 2020" }, { "code": null, "e": 25018, "s": 24556, "text": "An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the program’s instructions. Sometimes during the execution of the program, the user may face the possibility that the program may crash or show an unexpected event during its runtime execution. This unwanted event is known as Exception and it generally gives the indication regarding something wrong within the code." }, { "code": null, "e": 25107, "s": 25018, "text": "Example: To show the occurrence of exception during divide by zero operation as follows:" }, { "code": "// C# program to illustrate the exceptionusing System;class Geeks { // Main Method static void Main(string[] args) { // taking two integer value int A = 12; int B = 0; // divide by zero error int c = A / B; Console.Write(\"Value of C is \" + c); }}", "e": 25476, "s": 25107, "text": null }, { "code": null, "e": 25491, "s": 25476, "text": "Runtime Error:" }, { "code": null, "e": 25793, "s": 25491, "text": "Unhandled Exception:System.DivideByZeroException: Attempted to divide by zero.at Geeks.Main (System.String[] args) <0x4068cd50 + 0x0000c> in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide by zero.at Geeks.Main (System.String[] args) <0x4068cd50 + 0x0000c> in :0" }, { "code": null, "e": 25833, "s": 25793, "text": "Difference between Errors and Exception" }, { "code": null, "e": 25841, "s": 25833, "text": "Errors:" }, { "code": null, "e": 25920, "s": 25841, "text": "Errors are unexpected issues that may arise during computer program execution." }, { "code": null, "e": 25946, "s": 25920, "text": "Errors cannot be handled." }, { "code": null, "e": 25973, "s": 25946, "text": "All Errors are exceptions." }, { "code": null, "e": 25985, "s": 25973, "text": "Exceptions:" }, { "code": null, "e": 26050, "s": 25985, "text": "Exceptions are unexpected events that may arise during run-time." }, { "code": null, "e": 26104, "s": 26050, "text": "Exceptions can be handled using try-catch mechanisms." }, { "code": null, "e": 26135, "s": 26104, "text": "All exceptions are not errors." }, { "code": null, "e": 26155, "s": 26135, "text": "Exception Hierarchy" }, { "code": null, "e": 26780, "s": 26155, "text": "In C#, all the exceptions are derived from the base class Exception which gets further divided into two branches as ApplicationException and another one is SystemException. SystemException is a base class for all CLR or program code generated errors. ApplicationException is a base class for all application related exceptions. All the exception classes are directly or indirectly derived from the Exception class. In case of ApplicationException, the user may create its own exception types and classes. But SystemException contains all the known exception types such as DivideByZeroException or NullReferenceException etc." }, { "code": null, "e": 26887, "s": 26780, "text": "Different Exception Classes: There are different kinds of exceptions which can be generated in C# program:" }, { "code": null, "e": 26964, "s": 26887, "text": "Divide By Zero exception: It occurs when the user attempts to divide by zero" }, { "code": null, "e": 27052, "s": 26964, "text": "Out of Memory exceptions: It occurs when then the program tries to use excessive memory" }, { "code": null, "e": 27147, "s": 27052, "text": "Index out of bound Exception: Accessing the array element or index which is not present in it." }, { "code": null, "e": 27220, "s": 27147, "text": "Stackoverflow Exception: Mainly caused due to infinite recursion process" }, { "code": null, "e": 27342, "s": 27220, "text": "Null Reference Exception : Occurs when the user attempts to reference an object which is of NULL type......and many more." }, { "code": null, "e": 27362, "s": 27342, "text": ".....and many more." }, { "code": null, "e": 27518, "s": 27362, "text": "Properties of the Exception Class: The Exception class has many properties which help the user to get information about the exception during the exception." }, { "code": null, "e": 27646, "s": 27518, "text": "Data: This property helps to get the information about the arbitrary data which is held by the property in the key-value pairs." }, { "code": null, "e": 27740, "s": 27646, "text": "TargetSite: This property helps to get the name of the method where the exception will throw." }, { "code": null, "e": 27842, "s": 27740, "text": "Message: This property helps to provide the details about the main cause of the exception occurrence." }, { "code": null, "e": 27916, "s": 27842, "text": "HelpLink: This property helps to hold the URL for a particular exception." }, { "code": null, "e": 28007, "s": 27916, "text": "StackTrace: This property helps to provide the information about where the error occurred." }, { "code": null, "e": 28127, "s": 28007, "text": "InnerException: This property helps to provide the information about the series of exceptions that might have occurred." }, { "code": null, "e": 28138, "s": 28127, "text": "nidhi_biet" }, { "code": null, "e": 28146, "s": 28138, "text": "troumel" }, { "code": null, "e": 28172, "s": 28146, "text": "CSharp-Exception-Handling" }, { "code": null, "e": 28175, "s": 28172, "text": "C#" }, { "code": null, "e": 28273, "s": 28175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28282, "s": 28273, "text": "Comments" }, { "code": null, "e": 28295, "s": 28282, "text": "Old Comments" }, { "code": null, "e": 28317, "s": 28295, "text": "C# | Class and Object" }, { "code": null, "e": 28335, "s": 28317, "text": "C# | Constructors" }, { "code": null, "e": 28375, "s": 28335, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28398, "s": 28375, "text": "Extension Method in C#" }, { "code": null, "e": 28413, "s": 28398, "text": "C# | Delegates" }, { "code": null, "e": 28444, "s": 28413, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28460, "s": 28444, "text": "C# | Data Types" }, { "code": null, "e": 28506, "s": 28460, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28528, "s": 28506, "text": "C# | Replace() Method" } ]
randrange() in Python - GeeksforGeeks
10 Sep, 2020 Generating a random number has always been an important application and having many uses in daily life. Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module. More to this function is discussed in this article. Syntax : random.randrange(start(opt),stop,step(opt)) Parameters : start(opt) : Number consideration for generation starts from this, default value is 0. This parameter is optional. stop : Numbers less than this are generated. This parameter is mandatory. step(opt) : Step point of range, this won't be included. This is optional. Default value is 1. Return Value : This function generated the numbers in the sequence start-stop skipping step. Exceptions : Raises ValueError if stop <= start and number is non- integral. Python3 # Python code to demonstrate the working of# randrange() import random # Using randrange() to generate numbers from 0-100print ("Random number from 0-100 is : ",end="")print (random.randrange(100)) # Using randrange() to generate numbers from 50-100print ("Random number from 50-100 is : ",end="")print (random.randrange(50,100)) # Using randrange() to generate numbers from 50-100# skipping 5print ("Random number from 50-100 skip 5 is : ",end="")print (random.randrange(50,100,5)) Output: Random number from 0-100 is : 26 Random number from 50-100 is : 58 Random number from 50-100 skip 5 is : 90 1. Value Error – Floating point value Python3 # Python code to demonstrate the Exception of# randrange(), ValueError, Float value import random # Using randrange() to generate numbers from 14.5-100# Raises Exceptionprint ("Random number from 14.5-100 is : ",end="")print (random.randrange(14.5,100)) Output : Random number from 14.5-100 is : Runtime Error : Traceback (most recent call last): File "/home/5e40f42505a6926d0c75a09bec1279d9.py", line 9, in print (random.randrange(14.5,100)) File "/usr/lib/python3.5/random.py", line 182, in randrange raise ValueError("non-integer arg 1 for randrange()") ValueError: non-integer arg 1 for randrange() 2. Value Error – start >= stop Python3 # Python code to demonstrate the Exception of# randrange(), ValueError, start >= start import random # Using randrange() to generate numbers from 500-100# Raises Exceptionprint ("Random number from 500-100 is : ",end="")print (random.randrange(500,100)) Output : Random number from 500-100 is : Runtime Error : Traceback (most recent call last): File "/home/ea327cf3f1dd801a66a185d101c5cb13.py", line 9, in print (random.randrange(500,100)) File "/usr/lib/python3.5/random.py", line 196, in randrange raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width)) ValueError: empty range for randrange() (500,100, -400) Generating random numbers has always been an important application and has been used in many casino games, for gambling for many kid games like ludo, etc which use the concept of Dice. A short game, on who reaches 100 first wins have been depicted in the code below. Each player is allowed a dice of 1-10 numbers, i.e at each turn 1-10 can be attained.. Python3 # Python code to demonstrate the Application of# randrange() import random sum = 0sum1 = 0count = 0flag = 0 while(1): # generate random number at each turn 1-10 r1 = random.randrange(1,10) r2 = random.randrange(1,10) # adding to account of players sum = sum + r1 sum1 = sum1 + r2 count = count+1 print ("Total score of Player 1 after turn %d is : %d " % (count,sum)) # break when player 1 reaches 100 if(sum>=100): flag=1 break print ("Total score of Player 2 after turn %d is : %d" % (count,sum1)) # break when player 2 reaches 100 if(sum1>=100): flag=2 break if(flag==1): print("\nPlayer 1 wins the game")else : print("\nPlayer 2 wins the game") Total score of Player 1 after turn 1 is : 8 Total score of Player 2 after turn 1 is : 4 Total score of Player 1 after turn 2 is : 13 Total score of Player 2 after turn 2 is : 8 Total score of Player 1 after turn 3 is : 22 Total score of Player 2 after turn 3 is : 16 Total score of Player 1 after turn 4 is : 28 Total score of Player 2 after turn 4 is : 22 Total score of Player 1 after turn 5 is : 33 Total score of Player 2 after turn 5 is : 27 Total score of Player 1 after turn 6 is : 35 Total score of Player 2 after turn 6 is : 33 Total score of Player 1 after turn 7 is : 36 Total score of Player 2 after turn 7 is : 42 Total score of Player 1 after turn 8 is : 38 Total score of Player 2 after turn 8 is : 50 Total score of Player 1 after turn 9 is : 45 Total score of Player 2 after turn 9 is : 55 Total score of Player 1 after turn 10 is : 48 Total score of Player 2 after turn 10 is : 61 Total score of Player 1 after turn 11 is : 54 Total score of Player 2 after turn 11 is : 64 Total score of Player 1 after turn 12 is : 57 Total score of Player 2 after turn 12 is : 70 Total score of Player 1 after turn 13 is : 66 Total score of Player 2 after turn 13 is : 73 Total score of Player 1 after turn 14 is : 72 Total score of Player 2 after turn 14 is : 75 Total score of Player 1 after turn 15 is : 79 Total score of Player 2 after turn 15 is : 76 Total score of Player 1 after turn 16 is : 81 Total score of Player 2 after turn 16 is : 77 Total score of Player 1 after turn 17 is : 89 Total score of Player 2 after turn 17 is : 81 Total score of Player 1 after turn 18 is : 95 Total score of Player 2 after turn 18 is : 90 Total score of Player 1 after turn 19 is : 97 Total score of Player 2 after turn 19 is : 99 Total score of Player 1 after turn 20 is : 102 Player 1 wins the game This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshitaagarwal Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 23436, "s": 23408, "text": "\n10 Sep, 2020" }, { "code": null, "e": 23761, "s": 23436, "text": "Generating a random number has always been an important application and having many uses in daily life. Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module. More to this function is discussed in this article. " }, { "code": null, "e": 24287, "s": 23761, "text": "Syntax : \nrandom.randrange(start(opt),stop,step(opt))\nParameters :\nstart(opt) : Number consideration for generation starts from this,\ndefault value is 0. This parameter is optional.\nstop : Numbers less than this are generated. This parameter is mandatory.\nstep(opt) : Step point of range, this won't be included. This is optional.\nDefault value is 1.\nReturn Value : \nThis function generated the numbers in the sequence start-stop skipping step.\nExceptions :\nRaises ValueError if stop <= start and number is non- integral.\n\n\n" }, { "code": null, "e": 24297, "s": 24289, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# randrange() import random # Using randrange() to generate numbers from 0-100print (\"Random number from 0-100 is : \",end=\"\")print (random.randrange(100)) # Using randrange() to generate numbers from 50-100print (\"Random number from 50-100 is : \",end=\"\")print (random.randrange(50,100)) # Using randrange() to generate numbers from 50-100# skipping 5print (\"Random number from 50-100 skip 5 is : \",end=\"\")print (random.randrange(50,100,5))", "e": 24780, "s": 24297, "text": null }, { "code": null, "e": 24790, "s": 24780, "text": "Output: " }, { "code": null, "e": 24901, "s": 24790, "text": "Random number from 0-100 is : 26\nRandom number from 50-100 is : 58\nRandom number from 50-100 skip 5 is : 90\n\n\n" }, { "code": null, "e": 24943, "s": 24903, "text": "1. Value Error – Floating point value " }, { "code": null, "e": 24951, "s": 24943, "text": "Python3" }, { "code": "# Python code to demonstrate the Exception of# randrange(), ValueError, Float value import random # Using randrange() to generate numbers from 14.5-100# Raises Exceptionprint (\"Random number from 14.5-100 is : \",end=\"\")print (random.randrange(14.5,100))", "e": 25205, "s": 24951, "text": null }, { "code": null, "e": 25216, "s": 25205, "text": "Output : " }, { "code": null, "e": 25253, "s": 25216, "text": "Random number from 14.5-100 is : \n\n\n" }, { "code": null, "e": 25271, "s": 25253, "text": "Runtime Error : " }, { "code": null, "e": 25578, "s": 25271, "text": "Traceback (most recent call last):\n File \"/home/5e40f42505a6926d0c75a09bec1279d9.py\", line 9, in \n print (random.randrange(14.5,100))\n File \"/usr/lib/python3.5/random.py\", line 182, in randrange\n raise ValueError(\"non-integer arg 1 for randrange()\")\nValueError: non-integer arg 1 for randrange()\n\n\n" }, { "code": null, "e": 25611, "s": 25578, "text": "2. Value Error – start >= stop " }, { "code": null, "e": 25619, "s": 25611, "text": "Python3" }, { "code": "# Python code to demonstrate the Exception of# randrange(), ValueError, start >= start import random # Using randrange() to generate numbers from 500-100# Raises Exceptionprint (\"Random number from 500-100 is : \",end=\"\")print (random.randrange(500,100))", "e": 25873, "s": 25619, "text": null }, { "code": null, "e": 25884, "s": 25873, "text": "Output : " }, { "code": null, "e": 25920, "s": 25884, "text": "Random number from 500-100 is : \n\n\n" }, { "code": null, "e": 25938, "s": 25920, "text": "Runtime Error : " }, { "code": null, "e": 26285, "s": 25938, "text": "Traceback (most recent call last):\n File \"/home/ea327cf3f1dd801a66a185d101c5cb13.py\", line 9, in \n print (random.randrange(500,100))\n File \"/usr/lib/python3.5/random.py\", line 196, in randrange\n raise ValueError(\"empty range for randrange() (%d,%d, %d)\" % (istart, istop, width))\nValueError: empty range for randrange() (500,100, -400)\n\n\n" }, { "code": null, "e": 26642, "s": 26287, "text": "Generating random numbers has always been an important application and has been used in many casino games, for gambling for many kid games like ludo, etc which use the concept of Dice. A short game, on who reaches 100 first wins have been depicted in the code below. Each player is allowed a dice of 1-10 numbers, i.e at each turn 1-10 can be attained.. " }, { "code": null, "e": 26650, "s": 26642, "text": "Python3" }, { "code": "# Python code to demonstrate the Application of# randrange() import random sum = 0sum1 = 0count = 0flag = 0 while(1): # generate random number at each turn 1-10 r1 = random.randrange(1,10) r2 = random.randrange(1,10) # adding to account of players sum = sum + r1 sum1 = sum1 + r2 count = count+1 print (\"Total score of Player 1 after turn %d is : %d \" % (count,sum)) # break when player 1 reaches 100 if(sum>=100): flag=1 break print (\"Total score of Player 2 after turn %d is : %d\" % (count,sum1)) # break when player 2 reaches 100 if(sum1>=100): flag=2 break if(flag==1): print(\"\\nPlayer 1 wins the game\")else : print(\"\\nPlayer 2 wins the game\") ", "e": 27390, "s": 26650, "text": null }, { "code": null, "e": 29249, "s": 27390, "text": "Total score of Player 1 after turn 1 is : 8 \nTotal score of Player 2 after turn 1 is : 4\nTotal score of Player 1 after turn 2 is : 13 \nTotal score of Player 2 after turn 2 is : 8\nTotal score of Player 1 after turn 3 is : 22 \nTotal score of Player 2 after turn 3 is : 16\nTotal score of Player 1 after turn 4 is : 28 \nTotal score of Player 2 after turn 4 is : 22\nTotal score of Player 1 after turn 5 is : 33 \nTotal score of Player 2 after turn 5 is : 27\nTotal score of Player 1 after turn 6 is : 35 \nTotal score of Player 2 after turn 6 is : 33\nTotal score of Player 1 after turn 7 is : 36 \nTotal score of Player 2 after turn 7 is : 42\nTotal score of Player 1 after turn 8 is : 38 \nTotal score of Player 2 after turn 8 is : 50\nTotal score of Player 1 after turn 9 is : 45 \nTotal score of Player 2 after turn 9 is : 55\nTotal score of Player 1 after turn 10 is : 48 \nTotal score of Player 2 after turn 10 is : 61\nTotal score of Player 1 after turn 11 is : 54 \nTotal score of Player 2 after turn 11 is : 64\nTotal score of Player 1 after turn 12 is : 57 \nTotal score of Player 2 after turn 12 is : 70\nTotal score of Player 1 after turn 13 is : 66 \nTotal score of Player 2 after turn 13 is : 73\nTotal score of Player 1 after turn 14 is : 72 \nTotal score of Player 2 after turn 14 is : 75\nTotal score of Player 1 after turn 15 is : 79 \nTotal score of Player 2 after turn 15 is : 76\nTotal score of Player 1 after turn 16 is : 81 \nTotal score of Player 2 after turn 16 is : 77\nTotal score of Player 1 after turn 17 is : 89 \nTotal score of Player 2 after turn 17 is : 81\nTotal score of Player 1 after turn 18 is : 95 \nTotal score of Player 2 after turn 18 is : 90\nTotal score of Player 1 after turn 19 is : 97 \nTotal score of Player 2 after turn 19 is : 99\nTotal score of Player 1 after turn 20 is : 102 \n\nPlayer 1 wins the game\n\n" }, { "code": null, "e": 29675, "s": 29249, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29690, "s": 29675, "text": "anshitaagarwal" }, { "code": null, "e": 29705, "s": 29690, "text": "Python-Library" }, { "code": null, "e": 29712, "s": 29705, "text": "Python" }, { "code": null, "e": 29810, "s": 29712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29819, "s": 29810, "text": "Comments" }, { "code": null, "e": 29832, "s": 29819, "text": "Old Comments" }, { "code": null, "e": 29860, "s": 29832, "text": "Read JSON file using Python" }, { "code": null, "e": 29910, "s": 29860, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29932, "s": 29910, "text": "Python map() function" }, { "code": null, "e": 29976, "s": 29932, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 29994, "s": 29976, "text": "Python Dictionary" }, { "code": null, "e": 30017, "s": 29994, "text": "Taking input in Python" }, { "code": null, "e": 30052, "s": 30017, "text": "Read a file line by line in Python" }, { "code": null, "e": 30074, "s": 30052, "text": "Enumerate() in Python" }, { "code": null, "e": 30106, "s": 30074, "text": "How to Install PIP on Windows ?" } ]
C# | Char.CompareTo() Method - GeeksforGeeks
22 Jun, 2021 In C#, Char.CompareTo() is a System.Char struct method which is used to compare this instance of a specified object or value type and check whether the given instance is precedes, follow, or appears in the same position in the sort order as the specified object or value type. This method can be overloaded by passing the different type of arguments to it. Char.CompareTo(Char) Method Char.CompareTo(Object) Method This method is used to compare this instance to a specified Char object and check whether this instance precedes, follows, or appears in the same position in the sort order as the specified Char object. Syntax: public int CompareTo(Char ch); Parameter: ch: It is the required Char object which is to be compared. Return Type: It returns a signed number that shows the position of the instance in the sort order in relation to the ch parameter. The return type of this method is System.Int32. The different cases for the return values are shown in the below table: Example: C# // C# program to demonstrate the// Char.CompareTo(Char) Methodusing System; class CompareToSample { // Main Method public static void Main() { char ch1 = 'Z'; char ch2 = 'g'; char ch3 = 'A'; // using Char.CompareTo(Char) Method // returns 0 as this instance has // same position in the sort as in ch1 Console.WriteLine('Z'.CompareTo(ch1)); // using Char.CompareTo(Char) Method // returns -13 as this instance // precedes ch2 Console.WriteLine('Z'.CompareTo(ch2)); // using Char.CompareTo(Char) Method // returns 25 as this instance follows // ch3 Console.WriteLine('Z'.CompareTo(ch3)); }} 0 -13 25 This method is used to compare this instance to a specified object and check this instance precedes, follows, or appears in the same position in the sort order as the specified Object. The value of any instance of Char is considered greater than null. Syntax: public int CompareTo(object obj); Parameter: obj: It is the required object which is to be compared with this instance or null. Return Type: It returns a signed number that shows the position of the instance in the sort order in relation to the obj parameter. The return type of this method is System.Int32. The different case for the return values are shown in the below table: Exception: If the obj is not Char object then this method will give ArgumentException. Example: C# // C# program to illustrate the// Char.CompareTo(Object) Methodusing System; class GeeksforGeeks { // Main method public static void Main() { // declaration of data type char ch1 = 'G'; char ch2 = 'a'; char ch3 = 'B'; int output; // compare ch1 with G, as they are // equal so output will be zero output = ch1.CompareTo('G'); Console.WriteLine(output); // compare ch3 with ch2 // output is -31 which means // ch3 is less than ch2 by -31 output = ch3.CompareTo(ch2); Console.WriteLine(output); // compare ch1 with ch3 // output is 5 which means // ch1 is greater then ch3 by 5 output = ch1.CompareTo(ch3); Console.WriteLine(output); }} 0 -31 5 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.compareto?view=netframework-4.7.2 rajeev0719singh 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 Difference between Ref and Out keywords in C#
[ { "code": null, "e": 25277, "s": 25249, "text": "\n22 Jun, 2021" }, { "code": null, "e": 25634, "s": 25277, "text": "In C#, Char.CompareTo() is a System.Char struct method which is used to compare this instance of a specified object or value type and check whether the given instance is precedes, follow, or appears in the same position in the sort order as the specified object or value type. This method can be overloaded by passing the different type of arguments to it." }, { "code": null, "e": 25662, "s": 25634, "text": "Char.CompareTo(Char) Method" }, { "code": null, "e": 25693, "s": 25662, "text": "Char.CompareTo(Object) Method " }, { "code": null, "e": 25897, "s": 25693, "text": "This method is used to compare this instance to a specified Char object and check whether this instance precedes, follows, or appears in the same position in the sort order as the specified Char object. " }, { "code": null, "e": 25905, "s": 25897, "text": "Syntax:" }, { "code": null, "e": 25936, "s": 25905, "text": "public int CompareTo(Char ch);" }, { "code": null, "e": 25948, "s": 25936, "text": "Parameter: " }, { "code": null, "e": 26008, "s": 25948, "text": "ch: It is the required Char object which is to be compared." }, { "code": null, "e": 26259, "s": 26008, "text": "Return Type: It returns a signed number that shows the position of the instance in the sort order in relation to the ch parameter. The return type of this method is System.Int32. The different cases for the return values are shown in the below table:" }, { "code": null, "e": 26268, "s": 26259, "text": "Example:" }, { "code": null, "e": 26271, "s": 26268, "text": "C#" }, { "code": "// C# program to demonstrate the// Char.CompareTo(Char) Methodusing System; class CompareToSample { // Main Method public static void Main() { char ch1 = 'Z'; char ch2 = 'g'; char ch3 = 'A'; // using Char.CompareTo(Char) Method // returns 0 as this instance has // same position in the sort as in ch1 Console.WriteLine('Z'.CompareTo(ch1)); // using Char.CompareTo(Char) Method // returns -13 as this instance // precedes ch2 Console.WriteLine('Z'.CompareTo(ch2)); // using Char.CompareTo(Char) Method // returns 25 as this instance follows // ch3 Console.WriteLine('Z'.CompareTo(ch3)); }}", "e": 27009, "s": 26271, "text": null }, { "code": null, "e": 27018, "s": 27009, "text": "0\n-13\n25" }, { "code": null, "e": 27272, "s": 27020, "text": "This method is used to compare this instance to a specified object and check this instance precedes, follows, or appears in the same position in the sort order as the specified Object. The value of any instance of Char is considered greater than null." }, { "code": null, "e": 27281, "s": 27272, "text": "Syntax: " }, { "code": null, "e": 27315, "s": 27281, "text": "public int CompareTo(object obj);" }, { "code": null, "e": 27326, "s": 27315, "text": "Parameter:" }, { "code": null, "e": 27409, "s": 27326, "text": "obj: It is the required object which is to be compared with this instance or null." }, { "code": null, "e": 27660, "s": 27409, "text": "Return Type: It returns a signed number that shows the position of the instance in the sort order in relation to the obj parameter. The return type of this method is System.Int32. The different case for the return values are shown in the below table:" }, { "code": null, "e": 27747, "s": 27660, "text": "Exception: If the obj is not Char object then this method will give ArgumentException." }, { "code": null, "e": 27756, "s": 27747, "text": "Example:" }, { "code": null, "e": 27759, "s": 27756, "text": "C#" }, { "code": "// C# program to illustrate the// Char.CompareTo(Object) Methodusing System; class GeeksforGeeks { // Main method public static void Main() { // declaration of data type char ch1 = 'G'; char ch2 = 'a'; char ch3 = 'B'; int output; // compare ch1 with G, as they are // equal so output will be zero output = ch1.CompareTo('G'); Console.WriteLine(output); // compare ch3 with ch2 // output is -31 which means // ch3 is less than ch2 by -31 output = ch3.CompareTo(ch2); Console.WriteLine(output); // compare ch1 with ch3 // output is 5 which means // ch1 is greater then ch3 by 5 output = ch1.CompareTo(ch3); Console.WriteLine(output); }}", "e": 28580, "s": 27759, "text": null }, { "code": null, "e": 28588, "s": 28580, "text": "0\n-31\n5" }, { "code": null, "e": 28692, "s": 28590, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.compareto?view=netframework-4.7.2 " }, { "code": null, "e": 28708, "s": 28692, "text": "rajeev0719singh" }, { "code": null, "e": 28727, "s": 28708, "text": "CSharp-Char-Struct" }, { "code": null, "e": 28741, "s": 28727, "text": "CSharp-method" }, { "code": null, "e": 28744, "s": 28741, "text": "C#" }, { "code": null, "e": 28842, "s": 28744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28896, "s": 28842, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 28938, "s": 28896, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 29000, "s": 28938, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 29028, "s": 29000, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 29056, "s": 29028, "text": "C# Dictionary with examples" }, { "code": null, "e": 29079, "s": 29056, "text": "C# | Arrays of Strings" }, { "code": null, "e": 29094, "s": 29079, "text": "C# | Delegates" }, { "code": null, "e": 29117, "s": 29094, "text": "C# | Method Overriding" }, { "code": null, "e": 29139, "s": 29117, "text": "C# | Abstract Classes" } ]
D3.js scaleQuantize() Function - GeeksforGeeks
19 Aug, 2020 The d3.scaleQuantize() function in d3.js is used to create a new scale that is similar to linear scales except that linear scales use a discrete and dis-continuous scale. Syntax: d3.scaleQuantize(); Parameters: This function does not accept any parameter. Return Value: A function is returned by d3.scaleQuantize() function. Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0" /> <title>Geeks for geeks</title> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-color.v1.min.js"> </script> <script src= "https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src= "https://d3js.org/d3-scale-chromatic.v1.min.js"> </script> <style> body { line-height: 5px; text-align: center; } h2 { color: green; } </style></head> <body> <h2>Geeks for geeks</h2> <p>D3.scaleQuantize() Function </p> <script> var object = d3.scaleQuantize() .domain([0, 1]) .range(["less than 0.5", "greater than 0.5"]); document.write("<br/>") document.write("<h3>" + object(0.4) + "</h3>"); document.write("<h3>" + object(0.5) + "</h3>"); </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0" /> <title>Geeks for geeks</title> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-color.v1.min.js"> </script> <script src= "https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src= "https://d3js.org/d3-scale-chromatic.v1.min.js"> </script> <style> body { line-height: 5px; text-align: center; } h2 { color: green; } </style></head> <body> <h2>Geeks for geeks</h2> <p>D3.scaleQuantize() Function </p> <script> var object = d3.scaleQuantize() // Value from 1 to 10 decides // which value to output .domain([1, 10]) .range(["1. This is object(1)", "2. This is object(2)", "3. This is object(3)", "4. This is object(4)", "5. This is object(5)", "6. This is object(6)", "7. This is object(7)", "8. This is object(8)", "9. This is object(9)", "10. This is object(10)"]); document.write("<br/>") document.write("<h3>" + object(1) + "</h3>"); document.write("<h3>" + object(2) + "</h3>"); document.write("<h3>" + object(3) + "</h3>"); document.write("<h3>" + object(4) + "</h3>"); document.write("<h3>" + object(5) + "</h3>"); document.write("<h3>" + object(6) + "</h3>"); document.write("<h3>" + object(7) + "</h3>"); document.write("<h3>" + object(8) + "</h3>"); document.write("<h3>" + object(9) + "</h3>"); document.write("<h3>" + object(10) + "</h3>"); </script></body> </html> Output: D3.js JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples How to read a local text file using JavaScript? Node.js | fs.writeFileSync() Method
[ { "code": null, "e": 25439, "s": 25411, "text": "\n19 Aug, 2020" }, { "code": null, "e": 25610, "s": 25439, "text": "The d3.scaleQuantize() function in d3.js is used to create a new scale that is similar to linear scales except that linear scales use a discrete and dis-continuous scale." }, { "code": null, "e": 25618, "s": 25610, "text": "Syntax:" }, { "code": null, "e": 25638, "s": 25618, "text": "d3.scaleQuantize();" }, { "code": null, "e": 25695, "s": 25638, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 25764, "s": 25695, "text": "Return Value: A function is returned by d3.scaleQuantize() function." }, { "code": null, "e": 25775, "s": 25764, "text": "Example 1:" }, { "code": null, "e": 25780, "s": 25775, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\" /> <title>Geeks for geeks</title> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-color.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script> <style> body { line-height: 5px; text-align: center; } h2 { color: green; } </style></head> <body> <h2>Geeks for geeks</h2> <p>D3.scaleQuantize() Function </p> <script> var object = d3.scaleQuantize() .domain([0, 1]) .range([\"less than 0.5\", \"greater than 0.5\"]); document.write(\"<br/>\") document.write(\"<h3>\" + object(0.4) + \"</h3>\"); document.write(\"<h3>\" + object(0.5) + \"</h3>\"); </script></body> </html>", "e": 26806, "s": 25780, "text": null }, { "code": null, "e": 26814, "s": 26806, "text": "Output:" }, { "code": null, "e": 26825, "s": 26814, "text": "Example 2:" }, { "code": null, "e": 26830, "s": 26825, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\" /> <title>Geeks for geeks</title> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-color.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src= \"https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script> <style> body { line-height: 5px; text-align: center; } h2 { color: green; } </style></head> <body> <h2>Geeks for geeks</h2> <p>D3.scaleQuantize() Function </p> <script> var object = d3.scaleQuantize() // Value from 1 to 10 decides // which value to output .domain([1, 10]) .range([\"1. This is object(1)\", \"2. This is object(2)\", \"3. This is object(3)\", \"4. This is object(4)\", \"5. This is object(5)\", \"6. This is object(6)\", \"7. This is object(7)\", \"8. This is object(8)\", \"9. This is object(9)\", \"10. This is object(10)\"]); document.write(\"<br/>\") document.write(\"<h3>\" + object(1) + \"</h3>\"); document.write(\"<h3>\" + object(2) + \"</h3>\"); document.write(\"<h3>\" + object(3) + \"</h3>\"); document.write(\"<h3>\" + object(4) + \"</h3>\"); document.write(\"<h3>\" + object(5) + \"</h3>\"); document.write(\"<h3>\" + object(6) + \"</h3>\"); document.write(\"<h3>\" + object(7) + \"</h3>\"); document.write(\"<h3>\" + object(8) + \"</h3>\"); document.write(\"<h3>\" + object(9) + \"</h3>\"); document.write(\"<h3>\" + object(10) + \"</h3>\"); </script></body> </html>", "e": 28716, "s": 26830, "text": null }, { "code": null, "e": 28724, "s": 28716, "text": "Output:" }, { "code": null, "e": 28730, "s": 28724, "text": "D3.js" }, { "code": null, "e": 28741, "s": 28730, "text": "JavaScript" }, { "code": null, "e": 28839, "s": 28741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28879, "s": 28839, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28924, "s": 28879, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28985, "s": 28924, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29057, "s": 28985, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29109, "s": 29057, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29155, "s": 29109, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29196, "s": 29155, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29237, "s": 29196, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 29285, "s": 29237, "text": "How to read a local text file using JavaScript?" } ]
Implementing a character-level trigram language model from scratch in python | by Cleopatra Douglas | Towards Data Science
The complete code for this article can be found HERE An N-gram is a sequence of n items(words in this case) from a given sample of text or speech. For example, given the text “ Susan is a kind soul, she will help you out as long as it is within her boundaries” a sample n-gram(s) from the text above starting from the beginning is : unigram: [‘susan’, ‘is’, ‘a, ‘kind’, ’soul’, ‘she’, ‘will’, ‘help’.............] bigram: [‘susan is’, ‘is a’, ‘a kind’, ’kind soul’, ‘ soul she‘, ‘she will’, ‘will help’, ‘ help you’.............] trigram: [‘susan is a’, ‘is a kind’, ‘a kind soul’, ’kind soul she’, ‘soul she will‘, ‘she will help you’.............] From the examples above, we can see that n in n-grams can be different values, a sequence of 1 gram is called a unigram, 2 grams is called a bigram, sequence of 3 grams is called a trigram. We will be talking about trigram models in this article. A bigram model approximates the probability of a word given all the previous words by using only the conditional probability of the preceding words while a trigram model looks two words into the past. So based on the above, to compute a particular trigram probability of a word y given a previous words x, z, we’ll compute the count of the trigram C(xzy) and normalize by the sum of all the trigrams that share the same words x and z, this can be simplified using the equation below: That is, to compute a particular trigram probability of the word “soul”, given the previous words “kind”, “hearted”, we’ll compute the count of the trigram C(“kind hearted soul”) and normalize by the sum of all the trigrams that share the same first-words “kind hearted”. We always represent and compute language model probabilities in log format as log probabilities. Since probabilities are (by definition) less than or equal to 1, the more probabilities we multiply together, the smaller the product becomes. Multiplying enough n-grams together would result in numerical underflow, so we use the log probabilities, instead of the raw probabilities. Adding in log space is equivalent to multiplying in linear space, so we combine log probabilities by adding them. We will be using a corpus of data from the Gutenberg project. This contains passages from different books. We will be predicting character character-level trigram language model, for example, Consider this sentence from Austen: Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence; and had lived nearly twenty-one years in the world with very little to distress or vex her. The following are some examples of character-level trigrams in this sentence: Emm, mma, Woo, ood, ... First, we will do a little preprocessing of our data, we will combine the words in all the passages as one large corpus, remove numeric values if any, and double spaces. def preprocess(self): output = "" for file in self.texts: with open(os.path.join(os.getcwd(), file), 'r', encoding="utf-8-sig", errors='ignore') as suffix: sentence = suffix.read().split('\n') for line in sentence: output += " " + line return output Next is the code for generating our n-grams, we will write a general function that accepts our corpus and the value describing how we would like to divide our n-grams. See below: Next, we build a function that calculates the word frequency, when the word is not seen we will for this example smooth by replacing words with less than 5 frequency with a general character, in this case, UNK. def UNK_treated_ngram_frequency(self, ngram_list): frequency = {} for ngram in ngram_list: if ngram in frequency: frequency[ngram] += 1 else: frequency[ngram] = 1 sup = 0 result = {} for k, v in frequency.items(): if v >= 5: result[k] = v else: sup += v result["UNK"] = sup return result Next, we have our trigram model, we will use Laplace add-one smoothing for unknown probabilities, we will also add all our probabilities (in log space) together: There are two different approaches to evaluate and compare language models, Extrinsic evaluation and Intrinsic evaluation. We will be evaluating intrinsically because it is a useful way of quickly evaluating models. We will evaluate with a metric called Perplexity, this is an intrinsic evaluation method, not as good as evaluating intrinsically though, the article HERE can explain the evaluation concepts better. We will measure the quality of our model by its performance on some test data. The perplexity of a language model on a test set is the inverse probability of the test set, normalized by the number of words. Thus the higher the conditional probability of the word sequence, the lower the perplexity, and maximizing the perplexity is equivalent to maximizing the test set probability according to the language model. For our example, we will be using perplexity to compare our model against two test sentences, one English and another French. Perplexity is calculated as: Implemented as: def perplexity(total_log_prob, N): perplexity = total_log_prob ** (1 / N) return perplexity Testing both sentences below, we get the following perplexity: perp = self.perplexity(sum_prob, len(trigram_value))print("perplexity ==> ", perp) English Sentence: perplexity of 0.12571631288775162 If we do not change our economic and social policies, we will be in danger of undermining solidarity, the very value on which the European social model is based.The rapid drift towards an increasingly divided society is happening not only in Europe but also on a much wider scale. An entire continent, Africa - about which you made a highly relevant point in your speech, Prime Minister - has lost contact even with the developing world.We must do everything in our power to stop this unjust development model and to give voices and rights to those who have neither.Ladies and gentlemen, Prime Minister, the Laeken Summit and declaration are also vitally important for another reason.Laeken must determine how we are to structure the second stage of the 'Future of Europe' debate. French Sentence: perplexity of 0.21229602165162492 Je suis reconnaissante à la Commission d' avoir adopté ce plan d' action.Cependant, la condition de son applicabilité est que les personnes atteintes d' un handicap puissent disposer des moyens financiers nécessaires, et qu' elles aient la possibilité purement physique de passer les frontiÚres.Il serait intéressant de savoir si la Commission est aussi disposée à débloquer des fonds en faveur des personnes handicapées, pour qu' elles puissent, elles aussi, parcourir le monde, aussi loin que pourra les emmener le fauteuil roulant.J'ai mentionné la directive que la Commission a proposée pour l'aménagement des moyens de transport collectifs, afin que les handicapés puissent les utiliser.Le Conseil n'a pas encore fait avancer cette question, qui en est au stade de la concertation. As expected, our model is quite perplexed by the french sentence, This is good enough at the moment, however, our model can be improved on. Comments and feedbacks are welcome. Don't forget to click the follow button.
[ { "code": null, "e": 100, "s": 47, "text": "The complete code for this article can be found HERE" }, { "code": null, "e": 380, "s": 100, "text": "An N-gram is a sequence of n items(words in this case) from a given sample of text or speech. For example, given the text “ Susan is a kind soul, she will help you out as long as it is within her boundaries” a sample n-gram(s) from the text above starting from the beginning is :" }, { "code": null, "e": 461, "s": 380, "text": "unigram: [‘susan’, ‘is’, ‘a, ‘kind’, ’soul’, ‘she’, ‘will’, ‘help’.............]" }, { "code": null, "e": 577, "s": 461, "text": "bigram: [‘susan is’, ‘is a’, ‘a kind’, ’kind soul’, ‘ soul she‘, ‘she will’, ‘will help’, ‘ help you’.............]" }, { "code": null, "e": 697, "s": 577, "text": "trigram: [‘susan is a’, ‘is a kind’, ‘a kind soul’, ’kind soul she’, ‘soul she will‘, ‘she will help you’.............]" }, { "code": null, "e": 887, "s": 697, "text": "From the examples above, we can see that n in n-grams can be different values, a sequence of 1 gram is called a unigram, 2 grams is called a bigram, sequence of 3 grams is called a trigram." }, { "code": null, "e": 944, "s": 887, "text": "We will be talking about trigram models in this article." }, { "code": null, "e": 1145, "s": 944, "text": "A bigram model approximates the probability of a word given all the previous words by using only the conditional probability of the preceding words while a trigram model looks two words into the past." }, { "code": null, "e": 1428, "s": 1145, "text": "So based on the above, to compute a particular trigram probability of a word y given a previous words x, z, we’ll compute the count of the trigram C(xzy) and normalize by the sum of all the trigrams that share the same words x and z, this can be simplified using the equation below:" }, { "code": null, "e": 1700, "s": 1428, "text": "That is, to compute a particular trigram probability of the word “soul”, given the previous words “kind”, “hearted”, we’ll compute the count of the trigram C(“kind hearted soul”) and normalize by the sum of all the trigrams that share the same first-words “kind hearted”." }, { "code": null, "e": 2194, "s": 1700, "text": "We always represent and compute language model probabilities in log format as log probabilities. Since probabilities are (by definition) less than or equal to 1, the more probabilities we multiply together, the smaller the product becomes. Multiplying enough n-grams together would result in numerical underflow, so we use the log probabilities, instead of the raw probabilities. Adding in log space is equivalent to multiplying in linear space, so we combine log probabilities by adding them." }, { "code": null, "e": 2766, "s": 2194, "text": "We will be using a corpus of data from the Gutenberg project. This contains passages from different books. We will be predicting character character-level trigram language model, for example, Consider this sentence from Austen: Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence; and had lived nearly twenty-one years in the world with very little to distress or vex her. The following are some examples of character-level trigrams in this sentence: Emm, mma, Woo, ood, ..." }, { "code": null, "e": 2936, "s": 2766, "text": "First, we will do a little preprocessing of our data, we will combine the words in all the passages as one large corpus, remove numeric values if any, and double spaces." }, { "code": null, "e": 3239, "s": 2936, "text": "def preprocess(self): output = \"\" for file in self.texts: with open(os.path.join(os.getcwd(), file), 'r', encoding=\"utf-8-sig\", errors='ignore') as suffix: sentence = suffix.read().split('\\n') for line in sentence: output += \" \" + line return output" }, { "code": null, "e": 3418, "s": 3239, "text": "Next is the code for generating our n-grams, we will write a general function that accepts our corpus and the value describing how we would like to divide our n-grams. See below:" }, { "code": null, "e": 3629, "s": 3418, "text": "Next, we build a function that calculates the word frequency, when the word is not seen we will for this example smooth by replacing words with less than 5 frequency with a general character, in this case, UNK." }, { "code": null, "e": 4010, "s": 3629, "text": "def UNK_treated_ngram_frequency(self, ngram_list): frequency = {} for ngram in ngram_list: if ngram in frequency: frequency[ngram] += 1 else: frequency[ngram] = 1 sup = 0 result = {} for k, v in frequency.items(): if v >= 5: result[k] = v else: sup += v result[\"UNK\"] = sup return result" }, { "code": null, "e": 4172, "s": 4010, "text": "Next, we have our trigram model, we will use Laplace add-one smoothing for unknown probabilities, we will also add all our probabilities (in log space) together:" }, { "code": null, "e": 4587, "s": 4172, "text": "There are two different approaches to evaluate and compare language models, Extrinsic evaluation and Intrinsic evaluation. We will be evaluating intrinsically because it is a useful way of quickly evaluating models. We will evaluate with a metric called Perplexity, this is an intrinsic evaluation method, not as good as evaluating intrinsically though, the article HERE can explain the evaluation concepts better." }, { "code": null, "e": 5002, "s": 4587, "text": "We will measure the quality of our model by its performance on some test data. The perplexity of a language model on a test set is the inverse probability of the test set, normalized by the number of words. Thus the higher the conditional probability of the word sequence, the lower the perplexity, and maximizing the perplexity is equivalent to maximizing the test set probability according to the language model." }, { "code": null, "e": 5128, "s": 5002, "text": "For our example, we will be using perplexity to compare our model against two test sentences, one English and another French." }, { "code": null, "e": 5157, "s": 5128, "text": "Perplexity is calculated as:" }, { "code": null, "e": 5173, "s": 5157, "text": "Implemented as:" }, { "code": null, "e": 5271, "s": 5173, "text": "def perplexity(total_log_prob, N): perplexity = total_log_prob ** (1 / N) return perplexity" }, { "code": null, "e": 5334, "s": 5271, "text": "Testing both sentences below, we get the following perplexity:" }, { "code": null, "e": 5417, "s": 5334, "text": "perp = self.perplexity(sum_prob, len(trigram_value))print(\"perplexity ==> \", perp)" }, { "code": null, "e": 5469, "s": 5417, "text": "English Sentence: perplexity of 0.12571631288775162" }, { "code": null, "e": 6250, "s": 5469, "text": "If we do not change our economic and social policies, we will be in danger of undermining solidarity, the very value on which the European social model is based.The rapid drift towards an increasingly divided society is happening not only in Europe but also on a much wider scale. An entire continent, Africa - about which you made a highly relevant point in your speech, Prime Minister - has lost contact even with the developing world.We must do everything in our power to stop this unjust development model and to give voices and rights to those who have neither.Ladies and gentlemen, Prime Minister, the Laeken Summit and declaration are also vitally important for another reason.Laeken must determine how we are to structure the second stage of the 'Future of Europe' debate." }, { "code": null, "e": 6301, "s": 6250, "text": "French Sentence: perplexity of 0.21229602165162492" }, { "code": null, "e": 7119, "s": 6301, "text": "Je suis reconnaissante à la Commission d' avoir adopté ce plan d' action.Cependant, la condition de son applicabilité est que les personnes atteintes d' un handicap puissent disposer des moyens financiers nécessaires, et qu' elles aient la possibilité purement physique de passer les frontiÚres.Il serait intéressant de savoir si la Commission est aussi disposée à débloquer des fonds en faveur des personnes handicapées, pour qu' elles puissent, elles aussi, parcourir le monde, aussi loin que pourra les emmener le fauteuil roulant.J'ai mentionné la directive que la Commission a proposée pour l'aménagement des moyens de transport collectifs, afin que les handicapés puissent les utiliser.Le Conseil n'a pas encore fait avancer cette question, qui en est au stade de la concertation." }, { "code": null, "e": 7259, "s": 7119, "text": "As expected, our model is quite perplexed by the french sentence, This is good enough at the moment, however, our model can be improved on." }, { "code": null, "e": 7295, "s": 7259, "text": "Comments and feedbacks are welcome." } ]
PhotoView in Android - GeeksforGeeks
18 Feb, 2021 In this article, PhotoView is added in android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifies the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scrolling even when a scrolling parent container like ViewPager is used. It can be used in the gallery app. Approach: Step 1: Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application. XML allprojects { repositories { maven { url 'https://jitpack.io' } } } Step 2: Add the support library in build.gradle file and add the dependency in the dependencies section. It allows the developer to use the PhotoView directly in XML files. XML dependencies { implementation 'com.github.chrisbanes:PhotoView:2.0.0' } Step 3: Add the following code in the activity_main.xml file. In this file, PhotoView is added to the layout. activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.github.chrisbanes.photoview.PhotoView android:id="@+id/photo_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Add the following code in the MainActivity.java file. In this file, we add image to our PhotoView. setImageResource() method is used to add the image in PhotoView. MainActivity.java package org.geeksforgeeks.photoView import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import com.github.chrisbanes.photoview.PhotoView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhotoView photoView = (PhotoView) findViewById(R.id.photo_view); photoView.setImageResource(R.drawable.gfg); }} Output: Refer to the official documentation for more information. android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 26407, "s": 26379, "text": "\n18 Feb, 2021" }, { "code": null, "e": 26869, "s": 26407, "text": "In this article, PhotoView is added in android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifies the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scrolling even when a scrolling parent container like ViewPager is used. It can be used in the gallery app. Approach: " }, { "code": null, "e": 27144, "s": 26869, "text": "Step 1: Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application. " }, { "code": null, "e": 27148, "s": 27144, "text": "XML" }, { "code": " allprojects { repositories { maven { url 'https://jitpack.io' } } } ", "e": 27293, "s": 27148, "text": null }, { "code": null, "e": 27468, "s": 27293, "text": "Step 2: Add the support library in build.gradle file and add the dependency in the dependencies section. It allows the developer to use the PhotoView directly in XML files. " }, { "code": null, "e": 27472, "s": 27468, "text": "XML" }, { "code": " dependencies { implementation 'com.github.chrisbanes:PhotoView:2.0.0' } ", "e": 27591, "s": 27472, "text": null }, { "code": null, "e": 27701, "s": 27591, "text": "Step 3: Add the following code in the activity_main.xml file. In this file, PhotoView is added to the layout." }, { "code": null, "e": 27719, "s": 27701, "text": "activity_main.xml" }, { "code": " <?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <com.github.chrisbanes.photoview.PhotoView android:id=\"@+id/photo_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/> </androidx.constraintlayout.widget.ConstraintLayout> ", "e": 28323, "s": 27719, "text": null }, { "code": null, "e": 28496, "s": 28323, "text": "Step 4: Add the following code in the MainActivity.java file. In this file, we add image to our PhotoView. setImageResource() method is used to add the image in PhotoView." }, { "code": null, "e": 28514, "s": 28496, "text": "MainActivity.java" }, { "code": " package org.geeksforgeeks.photoView import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import com.github.chrisbanes.photoview.PhotoView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhotoView photoView = (PhotoView) findViewById(R.id.photo_view); photoView.setImageResource(R.drawable.gfg); }}", "e": 29062, "s": 28514, "text": null }, { "code": null, "e": 29070, "s": 29062, "text": "Output:" }, { "code": null, "e": 29129, "s": 29070, "text": " Refer to the official documentation for more information." }, { "code": null, "e": 29137, "s": 29129, "text": "android" }, { "code": null, "e": 29150, "s": 29137, "text": "Android-View" }, { "code": null, "e": 29158, "s": 29150, "text": "Android" }, { "code": null, "e": 29163, "s": 29158, "text": "Java" }, { "code": null, "e": 29168, "s": 29163, "text": "Java" }, { "code": null, "e": 29176, "s": 29168, "text": "Android" }, { "code": null, "e": 29274, "s": 29176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29312, "s": 29274, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29351, "s": 29312, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29401, "s": 29351, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29427, "s": 29401, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 29469, "s": 29427, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29484, "s": 29469, "text": "Arrays in Java" }, { "code": null, "e": 29528, "s": 29484, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29550, "s": 29528, "text": "For-each loop in Java" }, { "code": null, "e": 29601, "s": 29550, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Time Series Analysis: Creating Synthetic Datasets | by Soner Yıldırım | Towards Data Science
Time series is a sequence of values ordered in time. We may encounter time series data in pretty much any domain. Weather forecasts, exchange rates, sales data, sound waves are just a few examples. Time series can be any type of data that is represented as an ordered sequence. In an earlier post, I covered the basic concepts in time series analysis. In this post, we will create time series data with different patterns. One advantage of synthetic datasets is that we can measure the performance of a model and have an idea about how it will perform with real life data. The common patterns observed in a time series are: Trend: An overall upward or downward direction. Seasonality: Patterns that repeat observed or predictable intervals. White noise: Time series does not always follow a pattern or include seasonality. Some processes produce just random data. This kind of time series is called white noise. Note: The patterns are not always smooth and usually include some kind of noise. Furthermore, a time series may include a combination of different patterns. We will use numpy to generate arrays of values and matplotlib to plot the series. Let’s start with importing the required libraries: import numpy as npimport matplotlib.pyplot as plt%matplotlib inline We can define a function that takes the arrays as input and create plots: def plot_time_series(time, values, label): plt.figure(figsize=(10,6)) plt.plot(time, values) plt.xlabel("Time", fontsize=20) plt.ylabel("Value", fontsize=20) plt.title(label, fontsize=20) plt.grid(True) The first plot is the simplest one which is a time series with an upward trend. We create arrays for time and values with a slope. Then pass these arrays as arguments to our function: time = np.arange(100)values = time*0.4plot_time_series(time, values, "Upward Trend") We can now plot a time series with seasonality. We need a series that repeats the same pattern. # Just a random patterntime = np.arange(50)values = np.where(time < 10, time**3, (time-9)**2)# Repeat the pattern 5 timesseasonal = []for i in range(5): for j in range(50): seasonal.append(values[j])# Plottime_seasonal = np.arange(250)plot_time_series(time_seasonal, seasonal, label="Seasonality") This is just a random pattern. Feel free to try out different patterns with numpy. Let’s add some noise to the values because we are more likely to work with noisy data rather than smooth curves in real life. We can create the random noise using np.random.randn function. Then add that noise to the original seasonal series: noise = np.random.randn(250)*100seasonal += noisetime_seasonal = np.arange(250)plot_time_series(time_seasonal, seasonal, label="Seasonality with Noise") We may see a combination of different patterns in a time series. For example, the following time series contain both an upward trend and seasonality. Ofcourse, there is also some noise. seasonal_upward = seasonal + np.arange(250)*10time_seasonal = np.arange(250)plot_time_series(time_seasonal, seasonal_upward, label="Seasonality + Upward Trend + Noise") Some processes just produce random data that does not follow any pattern. This kind of time series is known as white noise which is very hard to analyze and predict. Let’s create an example of white noise: time = np.arange(200)values = np.random.randn(200)*100plot_time_series(time, values, label="White Noise") Up to now, we have seen time series that follows some pattern continuously. This kind of time series is called stationary. However, life is full of surprises so we may encounter some events that break the pattern and creates non-stationary time series. For example, coronavirus is such a big event that messed up many patterns and businesses are required to update their time series analysis. Let’s create an example: big_event = np.zeros(250)big_event[-50:] = np.arange(50)*-50non_stationary = seasonal_upward + big_eventtime_seasonal = np.arange(250)plot_time_series(time_seasonal, non_stationary, label="Non-stationary Time Series") We introduced a big event after time point 210 and the effect can be seen afterwards. Time series analysis is a broad field in data science domain. A comprehensive understanding of time series analysis requires knowledge in machine learning, statistics, and ofcourse, domain expertise. In this post, we covered how to create synthetic datasets. We can use these datasets to check the performance of the models we build. In an earlier post, I explained the basic concepts in time series analysis to understand the characteristics of time series and its applications. I plan to continue writing about time series analysis from simple concepts to advance analysis techniques. Stay tuned for the following posts. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 450, "s": 172, "text": "Time series is a sequence of values ordered in time. We may encounter time series data in pretty much any domain. Weather forecasts, exchange rates, sales data, sound waves are just a few examples. Time series can be any type of data that is represented as an ordered sequence." }, { "code": null, "e": 745, "s": 450, "text": "In an earlier post, I covered the basic concepts in time series analysis. In this post, we will create time series data with different patterns. One advantage of synthetic datasets is that we can measure the performance of a model and have an idea about how it will perform with real life data." }, { "code": null, "e": 796, "s": 745, "text": "The common patterns observed in a time series are:" }, { "code": null, "e": 844, "s": 796, "text": "Trend: An overall upward or downward direction." }, { "code": null, "e": 913, "s": 844, "text": "Seasonality: Patterns that repeat observed or predictable intervals." }, { "code": null, "e": 1084, "s": 913, "text": "White noise: Time series does not always follow a pattern or include seasonality. Some processes produce just random data. This kind of time series is called white noise." }, { "code": null, "e": 1241, "s": 1084, "text": "Note: The patterns are not always smooth and usually include some kind of noise. Furthermore, a time series may include a combination of different patterns." }, { "code": null, "e": 1374, "s": 1241, "text": "We will use numpy to generate arrays of values and matplotlib to plot the series. Let’s start with importing the required libraries:" }, { "code": null, "e": 1442, "s": 1374, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 1516, "s": 1442, "text": "We can define a function that takes the arrays as input and create plots:" }, { "code": null, "e": 1737, "s": 1516, "text": "def plot_time_series(time, values, label): plt.figure(figsize=(10,6)) plt.plot(time, values) plt.xlabel(\"Time\", fontsize=20) plt.ylabel(\"Value\", fontsize=20) plt.title(label, fontsize=20) plt.grid(True)" }, { "code": null, "e": 1921, "s": 1737, "text": "The first plot is the simplest one which is a time series with an upward trend. We create arrays for time and values with a slope. Then pass these arrays as arguments to our function:" }, { "code": null, "e": 2006, "s": 1921, "text": "time = np.arange(100)values = time*0.4plot_time_series(time, values, \"Upward Trend\")" }, { "code": null, "e": 2102, "s": 2006, "text": "We can now plot a time series with seasonality. We need a series that repeats the same pattern." }, { "code": null, "e": 2410, "s": 2102, "text": "# Just a random patterntime = np.arange(50)values = np.where(time < 10, time**3, (time-9)**2)# Repeat the pattern 5 timesseasonal = []for i in range(5): for j in range(50): seasonal.append(values[j])# Plottime_seasonal = np.arange(250)plot_time_series(time_seasonal, seasonal, label=\"Seasonality\")" }, { "code": null, "e": 2493, "s": 2410, "text": "This is just a random pattern. Feel free to try out different patterns with numpy." }, { "code": null, "e": 2619, "s": 2493, "text": "Let’s add some noise to the values because we are more likely to work with noisy data rather than smooth curves in real life." }, { "code": null, "e": 2735, "s": 2619, "text": "We can create the random noise using np.random.randn function. Then add that noise to the original seasonal series:" }, { "code": null, "e": 2888, "s": 2735, "text": "noise = np.random.randn(250)*100seasonal += noisetime_seasonal = np.arange(250)plot_time_series(time_seasonal, seasonal, label=\"Seasonality with Noise\")" }, { "code": null, "e": 3074, "s": 2888, "text": "We may see a combination of different patterns in a time series. For example, the following time series contain both an upward trend and seasonality. Ofcourse, there is also some noise." }, { "code": null, "e": 3243, "s": 3074, "text": "seasonal_upward = seasonal + np.arange(250)*10time_seasonal = np.arange(250)plot_time_series(time_seasonal, seasonal_upward, label=\"Seasonality + Upward Trend + Noise\")" }, { "code": null, "e": 3449, "s": 3243, "text": "Some processes just produce random data that does not follow any pattern. This kind of time series is known as white noise which is very hard to analyze and predict. Let’s create an example of white noise:" }, { "code": null, "e": 3555, "s": 3449, "text": "time = np.arange(200)values = np.random.randn(200)*100plot_time_series(time, values, label=\"White Noise\")" }, { "code": null, "e": 3973, "s": 3555, "text": "Up to now, we have seen time series that follows some pattern continuously. This kind of time series is called stationary. However, life is full of surprises so we may encounter some events that break the pattern and creates non-stationary time series. For example, coronavirus is such a big event that messed up many patterns and businesses are required to update their time series analysis. Let’s create an example:" }, { "code": null, "e": 4191, "s": 3973, "text": "big_event = np.zeros(250)big_event[-50:] = np.arange(50)*-50non_stationary = seasonal_upward + big_eventtime_seasonal = np.arange(250)plot_time_series(time_seasonal, non_stationary, label=\"Non-stationary Time Series\")" }, { "code": null, "e": 4277, "s": 4191, "text": "We introduced a big event after time point 210 and the effect can be seen afterwards." }, { "code": null, "e": 4900, "s": 4277, "text": "Time series analysis is a broad field in data science domain. A comprehensive understanding of time series analysis requires knowledge in machine learning, statistics, and ofcourse, domain expertise. In this post, we covered how to create synthetic datasets. We can use these datasets to check the performance of the models we build. In an earlier post, I explained the basic concepts in time series analysis to understand the characteristics of time series and its applications. I plan to continue writing about time series analysis from simple concepts to advance analysis techniques. Stay tuned for the following posts." } ]
How to Delete Data in SQLite Database in Android? - GeeksforGeeks
25 Feb, 2021 In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database. We will be building a simple application in which we will be deleting the course from our SQLite database in our Android app. A sample video is given below to get an idea about what we are going to do in this article. Step 1: Updating our DBHandler class As we have to delete data from our SQLite database. For that, we have to create a method to delete our data from the SQLite database. Navigate to the app > java > your app’s package name > DBHandler and add the below code to it. Java // below is the method for deleting our course.public void deleteCourse(String courseName) { // on below line we are creating // a variable to write our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are calling a method to delete our // course and we are comparing it with our course name. db.delete(TABLE_NAME, "name=?", new String[]{courseName}); db.close();} Below is the updated code for the DBHandler.java file after adding the above code snippet. Java import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; public class DBHandler extends SQLiteOpenHelper { // creating a constant variables for our database. // below variable is for our database name. private static final String DB_NAME = "coursedb"; // below int is our database version private static final int DB_VERSION = 1; // below variable is for our table name. private static final String TABLE_NAME = "mycourses"; // below variable is for our id column. private static final String ID_COL = "id"; // below variable is for our course name column private static final String NAME_COL = "name"; // below variable id for our course duration column. private static final String DURATION_COL = "duration"; // below variable for our course description column. private static final String DESCRIPTION_COL = "description"; // below variable is for our course tracks column. private static final String TRACKS_COL = "tracks"; // creating a constructor for our database handler. public DBHandler(Context context) { super(context, DB_NAME, null, DB_VERSION); } // below method is for creating a database by running a sqlite query @Override public void onCreate(SQLiteDatabase db) { // on below line we are creating // an sqlite query and we are // setting our column names // along with their data types. String query = "CREATE TABLE " + TABLE_NAME + " (" + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_COL + " TEXT," + DURATION_COL + " TEXT," + DESCRIPTION_COL + " TEXT," + TRACKS_COL + " TEXT)"; // at last we are calling a exec sql // method to execute above sql query db.execSQL(query); } // this method is use to add new course to our sqlite database. public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) { // on below line we are creating a variable for // our sqlite database and calling writable method // as we are writing data in our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are creating a // variable for content values. ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // after adding all values we are passing // content values to our table. db.insert(TABLE_NAME, null, values); // at last we are closing our // database after adding database. db.close(); } // we have created a new method for reading all the courses. public ArrayList<CourseModal> readCourses() { // on below line we are creating a // database for reading our database. SQLiteDatabase db = this.getReadableDatabase(); // on below line we are creating a cursor with query to read data from database. Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null); // on below line we are creating a new array list. ArrayList<CourseModal> courseModalArrayList = new ArrayList<>(); // moving our cursor to first position. if (cursorCourses.moveToFirst()) { do { // on below line we are adding the data from cursor to our array list. courseModalArrayList.add(new CourseModal(cursorCourses.getString(1), cursorCourses.getString(4), cursorCourses.getString(2), cursorCourses.getString(3))); } while (cursorCourses.moveToNext()); // moving our cursor to next. } // at last closing our cursor // and returning our array list. cursorCourses.close(); return courseModalArrayList; } // below is the method for updating our courses public void updateCourse(String originalCourseName, String courseName, String courseDescription, String courseTracks, String courseDuration) { // calling a method to get writable database. SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // on below line we are calling a update method to update our database and passing our values. // and we are comparing it with name of our course which is stored in original name variable. db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName}); db.close(); } // below is the method for deleting our course. public void deleteCourse(String courseName) { // on below line we are creating // a variable to write our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are calling a method to delete our // course and we are comparing it with our course name. db.delete(TABLE_NAME, "name=?", new String[]{courseName}); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // this method is called to check if the table exists already. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); }} Step 2: Adding a button to delete our course Navigate to the app > res > layout > activity_update_course.xml file and add a Button inside this layout for deleting a course. Below is the code for that file. XML <!--button for deleting our course--><Button android:id="@+id/idBtnDelete" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Delete Course" android:textAllCaps="false" /> Below is the updated code for the activity_update_course.xml file after adding the above code snippet. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".UpdateCourseActivity"> <!--Edit text to enter course name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter course Name" /> <!--edit text to enter course duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Duration" /> <!--edit text to display course tracks--> <EditText android:id="@+id/idEdtCourseTracks" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Tracks" /> <!--edit text for course description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Description" /> <!--button for updating our course--> <Button android:id="@+id/idBtnUpdateCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Update Course" android:textAllCaps="false" /> <!--button for deleting our course--> <Button android:id="@+id/idBtnDelete" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Delete Course" android:textAllCaps="false" /> </LinearLayout> Step 3: Initializing our button to delete our course Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Java // adding on click listener for delete button to delete our course.deleteCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to delete our course. dbHandler.deleteCourse(courseName); Toast.makeText(UpdateCourseActivity.this, "Deleted the course", Toast.LENGTH_SHORT).show(); Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); }}); Below is the updated code for the UpdateCourseActivity.java file after adding the above code snippet. Java import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class UpdateCourseActivity extends AppCompatActivity { // variables for our edit text, button, strings and dbhandler class. private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt; private Button updateCourseBtn, deleteCourseBtn; private DBHandler dbHandler; String courseName, courseDesc, courseDuration, courseTracks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing all our variables. courseNameEdt = findViewById(R.id.idEdtCourseName); courseTracksEdt = findViewById(R.id.idEdtCourseTracks); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); updateCourseBtn = findViewById(R.id.idBtnUpdateCourse); deleteCourseBtn = findViewById(R.id.idBtnDelete); // on below line we are initialing our dbhandler class. dbHandler = new DBHandler(UpdateCourseActivity.this); // on below lines we are getting data which // we passed in our adapter class. courseName = getIntent().getStringExtra("name"); courseDesc = getIntent().getStringExtra("description"); courseDuration = getIntent().getStringExtra("duration"); courseTracks = getIntent().getStringExtra("tracks"); // setting data to edit text // of our update activity. courseNameEdt.setText(courseName); courseDescriptionEdt.setText(courseDesc); courseTracksEdt.setText(courseTracks); courseDurationEdt.setText(courseDuration); // adding on click listener to our update course button. updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside this method we are calling an update course // method and passing all our edit text values. dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString()); // displaying a toast message that our course has been updated. Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show(); // launching our main activity. Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); } }); // adding on click listener for delete button to delete our course. deleteCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to delete our course. dbHandler.deleteCourse(courseName); Toast.makeText(UpdateCourseActivity.this, "Deleted the course", Toast.LENGTH_SHORT).show(); Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); } }); }} Now run your app and see the output of the app. Make sure to add data to our database before deleting it. Below is the complete project file structure after performing the delete operation: Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Services in Android with Example CardView in Android With Example Content Providers in Android with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24435, "s": 24407, "text": "\n25 Feb, 2021" }, { "code": null, "e": 24692, "s": 24435, "text": "In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database. " }, { "code": null, "e": 24911, "s": 24692, "text": "We will be building a simple application in which we will be deleting the course from our SQLite database in our Android app. A sample video is given below to get an idea about what we are going to do in this article. " }, { "code": null, "e": 24948, "s": 24911, "text": "Step 1: Updating our DBHandler class" }, { "code": null, "e": 25177, "s": 24948, "text": "As we have to delete data from our SQLite database. For that, we have to create a method to delete our data from the SQLite database. Navigate to the app > java > your app’s package name > DBHandler and add the below code to it." }, { "code": null, "e": 25182, "s": 25177, "text": "Java" }, { "code": "// below is the method for deleting our course.public void deleteCourse(String courseName) { // on below line we are creating // a variable to write our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are calling a method to delete our // course and we are comparing it with our course name. db.delete(TABLE_NAME, \"name=?\", new String[]{courseName}); db.close();}", "e": 25631, "s": 25182, "text": null }, { "code": null, "e": 25722, "s": 25631, "text": "Below is the updated code for the DBHandler.java file after adding the above code snippet." }, { "code": null, "e": 25727, "s": 25722, "text": "Java" }, { "code": "import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; public class DBHandler extends SQLiteOpenHelper { // creating a constant variables for our database. // below variable is for our database name. private static final String DB_NAME = \"coursedb\"; // below int is our database version private static final int DB_VERSION = 1; // below variable is for our table name. private static final String TABLE_NAME = \"mycourses\"; // below variable is for our id column. private static final String ID_COL = \"id\"; // below variable is for our course name column private static final String NAME_COL = \"name\"; // below variable id for our course duration column. private static final String DURATION_COL = \"duration\"; // below variable for our course description column. private static final String DESCRIPTION_COL = \"description\"; // below variable is for our course tracks column. private static final String TRACKS_COL = \"tracks\"; // creating a constructor for our database handler. public DBHandler(Context context) { super(context, DB_NAME, null, DB_VERSION); } // below method is for creating a database by running a sqlite query @Override public void onCreate(SQLiteDatabase db) { // on below line we are creating // an sqlite query and we are // setting our column names // along with their data types. String query = \"CREATE TABLE \" + TABLE_NAME + \" (\" + ID_COL + \" INTEGER PRIMARY KEY AUTOINCREMENT, \" + NAME_COL + \" TEXT,\" + DURATION_COL + \" TEXT,\" + DESCRIPTION_COL + \" TEXT,\" + TRACKS_COL + \" TEXT)\"; // at last we are calling a exec sql // method to execute above sql query db.execSQL(query); } // this method is use to add new course to our sqlite database. public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) { // on below line we are creating a variable for // our sqlite database and calling writable method // as we are writing data in our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are creating a // variable for content values. ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // after adding all values we are passing // content values to our table. db.insert(TABLE_NAME, null, values); // at last we are closing our // database after adding database. db.close(); } // we have created a new method for reading all the courses. public ArrayList<CourseModal> readCourses() { // on below line we are creating a // database for reading our database. SQLiteDatabase db = this.getReadableDatabase(); // on below line we are creating a cursor with query to read data from database. Cursor cursorCourses = db.rawQuery(\"SELECT * FROM \" + TABLE_NAME, null); // on below line we are creating a new array list. ArrayList<CourseModal> courseModalArrayList = new ArrayList<>(); // moving our cursor to first position. if (cursorCourses.moveToFirst()) { do { // on below line we are adding the data from cursor to our array list. courseModalArrayList.add(new CourseModal(cursorCourses.getString(1), cursorCourses.getString(4), cursorCourses.getString(2), cursorCourses.getString(3))); } while (cursorCourses.moveToNext()); // moving our cursor to next. } // at last closing our cursor // and returning our array list. cursorCourses.close(); return courseModalArrayList; } // below is the method for updating our courses public void updateCourse(String originalCourseName, String courseName, String courseDescription, String courseTracks, String courseDuration) { // calling a method to get writable database. SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // on below line we are calling a update method to update our database and passing our values. // and we are comparing it with name of our course which is stored in original name variable. db.update(TABLE_NAME, values, \"name=?\", new String[]{originalCourseName}); db.close(); } // below is the method for deleting our course. public void deleteCourse(String courseName) { // on below line we are creating // a variable to write our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are calling a method to delete our // course and we are comparing it with our course name. db.delete(TABLE_NAME, \"name=?\", new String[]{courseName}); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // this method is called to check if the table exists already. db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME); onCreate(db); }}", "e": 31735, "s": 25727, "text": null }, { "code": null, "e": 31780, "s": 31735, "text": "Step 2: Adding a button to delete our course" }, { "code": null, "e": 31942, "s": 31780, "text": "Navigate to the app > res > layout > activity_update_course.xml file and add a Button inside this layout for deleting a course. Below is the code for that file. " }, { "code": null, "e": 31946, "s": 31942, "text": "XML" }, { "code": "<!--button for deleting our course--><Button android:id=\"@+id/idBtnDelete\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Delete Course\" android:textAllCaps=\"false\" />", "e": 32189, "s": 31946, "text": null }, { "code": null, "e": 32292, "s": 32189, "text": "Below is the updated code for the activity_update_course.xml file after adding the above code snippet." }, { "code": null, "e": 32296, "s": 32292, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".UpdateCourseActivity\"> <!--Edit text to enter course name--> <EditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter course Name\" /> <!--edit text to enter course duration--> <EditText android:id=\"@+id/idEdtCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Duration\" /> <!--edit text to display course tracks--> <EditText android:id=\"@+id/idEdtCourseTracks\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Tracks\" /> <!--edit text for course description--> <EditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Description\" /> <!--button for updating our course--> <Button android:id=\"@+id/idBtnUpdateCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Update Course\" android:textAllCaps=\"false\" /> <!--button for deleting our course--> <Button android:id=\"@+id/idBtnDelete\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Delete Course\" android:textAllCaps=\"false\" /> </LinearLayout>", "e": 34303, "s": 32296, "text": null }, { "code": null, "e": 34356, "s": 34303, "text": "Step 3: Initializing our button to delete our course" }, { "code": null, "e": 34473, "s": 34356, "text": "Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. " }, { "code": null, "e": 34478, "s": 34473, "text": "Java" }, { "code": "// adding on click listener for delete button to delete our course.deleteCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to delete our course. dbHandler.deleteCourse(courseName); Toast.makeText(UpdateCourseActivity.this, \"Deleted the course\", Toast.LENGTH_SHORT).show(); Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); }});", "e": 35015, "s": 34478, "text": null }, { "code": null, "e": 35117, "s": 35015, "text": "Below is the updated code for the UpdateCourseActivity.java file after adding the above code snippet." }, { "code": null, "e": 35122, "s": 35117, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class UpdateCourseActivity extends AppCompatActivity { // variables for our edit text, button, strings and dbhandler class. private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt; private Button updateCourseBtn, deleteCourseBtn; private DBHandler dbHandler; String courseName, courseDesc, courseDuration, courseTracks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing all our variables. courseNameEdt = findViewById(R.id.idEdtCourseName); courseTracksEdt = findViewById(R.id.idEdtCourseTracks); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); updateCourseBtn = findViewById(R.id.idBtnUpdateCourse); deleteCourseBtn = findViewById(R.id.idBtnDelete); // on below line we are initialing our dbhandler class. dbHandler = new DBHandler(UpdateCourseActivity.this); // on below lines we are getting data which // we passed in our adapter class. courseName = getIntent().getStringExtra(\"name\"); courseDesc = getIntent().getStringExtra(\"description\"); courseDuration = getIntent().getStringExtra(\"duration\"); courseTracks = getIntent().getStringExtra(\"tracks\"); // setting data to edit text // of our update activity. courseNameEdt.setText(courseName); courseDescriptionEdt.setText(courseDesc); courseTracksEdt.setText(courseTracks); courseDurationEdt.setText(courseDuration); // adding on click listener to our update course button. updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside this method we are calling an update course // method and passing all our edit text values. dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString()); // displaying a toast message that our course has been updated. Toast.makeText(UpdateCourseActivity.this, \"Course Updated..\", Toast.LENGTH_SHORT).show(); // launching our main activity. Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); } }); // adding on click listener for delete button to delete our course. deleteCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to delete our course. dbHandler.deleteCourse(courseName); Toast.makeText(UpdateCourseActivity.this, \"Deleted the course\", Toast.LENGTH_SHORT).show(); Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); } }); }}", "e": 38529, "s": 35122, "text": null }, { "code": null, "e": 38636, "s": 38529, "text": "Now run your app and see the output of the app. Make sure to add data to our database before deleting it. " }, { "code": null, "e": 38720, "s": 38636, "text": "Below is the complete project file structure after performing the delete operation:" }, { "code": null, "e": 38744, "s": 38720, "text": "Technical Scripter 2020" }, { "code": null, "e": 38752, "s": 38744, "text": "Android" }, { "code": null, "e": 38757, "s": 38752, "text": "Java" }, { "code": null, "e": 38776, "s": 38757, "text": "Technical Scripter" }, { "code": null, "e": 38781, "s": 38776, "text": "Java" }, { "code": null, "e": 38789, "s": 38781, "text": "Android" }, { "code": null, "e": 38887, "s": 38789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38896, "s": 38887, "text": "Comments" }, { "code": null, "e": 38909, "s": 38896, "text": "Old Comments" }, { "code": null, "e": 38952, "s": 38909, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 38983, "s": 38952, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 39016, "s": 38983, "text": "Services in Android with Example" }, { "code": null, "e": 39049, "s": 39016, "text": "CardView in Android With Example" }, { "code": null, "e": 39091, "s": 39049, "text": "Content Providers in Android with Example" }, { "code": null, "e": 39106, "s": 39091, "text": "Arrays in Java" }, { "code": null, "e": 39150, "s": 39106, "text": "Split() String method in Java with examples" }, { "code": null, "e": 39172, "s": 39150, "text": "For-each loop in Java" }, { "code": null, "e": 39197, "s": 39172, "text": "Reverse a string in Java" } ]
How to Create an Automated Paper Trading System in 5 minutes | by Low Wei Hong | Towards Data Science
Are you bored of doing same stuff again? Feeling your life is just doing the same thing over and over again? Here is the thing, today I am going to introduce a tool to automate your BORING stuff — Python. Python is perhaps the most easiest language to learn. Because of your acquired Python skill, you will be able not only to increase your productivity, but also focus on work which you will be more interested in. Get Rid of boring stuff using Python is a series so click this link to view the whole series! Let’s get started! I will use an example, paper trading in Singapore stock market as an illustration on how automation could be done. Paper trading allow you to practice investing or trading using virtual money before you really put real money in it. This is a good way to start as to prove whether your strategy works. This is the agenda which I will be sharing: Part 1 — Input the stock code and amount which you want trade in a text file. Part 2 — How to do Web Scraping on your own, the full journey. Part 3 — Clean and tabulate data. Part 4— Output the result into a csv or excel file. Follow the whole journey and you will notice how simple it is to automate your boring stuff and to update your price IN 5 Seconds. Launch a new text file, enter the stock code and the price you will buy given the particular stock, separated by a comma. Launch a new text file, enter the stock code and the price you will buy given the particular stock, separated by a comma as shown This is a snapshot of the SGX website. I am going to illustrate how to scrape all trading information contain in this table. Do open a google chrome, right click on the website and you will be able to see the below snapshot. Click on the inspect button, then click on the network tab (top right corner of the below snapshot as highlighted in purple bracket). Next, click on the row as highlighted in purple box and then choose preview as shown in the highlighted green box, both shown in Snapshot 4 below. So you can see from the Preview, all the data are contained in JSON format. Next, click on the purple box (Headers) in Snapshot 5. What I am doing now, is to inspect what elements I should put in to scrape data from this page. From Snapshot 5 above, you will be able to see Request URL, which is the url you need to put in the request part later. Due to encoding issue, “%2c” in the Request URL will be encoded to “,”. If you are interested in encoding, view this link for more information. Now let’s prepare the required information for you to send a proper request to the server. Part 1 Request Url After changing all the “%2c” to “,”, the request url will turn out to be this link below. https://api.sgx.com/securities/v1.1?excludetypes=bonds&params=nc,adjusted-vwap,b,bv,p,c,change_vs_pc,change_vs_pc_percentage,cx,cn,dp,dpc,du,ed,fn,h,iiv,iopv,lt,l,o,p_,pv,ptd,s,sv,trading_time,v_,v,vl,vwap,vwap-currency Part 2 Headers Request header is a component of a network packet sent by a browser or client to the server to request for a specific page or data on the Web server. Referring to the purple box in Snapshot 6 , this is the header part which you should put in when you are scraping the website. {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36", "Origin": "https://www2.sgx.com", "Referer": "https://www2.sgx.com/securities/securities-prices"} Now let’s put everything together as shown in the gist below. Till now you will have the response in JSON format. we will use Python pandas library to clean the data. First, load in the stock code which you fill in earlier and clean it. with open('selected.txt') as f: selected_sc = f.readlines() selected_sc = [x.replace('\n', '') for x in selected_sc]portfolio = {x.split(',')[0]: float(x.split(',')[1]) for x in selected_sc} Then, load the scraped data into JSON object, then change it to python pandas object. data = json.loads(req.text)['data'] df = pd.DataFrame(data['prices']) Next, rename the column name to be easier to understand. df = df.rename( columns={'b': 'Bid', 'lt': 'Last', 'bv': 'Bid_Volume', 'c': 'Change', 'sv': 'Ask_volume', 'h': 'High', 'l': 'Low', 'o': 'open', 'p': 'Change_percent', 's': 'Ask', 'vl': 'Volume', 'nc': 'Stock_code'}) Finally, filter the interested stock code which you want to invest or trade in and then calculate the price difference. df = df[df['Stock_code'].isin(portfolio.keys())][['Stock_code', 'Last']] df['bought_price'] = df['Stock_code'].map(portfolio) df['percentage_changes'] = (df['Last'] - df['bought_price'])*100 df['percentage_changes'] = df['percentage_changes'].apply( lambda x: '{0:.2f}%'.format(x)) Save the data to csv file and 🎉WE ARE OFFICIALLY DONE! 🎉 df.to_csv('reseult.csv', index=False) Below is the snapshot of the csv file: The full code can be found in here. Happy coding! I am currently working as a Data Scientist, and what I can inform you is that crawling is still very important. Thank you for reading this post. Feel free to leave comments below on topics which you may be interested to know. I will be publishing more posts in future about my experiences and projects. Low Wei Hong is a Data Scientist at Shopee. His experiences involved more on crawling websites, creating data pipeline and also implementing machine learning model on solving business problems. He provides crawling services which is able to provide you the accurate and cleaned data which you need. You can visit this website to view his portfolio and also to contact him for crawling services. You can connect with him on LinkedIn and Medium.
[ { "code": null, "e": 213, "s": 172, "text": "Are you bored of doing same stuff again?" }, { "code": null, "e": 281, "s": 213, "text": "Feeling your life is just doing the same thing over and over again?" }, { "code": null, "e": 588, "s": 281, "text": "Here is the thing, today I am going to introduce a tool to automate your BORING stuff — Python. Python is perhaps the most easiest language to learn. Because of your acquired Python skill, you will be able not only to increase your productivity, but also focus on work which you will be more interested in." }, { "code": null, "e": 682, "s": 588, "text": "Get Rid of boring stuff using Python is a series so click this link to view the whole series!" }, { "code": null, "e": 701, "s": 682, "text": "Let’s get started!" }, { "code": null, "e": 1002, "s": 701, "text": "I will use an example, paper trading in Singapore stock market as an illustration on how automation could be done. Paper trading allow you to practice investing or trading using virtual money before you really put real money in it. This is a good way to start as to prove whether your strategy works." }, { "code": null, "e": 1046, "s": 1002, "text": "This is the agenda which I will be sharing:" }, { "code": null, "e": 1124, "s": 1046, "text": "Part 1 — Input the stock code and amount which you want trade in a text file." }, { "code": null, "e": 1187, "s": 1124, "text": "Part 2 — How to do Web Scraping on your own, the full journey." }, { "code": null, "e": 1221, "s": 1187, "text": "Part 3 — Clean and tabulate data." }, { "code": null, "e": 1273, "s": 1221, "text": "Part 4— Output the result into a csv or excel file." }, { "code": null, "e": 1404, "s": 1273, "text": "Follow the whole journey and you will notice how simple it is to automate your boring stuff and to update your price IN 5 Seconds." }, { "code": null, "e": 1526, "s": 1404, "text": "Launch a new text file, enter the stock code and the price you will buy given the particular stock, separated by a comma." }, { "code": null, "e": 1656, "s": 1526, "text": "Launch a new text file, enter the stock code and the price you will buy given the particular stock, separated by a comma as shown" }, { "code": null, "e": 1695, "s": 1656, "text": "This is a snapshot of the SGX website." }, { "code": null, "e": 1881, "s": 1695, "text": "I am going to illustrate how to scrape all trading information contain in this table. Do open a google chrome, right click on the website and you will be able to see the below snapshot." }, { "code": null, "e": 2015, "s": 1881, "text": "Click on the inspect button, then click on the network tab (top right corner of the below snapshot as highlighted in purple bracket)." }, { "code": null, "e": 2162, "s": 2015, "text": "Next, click on the row as highlighted in purple box and then choose preview as shown in the highlighted green box, both shown in Snapshot 4 below." }, { "code": null, "e": 2293, "s": 2162, "text": "So you can see from the Preview, all the data are contained in JSON format. Next, click on the purple box (Headers) in Snapshot 5." }, { "code": null, "e": 2653, "s": 2293, "text": "What I am doing now, is to inspect what elements I should put in to scrape data from this page. From Snapshot 5 above, you will be able to see Request URL, which is the url you need to put in the request part later. Due to encoding issue, “%2c” in the Request URL will be encoded to “,”. If you are interested in encoding, view this link for more information." }, { "code": null, "e": 2744, "s": 2653, "text": "Now let’s prepare the required information for you to send a proper request to the server." }, { "code": null, "e": 2763, "s": 2744, "text": "Part 1 Request Url" }, { "code": null, "e": 2853, "s": 2763, "text": "After changing all the “%2c” to “,”, the request url will turn out to be this link below." }, { "code": null, "e": 3073, "s": 2853, "text": "https://api.sgx.com/securities/v1.1?excludetypes=bonds&params=nc,adjusted-vwap,b,bv,p,c,change_vs_pc,change_vs_pc_percentage,cx,cn,dp,dpc,du,ed,fn,h,iiv,iopv,lt,l,o,p_,pv,ptd,s,sv,trading_time,v_,v,vl,vwap,vwap-currency" }, { "code": null, "e": 3088, "s": 3073, "text": "Part 2 Headers" }, { "code": null, "e": 3238, "s": 3088, "text": "Request header is a component of a network packet sent by a browser or client to the server to request for a specific page or data on the Web server." }, { "code": null, "e": 3365, "s": 3238, "text": "Referring to the purple box in Snapshot 6 , this is the header part which you should put in when you are scraping the website." }, { "code": null, "e": 3595, "s": 3365, "text": "{\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36\", \"Origin\": \"https://www2.sgx.com\", \"Referer\": \"https://www2.sgx.com/securities/securities-prices\"}" }, { "code": null, "e": 3657, "s": 3595, "text": "Now let’s put everything together as shown in the gist below." }, { "code": null, "e": 3762, "s": 3657, "text": "Till now you will have the response in JSON format. we will use Python pandas library to clean the data." }, { "code": null, "e": 3832, "s": 3762, "text": "First, load in the stock code which you fill in earlier and clean it." }, { "code": null, "e": 4033, "s": 3832, "text": "with open('selected.txt') as f: selected_sc = f.readlines() selected_sc = [x.replace('\\n', '') for x in selected_sc]portfolio = {x.split(',')[0]: float(x.split(',')[1]) for x in selected_sc}" }, { "code": null, "e": 4119, "s": 4033, "text": "Then, load the scraped data into JSON object, then change it to python pandas object." }, { "code": null, "e": 4190, "s": 4119, "text": "data = json.loads(req.text)['data'] df = pd.DataFrame(data['prices']) " }, { "code": null, "e": 4247, "s": 4190, "text": "Next, rename the column name to be easier to understand." }, { "code": null, "e": 4778, "s": 4247, "text": "df = df.rename( columns={'b': 'Bid', 'lt': 'Last', 'bv': 'Bid_Volume', 'c': 'Change', 'sv': 'Ask_volume', 'h': 'High', 'l': 'Low', 'o': 'open', 'p': 'Change_percent', 's': 'Ask', 'vl': 'Volume', 'nc': 'Stock_code'})" }, { "code": null, "e": 4898, "s": 4778, "text": "Finally, filter the interested stock code which you want to invest or trade in and then calculate the price difference." }, { "code": null, "e": 5212, "s": 4898, "text": "df = df[df['Stock_code'].isin(portfolio.keys())][['Stock_code', 'Last']] df['bought_price'] = df['Stock_code'].map(portfolio) df['percentage_changes'] = (df['Last'] - df['bought_price'])*100 df['percentage_changes'] = df['percentage_changes'].apply( lambda x: '{0:.2f}%'.format(x))" }, { "code": null, "e": 5269, "s": 5212, "text": "Save the data to csv file and 🎉WE ARE OFFICIALLY DONE! 🎉" }, { "code": null, "e": 5307, "s": 5269, "text": "df.to_csv('reseult.csv', index=False)" }, { "code": null, "e": 5346, "s": 5307, "text": "Below is the snapshot of the csv file:" }, { "code": null, "e": 5382, "s": 5346, "text": "The full code can be found in here." }, { "code": null, "e": 5396, "s": 5382, "text": "Happy coding!" }, { "code": null, "e": 5508, "s": 5396, "text": "I am currently working as a Data Scientist, and what I can inform you is that crawling is still very important." }, { "code": null, "e": 5699, "s": 5508, "text": "Thank you for reading this post. Feel free to leave comments below on topics which you may be interested to know. I will be publishing more posts in future about my experiences and projects." }, { "code": null, "e": 5893, "s": 5699, "text": "Low Wei Hong is a Data Scientist at Shopee. His experiences involved more on crawling websites, creating data pipeline and also implementing machine learning model on solving business problems." }, { "code": null, "e": 6094, "s": 5893, "text": "He provides crawling services which is able to provide you the accurate and cleaned data which you need. You can visit this website to view his portfolio and also to contact him for crawling services." } ]
Prime numbers and Fibonacci in C++
In this problem, we are given a number n. Our task is to print all prime and Fibonacci numbers less than or equal to n. Let’s take an example to understand the problem Input: n = 30 Output: 2 3 5 13 Explanation Fibonacci numbers less than 30 are : 1 1 2 3 5 8 13 21. Out of these numbers, prime numbers are 2 3 5 13. To solve this problem, we have to check if all numbers of the Fibonacci series less than n is a prime number. For this, we will find all prime numbers less than or equal to n. And check if the generated numbers are contained in the Fibonacci series or not. If a number is in the Fibonacci series, then it is in form 5i2 + 4 or 5i2 - 4. Program to show the implementation of our solution, Live Demo #include <bits/stdc++.h> using namespace std; bool isSquare(int n) { int sr = sqrt(n); return (sr * sr == n); } void printPrimeAndFibnacciNumbers(int n) { bool primeNumbers[n + 1]; memset(primeNumbers, true, sizeof(primeNumbers)); for (int p = 2; p * p <= n; p++) { if (primeNumbers[p] == true) { for (int i = p * 2; i <= n; i += p) primeNumbers[i] = false; } } for (int i=2; i<=n; i++) if (primeNumbers[i] && (isSquare(5*i*i+4) > 0 || isSquare(5*i*i-4) > 0)) cout<<i<<"\t"; } int main() { int N = 50; cout<<"All prime Fibonacci numbers less than "<<N<<" are :\n"; printPrimeAndFibnacciNumbers(N); return 0; } All prime Fibonacci numbers less than 50 are : 23513
[ { "code": null, "e": 1182, "s": 1062, "text": "In this problem, we are given a number n. Our task is to print all prime and Fibonacci numbers less than or equal to n." }, { "code": null, "e": 1230, "s": 1182, "text": "Let’s take an example to understand the problem" }, { "code": null, "e": 1261, "s": 1230, "text": "Input: n = 30\nOutput: 2 3 5 13" }, { "code": null, "e": 1273, "s": 1261, "text": "Explanation" }, { "code": null, "e": 1329, "s": 1273, "text": "Fibonacci numbers less than 30 are : 1 1 2 3 5 8 13 21." }, { "code": null, "e": 1379, "s": 1329, "text": "Out of these numbers, prime numbers are 2 3 5 13." }, { "code": null, "e": 1489, "s": 1379, "text": "To solve this problem, we have to check if all numbers of the Fibonacci series less than n is a prime number." }, { "code": null, "e": 1636, "s": 1489, "text": "For this, we will find all prime numbers less than or equal to n. And check if the generated numbers are contained in the Fibonacci series or not." }, { "code": null, "e": 1715, "s": 1636, "text": "If a number is in the Fibonacci series, then it is in form 5i2 + 4 or 5i2 - 4." }, { "code": null, "e": 1767, "s": 1715, "text": "Program to show the implementation of our solution," }, { "code": null, "e": 1778, "s": 1767, "text": " Live Demo" }, { "code": null, "e": 2463, "s": 1778, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isSquare(int n) {\n int sr = sqrt(n);\n return (sr * sr == n);\n}\nvoid printPrimeAndFibnacciNumbers(int n) {\n bool primeNumbers[n + 1];\n memset(primeNumbers, true, sizeof(primeNumbers));\n for (int p = 2; p * p <= n; p++) {\n if (primeNumbers[p] == true) {\n for (int i = p * 2; i <= n; i += p)\n primeNumbers[i] = false;\n }\n }\n for (int i=2; i<=n; i++)\n if (primeNumbers[i] && (isSquare(5*i*i+4) > 0 || isSquare(5*i*i-4) > 0))\n cout<<i<<\"\\t\";\n}\nint main() {\n int N = 50;\n cout<<\"All prime Fibonacci numbers less than \"<<N<<\" are :\\n\";\n printPrimeAndFibnacciNumbers(N);\n return 0;\n}" }, { "code": null, "e": 2516, "s": 2463, "text": "All prime Fibonacci numbers less than 50 are :\n23513" } ]
Inorder Traversal (Iterative) | Practice | GeeksforGeeks
Given a binary tree. Find the inorder traversal of the tree without using recursion. Example 1 Input: 1 / \ 2 3 / \ 4 5 Output: 4 2 5 1 3 Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3. Example 2 Input: 8 / \ 1 5 \ / \ 7 10 6 \ / 10 6 Output: 1 7 10 8 6 10 5 6 Explanation: Inorder traversal (Left->Root->Right) of the tree is 1 7 10 8 6 10 5 6. Expected time complexity: O(N) Expected auxiliary space: O(N) +1 hanumanmanyam8374 days ago class Solution { // Return a list containing the inorder traversal of the given tree ArrayList<Integer> inOrder(Node root) { // Code ArrayList<Integer>res=new ArrayList<>(); Stack<Node>st=new Stack<>(); while(true) { if(root!=null) { st.push(root); root=root.left; } else { if(st.isEmpty()) { break; } else { root=st.pop(); res.add(root.data); root=root.right; } } } return res; } } 0 scien-terrific3 weeks ago class Solution { public: vector<int> inOrder(Node* root) { //code here vector<int>res; Node* cur=root; while(cur){ if(!cur->left){ res.push_back(cur->data); cur=cur->right; } else{ Node* prev=cur->left; while(prev->right and prev->right!=cur)prev=prev->right; if(!prev->right){ prev->right=cur; cur=cur->left; } else{ prev->right=NULL; res.push_back(cur->data); cur=cur->right; } } } return res; } }; 0 devashishbakare1 month ago Java ArrayList<Integer> inOrder(Node root) { ArrayList<Integer> ans = new ArrayList<>(); if( root == null ) return ans; Stack<Node> stack = new Stack<>(); while( true ) { if( root != null){ //go to the extreme left until not found null and add nodes in stack for making the track of pervious call stack.push(root); root = root.left; } else { //break the loop when stack is empty if(stack.isEmpty()) break; else { //take the item out because its extreme left and passes call to it right for checking for the same root = stack.peek(); stack.pop(); ans.add(root.data); root = root.right; } } } return ans; } } +1 mr_coder99331 month ago vector<int> inOrder(Node* root) { vector<int> ans; stack<Node*> s; Node* node=root; while(true){ if(node){ s.push(node); node=node->left; }else{ if(s.empty()) break; node=s.top(); s.pop(); ans.push_back(node->data); node=node->right; } } return ans; } 0 prabhakarsati294261 month ago def inOrder(self, root): # code here if root is None: return st = [] curr = root while curr!= None: st.append(curr) curr = curr.left while len(st)>0: curr = st.pop() print(curr.data,end=" ") curr = curr.right while curr!=None: st.append(curr) curr = curr.left return st 0 himanshu11042003singh1 month ago SIMPLE C++ SOLUTION:- TIME COMPLEXITY- O(N) SPACE COMPLEXITY- O(1) CODE- class Solution {public: vector<int> inOrder(Node* root) { //code here vector<int>inorder; Node* curr= root; while(curr!=NULL){ if(curr->left==NULL){ inorder.push_back(curr->data); curr= curr->right; } else{ Node* prev= curr->left; while(prev->right&&prev->right!=curr){ prev= prev->right; } if(prev->right==NULL){ prev->right= curr; curr=curr->left; } else{ prev->right=NULL; inorder.push_back(curr->data); curr=curr->right; } } } return inorder; }}; 0 detroix071 month ago vector<int> inOrder(Node* root) { stack<Node*> s; vector<int> v; while(1) { if(root!=NULL){ s.push(root); root=root->left; } else { if(s.size()==0) break; root = s.top(); s.pop(); v.push_back(root->data); root=root->right; } } return v; } -2 imaniket2 months ago vector<int> inOrder(Node* root) { auto node = root; vector<int> ans; if(!root) return ans; stack<Node*> st; while(true){ if(node){ st.push(node); node= node->left; } else{ if(st.empty()) break; node = st.top(); st.pop(); ans.push_back(node->data); node= node->right; } } return ans; } -1 codewithmitesh2 months ago vector<int> inOrder(Node *root) { vector<int> ans; // * step 1 :- Create an empty stack S of datatype BinaryNode stack<Node *> s; // * step 2 :- Initialize current node as root Node *curr = root, *PoppedNode = NULL; while (curr != NULL || (s.empty() == false)) { // * step 3 :- Push the current node to S and set current = current->left until current is NULL while (curr != NULL) { s.push(curr); curr = curr->left; } // * Step 4 (a) :- If current is NULL and stack is not empty then Pop the top item from stack. PoppedNode = s.top(); s.pop(); // * Step 4 (b) :- Print the popped item and set current = popped_item->right ans.push_back(PoppedNode->data); curr = PoppedNode->right; } return ans; } 0 codewithmitesh This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 323, "s": 238, "text": "Given a binary tree. Find the inorder traversal of the tree without using recursion." }, { "code": null, "e": 333, "s": 323, "text": "Example 1" }, { "code": null, "e": 507, "s": 333, "text": "Input:\n 1\n / \\\n 2 3\n / \\\n 4 5\nOutput: 4 2 5 1 3\nExplanation:\nInorder traversal (Left->Root->Right) of \nthe tree is 4 2 5 1 3.\n" }, { "code": null, "e": 517, "s": 507, "text": "Example 2" }, { "code": null, "e": 767, "s": 517, "text": "Input:\n 8\n / \\\n 1 5\n \\ / \\\n 7 10 6\n \\ /\n 10 6\nOutput: 1 7 10 8 6 10 5 6\nExplanation:\nInorder traversal (Left->Root->Right) \nof the tree is 1 7 10 8 6 10 5 6." }, { "code": null, "e": 832, "s": 769, "text": "\nExpected time complexity: O(N)\nExpected auxiliary space: O(N)" }, { "code": null, "e": 835, "s": 832, "text": "+1" }, { "code": null, "e": 862, "s": 835, "text": "hanumanmanyam8374 days ago" }, { "code": null, "e": 1607, "s": 862, "text": "class Solution\n{\n // Return a list containing the inorder traversal of the given tree\n ArrayList<Integer> inOrder(Node root)\n {\n // Code\n ArrayList<Integer>res=new ArrayList<>();\n Stack<Node>st=new Stack<>();\n while(true)\n {\n if(root!=null)\n {\n st.push(root);\n root=root.left;\n }\n else\n {\n if(st.isEmpty())\n {\n break;\n }\n else\n {\n root=st.pop();\n res.add(root.data);\n root=root.right;\n }\n }\n }\n return res;\n }\n \n \n}" }, { "code": null, "e": 1609, "s": 1607, "text": "0" }, { "code": null, "e": 1635, "s": 1609, "text": "scien-terrific3 weeks ago" }, { "code": null, "e": 2372, "s": 1635, "text": "class Solution {\npublic:\n vector<int> inOrder(Node* root)\n {\n //code here\n vector<int>res;\n Node* cur=root;\n while(cur){\n if(!cur->left){\n res.push_back(cur->data);\n cur=cur->right;\n }\n else{\n Node* prev=cur->left;\n while(prev->right and prev->right!=cur)prev=prev->right;\n if(!prev->right){\n prev->right=cur;\n cur=cur->left;\n }\n else{\n prev->right=NULL;\n res.push_back(cur->data);\n cur=cur->right;\n }\n }\n }\n return res;\n }\n};" }, { "code": null, "e": 2374, "s": 2372, "text": "0" }, { "code": null, "e": 2401, "s": 2374, "text": "devashishbakare1 month ago" }, { "code": null, "e": 2407, "s": 2401, "text": "Java " }, { "code": null, "e": 3366, "s": 2409, "text": " ArrayList<Integer> inOrder(Node root) { ArrayList<Integer> ans = new ArrayList<>(); if( root == null ) return ans; Stack<Node> stack = new Stack<>(); while( true ) { if( root != null){ //go to the extreme left until not found null and add nodes in stack for making the track of pervious call stack.push(root); root = root.left; } else { //break the loop when stack is empty if(stack.isEmpty()) break; else { //take the item out because its extreme left and passes call to it right for checking for the same root = stack.peek(); stack.pop(); ans.add(root.data); root = root.right; } } } return ans; } }" }, { "code": null, "e": 3369, "s": 3366, "text": "+1" }, { "code": null, "e": 3393, "s": 3369, "text": "mr_coder99331 month ago" }, { "code": null, "e": 3849, "s": 3393, "text": "vector<int> inOrder(Node* root)\n {\n vector<int> ans;\n stack<Node*> s;\n Node* node=root;\n while(true){\n if(node){\n s.push(node);\n node=node->left;\n }else{\n if(s.empty()) break;\n node=s.top();\n s.pop();\n ans.push_back(node->data);\n node=node->right;\n }\n }\n return ans;\n }" }, { "code": null, "e": 3851, "s": 3849, "text": "0" }, { "code": null, "e": 3881, "s": 3851, "text": "prabhakarsati294261 month ago" }, { "code": null, "e": 4319, "s": 3883, "text": "def inOrder(self, root): # code here if root is None: return st = [] curr = root while curr!= None: st.append(curr) curr = curr.left while len(st)>0: curr = st.pop() print(curr.data,end=\" \") curr = curr.right while curr!=None: st.append(curr) curr = curr.left return st" }, { "code": null, "e": 4321, "s": 4319, "text": "0" }, { "code": null, "e": 4354, "s": 4321, "text": "himanshu11042003singh1 month ago" }, { "code": null, "e": 4376, "s": 4354, "text": "SIMPLE C++ SOLUTION:-" }, { "code": null, "e": 4398, "s": 4376, "text": "TIME COMPLEXITY- O(N)" }, { "code": null, "e": 4421, "s": 4398, "text": "SPACE COMPLEXITY- O(1)" }, { "code": null, "e": 4427, "s": 4421, "text": "CODE-" }, { "code": null, "e": 5194, "s": 4427, "text": "class Solution {public: vector<int> inOrder(Node* root) { //code here vector<int>inorder; Node* curr= root; while(curr!=NULL){ if(curr->left==NULL){ inorder.push_back(curr->data); curr= curr->right; } else{ Node* prev= curr->left; while(prev->right&&prev->right!=curr){ prev= prev->right; } if(prev->right==NULL){ prev->right= curr; curr=curr->left; } else{ prev->right=NULL; inorder.push_back(curr->data); curr=curr->right; } } } return inorder; }};" }, { "code": null, "e": 5196, "s": 5194, "text": "0" }, { "code": null, "e": 5217, "s": 5196, "text": "detroix071 month ago" }, { "code": null, "e": 5606, "s": 5217, "text": "vector<int> inOrder(Node* root) { stack<Node*> s; vector<int> v; while(1) { if(root!=NULL){ s.push(root); root=root->left; } else { if(s.size()==0) break; root = s.top(); s.pop(); v.push_back(root->data); root=root->right; } } return v; }" }, { "code": null, "e": 5609, "s": 5606, "text": "-2" }, { "code": null, "e": 5630, "s": 5609, "text": "imaniket2 months ago" }, { "code": null, "e": 6139, "s": 5630, "text": "vector<int> inOrder(Node* root)\n {\n auto node = root;\n vector<int> ans;\n if(!root) return ans;\n stack<Node*> st;\n while(true){\n if(node){\n st.push(node);\n node= node->left;\n }\n else{\n if(st.empty()) break;\n node = st.top();\n st.pop();\n ans.push_back(node->data);\n node= node->right;\n }\n }\n return ans;\n }" }, { "code": null, "e": 6142, "s": 6139, "text": "-1" }, { "code": null, "e": 6169, "s": 6142, "text": "codewithmitesh2 months ago" }, { "code": null, "e": 7008, "s": 6169, "text": "vector<int> inOrder(Node *root)\n{\n vector<int> ans;\n\n // * step 1 :- Create an empty stack S of datatype BinaryNode\n stack<Node *> s;\n // * step 2 :- Initialize current node as root\n Node *curr = root, *PoppedNode = NULL;\n\n while (curr != NULL || (s.empty() == false))\n {\n // * step 3 :- Push the current node to S and set current = current->left until current is NULL\n while (curr != NULL)\n {\n s.push(curr);\n curr = curr->left;\n }\n // * Step 4 (a) :- If current is NULL and stack is not empty then Pop the top item from stack.\n PoppedNode = s.top();\n s.pop();\n // * Step 4 (b) :- Print the popped item and set current = popped_item->right\n ans.push_back(PoppedNode->data);\n curr = PoppedNode->right;\n }\n return ans;\n}" }, { "code": null, "e": 7010, "s": 7008, "text": "0" }, { "code": null, "e": 7025, "s": 7010, "text": "codewithmitesh" }, { "code": null, "e": 7051, "s": 7025, "text": "This comment was deleted." }, { "code": null, "e": 7197, "s": 7051, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7233, "s": 7197, "text": " Login to access your submissions. " }, { "code": null, "e": 7243, "s": 7233, "text": "\nProblem\n" }, { "code": null, "e": 7253, "s": 7243, "text": "\nContest\n" }, { "code": null, "e": 7316, "s": 7253, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7464, "s": 7316, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7672, "s": 7464, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7778, "s": 7672, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to convert a nested OrderedDict to dict? - GeeksforGeeks
23 Nov, 2021 In this article, we will discuss how to convert a nested OrderedDict to dict? Before this we must go through some concepts: Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in the dictionary to make it more optimized. An OrderedDict is a dictionary subclass that remembers the order in that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order. By contrast, the order in the items are inserted is remembered by OrderedDict. To define the nested OrderedDict, we are using the collections module in python. Python3 #import packagefrom collections import OrderedDict # define OrderedDictod1 = OrderedDict([('1', 'one'), ('2', 'two')])print(type(od1))print(od1) # define nested OrderedDictod2 = OrderedDict([('1', 'one'), ('2', OrderedDict([('-2', '-ive'), ('+2', '+ive')]))])print(type(od2))print(od2) Output: <class ‘collections.OrderedDict’> OrderedDict([(‘1’, ‘one’), (‘2’, ‘two’)]) <class ‘collections.OrderedDict’> OrderedDict([(‘1’, ‘one’), (‘2’, OrderedDict([(‘-2’, ‘-ive’), (‘+2’, ‘+ive’)]))]) We can convert the OrderedDict to dict in just one line, but this is for only simple OrderedDict, not for the nested OrderedDict. Python3 # import packagefrom collections import OrderedDict # define OrderedDictod1 = OrderedDict([('1', 'one'), ('2', 'two')]) # convert to dictod1 = dict(od1) # display dictionaryprint(type(od1))print(od1) Output: <class 'dict'> {'1': 'one', '2': 'two'} So, to convert nested OrderedDict to dict, we are using json.loads() and json.dumps() methods. The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python. The json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary. The json.dumps() function converts a Python object into a json string. Python3 # import packagefrom collections import OrderedDictimport json # define nested OrderedDictod2 = OrderedDict([('1', 'one'), ('2', OrderedDict([('-2', '-ive'), ('+2', '+ive')]))])# convert to dictod2 = json.loads(json.dumps(od2)) # display deictionaryprint(type(od2))print(od2) Output: <class 'dict'> {'1': 'one', '2': {'-2': '-ive', '+2': '+ive'}} ddeevviissaavviittaa Picked Python collections-module python-dict Python python-dict 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 Python | os.path.join() method Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Nov, 2021" }, { "code": null, "e": 24416, "s": 24292, "text": "In this article, we will discuss how to convert a nested OrderedDict to dict? Before this we must go through some concepts:" }, { "code": null, "e": 24698, "s": 24416, "text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in the dictionary to make it more optimized." }, { "code": null, "e": 24797, "s": 24698, "text": "An OrderedDict is a dictionary subclass that remembers the order in that keys were first inserted." }, { "code": null, "e": 25108, "s": 24797, "text": "The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order. By contrast, the order in the items are inserted is remembered by OrderedDict." }, { "code": null, "e": 25189, "s": 25108, "text": "To define the nested OrderedDict, we are using the collections module in python." }, { "code": null, "e": 25197, "s": 25189, "text": "Python3" }, { "code": "#import packagefrom collections import OrderedDict # define OrderedDictod1 = OrderedDict([('1', 'one'), ('2', 'two')])print(type(od1))print(od1) # define nested OrderedDictod2 = OrderedDict([('1', 'one'), ('2', OrderedDict([('-2', '-ive'), ('+2', '+ive')]))])print(type(od2))print(od2)", "e": 25614, "s": 25197, "text": null }, { "code": null, "e": 25622, "s": 25614, "text": "Output:" }, { "code": null, "e": 25656, "s": 25622, "text": "<class ‘collections.OrderedDict’>" }, { "code": null, "e": 25698, "s": 25656, "text": "OrderedDict([(‘1’, ‘one’), (‘2’, ‘two’)])" }, { "code": null, "e": 25732, "s": 25698, "text": "<class ‘collections.OrderedDict’>" }, { "code": null, "e": 25814, "s": 25732, "text": "OrderedDict([(‘1’, ‘one’), (‘2’, OrderedDict([(‘-2’, ‘-ive’), (‘+2’, ‘+ive’)]))])" }, { "code": null, "e": 25944, "s": 25814, "text": "We can convert the OrderedDict to dict in just one line, but this is for only simple OrderedDict, not for the nested OrderedDict." }, { "code": null, "e": 25952, "s": 25944, "text": "Python3" }, { "code": "# import packagefrom collections import OrderedDict # define OrderedDictod1 = OrderedDict([('1', 'one'), ('2', 'two')]) # convert to dictod1 = dict(od1) # display dictionaryprint(type(od1))print(od1)", "e": 26152, "s": 25952, "text": null }, { "code": null, "e": 26160, "s": 26152, "text": "Output:" }, { "code": null, "e": 26200, "s": 26160, "text": "<class 'dict'>\n{'1': 'one', '2': 'two'}" }, { "code": null, "e": 26296, "s": 26200, "text": "So, to convert nested OrderedDict to dict, we are using json.loads() and json.dumps() methods. " }, { "code": null, "e": 26754, "s": 26296, "text": "The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python." }, { "code": null, "e": 26983, "s": 26754, "text": "The json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary." }, { "code": null, "e": 27054, "s": 26983, "text": "The json.dumps() function converts a Python object into a json string." }, { "code": null, "e": 27062, "s": 27054, "text": "Python3" }, { "code": "# import packagefrom collections import OrderedDictimport json # define nested OrderedDictod2 = OrderedDict([('1', 'one'), ('2', OrderedDict([('-2', '-ive'), ('+2', '+ive')]))])# convert to dictod2 = json.loads(json.dumps(od2)) # display deictionaryprint(type(od2))print(od2)", "e": 27469, "s": 27062, "text": null }, { "code": null, "e": 27477, "s": 27469, "text": "Output:" }, { "code": null, "e": 27540, "s": 27477, "text": "<class 'dict'>\n{'1': 'one', '2': {'-2': '-ive', '+2': '+ive'}}" }, { "code": null, "e": 27561, "s": 27540, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 27568, "s": 27561, "text": "Picked" }, { "code": null, "e": 27594, "s": 27568, "text": "Python collections-module" }, { "code": null, "e": 27606, "s": 27594, "text": "python-dict" }, { "code": null, "e": 27613, "s": 27606, "text": "Python" }, { "code": null, "e": 27625, "s": 27613, "text": "python-dict" }, { "code": null, "e": 27723, "s": 27625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27755, "s": 27723, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27797, "s": 27755, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27853, "s": 27797, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27895, "s": 27853, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27926, "s": 27895, "text": "Python | os.path.join() method" }, { "code": null, "e": 27948, "s": 27926, "text": "Defaultdict in Python" }, { "code": null, "e": 28003, "s": 27948, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28042, "s": 28003, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28071, "s": 28042, "text": "Create a directory in Python" } ]
C++ Program For Deleting A Given Node In Linked List Under Given Constraints - GeeksforGeeks
20 Dec, 2021 Given a Singly Linked List, write a function to delete a given node. Your function must follow the following constraints: It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global.It should not return a pointer to the head node.It should not accept pointer to pointer to the head node. It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global. It should not return a pointer to the head node. It should not accept pointer to pointer to the head node. You may assume that the Linked List never becomes empty.Let the function name be deleteNode(). In a straightforward implementation, the function needs to modify the head pointer when the node to be deleted is the first node. As discussed in previous post, when a function modifies the head pointer, the function must use one of the given approaches, we can’t use any of those approaches here. Solution: We explicitly handle the case when the node to be deleted is the first node, we copy the data of the next node to head and delete the next node. The cases when a deleted node is not the head node can be handled normally by finding the previous node and changing the next of the previous node. The following are the implementation. C++ // C++ program to delete a given node// in linked list under given constraints#include <bits/stdc++.h>using namespace std; // Structure of a linked list // node class Node { public: int data; Node *next; }; void deleteNode(Node *head, Node *n) { // When node to be deleted is // head node if(head == n) { if(head->next == NULL) { cout << "There is only one node." << " The list can't be made empty "; return; } // Copy the data of next node // to head head->data = head->next->data; // Store address of next node n = head->next; // Remove the link of next node head->next = head->next->next; // Free memory free(n); return; } // When not first node, follow // the normal deletion process // Find the previous node Node *prev = head; while(prev->next != NULL && prev->next != n) prev = prev->next; // Check if node really exists in // Linked List if(prev->next == NULL) { cout << "Given node is not present in Linked List"; return; } // Remove node from Linked List prev->next = prev->next->next; // Free memory free(n); return; } /* Utility function to insert a node at the beginning */void push(Node **head_ref, int new_data) { Node *new_node = new Node(); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node; } /* Utility function to print a linked list */void printList(Node *head) { while(head != NULL) { cout << head->data << " "; head = head->next; } cout << endl;} // Driver codeint main() { Node *head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head,3); push(&head,2); push(&head,6); push(&head,5); push(&head,11); push(&head,10); push(&head,15); push(&head,12); cout << "Given Linked List: "; printList(head); /* Let us delete the node with value 10 */ cout << "Deleting node " << head->next->next->data << " "; deleteNode(head, head->next->next); cout << "Modified Linked List: "; printList(head); // Let us delete the first node cout << "Deleting first node "; deleteNode(head, head); cout << "Modified Linked List: "; printList(head); return 0; } // This code is contributed by rathbhupendra Output: Given Linked List: 12 15 10 11 5 6 2 3 Deleting node 10: Modified Linked List: 12 15 11 5 6 2 3 Deleting first node Modified Linked List: 15 11 5 6 2 3 Please refer complete article on Delete a given node in Linked List under given constraints for more details! Linked Lists C++ C++ Programs Linked List Linked List 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++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character C++ program for hashing with chaining
[ { "code": null, "e": 23785, "s": 23757, "text": "\n20 Dec, 2021" }, { "code": null, "e": 23908, "s": 23785, "text": "Given a Singly Linked List, write a function to delete a given node. Your function must follow the following constraints: " }, { "code": null, "e": 24174, "s": 23908, "text": "It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global.It should not return a pointer to the head node.It should not accept pointer to pointer to the head node." }, { "code": null, "e": 24335, "s": 24174, "text": "It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global." }, { "code": null, "e": 24384, "s": 24335, "text": "It should not return a pointer to the head node." }, { "code": null, "e": 24442, "s": 24384, "text": "It should not accept pointer to pointer to the head node." }, { "code": null, "e": 25176, "s": 24442, "text": "You may assume that the Linked List never becomes empty.Let the function name be deleteNode(). In a straightforward implementation, the function needs to modify the head pointer when the node to be deleted is the first node. As discussed in previous post, when a function modifies the head pointer, the function must use one of the given approaches, we can’t use any of those approaches here. Solution: We explicitly handle the case when the node to be deleted is the first node, we copy the data of the next node to head and delete the next node. The cases when a deleted node is not the head node can be handled normally by finding the previous node and changing the next of the previous node. The following are the implementation." }, { "code": null, "e": 25180, "s": 25176, "text": "C++" }, { "code": "// C++ program to delete a given node// in linked list under given constraints#include <bits/stdc++.h>using namespace std; // Structure of a linked list // node class Node { public: int data; Node *next; }; void deleteNode(Node *head, Node *n) { // When node to be deleted is // head node if(head == n) { if(head->next == NULL) { cout << \"There is only one node.\" << \" The list can't be made empty \"; return; } // Copy the data of next node // to head head->data = head->next->data; // Store address of next node n = head->next; // Remove the link of next node head->next = head->next->next; // Free memory free(n); return; } // When not first node, follow // the normal deletion process // Find the previous node Node *prev = head; while(prev->next != NULL && prev->next != n) prev = prev->next; // Check if node really exists in // Linked List if(prev->next == NULL) { cout << \"Given node is not present in Linked List\"; return; } // Remove node from Linked List prev->next = prev->next->next; // Free memory free(n); return; } /* Utility function to insert a node at the beginning */void push(Node **head_ref, int new_data) { Node *new_node = new Node(); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node; } /* Utility function to print a linked list */void printList(Node *head) { while(head != NULL) { cout << head->data << \" \"; head = head->next; } cout << endl;} // Driver codeint main() { Node *head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head,3); push(&head,2); push(&head,6); push(&head,5); push(&head,11); push(&head,10); push(&head,15); push(&head,12); cout << \"Given Linked List: \"; printList(head); /* Let us delete the node with value 10 */ cout << \"Deleting node \" << head->next->next->data << \" \"; deleteNode(head, head->next->next); cout << \"Modified Linked List: \"; printList(head); // Let us delete the first node cout << \"Deleting first node \"; deleteNode(head, head); cout << \"Modified Linked List: \"; printList(head); return 0; } // This code is contributed by rathbhupendra", "e": 27760, "s": 25180, "text": null }, { "code": null, "e": 27768, "s": 27760, "text": "Output:" }, { "code": null, "e": 27922, "s": 27768, "text": "Given Linked List: 12 15 10 11 5 6 2 3\n\nDeleting node 10:\nModified Linked List: 12 15 11 5 6 2 3\n\nDeleting first node\nModified Linked List: 15 11 5 6 2 3" }, { "code": null, "e": 28032, "s": 27922, "text": "Please refer complete article on Delete a given node in Linked List under given constraints for more details!" }, { "code": null, "e": 28045, "s": 28032, "text": "Linked Lists" }, { "code": null, "e": 28049, "s": 28045, "text": "C++" }, { "code": null, "e": 28062, "s": 28049, "text": "C++ Programs" }, { "code": null, "e": 28074, "s": 28062, "text": "Linked List" }, { "code": null, "e": 28086, "s": 28074, "text": "Linked List" }, { "code": null, "e": 28090, "s": 28086, "text": "CPP" }, { "code": null, "e": 28188, "s": 28090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28197, "s": 28188, "text": "Comments" }, { "code": null, "e": 28210, "s": 28197, "text": "Old Comments" }, { "code": null, "e": 28238, "s": 28210, "text": "Operator Overloading in C++" }, { "code": null, "e": 28262, "s": 28238, "text": "Sorting a vector in C++" }, { "code": null, "e": 28282, "s": 28262, "text": "Polymorphism in C++" }, { "code": null, "e": 28315, "s": 28282, "text": "Friend class and function in C++" }, { "code": null, "e": 28359, "s": 28315, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 28394, "s": 28359, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 28420, "s": 28394, "text": "C++ Program for QuickSort" }, { "code": null, "e": 28479, "s": 28420, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 28523, "s": 28479, "text": "Program to print ASCII Value of a character" } ]
SL4A - Quick Guide
Android is a Linux based operating system, designed primarily for portable devices like smartphones and tablet. Android is more than an operating system. It is a software stack that provides many features for users, developers and manufacturers. It is open source and business friendly. The user can choose to replace built-in applications with applications of their choice. Many versions of Android have been released since its original release. The Android software stack comprises of different layers, each layer manifesting well-defined behavior and providing specific services to the layer above it. The following figure presents a broad architecture of Android with its primary components. Android is built on the Linux kernel code modified to run on embedded systems as against the traditional Linux system. Hardware drivers for many common devices are built into the kernel, thereby ensuring device portability. It is based on secure user based permission model, which prevents one application from reading another application’s information or from interfering with its execution (e.g. CPU, memory, devices etc.). Group ID based access to networking and Bluetooth features, logger, alarm, power management, low memory killer, Binder IPC mechanisms are a few noted enhancements to the Kernel. This forms the second layer of the architecture. It includes a set of hardware optimized C, C++ libraries, also referred to as the native layer. Examples include Media Libraries, SQLite, SSL, Bionic, WebKit etc. The Android Runtime comprises of two different components − the Dalvik VM and Core Libraries. The Dalvik VM provides an execution environment for the applications on the Android Platform. The set of core libraries provides most of the functionality available in Java APIs. This layer makes available the Libraries as services to the applications. Some most important components within this layer include Location Manager, Resource Manager, Activity Manager and Notification Manager. By default, Android comes with a rich set of applications, including the browser, SMS program, calendar, contact manager, maps etc. Google Play provides alternatives to these applications, if the user desires so. An application can interface with the system with four function blocks. They are as follows − Activities − Activities represent a single screen that the user sees or interacts with visually. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Activities − Activities represent a single screen that the user sees or interacts with visually. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Services − A majority of processing is done by these services for your application. It is the logic behind the user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity. Services − A majority of processing is done by these services for your application. It is the logic behind the user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity. Broadcast Receivers − A component that can be registered to listen for system or application events and issue notifications about the same. An instance for broadcast originating from the system is a ‘low battery notification’ while an application level broadcast could be a ‘download successful’ notification. Broadcast Receivers − A component that can be registered to listen for system or application events and issue notifications about the same. An instance for broadcast originating from the system is a ‘low battery notification’ while an application level broadcast could be a ‘download successful’ notification. Content Providers − A content provider manages and helps you share data between multiple applications. For e.g. a content provider may be used to share the contacts data. Content Providers − A content provider manages and helps you share data between multiple applications. For e.g. a content provider may be used to share the contacts data. These components interact with each other through messages called Intents. Android scripting is a handy tool for simple tasks such as automation and prototyping as against using the Java programming language for the same. The Scripting Layer for Android (SL4A) provides a platform for multiple scripting solutions on the android platform. The Scripting Layer for Android (SL4A) is a library that provides a platform to write simple scripts to automate tasks on an android device using languages other than JAVA. SL4A, originally called Android Scripting Environment (ASE), was first announced on the Google Open Source blog in June 2009. The project saw the light of the day primarily through the efforts of Damon Kohler and it has grown through the contributions of other developers. It supports most popular scripting languages. These include − Beanshell 2.0b4 JRuby 1.4 Lua 5.1.4 Perl 5.10.1 PHP 5.3.3 Python Rhino 1.7R2 Javascript TCL One of the first questions one would probably ask is, “Why use SL4A instead of Java?” Firstly, not everyone is a fan of Java. Scripting languages provide an easy programming environment as compared to Java. Secondly, the language requires the use of an edit/compile/run design loop. This means that you edit, re-compile and then run the application each time you desire some modification. On the contrary, scripts are interpreted and executed on the fly. Moreover, SL4A even makes it possible, in many cases, to reuse code written for a desktop environment. The following figure illustrates scripts written in Python targeting SL4A and in Java respectively. SL4A has three main components. They are as follows − Script Interpreters Android RPC Client Facades In this chapter, we will discuss more about these three components. SL4A acts a scripting host. It supports many scripting languages such as Python, Ruby, Lua, BeanShell, JavaScript and TCL . SL4A can be extended by incorporating new scripting languages dynamically by developing a new SL4A interpreter for that scripting language. Each script runs in its own interpreter instance. Hence, multiple scripts can run simultaneously without affecting each other. Scripts running within the interpreter instance communicates with the SL4A application through the Android Proxy RPC Client. The client establishes a Remote Procedure Call (RPC) connection to SL4A, and allows scripts to interact with the Android Framework. The SL4A facades facilitate this communication. Data is sent as JSON payloads. Android RPC clients are provided for every supported scripting language. The client modules can be obtained from the SL4A website at https://code.google.com. The façade simplifies the script’s access to the underlying Android API. SL4A exposes the Android Framework API to scripts through an extensive set of facades like AndroidFacade, BluetoothFacade, ActivityManagerFacade, CommonIntentsFacade, etc. SL4A functionality offers a basket of rich functionalities like Camera, Location, Battery Manager, Media Player, Media Recorder and many more. The SL4A system is suited for the following kinds of tasks − RAD programming − With SL4A, it is possible to use Rapid Application Development (RAD) approach to create a prototype application quickly. You can create a full-blown Android application if the feasibility of the idea is confirmed. RAD programming − With SL4A, it is possible to use Rapid Application Development (RAD) approach to create a prototype application quickly. You can create a full-blown Android application if the feasibility of the idea is confirmed. Test scripts − It can be used to write test scripts. Test scripts − It can be used to write test scripts. Building Utilities − Utility scripts or tools that perform small tasks or automate certain aspects of repetitive tasks can be built using SL4A. Building Utilities − Utility scripts or tools that perform small tasks or automate certain aspects of repetitive tasks can be built using SL4A. Python has a standard library, which includes a wide variety of routines that help you code and reuse these codes easily. A Module is a Python file that has definitions of variables and a set of related routines or functions. Some of the core Modules provided by the Python library are as follows − Built-in Functions and Exceptions − Python imports both these modules when it starts up and makes their content available for all programs. The built-in module defines built-in functions like len, int, range, while the exceptions module defines all built-in exceptions. Built-in Functions and Exceptions − Python imports both these modules when it starts up and makes their content available for all programs. The built-in module defines built-in functions like len, int, range, while the exceptions module defines all built-in exceptions. Operating System Interface Modules − The OS module makes available, the functions that enables performing OS level operations through scripts. Operating System Interface Modules − The OS module makes available, the functions that enables performing OS level operations through scripts. Type Support Modules − Type support modules include string module-to implement, commonly used string operations; math module provides mathematical operations etc. Type Support Modules − Type support modules include string module-to implement, commonly used string operations; math module provides mathematical operations etc. Regular Expressions − Regular Expressions are string patterns written in a specific syntax, which can be used to match or extract strings or substrings. The re module provides Regex support for Python. Regular Expressions − Regular Expressions are string patterns written in a specific syntax, which can be used to match or extract strings or substrings. The re module provides Regex support for Python. Language Support Modules − The sys module gives you access to various interpreter variables, such as the module search path, and the interpreter version. The operator module provides functional equivalents to many built-in operators. The copy module allows you to copy objects. Finally, the gc module gives you more control over the garbage collector facilities in python 2.0. Language Support Modules − The sys module gives you access to various interpreter variables, such as the module search path, and the interpreter version. The operator module provides functional equivalents to many built-in operators. The copy module allows you to copy objects. Finally, the gc module gives you more control over the garbage collector facilities in python 2.0. The JavaScript Object Notation (JSON) is a data-interchange format. Though many programming languages support JSON, it is especially useful for JavaScript-based apps, including websites and browser extensions. JSON can represent numbers, Booleans, strings, null, arrays (ordered sequences of values), and objects (string-value mappings) made up of these values (or of other arrays and objects). This chapter details the procedure to set up your development environment. It also discusses how to configure your device to use SL4A. You must download and install several pre-requisites before you can start developing with SL4A. To begin with, you should have a recent version of JDK (JDK 5 or upwards) installed on your system. To confirm that a compatible version of the JDK installed available to the environment, execute the following on the command line or console terminal, as follows − $javac –version $java –version Note − Set the PATH environment variable to jdk/bin folder It is likely that Python is installed on Mac OS X and Linux, by default. Windows OS, by default, does not have Python installed. Python can be downloaded from http://python.org. Once installed, modify your Windows path to add the Python directory. To verify if Python is installed on your system, open the terminal window and enter Python. The only additional file that one needs to download is the android.py file. Include a copy of this file under /Lib/site-packages in the Python installation directory. This file includes python modules for Android development. A number of tools are provided with the Android SDK. The first step is to download the appropriate install file for your operating system. Installers for Mac OS X, Linux and Windows are available. The SDK installer can be found at https://developer.android.com/sdk. The development environment discussed here is Windows. Google provides a zip file and an executable to install SDK on Windows. Eclipse was developed as an extensible, Integrated Development Environment (IDE) written in Java language. It requires an installation of Java to work. Eclipse comes in many flavors − Classic, Galelio, Luno, Mars, Neon, etc. It is distributed in a single .zip file. All you have to do is unpack the program contents. The extracted folder has an Eclipse.exe file. Double click the file to start the program. At times, you may want to write scripts on the device and execute them. The Scripting Layer for Android helps achieve the same. To install SL4A on your device, follow the steps given below − Download the SL4A.apk file on your device. Download the SL4A.apk file on your device. Launch the .apk file from the notifications screen. Launch the .apk file from the notifications screen. Select Install on the next screen to actually install SL4A. Select Install on the next screen to actually install SL4A. Alternatively, if you choose to use an emulator as against an android device, install SL4A using the browser inside the emulator. The SL4A installation initial screen on a device is shown below. To install the python interpreter on a device, follow the steps given below − Step 1 − Start the SL4A application. Step 1 − Start the SL4A application. Step 2 − Click the Menu button. Step 2 − Click the Menu button. Step 3 − A list of options will be displayed. Select View. Step 3 − A list of options will be displayed. Select View. Step 4 − Select the Interpreter option from the dialog box. Click Add. Step 4 − Select the Interpreter option from the dialog box. Click Add. Step 5 − A list of interpreters available for download is displayed. Select Python 2.62 (or greater). Step 5 − A list of interpreters available for download is displayed. Select Python 2.62 (or greater). To install python interpreter on an emulator, follow the steps given below − Step 1 − Ensure that the emulator is running in the background. Step 1 − Ensure that the emulator is running in the background. Step 2 − Download python_for_android_rx.apk. Step 2 − Download python_for_android_rx.apk. Step 3 − In the terminal command-line shell, navigate to the location where the apk file is stored and type the following on the command line − Step 3 − In the terminal command-line shell, navigate to the location where the apk file is stored and type the following on the command line − adb install python_for_android_rx.apk SL4A supports scripting engine for multiple languages. A list of some language specific apk files are mentioned below − beanshell_for_android_rx.apk jruby_for_android_rx.apk lua_for_android_rx.apk perl_for_android_rx.apk python_for_android_rx.apk rhino_for_android_rx.apk Step 1 − Download and Install the USB Driver for Windows. Step 2 − Setup your device − Start SL4A from All apps screen on the device. Start SL4A from All apps screen on the device. Tap the Menu button → View. Tap the Menu button → View. Choose the interpreters from the list. Choose the interpreters from the list. Tap the Menu button → Start Server. Tap the Menu button → Start Server. Select Public (to connect over Wi-Fi) or Private(to connect over USB). Select Public (to connect over Wi-Fi) or Private(to connect over USB). Step 3 − Add an environment variable (User variable) AP_PORT and value 9999. Android SDK and Eclipse have been discussed in the subsequent chapters. A software development kit that enables developers to create applications for the Android platform. The Android SDK includes sample projects with source code, development tools, an emulator, and required libraries to build Android applications. This chapter discusses the Android SDK and ways to use it for developing the code targeted at SL4A. The directory tree where you installed the Android SDK, contains a list of folders containing documentation, sample code and a number of tools. Navigating to the tools subdirectory reveals a number of executable files. Discussed below are some important components within the Android SDK. The Android SDK Manager separates the SDK tools, platforms, and other components into packages for easy access and management. The SDK can be configured to check for new or updated SDK packages and add-on tools. By default, Android Studio does not check for Android SDK updates. To enable automatic Android SDK checking − Step 1 − Choose File → Settings → Appearance & Behavior → System Settings → Updates. Step 1 − Choose File → Settings → Appearance & Behavior → System Settings → Updates. Step 2 − Check the Automatically check updates for Android SDK checkbox and select an update channel. Step 2 − Check the Automatically check updates for Android SDK checkbox and select an update channel. Step 3 − Click OK or Apply to enable the update checking. Step 3 − Click OK or Apply to enable the update checking. The SDK Update Sites tab displays the sites that Android Studio checks for Android SDK and third-party updates. You can add other sites that host their own Android SDK addons, then download the SDK add-ons from those sites. The AVD Manager provides a graphical user interface in which you can create and manage Android Virtual Devices (AVDs), which are required by the Android Emulator. An Android Virtual Device (AVD) consists of a number of files including configuration and virtual storage required by the emulator. You can create as many AVDs as you want for simulating different devices. The following steps can be used to create an AVD in Eclipse − Step 1 − Select Window → AVD Manager. Step 1 − Select Window → AVD Manager. Step 2 − Click New. Step 2 − Click New. Step 3 − Type the name of the AVD, choose the target and specify values for the other features. Step 3 − Type the name of the AVD, choose the target and specify values for the other features. Step 4 − Click Create AVD. Step 4 − Click Create AVD. For devices with keyboard, there is a standard set of mappings from the host keyboard to actions on the device. The default Emulator key mappings are − You can change these settings by editing the default.keyset file in the .android subdirectory. ADB, Android Debug Bridge, is a command-line utility included with Google’s Android SDK. ADB can control your device over USB from a computer, copy files back and forth, install and uninstall apps, run shell commands, and more. If you have an emulator running and a real device connected, you must specify where you want the ADB commands to a real device, use the option − d and for the emulator, use –e. Following is the list of flags and commands for ADB. -d Directs device to the only connected USB device; returns an error if more than one USB device is connected. -e Directs command to the only running emulator; returns an error if more than one emulator is running. -s <serial_number> Directs command the USB device or emulator with the given serial number. devices List all connected devices connect <host>:<port> Connect to a device via TCP/IP disconnect <host>:<port> Disconnect from a TCP/IP device adb push <local> <remote> Copy file/dir to device adb pull <remote> [<local>] Copy file/dir from device adb sync [<directory>] If <directory>is not specified, both /system and /data partitions will be updated. If it is “system” or “data”, only the corresponding partition is updated. adb shell Run remote shell interactively adb emu <command> Run emulator console command adb logcat View device log adb forward <local> <remote> Forward socket connections adb install [-l] [-r] [-s] <file> Push this package file to device and install it. (-l forward lock the app) (-r reinstall the app, keeping its data) (-s install on SD card instead of internal storage) adb uninstall [-k] <package> Remove this app package from the device. -k means keep the data and cache directories adb bugreport Return all information from the device that should be included in the bug report. adb help Show this help message adb version Show version number A shell is a program that listens to keyboard input from the user and performs actions as directed by the user. The adb shell command provides Unix to send shell commands to an emulator or a connected device and display the results. It can also be used to launch an interactive shell locally. To issue a single command without entering a remote shell, use the shell command like this − adb [-d|-e|-s <serialNumber>] shell <shell_command> Or to enter a remote shell on an emulator/device − adb [-d|-e|-s <serialNumber>] shell When you are ready to exit the remote shell, press CTRL+D or type EXIT. Android ships a debugging tool, Dalvik Debug Monitor Service (DDMS). This tool provides additional services such as port-forwarding services, screen capture on device, incoming call and SMS spoofing etc. When DDMS starts, it connects to adb. A VM monitoring service is created between adb and DDMS, when a device is connected. This service notifies DDMS when a VM on the device is started or terminated. Once the VM starts running, its process id is sent to the DDMS via adb and the adb daemon opens a connection to the VM’s debugger. DDMS can now talk to the VM using a custom wire protocol. This chapter will walk you through the basics of Eclipse IDE and configuring it to develop Python scripts for Android. Eclipse is an application with many capabilities and options. A welcome screen will greet you, the first time you launch the program. Eclipse uses a number of basic concepts and terminology to address different functions and operations of the program. Some of these terminologies are explained here − Workbench − It identifies the overall window of the Eclipse application. It contains multiple child windows, each window containing multiple tabs. Workspace − It refers to the location on your system’s file system where projects created using Eclipse will be saved. Perspective − It is a personal preference for which menus and windows are open at any one time. Eclipse has a number of perspectives configured for typical usage, such as writing code, debugging etc. You can also switch to a different perspective when your activity changes. Perspectives are also customizable. One needs to configure Eclipse to be able to develop SL4A applications. Once the prerequisites are installed successfully on the host, the following plugins for Eclipse must be added − ADT plugin for Eclipse (available at http://dl-ssl.google.com/android/eclipse/ ) ADT plugin for Eclipse (available at http://dl-ssl.google.com/android/eclipse/ ) Python Plugin for Eclipse (available at http://pydev.org/updates ) Python Plugin for Eclipse (available at http://pydev.org/updates ) The following steps can be used to install plugins on Eclipse − Step 1 − Click Help. Step 1 − Click Help. Step 2 − Select Install New Software. Step 2 − Select Install New Software. Step 3 − Click Add. Step 3 − Click Add. Step 4 − Specify the name and the URL to access the plugin. Click OK. Step 4 − Specify the name and the URL to access the plugin. Click OK. Step 5 − Select all the tools and click Next. The plugin installation starts Step 5 − Select all the tools and click Next. The plugin installation starts Follow the given steps to configure Python Interpreter in Eclipse. Step 1 − Select Windows → Preferences. Step 1 − Select Windows → Preferences. Step 2 − Go to PyDev → Interpreter → Python. Step 2 − Go to PyDev → Interpreter → Python. Step 3 − Click the New button. Step 3 − Click the New button. Step 4 − Specify a name for the interpreter. In the Location field, enter the path to python.exe. For example, C:\Python26\python.exe Step 4 − Specify a name for the interpreter. In the Location field, enter the path to python.exe. For example, C:\Python26\python.exe Step 5 − Click OK. Step 5 − Click OK. SL4A is based on the Facade Design Pattern to communicate with the underlying Android API. This chapter explains the working of Façade Design Pattern and the different SL4A API facades. A facade is an object that provides an interface that simplifies the access to the related interfaces in the application. In other words, a façade insulates the working of the libraries from the client and acts as an entry point to each subsystem level. Thus, the clients communicate only through their facades. The following illustration explains the same. SL4A hosts interpreters for each language it supports. The interpreters access the underlying Android APIs through an interface called a façade. The following table lists the top-level facades and the functionality they provide − ActivityResultFacade It sets how your script will return information as an activity. This method implies that your script will return a result of some kind. The result type can be set to either RESULT_CANCELED(0) or RESULT_OK(-1) AndroidFacade It provides access to common Android functions like reading input, notifications, launching application components etc. ApplicationManagerFacade List all available and running packages, launch an activity, create your task manager or terminate a specific set of packages. BatteryManagerFacade Exposes the battery manager and allows tracking battery status, health, type level, voltage etc. BluetoothFacade Provides access to Bluetooth capabilities from basic connection features to sending and receiving both ASCII and binary data. This façade requires at least API level 5. CameraFacade This method provides access to all camera-related functions. Allows taking a picture using the device’s camera and saving it to a specified path. It provides two functions namely cameraCapturePicture and cameraInteractiveCapturePicture. These functions are strictly for using the lens on the rear of the device. CommonIntentsFacade Provides access to common Android Intents like opening a list of contacts, making a map search, starting an activity by action etc. ContactsFacade Allows access to contacts such as providing the contact list for picking a contact, querying the contact list by attributes and getting a list of all contacts with their IDs and attributes. Some methods provided by the façade include contactsGet, pickContact, contactsGetById etc. EventFacade The Android OS maintains an event queue for passing information between applications asynchronously. This façade provides functions to manage the event queue such as clearing the existing events, posting new events, listing, registering and unregistering broadcast signals etc. Examples of methods include eventPost, eventClearBuffer, etc. EyesFreeFacade Available on devices below API level 4. It allows scripts to speak using text-to-speech technology. This façade is now replaced by TextToSpeechFacade. The only available function is ttsSpeak. LocationFacade Provides functions that enables tracking the current location either by GPS or by using information about the cell tower you’re currently using. This feature requires an active internet connection to do the actual lookup. The façade provides methods like getLastKnownLocation, startLocating, stopLocating, readLocation etc. MediaPlayerFacade Allows playing media files, controlling the media player, querying the current status of the media player and getting information about the media files. mediaIsPlaying, mediaPlayInfo and mediaPlayList returns the current state of the media player. A call to the startActivity function launches the media player. Functions like mediaPlay, mediaPlayPause, mediaPlayClose, mediaPlaySeek,mediaPlayStart and mediaPlaySetLooping are used to control the media player. MediaRecorderFacade This façade provides audio and video recording capability. startInteractiveVideoRecording, recorderStartMicrophone, recorderCaptureVideo functions are used to launch and start audio/video recording respectively. To end a previously started recording call the recorderStop function. PhoneFacade Makes available basic phone operations like tracking phone state, roaming status, initiating calls, SIM information etc. programmatically. Examples of methods include phoneCallNumber, phoneDialNumber, getCellLocation etc. PreferencesFacade Allows access to shared preferences like getting the list of existing preferences and reading, modifying and adding new preferences. There are three functions supported by SL4A r4 release: prefGetAll, prefGetValue and prefPutValue. SensorManagerFacade Allows tracking sensor data such as light,acceleration, magnetic field and orientation. To start/ stop sensing use the startSensing (deprecated and replaced with startSensingThreshold and startSensingTimed by SL4r4) and stopSensing function calls. readSensors, sensorsGetLight, sensorsReadAccelerometer, sensorsReadMagnetometer and sensorsReadOrientation are the functions provided by this façade. SettingsFacade Provides access to different phone settings like ringer volume, screen brightness, airplane mode, vibration, media volume etc. Functions provided by this façade are checkAirplaneMode, checkRingersilentMode and checkScreenOn(atleast API level 7), getVibrateMode, setScreenTimeout, toggleVibrateMode setRingerVolume etc. SignalStrengthFacade Allows monitoring phone signal strength. Call the startTrackingSignalStrengths function to start gathering data. Call the readSignalStrengths function to start gathering data. To shut down the process call the stoptrackingSignalStrengths function. It requires at least API level 7. SmsFacade It has functions for deleting, reading, marking and sending SMS messages. Examples of functions provided by this façade include smsMarkMessageRead, smsDeleteMessage, smsSend etc. SpeechRecognitionFacade Enables adding speech recognition functionality to the script. It has only one function named recognizeSpeech. TextToSpeechFacade Provides TTS services for API4 and later. To have a device speak use the ttsSpeak function. To determine if the speak function has completed use the ttsIsSpeaking function. ToneGeneratorFacade Generates DTMF tones for given digits. To use it you must call the generateDtmfTones function. UiFacade Provides functions for creating user interface elements like textboxes, checkboxes, datepickers etc. It also allows interactive use of HTML pages. WakeLockFacade Provides functions to create a wake lock include wakeLockAcquireBright, wakeLockAcquireDim, wakeLockAcquireFull and wakelockAcquirePartial. WebCamFacade This façade requires at least API level 8. It allows streaming MJPEG streams from the front-facing device camera to the network. To start/stop the webcam use the webcamStart and the webcamStop functions respectively. To adjust the quality of the video while streaming use the webcamAdjustQuality function. WifiFacade Helps you to control the Wi-Fi radio on your device. It allows scripts to query the status of Wi-Fi connectivity, search for access points, connect to and disconnect WiFi networks and hold a Wi-Fi lock during script execution. Refer https://code.google.com for a full list of methods provided by these facades. The subsequent chapters illustrate how to create utilities using Android Façade API functions. A Graphical User Interface (GUI) represents a set of graphical components that enables the user to browse, access and interact with the application functionalities. There are two basic approaches to user interaction with SL4A namely − Dialog boxes such as Alerts. Dialog boxes such as Alerts. Using HTML and JavaScript to build the UI and then Python behind the scenes to handle any additional processing. Using HTML and JavaScript to build the UI and then Python behind the scenes to handle any additional processing. This chapter explains both the approaches. SL4A includes a UI façade to access the basic UI elements provided by the android API. These functions return a result object as a named tuple when called. Each result is assigned a unique id for tracking purpose. The second element is the result. It represents the user’s input. The tuple also includes the third element error to provide feedback to the caller about any error condition that might have been encountered. If no errors were encountered this element is set to None. dialogGetInput Queries the user for a text input. title (String) title of the input box (default = Value) message (String) message to display above the input box (default = Please enter value:) defaultText (String) text to insert into the input box (optional) The result is the user's input, or None (null) if cancel was hit. dialogShow Show dialog dialogCreateAlert Create alert dialog. title (String)(optional) message (String) (optional) dialogDismiss Dismiss dialog. dialogCreateDatePicker Create date picker dialog. year (Integer) (default = 1970) month (Integer) (default = 1) day (Integer) (default = 1) dialogCreateTimePicker Create time picker dialog. hour (Integer) (default = 0) minute (Integer) (default = 0) is24hour (Boolean) Use 24 hour clock (default = false) dialogGetPassword Queries the user for a password. title (String) title of the password box (default = Password) message (String) message to display above the input box (default = Please enter password:) dialogGetResponse Returns dialog response. dialogSetPositiveButtonText Set alert dialog positive button text. text (String) dialogSetNegativeButtonText Set alert dialog button text. text (String) dialogSetNeutralButtonText Set alert dialog button text. text (String) dialogSetSingleChoiceItems This creates a list of radio buttons. dialogSetMultiChoiceItems This creates a checkbox dialogCreateHorizontalProgress Create a horizontal progress dialog. title (String) (optional) message (String) (optional) maximum progress (Integer) (default = 100) dialogCreateSpinnerProgress Create a spinner progress dialog. title (String) (optional) message (String) (optional) maximum progress (Integer) (default = 100) addContexMenuItem Adds a new item to context menu. label (String) label for this menu item event (String) event that will be generated on menu item click eventData (Object) (optional) addOptionsMenuItem Adds a new item to options menu. label (String) label for this menu item event (String) event that will be generated on menu item click eventData (Object) (optional) iconName (String) webViewShow Display a WebView with the given URL. url (String) wait (Boolean) block until the user exits the WebView (optional) clearContextMenu Removes all items previously added to context menu. clearOptionsMenu Removes all items previously added to options menu makeToast Create a notification A simple Toast Example import android droid = android.Android() uname = droid.getInput("Enter your name") print uname droid.makeToast("Hello %s" %uname.result) A Horizontal Progress Bar import android droid = android.Android() title = "Progress" str = "Loading..." droid.dialogCreateHorizontalProgress(title,str,100) droid.showDialog() for x in range(0,99) time.sleep(0.1) droid.dialogSetCurrentProgress(x) droid.dialogDismiss() A modal dialog box or window is a child to another process or window. With a modal dialog box, processing will wait or block until the user interacts with the new dialog box. A typical example of this case is an alert dialog box. The alert will not close until the user performs an action. The following image is an example of a modal dialog box. To sum up, use a modal dialog box when you need input from the user before you continue execution. SL4A enables building Graphical User Interfaces (GUIs) based on CSS, HTML, JavaScript and Python. The approach uses HTML and JavaScript to build the UI, CSS to enhance the appearance and consistency of HTML elements and fonts and Python to handle any additional processing. The following example illustrates a basic HTML GUI example − 1. Speech.html <html> <head> <title>Text To Speech</title> <script> var droid = new Android(); var speak = function(){ droid.postEvent("say",document.getElementById("say").value); } </script> </head> <body> <form onsubmit = "speak()";return false;”> <label for = "say">What is your message?</label> <input type = "text" id = "say"/> <input type = "submit" value = "Speak"/> </form> </body> </html> 2. txtToSpeech.py import android droid = android.Android() droid.webViewShow(‘file:///sdcard/sl4a/scripts/Speech.html’) while True: result = droid.waitForEvent(‘say’).result droid.ttsSpeak(result[‘data’]) Both the files − Speech.html and txtToSpeech.py, must reside in the /sdcard/sl4a/scripts directory on the device. Run the python script to launch the HTML file. This file is launched by the webViewShow API call. The event is generated when the Speak button is clicked. Email based applications are one of the most common utilities available in a mobile device. One can use the sendEmail API call available through the SL4A Android facade. This function takes three parameters − to_address − a comma-separated list of recipients. to_address − a comma-separated list of recipients. title − represents the title of the email message. title − represents the title of the email message. message − represents the message to be sent. message − represents the message to be sent. import android,datetime,smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText droid = android.Android() serv = ’smtp.gmail.com’ port = 587 mailto = ’chris’ mailfrom = ’charley’ pass = ’pass@123’ msg = MIMEMultipart() msg[‘Subject’] = ’Tes Mail’ msg[‘To’] = mailto msg[‘From’] = mailfrom body = ’This is a test mail!!’ msg.attach(MIMEText(body,’plain’)) smtpCon = smtplib.SMTP(serv,port) smtpCon.starttls() smtpCon.login(mailfrom,pass) smtpSendmail(mailfrom,mailto,msg.as_string()) smtpCon.close() The python library that have used to build the email program is smtplib. In addition, we have used the email library. This library contains a number of helper functions allowing us to construct our message in the correct form. The mimetypes library helps with the encoding of our message. The following code lists all available Wi-Fi access spots − import android, time def main(): global droid droid = android.Android() while not droid.wifiStartScan().result: time.sleep(0.25) networks = {} while not networks: for ap in in droid.wifiGetScanResults().result: networks[ap[‘bssid’]] = ap.copy() droid.dialogCreateAlert(‘Access Points’) droid.dialogSetItems([‘%(ssid)s,%(level)s,%(capabilities)s’ % ap for ap in networks.values() ]) droid.dialogSetPositiveButtonText(‘OK’) dorid.dialogShow() if __name__=’__main__’: main() The code for call logs is given below. import android droid = android.Android() mylog = droid.getConstants("android.provider.Calllog$Calls").result calls = droid.queryContent(mylog["CONTENT_URI"],["name","number","duration"]).result for c in calls: print c A service is a component, which runs in the background, without direct interaction with the user. It does not have any UI (user interface). The service runs in the background indefinitely even if application is destroyed. This chapter describes the writing scripts that perform specific tasks in the background. SL4A enables a script to run in a terminal or in the background. To launch a script in the background choose the icon that looks like a cog wheel. The script runs in the background infinitely. However, one may choose to explicitly shut down such services. These scripts are launched whenever the device boots. The Launch on Boot preferences screen is an application that lets you specify the device’s boot preferences. The utility supports execution of multiple scripts via a Master script. The Master script launches the other scripts. A trigger defines a set of actions that must be performed in response to an action/event. Triggers may be added as well as deleted. The /sdcard/sl4a/scripts directory allows you to choose a script to run when an event is triggered. The list of options that may trigger you script includes battery, location, phone, sensors and signal strength. SL4A lets us run scripts depending on the orientation and movement of the device. The startSensingTimedAPI is used to determine the orientation and movement of the device. The following snippet uses TTS function to notify the user when the phone has been placed face down − import android,time droid = android.Android() droid.startSensing() while True: res = droid.sensorsGetLight().result if res is not None and res <=10: droid.ttsSpeak("Device faced down!!") time.sleep(5) Library, church are the locations that you may frequently visit and you definitely want to silence your phone when you are there. SL4A allows you to build scripts that will track your location and take specific actions. These triggers are used to perform actions at a specific time of day. The 24-hour time format should be used to specify the time. Examples include a script to set alarm, reminders etc. As against a time-based trigger, an elapsed time-based trigger executes the script after an elapsed number of time. The snooze option on an alarm application is based on this concept. This chapter explains the ways to package and distribute scripts using Eclipse and QR codes. Most Android devices include a native barcode scanner. SL4A supports importing QR codes directly into the editor. A QR code can only encode 4,296 characters of content. Hence, this method of distribution is suitable for short scripts. There are several websites where you can paste text and create a QR code. However, we shall reference http://zxing.appspot.com/generator to generate the QR code in our illustration. The steps are explained below − Step 1 − Open the Contents drop-down and choose Text. Step 2 − On the first line of the Text Content, enter the name of the script (e.g., greet.py). Step 3 − Paste the script content below that. Step 4 − Choose the barcode size from the Size drop-down. Step 5 − Click Generate. Step 6 − Embed the resulting barcode image or share it. Thus, QR code is an effective way to share short scripts through a blog or a website. Android applications are distributed in a single file/package with an .apk extension. The Android Package (.apk) is similar to a .jar or .zip file. Each .apk contains a number of mandatory files that must be present. The most important file is the AndroidManifest.xml. The manifest file does a number of things − Declares application components. Declares application components. Identify user permissions the application requires. Identify user permissions the application requires. Declares hardware and software features used or required by the application, such as camera, Bluetooth services etc. Declares hardware and software features used or required by the application, such as camera, Bluetooth services etc. Specifies API libraries the application needs to be linked against, such as the Google Maps Library. Specifies API libraries the application needs to be linked against, such as the Google Maps Library. The steps to build a distributable project i.e. .apk in eclipse are illustrated below − Download and install Hg from mercurial − http://mercurial.selenic.com/wiki/Download. Set the PATH variable to the installation folder. Download and install Hg from mercurial − http://mercurial.selenic.com/wiki/Download. Set the PATH variable to the installation folder. Create a clone of the latest SL4A repository: Open the terminal and navigate to the directory where the clone must be created. Enter the following Hg clone: https://android-scripting.googlecode.com/hg/android-scripting. Create a clone of the latest SL4A repository: Open the terminal and navigate to the directory where the clone must be created. Enter the following Hg clone: https://android-scripting.googlecode.com/hg/android-scripting. Open Eclipse and click on File/Import/General/Existing Projects into Workspace/Next and Browse to the cloned directory. Click on Android/OK then select all and click Finish. Open Eclipse and click on File/Import/General/Existing Projects into Workspace/Next and Browse to the cloned directory. Click on Android/OK then select all and click Finish. Include ANDROID_SDK in the Classpath Variable list by clicking Windows/Preferences/Java/BuildPathVariables/New. Put ANDROID_SDK for the name and your SDK directory for the folder (probably c:\ProgramFiles\Android\android-sdk-windows). Include ANDROID_SDK in the Classpath Variable list by clicking Windows/Preferences/Java/BuildPathVariables/New. Put ANDROID_SDK for the name and your SDK directory for the folder (probably c:\ProgramFiles\Android\android-sdk-windows). Click Project/Build Automatically, then Project/Clean/Clean all Projects/OK. Click Project/Build Automatically, then Project/Clean/Clean all Projects/OK. To turn your script into an APK, make a copy of ScriptForAndroidTemplate (right click/copy then right click/paste into the same area). A new project will appear with the name Copy of ScriptForAndroidTemplate. To turn your script into an APK, make a copy of ScriptForAndroidTemplate (right click/copy then right click/paste into the same area). A new project will appear with the name Copy of ScriptForAndroidTemplate. To connect this project to your clone of SL4A, double click on it, right click on build.xml /Run As /Ant Build. Rename the project using Refactor/Rename to whatever name you choose for your project and Refresh/Clean/Build the project. To connect this project to your clone of SL4A, double click on it, right click on build.xml /Run As /Ant Build. Rename the project using Refactor/Rename to whatever name you choose for your project and Refresh/Clean/Build the project. Next, double-click on raw and Refactor/Rename to change the name script.py to your_script_name.py and then double-click src/com.dummy.fooforandroid/Script.java and change R.raw.script to R.raw.your_script_name and save. Next, double-click on raw and Refactor/Rename to change the name script.py to your_script_name.py and then double-click src/com.dummy.fooforandroid/Script.java and change R.raw.script to R.raw.your_script_name and save. Double-click on src and Refactor/Rename to change the package name com.dummy.fooforandroid to your.package.name. Do the same for gen. Double-click on src and Refactor/Rename to change the package name com.dummy.fooforandroid to your.package.name. Do the same for gen. Now highlight your project then click on Project/Properties/Android. Select your android target and click OK. Now highlight your project then click on Project/Properties/Android. Select your android target and click OK. Towards the bottom of your project list, double click on AndroidManifest.xml. Change the package name in the manifest from com.dummy.fooforandroid to your.package.name. Change your minSdkVersion from "4" to suit your android target (this is the API level for your android target shown in Project/Preferences/Android). Uncomment the permissions you require your application to have (take off <!-- at the start and --> at the end). Set Debug to False. Towards the bottom of your project list, double click on AndroidManifest.xml. Change the package name in the manifest from com.dummy.fooforandroid to your.package.name. Change your minSdkVersion from "4" to suit your android target (this is the API level for your android target shown in Project/Preferences/Android). Uncomment the permissions you require your application to have (take off <!-- at the start and --> at the end). Set Debug to False. Right click on your_script_name and open with text editor. Delete the default script, replace it with your own and save. Then Clean/Build/Refresh your project and run it. If all goes well click on File/Export to export your application as an apk. Right click on your_script_name and open with text editor. Delete the default script, replace it with your own and save. Then Clean/Build/Refresh your project and run it. If all goes well click on File/Export to export your application as an apk. Click Next. Click Next. Every Android Application must be digitally signed before it can be installed. Select Create new Keystore, if this is the first time you have been through this process. Every Android Application must be digitally signed before it can be installed. Select Create new Keystore, if this is the first time you have been through this process. Select a file to hold your keystore and it must be password protected. Select a file to hold your keystore and it must be password protected. Click Next. Notice the validity field. You may create a key valid for any number of years, from 1 to 99. Click Next. Notice the validity field. You may create a key valid for any number of years, from 1 to 99. The final dialog box allows you to specify where you want the .apk file to reside. Click Finish. The final dialog box allows you to specify where you want the .apk file to reside. Click Finish. One may use Eclipse or the ADB tool to test/install the .apk file. To install using ADB, open a terminal window, navigate to the .apk destination directory and type the following − One may use Eclipse or the ADB tool to test/install the .apk file. To install using ADB, open a terminal window, navigate to the .apk destination directory and type the following − adb install distributable_file.apk 15 Lectures 47 mins Nishant Kumar 19 Lectures 59 mins Ranjan Raja Print Add Notes Bookmark this page
[ { "code": null, "e": 2219, "s": 1973, "text": "Android is a Linux based operating system, designed primarily for portable devices like smartphones and tablet. Android is more than an operating system. It is a software stack that provides many features for users, developers and manufacturers." }, { "code": null, "e": 2420, "s": 2219, "text": "It is open source and business friendly. The user can choose to replace built-in applications with applications of their choice. Many versions of Android have been released since its original release." }, { "code": null, "e": 2669, "s": 2420, "text": "The Android software stack comprises of different layers, each layer manifesting well-defined behavior and providing specific services to the layer above it. The following figure presents a broad architecture of Android with its primary components." }, { "code": null, "e": 3095, "s": 2669, "text": "Android is built on the Linux kernel code modified to run on embedded systems as against the traditional Linux system. Hardware drivers for many common devices are built into the kernel, thereby ensuring device portability. It is based on secure user based permission model, which prevents one application from reading another application’s information or from interfering with its execution (e.g. CPU, memory, devices etc.)." }, { "code": null, "e": 3273, "s": 3095, "text": "Group ID based access to networking and Bluetooth features, logger, alarm, power management, low memory killer, Binder IPC mechanisms are a few noted enhancements to the Kernel." }, { "code": null, "e": 3485, "s": 3273, "text": "This forms the second layer of the architecture. It includes a set of hardware optimized C, C++ libraries, also referred to as the native layer. Examples include Media Libraries, SQLite, SSL, Bionic, WebKit etc." }, { "code": null, "e": 3758, "s": 3485, "text": "The Android Runtime comprises of two different components − the Dalvik VM and Core Libraries. The Dalvik VM provides an execution environment for the applications on the Android Platform. The set of core libraries provides most of the functionality available in Java APIs." }, { "code": null, "e": 3968, "s": 3758, "text": "This layer makes available the Libraries as services to the applications. Some most important components within this layer include Location Manager, Resource Manager, Activity Manager and Notification Manager." }, { "code": null, "e": 4181, "s": 3968, "text": "By default, Android comes with a rich set of applications, including the browser, SMS program, calendar, contact manager, maps etc. Google Play provides alternatives to these applications, if the user desires so." }, { "code": null, "e": 4275, "s": 4181, "text": "An application can interface with the system with four function blocks. They are as follows −" }, { "code": null, "e": 4534, "s": 4275, "text": "Activities − Activities represent a single screen that the user sees or interacts with visually. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails." }, { "code": null, "e": 4793, "s": 4534, "text": "Activities − Activities represent a single screen that the user sees or interacts with visually. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails." }, { "code": null, "e": 5108, "s": 4793, "text": "Services − A majority of processing is done by these services for your application. It is the logic behind the user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity." }, { "code": null, "e": 5423, "s": 5108, "text": "Services − A majority of processing is done by these services for your application. It is the logic behind the user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity." }, { "code": null, "e": 5733, "s": 5423, "text": "Broadcast Receivers − A component that can be registered to listen for system or application events and issue notifications about the same. An instance for broadcast originating from the system is a ‘low battery notification’ while an application level broadcast could be a ‘download successful’ notification." }, { "code": null, "e": 6043, "s": 5733, "text": "Broadcast Receivers − A component that can be registered to listen for system or application events and issue notifications about the same. An instance for broadcast originating from the system is a ‘low battery notification’ while an application level broadcast could be a ‘download successful’ notification." }, { "code": null, "e": 6214, "s": 6043, "text": "Content Providers − A content provider manages and helps you share data between multiple applications. For e.g. a content provider may be used to share the contacts data." }, { "code": null, "e": 6385, "s": 6214, "text": "Content Providers − A content provider manages and helps you share data between multiple applications. For e.g. a content provider may be used to share the contacts data." }, { "code": null, "e": 6460, "s": 6385, "text": "These components interact with each other through messages called Intents." }, { "code": null, "e": 6724, "s": 6460, "text": "Android scripting is a handy tool for simple tasks such as automation and prototyping as against using the Java programming language for the same. The Scripting Layer for Android (SL4A) provides a platform for multiple scripting solutions on the android platform." }, { "code": null, "e": 6897, "s": 6724, "text": "The Scripting Layer for Android (SL4A) is a library that provides a platform to write simple scripts to automate tasks on an android device using languages other than JAVA." }, { "code": null, "e": 7170, "s": 6897, "text": "SL4A, originally called Android Scripting Environment (ASE), was first announced on the Google Open Source blog in June 2009. The project saw the light of the day primarily through the efforts of Damon Kohler and it has grown through the contributions of other developers." }, { "code": null, "e": 7232, "s": 7170, "text": "It supports most popular scripting languages. These include −" }, { "code": null, "e": 7248, "s": 7232, "text": "Beanshell 2.0b4" }, { "code": null, "e": 7258, "s": 7248, "text": "JRuby 1.4" }, { "code": null, "e": 7268, "s": 7258, "text": "Lua 5.1.4" }, { "code": null, "e": 7280, "s": 7268, "text": "Perl 5.10.1" }, { "code": null, "e": 7290, "s": 7280, "text": "PHP 5.3.3" }, { "code": null, "e": 7297, "s": 7290, "text": "Python" }, { "code": null, "e": 7309, "s": 7297, "text": "Rhino 1.7R2" }, { "code": null, "e": 7320, "s": 7309, "text": "Javascript" }, { "code": null, "e": 7324, "s": 7320, "text": "TCL" }, { "code": null, "e": 7410, "s": 7324, "text": "One of the first questions one would probably ask is, “Why use SL4A instead of Java?”" }, { "code": null, "e": 7531, "s": 7410, "text": "Firstly, not everyone is a fan of Java. Scripting languages provide an easy programming environment as compared to Java." }, { "code": null, "e": 7882, "s": 7531, "text": "Secondly, the language requires the use of an edit/compile/run design loop. This means that you edit, re-compile and then run the application each time you desire some modification. On the contrary, scripts are interpreted and executed on the fly. Moreover, SL4A even makes it possible, in many cases, to reuse code written for a desktop environment." }, { "code": null, "e": 7982, "s": 7882, "text": "The following figure illustrates scripts written in Python targeting SL4A and in Java respectively." }, { "code": null, "e": 8036, "s": 7982, "text": "SL4A has three main components. They are as follows −" }, { "code": null, "e": 8056, "s": 8036, "text": "Script Interpreters" }, { "code": null, "e": 8075, "s": 8056, "text": "Android RPC Client" }, { "code": null, "e": 8083, "s": 8075, "text": "Facades" }, { "code": null, "e": 8151, "s": 8083, "text": "In this chapter, we will discuss more about these three components." }, { "code": null, "e": 8415, "s": 8151, "text": "SL4A acts a scripting host. It supports many scripting languages such as Python, Ruby, Lua, BeanShell, JavaScript and TCL . SL4A can be extended by incorporating new scripting languages dynamically by developing a new SL4A interpreter for that scripting language." }, { "code": null, "e": 8542, "s": 8415, "text": "Each script runs in its own interpreter instance. Hence, multiple scripts can run simultaneously without affecting each other." }, { "code": null, "e": 8878, "s": 8542, "text": "Scripts running within the interpreter instance communicates with the SL4A application through the Android Proxy RPC Client. The client establishes a Remote Procedure Call (RPC) connection to SL4A, and allows scripts to interact with the Android Framework. The SL4A facades facilitate this communication. Data is sent as JSON payloads." }, { "code": null, "e": 9037, "s": 8878, "text": "Android RPC clients are provided for every supported scripting language. The client modules can be obtained from the SL4A website at https://code.google.com." }, { "code": null, "e": 9283, "s": 9037, "text": "The façade simplifies the script’s access to the underlying Android API. SL4A exposes the Android Framework API to scripts through an extensive set of facades like AndroidFacade, BluetoothFacade, ActivityManagerFacade, CommonIntentsFacade, etc." }, { "code": null, "e": 9426, "s": 9283, "text": "SL4A functionality offers a basket of rich functionalities like Camera, Location, Battery Manager, Media Player, Media Recorder and many more." }, { "code": null, "e": 9487, "s": 9426, "text": "The SL4A system is suited for the following kinds of tasks −" }, { "code": null, "e": 9719, "s": 9487, "text": "RAD programming − With SL4A, it is possible to use Rapid Application Development (RAD) approach to create a prototype application quickly. You can create a full-blown Android application if the feasibility of the idea is confirmed." }, { "code": null, "e": 9951, "s": 9719, "text": "RAD programming − With SL4A, it is possible to use Rapid Application Development (RAD) approach to create a prototype application quickly. You can create a full-blown Android application if the feasibility of the idea is confirmed." }, { "code": null, "e": 10004, "s": 9951, "text": "Test scripts − It can be used to write test scripts." }, { "code": null, "e": 10057, "s": 10004, "text": "Test scripts − It can be used to write test scripts." }, { "code": null, "e": 10201, "s": 10057, "text": "Building Utilities − Utility scripts or tools that perform small tasks or automate certain aspects of repetitive tasks can be built using SL4A." }, { "code": null, "e": 10345, "s": 10201, "text": "Building Utilities − Utility scripts or tools that perform small tasks or automate certain aspects of repetitive tasks can be built using SL4A." }, { "code": null, "e": 10571, "s": 10345, "text": "Python has a standard library, which includes a wide variety of routines that help you code and reuse these codes easily. A Module is a Python file that has definitions of variables and a set of related routines or functions." }, { "code": null, "e": 10644, "s": 10571, "text": "Some of the core Modules provided by the Python library are as follows −" }, { "code": null, "e": 10914, "s": 10644, "text": "Built-in Functions and Exceptions − Python imports both these modules when it starts up and makes their content available for all programs. The built-in module defines built-in functions like len, int, range, while the exceptions module defines all built-in exceptions." }, { "code": null, "e": 11184, "s": 10914, "text": "Built-in Functions and Exceptions − Python imports both these modules when it starts up and makes their content available for all programs. The built-in module defines built-in functions like len, int, range, while the exceptions module defines all built-in exceptions." }, { "code": null, "e": 11327, "s": 11184, "text": "Operating System Interface Modules − The OS module makes available, the functions that enables performing OS level operations through scripts." }, { "code": null, "e": 11470, "s": 11327, "text": "Operating System Interface Modules − The OS module makes available, the functions that enables performing OS level operations through scripts." }, { "code": null, "e": 11633, "s": 11470, "text": "Type Support Modules − Type support modules include string module-to implement, commonly used string operations; math module provides mathematical operations etc." }, { "code": null, "e": 11796, "s": 11633, "text": "Type Support Modules − Type support modules include string module-to implement, commonly used string operations; math module provides mathematical operations etc." }, { "code": null, "e": 11998, "s": 11796, "text": "Regular Expressions − Regular Expressions are string patterns written in a specific syntax, which can be used to match or extract strings or substrings. The re module provides Regex support for Python." }, { "code": null, "e": 12200, "s": 11998, "text": "Regular Expressions − Regular Expressions are string patterns written in a specific syntax, which can be used to match or extract strings or substrings. The re module provides Regex support for Python." }, { "code": null, "e": 12577, "s": 12200, "text": "Language Support Modules − The sys module gives you access to various interpreter variables, such as the module search path, and the interpreter version. The operator module provides functional equivalents to many built-in operators. The copy module allows you to copy objects. Finally, the gc module gives you more control over the garbage collector facilities in python 2.0." }, { "code": null, "e": 12954, "s": 12577, "text": "Language Support Modules − The sys module gives you access to various interpreter variables, such as the module search path, and the interpreter version. The operator module provides functional equivalents to many built-in operators. The copy module allows you to copy objects. Finally, the gc module gives you more control over the garbage collector facilities in python 2.0." }, { "code": null, "e": 13349, "s": 12954, "text": "The JavaScript Object Notation (JSON) is a data-interchange format. Though many programming languages support JSON, it is especially useful for JavaScript-based apps, including websites and browser extensions. JSON can represent numbers, Booleans, strings, null, arrays (ordered sequences of values), and objects (string-value mappings) made up of these values (or of other arrays and objects)." }, { "code": null, "e": 13484, "s": 13349, "text": "This chapter details the procedure to set up your development environment. It also discusses how to configure your device to use SL4A." }, { "code": null, "e": 13580, "s": 13484, "text": "You must download and install several pre-requisites before you can start developing with SL4A." }, { "code": null, "e": 13680, "s": 13580, "text": "To begin with, you should have a recent version of JDK (JDK 5 or upwards) installed on your system." }, { "code": null, "e": 13844, "s": 13680, "text": "To confirm that a compatible version of the JDK installed available to the environment, execute the following on the command line or console terminal, as follows −" }, { "code": null, "e": 13877, "s": 13844, "text": "$javac –version \n$java –version\n" }, { "code": null, "e": 13936, "s": 13877, "text": "Note − Set the PATH environment variable to jdk/bin folder" }, { "code": null, "e": 14114, "s": 13936, "text": "It is likely that Python is installed on Mac OS X and Linux, by default. Windows OS, by default, does not have Python installed. Python can be downloaded from http://python.org." }, { "code": null, "e": 14184, "s": 14114, "text": "Once installed, modify your Windows path to add the Python directory." }, { "code": null, "e": 14276, "s": 14184, "text": "To verify if Python is installed on your system, open the terminal window and enter Python." }, { "code": null, "e": 14502, "s": 14276, "text": "The only additional file that one needs to download is the android.py file. Include a copy of this file under /Lib/site-packages in the Python installation directory. This file includes python modules for Android development." }, { "code": null, "e": 14769, "s": 14502, "text": "A number of tools are provided with the Android SDK. The first step is to download the appropriate install file for your operating system. Installers for Mac OS X, Linux and Windows are available. The SDK installer can be found at \nhttps://developer.android.com/sdk." }, { "code": null, "e": 14896, "s": 14769, "text": "The development environment discussed here is Windows. Google provides a zip file and an executable to install SDK on Windows." }, { "code": null, "e": 15121, "s": 14896, "text": "Eclipse was developed as an extensible, Integrated Development Environment (IDE) written in Java language. It requires an installation of Java to work. Eclipse comes in many flavors − Classic, Galelio, Luno, Mars, Neon, etc." }, { "code": null, "e": 15303, "s": 15121, "text": "It is distributed in a single .zip file. All you have to do is unpack the program contents. The extracted folder has an Eclipse.exe file. Double click the file to start the program." }, { "code": null, "e": 15494, "s": 15303, "text": "At times, you may want to write scripts on the device and execute them. The Scripting Layer for Android helps achieve the same. To install SL4A on your device, follow the steps given below −" }, { "code": null, "e": 15538, "s": 15494, "text": " Download the SL4A.apk file on your device." }, { "code": null, "e": 15582, "s": 15538, "text": " Download the SL4A.apk file on your device." }, { "code": null, "e": 15634, "s": 15582, "text": "Launch the .apk file from the notifications screen." }, { "code": null, "e": 15686, "s": 15634, "text": "Launch the .apk file from the notifications screen." }, { "code": null, "e": 15746, "s": 15686, "text": "Select Install on the next screen to actually install SL4A." }, { "code": null, "e": 15806, "s": 15746, "text": "Select Install on the next screen to actually install SL4A." }, { "code": null, "e": 16001, "s": 15806, "text": "Alternatively, if you choose to use an emulator as against an android device, install SL4A using the browser inside the emulator. The SL4A installation initial screen on a device is shown below." }, { "code": null, "e": 16079, "s": 16001, "text": "To install the python interpreter on a device, follow the steps given below −" }, { "code": null, "e": 16116, "s": 16079, "text": "Step 1 − Start the SL4A application." }, { "code": null, "e": 16153, "s": 16116, "text": "Step 1 − Start the SL4A application." }, { "code": null, "e": 16185, "s": 16153, "text": "Step 2 − Click the Menu button." }, { "code": null, "e": 16217, "s": 16185, "text": "Step 2 − Click the Menu button." }, { "code": null, "e": 16276, "s": 16217, "text": "Step 3 − A list of options will be displayed. Select View." }, { "code": null, "e": 16335, "s": 16276, "text": "Step 3 − A list of options will be displayed. Select View." }, { "code": null, "e": 16406, "s": 16335, "text": "Step 4 − Select the Interpreter option from the dialog box. Click Add." }, { "code": null, "e": 16477, "s": 16406, "text": "Step 4 − Select the Interpreter option from the dialog box. Click Add." }, { "code": null, "e": 16579, "s": 16477, "text": "Step 5 − A list of interpreters available for download is displayed. Select Python 2.62 (or greater)." }, { "code": null, "e": 16681, "s": 16579, "text": "Step 5 − A list of interpreters available for download is displayed. Select Python 2.62 (or greater)." }, { "code": null, "e": 16758, "s": 16681, "text": "To install python interpreter on an emulator, follow the steps given below −" }, { "code": null, "e": 16822, "s": 16758, "text": "Step 1 − Ensure that the emulator is running in the background." }, { "code": null, "e": 16886, "s": 16822, "text": "Step 1 − Ensure that the emulator is running in the background." }, { "code": null, "e": 16931, "s": 16886, "text": "Step 2 − Download python_for_android_rx.apk." }, { "code": null, "e": 16976, "s": 16931, "text": "Step 2 − Download python_for_android_rx.apk." }, { "code": null, "e": 17120, "s": 16976, "text": "Step 3 − In the terminal command-line shell, navigate to the location where the apk file is stored and type the following on the command line −" }, { "code": null, "e": 17264, "s": 17120, "text": "Step 3 − In the terminal command-line shell, navigate to the location where the apk file is stored and type the following on the command line −" }, { "code": null, "e": 17305, "s": 17264, "text": "adb install python_for_android_rx.apk\n" }, { "code": null, "e": 17425, "s": 17305, "text": "SL4A supports scripting engine for multiple languages. A list of some language specific apk files are mentioned below −" }, { "code": null, "e": 17454, "s": 17425, "text": "beanshell_for_android_rx.apk" }, { "code": null, "e": 17479, "s": 17454, "text": "jruby_for_android_rx.apk" }, { "code": null, "e": 17502, "s": 17479, "text": "lua_for_android_rx.apk" }, { "code": null, "e": 17526, "s": 17502, "text": "perl_for_android_rx.apk" }, { "code": null, "e": 17552, "s": 17526, "text": "python_for_android_rx.apk" }, { "code": null, "e": 17577, "s": 17552, "text": "rhino_for_android_rx.apk" }, { "code": null, "e": 17635, "s": 17577, "text": "Step 1 − Download and Install the USB Driver for Windows." }, { "code": null, "e": 17664, "s": 17635, "text": "Step 2 − Setup your device −" }, { "code": null, "e": 17711, "s": 17664, "text": "Start SL4A from All apps screen on the device." }, { "code": null, "e": 17758, "s": 17711, "text": "Start SL4A from All apps screen on the device." }, { "code": null, "e": 17786, "s": 17758, "text": "Tap the Menu button → View." }, { "code": null, "e": 17814, "s": 17786, "text": "Tap the Menu button → View." }, { "code": null, "e": 17853, "s": 17814, "text": "Choose the interpreters from the list." }, { "code": null, "e": 17892, "s": 17853, "text": "Choose the interpreters from the list." }, { "code": null, "e": 17928, "s": 17892, "text": "Tap the Menu button → Start Server." }, { "code": null, "e": 17964, "s": 17928, "text": "Tap the Menu button → Start Server." }, { "code": null, "e": 18035, "s": 17964, "text": "Select Public (to connect over Wi-Fi) or Private(to connect over USB)." }, { "code": null, "e": 18106, "s": 18035, "text": "Select Public (to connect over Wi-Fi) or Private(to connect over USB)." }, { "code": null, "e": 18183, "s": 18106, "text": "Step 3 − Add an environment variable (User variable) AP_PORT and value 9999." }, { "code": null, "e": 18255, "s": 18183, "text": "Android SDK and Eclipse have been discussed in the subsequent chapters." }, { "code": null, "e": 18600, "s": 18255, "text": "A software development kit that enables developers to create applications for the Android platform. The Android SDK includes sample projects with source code, development tools, an emulator, and required libraries to build Android applications. This chapter discusses the Android SDK and ways to use it for developing the code targeted at SL4A." }, { "code": null, "e": 18819, "s": 18600, "text": "The directory tree where you installed the Android SDK, contains a list of folders containing documentation, sample code and a number of tools. Navigating to the tools subdirectory reveals a number of executable files." }, { "code": null, "e": 18889, "s": 18819, "text": "Discussed below are some important components within the Android SDK." }, { "code": null, "e": 19101, "s": 18889, "text": "The Android SDK Manager separates the SDK tools, platforms, and other components into packages for easy access and management. The SDK can be configured to check for new or updated SDK packages and add-on tools." }, { "code": null, "e": 19211, "s": 19101, "text": "By default, Android Studio does not check for Android SDK updates. To enable automatic Android SDK checking −" }, { "code": null, "e": 19296, "s": 19211, "text": "Step 1 − Choose File → Settings → Appearance & Behavior → System Settings → Updates." }, { "code": null, "e": 19381, "s": 19296, "text": "Step 1 − Choose File → Settings → Appearance & Behavior → System Settings → Updates." }, { "code": null, "e": 19483, "s": 19381, "text": "Step 2 − Check the Automatically check updates for Android SDK checkbox and select an update channel." }, { "code": null, "e": 19585, "s": 19483, "text": "Step 2 − Check the Automatically check updates for Android SDK checkbox and select an update channel." }, { "code": null, "e": 19643, "s": 19585, "text": "Step 3 − Click OK or Apply to enable the update checking." }, { "code": null, "e": 19701, "s": 19643, "text": "Step 3 − Click OK or Apply to enable the update checking." }, { "code": null, "e": 19925, "s": 19701, "text": "The SDK Update Sites tab displays the sites that Android Studio checks for Android SDK and third-party updates. You can add other sites that host their own Android SDK addons, then download the SDK add-ons from those sites." }, { "code": null, "e": 20294, "s": 19925, "text": "The AVD Manager provides a graphical user interface in which you can create and manage Android Virtual Devices (AVDs), which are required by the Android Emulator. An Android Virtual Device (AVD) consists of a number of files including configuration and virtual storage required by the emulator. You can create as many AVDs as you want for simulating different devices." }, { "code": null, "e": 20356, "s": 20294, "text": "The following steps can be used to create an AVD in Eclipse −" }, { "code": null, "e": 20394, "s": 20356, "text": "Step 1 − Select Window → AVD Manager." }, { "code": null, "e": 20432, "s": 20394, "text": "Step 1 − Select Window → AVD Manager." }, { "code": null, "e": 20452, "s": 20432, "text": "Step 2 − Click New." }, { "code": null, "e": 20472, "s": 20452, "text": "Step 2 − Click New." }, { "code": null, "e": 20568, "s": 20472, "text": "Step 3 − Type the name of the AVD, choose the target and specify values for the other features." }, { "code": null, "e": 20664, "s": 20568, "text": "Step 3 − Type the name of the AVD, choose the target and specify values for the other features." }, { "code": null, "e": 20691, "s": 20664, "text": "Step 4 − Click Create AVD." }, { "code": null, "e": 20718, "s": 20691, "text": "Step 4 − Click Create AVD." }, { "code": null, "e": 20870, "s": 20718, "text": "For devices with keyboard, there is a standard set of mappings from the host keyboard to actions on the device. The default Emulator key mappings are −" }, { "code": null, "e": 20965, "s": 20870, "text": "You can change these settings by editing the default.keyset file in the .android subdirectory." }, { "code": null, "e": 21193, "s": 20965, "text": "ADB, Android Debug Bridge, is a command-line utility included with Google’s Android SDK. ADB can control your device over USB from a computer, copy files back and forth, install and uninstall apps, run shell commands, and more." }, { "code": null, "e": 21423, "s": 21193, "text": "If you have an emulator running and a real device connected, you must specify where you want the ADB commands to a real device, use the option − d and for the emulator, use –e. Following is the list of flags and commands for ADB." }, { "code": null, "e": 21426, "s": 21423, "text": "-d" }, { "code": null, "e": 21534, "s": 21426, "text": "Directs device to the only connected USB device; returns an error if more than one USB device is connected." }, { "code": null, "e": 21537, "s": 21534, "text": "-e" }, { "code": null, "e": 21638, "s": 21537, "text": "Directs command to the only running emulator; returns an error if more than one emulator is running." }, { "code": null, "e": 21657, "s": 21638, "text": "-s <serial_number>" }, { "code": null, "e": 21731, "s": 21657, "text": "Directs command the USB device or emulator with the given serial number." }, { "code": null, "e": 21739, "s": 21731, "text": "devices" }, { "code": null, "e": 21766, "s": 21739, "text": "List all connected devices" }, { "code": null, "e": 21788, "s": 21766, "text": "connect <host>:<port>" }, { "code": null, "e": 21819, "s": 21788, "text": "Connect to a device via TCP/IP" }, { "code": null, "e": 21844, "s": 21819, "text": "disconnect <host>:<port>" }, { "code": null, "e": 21876, "s": 21844, "text": "Disconnect from a TCP/IP device" }, { "code": null, "e": 21902, "s": 21876, "text": "adb push <local> <remote>" }, { "code": null, "e": 21926, "s": 21902, "text": "Copy file/dir to device" }, { "code": null, "e": 21954, "s": 21926, "text": "adb pull <remote> [<local>]" }, { "code": null, "e": 21980, "s": 21954, "text": "Copy file/dir from device" }, { "code": null, "e": 22003, "s": 21980, "text": "adb sync [<directory>]" }, { "code": null, "e": 22160, "s": 22003, "text": "If <directory>is not specified, both /system and /data partitions will be updated. If it is “system” or “data”, only the corresponding partition is updated." }, { "code": null, "e": 22170, "s": 22160, "text": "adb shell" }, { "code": null, "e": 22201, "s": 22170, "text": "Run remote shell interactively" }, { "code": null, "e": 22219, "s": 22201, "text": "adb emu <command>" }, { "code": null, "e": 22248, "s": 22219, "text": "Run emulator console command" }, { "code": null, "e": 22259, "s": 22248, "text": "adb logcat" }, { "code": null, "e": 22275, "s": 22259, "text": "View device log" }, { "code": null, "e": 22304, "s": 22275, "text": "adb forward <local> <remote>" }, { "code": null, "e": 22331, "s": 22304, "text": "Forward socket connections" }, { "code": null, "e": 22365, "s": 22331, "text": "adb install [-l] [-r] [-s] <file>" }, { "code": null, "e": 22440, "s": 22365, "text": "Push this package file to device and install it. (-l forward lock the app)" }, { "code": null, "e": 22481, "s": 22440, "text": "(-r reinstall the app, keeping its data)" }, { "code": null, "e": 22534, "s": 22481, "text": "(-s install on SD card instead of internal storage)" }, { "code": null, "e": 22563, "s": 22534, "text": "adb uninstall [-k] <package>" }, { "code": null, "e": 22650, "s": 22563, "text": "Remove this app package from the device. -k means keep the data and cache directories" }, { "code": null, "e": 22664, "s": 22650, "text": "adb bugreport" }, { "code": null, "e": 22746, "s": 22664, "text": "Return all information from the device that should be included in the bug report." }, { "code": null, "e": 22755, "s": 22746, "text": "adb help" }, { "code": null, "e": 22778, "s": 22755, "text": "Show this help message" }, { "code": null, "e": 22790, "s": 22778, "text": "adb version" }, { "code": null, "e": 22810, "s": 22790, "text": "Show version number" }, { "code": null, "e": 23103, "s": 22810, "text": "A shell is a program that listens to keyboard input from the user and performs actions as directed by the user. The adb shell command provides Unix to send shell commands to an emulator or a connected device and display the results. It can also be used to launch an interactive shell locally." }, { "code": null, "e": 23196, "s": 23103, "text": "To issue a single command without entering a remote shell, use the shell command like this −" }, { "code": null, "e": 23249, "s": 23196, "text": "adb [-d|-e|-s <serialNumber>] shell <shell_command>\n" }, { "code": null, "e": 23300, "s": 23249, "text": "Or to enter a remote shell on an emulator/device −" }, { "code": null, "e": 23337, "s": 23300, "text": "adb [-d|-e|-s <serialNumber>] shell\n" }, { "code": null, "e": 23409, "s": 23337, "text": "When you are ready to exit the remote shell, press CTRL+D or type EXIT." }, { "code": null, "e": 23613, "s": 23409, "text": "Android ships a debugging tool, Dalvik Debug Monitor Service (DDMS). This tool provides additional services such as port-forwarding services, screen capture on device, incoming call and SMS spoofing etc." }, { "code": null, "e": 23813, "s": 23613, "text": "When DDMS starts, it connects to adb. A VM monitoring service is created between adb and DDMS, when a device is connected. This service notifies DDMS when a VM on the device is started or terminated." }, { "code": null, "e": 24002, "s": 23813, "text": "Once the VM starts running, its process id is sent to the DDMS via adb and the adb daemon opens a connection to the VM’s debugger. DDMS can now talk to the VM using a custom wire protocol." }, { "code": null, "e": 24121, "s": 24002, "text": "This chapter will walk you through the basics of Eclipse IDE and configuring it to develop Python scripts for Android." }, { "code": null, "e": 24373, "s": 24121, "text": "Eclipse is an application with many capabilities and options. A welcome screen will greet you, the first time you launch the program. Eclipse uses a number of basic concepts and terminology to address different functions and operations of the program." }, { "code": null, "e": 24422, "s": 24373, "text": "Some of these terminologies are explained here −" }, { "code": null, "e": 24569, "s": 24422, "text": "Workbench − It identifies the overall window of the Eclipse application. It contains multiple child windows, each window containing multiple tabs." }, { "code": null, "e": 24688, "s": 24569, "text": "Workspace − It refers to the location on your system’s file system where projects created using Eclipse will be saved." }, { "code": null, "e": 24999, "s": 24688, "text": "Perspective − It is a personal preference for which menus and windows are open at any one time. Eclipse has a number of perspectives configured for typical usage, such as writing code, debugging etc. You can also switch to a different perspective when your activity changes. Perspectives are also customizable." }, { "code": null, "e": 25184, "s": 24999, "text": "One needs to configure Eclipse to be able to develop SL4A applications. Once the prerequisites are installed successfully on the host, the following plugins for Eclipse must be added −" }, { "code": null, "e": 25267, "s": 25184, "text": "ADT plugin for Eclipse (available at http://dl-ssl.google.com/android/eclipse/ )" }, { "code": null, "e": 25350, "s": 25267, "text": "ADT plugin for Eclipse (available at http://dl-ssl.google.com/android/eclipse/ )" }, { "code": null, "e": 25418, "s": 25350, "text": "Python Plugin for Eclipse (available at http://pydev.org/updates )" }, { "code": null, "e": 25486, "s": 25418, "text": "Python Plugin for Eclipse (available at http://pydev.org/updates )" }, { "code": null, "e": 25550, "s": 25486, "text": "The following steps can be used to install plugins on Eclipse −" }, { "code": null, "e": 25571, "s": 25550, "text": "Step 1 − Click Help." }, { "code": null, "e": 25592, "s": 25571, "text": "Step 1 − Click Help." }, { "code": null, "e": 25630, "s": 25592, "text": "Step 2 − Select Install New Software." }, { "code": null, "e": 25668, "s": 25630, "text": "Step 2 − Select Install New Software." }, { "code": null, "e": 25688, "s": 25668, "text": "Step 3 − Click Add." }, { "code": null, "e": 25708, "s": 25688, "text": "Step 3 − Click Add." }, { "code": null, "e": 25778, "s": 25708, "text": "Step 4 − Specify the name and the URL to access the plugin. Click OK." }, { "code": null, "e": 25848, "s": 25778, "text": "Step 4 − Specify the name and the URL to access the plugin. Click OK." }, { "code": null, "e": 25925, "s": 25848, "text": "Step 5 − Select all the tools and click Next. The plugin installation starts" }, { "code": null, "e": 26002, "s": 25925, "text": "Step 5 − Select all the tools and click Next. The plugin installation starts" }, { "code": null, "e": 26069, "s": 26002, "text": "Follow the given steps to configure Python Interpreter in Eclipse." }, { "code": null, "e": 26108, "s": 26069, "text": "Step 1 − Select Windows → Preferences." }, { "code": null, "e": 26147, "s": 26108, "text": "Step 1 − Select Windows → Preferences." }, { "code": null, "e": 26192, "s": 26147, "text": "Step 2 − Go to PyDev → Interpreter → Python." }, { "code": null, "e": 26237, "s": 26192, "text": "Step 2 − Go to PyDev → Interpreter → Python." }, { "code": null, "e": 26268, "s": 26237, "text": "Step 3 − Click the New button." }, { "code": null, "e": 26299, "s": 26268, "text": "Step 3 − Click the New button." }, { "code": null, "e": 26433, "s": 26299, "text": "Step 4 − Specify a name for the interpreter. In the Location field, enter the path to python.exe. For example, C:\\Python26\\python.exe" }, { "code": null, "e": 26567, "s": 26433, "text": "Step 4 − Specify a name for the interpreter. In the Location field, enter the path to python.exe. For example, C:\\Python26\\python.exe" }, { "code": null, "e": 26586, "s": 26567, "text": "Step 5 − Click OK." }, { "code": null, "e": 26605, "s": 26586, "text": "Step 5 − Click OK." }, { "code": null, "e": 26792, "s": 26605, "text": "SL4A is based on the Facade Design Pattern to communicate with the underlying Android API. This chapter explains the working of Façade Design Pattern and the different SL4A API facades." }, { "code": null, "e": 27151, "s": 26792, "text": "A facade is an object that provides an interface that simplifies the access to the related interfaces in the application. In other words, a façade insulates the working of the libraries from the client and acts as an entry point to each subsystem level. Thus, the clients communicate only through their facades. The following illustration explains the same." }, { "code": null, "e": 27297, "s": 27151, "text": "SL4A hosts interpreters for each language it supports. The interpreters access the underlying Android APIs through an interface called a façade." }, { "code": null, "e": 27382, "s": 27297, "text": "The following table lists the top-level facades and the functionality they provide −" }, { "code": null, "e": 27403, "s": 27382, "text": "ActivityResultFacade" }, { "code": null, "e": 27612, "s": 27403, "text": "It sets how your script will return information as an activity. This method implies that your script will return a result of some kind. The result type can be set to either RESULT_CANCELED(0) or RESULT_OK(-1)" }, { "code": null, "e": 27626, "s": 27612, "text": "AndroidFacade" }, { "code": null, "e": 27747, "s": 27626, "text": "It provides access to common Android functions like reading input, notifications, launching application components etc." }, { "code": null, "e": 27772, "s": 27747, "text": "ApplicationManagerFacade" }, { "code": null, "e": 27899, "s": 27772, "text": "List all available and running packages, launch an activity, create your task manager or terminate a specific set of packages." }, { "code": null, "e": 27920, "s": 27899, "text": "BatteryManagerFacade" }, { "code": null, "e": 28017, "s": 27920, "text": "Exposes the battery manager and allows tracking battery status, health, type level, voltage etc." }, { "code": null, "e": 28033, "s": 28017, "text": "BluetoothFacade" }, { "code": null, "e": 28203, "s": 28033, "text": "Provides access to Bluetooth capabilities from basic connection features to sending and receiving both ASCII and binary data. This façade requires at least API level 5." }, { "code": null, "e": 28216, "s": 28203, "text": "CameraFacade" }, { "code": null, "e": 28528, "s": 28216, "text": "This method provides access to all camera-related functions. Allows taking a picture using the device’s camera and saving it to a specified path. It provides two functions namely cameraCapturePicture and cameraInteractiveCapturePicture. These functions are strictly for using the lens on the rear of the device." }, { "code": null, "e": 28548, "s": 28528, "text": "CommonIntentsFacade" }, { "code": null, "e": 28681, "s": 28548, "text": "Provides access to common Android Intents like opening a list of contacts, making a map search, starting an activity by action etc." }, { "code": null, "e": 28696, "s": 28681, "text": "ContactsFacade" }, { "code": null, "e": 28978, "s": 28696, "text": "Allows access to contacts such as providing the contact list for picking a contact, querying the contact list by attributes and getting a list of all contacts with their IDs and attributes. Some methods provided by the façade include contactsGet, pickContact, contactsGetById etc." }, { "code": null, "e": 28990, "s": 28978, "text": "EventFacade" }, { "code": null, "e": 29331, "s": 28990, "text": "The Android OS maintains an event queue for passing information between applications asynchronously. This façade provides functions to manage the event queue such as clearing the existing events, posting new events, listing, registering and unregistering broadcast signals etc. Examples of methods include eventPost, eventClearBuffer, etc." }, { "code": null, "e": 29346, "s": 29331, "text": "EyesFreeFacade" }, { "code": null, "e": 29539, "s": 29346, "text": "Available on devices below API level 4. It allows scripts to speak using text-to-speech technology. This façade is now replaced by TextToSpeechFacade. The only available function is ttsSpeak." }, { "code": null, "e": 29554, "s": 29539, "text": "LocationFacade" }, { "code": null, "e": 29879, "s": 29554, "text": "Provides functions that enables tracking the current location either by GPS or by using information about the cell tower you’re currently using. This feature requires an active internet connection to do the actual lookup. The façade provides methods like getLastKnownLocation, startLocating, stopLocating, readLocation etc." }, { "code": null, "e": 29897, "s": 29879, "text": "MediaPlayerFacade" }, { "code": null, "e": 30358, "s": 29897, "text": "Allows playing media files, controlling the media player, querying the current status of the media player and getting information about the media files. mediaIsPlaying, mediaPlayInfo and mediaPlayList returns the current state of the media player. A call to the startActivity function launches the media player. Functions like mediaPlay, mediaPlayPause, mediaPlayClose, mediaPlaySeek,mediaPlayStart and mediaPlaySetLooping are used to control the media player." }, { "code": null, "e": 30378, "s": 30358, "text": "MediaRecorderFacade" }, { "code": null, "e": 30661, "s": 30378, "text": "This façade provides audio and video recording capability. startInteractiveVideoRecording, recorderStartMicrophone, recorderCaptureVideo functions are used to launch and start audio/video recording respectively. To end a previously started recording call the recorderStop function." }, { "code": null, "e": 30673, "s": 30661, "text": "PhoneFacade" }, { "code": null, "e": 30895, "s": 30673, "text": "Makes available basic phone operations like tracking phone state, roaming status, initiating calls, SIM information etc. programmatically. Examples of methods include phoneCallNumber, phoneDialNumber, getCellLocation etc." }, { "code": null, "e": 30913, "s": 30895, "text": "PreferencesFacade" }, { "code": null, "e": 31145, "s": 30913, "text": "Allows access to shared preferences like getting the list of existing preferences and reading, modifying and adding new preferences. There are three functions supported by SL4A r4 release: prefGetAll, prefGetValue and prefPutValue." }, { "code": null, "e": 31165, "s": 31145, "text": "SensorManagerFacade" }, { "code": null, "e": 31564, "s": 31165, "text": "Allows tracking sensor data such as light,acceleration, magnetic field and orientation. To start/ stop sensing use the startSensing (deprecated and replaced with startSensingThreshold and startSensingTimed by SL4r4) and stopSensing function calls. readSensors, sensorsGetLight, sensorsReadAccelerometer, sensorsReadMagnetometer and sensorsReadOrientation are the functions provided by this façade." }, { "code": null, "e": 31579, "s": 31564, "text": "SettingsFacade" }, { "code": null, "e": 31900, "s": 31579, "text": "Provides access to different phone settings like ringer volume, screen brightness, airplane mode, vibration, media volume etc. Functions provided by this façade are checkAirplaneMode, checkRingersilentMode and checkScreenOn(atleast API level 7), getVibrateMode, setScreenTimeout, toggleVibrateMode setRingerVolume etc." }, { "code": null, "e": 31921, "s": 31900, "text": "SignalStrengthFacade" }, { "code": null, "e": 32203, "s": 31921, "text": "Allows monitoring phone signal strength. Call the startTrackingSignalStrengths function to start gathering data. Call the readSignalStrengths function to start gathering data. To shut down the process call the stoptrackingSignalStrengths function. It requires at least API level 7." }, { "code": null, "e": 32213, "s": 32203, "text": "SmsFacade" }, { "code": null, "e": 32393, "s": 32213, "text": "It has functions for deleting, reading, marking and sending SMS messages. Examples of functions provided by this façade include smsMarkMessageRead, smsDeleteMessage, smsSend etc." }, { "code": null, "e": 32417, "s": 32393, "text": "SpeechRecognitionFacade" }, { "code": null, "e": 32528, "s": 32417, "text": "Enables adding speech recognition functionality to the script. It has only one function named recognizeSpeech." }, { "code": null, "e": 32547, "s": 32528, "text": "TextToSpeechFacade" }, { "code": null, "e": 32720, "s": 32547, "text": "Provides TTS services for API4 and later. To have a device speak use the ttsSpeak function. To determine if the speak function has completed use the ttsIsSpeaking function." }, { "code": null, "e": 32740, "s": 32720, "text": "ToneGeneratorFacade" }, { "code": null, "e": 32835, "s": 32740, "text": "Generates DTMF tones for given digits. To use it you must call the generateDtmfTones function." }, { "code": null, "e": 32844, "s": 32835, "text": "UiFacade" }, { "code": null, "e": 32991, "s": 32844, "text": "Provides functions for creating user interface elements like textboxes, checkboxes, datepickers etc. It also allows interactive use of HTML pages." }, { "code": null, "e": 33006, "s": 32991, "text": "WakeLockFacade" }, { "code": null, "e": 33147, "s": 33006, "text": "Provides functions to create a wake lock include wakeLockAcquireBright, wakeLockAcquireDim, wakeLockAcquireFull and wakelockAcquirePartial." }, { "code": null, "e": 33160, "s": 33147, "text": "WebCamFacade" }, { "code": null, "e": 33467, "s": 33160, "text": "This façade requires at least API level 8. It allows streaming MJPEG streams from the front-facing device camera to the network. To start/stop the webcam use the webcamStart and the webcamStop functions respectively. To adjust the quality of the video while streaming use the webcamAdjustQuality function." }, { "code": null, "e": 33478, "s": 33467, "text": "WifiFacade" }, { "code": null, "e": 33706, "s": 33478, "text": "Helps you to control the Wi-Fi radio on your device. It allows scripts to query the status of Wi-Fi connectivity, search for access points, connect to and disconnect WiFi networks and hold a Wi-Fi lock during script execution." }, { "code": null, "e": 33886, "s": 33706, "text": "Refer https://code.google.com for a full list of methods provided by these facades. The subsequent chapters illustrate how to create utilities using Android Façade API functions." }, { "code": null, "e": 34051, "s": 33886, "text": "A Graphical User Interface (GUI) represents a set of graphical components that enables the user to browse, access and interact with the application functionalities." }, { "code": null, "e": 34121, "s": 34051, "text": "There are two basic approaches to user interaction with SL4A namely −" }, { "code": null, "e": 34150, "s": 34121, "text": "Dialog boxes such as Alerts." }, { "code": null, "e": 34179, "s": 34150, "text": "Dialog boxes such as Alerts." }, { "code": null, "e": 34292, "s": 34179, "text": "Using HTML and JavaScript to build the UI and then Python behind the scenes to handle any additional processing." }, { "code": null, "e": 34405, "s": 34292, "text": "Using HTML and JavaScript to build the UI and then Python behind the scenes to handle any additional processing." }, { "code": null, "e": 34448, "s": 34405, "text": "This chapter explains both the approaches." }, { "code": null, "e": 34930, "s": 34448, "text": "SL4A includes a UI façade to access the basic UI elements provided by the android API. These functions return a result object as a named tuple when called. Each result is assigned a unique id for tracking purpose. The second element is the result. It represents the user’s input. The tuple also includes the third element error to provide feedback to the caller about any error condition that might have been encountered. If no errors were encountered this element is set to None." }, { "code": null, "e": 34945, "s": 34930, "text": "dialogGetInput" }, { "code": null, "e": 34980, "s": 34945, "text": "Queries the user for a text input." }, { "code": null, "e": 35036, "s": 34980, "text": "title (String) title of the input box (default = Value)" }, { "code": null, "e": 35124, "s": 35036, "text": "message (String) message to display above the input box (default = Please enter value:)" }, { "code": null, "e": 35191, "s": 35124, "text": "defaultText (String) text to insert into the input box (optional)" }, { "code": null, "e": 35257, "s": 35191, "text": "The result is the user's input, or None (null) if cancel was hit." }, { "code": null, "e": 35268, "s": 35257, "text": "dialogShow" }, { "code": null, "e": 35280, "s": 35268, "text": "Show dialog" }, { "code": null, "e": 35298, "s": 35280, "text": "dialogCreateAlert" }, { "code": null, "e": 35319, "s": 35298, "text": "Create alert dialog." }, { "code": null, "e": 35344, "s": 35319, "text": "title (String)(optional)" }, { "code": null, "e": 35372, "s": 35344, "text": "message (String) (optional)" }, { "code": null, "e": 35386, "s": 35372, "text": "dialogDismiss" }, { "code": null, "e": 35402, "s": 35386, "text": "Dismiss dialog." }, { "code": null, "e": 35425, "s": 35402, "text": "dialogCreateDatePicker" }, { "code": null, "e": 35452, "s": 35425, "text": "Create date picker dialog." }, { "code": null, "e": 35484, "s": 35452, "text": "year (Integer) (default = 1970)" }, { "code": null, "e": 35514, "s": 35484, "text": "month (Integer) (default = 1)" }, { "code": null, "e": 35542, "s": 35514, "text": "day (Integer) (default = 1)" }, { "code": null, "e": 35565, "s": 35542, "text": "dialogCreateTimePicker" }, { "code": null, "e": 35592, "s": 35565, "text": "Create time picker dialog." }, { "code": null, "e": 35621, "s": 35592, "text": "hour (Integer) (default = 0)" }, { "code": null, "e": 35652, "s": 35621, "text": "minute (Integer) (default = 0)" }, { "code": null, "e": 35707, "s": 35652, "text": "is24hour (Boolean) Use 24 hour clock (default = false)" }, { "code": null, "e": 35725, "s": 35707, "text": "dialogGetPassword" }, { "code": null, "e": 35758, "s": 35725, "text": "Queries the user for a password." }, { "code": null, "e": 35820, "s": 35758, "text": "title (String) title of the password box (default = Password)" }, { "code": null, "e": 35911, "s": 35820, "text": "message (String) message to display above the input box (default = Please enter password:)" }, { "code": null, "e": 35929, "s": 35911, "text": "dialogGetResponse" }, { "code": null, "e": 35954, "s": 35929, "text": "Returns dialog response." }, { "code": null, "e": 35982, "s": 35954, "text": "dialogSetPositiveButtonText" }, { "code": null, "e": 36035, "s": 35982, "text": "Set alert dialog positive button text. text (String)" }, { "code": null, "e": 36063, "s": 36035, "text": "dialogSetNegativeButtonText" }, { "code": null, "e": 36107, "s": 36063, "text": "Set alert dialog button text. text (String)" }, { "code": null, "e": 36134, "s": 36107, "text": "dialogSetNeutralButtonText" }, { "code": null, "e": 36178, "s": 36134, "text": "Set alert dialog button text. text (String)" }, { "code": null, "e": 36205, "s": 36178, "text": "dialogSetSingleChoiceItems" }, { "code": null, "e": 36243, "s": 36205, "text": "This creates a list of radio buttons." }, { "code": null, "e": 36269, "s": 36243, "text": "dialogSetMultiChoiceItems" }, { "code": null, "e": 36293, "s": 36269, "text": "This creates a checkbox" }, { "code": null, "e": 36324, "s": 36293, "text": "dialogCreateHorizontalProgress" }, { "code": null, "e": 36361, "s": 36324, "text": "Create a horizontal progress dialog." }, { "code": null, "e": 36387, "s": 36361, "text": "title (String) (optional)" }, { "code": null, "e": 36415, "s": 36387, "text": "message (String) (optional)" }, { "code": null, "e": 36458, "s": 36415, "text": "maximum progress (Integer) (default = 100)" }, { "code": null, "e": 36486, "s": 36458, "text": "dialogCreateSpinnerProgress" }, { "code": null, "e": 36520, "s": 36486, "text": "Create a spinner progress dialog." }, { "code": null, "e": 36546, "s": 36520, "text": "title (String) (optional)" }, { "code": null, "e": 36574, "s": 36546, "text": "message (String) (optional)" }, { "code": null, "e": 36617, "s": 36574, "text": "maximum progress (Integer) (default = 100)" }, { "code": null, "e": 36635, "s": 36617, "text": "addContexMenuItem" }, { "code": null, "e": 36668, "s": 36635, "text": "Adds a new item to context menu." }, { "code": null, "e": 36708, "s": 36668, "text": "label (String) label for this menu item" }, { "code": null, "e": 36771, "s": 36708, "text": "event (String) event that will be generated on menu item click" }, { "code": null, "e": 36801, "s": 36771, "text": "eventData (Object) (optional)" }, { "code": null, "e": 36820, "s": 36801, "text": "addOptionsMenuItem" }, { "code": null, "e": 36853, "s": 36820, "text": "Adds a new item to options menu." }, { "code": null, "e": 36893, "s": 36853, "text": "label (String) label for this menu item" }, { "code": null, "e": 36956, "s": 36893, "text": "event (String) event that will be generated on menu item click" }, { "code": null, "e": 36986, "s": 36956, "text": "eventData (Object) (optional)" }, { "code": null, "e": 37004, "s": 36986, "text": "iconName (String)" }, { "code": null, "e": 37016, "s": 37004, "text": "webViewShow" }, { "code": null, "e": 37054, "s": 37016, "text": "Display a WebView with the given URL." }, { "code": null, "e": 37067, "s": 37054, "text": "url (String)" }, { "code": null, "e": 37132, "s": 37067, "text": "wait (Boolean) block until the user exits the WebView (optional)" }, { "code": null, "e": 37149, "s": 37132, "text": "clearContextMenu" }, { "code": null, "e": 37201, "s": 37149, "text": "Removes all items previously added to context menu." }, { "code": null, "e": 37218, "s": 37201, "text": "clearOptionsMenu" }, { "code": null, "e": 37269, "s": 37218, "text": "Removes all items previously added to options menu" }, { "code": null, "e": 37279, "s": 37269, "text": "makeToast" }, { "code": null, "e": 37301, "s": 37279, "text": "Create a notification" }, { "code": null, "e": 37324, "s": 37301, "text": "A simple Toast Example" }, { "code": null, "e": 37466, "s": 37324, "text": "import android \ndroid = android.Android() \nuname = droid.getInput(\"Enter your name\") \nprint uname \ndroid.makeToast(\"Hello %s\" %uname.result)" }, { "code": null, "e": 37492, "s": 37466, "text": "A Horizontal Progress Bar" }, { "code": null, "e": 37782, "s": 37492, "text": "import android \n droid = android.Android() \n title = \"Progress\" \n str = \"Loading...\" \n droid.dialogCreateHorizontalProgress(title,str,100) \n droid.showDialog() \n\t\n for x in range(0,99) \n time.sleep(0.1) \n droid.dialogSetCurrentProgress(x) \n\t\t\n droid.dialogDismiss()" }, { "code": null, "e": 37957, "s": 37782, "text": "A modal dialog box or window is a child to another process or window. With a modal dialog box, processing will wait or block until the user interacts with the new dialog box." }, { "code": null, "e": 38072, "s": 37957, "text": "A typical example of this case is an alert dialog box. The alert will not close until the user performs an action." }, { "code": null, "e": 38129, "s": 38072, "text": "The following image is an example of a modal dialog box." }, { "code": null, "e": 38228, "s": 38129, "text": "To sum up, use a modal dialog box when you need input from the user before you continue execution." }, { "code": null, "e": 38502, "s": 38228, "text": "SL4A enables building Graphical User Interfaces (GUIs) based on CSS, HTML, JavaScript and Python. The approach uses HTML and JavaScript to build the UI, CSS to enhance the appearance and consistency of HTML elements and fonts and Python to handle any additional processing." }, { "code": null, "e": 38563, "s": 38502, "text": "The following example illustrates a basic HTML GUI example −" }, { "code": null, "e": 38578, "s": 38563, "text": "1. Speech.html" }, { "code": null, "e": 39095, "s": 38578, "text": "<html> \n <head> \n <title>Text To Speech</title> \n\t\t\n <script> \n var droid = new Android(); \n var speak = function(){ \n droid.postEvent(\"say\",document.getElementById(\"say\").value); \n } \n </script> \n\t\t\n </head>\n\t\n <body> \n <form onsubmit = \"speak()\";return false;”> \n <label for = \"say\">What is your message?</label> \n <input type = \"text\" id = \"say\"/> \n <input type = \"submit\" value = \"Speak\"/> \n </form> \n </body> \n\t\n</html>" }, { "code": null, "e": 39113, "s": 39095, "text": "2. txtToSpeech.py" }, { "code": null, "e": 39312, "s": 39113, "text": "import android \ndroid = android.Android() \ndroid.webViewShow(‘file:///sdcard/sl4a/scripts/Speech.html’) \n\nwhile True: \n result = droid.waitForEvent(‘say’).result \n droid.ttsSpeak(result[‘data’])" }, { "code": null, "e": 39473, "s": 39312, "text": "Both the files − Speech.html and txtToSpeech.py, must reside in the /sdcard/sl4a/scripts directory on the device. Run the python script to launch the HTML file." }, { "code": null, "e": 39581, "s": 39473, "text": "This file is launched by the webViewShow API call. The event is generated when the Speak button is clicked." }, { "code": null, "e": 39751, "s": 39581, "text": "Email based applications are one of the most common utilities available in a mobile device. One can use the sendEmail API call available through the SL4A Android facade." }, { "code": null, "e": 39790, "s": 39751, "text": "This function takes three parameters −" }, { "code": null, "e": 39841, "s": 39790, "text": "to_address − a comma-separated list of recipients." }, { "code": null, "e": 39892, "s": 39841, "text": "to_address − a comma-separated list of recipients." }, { "code": null, "e": 39943, "s": 39892, "text": "title − represents the title of the email message." }, { "code": null, "e": 39994, "s": 39943, "text": "title − represents the title of the email message." }, { "code": null, "e": 40039, "s": 39994, "text": "message − represents the message to be sent." }, { "code": null, "e": 40084, "s": 40039, "text": "message − represents the message to be sent." }, { "code": null, "e": 40642, "s": 40084, "text": "import android,datetime,smtplib \nfrom email.mime.multipart import MIMEMultipart \nfrom email.mime.text import MIMEText \n\ndroid = android.Android() \nserv = ’smtp.gmail.com’ \nport = 587 \nmailto = ’chris’ \nmailfrom = ’charley’ \npass = ’pass@123’ \n\nmsg = MIMEMultipart() \nmsg[‘Subject’] = ’Tes Mail’ \nmsg[‘To’] = mailto \nmsg[‘From’] = mailfrom \n\nbody = ’This is a test mail!!’ \nmsg.attach(MIMEText(body,’plain’)) \n\nsmtpCon = smtplib.SMTP(serv,port) \nsmtpCon.starttls() \nsmtpCon.login(mailfrom,pass) \nsmtpSendmail(mailfrom,mailto,msg.as_string()) \nsmtpCon.close()" }, { "code": null, "e": 40931, "s": 40642, "text": "The python library that have used to build the email program is smtplib. In addition, we have used the email library. This library contains a number of helper functions allowing us to construct our message in the correct form. The mimetypes library helps with the encoding of our message." }, { "code": null, "e": 40991, "s": 40931, "text": "The following code lists all available Wi-Fi access spots −" }, { "code": null, "e": 41525, "s": 40991, "text": "import android, time \n\ndef main(): \n global droid \n droid = android.Android() \n\t\nwhile not droid.wifiStartScan().result: \n time.sleep(0.25) \n\t\nnetworks = {} \n\nwhile not networks: \n for ap in in droid.wifiGetScanResults().result: \n networks[ap[‘bssid’]] = ap.copy() \n\t\t\n droid.dialogCreateAlert(‘Access Points’) \n droid.dialogSetItems([‘%(ssid)s,%(level)s,%(capabilities)s’ % \n ap for ap in networks.values() ]) \n\t\t\ndroid.dialogSetPositiveButtonText(‘OK’) \ndorid.dialogShow() \n\nif __name__=’__main__’: \n main()" }, { "code": null, "e": 41564, "s": 41525, "text": "The code for call logs is given below." }, { "code": null, "e": 41791, "s": 41564, "text": "import android \ndroid = android.Android() \nmylog = droid.getConstants(\"android.provider.Calllog$Calls\").result \ncalls = droid.queryContent(mylog[\"CONTENT_URI\"],[\"name\",\"number\",\"duration\"]).result \n\nfor c in calls: \n print c" }, { "code": null, "e": 42013, "s": 41791, "text": "A service is a component, which runs in the background, without direct interaction with the user. It does not have any UI (user interface). The service runs in the background indefinitely even if application is destroyed." }, { "code": null, "e": 42103, "s": 42013, "text": "This chapter describes the writing scripts that perform specific tasks in the background." }, { "code": null, "e": 42359, "s": 42103, "text": "SL4A enables a script to run in a terminal or in the background. To launch a script in the background choose the icon that looks like a cog wheel. The script runs in the background infinitely. However, one may choose to explicitly shut down such services." }, { "code": null, "e": 42640, "s": 42359, "text": "These scripts are launched whenever the device boots. The Launch on Boot preferences screen is an application that lets you specify the device’s boot preferences. The utility supports execution of multiple scripts via a Master script. The Master script launches the other scripts." }, { "code": null, "e": 42984, "s": 42640, "text": "A trigger defines a set of actions that must be performed in response to an action/event. Triggers may be added as well as deleted. The /sdcard/sl4a/scripts directory allows you to choose a script to run when an event is triggered. The list of options that may trigger you script includes battery, location, phone, sensors and signal strength." }, { "code": null, "e": 43156, "s": 42984, "text": "SL4A lets us run scripts depending on the orientation and movement of the device. The startSensingTimedAPI is used to determine the orientation and movement of the device." }, { "code": null, "e": 43258, "s": 43156, "text": "The following snippet uses TTS function to notify the user when the phone has been placed face down −" }, { "code": null, "e": 43484, "s": 43258, "text": "import android,time \ndroid = android.Android() \ndroid.startSensing() \n\nwhile True: \n res = droid.sensorsGetLight().result \n\t\n if res is not None and res <=10: \n droid.ttsSpeak(\"Device faced down!!\") \n time.sleep(5)" }, { "code": null, "e": 43704, "s": 43484, "text": "Library, church are the locations that you may frequently visit and you definitely want to silence your phone when you are there. SL4A allows you to build scripts that will track your location and take specific actions." }, { "code": null, "e": 44073, "s": 43704, "text": "These triggers are used to perform actions at a specific time of day. The 24-hour time format should be used to specify the time. Examples include a script to set alarm, reminders etc. As against a time-based trigger, an elapsed time-based trigger executes the script after an elapsed number of time. The snooze option on an alarm application is based on this concept." }, { "code": null, "e": 44166, "s": 44073, "text": "This chapter explains the ways to package and distribute scripts using Eclipse and QR codes." }, { "code": null, "e": 44401, "s": 44166, "text": "Most Android devices include a native barcode scanner. SL4A supports importing QR codes directly into the editor. A QR code can only encode 4,296 characters of content. Hence, this method of distribution is suitable for short scripts." }, { "code": null, "e": 44584, "s": 44401, "text": "There are several websites where you can paste text and create a QR code. However, we shall reference http://zxing.appspot.com/generator to generate the QR code in our illustration." }, { "code": null, "e": 44616, "s": 44584, "text": "The steps are explained below −" }, { "code": null, "e": 44670, "s": 44616, "text": "Step 1 − Open the Contents drop-down and choose Text." }, { "code": null, "e": 44765, "s": 44670, "text": "Step 2 − On the first line of the Text Content, enter the name of the script (e.g., greet.py)." }, { "code": null, "e": 44811, "s": 44765, "text": "Step 3 − Paste the script content below that." }, { "code": null, "e": 44869, "s": 44811, "text": "Step 4 − Choose the barcode size from the Size drop-down." }, { "code": null, "e": 44894, "s": 44869, "text": "Step 5 − Click Generate." }, { "code": null, "e": 44950, "s": 44894, "text": "Step 6 − Embed the resulting barcode image or share it." }, { "code": null, "e": 45036, "s": 44950, "text": "Thus, QR code is an effective way to share short scripts through a blog or a website." }, { "code": null, "e": 45305, "s": 45036, "text": "Android applications are distributed in a single file/package with an .apk extension. The Android Package (.apk) is similar to a .jar or .zip file. Each .apk contains a number of mandatory files that must be present. The most important file is the AndroidManifest.xml." }, { "code": null, "e": 45349, "s": 45305, "text": "The manifest file does a number of things −" }, { "code": null, "e": 45382, "s": 45349, "text": "Declares application components." }, { "code": null, "e": 45415, "s": 45382, "text": "Declares application components." }, { "code": null, "e": 45467, "s": 45415, "text": "Identify user permissions the application requires." }, { "code": null, "e": 45519, "s": 45467, "text": "Identify user permissions the application requires." }, { "code": null, "e": 45636, "s": 45519, "text": "Declares hardware and software features used or required by the application, such as camera, Bluetooth services etc." }, { "code": null, "e": 45753, "s": 45636, "text": "Declares hardware and software features used or required by the application, such as camera, Bluetooth services etc." }, { "code": null, "e": 45854, "s": 45753, "text": "Specifies API libraries the application needs to be linked against, such as the Google Maps Library." }, { "code": null, "e": 45955, "s": 45854, "text": "Specifies API libraries the application needs to be linked against, such as the Google Maps Library." }, { "code": null, "e": 46043, "s": 45955, "text": "The steps to build a distributable project i.e. .apk in eclipse are illustrated below −" }, { "code": null, "e": 46178, "s": 46043, "text": "Download and install Hg from mercurial − http://mercurial.selenic.com/wiki/Download. Set the PATH variable to the installation folder." }, { "code": null, "e": 46313, "s": 46178, "text": "Download and install Hg from mercurial − http://mercurial.selenic.com/wiki/Download. Set the PATH variable to the installation folder." }, { "code": null, "e": 46533, "s": 46313, "text": "Create a clone of the latest SL4A repository: Open the terminal and navigate to the directory where the clone must be created. Enter the following Hg clone: https://android-scripting.googlecode.com/hg/android-scripting." }, { "code": null, "e": 46753, "s": 46533, "text": "Create a clone of the latest SL4A repository: Open the terminal and navigate to the directory where the clone must be created. Enter the following Hg clone: https://android-scripting.googlecode.com/hg/android-scripting." }, { "code": null, "e": 46927, "s": 46753, "text": "Open Eclipse and click on File/Import/General/Existing Projects into Workspace/Next and Browse to the cloned directory. Click on Android/OK then select all and click Finish." }, { "code": null, "e": 47101, "s": 46927, "text": "Open Eclipse and click on File/Import/General/Existing Projects into Workspace/Next and Browse to the cloned directory. Click on Android/OK then select all and click Finish." }, { "code": null, "e": 47336, "s": 47101, "text": "Include ANDROID_SDK in the Classpath Variable list by clicking Windows/Preferences/Java/BuildPathVariables/New. Put ANDROID_SDK for the name and your SDK directory for the folder (probably c:\\ProgramFiles\\Android\\android-sdk-windows)." }, { "code": null, "e": 47571, "s": 47336, "text": "Include ANDROID_SDK in the Classpath Variable list by clicking Windows/Preferences/Java/BuildPathVariables/New. Put ANDROID_SDK for the name and your SDK directory for the folder (probably c:\\ProgramFiles\\Android\\android-sdk-windows)." }, { "code": null, "e": 47648, "s": 47571, "text": "Click Project/Build Automatically, then Project/Clean/Clean all Projects/OK." }, { "code": null, "e": 47725, "s": 47648, "text": "Click Project/Build Automatically, then Project/Clean/Clean all Projects/OK." }, { "code": null, "e": 47934, "s": 47725, "text": "To turn your script into an APK, make a copy of ScriptForAndroidTemplate (right click/copy then right click/paste into the same area). A new project will appear with the name Copy of ScriptForAndroidTemplate." }, { "code": null, "e": 48143, "s": 47934, "text": "To turn your script into an APK, make a copy of ScriptForAndroidTemplate (right click/copy then right click/paste into the same area). A new project will appear with the name Copy of ScriptForAndroidTemplate." }, { "code": null, "e": 48378, "s": 48143, "text": "To connect this project to your clone of SL4A, double click on it, right click on build.xml /Run As /Ant Build. Rename the project using Refactor/Rename to whatever name you choose for your project and Refresh/Clean/Build the project." }, { "code": null, "e": 48613, "s": 48378, "text": "To connect this project to your clone of SL4A, double click on it, right click on build.xml /Run As /Ant Build. Rename the project using Refactor/Rename to whatever name you choose for your project and Refresh/Clean/Build the project." }, { "code": null, "e": 48834, "s": 48613, "text": "Next, double-click on raw and Refactor/Rename to change the name script.py to your_script_name.py and then double-click src/com.dummy.fooforandroid/Script.java and change R.raw.script to R.raw.your_script_name and save." }, { "code": null, "e": 49055, "s": 48834, "text": "Next, double-click on raw and Refactor/Rename to change the name script.py to your_script_name.py and then double-click src/com.dummy.fooforandroid/Script.java and change R.raw.script to R.raw.your_script_name and save." }, { "code": null, "e": 49189, "s": 49055, "text": "Double-click on src and Refactor/Rename to change the package name com.dummy.fooforandroid to your.package.name. Do the same for gen." }, { "code": null, "e": 49323, "s": 49189, "text": "Double-click on src and Refactor/Rename to change the package name com.dummy.fooforandroid to your.package.name. Do the same for gen." }, { "code": null, "e": 49433, "s": 49323, "text": "Now highlight your project then click on Project/Properties/Android. Select your android target and click OK." }, { "code": null, "e": 49543, "s": 49433, "text": "Now highlight your project then click on Project/Properties/Android. Select your android target and click OK." }, { "code": null, "e": 49994, "s": 49543, "text": "Towards the bottom of your project list, double click on AndroidManifest.xml. Change the package name in the manifest from com.dummy.fooforandroid to your.package.name. Change your minSdkVersion from \"4\" to suit your android target (this is the API level for your android target shown in Project/Preferences/Android). Uncomment the permissions you require your application to have (take off <!-- at the start and --> at the end). Set Debug to False." }, { "code": null, "e": 50445, "s": 49994, "text": "Towards the bottom of your project list, double click on AndroidManifest.xml. Change the package name in the manifest from com.dummy.fooforandroid to your.package.name. Change your minSdkVersion from \"4\" to suit your android target (this is the API level for your android target shown in Project/Preferences/Android). Uncomment the permissions you require your application to have (take off <!-- at the start and --> at the end). Set Debug to False." }, { "code": null, "e": 50692, "s": 50445, "text": "Right click on your_script_name and open with text editor. Delete the default script, replace it with your own and save. Then Clean/Build/Refresh your project and run it. If all goes well click on File/Export to export your application as an apk." }, { "code": null, "e": 50939, "s": 50692, "text": "Right click on your_script_name and open with text editor. Delete the default script, replace it with your own and save. Then Clean/Build/Refresh your project and run it. If all goes well click on File/Export to export your application as an apk." }, { "code": null, "e": 50951, "s": 50939, "text": "Click Next." }, { "code": null, "e": 50963, "s": 50951, "text": "Click Next." }, { "code": null, "e": 51132, "s": 50963, "text": "Every Android Application must be digitally signed before it can be installed. Select Create new Keystore, if this is the first time you have been through this process." }, { "code": null, "e": 51301, "s": 51132, "text": "Every Android Application must be digitally signed before it can be installed. Select Create new Keystore, if this is the first time you have been through this process." }, { "code": null, "e": 51372, "s": 51301, "text": "Select a file to hold your keystore and it must be password protected." }, { "code": null, "e": 51443, "s": 51372, "text": "Select a file to hold your keystore and it must be password protected." }, { "code": null, "e": 51548, "s": 51443, "text": "Click Next. Notice the validity field. You may create a key valid for any number of years, from 1 to 99." }, { "code": null, "e": 51653, "s": 51548, "text": "Click Next. Notice the validity field. You may create a key valid for any number of years, from 1 to 99." }, { "code": null, "e": 51750, "s": 51653, "text": "The final dialog box allows you to specify where you want the .apk file to reside. Click Finish." }, { "code": null, "e": 51847, "s": 51750, "text": "The final dialog box allows you to specify where you want the .apk file to reside. Click Finish." }, { "code": null, "e": 52028, "s": 51847, "text": "One may use Eclipse or the ADB tool to test/install the .apk file. To install using ADB, open a terminal window, navigate to the .apk destination directory and type the following −" }, { "code": null, "e": 52209, "s": 52028, "text": "One may use Eclipse or the ADB tool to test/install the .apk file. To install using ADB, open a terminal window, navigate to the .apk destination directory and type the following −" }, { "code": null, "e": 52245, "s": 52209, "text": "adb install distributable_file.apk\n" }, { "code": null, "e": 52277, "s": 52245, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 52292, "s": 52277, "text": " Nishant Kumar" }, { "code": null, "e": 52324, "s": 52292, "text": "\n 19 Lectures \n 59 mins\n" }, { "code": null, "e": 52337, "s": 52324, "text": " Ranjan Raja" }, { "code": null, "e": 52344, "s": 52337, "text": " Print" }, { "code": null, "e": 52355, "s": 52344, "text": " Add Notes" } ]
Smallest Distance Between Two Words in Python
Suppose we have two strings, word0, and word1 and a text. We have to find the smallest distance between any two occurrences of word0 and word1 in the given text. Here the distance is measured in number of words. If they are not present in the text then return -1. So, if the input is like text = "cat dog abcd dog cat cat abcd dog wxyz", word0 = "abcd", word1 = "wxyz", then the output will be 1, as there is one word "dog" between "abcd" and "wxyz" To solve this, we will follow these steps − word_list := a list of words from text ans := size of word_list L := null for R in range 0 to size of word_list - 1, doif word_list[R] is word0 or word_list[R] is word1, thenif L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1L := R if word_list[R] is word0 or word_list[R] is word1, thenif L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1L := R if L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1 ans := minimum of ans and R - L - 1 L := R return -1 if ans is same as size of word_list otherwise ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, text, word0, word1): word_list = text.split() ans = len(word_list) L = None for R in range(len(word_list)): if word_list[R] == word0 or word_list[R] == word1: if L is not None and word_list[R] != word_list[L]: ans = min(ans, R - L - 1) L = R return -1 if ans == len(word_list) else ans ob = Solution() text = "cat dog abcd dog cat cat abcd dog wxyz" word0 = "abcd" word1 = "wxyz" print(ob.solve(text, word0, word1)) "cat dog abcd dog cat cat abcd dog wxyz", "abcd", "wxyz" 1
[ { "code": null, "e": 1326, "s": 1062, "text": "Suppose we have two strings, word0, and word1 and a text. We have to find the smallest\ndistance between any two occurrences of word0 and word1 in the given text. Here the distance\nis measured in number of words. If they are not present in the text then return -1." }, { "code": null, "e": 1512, "s": 1326, "text": "So, if the input is like text = \"cat dog abcd dog cat cat abcd dog wxyz\", word0 = \"abcd\", word1 =\n\"wxyz\", then the output will be 1, as there is one word \"dog\" between \"abcd\" and \"wxyz\"" }, { "code": null, "e": 1556, "s": 1512, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1595, "s": 1556, "text": "word_list := a list of words from text" }, { "code": null, "e": 1620, "s": 1595, "text": "ans := size of word_list" }, { "code": null, "e": 1630, "s": 1620, "text": "L := null" }, { "code": null, "e": 1831, "s": 1630, "text": "for R in range 0 to size of word_list - 1, doif word_list[R] is word0 or word_list[R] is word1, thenif L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1L := R" }, { "code": null, "e": 1987, "s": 1831, "text": "if word_list[R] is word0 or word_list[R] is word1, thenif L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1L := R" }, { "code": null, "e": 2082, "s": 1987, "text": "if L is not null and word_list[R] is not word_list[L], thenans := minimum of ans and R - L - 1" }, { "code": null, "e": 2118, "s": 2082, "text": "ans := minimum of ans and R - L - 1" }, { "code": null, "e": 2125, "s": 2118, "text": "L := R" }, { "code": null, "e": 2185, "s": 2125, "text": "return -1 if ans is same as size of word_list otherwise ans" }, { "code": null, "e": 2255, "s": 2185, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2266, "s": 2255, "text": " Live Demo" }, { "code": null, "e": 2798, "s": 2266, "text": "class Solution:\n def solve(self, text, word0, word1):\n word_list = text.split()\n ans = len(word_list)\n L = None\n for R in range(len(word_list)):\n if word_list[R] == word0 or word_list[R] == word1:\n if L is not None and word_list[R] != word_list[L]:\n ans = min(ans, R - L - 1)\n L = R\n return -1 if ans == len(word_list) else ans\nob = Solution()\ntext = \"cat dog abcd dog cat cat abcd dog wxyz\"\nword0 = \"abcd\"\nword1 = \"wxyz\"\nprint(ob.solve(text, word0, word1))" }, { "code": null, "e": 2855, "s": 2798, "text": "\"cat dog abcd dog cat cat abcd dog wxyz\", \"abcd\", \"wxyz\"" }, { "code": null, "e": 2857, "s": 2855, "text": "1" } ]
HTML - Lists
HTML offers web authors three ways for specifying lists of information. All lists must contain one or more list elements. Lists may contain − <ul> − An unordered list. This will list items using plain bullets. <ul> − An unordered list. This will list items using plain bullets. <ol> − An ordered list. This will use different schemes of numbers to list your items. <ol> − An ordered list. This will use different schemes of numbers to list your items. <dl> − A definition list. This arranges your items in the same way as they are arranged in a dictionary. <dl> − A definition list. This arranges your items in the same way as they are arranged in a dictionary. An unordered list is a collection of related items that have no special order or sequence. This list is created by using HTML <ul> tag. Each item in the list is marked with a bullet. <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <ul> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ul> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish You can use type attribute for <ul> tag to specify the type of bullet you like. By default, it is a disc. Following are the possible options − <ul type = "square"> <ul type = "disc"> <ul type = "circle"> Following is an example where we used <ul type = "square"> <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <ul type = "square"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ul> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Following is an example where we used <ul type = "disc"> − <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <ul type = "disc"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ul> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Following is an example where we used <ul type = "circle"> − <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <ul type = "circle"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ul> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish If you are required to put your items in a numbered list instead of bulleted, then HTML ordered list will be used. This list is created by using <ol> tag. The numbering starts at one and is incremented by one for each successive ordered list element tagged with <li>. <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish You can use type attribute for <ol> tag to specify the type of numbering you like. By default, it is a number. Following are the possible options − <ol type = "1"> - Default-Case Numerals. <ol type = "I"> - Upper-Case Numerals. <ol type = "i"> - Lower-Case Numerals. <ol type = "A"> - Upper-Case Letters. <ol type = "a"> - Lower-Case Letters. Following is an example where we used <ol type = "1"> <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol type = "1"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish Following is an example where we used <ol type = "I"> <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol type = "I"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish Following is an example where we used <ol type = "i"> <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol type = "i"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish Following is an example where we used <ol type = "A" > <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol type = "A"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish Following is an example where we used <ol type = "a"> <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol type = "a"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish You can use start attribute for <ol> tag to specify the starting point of numbering you need. Following are the possible options − <ol type = "1" start = "4"> - Numerals starts with 4. <ol type = "I" start = "4"> - Numerals starts with IV. <ol type = "i" start = "4"> - Numerals starts with iv. <ol type = "a" start = "4"> - Letters starts with d. <ol type = "A" start = "4"> - Letters starts with D. Following is an example where we used <ol type = "i" start = "4" > <!DOCTYPE html> <html> <head> <title>HTML Ordered List</title> </head> <body> <ol type = "i" start = "4"> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> This will produce the following result − Beetroot Ginger Potato Radish Beetroot Ginger Potato Radish HTML and XHTML supports a list style which is called definition lists where entries are listed like in a dictionary or encyclopedia. The definition list is the ideal way to present a glossary, list of terms, or other name/value list. Definition List makes use of following three tags. <dl> − Defines the start of the list <dt> − A term <dd> − Term definition </dl> − Defines the end of the list <!DOCTYPE html> <html> <head> <title>HTML Definition List</title> </head> <body> <dl> <dt><b>HTML</b></dt> <dd>This stands for Hyper Text Markup Language</dd> <dt><b>HTTP</b></dt> <dd>This stands for Hyper Text Transfer Protocol</dd> </dl> </body> </html> This will produce the following result − 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2374, "text": "HTML offers web authors three ways for specifying lists of information. All lists must contain one or more list elements. Lists may contain −" }, { "code": null, "e": 2584, "s": 2516, "text": "<ul> − An unordered list. This will list items using plain bullets." }, { "code": null, "e": 2652, "s": 2584, "text": "<ul> − An unordered list. This will list items using plain bullets." }, { "code": null, "e": 2739, "s": 2652, "text": "<ol> − An ordered list. This will use different schemes of numbers to list your items." }, { "code": null, "e": 2826, "s": 2739, "text": "<ol> − An ordered list. This will use different schemes of numbers to list your items." }, { "code": null, "e": 2931, "s": 2826, "text": "<dl> − A definition list. This arranges your items in the same way as they are arranged in a dictionary." }, { "code": null, "e": 3036, "s": 2931, "text": "<dl> − A definition list. This arranges your items in the same way as they are arranged in a dictionary." }, { "code": null, "e": 3219, "s": 3036, "text": "An unordered list is a collection of related items that have no special order or sequence. This list is created by using HTML <ul> tag. Each item in the list is marked with a bullet." }, { "code": null, "e": 3465, "s": 3219, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Unordered List</title>\n </head>\n\t\n <body>\n <ul>\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ul>\n </body>\n \n</html>" }, { "code": null, "e": 3506, "s": 3465, "text": "This will produce the following result −" }, { "code": null, "e": 3515, "s": 3506, "text": "Beetroot" }, { "code": null, "e": 3522, "s": 3515, "text": "Ginger" }, { "code": null, "e": 3529, "s": 3522, "text": "Potato" }, { "code": null, "e": 3536, "s": 3529, "text": "Radish" }, { "code": null, "e": 3679, "s": 3536, "text": "You can use type attribute for <ul> tag to specify the type of bullet you like. By default, it is a disc. Following are the possible options −" }, { "code": null, "e": 3741, "s": 3679, "text": "<ul type = \"square\">\n<ul type = \"disc\">\n<ul type = \"circle\">\n" }, { "code": null, "e": 3800, "s": 3741, "text": "Following is an example where we used <ul type = \"square\">" }, { "code": null, "e": 4058, "s": 3800, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Unordered List</title>\n </head>\n\n <body>\n <ul type = \"square\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ul>\n </body>\n\n</html>" }, { "code": null, "e": 4099, "s": 4058, "text": "This will produce the following result −" }, { "code": null, "e": 4108, "s": 4099, "text": "Beetroot" }, { "code": null, "e": 4115, "s": 4108, "text": "Ginger" }, { "code": null, "e": 4122, "s": 4115, "text": "Potato" }, { "code": null, "e": 4129, "s": 4122, "text": "Radish" }, { "code": null, "e": 4188, "s": 4129, "text": "Following is an example where we used <ul type = \"disc\"> −" }, { "code": null, "e": 4445, "s": 4188, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Unordered List</title>\n </head>\n\t\n <body>\n <ul type = \"disc\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ul>\n </body>\n\n</html>" }, { "code": null, "e": 4486, "s": 4445, "text": "This will produce the following result −" }, { "code": null, "e": 4495, "s": 4486, "text": "Beetroot" }, { "code": null, "e": 4502, "s": 4495, "text": "Ginger" }, { "code": null, "e": 4509, "s": 4502, "text": "Potato" }, { "code": null, "e": 4516, "s": 4509, "text": "Radish" }, { "code": null, "e": 4577, "s": 4516, "text": "Following is an example where we used <ul type = \"circle\"> −" }, { "code": null, "e": 4836, "s": 4577, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Unordered List</title>\n </head>\n\n <body>\n <ul type = \"circle\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ul>\n </body>\n\t\n</html>" }, { "code": null, "e": 4877, "s": 4836, "text": "This will produce the following result −" }, { "code": null, "e": 4886, "s": 4877, "text": "Beetroot" }, { "code": null, "e": 4893, "s": 4886, "text": "Ginger" }, { "code": null, "e": 4900, "s": 4893, "text": "Potato" }, { "code": null, "e": 4907, "s": 4900, "text": "Radish" }, { "code": null, "e": 5175, "s": 4907, "text": "If you are required to put your items in a numbered list instead of bulleted, then HTML ordered list will be used. This list is created by using <ol> tag. The numbering starts at one and is incremented by one for each successive ordered list element tagged with <li>." }, { "code": null, "e": 5415, "s": 5175, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Ordered List</title>\n </head>\n\n <body>\n <ol>\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\n</html>" }, { "code": null, "e": 5456, "s": 5415, "text": "This will produce the following result −" }, { "code": null, "e": 5488, "s": 5456, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 5497, "s": 5488, "text": "Beetroot" }, { "code": null, "e": 5504, "s": 5497, "text": "Ginger" }, { "code": null, "e": 5511, "s": 5504, "text": "Potato" }, { "code": null, "e": 5518, "s": 5511, "text": "Radish" }, { "code": null, "e": 5666, "s": 5518, "text": "You can use type attribute for <ol> tag to specify the type of numbering you like. By default, it is a number. Following are the possible options −" }, { "code": null, "e": 5862, "s": 5666, "text": "<ol type = \"1\"> - Default-Case Numerals.\n<ol type = \"I\"> - Upper-Case Numerals.\n<ol type = \"i\"> - Lower-Case Numerals.\n<ol type = \"A\"> - Upper-Case Letters.\n<ol type = \"a\"> - Lower-Case Letters.\n" }, { "code": null, "e": 5916, "s": 5862, "text": "Following is an example where we used <ol type = \"1\">" }, { "code": null, "e": 6167, "s": 5916, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Ordered List</title>\n </head>\n\n <body>\n <ol type = \"1\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\n</html>" }, { "code": null, "e": 6208, "s": 6167, "text": "This will produce the following result −" }, { "code": null, "e": 6240, "s": 6208, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 6249, "s": 6240, "text": "Beetroot" }, { "code": null, "e": 6256, "s": 6249, "text": "Ginger" }, { "code": null, "e": 6263, "s": 6256, "text": "Potato" }, { "code": null, "e": 6270, "s": 6263, "text": "Radish" }, { "code": null, "e": 6324, "s": 6270, "text": "Following is an example where we used <ol type = \"I\">" }, { "code": null, "e": 6577, "s": 6324, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Ordered List</title>\n </head>\n\t\n <body>\n <ol type = \"I\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\t\n</html>" }, { "code": null, "e": 6618, "s": 6577, "text": "This will produce the following result −" }, { "code": null, "e": 6650, "s": 6618, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 6659, "s": 6650, "text": "Beetroot" }, { "code": null, "e": 6666, "s": 6659, "text": "Ginger" }, { "code": null, "e": 6673, "s": 6666, "text": "Potato" }, { "code": null, "e": 6680, "s": 6673, "text": "Radish" }, { "code": null, "e": 6734, "s": 6680, "text": "Following is an example where we used <ol type = \"i\">" }, { "code": null, "e": 6990, "s": 6734, "text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>HTML Ordered List</title>\n </head>\n\t\n <body>\n <ol type = \"i\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\t\n</html>" }, { "code": null, "e": 7031, "s": 6990, "text": "This will produce the following result −" }, { "code": null, "e": 7063, "s": 7031, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 7072, "s": 7063, "text": "Beetroot" }, { "code": null, "e": 7079, "s": 7072, "text": "Ginger" }, { "code": null, "e": 7086, "s": 7079, "text": "Potato" }, { "code": null, "e": 7093, "s": 7086, "text": "Radish" }, { "code": null, "e": 7148, "s": 7093, "text": "Following is an example where we used <ol type = \"A\" >" }, { "code": null, "e": 7401, "s": 7148, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Ordered List</title>\n </head>\n\t\n <body>\n <ol type = \"A\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\t\n</html>" }, { "code": null, "e": 7442, "s": 7401, "text": "This will produce the following result −" }, { "code": null, "e": 7474, "s": 7442, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 7483, "s": 7474, "text": "Beetroot" }, { "code": null, "e": 7490, "s": 7483, "text": "Ginger" }, { "code": null, "e": 7497, "s": 7490, "text": "Potato" }, { "code": null, "e": 7504, "s": 7497, "text": "Radish" }, { "code": null, "e": 7558, "s": 7504, "text": "Following is an example where we used <ol type = \"a\">" }, { "code": null, "e": 7814, "s": 7558, "text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>HTML Ordered List</title>\n </head>\n\t\n <body>\n <ol type = \"a\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\t\n</html>" }, { "code": null, "e": 7855, "s": 7814, "text": "This will produce the following result −" }, { "code": null, "e": 7887, "s": 7855, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 7896, "s": 7887, "text": "Beetroot" }, { "code": null, "e": 7903, "s": 7896, "text": "Ginger" }, { "code": null, "e": 7910, "s": 7903, "text": "Potato" }, { "code": null, "e": 7917, "s": 7910, "text": "Radish" }, { "code": null, "e": 8048, "s": 7917, "text": "You can use start attribute for <ol> tag to specify the starting point of numbering you need. Following are the possible options −" }, { "code": null, "e": 8334, "s": 8048, "text": "<ol type = \"1\" start = \"4\"> - Numerals starts with 4.\n<ol type = \"I\" start = \"4\"> - Numerals starts with IV.\n<ol type = \"i\" start = \"4\"> - Numerals starts with iv.\n<ol type = \"a\" start = \"4\"> - Letters starts with d.\n<ol type = \"A\" start = \"4\"> - Letters starts with D.\n" }, { "code": null, "e": 8401, "s": 8334, "text": "Following is an example where we used <ol type = \"i\" start = \"4\" >" }, { "code": null, "e": 8666, "s": 8401, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Ordered List</title>\n </head>\n\t\n <body>\n <ol type = \"i\" start = \"4\">\n <li>Beetroot</li>\n <li>Ginger</li>\n <li>Potato</li>\n <li>Radish</li>\n </ol>\n </body>\n\t\n</html>" }, { "code": null, "e": 8707, "s": 8666, "text": "This will produce the following result −" }, { "code": null, "e": 8739, "s": 8707, "text": "\nBeetroot\nGinger\nPotato\nRadish\n" }, { "code": null, "e": 8748, "s": 8739, "text": "Beetroot" }, { "code": null, "e": 8755, "s": 8748, "text": "Ginger" }, { "code": null, "e": 8762, "s": 8755, "text": "Potato" }, { "code": null, "e": 8769, "s": 8762, "text": "Radish" }, { "code": null, "e": 9003, "s": 8769, "text": "HTML and XHTML supports a list style which is called definition lists where entries are listed like in a dictionary or encyclopedia. The definition list is the ideal way to present a glossary, list of terms, or other name/value list." }, { "code": null, "e": 9054, "s": 9003, "text": "Definition List makes use of following three tags." }, { "code": null, "e": 9091, "s": 9054, "text": "<dl> − Defines the start of the list" }, { "code": null, "e": 9105, "s": 9091, "text": "<dt> − A term" }, { "code": null, "e": 9128, "s": 9105, "text": "<dd> − Term definition" }, { "code": null, "e": 9164, "s": 9128, "text": "</dl> − Defines the end of the list" }, { "code": null, "e": 9491, "s": 9164, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Definition List</title>\n </head>\n\t\n <body>\n <dl>\n <dt><b>HTML</b></dt>\n <dd>This stands for Hyper Text Markup Language</dd>\n <dt><b>HTTP</b></dt>\n <dd>This stands for Hyper Text Transfer Protocol</dd>\n </dl>\n </body>\n\t\n</html>" }, { "code": null, "e": 9532, "s": 9491, "text": "This will produce the following result −" }, { "code": null, "e": 9565, "s": 9532, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 9579, "s": 9565, "text": " Anadi Sharma" }, { "code": null, "e": 9614, "s": 9579, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9628, "s": 9614, "text": " Anadi Sharma" }, { "code": null, "e": 9663, "s": 9628, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9680, "s": 9663, "text": " Frahaan Hussain" }, { "code": null, "e": 9715, "s": 9680, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9746, "s": 9715, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9779, "s": 9746, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9810, "s": 9779, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9845, "s": 9810, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9876, "s": 9845, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9883, "s": 9876, "text": " Print" }, { "code": null, "e": 9894, "s": 9883, "text": " Add Notes" } ]
How to write a simple Flask API for hello world? - GeeksforGeeks
17 Oct, 2021 Prerequisites: Introduction to REST API REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple REST API that returns ‘Hello World’, with the help of a flask. In this article we are going to write a simple flask API for hello world using two methods: Using Flask jsonify object. Using the flask_restful library with Flask. 1. Install the python Flask library using the following command. pip install Flask 2. Install the flask-restful library using the following command. pip install Flask-RESTful Create a new python file named ‘main.py’. import Flask, jsonify and request from the flask framework. Register the web app into an app variable using the following syntax. Python3 app = Flask(__name__) Create a new function named ‘helloworld’. This function is going to return the ‘Hello World’ text in JSON format. Route the ‘helloworld’ function to your desired URL using the following syntax. Python3 @app.route('/path_of_the_response', methods=['GET'])def helloworld(): pass Inside the ‘helloworld’ function if request method is ‘GET’ then create a python dictionary with the ‘Hello World’ message. Jsonify the python dictionary and return it. Build the flask application using the following command. Python3 if __name__ == '__main__': app.run(debug=True) Run the ‘main.py’ file in the terminal or the IDE and type the following URL in the browser. http://127.0.0.1:5000/hello Code : Python3 from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/hello', methods=['GET'])def helloworld(): if(request.method == 'GET'): data = {"data": "Hello World"} return jsonify(data) if __name__ == '__main__': app.run(debug=True) Output : Create a new python file named ‘main.py’. Import Flask from the flask framework. Import API and Resource from the ‘flask_restful’ library. Register the web app into a app variable using the following syntax. Python3 app = Flask(__name__) Register the app variable as an API object using the Api method of the ‘flask_restful’ library. Python3 api = Api(app) Create a resource class named ‘HelloWorld’. Inside the resource class, create a ‘get’ method. Return a dictionary with the ‘Hello World’ message from the ‘get’ method. Add the resource class to the API using the add_resource method. Build the flask application using the following command. Python3 if __name__ == '__main__': app.run(debug=True) Run the ‘main.py’ file in the terminal or the IDE and type the following URL in the browser. http://127.0.0.1:5000/hello Code : Python3 from flask import Flaskfrom flask_restful import Api, Resource app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): data={"data":"Hello World"} return data api.add_resource(HelloWorld,'/hello') if __name__=='__main__': app.run(debug=True) Output : Picked Python Flask TrueGeek-2021 Python TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? SQL Statement to Remove Part of a String Basics of API Testing Using Postman Types of Internet Protocols
[ { "code": null, "e": 24292, "s": 24264, "text": "\n17 Oct, 2021" }, { "code": null, "e": 24333, "s": 24292, "text": "Prerequisites: Introduction to REST API " }, { "code": null, "e": 24654, "s": 24333, "text": "REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple REST API that returns ‘Hello World’, with the help of a flask." }, { "code": null, "e": 24746, "s": 24654, "text": "In this article we are going to write a simple flask API for hello world using two methods:" }, { "code": null, "e": 24774, "s": 24746, "text": "Using Flask jsonify object." }, { "code": null, "e": 24818, "s": 24774, "text": "Using the flask_restful library with Flask." }, { "code": null, "e": 24883, "s": 24818, "text": "1. Install the python Flask library using the following command." }, { "code": null, "e": 24901, "s": 24883, "text": "pip install Flask" }, { "code": null, "e": 24967, "s": 24901, "text": "2. Install the flask-restful library using the following command." }, { "code": null, "e": 24993, "s": 24967, "text": "pip install Flask-RESTful" }, { "code": null, "e": 25035, "s": 24993, "text": "Create a new python file named ‘main.py’." }, { "code": null, "e": 25095, "s": 25035, "text": "import Flask, jsonify and request from the flask framework." }, { "code": null, "e": 25165, "s": 25095, "text": "Register the web app into an app variable using the following syntax." }, { "code": null, "e": 25173, "s": 25165, "text": "Python3" }, { "code": "app = Flask(__name__)", "e": 25197, "s": 25173, "text": null }, { "code": null, "e": 25311, "s": 25197, "text": "Create a new function named ‘helloworld’. This function is going to return the ‘Hello World’ text in JSON format." }, { "code": null, "e": 25391, "s": 25311, "text": "Route the ‘helloworld’ function to your desired URL using the following syntax." }, { "code": null, "e": 25399, "s": 25391, "text": "Python3" }, { "code": "@app.route('/path_of_the_response', methods=['GET'])def helloworld(): pass", "e": 25477, "s": 25399, "text": null }, { "code": null, "e": 25601, "s": 25477, "text": "Inside the ‘helloworld’ function if request method is ‘GET’ then create a python dictionary with the ‘Hello World’ message." }, { "code": null, "e": 25646, "s": 25601, "text": "Jsonify the python dictionary and return it." }, { "code": null, "e": 25703, "s": 25646, "text": "Build the flask application using the following command." }, { "code": null, "e": 25711, "s": 25703, "text": "Python3" }, { "code": "if __name__ == '__main__': app.run(debug=True)", "e": 25761, "s": 25711, "text": null }, { "code": null, "e": 25854, "s": 25761, "text": "Run the ‘main.py’ file in the terminal or the IDE and type the following URL in the browser." }, { "code": null, "e": 25882, "s": 25854, "text": "http://127.0.0.1:5000/hello" }, { "code": null, "e": 25889, "s": 25882, "text": "Code :" }, { "code": null, "e": 25897, "s": 25889, "text": "Python3" }, { "code": "from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/hello', methods=['GET'])def helloworld(): if(request.method == 'GET'): data = {\"data\": \"Hello World\"} return jsonify(data) if __name__ == '__main__': app.run(debug=True)", "e": 26171, "s": 25897, "text": null }, { "code": null, "e": 26180, "s": 26171, "text": "Output :" }, { "code": null, "e": 26222, "s": 26180, "text": "Create a new python file named ‘main.py’." }, { "code": null, "e": 26261, "s": 26222, "text": "Import Flask from the flask framework." }, { "code": null, "e": 26319, "s": 26261, "text": "Import API and Resource from the ‘flask_restful’ library." }, { "code": null, "e": 26388, "s": 26319, "text": "Register the web app into a app variable using the following syntax." }, { "code": null, "e": 26396, "s": 26388, "text": "Python3" }, { "code": "app = Flask(__name__)", "e": 26420, "s": 26396, "text": null }, { "code": null, "e": 26517, "s": 26420, "text": "Register the app variable as an API object using the Api method of the ‘flask_restful’ library." }, { "code": null, "e": 26525, "s": 26517, "text": "Python3" }, { "code": "api = Api(app)", "e": 26542, "s": 26525, "text": null }, { "code": null, "e": 26586, "s": 26542, "text": "Create a resource class named ‘HelloWorld’." }, { "code": null, "e": 26636, "s": 26586, "text": "Inside the resource class, create a ‘get’ method." }, { "code": null, "e": 26710, "s": 26636, "text": "Return a dictionary with the ‘Hello World’ message from the ‘get’ method." }, { "code": null, "e": 26775, "s": 26710, "text": "Add the resource class to the API using the add_resource method." }, { "code": null, "e": 26832, "s": 26775, "text": "Build the flask application using the following command." }, { "code": null, "e": 26840, "s": 26832, "text": "Python3" }, { "code": "if __name__ == '__main__': app.run(debug=True)", "e": 26890, "s": 26840, "text": null }, { "code": null, "e": 26983, "s": 26890, "text": "Run the ‘main.py’ file in the terminal or the IDE and type the following URL in the browser." }, { "code": null, "e": 27011, "s": 26983, "text": "http://127.0.0.1:5000/hello" }, { "code": null, "e": 27018, "s": 27011, "text": "Code :" }, { "code": null, "e": 27026, "s": 27018, "text": "Python3" }, { "code": "from flask import Flaskfrom flask_restful import Api, Resource app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): data={\"data\":\"Hello World\"} return data api.add_resource(HelloWorld,'/hello') if __name__=='__main__': app.run(debug=True)", "e": 27323, "s": 27026, "text": null }, { "code": null, "e": 27332, "s": 27323, "text": "Output :" }, { "code": null, "e": 27339, "s": 27332, "text": "Picked" }, { "code": null, "e": 27352, "s": 27339, "text": "Python Flask" }, { "code": null, "e": 27366, "s": 27352, "text": "TrueGeek-2021" }, { "code": null, "e": 27373, "s": 27366, "text": "Python" }, { "code": null, "e": 27382, "s": 27373, "text": "TrueGeek" }, { "code": null, "e": 27480, "s": 27382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27512, "s": 27480, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27568, "s": 27512, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27610, "s": 27568, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27652, "s": 27610, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27674, "s": 27652, "text": "Defaultdict in Python" }, { "code": null, "e": 27719, "s": 27674, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27776, "s": 27719, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27817, "s": 27776, "text": "SQL Statement to Remove Part of a String" }, { "code": null, "e": 27853, "s": 27817, "text": "Basics of API Testing Using Postman" } ]
MLflow Part 4: Interacting with the Server Client! | by David Hundley | Towards Data Science
Hello there all! Long time, no see, right? My previous post in this series was published all the way back in October 2020, which is coincidentally the time when a ton of new video games rolled out. Because I write these posts in my free time, I clearly was using my free time for other things. 😂 This will be the fourth and likely final post in our MLflow 101 series. It’s been a great ride, but all good things must come to an end. If you would like to catch up on the previous posts, please check them out at the following links: Part 1: Getting Started with MLflow! Part 2: Deploying a Tracking Server to Minikube! Part 3: Logging Models to a Tracking Server If you would like to follow along with the code shown in this post, you can find it at my personal GitHub here. To briefly recap where we left off from the last post, we had finally logged our first model into the MLflow tracking server we deployed out onto Kubernetes (Minikube). I intentionally logged the model as three different versions, and if you open them up in the MLflow server interface, this is what you might recall seeing: And as another quick refresher, the diagram below shows the architecture for how we have this server deployed. In short, we have a Postgres instance housing the metadata about our models, and we have a Minio server housing the model artifacts in an AWS S3-like interface. Remember, Minio is intentionally set up to emulate S3. This will be important to remember further on down in the post. Okay, so let’s dive into some new stuff now! As great as interacting with the MLflow UI is, it’s better if we can programmatically interact with the server client for consistency’s sake. There are a ton of cool things you can do with the Python tracking client, and you can learn all about them via MLflow’s documentation. For this post, we’ll cover just a few things. First, we need to connect to the client itself. In order to do this, you’ll need to recall the URI we created for our tracking server back in Part 2 of this series. In my case, my client’s URI is http://mlflow-server.local. Instantiating the MLflow client in Python is actually super simple. This is what that syntax looks like: # Importing our required librariesimport mlflowimport mlflow.sklearnimport pandas as pdimport os# Setting the MLflow clientclient = mlflow.tracking.MlflowClient(tracking_uri = 'http://mlflow-server.local') Before moving forward, we have to do one other special thing with some environment variables given that we are using the Minio artifact store. Because Minio emulates AWS and S3, it’s going to look for those same environment variables that AWS would look for if we were legitimately using AWS. You can export those environment variables from the command line, or if you’d like to do it right in your Python code, all you have to do is this: # Setting the requried environment variablesos.environ['MLFLOW_S3_ENDPOINT_URL'] = 'http://mlflow-minio.local/'os.environ['AWS_ACCESS_KEY_ID'] = 'minio'os.environ['AWS_SECRET_ACCESS_KEY'] = 'minio123' Client instantiated: check! Environment variables: check! We’re ready to roll, folks! Let’s start off with some simple stuff. Truth be told, I don’t know what real world use case you’d want to execute the following commands, but it’s nice to know they’re there. The first is a very simple list of all the model experiments we’ve created thus far, and the second shows all the versions of a particular model given it’s name. Here is the syntax, and down below shows the output of that syntax: # Listing the MLflow experimentsclient.list_experiments()# Getting the model versions for the wine-pyfile-modelresults = client.search_model_versions("name='wine-pyfile-model'")for res in results: print(f'name={res.name}; version={res.version}') For the client.list_experiments() function, you can see we have one experiment and other details about that experiment, including where the artifacts are stored in “S3” (aka Minio). In the next function, we do a search using the “wine-pyfile-model” name (as we completed in Part 3), and it shows that I have three different versions of that model in MLflow. “Okay,” you might be wondering, “when are we going to do something really useful?” Here’s where I think MLflow’s client interaction shows the most potential: model deployment. Now, for those of you familiar with MLflow, you’ll recognize that this is not the recommended way to deploy models with MLflow. MLflow actually does have another recommended way to deploy models, but truth be told... I’m not wild about it. In my opinion, I think it’s too rigid. It follows a very precise syntax and way to package things, and I just found it to be too much of a hassle to be useful. Instead of doing things the way MLflow would encourage them, I’m going to show you my preferred route using the same MLflow client we’ve been working with. In this pattern, we can use the MLflow client to find the precise location of our model artifact within “S3” (Minio) and directly load the model for usage within our Python file. In this example, I’m going to grab Version 2 of our model just to show we can grab whatever version we like. Here’s the syntax for using the client to both find and load the model: # Getting the URI for version 2 of the Wine modeluri = (client.get_model_version_download_uri(name = 'wine-pyfile-model', version='2')) + '/'print(uri)# Loading the model using the URI abovemodel = mlflow.sklearn.load_model(model_uri = uri) And that’s it! You now have your model loaded into memory, and you can use this for inference from here on out. I’m not going to show it in this post, but I have successfully deployed a Flask API to Kubernetes that does an upfront load of the model directly from MLflow and holds it in memory for all incoming inference requests. As a simple means to prove to you that this works, I’ll run this model against the same training data that we trained the model on originally. In the screenshot below, you can see that I’ve loaded the dataset, dropped the predictor value, and ran the remaining columns through the model. It produces inference outputs like a dream! Theoretically speaking, if you have all the proper security and networking measures in place, this means you can effectively deploy your model to any platform. For example, if I train all my models locally in Kubernetes and want to use them in AWS, GCP, or Azure, all I’d need to do is make a call out to Kubernetes and load in that model on the fly. Goodbye, vendor lock-in! And that wraps up this series on MLflow! Apologies again that this post was super delayed. I hope you found a lot of value in this series, and I learned a lot myself by writing these posts. I haven’t yet decided what my next series of posts will be, so if you would like to see something covered, please reach out to me with your input. Thanks again for reading!
[ { "code": null, "e": 468, "s": 172, "text": "Hello there all! Long time, no see, right? My previous post in this series was published all the way back in October 2020, which is coincidentally the time when a ton of new video games rolled out. Because I write these posts in my free time, I clearly was using my free time for other things. 😂" }, { "code": null, "e": 704, "s": 468, "text": "This will be the fourth and likely final post in our MLflow 101 series. It’s been a great ride, but all good things must come to an end. If you would like to catch up on the previous posts, please check them out at the following links:" }, { "code": null, "e": 741, "s": 704, "text": "Part 1: Getting Started with MLflow!" }, { "code": null, "e": 790, "s": 741, "text": "Part 2: Deploying a Tracking Server to Minikube!" }, { "code": null, "e": 834, "s": 790, "text": "Part 3: Logging Models to a Tracking Server" }, { "code": null, "e": 946, "s": 834, "text": "If you would like to follow along with the code shown in this post, you can find it at my personal GitHub here." }, { "code": null, "e": 1271, "s": 946, "text": "To briefly recap where we left off from the last post, we had finally logged our first model into the MLflow tracking server we deployed out onto Kubernetes (Minikube). I intentionally logged the model as three different versions, and if you open them up in the MLflow server interface, this is what you might recall seeing:" }, { "code": null, "e": 1662, "s": 1271, "text": "And as another quick refresher, the diagram below shows the architecture for how we have this server deployed. In short, we have a Postgres instance housing the metadata about our models, and we have a Minio server housing the model artifacts in an AWS S3-like interface. Remember, Minio is intentionally set up to emulate S3. This will be important to remember further on down in the post." }, { "code": null, "e": 2031, "s": 1662, "text": "Okay, so let’s dive into some new stuff now! As great as interacting with the MLflow UI is, it’s better if we can programmatically interact with the server client for consistency’s sake. There are a ton of cool things you can do with the Python tracking client, and you can learn all about them via MLflow’s documentation. For this post, we’ll cover just a few things." }, { "code": null, "e": 2360, "s": 2031, "text": "First, we need to connect to the client itself. In order to do this, you’ll need to recall the URI we created for our tracking server back in Part 2 of this series. In my case, my client’s URI is http://mlflow-server.local. Instantiating the MLflow client in Python is actually super simple. This is what that syntax looks like:" }, { "code": null, "e": 2566, "s": 2360, "text": "# Importing our required librariesimport mlflowimport mlflow.sklearnimport pandas as pdimport os# Setting the MLflow clientclient = mlflow.tracking.MlflowClient(tracking_uri = 'http://mlflow-server.local')" }, { "code": null, "e": 3006, "s": 2566, "text": "Before moving forward, we have to do one other special thing with some environment variables given that we are using the Minio artifact store. Because Minio emulates AWS and S3, it’s going to look for those same environment variables that AWS would look for if we were legitimately using AWS. You can export those environment variables from the command line, or if you’d like to do it right in your Python code, all you have to do is this:" }, { "code": null, "e": 3207, "s": 3006, "text": "# Setting the requried environment variablesos.environ['MLFLOW_S3_ENDPOINT_URL'] = 'http://mlflow-minio.local/'os.environ['AWS_ACCESS_KEY_ID'] = 'minio'os.environ['AWS_SECRET_ACCESS_KEY'] = 'minio123'" }, { "code": null, "e": 3699, "s": 3207, "text": "Client instantiated: check! Environment variables: check! We’re ready to roll, folks! Let’s start off with some simple stuff. Truth be told, I don’t know what real world use case you’d want to execute the following commands, but it’s nice to know they’re there. The first is a very simple list of all the model experiments we’ve created thus far, and the second shows all the versions of a particular model given it’s name. Here is the syntax, and down below shows the output of that syntax:" }, { "code": null, "e": 3948, "s": 3699, "text": "# Listing the MLflow experimentsclient.list_experiments()# Getting the model versions for the wine-pyfile-modelresults = client.search_model_versions(\"name='wine-pyfile-model'\")for res in results: print(f'name={res.name}; version={res.version}')" }, { "code": null, "e": 4306, "s": 3948, "text": "For the client.list_experiments() function, you can see we have one experiment and other details about that experiment, including where the artifacts are stored in “S3” (aka Minio). In the next function, we do a search using the “wine-pyfile-model” name (as we completed in Part 3), and it shows that I have three different versions of that model in MLflow." }, { "code": null, "e": 4882, "s": 4306, "text": "“Okay,” you might be wondering, “when are we going to do something really useful?” Here’s where I think MLflow’s client interaction shows the most potential: model deployment. Now, for those of you familiar with MLflow, you’ll recognize that this is not the recommended way to deploy models with MLflow. MLflow actually does have another recommended way to deploy models, but truth be told... I’m not wild about it. In my opinion, I think it’s too rigid. It follows a very precise syntax and way to package things, and I just found it to be too much of a hassle to be useful." }, { "code": null, "e": 5398, "s": 4882, "text": "Instead of doing things the way MLflow would encourage them, I’m going to show you my preferred route using the same MLflow client we’ve been working with. In this pattern, we can use the MLflow client to find the precise location of our model artifact within “S3” (Minio) and directly load the model for usage within our Python file. In this example, I’m going to grab Version 2 of our model just to show we can grab whatever version we like. Here’s the syntax for using the client to both find and load the model:" }, { "code": null, "e": 5639, "s": 5398, "text": "# Getting the URI for version 2 of the Wine modeluri = (client.get_model_version_download_uri(name = 'wine-pyfile-model', version='2')) + '/'print(uri)# Loading the model using the URI abovemodel = mlflow.sklearn.load_model(model_uri = uri)" }, { "code": null, "e": 5969, "s": 5639, "text": "And that’s it! You now have your model loaded into memory, and you can use this for inference from here on out. I’m not going to show it in this post, but I have successfully deployed a Flask API to Kubernetes that does an upfront load of the model directly from MLflow and holds it in memory for all incoming inference requests." }, { "code": null, "e": 6301, "s": 5969, "text": "As a simple means to prove to you that this works, I’ll run this model against the same training data that we trained the model on originally. In the screenshot below, you can see that I’ve loaded the dataset, dropped the predictor value, and ran the remaining columns through the model. It produces inference outputs like a dream!" }, { "code": null, "e": 6677, "s": 6301, "text": "Theoretically speaking, if you have all the proper security and networking measures in place, this means you can effectively deploy your model to any platform. For example, if I train all my models locally in Kubernetes and want to use them in AWS, GCP, or Azure, all I’d need to do is make a call out to Kubernetes and load in that model on the fly. Goodbye, vendor lock-in!" } ]
Capacity To Ship Packages Within D Days - GeeksforGeeks
06 Jul, 2021 Given an array arr[] consisting of N positive integers representing the weights of N items and a positive integer D, the task is to find the minimum weight capacity of a boat(say K) to ship all weights within D days such that the order of weights loaded on the ship is in the order of the array elements in arr[] and the total amount of weight loaded by ship each day is K. Examples: Input: arr[] = {1, 2, 1}, D = 2Output: 3Explanation:Consider the minimum weight required by the boat as 3, then below is the order of weights such all the weight can be shipped within D(= 2) days:Day 1: Ship the weights of values 1 and 2 on the first day as the sum of weights 1 + 2 = 3(<= 3).Day 2: Ship the weights of value 1 on the second day as the sum of weights 1(<= 3).Considering the minimum weight amount as 3, ships all the weight within D(= 2) days. Therefore, print 3. Input: arr[] = {9, 8, 10}, D = 3Output: 10 Approach: The given problem can be solved by using the Greedy Technique and Binary Search. The monotonicity of the problem can be observed that if all packages can be successfully shipped within D days with capacity K, then definitely they can be shipped with any capacity larger than K. Follow the steps below to solve the problem: Initialize a variable, say ans as -1 to store the resultant minimum capacity of the boat required. Initialize two variables, say s and e with the maximum element in the given array and the total sum of the array respectively which denotes the lower and upper bounds of the search space. Iterate until the value of s is less than or equals to e, and perform the following steps:Initialize a variable, say mid as (s + e)/2.Check if it is possible to ship all the packages within D days when the maximum capacity allowed is mid. If found to be true, then update the value of ans to mid and the value of e to (mid – 1).Otherwise, update the value of s to (mid + 1). Initialize a variable, say mid as (s + e)/2. Check if it is possible to ship all the packages within D days when the maximum capacity allowed is mid. If found to be true, then update the value of ans to mid and the value of e to (mid – 1). Otherwise, update the value of s to (mid + 1). After completing the above steps, print the value of ans as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to check if the weights // can be delivered in D days or not bool isValid(int weight[], int n, int D, int mx) { // Stores the count of days required // to ship all the weights if the // maximum capacity is mx int st = 1; int sum = 0; // Traverse all the weights for (int i = 0; i < n; i++) { sum += weight[i]; // If total weight is more than // the maximum capacity if (sum > mx) { st++; sum = weight[i]; } // If days are more than D, // then return false if (st > D) return false; } // Return true for the days < D return true; } // Function to find the least weight // capacity of a boat to ship all the // weights within D days void shipWithinDays(int weight[], int D, int n) { // Stores the total weights to // be shipped int sum = 0; // Find the sum of weights for (int i = 0; i < n; i++) sum += weight[i]; // Stores the maximum weight in the // array that has to be shipped int s = weight[0]; for (int i = 1; i < n; i++) { s = max(s, weight[i]); } // Store the ending value for // the search space int e = sum; // Store the required result int res = -1; // Perform binary search while (s <= e) { // Store the middle value int mid = s + (e - s) / 2; // If mid can be shipped, then // update the result and end // value of the search space if (isValid(weight, n, D, mid)) { res = mid; e = mid - 1; } // Search for minimum value // in the right part else s = mid + 1; } // Print the result cout << res; } // Driver Code int main() { int weight[] = { 9, 8, 10 }; int D = 3; int N = sizeof(weight) / sizeof(weight[0]); shipWithinDays(weight, D, N); return 0; } // Java program for the above approach import java.io.*; class GFG{ // Function to check if the weights // can be delivered in D days or not static boolean isValid(int[] weight, int n, int D, int mx) { // Stores the count of days required // to ship all the weights if the // maximum capacity is mx int st = 1; int sum = 0; // Traverse all the weights for(int i = 0; i < n; i++) { sum += weight[i]; // If total weight is more than // the maximum capacity if (sum > mx) { st++; sum = weight[i]; } // If days are more than D, // then return false if (st > D) return false; } // Return true for the days < D return true; } // Function to find the least weight // capacity of a boat to ship all the // weights within D days static void shipWithinDays(int[] weight, int D, int n) { // Stores the total weights to // be shipped int sum = 0; // Find the sum of weights for(int i = 0; i < n; i++) sum += weight[i]; // Stores the maximum weight in the // array that has to be shipped int s = weight[0]; for(int i = 1; i < n; i++) { s = Math.max(s, weight[i]); } // Store the ending value for // the search space int e = sum; // Store the required result int res = -1; // Perform binary search while (s <= e) { // Store the middle value int mid = s + (e - s) / 2; // If mid can be shipped, then // update the result and end // value of the search space if (isValid(weight, n, D, mid)) { res = mid; e = mid - 1; } // Search for minimum value // in the right part else s = mid + 1; } // Print the result System.out.println(res); } // Driver Code public static void main(String[] args) { int[] weight = { 9, 8, 10 }; int D = 3; int N = weight.length; shipWithinDays(weight, D, N); } } // This code is contributed by Dharanendra L V. # Python3 program for the above approach # Function to check if the weights # can be delivered in D days or not def isValid(weight, n, D, mx): # Stores the count of days required # to ship all the weights if the # maximum capacity is mx st = 1 sum = 0 # Traverse all the weights for i in range(n): sum += weight[i] # If total weight is more than # the maximum capacity if (sum > mx): st += 1 sum = weight[i] # If days are more than D, # then return false if (st > D): return False # Return true for the days < D return True # Function to find the least weight # capacity of a boat to ship all the # weights within D days def shipWithinDays(weight, D, n): # Stores the total weights to # be shipped sum = 0 # Find the sum of weights for i in range(n): sum += weight[i] # Stores the maximum weight in the # array that has to be shipped s = weight[0] for i in range(1, n): s = max(s, weight[i]) # Store the ending value for # the search space e = sum # Store the required result res = -1 # Perform binary search while (s <= e): # Store the middle value mid = s + (e - s) // 2 # If mid can be shipped, then # update the result and end # value of the search space if (isValid(weight, n, D, mid)): res = mid e = mid - 1 # Search for minimum value # in the right part else: s = mid + 1 # Print the result print(res) # Driver Code if __name__ == '__main__': weight = [ 9, 8, 10 ] D = 3 N = len(weight) shipWithinDays(weight, D, N) # This code is contributed by ipg2016107 // C# program for the above approach using System; class GFG{ // Function to check if the weights // can be delivered in D days or not static bool isValid(int[] weight, int n, int D, int mx) { // Stores the count of days required // to ship all the weights if the // maximum capacity is mx int st = 1; int sum = 0; // Traverse all the weights for(int i = 0; i < n; i++) { sum += weight[i]; // If total weight is more than // the maximum capacity if (sum > mx) { st++; sum = weight[i]; } // If days are more than D, // then return false if (st > D) return false; } // Return true for the days < D return true; } // Function to find the least weight // capacity of a boat to ship all the // weights within D days static void shipWithinDays(int[] weight, int D, int n) { // Stores the total weights to // be shipped int sum = 0; // Find the sum of weights for(int i = 0; i < n; i++) sum += weight[i]; // Stores the maximum weight in the // array that has to be shipped int s = weight[0]; for(int i = 1; i < n; i++) { s = Math.Max(s, weight[i]); } // Store the ending value for // the search space int e = sum; // Store the required result int res = -1; // Perform binary search while (s <= e) { // Store the middle value int mid = s + (e - s) / 2; // If mid can be shipped, then // update the result and end // value of the search space if (isValid(weight, n, D, mid)) { res = mid; e = mid - 1; } // Search for minimum value // in the right part else s = mid + 1; } // Print the result Console.WriteLine(res); } // Driver Code public static void Main() { int[] weight = { 9, 8, 10 }; int D = 3; int N = weight.Length; shipWithinDays(weight, D, N); } } // This code is contributed by ukasp <script> // JavaScript program for the above approach // Function to check if the weights // can be delivered in D days or not function isValid(weight, n, D, mx) { // Stores the count of days required // to ship all the weights if the // maximum capacity is mx let st = 1; let sum = 0; // Traverse all the weights for(let i = 0; i < n; i++) { sum += weight[i]; // If total weight is more than // the maximum capacity if (sum > mx) { st++; sum = weight[i]; } // If days are more than D, // then return false if (st > D) return false; } // Return true for the days < D return true; } // Function to find the least weight // capacity of a boat to ship all the // weights within D days function shipWithinDays(weight, D, n) { // Stores the total weights to // be shipped let sum = 0; // Find the sum of weights for(let i = 0; i < n; i++) sum += weight[i]; // Stores the maximum weight in the // array that has to be shipped let s = weight[0]; for(let i = 1; i < n; i++) { s = Math.max(s, weight[i]); } // Store the ending value for // the search space let e = sum; // Store the required result let res = -1; // Perform binary search while (s <= e) { // Store the middle value let mid = s + Math.floor((e - s) / 2); // If mid can be shipped, then // update the result and end // value of the search space if (isValid(weight, n, D, mid)) { res = mid; e = mid - 1; } // Search for minimum value // in the right part else s = mid + 1; } // Print the result document.write(res); } // Driver Code let weight = [ 9, 8, 10 ]; let D = 3; let N = weight.length; shipWithinDays(weight, D, N); </script> 10 Time Complexity: O(N*log(S – M)), where S is the sum of the array elements and M is the maximum element of the array.Auxiliary Space: O(1) ukasp dharanendralv23 sanjoy_62 ipg2016107 sweetyty Binary Search DE Shaw interview-preparation Arrays Greedy Mathematical Searching DE Shaw Arrays Searching Greedy Mathematical Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24890, "s": 24862, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25264, "s": 24890, "text": "Given an array arr[] consisting of N positive integers representing the weights of N items and a positive integer D, the task is to find the minimum weight capacity of a boat(say K) to ship all weights within D days such that the order of weights loaded on the ship is in the order of the array elements in arr[] and the total amount of weight loaded by ship each day is K." }, { "code": null, "e": 25274, "s": 25264, "text": "Examples:" }, { "code": null, "e": 25755, "s": 25274, "text": "Input: arr[] = {1, 2, 1}, D = 2Output: 3Explanation:Consider the minimum weight required by the boat as 3, then below is the order of weights such all the weight can be shipped within D(= 2) days:Day 1: Ship the weights of values 1 and 2 on the first day as the sum of weights 1 + 2 = 3(<= 3).Day 2: Ship the weights of value 1 on the second day as the sum of weights 1(<= 3).Considering the minimum weight amount as 3, ships all the weight within D(= 2) days. Therefore, print 3." }, { "code": null, "e": 25798, "s": 25755, "text": "Input: arr[] = {9, 8, 10}, D = 3Output: 10" }, { "code": null, "e": 26131, "s": 25798, "text": "Approach: The given problem can be solved by using the Greedy Technique and Binary Search. The monotonicity of the problem can be observed that if all packages can be successfully shipped within D days with capacity K, then definitely they can be shipped with any capacity larger than K. Follow the steps below to solve the problem:" }, { "code": null, "e": 26230, "s": 26131, "text": "Initialize a variable, say ans as -1 to store the resultant minimum capacity of the boat required." }, { "code": null, "e": 26418, "s": 26230, "text": "Initialize two variables, say s and e with the maximum element in the given array and the total sum of the array respectively which denotes the lower and upper bounds of the search space." }, { "code": null, "e": 26793, "s": 26418, "text": "Iterate until the value of s is less than or equals to e, and perform the following steps:Initialize a variable, say mid as (s + e)/2.Check if it is possible to ship all the packages within D days when the maximum capacity allowed is mid. If found to be true, then update the value of ans to mid and the value of e to (mid – 1).Otherwise, update the value of s to (mid + 1)." }, { "code": null, "e": 26838, "s": 26793, "text": "Initialize a variable, say mid as (s + e)/2." }, { "code": null, "e": 27033, "s": 26838, "text": "Check if it is possible to ship all the packages within D days when the maximum capacity allowed is mid. If found to be true, then update the value of ans to mid and the value of e to (mid – 1)." }, { "code": null, "e": 27080, "s": 27033, "text": "Otherwise, update the value of s to (mid + 1)." }, { "code": null, "e": 27152, "s": 27080, "text": "After completing the above steps, print the value of ans as the result." }, { "code": null, "e": 27203, "s": 27152, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27207, "s": 27203, "text": "C++" }, { "code": null, "e": 27212, "s": 27207, "text": "Java" }, { "code": null, "e": 27220, "s": 27212, "text": "Python3" }, { "code": null, "e": 27223, "s": 27220, "text": "C#" }, { "code": null, "e": 27234, "s": 27223, "text": "Javascript" }, { "code": null, "e": 29316, "s": 27234, "text": "// C++ program for the above approach\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Function to check if the weights\n// can be delivered in D days or not\nbool isValid(int weight[], int n,\n int D, int mx)\n{\n // Stores the count of days required\n // to ship all the weights if the\n // maximum capacity is mx\n int st = 1;\n int sum = 0;\n\n // Traverse all the weights\n for (int i = 0; i < n; i++) {\n sum += weight[i];\n\n // If total weight is more than\n // the maximum capacity\n if (sum > mx) {\n st++;\n sum = weight[i];\n }\n\n // If days are more than D,\n // then return false\n if (st > D)\n return false;\n }\n\n // Return true for the days < D\n return true;\n}\n\n// Function to find the least weight\n// capacity of a boat to ship all the\n// weights within D days\nvoid shipWithinDays(int weight[], int D,\n int n)\n{\n // Stores the total weights to\n // be shipped\n int sum = 0;\n\n // Find the sum of weights\n for (int i = 0; i < n; i++)\n sum += weight[i];\n\n // Stores the maximum weight in the\n // array that has to be shipped\n int s = weight[0];\n for (int i = 1; i < n; i++) {\n s = max(s, weight[i]);\n }\n\n // Store the ending value for\n // the search space\n int e = sum;\n\n // Store the required result\n int res = -1;\n\n // Perform binary search\n while (s <= e) {\n\n // Store the middle value\n int mid = s + (e - s) / 2;\n\n // If mid can be shipped, then\n // update the result and end\n // value of the search space\n if (isValid(weight, n, D, mid)) {\n res = mid;\n e = mid - 1;\n }\n\n // Search for minimum value\n // in the right part\n else\n s = mid + 1;\n }\n\n // Print the result\n cout << res;\n}\n\n// Driver Code\nint main()\n{\n int weight[] = { 9, 8, 10 };\n int D = 3;\n int N = sizeof(weight) / sizeof(weight[0]);\n shipWithinDays(weight, D, N);\n\n return 0;\n}\n" }, { "code": null, "e": 31507, "s": 29316, "text": "// Java program for the above approach\nimport java.io.*;\n\nclass GFG{\n \n// Function to check if the weights\n// can be delivered in D days or not\nstatic boolean isValid(int[] weight, int n, \n int D, int mx)\n{\n \n // Stores the count of days required\n // to ship all the weights if the\n // maximum capacity is mx\n int st = 1;\n int sum = 0;\n\n // Traverse all the weights\n for(int i = 0; i < n; i++)\n {\n sum += weight[i];\n\n // If total weight is more than\n // the maximum capacity\n if (sum > mx)\n {\n st++;\n sum = weight[i];\n }\n\n // If days are more than D,\n // then return false\n if (st > D)\n return false;\n }\n\n // Return true for the days < D\n return true;\n}\n\n// Function to find the least weight\n// capacity of a boat to ship all the\n// weights within D days\nstatic void shipWithinDays(int[] weight, int D, int n)\n{\n \n // Stores the total weights to\n // be shipped\n int sum = 0;\n\n // Find the sum of weights\n for(int i = 0; i < n; i++)\n sum += weight[i];\n\n // Stores the maximum weight in the\n // array that has to be shipped\n int s = weight[0];\n for(int i = 1; i < n; i++)\n {\n s = Math.max(s, weight[i]);\n }\n\n // Store the ending value for\n // the search space\n int e = sum;\n\n // Store the required result\n int res = -1;\n\n // Perform binary search\n while (s <= e) \n {\n \n // Store the middle value\n int mid = s + (e - s) / 2;\n\n // If mid can be shipped, then\n // update the result and end\n // value of the search space\n if (isValid(weight, n, D, mid)) \n {\n res = mid;\n e = mid - 1;\n }\n\n // Search for minimum value\n // in the right part\n else\n s = mid + 1;\n }\n\n // Print the result\n System.out.println(res);\n}\n\n// Driver Code\npublic static void main(String[] args) \n{\n \n int[] weight = { 9, 8, 10 };\n int D = 3;\n int N = weight.length;\n \n shipWithinDays(weight, D, N);\n}\n}\n\n// This code is contributed by Dharanendra L V." }, { "code": null, "e": 33356, "s": 31507, "text": "# Python3 program for the above approach\n\n# Function to check if the weights\n# can be delivered in D days or not\ndef isValid(weight, n, D, mx):\n \n # Stores the count of days required\n # to ship all the weights if the\n # maximum capacity is mx\n st = 1\n sum = 0\n\n # Traverse all the weights\n for i in range(n):\n sum += weight[i]\n\n # If total weight is more than\n # the maximum capacity\n if (sum > mx):\n st += 1\n sum = weight[i]\n\n # If days are more than D,\n # then return false\n if (st > D):\n return False\n\n # Return true for the days < D\n return True\n\n# Function to find the least weight\n# capacity of a boat to ship all the\n# weights within D days\ndef shipWithinDays(weight, D, n):\n \n # Stores the total weights to\n # be shipped\n sum = 0\n\n # Find the sum of weights\n for i in range(n):\n sum += weight[i]\n\n # Stores the maximum weight in the\n # array that has to be shipped\n s = weight[0]\n for i in range(1, n):\n s = max(s, weight[i])\n\n # Store the ending value for\n # the search space\n e = sum\n\n # Store the required result\n res = -1\n\n # Perform binary search\n while (s <= e):\n \n # Store the middle value\n mid = s + (e - s) // 2\n\n # If mid can be shipped, then\n # update the result and end\n # value of the search space\n if (isValid(weight, n, D, mid)):\n res = mid\n e = mid - 1\n\n # Search for minimum value\n # in the right part\n else:\n s = mid + 1\n\n # Print the result\n print(res)\n\n# Driver Code\nif __name__ == '__main__':\n \n weight = [ 9, 8, 10 ]\n D = 3\n N = len(weight)\n \n shipWithinDays(weight, D, N)\n\n# This code is contributed by ipg2016107" }, { "code": null, "e": 35502, "s": 33356, "text": "// C# program for the above approach\nusing System;\n\nclass GFG{\n\n// Function to check if the weights\n// can be delivered in D days or not\nstatic bool isValid(int[] weight, int n, \n int D, int mx)\n{\n \n // Stores the count of days required\n // to ship all the weights if the\n // maximum capacity is mx\n int st = 1;\n int sum = 0;\n\n // Traverse all the weights\n for(int i = 0; i < n; i++)\n {\n sum += weight[i];\n\n // If total weight is more than\n // the maximum capacity\n if (sum > mx)\n {\n st++;\n sum = weight[i];\n }\n\n // If days are more than D,\n // then return false\n if (st > D)\n return false;\n }\n\n // Return true for the days < D\n return true;\n}\n\n// Function to find the least weight\n// capacity of a boat to ship all the\n// weights within D days\nstatic void shipWithinDays(int[] weight, int D, int n)\n{\n \n // Stores the total weights to\n // be shipped\n int sum = 0;\n\n // Find the sum of weights\n for(int i = 0; i < n; i++)\n sum += weight[i];\n\n // Stores the maximum weight in the\n // array that has to be shipped\n int s = weight[0];\n for(int i = 1; i < n; i++)\n {\n s = Math.Max(s, weight[i]);\n }\n\n // Store the ending value for\n // the search space\n int e = sum;\n\n // Store the required result\n int res = -1;\n\n // Perform binary search\n while (s <= e) \n {\n \n // Store the middle value\n int mid = s + (e - s) / 2;\n\n // If mid can be shipped, then\n // update the result and end\n // value of the search space\n if (isValid(weight, n, D, mid)) \n {\n res = mid;\n e = mid - 1;\n }\n\n // Search for minimum value\n // in the right part\n else\n s = mid + 1;\n }\n\n // Print the result\n Console.WriteLine(res);\n}\n\n// Driver Code\npublic static void Main()\n{\n int[] weight = { 9, 8, 10 };\n int D = 3;\n int N = weight.Length;\n \n shipWithinDays(weight, D, N);\n}\n}\n\n// This code is contributed by ukasp" }, { "code": null, "e": 37570, "s": 35502, "text": "<script>\n\n// JavaScript program for the above approach\n\n// Function to check if the weights\n// can be delivered in D days or not\nfunction isValid(weight, n,\n D, mx)\n{\n \n // Stores the count of days required\n // to ship all the weights if the\n // maximum capacity is mx\n let st = 1;\n let sum = 0;\n \n // Traverse all the weights\n for(let i = 0; i < n; i++)\n {\n sum += weight[i];\n \n // If total weight is more than\n // the maximum capacity\n if (sum > mx)\n {\n st++;\n sum = weight[i];\n }\n \n // If days are more than D,\n // then return false\n if (st > D)\n return false;\n }\n \n // Return true for the days < D\n return true;\n}\n \n// Function to find the least weight\n// capacity of a boat to ship all the\n// weights within D days\nfunction shipWithinDays(weight, D, n)\n{\n \n // Stores the total weights to\n // be shipped\n let sum = 0;\n \n // Find the sum of weights\n for(let i = 0; i < n; i++)\n sum += weight[i];\n \n // Stores the maximum weight in the\n // array that has to be shipped\n let s = weight[0];\n for(let i = 1; i < n; i++)\n {\n s = Math.max(s, weight[i]);\n }\n \n // Store the ending value for\n // the search space\n let e = sum;\n \n // Store the required result\n let res = -1;\n \n // Perform binary search\n while (s <= e)\n {\n \n // Store the middle value\n let mid = s + Math.floor((e - s) / 2);\n \n // If mid can be shipped, then\n // update the result and end\n // value of the search space\n if (isValid(weight, n, D, mid))\n {\n res = mid;\n e = mid - 1;\n }\n \n // Search for minimum value\n // in the right part\n else\n s = mid + 1;\n }\n \n // Print the result\n document.write(res);\n}\n\n// Driver Code\n\n let weight = [ 9, 8, 10 ];\n let D = 3;\n let N = weight.length;\n \n shipWithinDays(weight, D, N);\n\n</script> \n" }, { "code": null, "e": 37573, "s": 37570, "text": "10" }, { "code": null, "e": 37714, "s": 37575, "text": "Time Complexity: O(N*log(S – M)), where S is the sum of the array elements and M is the maximum element of the array.Auxiliary Space: O(1)" }, { "code": null, "e": 37720, "s": 37714, "text": "ukasp" }, { "code": null, "e": 37736, "s": 37720, "text": "dharanendralv23" }, { "code": null, "e": 37746, "s": 37736, "text": "sanjoy_62" }, { "code": null, "e": 37757, "s": 37746, "text": "ipg2016107" }, { "code": null, "e": 37766, "s": 37757, "text": "sweetyty" }, { "code": null, "e": 37780, "s": 37766, "text": "Binary Search" }, { "code": null, "e": 37788, "s": 37780, "text": "DE Shaw" }, { "code": null, "e": 37810, "s": 37788, "text": "interview-preparation" }, { "code": null, "e": 37817, "s": 37810, "text": "Arrays" }, { "code": null, "e": 37824, "s": 37817, "text": "Greedy" }, { "code": null, "e": 37837, "s": 37824, "text": "Mathematical" }, { "code": null, "e": 37847, "s": 37837, "text": "Searching" }, { "code": null, "e": 37855, "s": 37847, "text": "DE Shaw" }, { "code": null, "e": 37862, "s": 37855, "text": "Arrays" }, { "code": null, "e": 37872, "s": 37862, "text": "Searching" }, { "code": null, "e": 37879, "s": 37872, "text": "Greedy" }, { "code": null, "e": 37892, "s": 37879, "text": "Mathematical" }, { "code": null, "e": 37906, "s": 37892, "text": "Binary Search" }, { "code": null, "e": 38004, "s": 37906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38013, "s": 38004, "text": "Comments" }, { "code": null, "e": 38026, "s": 38013, "text": "Old Comments" }, { "code": null, "e": 38074, "s": 38026, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38118, "s": 38074, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 38150, "s": 38118, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38173, "s": 38150, "text": "Introduction to Arrays" }, { "code": null, "e": 38187, "s": 38173, "text": "Linear Search" }, { "code": null, "e": 38238, "s": 38187, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 38296, "s": 38238, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 38347, "s": 38296, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 38378, "s": 38347, "text": "Huffman Coding | Greedy Algo-3" } ]
Implementing Linear Search in JavaScript
Following is the code for implementing linear search in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 20px; font-weight: 500; color: blueviolet; } .sample{ color:red; } </style> </head> <body> <h1>Implementing linear search</h1> <div class="sample">[1,19,5,11,22,55]</div><br> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to search for 22 in the above array</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let arr = [1,19,5,11,22,55]; BtnEle.addEventListener("click", () => { for(let i=0;i<arr.length;i++){ if(arr[i]===22){ resEle.innerHTML = 'Element found at : '+i; break; } } }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1131, "s": 1062, "text": "Following is the code for implementing linear search in JavaScript −" }, { "code": null, "e": 1142, "s": 1131, "text": " Live Demo" }, { "code": null, "e": 2154, "s": 1142, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,.sample {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n .sample{\n color:red;\n }\n</style>\n</head>\n<body>\n<h1>Implementing linear search</h1>\n<div class=\"sample\">[1,19,5,11,22,55]</div><br>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to search for 22 in the above array</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n let arr = [1,19,5,11,22,55];\n BtnEle.addEventListener(\"click\", () => {\n for(let i=0;i<arr.length;i++){\n if(arr[i]===22){\n resEle.innerHTML = 'Element found at : '+i;\n break;\n }\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2192, "s": 2154, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Mouse Cursor Control Using Facial Movements — An HCI Application | by Akshay L Chandra | Towards Data Science
This HCI (Human-Computer Interaction) application in Python(3.6) will allow you to control your mouse cursor with your facial movements, works with just your regular webcam. Its hands-free, no wearable hardware or sensors needed. Special thanks to Adrian Rosebrock for his amazing blog posts [2] [3], code snippets and his imutils library [7] that played an important role in making this idea of mine a reality. Now, I definitely understand that these facial movements could be a little bit weird to do, especially when you are around people. Being a patient of benign-positional-vertigo, I hate doing some of these actions myself. But I hope to make them easier and less weird over time. Feel free to suggest some public friendly actions that I can incorporate in the project. You can find the code files here: github.com Numpy — 1.13.3 OpenCV — 3.2.0 PyAutoGUI — 0.9.36 Dlib — 19.4.0 Imutils — 0.4.6 Execution steps are mentioned in the README.md of the repo. Feel free to raise an issue in case of any errors. This project is deeply centered around predicting the facial landmarks of a given face. We can accomplish a lot of things using these landmarks. From detecting eye-blinks [3] in a video to predicting emotions of the subject. The applications, outcomes, and possibilities of facial landmarks are immense and intriguing. Dlib’s prebuilt model, which is essentially an implementation of [4], not only does a fast face-detection but also allows us to accurately predict 68 2D facial landmarks. Very handy. Using these predicted landmarks of the face, we can build appropriate features that will further allow us to detect certain actions, like using the eye-aspect-ratio (more on this below) to detect a blink or a wink, using the mouth-aspect-ratio to detect a yawn etc or maybe even a pout. In this project, these actions are programmed as triggers to control the mouse cursor. PyAutoGUI library was used to move the cursor around. You will see that Eye-Aspect-Ratio [1] is the simplest and the most elegant feature that takes good advantage of the facial landmarks. EAR helps us in detecting blinks [3] and winks etc. You can see that the EAR value drops whenever the eye closes. We can train a simple classifier to detect the drop. However, a normal if condition works just fine. Something like this: if EAR <= SOME_THRESHOLD: EYE_STATUS = 'CLOSE' Highly inspired by the EAR feature, I tweaked the formula a little bit to get a metric that can detect opened/closed mouth. Unoriginal but it works. Similar to EAR, MAR value goes up when the mouth opens. Similar intuitions hold true for this metric as well. The model offers two important functions. A detector to detect the face and a predictor to predict the landmarks. The face detector used is made using the classic Histogram of Oriented Gradients (HOG) feature combined with a linear classifier, an image pyramid, and sliding window detection scheme. The facial landmarks estimator was created by using Dlib’s implementation of the paper: One Millisecond Face Alignment with an Ensemble of Regression Trees by Vahid Kazemi and Josephine Sullivan, CVPR 2014. And was trained on the iBUG 300-W face landmark dataset: C. Sagonas, E. Antonakos, G, Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 faces In-the-wild challenge: Database and results. Image and Vision Computing (IMAVIS), Special Issue on Facial Landmark Localisation “In-The-Wild”. 2016. You can get the trained model file from http://dlib.net/files, click on shape_predictor_68_face_landmarks.dat.bz2. The model, .dat file has to be in the project folder. Note: The license for the iBUG 300-W dataset excludes commercial use. So you should contact Imperial College London to find out if it’s OK for you to use this model file in a commercial product. [1]. Tereza Soukupova ́ and Jan Cˇ ech. Real-Time Eye Blink Detection using Facial Landmarks. In 21st Computer Vision Winter Workshop, February 2016.[2]. Adrian Rosebrock. Detect eyes, nose, lips, and jaw with dlib, OpenCV, and Python. [3]. Adrian Rosebrock. Eye blink detection with OpenCV, Python, and dlib.[4]. Vahid Kazemi, Josephine Sullivan. One millisecond face alignment with an ensemble of regression trees. In CVPR, 2014.[5]. S. Zafeiriou, G. Tzimiropoulos, and M. Pantic. The 300 videos in the wild (300-VW) facial landmark tracking in-the-wild challenge. In ICCV Workshop, 2015. [6]. C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 Faces in-the-Wild Challenge: The first facial landmark localization Challenge. Proceedings of IEEE Int’l Conf. on Computer Vision (ICCV-W), 300 Faces in-the-Wild Challenge (300-W). Sydney, Australia, December 2013[7]. Adrian Rosebrock. Imutils. https://github.com/jrosebr1/imutils.
[ { "code": null, "e": 401, "s": 171, "text": "This HCI (Human-Computer Interaction) application in Python(3.6) will allow you to control your mouse cursor with your facial movements, works with just your regular webcam. Its hands-free, no wearable hardware or sensors needed." }, { "code": null, "e": 583, "s": 401, "text": "Special thanks to Adrian Rosebrock for his amazing blog posts [2] [3], code snippets and his imutils library [7] that played an important role in making this idea of mine a reality." }, { "code": null, "e": 949, "s": 583, "text": "Now, I definitely understand that these facial movements could be a little bit weird to do, especially when you are around people. Being a patient of benign-positional-vertigo, I hate doing some of these actions myself. But I hope to make them easier and less weird over time. Feel free to suggest some public friendly actions that I can incorporate in the project." }, { "code": null, "e": 983, "s": 949, "text": "You can find the code files here:" }, { "code": null, "e": 994, "s": 983, "text": "github.com" }, { "code": null, "e": 1009, "s": 994, "text": "Numpy — 1.13.3" }, { "code": null, "e": 1024, "s": 1009, "text": "OpenCV — 3.2.0" }, { "code": null, "e": 1043, "s": 1024, "text": "PyAutoGUI — 0.9.36" }, { "code": null, "e": 1057, "s": 1043, "text": "Dlib — 19.4.0" }, { "code": null, "e": 1073, "s": 1057, "text": "Imutils — 0.4.6" }, { "code": null, "e": 1184, "s": 1073, "text": "Execution steps are mentioned in the README.md of the repo. Feel free to raise an issue in case of any errors." }, { "code": null, "e": 1503, "s": 1184, "text": "This project is deeply centered around predicting the facial landmarks of a given face. We can accomplish a lot of things using these landmarks. From detecting eye-blinks [3] in a video to predicting emotions of the subject. The applications, outcomes, and possibilities of facial landmarks are immense and intriguing." }, { "code": null, "e": 1686, "s": 1503, "text": "Dlib’s prebuilt model, which is essentially an implementation of [4], not only does a fast face-detection but also allows us to accurately predict 68 2D facial landmarks. Very handy." }, { "code": null, "e": 2114, "s": 1686, "text": "Using these predicted landmarks of the face, we can build appropriate features that will further allow us to detect certain actions, like using the eye-aspect-ratio (more on this below) to detect a blink or a wink, using the mouth-aspect-ratio to detect a yawn etc or maybe even a pout. In this project, these actions are programmed as triggers to control the mouse cursor. PyAutoGUI library was used to move the cursor around." }, { "code": null, "e": 2301, "s": 2114, "text": "You will see that Eye-Aspect-Ratio [1] is the simplest and the most elegant feature that takes good advantage of the facial landmarks. EAR helps us in detecting blinks [3] and winks etc." }, { "code": null, "e": 2485, "s": 2301, "text": "You can see that the EAR value drops whenever the eye closes. We can train a simple classifier to detect the drop. However, a normal if condition works just fine. Something like this:" }, { "code": null, "e": 2537, "s": 2485, "text": "if EAR <= SOME_THRESHOLD: EYE_STATUS = 'CLOSE'" }, { "code": null, "e": 2686, "s": 2537, "text": "Highly inspired by the EAR feature, I tweaked the formula a little bit to get a metric that can detect opened/closed mouth. Unoriginal but it works." }, { "code": null, "e": 2796, "s": 2686, "text": "Similar to EAR, MAR value goes up when the mouth opens. Similar intuitions hold true for this metric as well." }, { "code": null, "e": 3095, "s": 2796, "text": "The model offers two important functions. A detector to detect the face and a predictor to predict the landmarks. The face detector used is made using the classic Histogram of Oriented Gradients (HOG) feature combined with a linear classifier, an image pyramid, and sliding window detection scheme." }, { "code": null, "e": 3587, "s": 3095, "text": "The facial landmarks estimator was created by using Dlib’s implementation of the paper: One Millisecond Face Alignment with an Ensemble of Regression Trees by Vahid Kazemi and Josephine Sullivan, CVPR 2014. And was trained on the iBUG 300-W face landmark dataset: C. Sagonas, E. Antonakos, G, Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 faces In-the-wild challenge: Database and results. Image and Vision Computing (IMAVIS), Special Issue on Facial Landmark Localisation “In-The-Wild”. 2016." }, { "code": null, "e": 3756, "s": 3587, "text": "You can get the trained model file from http://dlib.net/files, click on shape_predictor_68_face_landmarks.dat.bz2. The model, .dat file has to be in the project folder." }, { "code": null, "e": 3951, "s": 3756, "text": "Note: The license for the iBUG 300-W dataset excludes commercial use. So you should contact Imperial College London to find out if it’s OK for you to use this model file in a commercial product." } ]
UUID timestamp() Method in Java with Examples
27 Dec, 2018 The timestamp() method of UUID class in Java is generally used to get the stamp value associated with a particular UUID. Syntax: public long timestamp() Parameters: This method does not take any parameter. Return Value: This method returns the time stamp value of this UUID. Exception: This method throws UnsupportedOperationException if this UUID is not a part of version 1 UUID. Below programs illustrate the working of timestamp() method: Program 1: // Java code to illustrate timestamp() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( "58e0a7d7-eebc-11d8-9669-0800200c9a66"); // Displaying the UUID System.out.println("UUID: " + UUID_1); // Displaying the timestamp value System.out.println("The timestamp value is: " + UUID_1.timestamp()); }} UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66 The timestamp value is: 133118681719810007 Program 2: // Java code to illustrate timestamp() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( "5fc03087-d265-11e7-b8c6-83e29cd24f4c"); // Displaying the UUID System.out.println("UUID: " + UUID_1); // Displaying the timestamp Value System.out.println("The timestamp value is: " + UUID_1.timestamp()); }} UUID: 5fc03087-d265-11e7-b8c6-83e29cd24f4c The timestamp value is: 137309646498050183 Java - util package Java-Functions Java-UUID 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": "\n27 Dec, 2018" }, { "code": null, "e": 149, "s": 28, "text": "The timestamp() method of UUID class in Java is generally used to get the stamp value associated with a particular UUID." }, { "code": null, "e": 157, "s": 149, "text": "Syntax:" }, { "code": null, "e": 181, "s": 157, "text": "public long timestamp()" }, { "code": null, "e": 234, "s": 181, "text": "Parameters: This method does not take any parameter." }, { "code": null, "e": 303, "s": 234, "text": "Return Value: This method returns the time stamp value of this UUID." }, { "code": null, "e": 409, "s": 303, "text": "Exception: This method throws UnsupportedOperationException if this UUID is not a part of version 1 UUID." }, { "code": null, "e": 470, "s": 409, "text": "Below programs illustrate the working of timestamp() method:" }, { "code": null, "e": 481, "s": 470, "text": "Program 1:" }, { "code": "// Java code to illustrate timestamp() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( \"58e0a7d7-eebc-11d8-9669-0800200c9a66\"); // Displaying the UUID System.out.println(\"UUID: \" + UUID_1); // Displaying the timestamp value System.out.println(\"The timestamp value is: \" + UUID_1.timestamp()); }}", "e": 1036, "s": 481, "text": null }, { "code": null, "e": 1123, "s": 1036, "text": "UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66\nThe timestamp value is: 133118681719810007\n" }, { "code": null, "e": 1134, "s": 1123, "text": "Program 2:" }, { "code": "// Java code to illustrate timestamp() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( \"5fc03087-d265-11e7-b8c6-83e29cd24f4c\"); // Displaying the UUID System.out.println(\"UUID: \" + UUID_1); // Displaying the timestamp Value System.out.println(\"The timestamp value is: \" + UUID_1.timestamp()); }}", "e": 1689, "s": 1134, "text": null }, { "code": null, "e": 1776, "s": 1689, "text": "UUID: 5fc03087-d265-11e7-b8c6-83e29cd24f4c\nThe timestamp value is: 137309646498050183\n" }, { "code": null, "e": 1796, "s": 1776, "text": "Java - util package" }, { "code": null, "e": 1811, "s": 1796, "text": "Java-Functions" }, { "code": null, "e": 1821, "s": 1811, "text": "Java-UUID" }, { "code": null, "e": 1826, "s": 1821, "text": "Java" }, { "code": null, "e": 1831, "s": 1826, "text": "Java" } ]
Python | Pandas dataframe.diff()
20 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.diff() is used to find the first discrete difference of objects over the given axis. We can provide a period value to shift for forming the difference. Syntax: DataFrame.diff(periods=1, axis=0) Parameters:periods : Periods to shift for forming differenceaxis : Take difference over rows (0) or columns (1). Returns: diffed : DataFrame Example #1: Use diff() function to find the discrete difference over the index axis with period value equal to 1. # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # Print the dataframedf Now find the discrete difference over the index axis. # To find the discrete differencedf.diff(axis = 0, periods = 1) Output : The output is a dataframe with cells containing the discrete difference over the index axis. The value present in each cell is the difference of current cell value with the previous row corresponding cell. Notice, the first row is NaN filled. This is because there is no row above that to find the difference with so it is treated as NaN. Example #2: Use diff() function to find the discrete difference over the column axis with period value equal to 1. # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # To find the discrete differencedf.diff(axis = 1, periods = 1) Output : The output is a dataframe with cells containing the discrete difference over the column axis. The value present in each cell is the difference of current cell value with the previous column corresponding cell. Notice, the first column is NaN filled. This is because there is no column to the left of it to find the difference with so it is treated as NaN. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas 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 How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 411, "s": 242, "text": "Pandas dataframe.diff() is used to find the first discrete difference of objects over the given axis. We can provide a period value to shift for forming the difference." }, { "code": null, "e": 453, "s": 411, "text": "Syntax: DataFrame.diff(periods=1, axis=0)" }, { "code": null, "e": 566, "s": 453, "text": "Parameters:periods : Periods to shift for forming differenceaxis : Take difference over rows (0) or columns (1)." }, { "code": null, "e": 594, "s": 566, "text": "Returns: diffed : DataFrame" }, { "code": null, "e": 708, "s": 594, "text": "Example #1: Use diff() function to find the discrete difference over the index axis with period value equal to 1." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # Print the dataframedf", "e": 950, "s": 708, "text": null }, { "code": null, "e": 1004, "s": 950, "text": "Now find the discrete difference over the index axis." }, { "code": "# To find the discrete differencedf.diff(axis = 0, periods = 1)", "e": 1068, "s": 1004, "text": null }, { "code": null, "e": 1077, "s": 1068, "text": "Output :" }, { "code": null, "e": 1417, "s": 1077, "text": "The output is a dataframe with cells containing the discrete difference over the index axis. The value present in each cell is the difference of current cell value with the previous row corresponding cell. Notice, the first row is NaN filled. This is because there is no row above that to find the difference with so it is treated as NaN. " }, { "code": null, "e": 1532, "s": 1417, "text": "Example #2: Use diff() function to find the discrete difference over the column axis with period value equal to 1." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # To find the discrete differencedf.diff(axis = 1, periods = 1)", "e": 1815, "s": 1532, "text": null }, { "code": null, "e": 1824, "s": 1815, "text": "Output :" }, { "code": null, "e": 2180, "s": 1824, "text": "The output is a dataframe with cells containing the discrete difference over the column axis. The value present in each cell is the difference of current cell value with the previous column corresponding cell. Notice, the first column is NaN filled. This is because there is no column to the left of it to find the difference with so it is treated as NaN." }, { "code": null, "e": 2204, "s": 2180, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2236, "s": 2204, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2250, "s": 2236, "text": "Python-pandas" }, { "code": null, "e": 2257, "s": 2250, "text": "Python" }, { "code": null, "e": 2355, "s": 2257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2373, "s": 2355, "text": "Python Dictionary" }, { "code": null, "e": 2415, "s": 2373, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2437, "s": 2415, "text": "Enumerate() in Python" }, { "code": null, "e": 2469, "s": 2437, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2498, "s": 2469, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2525, "s": 2498, "text": "Python Classes and Objects" }, { "code": null, "e": 2546, "s": 2525, "text": "Python OOPs Concepts" }, { "code": null, "e": 2569, "s": 2546, "text": "Introduction To PYTHON" }, { "code": null, "e": 2600, "s": 2569, "text": "Python | os.path.join() method" } ]
Get maximum items when other items of total cost of an item are free
31 May, 2022 Given a list of prices of ‘N’ items. A person can buy only one item of any price and he can get other items for free such that the total price of the rest of the items doesn’t exceed the price of the bought item. The task is to find the maximum number of items the person can have.Examples: Input: n = 5, arr = {5, 3, 1, 5, 6} Output: 3 The person can buy any item of price 5 or 6 and download items of prices 1 and 3 for free. So, he can get at most 3 items.Input: n = 2, arr = {7, 7} Output: 2 Approach: The person should buy the most expensive item and then start taking the items starting from the least pricing (until the total price is lest than or equal to the bought item) in order to maximize the total number of items. Thus, we sort the list of prices and choose the last element, then we will iterate from 1st index to n-2 index and check if the total sum is less than or equal to the last element. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to count the// total number of itemsint items(int n, int a[]){ // Sort the prices sort(a,a+n); // Choose the last element int z = a[n-1]; // Initial count of item int x = 1; // Sum to keep track of // the total price // of free items int s = 0; for (int i=0;i<n-1;i++) { s += a[i]; // If total is less than // or equal to z then // we will add 1 to the answer if (s <= z) x+= 1; else break; } return x;}int main(){int n = 5; int a[]= {5, 3, 1, 5, 6}; cout<<items(n, a);} //contributed by Arnab Kundu // Java implementation of// the above approachimport java.util.Arrays;import java.io.*; class GFG { // Function to count the// total number of itemsstatic int items(int n, int a[]){ // Sort the prices Arrays.sort(a); // Choose the last element int z = a[n-1]; // Initial count of item int x = 1; // Sum to keep track of // the total price // of free items int s = 0; for (int i=0;i<n-1;i++) { s += a[i]; // If total is less than // or equal to z then // we will add 1 to the answer if (s <= z) x+= 1; else break; } return x;} // Driver code public static void main (String[] args) { int n = 5; int a[]= {5, 3, 1, 5, 6}; System.out.println(items(n, a)); }//This code is contributed by ajit } # Python3 implementation of# the above approach # Function to count the# total number of itemsdef items(n, a): # Sort the prices a.sort() # Choose the last element z = a[n-1] # Initial count of item x = 1 # Sum to keep track of # the total price # of free items s = 0 for i in range(0, n-1): s += a[i] # If total is less than # or equal to z then # we will add 1 to the answer if (s <= z): x+= 1 else: break return x n = 5a = [5, 3, 1, 5, 6]print(items(n, a)) // C# implementation of the// above approachusing System; class GFG{// Function to count the// total number of itemsstatic int items(int n, int []a){ // Sort the prices Array.Sort(a); // Choose the last element int z = a[n - 1]; // Initial count of item int x = 1; // Sum to keep track of // the total price // of free items int s = 0; for (int i = 0; i < n - 1; i++) { s += a[i]; // If total is less than or equal to z // then we will add 1 to the answer if (s <= z) x += 1; else break; } return x;} // Driver codestatic public void Main (){ int n = 5; int []a = {5, 3, 1, 5, 6}; Console.WriteLine(items(n, a));}} // This code is contributed// by akt_mit <?php//PHP implementation of// the above approach// Function to count the// total number of items function items($n, $a){ // Sort the prices sort($a); // Choose the last element $z = $a[$n-1]; // Initial count of item $x = 1; // Sum to keep track of // the total price // of free items $s = 0; for ($i=0;$i<$n-1;$i++) { $s += $a[$i]; // If total is less than // or equal to z then // we will add 1 to the answer if ($s <= $z) $x+= 1; else break; } return $x;}//Code driven$n = 5;$a= array(5, 3, 1, 5, 6); echo items($n, $a); //This code is contributed by ajit?> <script> // Javascript implementation of the above approach // Function to count the // total number of items function items(n, a) { // Sort the prices a.sort(function(a, b){return a - b}); // Choose the last element let z = a[n - 1]; // Initial count of item let x = 1; // Sum to keep track of // the total price // of free items let s = 0; for (let i = 0; i < n - 1; i++) { s += a[i]; // If total is less than or equal to z // then we will add 1 to the answer if (s <= z) x += 1; else break; } return x; } let n = 5; let a = [5, 3, 1, 5, 6]; document.write(items(n, a)); </script> 3 Time Complexity: O(N*logN), as we are using inbuilt sort function. Auxiliary Space: O(1), as we are not using any extra space. andrew1234 jit_t decode2207 rohan07 Arrays Greedy Sorting Arrays Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 345, "s": 52, "text": "Given a list of prices of ‘N’ items. A person can buy only one item of any price and he can get other items for free such that the total price of the rest of the items doesn’t exceed the price of the bought item. The task is to find the maximum number of items the person can have.Examples: " }, { "code": null, "e": 552, "s": 345, "text": "Input: n = 5, arr = {5, 3, 1, 5, 6} Output: 3 The person can buy any item of price 5 or 6 and download items of prices 1 and 3 for free. So, he can get at most 3 items.Input: n = 2, arr = {7, 7} Output: 2 " }, { "code": null, "e": 566, "s": 554, "text": "Approach: " }, { "code": null, "e": 972, "s": 566, "text": "The person should buy the most expensive item and then start taking the items starting from the least pricing (until the total price is lest than or equal to the bought item) in order to maximize the total number of items. Thus, we sort the list of prices and choose the last element, then we will iterate from 1st index to n-2 index and check if the total sum is less than or equal to the last element. " }, { "code": null, "e": 1025, "s": 972, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1029, "s": 1025, "text": "C++" }, { "code": null, "e": 1034, "s": 1029, "text": "Java" }, { "code": null, "e": 1042, "s": 1034, "text": "Python3" }, { "code": null, "e": 1045, "s": 1042, "text": "C#" }, { "code": null, "e": 1049, "s": 1045, "text": "PHP" }, { "code": null, "e": 1060, "s": 1049, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to count the// total number of itemsint items(int n, int a[]){ // Sort the prices sort(a,a+n); // Choose the last element int z = a[n-1]; // Initial count of item int x = 1; // Sum to keep track of // the total price // of free items int s = 0; for (int i=0;i<n-1;i++) { s += a[i]; // If total is less than // or equal to z then // we will add 1 to the answer if (s <= z) x+= 1; else break; } return x;}int main(){int n = 5; int a[]= {5, 3, 1, 5, 6}; cout<<items(n, a);} //contributed by Arnab Kundu", "e": 1774, "s": 1060, "text": null }, { "code": "// Java implementation of// the above approachimport java.util.Arrays;import java.io.*; class GFG { // Function to count the// total number of itemsstatic int items(int n, int a[]){ // Sort the prices Arrays.sort(a); // Choose the last element int z = a[n-1]; // Initial count of item int x = 1; // Sum to keep track of // the total price // of free items int s = 0; for (int i=0;i<n-1;i++) { s += a[i]; // If total is less than // or equal to z then // we will add 1 to the answer if (s <= z) x+= 1; else break; } return x;} // Driver code public static void main (String[] args) { int n = 5; int a[]= {5, 3, 1, 5, 6}; System.out.println(items(n, a)); }//This code is contributed by ajit }", "e": 2613, "s": 1774, "text": null }, { "code": "# Python3 implementation of# the above approach # Function to count the# total number of itemsdef items(n, a): # Sort the prices a.sort() # Choose the last element z = a[n-1] # Initial count of item x = 1 # Sum to keep track of # the total price # of free items s = 0 for i in range(0, n-1): s += a[i] # If total is less than # or equal to z then # we will add 1 to the answer if (s <= z): x+= 1 else: break return x n = 5a = [5, 3, 1, 5, 6]print(items(n, a))", "e": 3179, "s": 2613, "text": null }, { "code": "// C# implementation of the// above approachusing System; class GFG{// Function to count the// total number of itemsstatic int items(int n, int []a){ // Sort the prices Array.Sort(a); // Choose the last element int z = a[n - 1]; // Initial count of item int x = 1; // Sum to keep track of // the total price // of free items int s = 0; for (int i = 0; i < n - 1; i++) { s += a[i]; // If total is less than or equal to z // then we will add 1 to the answer if (s <= z) x += 1; else break; } return x;} // Driver codestatic public void Main (){ int n = 5; int []a = {5, 3, 1, 5, 6}; Console.WriteLine(items(n, a));}} // This code is contributed// by akt_mit", "e": 3948, "s": 3179, "text": null }, { "code": "<?php//PHP implementation of// the above approach// Function to count the// total number of items function items($n, $a){ // Sort the prices sort($a); // Choose the last element $z = $a[$n-1]; // Initial count of item $x = 1; // Sum to keep track of // the total price // of free items $s = 0; for ($i=0;$i<$n-1;$i++) { $s += $a[$i]; // If total is less than // or equal to z then // we will add 1 to the answer if ($s <= $z) $x+= 1; else break; } return $x;}//Code driven$n = 5;$a= array(5, 3, 1, 5, 6); echo items($n, $a); //This code is contributed by ajit?>", "e": 4622, "s": 3948, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to count the // total number of items function items(n, a) { // Sort the prices a.sort(function(a, b){return a - b}); // Choose the last element let z = a[n - 1]; // Initial count of item let x = 1; // Sum to keep track of // the total price // of free items let s = 0; for (let i = 0; i < n - 1; i++) { s += a[i]; // If total is less than or equal to z // then we will add 1 to the answer if (s <= z) x += 1; else break; } return x; } let n = 5; let a = [5, 3, 1, 5, 6]; document.write(items(n, a)); </script>", "e": 5434, "s": 4622, "text": null }, { "code": null, "e": 5436, "s": 5434, "text": "3" }, { "code": null, "e": 5505, "s": 5438, "text": "Time Complexity: O(N*logN), as we are using inbuilt sort function." }, { "code": null, "e": 5565, "s": 5505, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 5576, "s": 5565, "text": "andrew1234" }, { "code": null, "e": 5582, "s": 5576, "text": "jit_t" }, { "code": null, "e": 5593, "s": 5582, "text": "decode2207" }, { "code": null, "e": 5601, "s": 5593, "text": "rohan07" }, { "code": null, "e": 5608, "s": 5601, "text": "Arrays" }, { "code": null, "e": 5615, "s": 5608, "text": "Greedy" }, { "code": null, "e": 5623, "s": 5615, "text": "Sorting" }, { "code": null, "e": 5630, "s": 5623, "text": "Arrays" }, { "code": null, "e": 5637, "s": 5630, "text": "Greedy" }, { "code": null, "e": 5645, "s": 5637, "text": "Sorting" } ]
Largest gap in an array
12 May, 2021 Given an unsorted array of length N, and we have to find the largest gap between any two elements of the array. In simple words, find max(|Ai-Aj|) where 1 ≤ i ≤ N and 1 ≤ j ≤ N. Examples: Input : arr = {3, 10, 6, 7} Output : 7 Explanation : Here, we can see largest gap can be found between 3 and 10 which is 7 Input : arr = {-3, -1, 6, 7, 0} Output : 10 Explanation : Here, we can see largest gap can be found between -3 and 7 which is 10 Simple Approach: A simple solution is, we can use a naive approach. We will check the absolute difference of every pair in the array, and we will find the maximum value of it. So we will run two loops one is for i and one is for j complexity of this method is O(N^2) C++ C Java Python3 C# PHP Javascript // A C++ program to find largest gap// between two elements in an array.#include<bits/stdc++.h>using namespace std; // function to solve the given problemint solve(int a[], int n){ int max1 = INT_MIN; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (abs(a[i] - a[j]) > max1) { max1 = abs(a[i] - a[j]); } } } return max1;} // Driver Codeint main(){ int arr[] = { -1, 2, 3, -4, -10, 22 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "Largest gap is : " << solve(arr, size); return 0;} // This code is contributed// by Akanksha Rai // A C program to find largest gap// between two elements in an array.#include <limits.h>#include <stdio.h>#include <stdlib.h> // function to solve the given problemint solve(int a[], int n){ int max1 = INT_MIN; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (abs(a[i] - a[j]) > max1) { max1 = abs(a[i] - a[j]); } } } return max1;} int main(){ int arr[] = { -1, 2, 3, -4, -10, 22 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Largest gap is : %d", solve(arr, size)); return 0;} // A Java program to find// largest gap between// two elements in an array.import java .io.*; class GFG{ // function to solve// the given problemstatic int solve(int []a, int n){ int max1 = Integer.MIN_VALUE ; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.abs(a[i] - a[j]) > max1) { max1 = Math.abs(a[i] - a[j]); } } } return max1;} // Driver Codestatic public void main (String[] args){ int []arr = {-1, 2, 3, -4, -10, 22}; int size = arr.length; System.out.println("Largest gap is : " + solve(arr, size));}} // This code is contributed// by anuj_67. # A Python 3 program to find largest gap# between two elements in an array.import sys # function to solve the given problemdef solve(a, n): max1 = -sys.maxsize - 1 for i in range(0, n, 1): for j in range(0, n, 1): if (abs(a[i] - a[j]) > max1): max1 = abs(a[i] - a[j]) return max1 # Driver Codeif __name__ == '__main__': arr = [-1, 2, 3, -4, -10, 22] size = len(arr) print("Largest gap is :", solve(arr, size)) # This code is contributed by# Sanjit_Prasad // A C# program to find// largest gap between// two elements in an array.using System; class GFG{ // function to solve// the given problemstatic int solve(int []a, int n){ int max1 = int.MinValue ; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.Abs(a[i] - a[j]) > max1) { max1 = Math.Abs(a[i] - a[j]); } } } return max1;} // Driver Codestatic public void Main (){ int []arr = {-1, 2, 3, -4, -10, 22}; int size = arr.Length; Console.WriteLine("Largest gap is : " + solve(arr, size));}} // This code is contributed// by anuj_67. <?php// A PHP program to find// largest gap between// two elements in an array. // function to solve// the given problemfunction solve($a, $n){ $max1 = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if (abs($a[$i] - $a[$j]) > $max1) { $max1 = abs($a[$i] - $a[$j]); } } } return $max1;} // Driver Code$arr = array(-1, 2, 3, -4, -10, 22);$size = count($arr);echo "Largest gap is : ", solve($arr, $size); // This code is contributed// by anuj_67.?> <script> // A Javascript program to find// largest gap between// two elements in an array. // function to solve// the given problem function solve(a,n) { let max1 = Number.MIN_VALUE ; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (Math.abs(a[i] - a[j]) > max1) { max1 = Math.abs(a[i] - a[j]); } } } return max1; } // Driver Code let arr=[-1, 2, 3, -4, -10, 22]; let size = arr.length; document.write("Largest gap is : " + solve(arr, size)); // This code is contributed by rag2127 </script> Largest gap is : 32 Better Approach: Now we will see a better approach it is a greedy approach that can solve this problem in O(N). We will find the maximum and minimum element of the array which can be done in O(N) and then we will return the value of (maximum-minimum). C++ C Java Python3 C# PHP Javascript // A C++ program to find largest gap between// two elements in an array.#include<bits/stdc++.h>using namespace std; // function to solve the given problemint solve(int a[], int n){ int min1 = a[0]; int max1 = a[0]; // finding maximum and minimum of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return abs(min1 - max1);} // Driver codeint main(){ int arr[] = { -1, 2, 3, 4, -10 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "Largest gap is : " << solve(arr, size); return 0;} //This code is contributed by Mukul Singh. // A C program to find largest gap between// two elements in an array.#include <limits.h>#include <stdio.h>#include <stdlib.h> // function to solve the given problemint solve(int a[], int n){ int min1 = a[0]; int max1 = a[0]; // finding maximum and minimum of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return abs(min1 - max1);} int main(){ int arr[] = { -1, 2, 3, 4, -10 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Largest gap is : %d", solve(arr, size)); return 0;} // A Java program to find largest gap// between two elements in an array.import java.io.*; class GFG { // function to solve the given // problem static int solve(int a[], int n) { int min1 = a[0]; int max1 = a[0]; // finding maximum and minimum // of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return Math.abs(min1 - max1); } // Driver code public static void main (String[] args) { int []arr = { -1, 2, 3, 4, -10 }; int size = arr.length; System.out.println("Largest gap is : " + solve(arr, size)); }} // This code is contributed by anuj_67. # A python 3 program to find largest gap between# two elements in an array. # function to solve the given problemdef solve(a, n): min1 = a[0] max1 = a[0] # finding maximum and minimum of an array for i in range ( n): if (a[i] > max1): max1 = a[i] if (a[i] < min1): min1 = a[i] return abs(min1 - max1) # Driver codeif __name__ == "__main__": arr = [ -1, 2, 3, 4, -10 ] size = len(arr) print("Largest gap is : " ,solve(arr, size)) # This code is contributed by chitranayal // A C# program to find// largest gap between// two elements in an array.using System; class GFG{ // function to solve // the given problem static int solve(int []a, int n) { int min1 = a[0]; int max1 = a[0]; // finding maximum and // minimum of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return Math.Abs(min1 - max1); } // Driver code public static void Main () { int []arr = {-1, 2, 3, 4, -10}; int size = arr.Length; Console.WriteLine("Largest gap is : " + solve(arr, size)); }} // This code is contributed// by anuj_67. <?php// A PHP program to find// largest gap between// two elements in an array. // function to solve// the given problemfunction solve($a, $n){ $min1 = $a[0]; $max1 = $a[0]; // finding maximum and // minimum of an array for ($i = 0; $i < $n; $i++) { if ($a[$i] > $max1) $max1 = $a[$i]; if ($a[$i] < $min1) $min1 = $a[$i]; } return abs($min1 - $max1);} // Driver Code$arr = array(-1, 2, 3, 4, -10);$size = count($arr);echo "Largest gap is : ", solve($arr, $size); // This code is contributed// by anuj_67.?> <script>// A Javascript program to find largest gap// between two elements in an array. // function to solve the given // problem function solve(a,n) { let min1 = a[0]; let max1 = a[0]; // finding maximum and minimum // of an array for (let i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return Math.abs(min1 - max1); } // Driver code let arr=[-1, 2, 3, 4, -10 ]; let size = arr.length; document.write("Largest gap is : " + solve(arr, size)); // This code is contributed by avanitrachhadiya2155</script> Largest gap is : 14 vt_m Sanjit_Prasad Akanksha_Rai Code_Mech ukasp rag2127 avanitrachhadiya2155 Arrays Greedy Searching Arrays Searching Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Longest Consecutive Subsequence Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 53, "s": 25, "text": "\n12 May, 2021" }, { "code": null, "e": 231, "s": 53, "text": "Given an unsorted array of length N, and we have to find the largest gap between any two elements of the array. In simple words, find max(|Ai-Aj|) where 1 ≤ i ≤ N and 1 ≤ j ≤ N." }, { "code": null, "e": 243, "s": 231, "text": "Examples: " }, { "code": null, "e": 498, "s": 243, "text": "Input : arr = {3, 10, 6, 7}\nOutput : 7\nExplanation :\nHere, we can see largest gap can be\nfound between 3 and 10 which is 7\n\nInput : arr = {-3, -1, 6, 7, 0}\nOutput : 10\nExplanation :\nHere, we can see largest gap can be \nfound between -3 and 7 which is 10 " }, { "code": null, "e": 767, "s": 498, "text": "Simple Approach: A simple solution is, we can use a naive approach. We will check the absolute difference of every pair in the array, and we will find the maximum value of it. So we will run two loops one is for i and one is for j complexity of this method is O(N^2) " }, { "code": null, "e": 771, "s": 767, "text": "C++" }, { "code": null, "e": 773, "s": 771, "text": "C" }, { "code": null, "e": 778, "s": 773, "text": "Java" }, { "code": null, "e": 786, "s": 778, "text": "Python3" }, { "code": null, "e": 789, "s": 786, "text": "C#" }, { "code": null, "e": 793, "s": 789, "text": "PHP" }, { "code": null, "e": 804, "s": 793, "text": "Javascript" }, { "code": "// A C++ program to find largest gap// between two elements in an array.#include<bits/stdc++.h>using namespace std; // function to solve the given problemint solve(int a[], int n){ int max1 = INT_MIN; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (abs(a[i] - a[j]) > max1) { max1 = abs(a[i] - a[j]); } } } return max1;} // Driver Codeint main(){ int arr[] = { -1, 2, 3, -4, -10, 22 }; int size = sizeof(arr) / sizeof(arr[0]); cout << \"Largest gap is : \" << solve(arr, size); return 0;} // This code is contributed// by Akanksha Rai", "e": 1457, "s": 804, "text": null }, { "code": "// A C program to find largest gap// between two elements in an array.#include <limits.h>#include <stdio.h>#include <stdlib.h> // function to solve the given problemint solve(int a[], int n){ int max1 = INT_MIN; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (abs(a[i] - a[j]) > max1) { max1 = abs(a[i] - a[j]); } } } return max1;} int main(){ int arr[] = { -1, 2, 3, -4, -10, 22 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Largest gap is : %d\", solve(arr, size)); return 0;}", "e": 2032, "s": 1457, "text": null }, { "code": "// A Java program to find// largest gap between// two elements in an array.import java .io.*; class GFG{ // function to solve// the given problemstatic int solve(int []a, int n){ int max1 = Integer.MIN_VALUE ; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.abs(a[i] - a[j]) > max1) { max1 = Math.abs(a[i] - a[j]); } } } return max1;} // Driver Codestatic public void main (String[] args){ int []arr = {-1, 2, 3, -4, -10, 22}; int size = arr.length; System.out.println(\"Largest gap is : \" + solve(arr, size));}} // This code is contributed// by anuj_67.", "e": 2810, "s": 2032, "text": null }, { "code": "# A Python 3 program to find largest gap# between two elements in an array.import sys # function to solve the given problemdef solve(a, n): max1 = -sys.maxsize - 1 for i in range(0, n, 1): for j in range(0, n, 1): if (abs(a[i] - a[j]) > max1): max1 = abs(a[i] - a[j]) return max1 # Driver Codeif __name__ == '__main__': arr = [-1, 2, 3, -4, -10, 22] size = len(arr) print(\"Largest gap is :\", solve(arr, size)) # This code is contributed by# Sanjit_Prasad", "e": 3317, "s": 2810, "text": null }, { "code": "// A C# program to find// largest gap between// two elements in an array.using System; class GFG{ // function to solve// the given problemstatic int solve(int []a, int n){ int max1 = int.MinValue ; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (Math.Abs(a[i] - a[j]) > max1) { max1 = Math.Abs(a[i] - a[j]); } } } return max1;} // Driver Codestatic public void Main (){ int []arr = {-1, 2, 3, -4, -10, 22}; int size = arr.Length; Console.WriteLine(\"Largest gap is : \" + solve(arr, size));}} // This code is contributed// by anuj_67.", "e": 4070, "s": 3317, "text": null }, { "code": "<?php// A PHP program to find// largest gap between// two elements in an array. // function to solve// the given problemfunction solve($a, $n){ $max1 = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if (abs($a[$i] - $a[$j]) > $max1) { $max1 = abs($a[$i] - $a[$j]); } } } return $max1;} // Driver Code$arr = array(-1, 2, 3, -4, -10, 22);$size = count($arr);echo \"Largest gap is : \", solve($arr, $size); // This code is contributed// by anuj_67.?>", "e": 4689, "s": 4070, "text": null }, { "code": "<script> // A Javascript program to find// largest gap between// two elements in an array. // function to solve// the given problem function solve(a,n) { let max1 = Number.MIN_VALUE ; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (Math.abs(a[i] - a[j]) > max1) { max1 = Math.abs(a[i] - a[j]); } } } return max1; } // Driver Code let arr=[-1, 2, 3, -4, -10, 22]; let size = arr.length; document.write(\"Largest gap is : \" + solve(arr, size)); // This code is contributed by rag2127 </script>", "e": 5401, "s": 4689, "text": null }, { "code": null, "e": 5421, "s": 5401, "text": "Largest gap is : 32" }, { "code": null, "e": 5677, "s": 5423, "text": "Better Approach: Now we will see a better approach it is a greedy approach that can solve this problem in O(N). We will find the maximum and minimum element of the array which can be done in O(N) and then we will return the value of (maximum-minimum). " }, { "code": null, "e": 5681, "s": 5677, "text": "C++" }, { "code": null, "e": 5683, "s": 5681, "text": "C" }, { "code": null, "e": 5688, "s": 5683, "text": "Java" }, { "code": null, "e": 5696, "s": 5688, "text": "Python3" }, { "code": null, "e": 5699, "s": 5696, "text": "C#" }, { "code": null, "e": 5703, "s": 5699, "text": "PHP" }, { "code": null, "e": 5714, "s": 5703, "text": "Javascript" }, { "code": "// A C++ program to find largest gap between// two elements in an array.#include<bits/stdc++.h>using namespace std; // function to solve the given problemint solve(int a[], int n){ int min1 = a[0]; int max1 = a[0]; // finding maximum and minimum of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return abs(min1 - max1);} // Driver codeint main(){ int arr[] = { -1, 2, 3, 4, -10 }; int size = sizeof(arr) / sizeof(arr[0]); cout << \"Largest gap is : \" << solve(arr, size); return 0;} //This code is contributed by Mukul Singh.", "e": 6364, "s": 5714, "text": null }, { "code": "// A C program to find largest gap between// two elements in an array.#include <limits.h>#include <stdio.h>#include <stdlib.h> // function to solve the given problemint solve(int a[], int n){ int min1 = a[0]; int max1 = a[0]; // finding maximum and minimum of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return abs(min1 - max1);} int main(){ int arr[] = { -1, 2, 3, 4, -10 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Largest gap is : %d\", solve(arr, size)); return 0;}", "e": 6970, "s": 6364, "text": null }, { "code": "// A Java program to find largest gap// between two elements in an array.import java.io.*; class GFG { // function to solve the given // problem static int solve(int a[], int n) { int min1 = a[0]; int max1 = a[0]; // finding maximum and minimum // of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return Math.abs(min1 - max1); } // Driver code public static void main (String[] args) { int []arr = { -1, 2, 3, 4, -10 }; int size = arr.length; System.out.println(\"Largest gap is : \" + solve(arr, size)); }} // This code is contributed by anuj_67.", "e": 7767, "s": 6970, "text": null }, { "code": "# A python 3 program to find largest gap between# two elements in an array. # function to solve the given problemdef solve(a, n): min1 = a[0] max1 = a[0] # finding maximum and minimum of an array for i in range ( n): if (a[i] > max1): max1 = a[i] if (a[i] < min1): min1 = a[i] return abs(min1 - max1) # Driver codeif __name__ == \"__main__\": arr = [ -1, 2, 3, 4, -10 ] size = len(arr) print(\"Largest gap is : \" ,solve(arr, size)) # This code is contributed by chitranayal ", "e": 8315, "s": 7767, "text": null }, { "code": "// A C# program to find// largest gap between// two elements in an array.using System; class GFG{ // function to solve // the given problem static int solve(int []a, int n) { int min1 = a[0]; int max1 = a[0]; // finding maximum and // minimum of an array for (int i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return Math.Abs(min1 - max1); } // Driver code public static void Main () { int []arr = {-1, 2, 3, 4, -10}; int size = arr.Length; Console.WriteLine(\"Largest gap is : \" + solve(arr, size)); }} // This code is contributed// by anuj_67.", "e": 9140, "s": 8315, "text": null }, { "code": "<?php// A PHP program to find// largest gap between// two elements in an array. // function to solve// the given problemfunction solve($a, $n){ $min1 = $a[0]; $max1 = $a[0]; // finding maximum and // minimum of an array for ($i = 0; $i < $n; $i++) { if ($a[$i] > $max1) $max1 = $a[$i]; if ($a[$i] < $min1) $min1 = $a[$i]; } return abs($min1 - $max1);} // Driver Code$arr = array(-1, 2, 3, 4, -10);$size = count($arr);echo \"Largest gap is : \", solve($arr, $size); // This code is contributed// by anuj_67.?>", "e": 9718, "s": 9140, "text": null }, { "code": "<script>// A Javascript program to find largest gap// between two elements in an array. // function to solve the given // problem function solve(a,n) { let min1 = a[0]; let max1 = a[0]; // finding maximum and minimum // of an array for (let i = 0; i < n; i++) { if (a[i] > max1) max1 = a[i]; if (a[i] < min1) min1 = a[i]; } return Math.abs(min1 - max1); } // Driver code let arr=[-1, 2, 3, 4, -10 ]; let size = arr.length; document.write(\"Largest gap is : \" + solve(arr, size)); // This code is contributed by avanitrachhadiya2155</script>", "e": 10454, "s": 9718, "text": null }, { "code": null, "e": 10474, "s": 10454, "text": "Largest gap is : 14" }, { "code": null, "e": 10481, "s": 10476, "text": "vt_m" }, { "code": null, "e": 10495, "s": 10481, "text": "Sanjit_Prasad" }, { "code": null, "e": 10508, "s": 10495, "text": "Akanksha_Rai" }, { "code": null, "e": 10518, "s": 10508, "text": "Code_Mech" }, { "code": null, "e": 10524, "s": 10518, "text": "ukasp" }, { "code": null, "e": 10532, "s": 10524, "text": "rag2127" }, { "code": null, "e": 10553, "s": 10532, "text": "avanitrachhadiya2155" }, { "code": null, "e": 10560, "s": 10553, "text": "Arrays" }, { "code": null, "e": 10567, "s": 10560, "text": "Greedy" }, { "code": null, "e": 10577, "s": 10567, "text": "Searching" }, { "code": null, "e": 10584, "s": 10577, "text": "Arrays" }, { "code": null, "e": 10594, "s": 10584, "text": "Searching" }, { "code": null, "e": 10601, "s": 10594, "text": "Greedy" }, { "code": null, "e": 10699, "s": 10601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10731, "s": 10699, "text": "Introduction to Data Structures" }, { "code": null, "e": 10778, "s": 10731, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 10803, "s": 10778, "text": "Window Sliding Technique" }, { "code": null, "e": 10834, "s": 10803, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 10866, "s": 10834, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 10917, "s": 10866, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 10968, "s": 10917, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 11028, "s": 10968, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11086, "s": 11028, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Java.util.Dictionary Class in Java
07 Dec, 2021 util.Dictionary is an abstract class, representing a key-value relation and works similar to a map. Given a key you can store values and when needed can retrieve the value back using its key. Thus, it is a list of key-value pair. Declaration public abstract class Dictionary extends Object Constructors: Dictionary() Sole constructor. Methods of util.Dictionary Class : 1. put(K key, V value) : java.util.Dictionary.put(K key, V value) adds key-value pair to the dictionary. Syntax : public abstract V put(K key, V value) Parameters : -> key -> value Return : key-value pair mapped in the dictionary 2. elements() : java.util.Dictionary.elements() returns value representation in dictionary. Syntax : public abstract Enumeration elements() Parameters : -------- Return : value enumeration in dictionary 3. get(Object key) : java.util.Dictionary.get(Object key) returns the value that is mapped with the argumented key in the dictionary. Syntax : public abstract V get(Object key) Parameters : key - key whose mapped value we want Return : value mapped with the argumented key 4. isEmpty() : java.util.Dictionary.isEmpty() checks whether the dictionary is empty or not. Syntax : public abstract boolean isEmpty() Parameters : ------ Return : true, if there is no key-value relation in the dictionary; else false 5. keys() : java.util.Dictionary.keys() returns key representation in dictionary. Syntax : public abstract Enumeration keys() Parameters : -------- Return : key enumeration in dictionary 6. remove(Object key) : java.util.Dictionary.remove(Object key) removes the key-value pair mapped with the argumented key. Syntax : public abstract V remove(Object key) Parameters : key : key to be removed Return : value mapped with the key 7. size() : java.util.Dictionary.size() returns the no. of key-value pairs in the Dictionary. Syntax : public abstract int size() Parameters : ------- Return : returns the no. of key-value pairs in the Dictionary Java // Java Program explaining util.Dictionary class Methods// put(), elements(), get(), isEmpty(), keys()// remove(), size() import java.util.*;public class New_Class{ public static void main(String[] args) { // Initializing a Dictionary Dictionary geek = new Hashtable(); // put() method geek.put("123", "Code"); geek.put("456", "Program"); // elements() method : for (Enumeration i = geek.elements(); i.hasMoreElements();) { System.out.println("Value in Dictionary : " + i.nextElement()); } // get() method : System.out.println("\nValue at key = 6 : " + geek.get("6")); System.out.println("Value at key = 456 : " + geek.get("123")); // isEmpty() method : System.out.println("\nThere is no key-value pair : " + geek.isEmpty() + "\n"); // keys() method : for (Enumeration k = geek.keys(); k.hasMoreElements();) { System.out.println("Keys in Dictionary : " + k.nextElement()); } // remove() method : System.out.println("\nRemove : " + geek.remove("123")); System.out.println("Check the value of removed key : " + geek.get("123")); System.out.println("\nSize of Dictionary : " + geek.size()); }} Output: Value in Dictionary : Code Value in Dictionary : Program Value at key = 6 : null Value at key = 456 : Code There is no key-value pair : false Keys in Dictionary : 123 Keys in Dictionary : 456 Remove : Code Check the value of removed key : null Size of Dictionary : 1 This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 Java - util package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Dec, 2021" }, { "code": null, "e": 285, "s": 54, "text": "util.Dictionary is an abstract class, representing a key-value relation and works similar to a map. Given a key you can store values and when needed can retrieve the value back using its key. Thus, it is a list of key-value pair. " }, { "code": null, "e": 298, "s": 285, "text": "Declaration " }, { "code": null, "e": 346, "s": 298, "text": "public abstract class Dictionary extends Object" }, { "code": null, "e": 392, "s": 346, "text": "Constructors: Dictionary() Sole constructor. " }, { "code": null, "e": 428, "s": 392, "text": "Methods of util.Dictionary Class : " }, { "code": null, "e": 533, "s": 428, "text": "1. put(K key, V value) : java.util.Dictionary.put(K key, V value) adds key-value pair to the dictionary." }, { "code": null, "e": 542, "s": 533, "text": "Syntax :" }, { "code": null, "e": 660, "s": 542, "text": "public abstract V put(K key, V value)\nParameters : \n-> key\n-> value\nReturn : \nkey-value pair mapped in the dictionary" }, { "code": null, "e": 752, "s": 660, "text": "2. elements() : java.util.Dictionary.elements() returns value representation in dictionary." }, { "code": null, "e": 761, "s": 752, "text": "Syntax :" }, { "code": null, "e": 865, "s": 761, "text": "public abstract Enumeration elements()\nParameters : \n--------\nReturn : \nvalue enumeration in dictionary" }, { "code": null, "e": 999, "s": 865, "text": "3. get(Object key) : java.util.Dictionary.get(Object key) returns the value that is mapped with the argumented key in the dictionary." }, { "code": null, "e": 1008, "s": 999, "text": "Syntax :" }, { "code": null, "e": 1140, "s": 1008, "text": "public abstract V get(Object key)\nParameters : \nkey - key whose mapped value we want\nReturn : \nvalue mapped with the argumented key" }, { "code": null, "e": 1234, "s": 1140, "text": "4. isEmpty() : java.util.Dictionary.isEmpty() checks whether the dictionary is empty or not. " }, { "code": null, "e": 1243, "s": 1234, "text": "Syntax :" }, { "code": null, "e": 1378, "s": 1243, "text": "public abstract boolean isEmpty()\nParameters : \n------\nReturn : \ntrue, if there is no key-value relation in the dictionary; else false" }, { "code": null, "e": 1460, "s": 1378, "text": "5. keys() : java.util.Dictionary.keys() returns key representation in dictionary." }, { "code": null, "e": 1469, "s": 1460, "text": "Syntax :" }, { "code": null, "e": 1567, "s": 1469, "text": "public abstract Enumeration keys()\nParameters : \n--------\nReturn : \nkey enumeration in dictionary" }, { "code": null, "e": 1691, "s": 1567, "text": "6. remove(Object key) : java.util.Dictionary.remove(Object key) removes the key-value pair mapped with the argumented key. " }, { "code": null, "e": 1700, "s": 1691, "text": "Syntax :" }, { "code": null, "e": 1811, "s": 1700, "text": "public abstract V remove(Object key)\nParameters : \nkey : key to be removed\nReturn : \nvalue mapped with the key" }, { "code": null, "e": 1905, "s": 1811, "text": "7. size() : java.util.Dictionary.size() returns the no. of key-value pairs in the Dictionary." }, { "code": null, "e": 1914, "s": 1905, "text": "Syntax :" }, { "code": null, "e": 2026, "s": 1914, "text": "public abstract int size()\nParameters : \n-------\nReturn : \nreturns the no. of key-value pairs in the Dictionary" }, { "code": null, "e": 2031, "s": 2026, "text": "Java" }, { "code": "// Java Program explaining util.Dictionary class Methods// put(), elements(), get(), isEmpty(), keys()// remove(), size() import java.util.*;public class New_Class{ public static void main(String[] args) { // Initializing a Dictionary Dictionary geek = new Hashtable(); // put() method geek.put(\"123\", \"Code\"); geek.put(\"456\", \"Program\"); // elements() method : for (Enumeration i = geek.elements(); i.hasMoreElements();) { System.out.println(\"Value in Dictionary : \" + i.nextElement()); } // get() method : System.out.println(\"\\nValue at key = 6 : \" + geek.get(\"6\")); System.out.println(\"Value at key = 456 : \" + geek.get(\"123\")); // isEmpty() method : System.out.println(\"\\nThere is no key-value pair : \" + geek.isEmpty() + \"\\n\"); // keys() method : for (Enumeration k = geek.keys(); k.hasMoreElements();) { System.out.println(\"Keys in Dictionary : \" + k.nextElement()); } // remove() method : System.out.println(\"\\nRemove : \" + geek.remove(\"123\")); System.out.println(\"Check the value of removed key : \" + geek.get(\"123\")); System.out.println(\"\\nSize of Dictionary : \" + geek.size()); }}", "e": 3316, "s": 2031, "text": null }, { "code": null, "e": 3325, "s": 3316, "text": "Output: " }, { "code": null, "e": 3597, "s": 3325, "text": "Value in Dictionary : Code\nValue in Dictionary : Program\n\nValue at key = 6 : null\nValue at key = 456 : Code\n\nThere is no key-value pair : false\n\nKeys in Dictionary : 123\nKeys in Dictionary : 456\n\nRemove : Code\nCheck the value of removed key : null\n\nSize of Dictionary : 1" }, { "code": null, "e": 4022, "s": 3597, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4035, "s": 4022, "text": "simmytarika5" }, { "code": null, "e": 4055, "s": 4035, "text": "Java - util package" }, { "code": null, "e": 4060, "s": 4055, "text": "Java" }, { "code": null, "e": 4065, "s": 4060, "text": "Java" } ]
How to sort strings in JavaScript?
17 Jun, 2019 We can sort the strings in JavaScript by following methods described below: Using sort() method Using loop Using sort() method: In this method, we use predefined sort() method of JavaScript to sort the array of string. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method. Examples: Original StringSuraj, Sanjeev, Rajnish, Yash, RaviAfter sortingRajnish, Ravi, Sanjeev, Suraj, Yash Original String40, 100, 1, 5, 25, 10After sorting1, 10, 100, 25, 40, 5 Below program illustrates the above approach: Program: <script>// JavaScript code to sort strings // Original stringvar string = ["Suraj", "Sanjeev", "Rajnish", "Yash", "Ravi"]; // Print original string arraydocument.write("Original String</br>");document.write(string); document.write("</br>"); // Use sort() method to sort the stringsstring.sort(); document.write("</br>After sorting</br>"); // Print sorted string arraydocument.write(string); </script> Output: Original String Suraj, Sanjeev, Rajnish, Yash, Ravi After sorting Rajnish, Ravi, Sanjeev, Suraj, Yash Using loop: We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array.Examples: Original StringSuraj,Sanjeev,Rajnish,Yash,RaviAfter sortingRajnish,Ravi,Sanjeev,Suraj,Yash Original String40, 100, 1, 5, 25, 10After sorting1,5,10,25,40,100 Below program illustrates the above approach: Program: <script>// JavaScript code to sort the strings // Function to perform sortfunction string_sort(str) { var i = 0, j; while (i < str.length) { j = i + 1; while (j < str.length) { if (str[j] < str[i]) { var temp = str[i]; str[i] = str[j]; str[j] = temp; } j++; } i++; }} // Driver code // Original stringvar string = ["Suraj", "Sanjeev", "Rajnish", "Yash", "Ravi"]; // Print original string arraydocument.write("Original String</br>");document.write(string); document.write("</br>"); // Call string_sort methodstring_sort(string); document.write("</br>After sorting</br>"); // Print sorted string arraydocument.write(string); </script> Output: Original String Suraj, Sanjeev, Rajnish, Yash, Ravi After sorting Rajnish, Ravi, Sanjeev, Suraj, Yash javascript-string Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2019" }, { "code": null, "e": 128, "s": 52, "text": "We can sort the strings in JavaScript by following methods described below:" }, { "code": null, "e": 148, "s": 128, "text": "Using sort() method" }, { "code": null, "e": 159, "s": 148, "text": "Using loop" }, { "code": null, "e": 412, "s": 159, "text": "Using sort() method: In this method, we use predefined sort() method of JavaScript to sort the array of string. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method." }, { "code": null, "e": 422, "s": 412, "text": "Examples:" }, { "code": null, "e": 521, "s": 422, "text": "Original StringSuraj, Sanjeev, Rajnish, Yash, RaviAfter sortingRajnish, Ravi, Sanjeev, Suraj, Yash" }, { "code": null, "e": 592, "s": 521, "text": "Original String40, 100, 1, 5, 25, 10After sorting1, 10, 100, 25, 40, 5" }, { "code": null, "e": 638, "s": 592, "text": "Below program illustrates the above approach:" }, { "code": null, "e": 647, "s": 638, "text": "Program:" }, { "code": "<script>// JavaScript code to sort strings // Original stringvar string = [\"Suraj\", \"Sanjeev\", \"Rajnish\", \"Yash\", \"Ravi\"]; // Print original string arraydocument.write(\"Original String</br>\");document.write(string); document.write(\"</br>\"); // Use sort() method to sort the stringsstring.sort(); document.write(\"</br>After sorting</br>\"); // Print sorted string arraydocument.write(string); </script> ", "e": 1103, "s": 647, "text": null }, { "code": null, "e": 1111, "s": 1103, "text": "Output:" }, { "code": null, "e": 1215, "s": 1111, "text": "Original String\nSuraj, Sanjeev, Rajnish, Yash, Ravi\n\nAfter sorting\nRajnish, Ravi, Sanjeev, Suraj, Yash\n" }, { "code": null, "e": 1486, "s": 1215, "text": "Using loop: We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array.Examples:" }, { "code": null, "e": 1577, "s": 1486, "text": "Original StringSuraj,Sanjeev,Rajnish,Yash,RaviAfter sortingRajnish,Ravi,Sanjeev,Suraj,Yash" }, { "code": null, "e": 1643, "s": 1577, "text": "Original String40, 100, 1, 5, 25, 10After sorting1,5,10,25,40,100" }, { "code": null, "e": 1689, "s": 1643, "text": "Below program illustrates the above approach:" }, { "code": null, "e": 1698, "s": 1689, "text": "Program:" }, { "code": "<script>// JavaScript code to sort the strings // Function to perform sortfunction string_sort(str) { var i = 0, j; while (i < str.length) { j = i + 1; while (j < str.length) { if (str[j] < str[i]) { var temp = str[i]; str[i] = str[j]; str[j] = temp; } j++; } i++; }} // Driver code // Original stringvar string = [\"Suraj\", \"Sanjeev\", \"Rajnish\", \"Yash\", \"Ravi\"]; // Print original string arraydocument.write(\"Original String</br>\");document.write(string); document.write(\"</br>\"); // Call string_sort methodstring_sort(string); document.write(\"</br>After sorting</br>\"); // Print sorted string arraydocument.write(string); </script> ", "e": 2521, "s": 1698, "text": null }, { "code": null, "e": 2529, "s": 2521, "text": "Output:" }, { "code": null, "e": 2633, "s": 2529, "text": "Original String\nSuraj, Sanjeev, Rajnish, Yash, Ravi\n\nAfter sorting\nRajnish, Ravi, Sanjeev, Suraj, Yash\n" }, { "code": null, "e": 2651, "s": 2633, "text": "javascript-string" }, { "code": null, "e": 2658, "s": 2651, "text": "Picked" }, { "code": null, "e": 2669, "s": 2658, "text": "JavaScript" }, { "code": null, "e": 2686, "s": 2669, "text": "Web Technologies" }, { "code": null, "e": 2713, "s": 2686, "text": "Web technologies Questions" } ]
How to save connection result in a variable in Node.js ?
07 Apr, 2021 We are going to use the query function in MySQL library in node.js that will return our output as expected. Using this approach, we can save connection result in a variable in Node.js. Setting up environment and Execution: Step 1: Initialize node project using the following command. npm init Step 2: Turn on MySQL Database Step 3: After creating the NodeJS application, Install the mysql module using the following command. npm install mysql Database Table: Our sample gfg_table database with look like this. Step 4: Create an index.js file with the following code. index.js const mysql = require("mysql"); var db_con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "gfg_db"}); let output; const setOutput = (rows) => { output = rows; console.log(output);} db_con.connect(async(err) => { if (err) { console.log("Database Connection Failed !!!", err); return; } console.log("Connected to Database"); let query = 'SELECT * FROM users'; db_con.query(query, (err, rows) => { if (err) { console.log("internal error", err); return; } // This is the important function setOutput(rows); });}); Step 5: Run the index.js file using the following command. node index.js Output: Node.js-Methods NodeJS-MySQL NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 213, "s": 28, "text": "We are going to use the query function in MySQL library in node.js that will return our output as expected. Using this approach, we can save connection result in a variable in Node.js." }, { "code": null, "e": 251, "s": 213, "text": "Setting up environment and Execution:" }, { "code": null, "e": 312, "s": 251, "text": "Step 1: Initialize node project using the following command." }, { "code": null, "e": 321, "s": 312, "text": "npm init" }, { "code": null, "e": 352, "s": 321, "text": "Step 2: Turn on MySQL Database" }, { "code": null, "e": 453, "s": 352, "text": "Step 3: After creating the NodeJS application, Install the mysql module using the following command." }, { "code": null, "e": 471, "s": 453, "text": "npm install mysql" }, { "code": null, "e": 538, "s": 471, "text": "Database Table: Our sample gfg_table database with look like this." }, { "code": null, "e": 595, "s": 538, "text": "Step 4: Create an index.js file with the following code." }, { "code": null, "e": 604, "s": 595, "text": "index.js" }, { "code": "const mysql = require(\"mysql\"); var db_con = mysql.createConnection({ host: \"localhost\", user: \"root\", password: \"\", database: \"gfg_db\"}); let output; const setOutput = (rows) => { output = rows; console.log(output);} db_con.connect(async(err) => { if (err) { console.log(\"Database Connection Failed !!!\", err); return; } console.log(\"Connected to Database\"); let query = 'SELECT * FROM users'; db_con.query(query, (err, rows) => { if (err) { console.log(\"internal error\", err); return; } // This is the important function setOutput(rows); });});", "e": 1269, "s": 604, "text": null }, { "code": null, "e": 1328, "s": 1269, "text": "Step 5: Run the index.js file using the following command." }, { "code": null, "e": 1342, "s": 1328, "text": "node index.js" }, { "code": null, "e": 1350, "s": 1342, "text": "Output:" }, { "code": null, "e": 1366, "s": 1350, "text": "Node.js-Methods" }, { "code": null, "e": 1379, "s": 1366, "text": "NodeJS-MySQL" }, { "code": null, "e": 1396, "s": 1379, "text": "NodeJS-Questions" }, { "code": null, "e": 1403, "s": 1396, "text": "Picked" }, { "code": null, "e": 1411, "s": 1403, "text": "Node.js" }, { "code": null, "e": 1428, "s": 1411, "text": "Web Technologies" } ]
HTML | DOM getElementsByName() Method - GeeksforGeeks
25 Jul, 2019 The getElementsByName() method returns collection of all elements of particular document by name. This collection is called node list and each element of the node list can be visited with the help of the index. Syntax: document.getElementsByName(name) Parameter:This function accepts name of document. Return Type:This function returns collection of elements. By using the build in method length we can find the total number of elements presents inside that particular element. Below example illustrates it clearly. Note:There is no getElementByName() method exists, it is getElementsByName(), with a ‘s’.Example-1: <!DOCTYPE html><html> <head> <title>DOM getElementsByName()</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> // creating geeks function to display // number of elements at particular name function geeks() { // taking list of elements under name ga var x = document.getElementsByName("ga"); // printing number of elements inside alert tag alert("Total element with name ga are: " + x.length); } </script></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementsByName() Method</h2> <!-- creating tag with name ga --> <h4 name="ga">Geeks</h4> <h4 name="ga">for</h4> <h4 name="ga">Geeks</h4> <input type="button" onclick="geeks()" value="Click here" /></body> </html> Output: Since document.getElementsByName() method returns an array containing of objects if we want to get value of any object then we should use document.getElementsByName(“element_name”)[index].value. Otherwise we will get result undefined. Below program explains it clearly. <!DOCTYPE html><html> <head> <title>DOM getElementsByName()</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> // creating geeks function to display // elements at particular name function geeks() { // This line will print entered result alert(document.getElementsByName("ga")[0].value); } </script></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementsByName() Method</h2> <!-- This will create an input tag--> <input type="text" name="ga" /> <br> <br> <!-- function will be called when we click on this button--> <input type="button" onclick="geeks()" value="Click here" /> <p></p></body> </html> Output: Supported Browsers: The browser supported by DOM getElementsByName() method are listed below: Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23513, "s": 23485, "text": "\n25 Jul, 2019" }, { "code": null, "e": 23724, "s": 23513, "text": "The getElementsByName() method returns collection of all elements of particular document by name. This collection is called node list and each element of the node list can be visited with the help of the index." }, { "code": null, "e": 23732, "s": 23724, "text": "Syntax:" }, { "code": null, "e": 23766, "s": 23732, "text": "document.getElementsByName(name)\n" }, { "code": null, "e": 23816, "s": 23766, "text": "Parameter:This function accepts name of document." }, { "code": null, "e": 23874, "s": 23816, "text": "Return Type:This function returns collection of elements." }, { "code": null, "e": 24030, "s": 23874, "text": "By using the build in method length we can find the total number of elements presents inside that particular element. Below example illustrates it clearly." }, { "code": null, "e": 24130, "s": 24030, "text": "Note:There is no getElementByName() method exists, it is getElementsByName(), with a ‘s’.Example-1:" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM getElementsByName()</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> // creating geeks function to display // number of elements at particular name function geeks() { // taking list of elements under name ga var x = document.getElementsByName(\"ga\"); // printing number of elements inside alert tag alert(\"Total element with name ga are: \" + x.length); } </script></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementsByName() Method</h2> <!-- creating tag with name ga --> <h4 name=\"ga\">Geeks</h4> <h4 name=\"ga\">for</h4> <h4 name=\"ga\">Geeks</h4> <input type=\"button\" onclick=\"geeks()\" value=\"Click here\" /></body> </html>", "e": 25032, "s": 24130, "text": null }, { "code": null, "e": 25040, "s": 25032, "text": "Output:" }, { "code": null, "e": 25310, "s": 25040, "text": "Since document.getElementsByName() method returns an array containing of objects if we want to get value of any object then we should use document.getElementsByName(“element_name”)[index].value. Otherwise we will get result undefined. Below program explains it clearly." }, { "code": "<!DOCTYPE html><html> <head> <title>DOM getElementsByName()</title> <style> body { text-align: center; } h1 { color: green; } </style> <script> // creating geeks function to display // elements at particular name function geeks() { // This line will print entered result alert(document.getElementsByName(\"ga\")[0].value); } </script></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementsByName() Method</h2> <!-- This will create an input tag--> <input type=\"text\" name=\"ga\" /> <br> <br> <!-- function will be called when we click on this button--> <input type=\"button\" onclick=\"geeks()\" value=\"Click here\" /> <p></p></body> </html> ", "e": 26159, "s": 25310, "text": null }, { "code": null, "e": 26167, "s": 26159, "text": "Output:" }, { "code": null, "e": 26261, "s": 26167, "text": "Supported Browsers: The browser supported by DOM getElementsByName() method are listed below:" }, { "code": null, "e": 26268, "s": 26261, "text": "Chrome" }, { "code": null, "e": 26286, "s": 26268, "text": "Internet Explorer" }, { "code": null, "e": 26294, "s": 26286, "text": "Firefox" }, { "code": null, "e": 26300, "s": 26294, "text": "Opera" }, { "code": null, "e": 26307, "s": 26300, "text": "Safari" }, { "code": null, "e": 26444, "s": 26307, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26453, "s": 26444, "text": "HTML-DOM" }, { "code": null, "e": 26460, "s": 26453, "text": "Picked" }, { "code": null, "e": 26465, "s": 26460, "text": "HTML" }, { "code": null, "e": 26482, "s": 26465, "text": "Web Technologies" }, { "code": null, "e": 26487, "s": 26482, "text": "HTML" }, { "code": null, "e": 26585, "s": 26487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26594, "s": 26585, "text": "Comments" }, { "code": null, "e": 26607, "s": 26594, "text": "Old Comments" }, { "code": null, "e": 26669, "s": 26607, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26719, "s": 26669, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26779, "s": 26719, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26827, "s": 26779, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26888, "s": 26827, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26944, "s": 26888, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26977, "s": 26944, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27039, "s": 26977, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27082, "s": 27039, "text": "How to fetch data from an API in ReactJS ?" } ]
MD5 hash encoding using Python?
One of the major concern of all IT companies in the security of there data. Multiple hashing techniques are there to project and check our data. Hash is a function which takes variable length sequence of bytes as input and converts it to a fixed length sequence. However, to get your original data(input bytes) back is not easy. For example, x is your input and f is the f is the hashing function, then calculating f(x) is quick and easy but trying to obtain x again is a very time-consuming job. The return value from a hash function is called hash, checksum, hash value or message digest. We can summarize above as below − Suppose you want to convert the “Hello World” message to md5 hash function then the result is a, In real life scenario, hash functions are used heavily in cryptographic algorithms, in digital signatures, fingerprints, to store password and many more areas. As a python programmer, we need hash functions to check the duplicity of data or files, to check data integrity when you transmit data over a public network, storing the password in a database etc. Two mostly used hash functions or algorithms are − MD5 - MD5 or message digest algorithm will produce a 128-bit hash value. There are a couple of security issues with the md5 algorithm that is why we mainly used it to check data integrity. MD5 - MD5 or message digest algorithm will produce a 128-bit hash value. There are a couple of security issues with the md5 algorithm that is why we mainly used it to check data integrity. SHA - There are multiple algorithms comes under SHA group of the algorithm, which is developed by U.S Federal Information processing standard. These algorithms are much more secure than md5 and hence widely used in several areas including cryptographic applications. The message generated by these algorithms ranges from 160 bits to 512 bits. SHA - There are multiple algorithms comes under SHA group of the algorithm, which is developed by U.S Federal Information processing standard. These algorithms are much more secure than md5 and hence widely used in several areas including cryptographic applications. The message generated by these algorithms ranges from 160 bits to 512 bits. The Python standard library includes a module called hashlib, which contains most of the popular hashing algorithms. Most of the algorithms are implemented inside hashlib module however, if you have OpenSSL installed, hashlib can be used to work with these algorithms too. First, if you want to use any hashing algorithm, import the hashlib module − import hashlib Now to check if the required algorithm or what all algorithms are currently available in hashlib module − >>> print(hashlib.algorithms_available) {'sha3_256', 'sha3_224', 'sha1', 'blake2b', 'sha512', 'dsaEncryption', 'dsaWithSHA', 'DSA', 'md5', 'sha384', 'sha224', 'sha3_384', 'ecdsa-with-SHA1', 'DSA-SHA', 'SHA1', 'md4', 'SHA256', 'MD4', 'sha3_512', 'whirlpool', 'sha256', 'shake_256', 'SHA', 'RIPEMD160', 'shake_128', 'SHA512', 'ripemd160', 'SHA224', 'sha', 'blake2s', 'SHA384', 'MD5'} The above list of algorithms available through hashlib module includes the algorithms through OpenSSL. However, to check the list of algorithms always available, we can check it through algorithms_guaranteed. >>> print(hashlib.algorithms_guaranteed) {'sha3_512', 'sha256', 'sha3_256', 'shake_256', 'sha3_224', 'sha1', 'blake2b', 'sha512', 'md5', 'shake_128', 'sha384', 'sha224', 'sha3_384', 'blake2s'} Let’s create one simple program through md5 algorithm − Live Demo import hashlib hash_obj = hashlib.md5(b'Hello, Python!') print(hash_obj.hexdigest()) a0af7810eb5fcb84c730f851361de06a The code above takes the “Hello, Python!” string as input and prints the HEX digest of that string. Hexdigest returns a HEX string representing the hash. However, if you want the sequence of bytes returned, you should use hash_obj.diget(), like − Live Demo import hashlib hash_obj = hashlib.md5(b'Hello, Python!') #To generate, sequence of bytes print(hash_obj.digest()) b'\xa0\xafx\x10\xeb_\xcb\x84\xc70\xf8Q6\x1d\xe0j' If you notice, we have used ‘b’ before any string literals, this is to generate the bytes from the string as hashing function only accept a sequence of bytes as a parameter. In case you want to pass the string from the console, don’t forget to encode the string in a sequence of bytes − Live Demo import hashlib mystring = input('Enter string to hash: ') hash_obj = hashlib.md5(mystring.encode()) print(hash_obj.hexdigest()) Enter string to hash: Hello, TutorialsPoint 9a5d3fad65690dcf44adaec67226abe7
[ { "code": null, "e": 1207, "s": 1062, "text": "One of the major concern of all IT companies in the security of there data. Multiple hashing techniques are there to project and check our data." }, { "code": null, "e": 1559, "s": 1207, "text": "Hash is a function which takes variable length sequence of bytes as input and converts it to a fixed length sequence. However, to get your original data(input bytes) back is not easy. For example, x is your input and f is the f is the hashing function, then calculating f(x) is quick and easy but trying to obtain x again is a very time-consuming job." }, { "code": null, "e": 1653, "s": 1559, "text": "The return value from a hash function is called hash, checksum, hash value or message digest." }, { "code": null, "e": 1687, "s": 1653, "text": "We can summarize above as below −" }, { "code": null, "e": 1784, "s": 1687, "text": "Suppose you want to convert the “Hello World” message to md5 hash function then the result is a," }, { "code": null, "e": 2142, "s": 1784, "text": "In real life scenario, hash functions are used heavily in cryptographic algorithms, in digital signatures, fingerprints, to store password and many more areas. As a python programmer, we need hash functions to check the duplicity of data or files, to check data integrity when you transmit data over a public network, storing the password in a database etc." }, { "code": null, "e": 2193, "s": 2142, "text": "Two mostly used hash functions or algorithms are −" }, { "code": null, "e": 2382, "s": 2193, "text": "MD5 - MD5 or message digest algorithm will produce a 128-bit hash value. There are a couple of security issues with the md5 algorithm that is why we mainly used it to check data integrity." }, { "code": null, "e": 2571, "s": 2382, "text": "MD5 - MD5 or message digest algorithm will produce a 128-bit hash value. There are a couple of security issues with the md5 algorithm that is why we mainly used it to check data integrity." }, { "code": null, "e": 2914, "s": 2571, "text": "SHA - There are multiple algorithms comes under SHA group of the algorithm, which is developed by U.S Federal Information processing standard. These algorithms are much more secure than md5 and hence widely used in several areas including cryptographic applications. The message generated by these algorithms ranges from 160 bits to 512 bits." }, { "code": null, "e": 3257, "s": 2914, "text": "SHA - There are multiple algorithms comes under SHA group of the algorithm, which is developed by U.S Federal Information processing standard. These algorithms are much more secure than md5 and hence widely used in several areas including cryptographic applications. The message generated by these algorithms ranges from 160 bits to 512 bits." }, { "code": null, "e": 3530, "s": 3257, "text": "The Python standard library includes a module called hashlib, which contains most of the popular hashing algorithms. Most of the algorithms are implemented inside hashlib module however, if you have OpenSSL installed, hashlib can be used to work with these algorithms too." }, { "code": null, "e": 3607, "s": 3530, "text": "First, if you want to use any hashing algorithm, import the hashlib module −" }, { "code": null, "e": 3622, "s": 3607, "text": "import hashlib" }, { "code": null, "e": 3728, "s": 3622, "text": "Now to check if the required algorithm or what all algorithms are currently available in hashlib module −" }, { "code": null, "e": 4110, "s": 3728, "text": ">>> print(hashlib.algorithms_available)\n{'sha3_256', 'sha3_224', 'sha1', 'blake2b', 'sha512', 'dsaEncryption', 'dsaWithSHA', 'DSA', 'md5', 'sha384', 'sha224', 'sha3_384', 'ecdsa-with-SHA1', 'DSA-SHA', 'SHA1', 'md4', 'SHA256', 'MD4', 'sha3_512', 'whirlpool', 'sha256', 'shake_256', 'SHA', 'RIPEMD160', 'shake_128', 'SHA512', 'ripemd160', 'SHA224', 'sha', 'blake2s', 'SHA384', 'MD5'}" }, { "code": null, "e": 4213, "s": 4110, "text": "The above list of algorithms available through hashlib module includes the algorithms through OpenSSL." }, { "code": null, "e": 4319, "s": 4213, "text": "However, to check the list of algorithms always available, we can check it through algorithms_guaranteed." }, { "code": null, "e": 4512, "s": 4319, "text": ">>> print(hashlib.algorithms_guaranteed)\n{'sha3_512', 'sha256', 'sha3_256', 'shake_256', 'sha3_224', 'sha1', 'blake2b', 'sha512', 'md5', 'shake_128', 'sha384', 'sha224', 'sha3_384', 'blake2s'}" }, { "code": null, "e": 4568, "s": 4512, "text": "Let’s create one simple program through md5 algorithm −" }, { "code": null, "e": 4579, "s": 4568, "text": " Live Demo" }, { "code": null, "e": 4664, "s": 4579, "text": "import hashlib\nhash_obj = hashlib.md5(b'Hello, Python!')\nprint(hash_obj.hexdigest())" }, { "code": null, "e": 4697, "s": 4664, "text": "a0af7810eb5fcb84c730f851361de06a" }, { "code": null, "e": 4851, "s": 4697, "text": "The code above takes the “Hello, Python!” string as input and prints the HEX digest of that string. Hexdigest returns a HEX string representing the hash." }, { "code": null, "e": 4944, "s": 4851, "text": "However, if you want the sequence of bytes returned, you should use hash_obj.diget(), like −" }, { "code": null, "e": 4955, "s": 4944, "text": " Live Demo" }, { "code": null, "e": 5069, "s": 4955, "text": "import hashlib\nhash_obj = hashlib.md5(b'Hello, Python!')\n#To generate, sequence of bytes\nprint(hash_obj.digest())" }, { "code": null, "e": 5119, "s": 5069, "text": "b'\\xa0\\xafx\\x10\\xeb_\\xcb\\x84\\xc70\\xf8Q6\\x1d\\xe0j'" }, { "code": null, "e": 5293, "s": 5119, "text": "If you notice, we have used ‘b’ before any string literals, this is to generate the bytes from the string as hashing function only accept a sequence of bytes as a parameter." }, { "code": null, "e": 5406, "s": 5293, "text": "In case you want to pass the string from the console, don’t forget to encode the string in a sequence of bytes −" }, { "code": null, "e": 5417, "s": 5406, "text": " Live Demo" }, { "code": null, "e": 5545, "s": 5417, "text": "import hashlib\nmystring = input('Enter string to hash: ')\nhash_obj = hashlib.md5(mystring.encode())\nprint(hash_obj.hexdigest())" }, { "code": null, "e": 5622, "s": 5545, "text": "Enter string to hash: Hello, TutorialsPoint\n9a5d3fad65690dcf44adaec67226abe7" } ]
How can I plot a single point in Matplotlib Python?
To plot a single data point in matplotlib, we can take the following steps − Initialize a list for x and y with a single value. Initialize a list for x and y with a single value. Limit X and Y axis range for 0 to 5. Limit X and Y axis range for 0 to 5. Lay out a grid in the current line style. Lay out a grid in the current line style. Plot x and y using plot() method with marker="o", markeredgecolor="red", markerfacecolor="green". Plot x and y using plot() method with marker="o", markeredgecolor="red", markerfacecolor="green". To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [4] y = [3] plt.xlim(0, 5) plt.ylim(0, 5) plt.grid() plt.plot(x, y, marker="o", markersize=20, markeredgecolor="red", markerfacecolor="green") plt.show()
[ { "code": null, "e": 1139, "s": 1062, "text": "To plot a single data point in matplotlib, we can take the following steps −" }, { "code": null, "e": 1190, "s": 1139, "text": "Initialize a list for x and y with a single value." }, { "code": null, "e": 1241, "s": 1190, "text": "Initialize a list for x and y with a single value." }, { "code": null, "e": 1278, "s": 1241, "text": "Limit X and Y axis range for 0 to 5." }, { "code": null, "e": 1315, "s": 1278, "text": "Limit X and Y axis range for 0 to 5." }, { "code": null, "e": 1357, "s": 1315, "text": "Lay out a grid in the current line style." }, { "code": null, "e": 1399, "s": 1357, "text": "Lay out a grid in the current line style." }, { "code": null, "e": 1497, "s": 1399, "text": "Plot x and y using plot() method with marker=\"o\", markeredgecolor=\"red\", markerfacecolor=\"green\"." }, { "code": null, "e": 1595, "s": 1497, "text": "Plot x and y using plot() method with marker=\"o\", markeredgecolor=\"red\", markerfacecolor=\"green\"." }, { "code": null, "e": 1637, "s": 1595, "text": "To display the figure, use show() method." }, { "code": null, "e": 1679, "s": 1637, "text": "To display the figure, use show() method." }, { "code": null, "e": 1961, "s": 1679, "text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = [4]\ny = [3]\nplt.xlim(0, 5)\nplt.ylim(0, 5)\nplt.grid()\nplt.plot(x, y, marker=\"o\", markersize=20, markeredgecolor=\"red\", markerfacecolor=\"green\")\nplt.show()" } ]
How to download and visualize your Twitter network | by Steve Hedden | Towards Data Science
Social Network Analysis (SNA) is an incredibly interesting field of research in itself as well as a useful skillset for data scientists to apply to other fields. In this tutorial, we will use a Python package, Tweepy, to download Twitter data from the Twitter API and another Python package, NetworkX, to build a network out of that data and run some analysis. Finally, we will use Gephi to visualize the network. According to Wikipedia, “Social network analysis (SNA) is the process of investigating social structures through the use of networks and graph theory. It characterizes networked structures in terms of nodes (individual actors, people, or things within the network) and the ties, edges, or links (relationships or interactions) that connect them.” It has made its way into virtually every field — again, according to Wikipedia: “Social network analysis has emerged as a key technique in modern sociology. It has also gained a significant following in anthropology, biology, demography, communication studies, economics, geography, history, information science, organizational studies, political science, public health, social psychology, development studies, sociolinguistics, and computer science and is now commonly available as a consumer tool (see the list of SNA software).” Use Tweepy to scrape Twitter for all of my followers and (most of) their followersCreate a pandas DataFrame from all of these connectionsUse NetworkX to extract a network from these data and run some basic network analyticsVisualize the network in Gephi Use Tweepy to scrape Twitter for all of my followers and (most of) their followers Create a pandas DataFrame from all of these connections Use NetworkX to extract a network from these data and run some basic network analytics Visualize the network in Gephi Twitter offers a free REST API to stream data in realtime and download historical data in chunks. Jaime Zornoza has written some great tutorials on using the API for both streaming and downloading data, so if you’re looking to get started with using the API, I’d suggest going through those first. To get started, we will build a network using my personal Twitter account (@ stevehedden). To do this, we’ll start with a list of all of my followers (about 450). Then we’ll get all of the followers of those 450 accounts. To save time, for accounts with more than 5,000 followers, I will only scrape the first 5,000 of their followers. First, we need to import the Tweepy and pandas packages. import tweepyimport pandas as pd Then we need to enter our Twitter API credentials. If you don’t have these already, you will need to go to https://apps.twitter.com/ and “create an app”. After you create an app, go to “Keys and Tokens” to get your tokens. consumer_key = 'XXXXXXXXXXXXX'consumer_secret = 'XXXXXXXXXXXXX'access_token = 'XXXXXXXXXXXXX'access_token_secret = 'XXXXXXXXXXXXX' With Tweepy, we can use these credentials to connect to the Twitter API and begin downloading data. The following code just uses the credentials entered above to connect to the API. Since we are going to be downloading pretty big datasets it is important to specify some parameters when we initialize the API. We set ‘wait_on_rate_limit’ and ‘wait_on_rate_limit_notify’ to True. There are rate limits when downloading data from Twitter — you can only make a limited number of download requests to the API in a given time frame. By setting these parameters to True, we won’t break the connection to the API when we hit these limits. Instead, we’ll just wait until the timeout ends and we can continue downloading data. auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True) To start the data download, we will get all of the followers from an individual user. To get this, you need the user ID of the user. You can get the user ID of a user if you know their screen name using the code below. me = api.get_user(screen_name = ‘stevehedden’)me.id My user id is: 1210627806 A network consists of nodes (or vertices) and links (or edges). For this network, we will use individual user accounts as nodes and followers as links. Our goal, therefore, is to create an edge DataFrame of user IDs with two columns: source and target. For each row, the target follows the source. To start, we want to list all of my followers as targets. The screenshot above shows the structure of the DataFrame we want to create. The first column, the “source”, is my user ID (1210627806) and the second column, the “target”, are all of my followers. The following code creates a list of my 450 followers. user_list = ["1210627806"]follower_list = []for user in user_list: followers = [] try: for page in tweepy.Cursor(api.followers_ids, user_id=user).pages(): followers.extend(page) print(len(followers)) except tweepy.TweepError: print("error") continue follower_list.append(followers) Now that we have a list of all the followers we can put them into a DataFrame. df = pd.DataFrame(columns=['source','target']) #Empty DataFramedf['target'] = follower_list[0] #Set the list of followers as the target columndf['source'] = 1210627806 #Set my user ID as the source But this is not a very interesting network. To visualize this simple network, we can use the NetworkX package to convert the DataFrame into a graph or network. import networkx as nxG = nx.from_pandas_edgelist(df, 'source', 'target') #Turn df into graphpos = nx.spring_layout(G) #specify layout for visual Then we plot the graph using matplotlib. import matplotlib.pyplot as pltf, ax = plt.subplots(figsize=(10, 10))plt.style.use('ggplot')nodes = nx.draw_networkx_nodes(G, pos, alpha=0.8)nodes.set_edgecolor('k')nx.draw_networkx_labels(G, pos, font_size=8)nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.2) The code above renders the following visual — not very interesting. What we really want is to get all of the followers of these 450 users. To do this, we will loop through the list of all those 450 users, get their followers, and add those links to the original DataFrame. This is the code that will take a very long time to run because of the rate limits. user_list = list(df['target']) #Use the list of followers we extracted in the code above i.e. my 450 followersfor userID in user_list: print(userID) followers = [] follower_list = [] # fetching the user user = api.get_user(userID) # fetching the followers_count followers_count = user.followers_count try: for page in tweepy.Cursor(api.followers_ids, user_id=userID).pages(): followers.extend(page) print(len(followers)) if followers_count >= 5000: #Only take first 5000 followers break except tweepy.TweepError: print("error") continue follower_list.append(followers) temp = pd.DataFrame(columns=['source', 'target']) temp['target'] = follower_list[0] temp['source'] = userID df = df.append(temp) df.to_csv("networkOfFollowers.csv") This code is very similar to the code above in that it gets all the followers of a given user ID. The major difference is that instead of feeding in just one account, we are looping through all 450 accounts that follow me. Another difference is that if an account has more than 5000 followers, we only take the first 5000 followers. This is because of the way the API works. Each API request will only return 5000 accounts. So if we want all followers from an account that has, say, one million followers, we would need to make 200 individuals requests. Because of the rate limits, I left this running overnight to get all the data. It makes 15 API requests, then has to wait for 15 minutes, then makes another 15 requests, and so on. So it can take a long time. Once this is done running, you should have a csv with all of the edges of the network. I wrote this all to a csv just so that if it breaks while running I still have all the edges already scraped. Now read the csv and turn the df into a graph using NetworkX. df = pd.read_csv(“networkOfFollowers.csv”) #Read into a dfG = nx.from_pandas_edgelist(df, 'source', 'target') Once the data has been converted to a graph, we can run some basic network analytics. G.number_of_nodes() #Find the total number of nodes in this graph There are 716, 653 nodes in my network! We can also find the most influential nodes in the network using centrality measures. The most simple measure of centrality is Degree Centrality, which is just a function of the number of connections each node has. The following code finds the number of connections each node has i.e. the degree of each node and sorts them in descending order. G_sorted = pd.DataFrame(sorted(G.degree, key=lambda x: x[1], reverse=True))G_sorted.columns = [‘nconst’,’degree’]G_sorted.head() The node in my network with the highest degree is node 37728789 or @ TheSolarCo. TheSolarCo has a degree of 5039. 5000 of these connections are the 5000 followers of this node that we scraped. But this means there are 39 additional connections — meaning TheSolarCo follows 39 accounts that follow me. To get the username of an account given the user ID use the following code, similar to how we got our user ID above. u = api.get_user(37728789)u.screen_name Because the network is so big now (over 700K nodes), any analytics will take a long time to run and any visualization will be a complete mess. For the rest of this tutorial, we will filter the network down to a more manageable number of nodes. We do this using the k_core function of NetworkX. The k_core function filters out nodes with degree less than a given number, k. In this example, I set k equal to 10, which reduces the number of nodes in the graph to about 1000. G_tmp = nx.k_core(G, 10) #Exclude nodes with degree less than 10 With this smaller graph we can easily do some network analytics. We start by splitting the graph into groups using a community detection algorithm. from community import community_louvainpartition = community_louvain.best_partition(G_tmp)#Turn partition into dataframepartition1 = pd.DataFrame([partition]).Tpartition1 = partition1.reset_index()partition1.columns = ['names','group'] We need to run the degree centrality code again now that our network is smaller. G_sorted = pd.DataFrame(sorted(G_tmp.degree, key=lambda x: x[1], reverse=True))G_sorted.columns = ['names','degree']G_sorted.head()dc = G_sorted Now that we have the nodes split into groups and the degree of each node, we combine these into one DataFrame. combined = pd.merge(dc,partition1, how='left', left_on="names",right_on="names") Now your DataFrame should look something like this. Now we can visualize this graph using the following code. pos = nx.spring_layout(G_tmp)f, ax = plt.subplots(figsize=(10, 10))plt.style.use('ggplot')#cc = nx.betweenness_centrality(G2)nodes = nx.draw_networkx_nodes(G_tmp, pos, cmap=plt.cm.Set1, node_color=combined['group'], alpha=0.8)nodes.set_edgecolor('k')nx.draw_networkx_labels(G_tmp, pos, font_size=8)nx.draw_networkx_edges(G_tmp, pos, width=1.0, alpha=0.2)plt.savefig('twitterFollowers.png') This should create graph that looks something like this. What a mess. I’m sure there are ways to make that visual look better using matplotlib, but at this point, I always just export the files to csv format and use Gephi to visualize. Gephi is an open-source network analysis and visualization software. You should be able to easily install it for free from their website. It’s pretty easy to get started and allows for some really beautiful visualizations. If you have never used Gephi, here is a good tutorial to get started from Luca Hammer. To use Gephi, first you need to export the node list and the edge list as csv files. combined = combined.rename(columns={"names": "Id"}) #I've found Gephi really likes when your node column is called 'Id'edges = nx.to_pandas_edgelist(G_tmp)nodes = combined['Id']edges.to_csv("edges.csv")combined.to_csv("nodes.csv") You can follow the Gephi tutorial I mentioned above to import these files into Gephi and start visualizing your network. Here is what mine looks like. Hopefully, you were able to follow along without too many issues. If you do have issues or if you feel like I’ve missed anything, leave a comment below and I’ll respond.
[ { "code": null, "e": 586, "s": 172, "text": "Social Network Analysis (SNA) is an incredibly interesting field of research in itself as well as a useful skillset for data scientists to apply to other fields. In this tutorial, we will use a Python package, Tweepy, to download Twitter data from the Twitter API and another Python package, NetworkX, to build a network out of that data and run some analysis. Finally, we will use Gephi to visualize the network." }, { "code": null, "e": 610, "s": 586, "text": "According to Wikipedia," }, { "code": null, "e": 933, "s": 610, "text": "“Social network analysis (SNA) is the process of investigating social structures through the use of networks and graph theory. It characterizes networked structures in terms of nodes (individual actors, people, or things within the network) and the ties, edges, or links (relationships or interactions) that connect them.”" }, { "code": null, "e": 1013, "s": 933, "text": "It has made its way into virtually every field — again, according to Wikipedia:" }, { "code": null, "e": 1465, "s": 1013, "text": "“Social network analysis has emerged as a key technique in modern sociology. It has also gained a significant following in anthropology, biology, demography, communication studies, economics, geography, history, information science, organizational studies, political science, public health, social psychology, development studies, sociolinguistics, and computer science and is now commonly available as a consumer tool (see the list of SNA software).”" }, { "code": null, "e": 1719, "s": 1465, "text": "Use Tweepy to scrape Twitter for all of my followers and (most of) their followersCreate a pandas DataFrame from all of these connectionsUse NetworkX to extract a network from these data and run some basic network analyticsVisualize the network in Gephi" }, { "code": null, "e": 1802, "s": 1719, "text": "Use Tweepy to scrape Twitter for all of my followers and (most of) their followers" }, { "code": null, "e": 1858, "s": 1802, "text": "Create a pandas DataFrame from all of these connections" }, { "code": null, "e": 1945, "s": 1858, "text": "Use NetworkX to extract a network from these data and run some basic network analytics" }, { "code": null, "e": 1976, "s": 1945, "text": "Visualize the network in Gephi" }, { "code": null, "e": 2274, "s": 1976, "text": "Twitter offers a free REST API to stream data in realtime and download historical data in chunks. Jaime Zornoza has written some great tutorials on using the API for both streaming and downloading data, so if you’re looking to get started with using the API, I’d suggest going through those first." }, { "code": null, "e": 2610, "s": 2274, "text": "To get started, we will build a network using my personal Twitter account (@ stevehedden). To do this, we’ll start with a list of all of my followers (about 450). Then we’ll get all of the followers of those 450 accounts. To save time, for accounts with more than 5,000 followers, I will only scrape the first 5,000 of their followers." }, { "code": null, "e": 2667, "s": 2610, "text": "First, we need to import the Tweepy and pandas packages." }, { "code": null, "e": 2700, "s": 2667, "text": "import tweepyimport pandas as pd" }, { "code": null, "e": 2923, "s": 2700, "text": "Then we need to enter our Twitter API credentials. If you don’t have these already, you will need to go to https://apps.twitter.com/ and “create an app”. After you create an app, go to “Keys and Tokens” to get your tokens." }, { "code": null, "e": 3054, "s": 2923, "text": "consumer_key = 'XXXXXXXXXXXXX'consumer_secret = 'XXXXXXXXXXXXX'access_token = 'XXXXXXXXXXXXX'access_token_secret = 'XXXXXXXXXXXXX'" }, { "code": null, "e": 3772, "s": 3054, "text": "With Tweepy, we can use these credentials to connect to the Twitter API and begin downloading data. The following code just uses the credentials entered above to connect to the API. Since we are going to be downloading pretty big datasets it is important to specify some parameters when we initialize the API. We set ‘wait_on_rate_limit’ and ‘wait_on_rate_limit_notify’ to True. There are rate limits when downloading data from Twitter — you can only make a limited number of download requests to the API in a given time frame. By setting these parameters to True, we won’t break the connection to the API when we hit these limits. Instead, we’ll just wait until the timeout ends and we can continue downloading data." }, { "code": null, "e": 3983, "s": 3772, "text": "auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)" }, { "code": null, "e": 4202, "s": 3983, "text": "To start the data download, we will get all of the followers from an individual user. To get this, you need the user ID of the user. You can get the user ID of a user if you know their screen name using the code below." }, { "code": null, "e": 4254, "s": 4202, "text": "me = api.get_user(screen_name = ‘stevehedden’)me.id" }, { "code": null, "e": 4280, "s": 4254, "text": "My user id is: 1210627806" }, { "code": null, "e": 4636, "s": 4280, "text": "A network consists of nodes (or vertices) and links (or edges). For this network, we will use individual user accounts as nodes and followers as links. Our goal, therefore, is to create an edge DataFrame of user IDs with two columns: source and target. For each row, the target follows the source. To start, we want to list all of my followers as targets." }, { "code": null, "e": 4834, "s": 4636, "text": "The screenshot above shows the structure of the DataFrame we want to create. The first column, the “source”, is my user ID (1210627806) and the second column, the “target”, are all of my followers." }, { "code": null, "e": 4889, "s": 4834, "text": "The following code creates a list of my 450 followers." }, { "code": null, "e": 5226, "s": 4889, "text": "user_list = [\"1210627806\"]follower_list = []for user in user_list: followers = [] try: for page in tweepy.Cursor(api.followers_ids, user_id=user).pages(): followers.extend(page) print(len(followers)) except tweepy.TweepError: print(\"error\") continue follower_list.append(followers)" }, { "code": null, "e": 5305, "s": 5226, "text": "Now that we have a list of all the followers we can put them into a DataFrame." }, { "code": null, "e": 5504, "s": 5305, "text": "df = pd.DataFrame(columns=['source','target']) #Empty DataFramedf['target'] = follower_list[0] #Set the list of followers as the target columndf['source'] = 1210627806 #Set my user ID as the source " }, { "code": null, "e": 5664, "s": 5504, "text": "But this is not a very interesting network. To visualize this simple network, we can use the NetworkX package to convert the DataFrame into a graph or network." }, { "code": null, "e": 5809, "s": 5664, "text": "import networkx as nxG = nx.from_pandas_edgelist(df, 'source', 'target') #Turn df into graphpos = nx.spring_layout(G) #specify layout for visual" }, { "code": null, "e": 5850, "s": 5809, "text": "Then we plot the graph using matplotlib." }, { "code": null, "e": 6142, "s": 5850, "text": "import matplotlib.pyplot as pltf, ax = plt.subplots(figsize=(10, 10))plt.style.use('ggplot')nodes = nx.draw_networkx_nodes(G, pos, alpha=0.8)nodes.set_edgecolor('k')nx.draw_networkx_labels(G, pos, font_size=8)nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.2)" }, { "code": null, "e": 6210, "s": 6142, "text": "The code above renders the following visual — not very interesting." }, { "code": null, "e": 6499, "s": 6210, "text": "What we really want is to get all of the followers of these 450 users. To do this, we will loop through the list of all those 450 users, get their followers, and add those links to the original DataFrame. This is the code that will take a very long time to run because of the rate limits." }, { "code": null, "e": 7347, "s": 6499, "text": "user_list = list(df['target']) #Use the list of followers we extracted in the code above i.e. my 450 followersfor userID in user_list: print(userID) followers = [] follower_list = [] # fetching the user user = api.get_user(userID) # fetching the followers_count followers_count = user.followers_count try: for page in tweepy.Cursor(api.followers_ids, user_id=userID).pages(): followers.extend(page) print(len(followers)) if followers_count >= 5000: #Only take first 5000 followers break except tweepy.TweepError: print(\"error\") continue follower_list.append(followers) temp = pd.DataFrame(columns=['source', 'target']) temp['target'] = follower_list[0] temp['source'] = userID df = df.append(temp) df.to_csv(\"networkOfFollowers.csv\")" }, { "code": null, "e": 7901, "s": 7347, "text": "This code is very similar to the code above in that it gets all the followers of a given user ID. The major difference is that instead of feeding in just one account, we are looping through all 450 accounts that follow me. Another difference is that if an account has more than 5000 followers, we only take the first 5000 followers. This is because of the way the API works. Each API request will only return 5000 accounts. So if we want all followers from an account that has, say, one million followers, we would need to make 200 individuals requests." }, { "code": null, "e": 8110, "s": 7901, "text": "Because of the rate limits, I left this running overnight to get all the data. It makes 15 API requests, then has to wait for 15 minutes, then makes another 15 requests, and so on. So it can take a long time." }, { "code": null, "e": 8307, "s": 8110, "text": "Once this is done running, you should have a csv with all of the edges of the network. I wrote this all to a csv just so that if it breaks while running I still have all the edges already scraped." }, { "code": null, "e": 8369, "s": 8307, "text": "Now read the csv and turn the df into a graph using NetworkX." }, { "code": null, "e": 8479, "s": 8369, "text": "df = pd.read_csv(“networkOfFollowers.csv”) #Read into a dfG = nx.from_pandas_edgelist(df, 'source', 'target')" }, { "code": null, "e": 8565, "s": 8479, "text": "Once the data has been converted to a graph, we can run some basic network analytics." }, { "code": null, "e": 8631, "s": 8565, "text": "G.number_of_nodes() #Find the total number of nodes in this graph" }, { "code": null, "e": 8671, "s": 8631, "text": "There are 716, 653 nodes in my network!" }, { "code": null, "e": 9016, "s": 8671, "text": "We can also find the most influential nodes in the network using centrality measures. The most simple measure of centrality is Degree Centrality, which is just a function of the number of connections each node has. The following code finds the number of connections each node has i.e. the degree of each node and sorts them in descending order." }, { "code": null, "e": 9145, "s": 9016, "text": "G_sorted = pd.DataFrame(sorted(G.degree, key=lambda x: x[1], reverse=True))G_sorted.columns = [‘nconst’,’degree’]G_sorted.head()" }, { "code": null, "e": 9563, "s": 9145, "text": "The node in my network with the highest degree is node 37728789 or @ TheSolarCo. TheSolarCo has a degree of 5039. 5000 of these connections are the 5000 followers of this node that we scraped. But this means there are 39 additional connections — meaning TheSolarCo follows 39 accounts that follow me. To get the username of an account given the user ID use the following code, similar to how we got our user ID above." }, { "code": null, "e": 9603, "s": 9563, "text": "u = api.get_user(37728789)u.screen_name" }, { "code": null, "e": 10076, "s": 9603, "text": "Because the network is so big now (over 700K nodes), any analytics will take a long time to run and any visualization will be a complete mess. For the rest of this tutorial, we will filter the network down to a more manageable number of nodes. We do this using the k_core function of NetworkX. The k_core function filters out nodes with degree less than a given number, k. In this example, I set k equal to 10, which reduces the number of nodes in the graph to about 1000." }, { "code": null, "e": 10141, "s": 10076, "text": "G_tmp = nx.k_core(G, 10) #Exclude nodes with degree less than 10" }, { "code": null, "e": 10289, "s": 10141, "text": "With this smaller graph we can easily do some network analytics. We start by splitting the graph into groups using a community detection algorithm." }, { "code": null, "e": 10525, "s": 10289, "text": "from community import community_louvainpartition = community_louvain.best_partition(G_tmp)#Turn partition into dataframepartition1 = pd.DataFrame([partition]).Tpartition1 = partition1.reset_index()partition1.columns = ['names','group']" }, { "code": null, "e": 10606, "s": 10525, "text": "We need to run the degree centrality code again now that our network is smaller." }, { "code": null, "e": 10751, "s": 10606, "text": "G_sorted = pd.DataFrame(sorted(G_tmp.degree, key=lambda x: x[1], reverse=True))G_sorted.columns = ['names','degree']G_sorted.head()dc = G_sorted" }, { "code": null, "e": 10862, "s": 10751, "text": "Now that we have the nodes split into groups and the degree of each node, we combine these into one DataFrame." }, { "code": null, "e": 10943, "s": 10862, "text": "combined = pd.merge(dc,partition1, how='left', left_on=\"names\",right_on=\"names\")" }, { "code": null, "e": 10995, "s": 10943, "text": "Now your DataFrame should look something like this." }, { "code": null, "e": 11053, "s": 10995, "text": "Now we can visualize this graph using the following code." }, { "code": null, "e": 11533, "s": 11053, "text": "pos = nx.spring_layout(G_tmp)f, ax = plt.subplots(figsize=(10, 10))plt.style.use('ggplot')#cc = nx.betweenness_centrality(G2)nodes = nx.draw_networkx_nodes(G_tmp, pos, cmap=plt.cm.Set1, node_color=combined['group'], alpha=0.8)nodes.set_edgecolor('k')nx.draw_networkx_labels(G_tmp, pos, font_size=8)nx.draw_networkx_edges(G_tmp, pos, width=1.0, alpha=0.2)plt.savefig('twitterFollowers.png')" }, { "code": null, "e": 11590, "s": 11533, "text": "This should create graph that looks something like this." }, { "code": null, "e": 12079, "s": 11590, "text": "What a mess. I’m sure there are ways to make that visual look better using matplotlib, but at this point, I always just export the files to csv format and use Gephi to visualize. Gephi is an open-source network analysis and visualization software. You should be able to easily install it for free from their website. It’s pretty easy to get started and allows for some really beautiful visualizations. If you have never used Gephi, here is a good tutorial to get started from Luca Hammer." }, { "code": null, "e": 12164, "s": 12079, "text": "To use Gephi, first you need to export the node list and the edge list as csv files." }, { "code": null, "e": 12395, "s": 12164, "text": "combined = combined.rename(columns={\"names\": \"Id\"}) #I've found Gephi really likes when your node column is called 'Id'edges = nx.to_pandas_edgelist(G_tmp)nodes = combined['Id']edges.to_csv(\"edges.csv\")combined.to_csv(\"nodes.csv\")" }, { "code": null, "e": 12546, "s": 12395, "text": "You can follow the Gephi tutorial I mentioned above to import these files into Gephi and start visualizing your network. Here is what mine looks like." } ]
Affinity Analysis (Market Basket Analysis) | by Eser Saygın | Towards Data Science
Have you ever wondered how often do you buy certain items together? Why do you buy some items together? How likely do you purchase an item along with another one? Why sugar placed near tea bags? Is there any relationship between these items? What is the main idea behind it? The answer to all those questions is Affinity Analysis (can also be referred to as Market Basket Analysis). The main idea behind this analysis is to achieve valuable insights by identifying which items are frequently purchased together. Affinity Analysis (or Market Basket Analysis) finds patterns to determine connections between purchases in order that stores can increase their cross-selling potential. Before we get into the detail, we’ll have to explain some terms. A market basket refers to a set of items that are commonly purchased and sold in an economic system. (Check out the image above to see the basic example of the market basket.) As everyone knows, an itemset is a set of items that consist of two or more items. (What a piece of exciting information, right? :P) Transactions are the main data source of Affinity Analysis. Stores or retailers gather tremendous transaction data by recording activities over time. Each transaction is associated with a unique transaction ID (TID), and it contains subsets of itemsets. Support simply emphasizes how popular an itemset is. Support, despite being simple, is an important metric in the Affinity Analysis that used to determine the strength of association between items. Take 5 transactions, for instance. If you purchase bread in 3 transactions, you can tell the support of bread is equal to 3/5. While the support emphasizes how popular an itemset is, confidence denotes the likelihood of certain items are purchased together. For instance, how likely butter is purchased when item bread is purchased. Confidence is typically notated as Bread ⇒ Butter (Proportion of transactions containing Bread that also contain Butter.) Confidence, as you can see above, is a probability and so its range is [0,1]. If the confidence of Bread ⇒ Butter is equal to 1, we can say every time a customer purchases bread, also purchases butter. Like confidence, the lift is notated as Bread ⇒ Butter. It says how likely Butter is purchased when Bread is purchased while controlling for how popular Butter is. Lift’s range is [0, +∞]. When lift equal to one, bread and butter are independent and, thus, no inferences can be made about butter when the bread is purchased. However, when the lift is greater than 1, it means that the butter is likely to be purchased together with bread. Wikipedia says “ conviction can be interpreted as the ratio of the expected frequency that X occurs without Y (that is to say, the frequency that the rule makes an incorrect prediction) if X and Y were independent divided by the observed frequency of incorrect predictions.” Conviction has the range [0,+∞] and the following form: So, let’s go over it to make sure you clearly understand what the terms mean. Step 1: Let’s create transaction data. Step 2: Let’s define a function. This function gives the values of support, confidence, lift and conviction. (By the way, you can determine more than two parameters.) frequency_items('bread','butter') 36% of transactions contain both bread and butter. Butter appears every time in transactions that contain bread only. Confidence = 1 indicates that butter is always purchased whenever bread is purchased. Lastly, the value of lift is greater than 1 and it means it is more likely bread and butter will be bought together than each individually. (Remember our dataset is pretty small. In practice, a rule needs the support of several hundred transactions.) The Apriori algorithm is a data mining technique for identifying the frequent itemsets and relevant association rules in the database. Support, confidence and lift are the three main components of the Apriori Algorithm. Let’s illustrate the apriori algorithm using an example: Step 1: In the first step, we will create a frequency table of items in the transactions. Let us set the minimum support to 2. As you notice, all the items have greater support than the minimum support (2). Step 2: In this step, we will make all the possible pairs of items. (Order doesn’t matter, i.e {Bread,Butter} = {Butter, Bread}) Again we need to compare these pairs with the minimum support(2). Repeat previous steps: Now analyze 3 item sets and calculate the frequency, and apply the threshold again. (Bread, Butter, Beer), (Bread, Butter, Toilet Paper)... As you notice the algorithm scans the database over and over again. Hence, overall performance reduces. I’m going to use Groceries Market Basket Dataset. (Kaggle Link) Loading data. Loading data. 2. Importing packages and data preprocessing (about mlxtend) 3. Converting to dataframe. 4. Calculating support. 5. Creating rules (Metric: Confidence) Antecedents ⇒ Consequents 6. Creating rules (Metric: Lift) Antecedents ⇒ Consequents 7. Scatter plot Scatter plots help us to evaluate general tendencies of rules between antecedents and consequents. In this post, we have had a glimpse into what Affinity Analysis is and how to implement it in python. Affinity Analysis or Market Basket Analysis is used to extract valuable insights from transaction data. It can be used to determine what products to discount. Also, it can increase sales and customer satisfaction. It is important to realize that there are many other areas in which it can be applied. You can find the mlxtend documentation here.
[ { "code": null, "e": 447, "s": 172, "text": "Have you ever wondered how often do you buy certain items together? Why do you buy some items together? How likely do you purchase an item along with another one? Why sugar placed near tea bags? Is there any relationship between these items? What is the main idea behind it?" }, { "code": null, "e": 684, "s": 447, "text": "The answer to all those questions is Affinity Analysis (can also be referred to as Market Basket Analysis). The main idea behind this analysis is to achieve valuable insights by identifying which items are frequently purchased together." }, { "code": null, "e": 853, "s": 684, "text": "Affinity Analysis (or Market Basket Analysis) finds patterns to determine connections between purchases in order that stores can increase their cross-selling potential." }, { "code": null, "e": 918, "s": 853, "text": "Before we get into the detail, we’ll have to explain some terms." }, { "code": null, "e": 1094, "s": 918, "text": "A market basket refers to a set of items that are commonly purchased and sold in an economic system. (Check out the image above to see the basic example of the market basket.)" }, { "code": null, "e": 1227, "s": 1094, "text": "As everyone knows, an itemset is a set of items that consist of two or more items. (What a piece of exciting information, right? :P)" }, { "code": null, "e": 1481, "s": 1227, "text": "Transactions are the main data source of Affinity Analysis. Stores or retailers gather tremendous transaction data by recording activities over time. Each transaction is associated with a unique transaction ID (TID), and it contains subsets of itemsets." }, { "code": null, "e": 1806, "s": 1481, "text": "Support simply emphasizes how popular an itemset is. Support, despite being simple, is an important metric in the Affinity Analysis that used to determine the strength of association between items. Take 5 transactions, for instance. If you purchase bread in 3 transactions, you can tell the support of bread is equal to 3/5." }, { "code": null, "e": 2134, "s": 1806, "text": "While the support emphasizes how popular an itemset is, confidence denotes the likelihood of certain items are purchased together. For instance, how likely butter is purchased when item bread is purchased. Confidence is typically notated as Bread ⇒ Butter (Proportion of transactions containing Bread that also contain Butter.)" }, { "code": null, "e": 2336, "s": 2134, "text": "Confidence, as you can see above, is a probability and so its range is [0,1]. If the confidence of Bread ⇒ Butter is equal to 1, we can say every time a customer purchases bread, also purchases butter." }, { "code": null, "e": 2500, "s": 2336, "text": "Like confidence, the lift is notated as Bread ⇒ Butter. It says how likely Butter is purchased when Bread is purchased while controlling for how popular Butter is." }, { "code": null, "e": 2775, "s": 2500, "text": "Lift’s range is [0, +∞]. When lift equal to one, bread and butter are independent and, thus, no inferences can be made about butter when the bread is purchased. However, when the lift is greater than 1, it means that the butter is likely to be purchased together with bread." }, { "code": null, "e": 3106, "s": 2775, "text": "Wikipedia says “ conviction can be interpreted as the ratio of the expected frequency that X occurs without Y (that is to say, the frequency that the rule makes an incorrect prediction) if X and Y were independent divided by the observed frequency of incorrect predictions.” Conviction has the range [0,+∞] and the following form:" }, { "code": null, "e": 3184, "s": 3106, "text": "So, let’s go over it to make sure you clearly understand what the terms mean." }, { "code": null, "e": 3192, "s": 3184, "text": "Step 1:" }, { "code": null, "e": 3223, "s": 3192, "text": "Let’s create transaction data." }, { "code": null, "e": 3231, "s": 3223, "text": "Step 2:" }, { "code": null, "e": 3256, "s": 3231, "text": "Let’s define a function." }, { "code": null, "e": 3390, "s": 3256, "text": "This function gives the values of support, confidence, lift and conviction. (By the way, you can determine more than two parameters.)" }, { "code": null, "e": 3424, "s": 3390, "text": "frequency_items('bread','butter')" }, { "code": null, "e": 3768, "s": 3424, "text": "36% of transactions contain both bread and butter. Butter appears every time in transactions that contain bread only. Confidence = 1 indicates that butter is always purchased whenever bread is purchased. Lastly, the value of lift is greater than 1 and it means it is more likely bread and butter will be bought together than each individually." }, { "code": null, "e": 3879, "s": 3768, "text": "(Remember our dataset is pretty small. In practice, a rule needs the support of several hundred transactions.)" }, { "code": null, "e": 4099, "s": 3879, "text": "The Apriori algorithm is a data mining technique for identifying the frequent itemsets and relevant association rules in the database. Support, confidence and lift are the three main components of the Apriori Algorithm." }, { "code": null, "e": 4156, "s": 4099, "text": "Let’s illustrate the apriori algorithm using an example:" }, { "code": null, "e": 4164, "s": 4156, "text": "Step 1:" }, { "code": null, "e": 4283, "s": 4164, "text": "In the first step, we will create a frequency table of items in the transactions. Let us set the minimum support to 2." }, { "code": null, "e": 4363, "s": 4283, "text": "As you notice, all the items have greater support than the minimum support (2)." }, { "code": null, "e": 4371, "s": 4363, "text": "Step 2:" }, { "code": null, "e": 4492, "s": 4371, "text": "In this step, we will make all the possible pairs of items. (Order doesn’t matter, i.e {Bread,Butter} = {Butter, Bread})" }, { "code": null, "e": 4558, "s": 4492, "text": "Again we need to compare these pairs with the minimum support(2)." }, { "code": null, "e": 4581, "s": 4558, "text": "Repeat previous steps:" }, { "code": null, "e": 4721, "s": 4581, "text": "Now analyze 3 item sets and calculate the frequency, and apply the threshold again. (Bread, Butter, Beer), (Bread, Butter, Toilet Paper)..." }, { "code": null, "e": 4825, "s": 4721, "text": "As you notice the algorithm scans the database over and over again. Hence, overall performance reduces." }, { "code": null, "e": 4889, "s": 4825, "text": "I’m going to use Groceries Market Basket Dataset. (Kaggle Link)" }, { "code": null, "e": 4903, "s": 4889, "text": "Loading data." }, { "code": null, "e": 4917, "s": 4903, "text": "Loading data." }, { "code": null, "e": 4978, "s": 4917, "text": "2. Importing packages and data preprocessing (about mlxtend)" }, { "code": null, "e": 5006, "s": 4978, "text": "3. Converting to dataframe." }, { "code": null, "e": 5030, "s": 5006, "text": "4. Calculating support." }, { "code": null, "e": 5095, "s": 5030, "text": "5. Creating rules (Metric: Confidence) Antecedents ⇒ Consequents" }, { "code": null, "e": 5154, "s": 5095, "text": "6. Creating rules (Metric: Lift) Antecedents ⇒ Consequents" }, { "code": null, "e": 5170, "s": 5154, "text": "7. Scatter plot" }, { "code": null, "e": 5269, "s": 5170, "text": "Scatter plots help us to evaluate general tendencies of rules between antecedents and consequents." }, { "code": null, "e": 5371, "s": 5269, "text": "In this post, we have had a glimpse into what Affinity Analysis is and how to implement it in python." }, { "code": null, "e": 5672, "s": 5371, "text": "Affinity Analysis or Market Basket Analysis is used to extract valuable insights from transaction data. It can be used to determine what products to discount. Also, it can increase sales and customer satisfaction. It is important to realize that there are many other areas in which it can be applied." } ]
Huang's Termination detection algorithm - GeeksforGeeks
30 Apr, 2019 Huang’s algorithm is an algorithm for detecting termination in a distributed system. The algorithm was proposed by Shing-Tsaan Huang in 1989 in the Journal of Computers. In a distributed system, a process is either in an active state or in an idle state at any given point of time. Termination occurs when all of the processes becomes idle and there are no any in transit(on its way to be delivered) computational message. Assumptions of the algorithm: One of the co-operating processes which monitors the computation is called the controlling agent. The initial weight of controlling agent is 1 All other processes are initially idle and have weight 0. The computation starts when the controlling agent send a computation message to one of the processes. The process become active on receiving a computation message. Computation message can be sent only by controlling agent or an active process. Control message is sent to controlling agent by an active process when they are becoming idle. The algorithm assigns a weight W (such that 0 < W < 1 ) to every active process and every in transit message. Notations used in the algorithm: B(DW): Computation message with weight DW C(DW): Control message with weight DW Algorithm: Rule to send B(DW) –Suppose Process P with weight W is sending B(DW) to process QSplit the weight of the process P into W1 and W2.Such thatW = W1 + W2 and W1 > 0, W2 > 0Set weight of the process P as W1 ( i.e W = W1 )Send B(W2) to process Q, here DW = W2.Note: Only the Controlling agent or any active process can send Computation message. Suppose Process P with weight W is sending B(DW) to process Q Split the weight of the process P into W1 and W2.Such thatW = W1 + W2 and W1 > 0, W2 > 0 W = W1 + W2 and W1 > 0, W2 > 0 Set weight of the process P as W1 ( i.e W = W1 ) Send B(W2) to process Q, here DW = W2. Note: Only the Controlling agent or any active process can send Computation message. On receiving B(DW) by process Q –Add the weight DW to the weight of process Q i.e for process Q, W = W + DWIf process Q was idle, it will become active on receiving B(DW). Add the weight DW to the weight of process Q i.e for process Q, W = W + DW If process Q was idle, it will become active on receiving B(DW). Rule to send C(DW) –Any active process having weight W can become idle by sending C(W) to controlling agentSend a control message C(W) to the controlling agent. Here DW = W.Set weight of the process as 0 i.e W = 0. (After this process will become idle.) Any active process having weight W can become idle by sending C(W) to controlling agent Send a control message C(W) to the controlling agent. Here DW = W. Set weight of the process as 0 i.e W = 0. (After this process will become idle.) On receiving C(DW) by controlling agent –Add the weight received through control message to the weight of controlling agent i.e W = W + DWAfter adding, if the weight of controlling agent becomes 1 then it can be conclude that the computation has terminated. Add the weight received through control message to the weight of controlling agent i.e W = W + DW After adding, if the weight of controlling agent becomes 1 then it can be conclude that the computation has terminated. Advantages of Huang’s Algorithm: The algorithm detects every true termination in finite time. Limitations of Huang’s Algorithm: The algorithm is unable to detect computation termination if a message is lost in transit. It also does not work when a process fails while in an active state. Distributed System Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments States of a Process in Operating Systems Introduction of Process Management Process Table and Process Control Block (PCB) Memory Management in Operating System Process Schedulers in Operating System Difference between Internal and External fragmentation Introduction of System Call Dining Philosopher Problem Using Semaphores Logical and Physical Address in Operating System Program for Least Recently Used (LRU) Page Replacement algorithm
[ { "code": null, "e": 24412, "s": 24384, "text": "\n30 Apr, 2019" }, { "code": null, "e": 24582, "s": 24412, "text": "Huang’s algorithm is an algorithm for detecting termination in a distributed system. The algorithm was proposed by Shing-Tsaan Huang in 1989 in the Journal of Computers." }, { "code": null, "e": 24835, "s": 24582, "text": "In a distributed system, a process is either in an active state or in an idle state at any given point of time. Termination occurs when all of the processes becomes idle and there are no any in transit(on its way to be delivered) computational message." }, { "code": null, "e": 24865, "s": 24835, "text": "Assumptions of the algorithm:" }, { "code": null, "e": 24963, "s": 24865, "text": "One of the co-operating processes which monitors the computation is called the controlling agent." }, { "code": null, "e": 25008, "s": 24963, "text": "The initial weight of controlling agent is 1" }, { "code": null, "e": 25066, "s": 25008, "text": "All other processes are initially idle and have weight 0." }, { "code": null, "e": 25168, "s": 25066, "text": "The computation starts when the controlling agent send a computation message to one of the processes." }, { "code": null, "e": 25230, "s": 25168, "text": "The process become active on receiving a computation message." }, { "code": null, "e": 25310, "s": 25230, "text": "Computation message can be sent only by controlling agent or an active process." }, { "code": null, "e": 25405, "s": 25310, "text": "Control message is sent to controlling agent by an active process when they are becoming idle." }, { "code": null, "e": 25515, "s": 25405, "text": "The algorithm assigns a weight W (such that 0 < W < 1 ) to every active process and every in transit message." }, { "code": null, "e": 25548, "s": 25515, "text": "Notations used in the algorithm:" }, { "code": null, "e": 25590, "s": 25548, "text": "B(DW): Computation message with weight DW" }, { "code": null, "e": 25628, "s": 25590, "text": "C(DW): Control message with weight DW" }, { "code": null, "e": 25639, "s": 25628, "text": "Algorithm:" }, { "code": null, "e": 25980, "s": 25639, "text": "Rule to send B(DW) –Suppose Process P with weight W is sending B(DW) to process QSplit the weight of the process P into W1 and W2.Such thatW = W1 + W2 and W1 > 0, W2 > 0Set weight of the process P as W1 ( i.e W = W1 )Send B(W2) to process Q, here DW = W2.Note: Only the Controlling agent or any active process can send Computation message." }, { "code": null, "e": 26042, "s": 25980, "text": "Suppose Process P with weight W is sending B(DW) to process Q" }, { "code": null, "e": 26132, "s": 26042, "text": "Split the weight of the process P into W1 and W2.Such thatW = W1 + W2 and W1 > 0, W2 > 0" }, { "code": null, "e": 26164, "s": 26132, "text": "W = W1 + W2 and W1 > 0, W2 > 0" }, { "code": null, "e": 26213, "s": 26164, "text": "Set weight of the process P as W1 ( i.e W = W1 )" }, { "code": null, "e": 26252, "s": 26213, "text": "Send B(W2) to process Q, here DW = W2." }, { "code": null, "e": 26337, "s": 26252, "text": "Note: Only the Controlling agent or any active process can send Computation message." }, { "code": null, "e": 26509, "s": 26337, "text": "On receiving B(DW) by process Q –Add the weight DW to the weight of process Q i.e for process Q, W = W + DWIf process Q was idle, it will become active on receiving B(DW)." }, { "code": null, "e": 26584, "s": 26509, "text": "Add the weight DW to the weight of process Q i.e for process Q, W = W + DW" }, { "code": null, "e": 26649, "s": 26584, "text": "If process Q was idle, it will become active on receiving B(DW)." }, { "code": null, "e": 26903, "s": 26649, "text": "Rule to send C(DW) –Any active process having weight W can become idle by sending C(W) to controlling agentSend a control message C(W) to the controlling agent. Here DW = W.Set weight of the process as 0 i.e W = 0. (After this process will become idle.)" }, { "code": null, "e": 26991, "s": 26903, "text": "Any active process having weight W can become idle by sending C(W) to controlling agent" }, { "code": null, "e": 27058, "s": 26991, "text": "Send a control message C(W) to the controlling agent. Here DW = W." }, { "code": null, "e": 27139, "s": 27058, "text": "Set weight of the process as 0 i.e W = 0. (After this process will become idle.)" }, { "code": null, "e": 27397, "s": 27139, "text": "On receiving C(DW) by controlling agent –Add the weight received through control message to the weight of controlling agent i.e W = W + DWAfter adding, if the weight of controlling agent becomes 1 then it can be conclude that the computation has terminated." }, { "code": null, "e": 27495, "s": 27397, "text": "Add the weight received through control message to the weight of controlling agent i.e W = W + DW" }, { "code": null, "e": 27615, "s": 27495, "text": "After adding, if the weight of controlling agent becomes 1 then it can be conclude that the computation has terminated." }, { "code": null, "e": 27648, "s": 27615, "text": "Advantages of Huang’s Algorithm:" }, { "code": null, "e": 27709, "s": 27648, "text": "The algorithm detects every true termination in finite time." }, { "code": null, "e": 27743, "s": 27709, "text": "Limitations of Huang’s Algorithm:" }, { "code": null, "e": 27834, "s": 27743, "text": "The algorithm is unable to detect computation termination if a message is lost in transit." }, { "code": null, "e": 27903, "s": 27834, "text": "It also does not work when a process fails while in an active state." }, { "code": null, "e": 27922, "s": 27903, "text": "Distributed System" }, { "code": null, "e": 27940, "s": 27922, "text": "Operating Systems" }, { "code": null, "e": 27958, "s": 27940, "text": "Operating Systems" }, { "code": null, "e": 28056, "s": 27958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28065, "s": 28056, "text": "Comments" }, { "code": null, "e": 28078, "s": 28065, "text": "Old Comments" }, { "code": null, "e": 28119, "s": 28078, "text": "States of a Process in Operating Systems" }, { "code": null, "e": 28154, "s": 28119, "text": "Introduction of Process Management" }, { "code": null, "e": 28200, "s": 28154, "text": "Process Table and Process Control Block (PCB)" }, { "code": null, "e": 28238, "s": 28200, "text": "Memory Management in Operating System" }, { "code": null, "e": 28277, "s": 28238, "text": "Process Schedulers in Operating System" }, { "code": null, "e": 28332, "s": 28277, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28360, "s": 28332, "text": "Introduction of System Call" }, { "code": null, "e": 28404, "s": 28360, "text": "Dining Philosopher Problem Using Semaphores" }, { "code": null, "e": 28453, "s": 28404, "text": "Logical and Physical Address in Operating System" } ]
Feature selection in machine learning using Lasso regression | by Gianluca Malato | Towards Data Science
The first thing I have learned as a data scientist is that feature selection is one of the most important steps of a machine learning pipeline. Fortunately, some models may help us accomplish this goal by giving us their own interpretation of feature importance. One of such models is the Lasso regression. I have already talked about Lasso regression in a previous blog post. Let me summarize the main properties of such a model. It is a linear model that uses this cost function: aj is the coefficient of the j-th feature. The final term is called l1 penalty and α is a hyperparameter that tunes the intensity of this penalty term. The higher the coefficient of a feature, the higher the value of the cost function. So, the idea of Lasso regression is to optimize the cost function reducing the absolute values of the coefficients. Obviously, this works if the features have been previously scaled, for example using standardization or other scaling techniques. α hyperparameter value must be found using a cross-validation approach. Trying to minimize the cost function, Lasso regression will automatically select those features that are useful, discarding the useless or redundant features. In Lasso regression, discarding a feature will make its coefficient equal to 0. So, the idea of using Lasso regression for feature selection purposes is very simple: we fit a Lasso regression on a scaled version of our dataset and we consider only those features that have a coefficient different from 0. Obviously, we first need to tune α hyperparameter in order to have the right kind of Lasso regression. That’s pretty easy and will make us easily detect the useful features and discard the useless features. Let’s see how to do it in Python. In this example, I’m going to show you how to use Lasso for feature selection in Python using the diabetes dataset. You can find the whole code in my GitHub repository. First, let’s import some libraries: import numpy as npfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import Pipelinefrom sklearn.model_selection import train_test_split, GridSearchCVfrom sklearn.linear_model import Lasso Then, we can import our dataset and the names of the features. from sklearn.datasets import load_diabetesX,y = load_diabetes(return_X_y=True)features = load_diabetes()['feature_names'] As always, we can now split our dataset into training and test sets and perform all the calculations on the training set only. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) Now we have to build our model, optimize its hyperparameter and train it on the training dataset. Since our dataset needs to be scaled in advance, we can make use of the powerful Pipeline object in scikit-learn. Our pipeline is made by a StandardScaler and the Lasso object itself. pipeline = Pipeline([ ('scaler',StandardScaler()), ('model',Lasso())]) Now we have to optimize the α hyperparameter of Lasso regression. For this example, we are going to test several values from 0.1 to 10 with 0.1 step. For each value, we calculate the average value of the mean squared error in a 5-folds cross-validation and select the value of α that minimizes such average performance metrics. We can use the GridSearchCV object for this purpose. search = GridSearchCV(pipeline, {'model__alpha':np.arange(0.1,10,0.1)}, cv = 5, scoring="neg_mean_squared_error",verbose=3 ) We use neg_mean_squared_error because the grid search tries to maximize the performance metrics, so we add a minus sign to minimize the mean squared error. We can now fit the grid search. search.fit(X_train,y_train) The best value for α is: search.best_params_# {'model__alpha': 1.2000000000000002} Now, we have to get the values of the coefficients of Lasso regression. coefficients = search.best_estimator_.named_steps['model'].coef_ The importance of a feature is the absolute value of its coefficient, so: importance = np.abs(coefficients) Let’s take a look at the importance: As we can see, there are 3 features with 0 importance. Those features have been discarded by our model. The features that survived the Lasso regression are: np.array(features)[importance > 0]# array(['age', 'sex', 'bmi', 'bp', 's1', 's3', 's5'], dtype='<U3') While the 3 discarded features are: np.array(features)[importance == 0]# array(['s2', 's4', 's6'], dtype='<U3') In this way, we have used a properly optimized Lasso regression to get information about the most important features of our dataset according to the given target variable. Lasso regression has a very powerful built-in feature selection capability that can be used in several situations. However, it has some drawbacks as well. For example, if the relationship between the features and the target variable is not linear, using a linear model might not be a good idea. As usual, a proper Exploratory Data Analysis can help us better understand the most important relationships between the features and the target, making us select the best model. If you want to learn more about Lasso Regression, join my Supervised Machine Learning in Python online course. Originally published at https://www.yourdatateacher.com on May 5, 2021.
[ { "code": null, "e": 478, "s": 171, "text": "The first thing I have learned as a data scientist is that feature selection is one of the most important steps of a machine learning pipeline. Fortunately, some models may help us accomplish this goal by giving us their own interpretation of feature importance. One of such models is the Lasso regression." }, { "code": null, "e": 653, "s": 478, "text": "I have already talked about Lasso regression in a previous blog post. Let me summarize the main properties of such a model. It is a linear model that uses this cost function:" }, { "code": null, "e": 1207, "s": 653, "text": "aj is the coefficient of the j-th feature. The final term is called l1 penalty and α is a hyperparameter that tunes the intensity of this penalty term. The higher the coefficient of a feature, the higher the value of the cost function. So, the idea of Lasso regression is to optimize the cost function reducing the absolute values of the coefficients. Obviously, this works if the features have been previously scaled, for example using standardization or other scaling techniques. α hyperparameter value must be found using a cross-validation approach." }, { "code": null, "e": 1446, "s": 1207, "text": "Trying to minimize the cost function, Lasso regression will automatically select those features that are useful, discarding the useless or redundant features. In Lasso regression, discarding a feature will make its coefficient equal to 0." }, { "code": null, "e": 1774, "s": 1446, "text": "So, the idea of using Lasso regression for feature selection purposes is very simple: we fit a Lasso regression on a scaled version of our dataset and we consider only those features that have a coefficient different from 0. Obviously, we first need to tune α hyperparameter in order to have the right kind of Lasso regression." }, { "code": null, "e": 1878, "s": 1774, "text": "That’s pretty easy and will make us easily detect the useful features and discard the useless features." }, { "code": null, "e": 1912, "s": 1878, "text": "Let’s see how to do it in Python." }, { "code": null, "e": 2081, "s": 1912, "text": "In this example, I’m going to show you how to use Lasso for feature selection in Python using the diabetes dataset. You can find the whole code in my GitHub repository." }, { "code": null, "e": 2117, "s": 2081, "text": "First, let’s import some libraries:" }, { "code": null, "e": 2325, "s": 2117, "text": "import numpy as npfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import Pipelinefrom sklearn.model_selection import train_test_split, GridSearchCVfrom sklearn.linear_model import Lasso" }, { "code": null, "e": 2388, "s": 2325, "text": "Then, we can import our dataset and the names of the features." }, { "code": null, "e": 2510, "s": 2388, "text": "from sklearn.datasets import load_diabetesX,y = load_diabetes(return_X_y=True)features = load_diabetes()['feature_names']" }, { "code": null, "e": 2637, "s": 2510, "text": "As always, we can now split our dataset into training and test sets and perform all the calculations on the training set only." }, { "code": null, "e": 2728, "s": 2637, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)" }, { "code": null, "e": 2826, "s": 2728, "text": "Now we have to build our model, optimize its hyperparameter and train it on the training dataset." }, { "code": null, "e": 3010, "s": 2826, "text": "Since our dataset needs to be scaled in advance, we can make use of the powerful Pipeline object in scikit-learn. Our pipeline is made by a StandardScaler and the Lasso object itself." }, { "code": null, "e": 3121, "s": 3010, "text": "pipeline = Pipeline([ ('scaler',StandardScaler()), ('model',Lasso())])" }, { "code": null, "e": 3502, "s": 3121, "text": "Now we have to optimize the α hyperparameter of Lasso regression. For this example, we are going to test several values from 0.1 to 10 with 0.1 step. For each value, we calculate the average value of the mean squared error in a 5-folds cross-validation and select the value of α that minimizes such average performance metrics. We can use the GridSearchCV object for this purpose." }, { "code": null, "e": 3690, "s": 3502, "text": "search = GridSearchCV(pipeline, {'model__alpha':np.arange(0.1,10,0.1)}, cv = 5, scoring=\"neg_mean_squared_error\",verbose=3 )" }, { "code": null, "e": 3846, "s": 3690, "text": "We use neg_mean_squared_error because the grid search tries to maximize the performance metrics, so we add a minus sign to minimize the mean squared error." }, { "code": null, "e": 3878, "s": 3846, "text": "We can now fit the grid search." }, { "code": null, "e": 3906, "s": 3878, "text": "search.fit(X_train,y_train)" }, { "code": null, "e": 3931, "s": 3906, "text": "The best value for α is:" }, { "code": null, "e": 3989, "s": 3931, "text": "search.best_params_# {'model__alpha': 1.2000000000000002}" }, { "code": null, "e": 4061, "s": 3989, "text": "Now, we have to get the values of the coefficients of Lasso regression." }, { "code": null, "e": 4126, "s": 4061, "text": "coefficients = search.best_estimator_.named_steps['model'].coef_" }, { "code": null, "e": 4200, "s": 4126, "text": "The importance of a feature is the absolute value of its coefficient, so:" }, { "code": null, "e": 4234, "s": 4200, "text": "importance = np.abs(coefficients)" }, { "code": null, "e": 4271, "s": 4234, "text": "Let’s take a look at the importance:" }, { "code": null, "e": 4375, "s": 4271, "text": "As we can see, there are 3 features with 0 importance. Those features have been discarded by our model." }, { "code": null, "e": 4428, "s": 4375, "text": "The features that survived the Lasso regression are:" }, { "code": null, "e": 4530, "s": 4428, "text": "np.array(features)[importance > 0]# array(['age', 'sex', 'bmi', 'bp', 's1', 's3', 's5'], dtype='<U3')" }, { "code": null, "e": 4566, "s": 4530, "text": "While the 3 discarded features are:" }, { "code": null, "e": 4642, "s": 4566, "text": "np.array(features)[importance == 0]# array(['s2', 's4', 's6'], dtype='<U3')" }, { "code": null, "e": 4814, "s": 4642, "text": "In this way, we have used a properly optimized Lasso regression to get information about the most important features of our dataset according to the given target variable." }, { "code": null, "e": 5287, "s": 4814, "text": "Lasso regression has a very powerful built-in feature selection capability that can be used in several situations. However, it has some drawbacks as well. For example, if the relationship between the features and the target variable is not linear, using a linear model might not be a good idea. As usual, a proper Exploratory Data Analysis can help us better understand the most important relationships between the features and the target, making us select the best model." }, { "code": null, "e": 5398, "s": 5287, "text": "If you want to learn more about Lasso Regression, join my Supervised Machine Learning in Python online course." } ]
CSS Buttons - bttn.css Usage
bttn.css library provides a huge collection of simple styles for buttons. This library is completely free for both personal and commercial use. These buttons can be customized easily. To load the btns.css library, go to the link btns.css and paste the following line in the <head> section of the webpage. <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css"> </head> Create a button using html button tag and add styles bttn-slant, bttn-royal with size specifier bttn-lg. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css"> </head> <body> <button class = "bttn-slant">Submit</button> </body> </html> It will produce the following output − You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css"> </head> <body> <button class = "bttn-pill bttn-lg">Large</button> <button class = "bttn-pill bttn-md">Medium</button> <button class = "bttn-pill bttn-sm">Small</button> <button class = "bttn-pill bttn-xs">Extra Small</button> </body> </html> It will produce the following output − Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css"> </head> <body> <button class = "bttn-pill bttn-lg bttn-primary">Primary</button> <button class = "bttn-pill bttn-md bttn-warning">Warning</button> <button class = "bttn-pill bttn-sm bttn-danger">Danger</button> <button class = "bttn-pill bttn-xs bttn-success">Success</button> <button class = "bttn-pill bttn-xs bttn-royal">Royal</button> </body> </html> It will produce the following output − 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2082, "s": 1898, "text": "bttn.css library provides a huge collection of simple styles for buttons. This library is completely free for both personal and commercial use. These buttons can be customized easily." }, { "code": null, "e": 2203, "s": 2082, "text": "To load the btns.css library, go to the link btns.css and paste the following line in the <head> section of the webpage." }, { "code": null, "e": 2320, "s": 2203, "text": "<head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css\">\n</head>\n" }, { "code": null, "e": 2425, "s": 2320, "text": "Create a button using html button tag and add styles bttn-slant, bttn-royal with size specifier bttn-lg." }, { "code": null, "e": 2641, "s": 2425, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css\">\n </head>\n \n <body>\n <button class = \"bttn-slant\">Submit</button>\n </body>\n</html>" }, { "code": null, "e": 2680, "s": 2641, "text": "It will produce the following output −" }, { "code": null, "e": 2868, "s": 2680, "text": "You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes." }, { "code": null, "e": 3268, "s": 2868, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css\">\n </head>\n \n <body>\n <button class = \"bttn-pill bttn-lg\">Large</button>\n <button class = \"bttn-pill bttn-md\">Medium</button>\n <button class = \"bttn-pill bttn-sm\">Small</button>\n <button class = \"bttn-pill bttn-xs\">Extra Small</button>\n </body>\n</html>" }, { "code": null, "e": 3307, "s": 3268, "text": "It will produce the following output −" }, { "code": null, "e": 3440, "s": 3307, "text": "Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button." }, { "code": null, "e": 3959, "s": 3440, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css\">\n </head>\n \n <body>\n <button class = \"bttn-pill bttn-lg bttn-primary\">Primary</button>\n <button class = \"bttn-pill bttn-md bttn-warning\">Warning</button>\n <button class = \"bttn-pill bttn-sm bttn-danger\">Danger</button>\n <button class = \"bttn-pill bttn-xs bttn-success\">Success</button>\n <button class = \"bttn-pill bttn-xs bttn-royal\">Royal</button>\n </body>\n</html>" }, { "code": null, "e": 3998, "s": 3959, "text": "It will produce the following output −" }, { "code": null, "e": 4033, "s": 3998, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4047, "s": 4033, "text": " Anadi Sharma" }, { "code": null, "e": 4082, "s": 4047, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4099, "s": 4082, "text": " Frahaan Hussain" }, { "code": null, "e": 4134, "s": 4099, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4165, "s": 4134, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4200, "s": 4165, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4231, "s": 4200, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4266, "s": 4231, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4297, "s": 4266, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4330, "s": 4297, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 4361, "s": 4330, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4368, "s": 4361, "text": " Print" }, { "code": null, "e": 4379, "s": 4368, "text": " Add Notes" } ]
Pascal - Multi-dimensional Array
Pascal programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration − type array-identifier = array [index-type1, index-type2, ...] of element-type; var a1, a2, ... : array-identifier; For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array − var threedim: array[1..5, 1..10, 1..4] of integer; The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x, y you would write something as follows − var arrayName: array[1..x, 1..y] of element-type; Where element-type can be any valid Pascal data type and arrayName will be a valid Pascal identifier. A two-dimensional array can be visualized as a table, which will have x number of rows and y number of columns. A 2-dimensional array that contains three rows and four columns can be shown as below − Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a. Multidimensional arrays, like one-dimensional array, are initialized by through assignment, either by specifying a particular subscript or using a for-do loop. For example, var a: array [0..3, 0..3] of integer; i, j : integer; begin for i:= 0 to 3 do for j:= 0 to 3 do a[i,j]:= i * j; ... end; An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example − var val: integer; val := a[2, 3]; The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two-dimensional array − program ex2dimarray; var a: array [0..3, 0..3] of integer; i,j : integer; begin for i:=0 to 3 do for j:=0 to 3 do a[i,j]:= i * j; for i:=0 to 3 do begin for j:=0 to 3 do write(a[i,j]:2,' '); writeln; end; end. When the above code is compiled and executed, it produces the following result − 0 0 0 0 0 1 2 3 0 2 4 6 0 3 6 9 As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions. 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2210, "s": 2083, "text": "Pascal programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −" }, { "code": null, "e": 2332, "s": 2210, "text": "type \n array-identifier = array [index-type1, index-type2, ...] of element-type;\nvar\n a1, a2, ... : array-identifier;" }, { "code": null, "e": 2426, "s": 2332, "text": "For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −" }, { "code": null, "e": 2480, "s": 2426, "text": "var\n threedim: array[1..5, 1..10, 1..4] of integer;" }, { "code": null, "e": 2727, "s": 2480, "text": "The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x, y you would write something as follows −" }, { "code": null, "e": 2780, "s": 2727, "text": "var\n arrayName: array[1..x, 1..y] of element-type;" }, { "code": null, "e": 3082, "s": 2780, "text": "Where element-type can be any valid Pascal data type and arrayName will be a valid Pascal identifier. A two-dimensional array can be visualized as a table, which will have x number of rows and y number of columns. A 2-dimensional array that contains three rows and four columns can be shown as below −" }, { "code": null, "e": 3278, "s": 3082, "text": "Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a." }, { "code": null, "e": 3438, "s": 3278, "text": "Multidimensional arrays, like one-dimensional array, are initialized by through assignment, either by specifying a particular subscript or using a for-do loop." }, { "code": null, "e": 3451, "s": 3438, "text": "For example," }, { "code": null, "e": 3610, "s": 3451, "text": "var\n a: array [0..3, 0..3] of integer;\n i, j : integer;\n\nbegin \n for i:= 0 to 3 do \n for j:= 0 to 3 do \n a[i,j]:= i * j; \n ...\nend; " }, { "code": null, "e": 3742, "s": 3610, "text": "An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −" }, { "code": null, "e": 3782, "s": 3742, "text": "var\n val: integer;\n val := a[2, 3];" }, { "code": null, "e": 3989, "s": 3782, "text": "The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two-dimensional array −" }, { "code": null, "e": 4275, "s": 3989, "text": "program ex2dimarray;\nvar \n a: array [0..3, 0..3] of integer;\n i,j : integer; \n\nbegin \n for i:=0 to 3 do\n for j:=0 to 3 do\n a[i,j]:= i * j; \n \n for i:=0 to 3 do\n begin \n for j:=0 to 3 do \n write(a[i,j]:2,' '); \n writeln; \n end; \nend." }, { "code": null, "e": 4356, "s": 4275, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4389, "s": 4356, "text": "0 0 0 0\n0 1 2 3\n0 2 4 6\n0 3 6 9\n" }, { "code": null, "e": 4551, "s": 4389, "text": "As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions." }, { "code": null, "e": 4586, "s": 4551, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4609, "s": 4586, "text": " Stone River ELearning" }, { "code": null, "e": 4616, "s": 4609, "text": " Print" }, { "code": null, "e": 4627, "s": 4616, "text": " Add Notes" } ]
C library function - gets()
The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first. Following is the declaration for gets() function. char *gets(char *str) str − This is the pointer to an array of chars where the C string is stored. str − This is the pointer to an array of chars where the C string is stored. This function returns str on success, and NULL on error or when end of file occurs, while no characters have been read. The following example shows the usage of gets() function. #include <stdio.h> int main () { char str[50]; printf("Enter a string : "); gets(str); printf("You entered: %s", str); return(0); } Let us compile and run the above program that will produce the following result − Enter a string : tutorialspoint.com You entered: tutorialspoint.com 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": 2235, "s": 2007, "text": "The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first." }, { "code": null, "e": 2285, "s": 2235, "text": "Following is the declaration for gets() function." }, { "code": null, "e": 2307, "s": 2285, "text": "char *gets(char *str)" }, { "code": null, "e": 2384, "s": 2307, "text": "str − This is the pointer to an array of chars where the C string is stored." }, { "code": null, "e": 2461, "s": 2384, "text": "str − This is the pointer to an array of chars where the C string is stored." }, { "code": null, "e": 2581, "s": 2461, "text": "This function returns str on success, and NULL on error or when end of file occurs, while no characters have been read." }, { "code": null, "e": 2639, "s": 2581, "text": "The following example shows the usage of gets() function." }, { "code": null, "e": 2790, "s": 2639, "text": "#include <stdio.h>\n\nint main () {\n char str[50];\n\n printf(\"Enter a string : \");\n gets(str);\n\n printf(\"You entered: %s\", str);\n\n return(0);\n}" }, { "code": null, "e": 2872, "s": 2790, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2941, "s": 2872, "text": "Enter a string : tutorialspoint.com\nYou entered: tutorialspoint.com\n" }, { "code": null, "e": 2974, "s": 2941, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2989, "s": 2974, "text": " Nishant Malik" }, { "code": null, "e": 3024, "s": 2989, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3039, "s": 3024, "text": " Nishant Malik" }, { "code": null, "e": 3074, "s": 3039, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3088, "s": 3074, "text": " Asif Hussain" }, { "code": null, "e": 3121, "s": 3088, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3139, "s": 3121, "text": " Richa Maheshwari" }, { "code": null, "e": 3174, "s": 3139, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3193, "s": 3174, "text": " Vandana Annavaram" }, { "code": null, "e": 3226, "s": 3193, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3238, "s": 3226, "text": " Amit Diwan" }, { "code": null, "e": 3245, "s": 3238, "text": " Print" }, { "code": null, "e": 3256, "s": 3245, "text": " Add Notes" } ]
Data scientist’s guide to efficient coding in Python | by Dr. Varshita Sher | Towards Data Science
In this article, I wanted to share a few tips for writing cleaner codes that I have absorbed in the last year — mainly from pair programming. Generally speaking, including them as part of my everyday coding routine has helped me generate supreme quality Python scripts, that are easily maintainable and scalable over time. Ever thought why senior developer’s code look so much better in comparison to a junior developer. Read on to bridge the gap.... Rather than giving generic examples on how to use these techniques, I will be giving real-life coding scenarios where I have actually used them! Here is the Jupyter Colab Notebook if you’d like to follow along! Imagine looping over a large iterable (list, dictionary, tuple, set), and not knowing whether the code has finished running! Bummer, right! In such scenarios make sure to use tqdm construct to display a progress bar alongside. For instance, to display the progress as I read through all the files present in 44 different directories (whose paths I have already stored in a list called fpaths): from tqdm import tqdmfiles = list()fpaths = ["dir1/subdir1", "dir2/subdir3", ......]for fpath in tqdm(fpaths, desc="Looping over fpaths")): files.extend(os.listdir(fpath)) Note: Use the desc argument to specify a small description for the loop. In simple terms, it means explicitly stating the type of all the arguments in your Python function definition. I wish there were specific use cases I could provide to emphasize when I use type hinting for my work, but the truth is, I use them more often than not. Here’s a hypothetical example of a function update_df(). It updates a given data frame by appending a row containing useful information from a simulation run — such as classifier used, accuracy scored, train-test split size, and additional remarks for that particular run. def update_df(df: pd.DataFrame, clf: str, acc: float, split:float = 0.5, remarks: List[str] = [] ) -> pd.DataFrame: new_row = {'Classifier':clf, 'Accuracy':acc, 'split_size':split, 'Remarks':remarks} df = df.append(new_row, ignore_index=True) return df Few things to note: The datatype following the -> symbol in the function definition (def update_df(.......) -> pd.DataFrame) indicates the type of the value returned by the functions, i.e. a Pandas’s dataframe in this case. The default value, if any, can be specified as usual in the form param:type = value . (For example: split: float = 0.5) In case a function does not return anything, feel free to use None. For example : def func(a: str, b: int) -> None: print(a,b) To return values of mixed types, for example, say a function could either print a statement if a flag optionwas set OR return an intif the flag was not set: from typing import Uniondef dummy_args(*args: list[int], option = True) -> Union[None, int]: if option: print(args) else: return 10 Note: As of Python 3.10, Union is not required, so you can simply do: def dummy_args(*args: list[int], option = True) -> None | int: if option: print(args) else: return 10 You can go as specific as you’d like while defining the types of parameters, as we have done for remarks: List[str]. Not only do we specify it should be a List, but it should be a list of str only. For fun, try passing a list of integers to remarkswhile calling the function. You’ll see no error returned! Why is that? Because Python interpreter doesn’t enforce any type checking based on your type-hints. Type-hints have no impact on your code other than adding documentation. It’s still good practice, though, to include it! I feel it lends more clarity to oneself when writing a function. In addition, when someone makes a call to such a function, they get to see nice prompts for the arguments it would take as inputs. Imagine this: you want to write a function that takes as input some directory paths and prints the number of files within each. The problem is, we do not know how many paths the user would input! Could be 2 could be 20! So we are unsure how many parameters should we define in our function definition. Clearly, writing a function like def count_files(file1, file2, file3, .....file20)would be silly. In such cases, args and (sometimes kwargs) come handy! Args is used for specifying an unknown number of positional arguments.Kwargs is used for specifying an unknown number of keyword arguments. Here’s an example of a function count_files_in_dir()that takes in project_root_dir and an arbitrary number of folder paths within it (using *fpaths in the function definition). As an output, it prints the number of files within each of these folders. def count_files_in_dir(project_root_dir, *fpaths: str): for path in fpaths: rel_path = os.path.join(project_root_dir, path) print(path, ":", len(os.listdir(rel_path))) In the function call, we pass in 5 arguments. As the function definition expects one required positional arguments i.e. project_root_dir, it automatically knows "../usr" must be it. All the remaining arguments (four in this case) are “soaked up” by *fpathsand are used for counting the files. Note: The proper terminology for this soaking up technique is “argument packing” i.e. remaining arguments are packed into *fpaths. Let’s look at functions that must take an unknown number of keyword arguments. In such scenarios, we must use kwargs instead of args. Here’s a short (useless) example: def print_results(**results): for key, val in results.items(): print(key, val) The usage is quite similar to *args but now we are able to pass an arbitrary number of keyword arguments to a function. These arguments get stored as key-value pairs in **resultsdictionary. From hereon, it is easy to access the items within this dictionary using .items(). I have found two main applications for kwargs in my work: merging dictionaries (useful but less interesting) dict1 = {'a':2 , 'b': 20}dict2 = {'c':15 , 'd': 40}merged_dict = {**dict1, **dict2}*************************{'a': 2, 'b': 20, 'c': 15, 'd': 40} extending an existing method (more interesting) def myfunc(a, b, flag, **kwargs): if flag: a, b = do_some_computation(a,b) actual_function(a,b, **kwargs) Note: Checkout matplotlib’s plot function using kwargs to specify optional embellishments for a plot such as linewidth and label. Here’s a real practical use-case for extending methods using **kwargs from one of my recent projects:We often use Sklearn’s train_test_split() for splitting X and y. While working on one of the GANs projects, I had to split the generated synthetic images into the same train-test split that is used for splitting real images and their respective labels. In addition, I also wanted to be able to pass any other arguments that one would normally pass to the train_test_split(). Finally, stratify must always be passed because I was working on a face recognition problem (and wanted all labels to be present in both train and test set). To achieve this, we created a function called custom_train_test_split(). I’ve included a bunch of print statements to show what exactly is happening under the hood (and omitted some snippets for brevity). def custom_train_test_split(clf, y, *X, stratify, **split_args): print("Classifier used: ", classifier) print("Keys:", split_args.keys()) print("Values: ", split_args.values()) print(X) print(y) print("Length of passed keyword arguments: ", len(split_args)) trainx,testx,*synthetic,trainy,testy = train_test_split( *X, y, stratify=stratify, **split_args ) ######### OMITTED CODE SNIPPET ############# # Train classifier on train and synthetic ims # Calculate accuracy on testx, testy ############################################ print("trainx: ", trainx, "trainy: ",trainy, '\n', "testx: ", testx, "testy:", testy) print("synthetic: ", *synthetic) Note: While calling this function, instead of using the actual image vectors and labels (see figure below), I have replaced them with dummy data for ease of understanding. The code, however, should work for real images as well! Bunch of things to note: All the keyword arguments (except stratify), used in the function call statement (such as train_size and random_state) will be stored as a key-value pair in the **split_args dictionary. (To verify, check out the output in Blue.)Why not stratify, you might ask? This is because according to the function definition, it is a required keyword-only argument and not an optional one. All the non-keyword (i.e. positional) arguments passed in the function call (such as "SVM", labels, etc.) would be stored in the first three parameters in function definition i.e.clf, y and *X, (and yes the order in which they are passed matters). However, we have four arguments in function call i.e. "SVM", labels, ims , and synthetic_ims. Where do we store the fourth one?Remember that we used *X as the third parameter in the function definition, hence all arguments passed to the function after the first two arguments are packed (soaked) into *X. (To verify, check output in Green). When calling train_test_split() method within our function, we are essentially unpacking the X and split_args arguments using the * operator,(*X and **split_args), so that all elements of it can be passed as different parameters. That is, train_test_split(*X, y, stratify = stratify, **split_args) is equivalent to writing train_test_split(ims, synthetic_ims, y, stratify = stratify, train_size = 0.6, random_state = 50) When storing the results from the train_test_split() method, we again pack the synthetic_train and synthetic_test sets into a single *synthetic variable. To check what’s inside it, we can unpack it again using * operator (see the output in Pink). Note: For those of you who’d like a deep dive into packing & unpacking using * operator, do check out this article. The code we write is often messy and lacks proper formatting such as trailing whitespaces, trailing commas, unsorted import statements, spaces in indentation, etc. While it is possible to fix all this manually, you will be saving yourself a great deal of time with pre-commit hooks. In simpler terms, these hooks can perform auto-formatting for you with one line of command — pre-commit run. Here are some simple steps from the official documentation to get started and create a .pre-commit-config.yaml file. It will contain hooks for all the formatting issues that you care about! As a purely personal preference, I tend to keep my .pre-commit-config.yaml configuration file simple and stick with Black’s pre-commit configuration. Note: One thing to remember is that files must be staged i.e. git add . before you do pre-commit run , otherwise, you’ll see all the files will be Skipped : If your project contains a lot of config variables such as database hostname, passwords, AWS credentials, etc. use a .yml file to keep track of all of them. You can later use this file in any Jupyter Notebook or script that you wish. Given most of my work is aimed at providing a model framework to clients so they can train it again on their own dataset, I usually use config files for storing paths to folders and files. It is also a nice way to make sure the client has to make changes to only one file when running your script at their end. Let’s go ahead and create a fpaths.yml file in the project directory. We will be storing the root directory where images must be stored. Additionally, the paths to the file names, labels, attributes, etc. Finally, we also store the paths to synthetic images. image_data_dir: path/to/img/dir# the following paths are relative to images_data_dirfnames: fnames_fname: fnames.txt fnames_label: labels.txt fnames_attr: attr.txtsynthetic: edit_method: interface_edits expression: smile.pkl pose: pose.pkl You can read this file like: # open the yml filewith open(CONFIG_FPATH) as f: dictionary = yaml.safe_load(f)# print elements in dictionaryfor key, value in dictionary.items(): print(key + " : " + str(value)) print() Note: If you’d like to dig deeper, here’s a brilliant tutorial to get you started with yaml. While there are certainly many nice choices for Python editors, I must say VSCode is hands-down the best I have seen so far (sorry, Pycharm). To get even more use of it, consider installing these extensions from the marketplace: Bracket Pair Colorizer — allows matching brackets to be identified with colors. Path Intellisense — allows autocompleting filenames. Python Dockstring generator — allows generating docstrings for Python functions. Pro-tip: Generate the docstring (using """) after you’ve written the function using type hinting. This way, the docstring generated will be even richer in information such as default value, argument types, etc. (See image on right above). Python Indent — (my favorite; published by by Kevin Rose) allows proper indentation of code/brackets that runs on multiple lines. Python Type Hint — allows auto-completion for type hints when writing functions. TODO tree: (second favorite) keeps track of ALL the TODO's at one place that were inserted while writing scripts. Pylance — allows code completion, parameter suggestions (and a loootttt more for writing code faster). Congrats on being one step closer to a professional Python developer. I intend to keep updating this article as and when I learn more cool tricks. As always, if there’s an easier way to do some of the things I mentioned in this article, please do let me know. Until next time :)
[ { "code": null, "e": 495, "s": 172, "text": "In this article, I wanted to share a few tips for writing cleaner codes that I have absorbed in the last year — mainly from pair programming. Generally speaking, including them as part of my everyday coding routine has helped me generate supreme quality Python scripts, that are easily maintainable and scalable over time." }, { "code": null, "e": 623, "s": 495, "text": "Ever thought why senior developer’s code look so much better in comparison to a junior developer. Read on to bridge the gap...." }, { "code": null, "e": 834, "s": 623, "text": "Rather than giving generic examples on how to use these techniques, I will be giving real-life coding scenarios where I have actually used them! Here is the Jupyter Colab Notebook if you’d like to follow along!" }, { "code": null, "e": 1061, "s": 834, "text": "Imagine looping over a large iterable (list, dictionary, tuple, set), and not knowing whether the code has finished running! Bummer, right! In such scenarios make sure to use tqdm construct to display a progress bar alongside." }, { "code": null, "e": 1228, "s": 1061, "text": "For instance, to display the progress as I read through all the files present in 44 different directories (whose paths I have already stored in a list called fpaths):" }, { "code": null, "e": 1408, "s": 1228, "text": "from tqdm import tqdmfiles = list()fpaths = [\"dir1/subdir1\", \"dir2/subdir3\", ......]for fpath in tqdm(fpaths, desc=\"Looping over fpaths\")): files.extend(os.listdir(fpath))" }, { "code": null, "e": 1481, "s": 1408, "text": "Note: Use the desc argument to specify a small description for the loop." }, { "code": null, "e": 1592, "s": 1481, "text": "In simple terms, it means explicitly stating the type of all the arguments in your Python function definition." }, { "code": null, "e": 1745, "s": 1592, "text": "I wish there were specific use cases I could provide to emphasize when I use type hinting for my work, but the truth is, I use them more often than not." }, { "code": null, "e": 2018, "s": 1745, "text": "Here’s a hypothetical example of a function update_df(). It updates a given data frame by appending a row containing useful information from a simulation run — such as classifier used, accuracy scored, train-test split size, and additional remarks for that particular run." }, { "code": null, "e": 2391, "s": 2018, "text": "def update_df(df: pd.DataFrame, clf: str, acc: float, split:float = 0.5, remarks: List[str] = [] ) -> pd.DataFrame: new_row = {'Classifier':clf, 'Accuracy':acc, 'split_size':split, 'Remarks':remarks} df = df.append(new_row, ignore_index=True) return df" }, { "code": null, "e": 2411, "s": 2391, "text": "Few things to note:" }, { "code": null, "e": 2615, "s": 2411, "text": "The datatype following the -> symbol in the function definition (def update_df(.......) -> pd.DataFrame) indicates the type of the value returned by the functions, i.e. a Pandas’s dataframe in this case." }, { "code": null, "e": 2735, "s": 2615, "text": "The default value, if any, can be specified as usual in the form param:type = value . (For example: split: float = 0.5)" }, { "code": null, "e": 2862, "s": 2735, "text": "In case a function does not return anything, feel free to use None. For example : def func(a: str, b: int) -> None: print(a,b)" }, { "code": null, "e": 3019, "s": 2862, "text": "To return values of mixed types, for example, say a function could either print a statement if a flag optionwas set OR return an intif the flag was not set:" }, { "code": null, "e": 3177, "s": 3019, "text": "from typing import Uniondef dummy_args(*args: list[int], option = True) -> Union[None, int]: if option: print(args) else: return 10" }, { "code": null, "e": 3247, "s": 3177, "text": "Note: As of Python 3.10, Union is not required, so you can simply do:" }, { "code": null, "e": 3375, "s": 3247, "text": "def dummy_args(*args: list[int], option = True) -> None | int: if option: print(args) else: return 10" }, { "code": null, "e": 3781, "s": 3375, "text": "You can go as specific as you’d like while defining the types of parameters, as we have done for remarks: List[str]. Not only do we specify it should be a List, but it should be a list of str only. For fun, try passing a list of integers to remarkswhile calling the function. You’ll see no error returned! Why is that? Because Python interpreter doesn’t enforce any type checking based on your type-hints." }, { "code": null, "e": 3853, "s": 3781, "text": "Type-hints have no impact on your code other than adding documentation." }, { "code": null, "e": 4098, "s": 3853, "text": "It’s still good practice, though, to include it! I feel it lends more clarity to oneself when writing a function. In addition, when someone makes a call to such a function, they get to see nice prompts for the arguments it would take as inputs." }, { "code": null, "e": 4553, "s": 4098, "text": "Imagine this: you want to write a function that takes as input some directory paths and prints the number of files within each. The problem is, we do not know how many paths the user would input! Could be 2 could be 20! So we are unsure how many parameters should we define in our function definition. Clearly, writing a function like def count_files(file1, file2, file3, .....file20)would be silly. In such cases, args and (sometimes kwargs) come handy!" }, { "code": null, "e": 4693, "s": 4553, "text": "Args is used for specifying an unknown number of positional arguments.Kwargs is used for specifying an unknown number of keyword arguments." }, { "code": null, "e": 4944, "s": 4693, "text": "Here’s an example of a function count_files_in_dir()that takes in project_root_dir and an arbitrary number of folder paths within it (using *fpaths in the function definition). As an output, it prints the number of files within each of these folders." }, { "code": null, "e": 5140, "s": 4944, "text": "def count_files_in_dir(project_root_dir, *fpaths: str): for path in fpaths: rel_path = os.path.join(project_root_dir, path) print(path, \":\", len(os.listdir(rel_path)))" }, { "code": null, "e": 5433, "s": 5140, "text": "In the function call, we pass in 5 arguments. As the function definition expects one required positional arguments i.e. project_root_dir, it automatically knows \"../usr\" must be it. All the remaining arguments (four in this case) are “soaked up” by *fpathsand are used for counting the files." }, { "code": null, "e": 5564, "s": 5433, "text": "Note: The proper terminology for this soaking up technique is “argument packing” i.e. remaining arguments are packed into *fpaths." }, { "code": null, "e": 5732, "s": 5564, "text": "Let’s look at functions that must take an unknown number of keyword arguments. In such scenarios, we must use kwargs instead of args. Here’s a short (useless) example:" }, { "code": null, "e": 5822, "s": 5732, "text": "def print_results(**results): for key, val in results.items(): print(key, val)" }, { "code": null, "e": 6095, "s": 5822, "text": "The usage is quite similar to *args but now we are able to pass an arbitrary number of keyword arguments to a function. These arguments get stored as key-value pairs in **resultsdictionary. From hereon, it is easy to access the items within this dictionary using .items()." }, { "code": null, "e": 6153, "s": 6095, "text": "I have found two main applications for kwargs in my work:" }, { "code": null, "e": 6204, "s": 6153, "text": "merging dictionaries (useful but less interesting)" }, { "code": null, "e": 6348, "s": 6204, "text": "dict1 = {'a':2 , 'b': 20}dict2 = {'c':15 , 'd': 40}merged_dict = {**dict1, **dict2}*************************{'a': 2, 'b': 20, 'c': 15, 'd': 40}" }, { "code": null, "e": 6396, "s": 6348, "text": "extending an existing method (more interesting)" }, { "code": null, "e": 6532, "s": 6396, "text": "def myfunc(a, b, flag, **kwargs): if flag: a, b = do_some_computation(a,b) actual_function(a,b, **kwargs)" }, { "code": null, "e": 6662, "s": 6532, "text": "Note: Checkout matplotlib’s plot function using kwargs to specify optional embellishments for a plot such as linewidth and label." }, { "code": null, "e": 7296, "s": 6662, "text": "Here’s a real practical use-case for extending methods using **kwargs from one of my recent projects:We often use Sklearn’s train_test_split() for splitting X and y. While working on one of the GANs projects, I had to split the generated synthetic images into the same train-test split that is used for splitting real images and their respective labels. In addition, I also wanted to be able to pass any other arguments that one would normally pass to the train_test_split(). Finally, stratify must always be passed because I was working on a face recognition problem (and wanted all labels to be present in both train and test set)." }, { "code": null, "e": 7501, "s": 7296, "text": "To achieve this, we created a function called custom_train_test_split(). I’ve included a bunch of print statements to show what exactly is happening under the hood (and omitted some snippets for brevity)." }, { "code": null, "e": 8423, "s": 7501, "text": "def custom_train_test_split(clf, y, *X, stratify, **split_args): print(\"Classifier used: \", classifier) print(\"Keys:\", split_args.keys()) print(\"Values: \", split_args.values()) print(X) print(y) print(\"Length of passed keyword arguments: \", len(split_args)) trainx,testx,*synthetic,trainy,testy = train_test_split( *X, y, stratify=stratify, **split_args ) ######### OMITTED CODE SNIPPET ############# # Train classifier on train and synthetic ims # Calculate accuracy on testx, testy ############################################ print(\"trainx: \", trainx, \"trainy: \",trainy, '\\n', \"testx: \", testx, \"testy:\", testy) print(\"synthetic: \", *synthetic)" }, { "code": null, "e": 8651, "s": 8423, "text": "Note: While calling this function, instead of using the actual image vectors and labels (see figure below), I have replaced them with dummy data for ease of understanding. The code, however, should work for real images as well!" }, { "code": null, "e": 8676, "s": 8651, "text": "Bunch of things to note:" }, { "code": null, "e": 9055, "s": 8676, "text": "All the keyword arguments (except stratify), used in the function call statement (such as train_size and random_state) will be stored as a key-value pair in the **split_args dictionary. (To verify, check out the output in Blue.)Why not stratify, you might ask? This is because according to the function definition, it is a required keyword-only argument and not an optional one." }, { "code": null, "e": 9644, "s": 9055, "text": "All the non-keyword (i.e. positional) arguments passed in the function call (such as \"SVM\", labels, etc.) would be stored in the first three parameters in function definition i.e.clf, y and *X, (and yes the order in which they are passed matters). However, we have four arguments in function call i.e. \"SVM\", labels, ims , and synthetic_ims. Where do we store the fourth one?Remember that we used *X as the third parameter in the function definition, hence all arguments passed to the function after the first two arguments are packed (soaked) into *X. (To verify, check output in Green)." }, { "code": null, "e": 9874, "s": 9644, "text": "When calling train_test_split() method within our function, we are essentially unpacking the X and split_args arguments using the * operator,(*X and **split_args), so that all elements of it can be passed as different parameters." }, { "code": null, "e": 9883, "s": 9874, "text": "That is," }, { "code": null, "e": 9942, "s": 9883, "text": "train_test_split(*X, y, stratify = stratify, **split_args)" }, { "code": null, "e": 9967, "s": 9942, "text": "is equivalent to writing" }, { "code": null, "e": 10065, "s": 9967, "text": "train_test_split(ims, synthetic_ims, y, stratify = stratify, train_size = 0.6, random_state = 50)" }, { "code": null, "e": 10219, "s": 10065, "text": "When storing the results from the train_test_split() method, we again pack the synthetic_train and synthetic_test sets into a single *synthetic variable." }, { "code": null, "e": 10312, "s": 10219, "text": "To check what’s inside it, we can unpack it again using * operator (see the output in Pink)." }, { "code": null, "e": 10428, "s": 10312, "text": "Note: For those of you who’d like a deep dive into packing & unpacking using * operator, do check out this article." }, { "code": null, "e": 10592, "s": 10428, "text": "The code we write is often messy and lacks proper formatting such as trailing whitespaces, trailing commas, unsorted import statements, spaces in indentation, etc." }, { "code": null, "e": 10820, "s": 10592, "text": "While it is possible to fix all this manually, you will be saving yourself a great deal of time with pre-commit hooks. In simpler terms, these hooks can perform auto-formatting for you with one line of command — pre-commit run." }, { "code": null, "e": 11010, "s": 10820, "text": "Here are some simple steps from the official documentation to get started and create a .pre-commit-config.yaml file. It will contain hooks for all the formatting issues that you care about!" }, { "code": null, "e": 11160, "s": 11010, "text": "As a purely personal preference, I tend to keep my .pre-commit-config.yaml configuration file simple and stick with Black’s pre-commit configuration." }, { "code": null, "e": 11317, "s": 11160, "text": "Note: One thing to remember is that files must be staged i.e. git add . before you do pre-commit run , otherwise, you’ll see all the files will be Skipped :" }, { "code": null, "e": 11551, "s": 11317, "text": "If your project contains a lot of config variables such as database hostname, passwords, AWS credentials, etc. use a .yml file to keep track of all of them. You can later use this file in any Jupyter Notebook or script that you wish." }, { "code": null, "e": 11862, "s": 11551, "text": "Given most of my work is aimed at providing a model framework to clients so they can train it again on their own dataset, I usually use config files for storing paths to folders and files. It is also a nice way to make sure the client has to make changes to only one file when running your script at their end." }, { "code": null, "e": 12121, "s": 11862, "text": "Let’s go ahead and create a fpaths.yml file in the project directory. We will be storing the root directory where images must be stored. Additionally, the paths to the file names, labels, attributes, etc. Finally, we also store the paths to synthetic images." }, { "code": null, "e": 12394, "s": 12121, "text": "image_data_dir: path/to/img/dir# the following paths are relative to images_data_dirfnames: fnames_fname: fnames.txt fnames_label: labels.txt fnames_attr: attr.txtsynthetic: edit_method: interface_edits expression: smile.pkl pose: pose.pkl" }, { "code": null, "e": 12423, "s": 12394, "text": "You can read this file like:" }, { "code": null, "e": 12622, "s": 12423, "text": "# open the yml filewith open(CONFIG_FPATH) as f: dictionary = yaml.safe_load(f)# print elements in dictionaryfor key, value in dictionary.items(): print(key + \" : \" + str(value)) print()" }, { "code": null, "e": 12715, "s": 12622, "text": "Note: If you’d like to dig deeper, here’s a brilliant tutorial to get you started with yaml." }, { "code": null, "e": 12944, "s": 12715, "text": "While there are certainly many nice choices for Python editors, I must say VSCode is hands-down the best I have seen so far (sorry, Pycharm). To get even more use of it, consider installing these extensions from the marketplace:" }, { "code": null, "e": 13024, "s": 12944, "text": "Bracket Pair Colorizer — allows matching brackets to be identified with colors." }, { "code": null, "e": 13077, "s": 13024, "text": "Path Intellisense — allows autocompleting filenames." }, { "code": null, "e": 13158, "s": 13077, "text": "Python Dockstring generator — allows generating docstrings for Python functions." }, { "code": null, "e": 13397, "s": 13158, "text": "Pro-tip: Generate the docstring (using \"\"\") after you’ve written the function using type hinting. This way, the docstring generated will be even richer in information such as default value, argument types, etc. (See image on right above)." }, { "code": null, "e": 13527, "s": 13397, "text": "Python Indent — (my favorite; published by by Kevin Rose) allows proper indentation of code/brackets that runs on multiple lines." }, { "code": null, "e": 13608, "s": 13527, "text": "Python Type Hint — allows auto-completion for type hints when writing functions." }, { "code": null, "e": 13722, "s": 13608, "text": "TODO tree: (second favorite) keeps track of ALL the TODO's at one place that were inserted while writing scripts." }, { "code": null, "e": 13825, "s": 13722, "text": "Pylance — allows code completion, parameter suggestions (and a loootttt more for writing code faster)." }, { "code": null, "e": 14085, "s": 13825, "text": "Congrats on being one step closer to a professional Python developer. I intend to keep updating this article as and when I learn more cool tricks. As always, if there’s an easier way to do some of the things I mentioned in this article, please do let me know." } ]
How to Protect Files and Directories from Deleting in Linux
Are you working as a Linux Admin? Do you generally defend script documents or any important files? You might be aware that, Chattr (change Attribute) is a command line Linux utility that is used to set/unset exact attributes to a file in Linux process to comfortable unintended deletion or change of major files and folders, although you’re logged in as a root user. This article helps you to look after your records or folders that may support in disallowing an unauthorized user to delete your touchy contents. In the below example abc.txt is the file name To protect file, use the following command – $ sudo chattr +i abc.txt Now try to remove file, using rm command as shown below – $ rm abc.txt The sample output should be like this – rm: remove write-protected regular file 'abc.txt'? To remove the protection to file, use the following command – $ sudo chattr -i abc.txt To verify the above command, use the following command as shown below- $ rm abc.txt The above command removes the file without giving information. In the below example abc is a directory name To protect directory, use the following command – $ sudo chattr -R +i abc To verify the above command, use the following command as shown below – $ rm -r abc The sample output should be like this – rm: descend into write-protected directory 'abc'? To remove protection to the directory, use the following command- $ sudo chattr -R -i abc To verify the above command, use the following command as shown below – $ rm -r abc The above command remove the file without giving information. In the above article, we have learnt about – Learn how to protect files & directories from delete. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
[ { "code": null, "e": 1429, "s": 1062, "text": "Are you working as a Linux Admin? Do you generally defend script documents or any important files? You might be aware that, Chattr (change Attribute) is a command line Linux utility that is used to set/unset exact attributes to a file in Linux process to comfortable unintended deletion or change of major files and folders, although you’re logged in as a root user." }, { "code": null, "e": 1575, "s": 1429, "text": "This article helps you to look after your records or folders that may support in disallowing an unauthorized user to delete your touchy contents." }, { "code": null, "e": 1621, "s": 1575, "text": "In the below example abc.txt is the file name" }, { "code": null, "e": 1666, "s": 1621, "text": "To protect file, use the following command –" }, { "code": null, "e": 1691, "s": 1666, "text": "$ sudo chattr +i abc.txt" }, { "code": null, "e": 1749, "s": 1691, "text": "Now try to remove file, using rm command as shown below –" }, { "code": null, "e": 1762, "s": 1749, "text": "$ rm abc.txt" }, { "code": null, "e": 1802, "s": 1762, "text": "The sample output should be like this –" }, { "code": null, "e": 1853, "s": 1802, "text": "rm: remove write-protected regular file 'abc.txt'?" }, { "code": null, "e": 1915, "s": 1853, "text": "To remove the protection to file, use the following command –" }, { "code": null, "e": 1941, "s": 1915, "text": "$ sudo chattr -i abc.txt\n" }, { "code": null, "e": 2012, "s": 1941, "text": "To verify the above command, use the following command as shown below-" }, { "code": null, "e": 2025, "s": 2012, "text": "$ rm abc.txt" }, { "code": null, "e": 2088, "s": 2025, "text": "The above command removes the file without giving information." }, { "code": null, "e": 2133, "s": 2088, "text": "In the below example abc is a directory name" }, { "code": null, "e": 2183, "s": 2133, "text": "To protect directory, use the following command –" }, { "code": null, "e": 2207, "s": 2183, "text": "$ sudo chattr -R +i abc" }, { "code": null, "e": 2279, "s": 2207, "text": "To verify the above command, use the following command as shown below –" }, { "code": null, "e": 2291, "s": 2279, "text": "$ rm -r abc" }, { "code": null, "e": 2331, "s": 2291, "text": "The sample output should be like this –" }, { "code": null, "e": 2382, "s": 2331, "text": "rm: descend into write-protected directory 'abc'?\n" }, { "code": null, "e": 2448, "s": 2382, "text": "To remove protection to the directory, use the following command-" }, { "code": null, "e": 2472, "s": 2448, "text": "$ sudo chattr -R -i abc" }, { "code": null, "e": 2544, "s": 2472, "text": "To verify the above command, use the following command as shown below –" }, { "code": null, "e": 2556, "s": 2544, "text": "$ rm -r abc" }, { "code": null, "e": 2618, "s": 2556, "text": "The above command remove the file without giving information." }, { "code": null, "e": 2808, "s": 2618, "text": "In the above article, we have learnt about – Learn how to protect files & directories from delete. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!" } ]
Stop Using Excel for Data Analytics: Upgrade to Python | by Tyler Folkman | Towards Data Science
In 2017, it was estimated that 750 million people worldwide used Excel. The population of the world in 2017 was about 7.6 billion. That means roughly 10% of the population was using Excel and I would guess mostly for data analytics. That is insane. There is no doubt that Excel has been an incredibly important tool for companies and still has a place in the toolkit of every data analyst and scientist, but for most of your work, you need to stop using Excel and upgrade to Python. I’m going to show you why. So, if you still have not taken the leap to learn Python and take your data analytics and visualization skills to the next level, I present you with 5 reasons why you need to learn Python right now. By the end, I’m confident you’ll be looking forward to replacing most of your Excel work with Python. Excel is great when you want to do quick, ad-hoc analysis with small data, but once you want to move to a larger scale, it just doesn’t work. Excel can support data up to 1,048,576 rows by 16,384 columns. On the other hand, Python can scale to the size of your memory and also has many tools that support out-of-memory computations. For example, the Dask library allows you to scale your computations to run on a cluster of machines and not just your laptop. In fact, if you are familiar with Pandas, it’s almost exactly the same code to read in a CSV: import dask.dataframe as dd # Load the data with Dask instead of Pandas. df = dd.read_csv(<file_path>) One line of code and you are now reading in data larger than your computer’s memory. I’d show you how to do that in Excel, but it’s not even possible. If this code looks foreign, check out this course that teaches you everything you need to know to get started with Pandas. Also, Python can scale when it comes to multiple data sources. While Excel is both the data store and the computation engine, Python is completely data agnostic. If you can find a way to read your data into Python, you can use it. And since Python has so many great libraries, it is trivial to read in data from many sources such as CSV, Excel, JSON, and SQL databases. Lastly, Python is an amazing programming language when it comes to automation. Since you can connect Python directly to any data source, it is easy to schedule a job that will re-pull your data with any updates, run your calculations, and even create a report or dynamic dashboard saving you tons of time. Excel, on the other hand, requires far too much manual labor and cannot automate updates. Reproducibility is the concept that any analytics or visualizations you create should be easy and straightforward to reproduce for someone else. Not only does someone need to be able to re-run your process and end up with the same result, but they should also be able to walk through your steps to ensure accuracy. This concept is extremely important as you start relying on automation. Automation is amazing when working correctly, but when incorrect, automated reports can be a nightmare. Reproducibility with Excel is very challenging. Excel calculations in cells are all but impossible to check at any type of scale. Data types are extremely confusing because what you see isn’t always what is represented in the raw data, and while VBA makes reproducibility slightly better, at that point, you’re much better off investing in learning Python. Take a look at this Excel document: You know the sum column should be the sum of a and b, but how do you confirm that? You could check one of the formulas and see that it is in fact the sum, but since every cell can be its own formula, what if they all are not correct? If you were not paying attention, you might have missed that row x was wrong. But in Python, your sum would look like this: a = [1,2,3,4]b = [5,6,7,8]sum = []for i in range(a): sum.append(a[i] + b[i]) This code is clear and easy to confirm that the sum is always calculated correctly. With Python, you get all the tools developed to make reproducibility and collaboration better for software engineers. On top of that, Python is superior for data connectivity, allowing us to analyze data in the cloud and repeat a process instantly. Git, unit testing, documentation, and code formatting standards are all prevalent in the Python community. With Python 3, you can even add static typing to make your code even more clear. All of these tools make it easier to ensure your code is written well and correctly. So that the next time you look at your code or someone else picks it up, it’s easy to reproduce and understand. If you know Excel, you know Excel. While the skills you learn are useful, they are not transferable to anything else. One of the things I like most about Python is that not only is it an amazing tool for data analytics and visualization, but it’s a solid programming language that can be used for so many other things. Want to do machine learning or even deep learning? You can do that with Python. Want to build a website? Python can do that. Want to automate your smart home? Python can do that as well. Also, Python is much closer to other programming languages than Excel. That makes it much easier to pick up other languages you might encounter along the way. Learning Python opens up far more doors than Excel ever could. Lastly, the demand for Python is incredibly high. According to StackOverflow, in 2019, it was ranked as the world’s 4th most popular programming language among professional software developers as well as the first most wanted programming language. And Indeed says the average Python developer salary in the US in 2020 is $120K per year. Not bad. Excel has a lot of built-in formulas, but it pales in comparison with Python’s capabilities. Not only does Python offer hundreds of libraries to make advanced statistics and analytics easier, but it can also take your visualizations to another level. With tools like Matplotlib, Plotly, Streamlit, and Seaborn, you can create beautiful visualizations of data as well as interactive dashboards and plots. Numpy and scipy have amazing support for scientific computations, linear algebra, and vectorized calculations. And scikit-learn lets you train machine learning algorithms from decision trees to gradient boosting machines. I think xkcd said it best: Given all the amazing benefits of Python over Excel, it must be hard to learn, right? No! Check out the Java version of Hello World, the simplest program: class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello World!" ); }} Python is literally one line: print(“Hello World!”). It doesn’t get any simpler. Python is one of the easiest programming languages to pick up and has one of the most active communities, especially in the data analytics world. Python is one of the most intuitive programming languages out there, and it’s even understandable for someone with little background in computer science! While the learning curve Excel might seem preferable, there is far less payoff on the other end. Python’s learning curve is worth the time and effort in a way that Excel will never match due to its one-size-fits-all design. Python is easy to use, and with a huge community of support, it’s never been easier to learn. To show you just how easy Python is, in the next section I will introduce you to some of the foundations for data analytics and visualizations in Python. To get you started, I want to walk you through some basic commands and operations in Python that will be essential to your data analysis skills. Let’s start with the foundations. The first thing you will notice is that Python makes use of whitespace and does not use a use semicolon ; like other languages. Here is a very simple example: x = 5y = 10print(x+y) We will make use of many libraries, some that are pre-installed with Python and some we will have to install ourselves. To get a library use an import statement: from collections import Counter This command imports the class Counter from the collections library. Counter is a very useful tool for data scientists; it can count the number of times items appear in collections such as lists. For example, in the code below we will create a list of marriage ages. Using Counter we can quickly count the number of times each unique age appears. Lists are a useful data structure to store data. They will be studied in more detail during the next lesson. For example: from collections import Countermarriage_ages = [22, 22, 25, 25, 30, 24, 26, 24, 35]value_counts = Counter(marriage_ages)print(value_counts.most_common()) You can see that we created a list containing marriage ages using the [] at line 2. We then fed that list into the Counter function at line 4 to print out the most common values as a list of tuples, at line 5. A tuple is a collection inside the (). These tuples contain two elements: the value and then the number of times that value appeared in your list. The frequency orders the list of tuples. The value with the most occurrence appears first. Functions are also useful. Functions in Python start with the keyword def and the function name followed by the inputs the function expects within brackets. Here is a function that takes in 2 inputs, x and y, and returns the sum: def add_two_numbers(x, y): # function header """ Takes in two numbers and returns the sum parameters x : str first number y : str second number returns x+y """ z = x + y return z # function returnprint(add_two_numbers(100,5)) # function call Functions can also be anonymous, meaning that you don’t have to declare them with the above structure. Instead, you can use the lambda keyword. Here is the same function as above, but as an anonymous function: y = lambda x, y: x + yprint(y(100,5)) # call the function It’s time to make the switch to Python. There are no more excuses! I hope this post helped you see the benefits of learning Python and break down some of the barriers to learning. Go and take your skills to the next level with Python!
[ { "code": null, "e": 421, "s": 172, "text": "In 2017, it was estimated that 750 million people worldwide used Excel. The population of the world in 2017 was about 7.6 billion. That means roughly 10% of the population was using Excel and I would guess mostly for data analytics. That is insane." }, { "code": null, "e": 682, "s": 421, "text": "There is no doubt that Excel has been an incredibly important tool for companies and still has a place in the toolkit of every data analyst and scientist, but for most of your work, you need to stop using Excel and upgrade to Python. I’m going to show you why." }, { "code": null, "e": 983, "s": 682, "text": "So, if you still have not taken the leap to learn Python and take your data analytics and visualization skills to the next level, I present you with 5 reasons why you need to learn Python right now. By the end, I’m confident you’ll be looking forward to replacing most of your Excel work with Python." }, { "code": null, "e": 1316, "s": 983, "text": "Excel is great when you want to do quick, ad-hoc analysis with small data, but once you want to move to a larger scale, it just doesn’t work. Excel can support data up to 1,048,576 rows by 16,384 columns. On the other hand, Python can scale to the size of your memory and also has many tools that support out-of-memory computations." }, { "code": null, "e": 1536, "s": 1316, "text": "For example, the Dask library allows you to scale your computations to run on a cluster of machines and not just your laptop. In fact, if you are familiar with Pandas, it’s almost exactly the same code to read in a CSV:" }, { "code": null, "e": 1639, "s": 1536, "text": "import dask.dataframe as dd # Load the data with Dask instead of Pandas. df = dd.read_csv(<file_path>)" }, { "code": null, "e": 1790, "s": 1639, "text": "One line of code and you are now reading in data larger than your computer’s memory. I’d show you how to do that in Excel, but it’s not even possible." }, { "code": null, "e": 1913, "s": 1790, "text": "If this code looks foreign, check out this course that teaches you everything you need to know to get started with Pandas." }, { "code": null, "e": 2283, "s": 1913, "text": "Also, Python can scale when it comes to multiple data sources. While Excel is both the data store and the computation engine, Python is completely data agnostic. If you can find a way to read your data into Python, you can use it. And since Python has so many great libraries, it is trivial to read in data from many sources such as CSV, Excel, JSON, and SQL databases." }, { "code": null, "e": 2679, "s": 2283, "text": "Lastly, Python is an amazing programming language when it comes to automation. Since you can connect Python directly to any data source, it is easy to schedule a job that will re-pull your data with any updates, run your calculations, and even create a report or dynamic dashboard saving you tons of time. Excel, on the other hand, requires far too much manual labor and cannot automate updates." }, { "code": null, "e": 3170, "s": 2679, "text": "Reproducibility is the concept that any analytics or visualizations you create should be easy and straightforward to reproduce for someone else. Not only does someone need to be able to re-run your process and end up with the same result, but they should also be able to walk through your steps to ensure accuracy. This concept is extremely important as you start relying on automation. Automation is amazing when working correctly, but when incorrect, automated reports can be a nightmare." }, { "code": null, "e": 3527, "s": 3170, "text": "Reproducibility with Excel is very challenging. Excel calculations in cells are all but impossible to check at any type of scale. Data types are extremely confusing because what you see isn’t always what is represented in the raw data, and while VBA makes reproducibility slightly better, at that point, you’re much better off investing in learning Python." }, { "code": null, "e": 3563, "s": 3527, "text": "Take a look at this Excel document:" }, { "code": null, "e": 3875, "s": 3563, "text": "You know the sum column should be the sum of a and b, but how do you confirm that? You could check one of the formulas and see that it is in fact the sum, but since every cell can be its own formula, what if they all are not correct? If you were not paying attention, you might have missed that row x was wrong." }, { "code": null, "e": 3921, "s": 3875, "text": "But in Python, your sum would look like this:" }, { "code": null, "e": 4001, "s": 3921, "text": "a = [1,2,3,4]b = [5,6,7,8]sum = []for i in range(a): sum.append(a[i] + b[i])" }, { "code": null, "e": 4085, "s": 4001, "text": "This code is clear and easy to confirm that the sum is always calculated correctly." }, { "code": null, "e": 4719, "s": 4085, "text": "With Python, you get all the tools developed to make reproducibility and collaboration better for software engineers. On top of that, Python is superior for data connectivity, allowing us to analyze data in the cloud and repeat a process instantly. Git, unit testing, documentation, and code formatting standards are all prevalent in the Python community. With Python 3, you can even add static typing to make your code even more clear. All of these tools make it easier to ensure your code is written well and correctly. So that the next time you look at your code or someone else picks it up, it’s easy to reproduce and understand." }, { "code": null, "e": 5038, "s": 4719, "text": "If you know Excel, you know Excel. While the skills you learn are useful, they are not transferable to anything else. One of the things I like most about Python is that not only is it an amazing tool for data analytics and visualization, but it’s a solid programming language that can be used for so many other things." }, { "code": null, "e": 5225, "s": 5038, "text": "Want to do machine learning or even deep learning? You can do that with Python. Want to build a website? Python can do that. Want to automate your smart home? Python can do that as well." }, { "code": null, "e": 5447, "s": 5225, "text": "Also, Python is much closer to other programming languages than Excel. That makes it much easier to pick up other languages you might encounter along the way. Learning Python opens up far more doors than Excel ever could." }, { "code": null, "e": 5793, "s": 5447, "text": "Lastly, the demand for Python is incredibly high. According to StackOverflow, in 2019, it was ranked as the world’s 4th most popular programming language among professional software developers as well as the first most wanted programming language. And Indeed says the average Python developer salary in the US in 2020 is $120K per year. Not bad." }, { "code": null, "e": 6197, "s": 5793, "text": "Excel has a lot of built-in formulas, but it pales in comparison with Python’s capabilities. Not only does Python offer hundreds of libraries to make advanced statistics and analytics easier, but it can also take your visualizations to another level. With tools like Matplotlib, Plotly, Streamlit, and Seaborn, you can create beautiful visualizations of data as well as interactive dashboards and plots." }, { "code": null, "e": 6446, "s": 6197, "text": "Numpy and scipy have amazing support for scientific computations, linear algebra, and vectorized calculations. And scikit-learn lets you train machine learning algorithms from decision trees to gradient boosting machines. I think xkcd said it best:" }, { "code": null, "e": 6601, "s": 6446, "text": "Given all the amazing benefits of Python over Excel, it must be hard to learn, right? No! Check out the Java version of Hello World, the simplest program:" }, { "code": null, "e": 6717, "s": 6601, "text": "class HelloWorld { public static void main( String args[] ) { System.out.println( \"Hello World!\" ); }}" }, { "code": null, "e": 7322, "s": 6717, "text": "Python is literally one line: print(“Hello World!”). It doesn’t get any simpler. Python is one of the easiest programming languages to pick up and has one of the most active communities, especially in the data analytics world. Python is one of the most intuitive programming languages out there, and it’s even understandable for someone with little background in computer science! While the learning curve Excel might seem preferable, there is far less payoff on the other end. Python’s learning curve is worth the time and effort in a way that Excel will never match due to its one-size-fits-all design." }, { "code": null, "e": 7416, "s": 7322, "text": "Python is easy to use, and with a huge community of support, it’s never been easier to learn." }, { "code": null, "e": 7570, "s": 7416, "text": "To show you just how easy Python is, in the next section I will introduce you to some of the foundations for data analytics and visualizations in Python." }, { "code": null, "e": 7749, "s": 7570, "text": "To get you started, I want to walk you through some basic commands and operations in Python that will be essential to your data analysis skills. Let’s start with the foundations." }, { "code": null, "e": 7908, "s": 7749, "text": "The first thing you will notice is that Python makes use of whitespace and does not use a use semicolon ; like other languages. Here is a very simple example:" }, { "code": null, "e": 7930, "s": 7908, "text": "x = 5y = 10print(x+y)" }, { "code": null, "e": 8092, "s": 7930, "text": "We will make use of many libraries, some that are pre-installed with Python and some we will have to install ourselves. To get a library use an import statement:" }, { "code": null, "e": 8124, "s": 8092, "text": "from collections import Counter" }, { "code": null, "e": 8471, "s": 8124, "text": "This command imports the class Counter from the collections library. Counter is a very useful tool for data scientists; it can count the number of times items appear in collections such as lists. For example, in the code below we will create a list of marriage ages. Using Counter we can quickly count the number of times each unique age appears." }, { "code": null, "e": 8593, "s": 8471, "text": "Lists are a useful data structure to store data. They will be studied in more detail during the next lesson. For example:" }, { "code": null, "e": 8747, "s": 8593, "text": "from collections import Countermarriage_ages = [22, 22, 25, 25, 30, 24, 26, 24, 35]value_counts = Counter(marriage_ages)print(value_counts.most_common())" }, { "code": null, "e": 8957, "s": 8747, "text": "You can see that we created a list containing marriage ages using the [] at line 2. We then fed that list into the Counter function at line 4 to print out the most common values as a list of tuples, at line 5." }, { "code": null, "e": 9195, "s": 8957, "text": "A tuple is a collection inside the (). These tuples contain two elements: the value and then the number of times that value appeared in your list. The frequency orders the list of tuples. The value with the most occurrence appears first." }, { "code": null, "e": 9425, "s": 9195, "text": "Functions are also useful. Functions in Python start with the keyword def and the function name followed by the inputs the function expects within brackets. Here is a function that takes in 2 inputs, x and y, and returns the sum:" }, { "code": null, "e": 9719, "s": 9425, "text": "def add_two_numbers(x, y): # function header \"\"\" Takes in two numbers and returns the sum parameters x : str first number y : str second number returns x+y \"\"\" z = x + y return z # function returnprint(add_two_numbers(100,5)) # function call" }, { "code": null, "e": 9929, "s": 9719, "text": "Functions can also be anonymous, meaning that you don’t have to declare them with the above structure. Instead, you can use the lambda keyword. Here is the same function as above, but as an anonymous function:" }, { "code": null, "e": 9988, "s": 9929, "text": "y = lambda x, y: x + yprint(y(100,5)) # call the function" }, { "code": null, "e": 10168, "s": 9988, "text": "It’s time to make the switch to Python. There are no more excuses! I hope this post helped you see the benefits of learning Python and break down some of the barriers to learning." } ]
Deploying a Simple UI for Python. Streamlit Sharing: A Python Project... | by Max Reynolds | Towards Data Science
Creating a user interface for a Python project is seamless with Streamlit, a relatively new browser-based Python framework that lets you elegantly showcase a project without writing any HTML, CSS, or Javascript code. Now, with Streamlit Sharing, you can deploy your project for free without needing to spin up a server or use any cloud services like Heroku. In previous articles, we built a simple maze-solver app. In short, it allows users to upload an image of a maze and it shows a solution. A few of the Streamlit features used to facilitate user interaction are: For a more in-depth look at how Streamlit features are implemented for this app: towardsdatascience.com Streamlit recently introduced the Streamlit Sharing service to facilitate deployment of Streamlit projects. Using the service requires a few quick steps. You can create this using the following command while in your project’s environment: pip freeze > requirements.txt Create a public repository for your project and be sure to commit the requirements.txt in addition to any project files. Here’s a primer on creating a repository if you have not used Github. While the service is still in its early stages, you can request access here. I received access from the Streamlit team in less than 24 hours. Once you receive the access email, sign in to share.streamlit.io with your current GitHub account. Once you are signed in hit “New App” and enter the repository information. Note: If your python dependencies require OS-level packages you may need to add a packages.txt file to your repository. For example, using the OpenCV Python library with Streamlit requires the host server to install ffmpeg. In this lesson, we quickly deployed a Python project for free using Streamlit Sharing. You can view the final, deployed app here as well as all of the source code on Github. To learn more about the algorithm behind the maze solver, or how to use Streamlit to create a friendly web interface using very few lines of Python code, check out Parts I and II of this series. towardsdatascience.com towardsdatascience.com Registering for Medium membership supports my work.
[ { "code": null, "e": 389, "s": 172, "text": "Creating a user interface for a Python project is seamless with Streamlit, a relatively new browser-based Python framework that lets you elegantly showcase a project without writing any HTML, CSS, or Javascript code." }, { "code": null, "e": 530, "s": 389, "text": "Now, with Streamlit Sharing, you can deploy your project for free without needing to spin up a server or use any cloud services like Heroku." }, { "code": null, "e": 740, "s": 530, "text": "In previous articles, we built a simple maze-solver app. In short, it allows users to upload an image of a maze and it shows a solution. A few of the Streamlit features used to facilitate user interaction are:" }, { "code": null, "e": 821, "s": 740, "text": "For a more in-depth look at how Streamlit features are implemented for this app:" }, { "code": null, "e": 844, "s": 821, "text": "towardsdatascience.com" }, { "code": null, "e": 998, "s": 844, "text": "Streamlit recently introduced the Streamlit Sharing service to facilitate deployment of Streamlit projects. Using the service requires a few quick steps." }, { "code": null, "e": 1083, "s": 998, "text": "You can create this using the following command while in your project’s environment:" }, { "code": null, "e": 1113, "s": 1083, "text": "pip freeze > requirements.txt" }, { "code": null, "e": 1234, "s": 1113, "text": "Create a public repository for your project and be sure to commit the requirements.txt in addition to any project files." }, { "code": null, "e": 1304, "s": 1234, "text": "Here’s a primer on creating a repository if you have not used Github." }, { "code": null, "e": 1446, "s": 1304, "text": "While the service is still in its early stages, you can request access here. I received access from the Streamlit team in less than 24 hours." }, { "code": null, "e": 1545, "s": 1446, "text": "Once you receive the access email, sign in to share.streamlit.io with your current GitHub account." }, { "code": null, "e": 1620, "s": 1545, "text": "Once you are signed in hit “New App” and enter the repository information." }, { "code": null, "e": 1844, "s": 1620, "text": "Note: If your python dependencies require OS-level packages you may need to add a packages.txt file to your repository. For example, using the OpenCV Python library with Streamlit requires the host server to install ffmpeg." }, { "code": null, "e": 2018, "s": 1844, "text": "In this lesson, we quickly deployed a Python project for free using Streamlit Sharing. You can view the final, deployed app here as well as all of the source code on Github." }, { "code": null, "e": 2213, "s": 2018, "text": "To learn more about the algorithm behind the maze solver, or how to use Streamlit to create a friendly web interface using very few lines of Python code, check out Parts I and II of this series." }, { "code": null, "e": 2236, "s": 2213, "text": "towardsdatascience.com" }, { "code": null, "e": 2259, "s": 2236, "text": "towardsdatascience.com" } ]
Validate an IP Address | Practice | GeeksforGeeks
Write a program to Validate an IPv4 Address. According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 . A valid IPv4 Address is of the form x1.x2.x3.x4 where 0 <= (x1, x2, x3, x4) <= 255. Thus, we can write the generalized form of an IPv4 address as (0-255).(0-255).(0-255).(0-255). Note: Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid. Your task is to complete the function isValid which returns 1 if the given IPv4 address is valid else returns 0. The function takes the IPv4 address as the only argument in the form of string. Example 1: Input: IPv4 address = 222.111.111.111 Output: 1 Explanation: Here, the IPv4 address is as per the criteria mentioned and also all four decimal numbers lies in the mentioned range. Example 2: Input: IPv4 address = 5555..555 Output: 0 Explanation: 5555..555 is not a valid IPv4 address, as the middle two portions are missing. Your Task: Complete the function isValid() which takes the address in the form of string s as an input parameter and returns 1 if this is a valid address otherwise returns 0. Expected Time Complexity: O(N), N = length of the string. Expected Auxiliary Space: O(1) Constraints: 1<=length of string <=50 Note: The Input/Output format and Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 mukesh kumar2 days ago class Solution { public: int isValid(string s) { if(s.size() < 7) //minimum lenght of ip address 0.0.0.0 return 0; //check for minimum and maximum three dots size_t _count = std::count(s.begin(), s.end(), '.'); if( _count != 3) return 0; string tmpStr(s); string currVal; int currValInt; int pos; while(_count > 0) { pos = tmpStr.find('.'); currVal = tmpStr.substr(0, pos); if(!isdigit(currVal[0])) //to check a.b.c.d return 0; currValInt = stoi(currVal); if(currValInt == 0 && currVal.size()>1) //000.000.000.000 break; if(currVal.size() > 3) //3343.46546.323.11 break; if(currValInt > 255 || currValInt < 0 ) //300.333.266.32 break; if((currValInt < pow(10,currVal.length()-1)) && (currValInt != 0)) //01.022.22.44 return 0; tmpStr = tmpStr.substr(pos + 1); _count--; } if(_count > 0) return 0; //Now validate the last element of the IP address i.e. out of x1.x2.x3.x4 validate x4 currValInt = stoi(tmpStr); if(currValInt == 0 && tmpStr.size() > 1) return 0; if(tmpStr.size() == 0 || tmpStr.size() > 3) return 0; if(stoi(tmpStr) > 255 || stoi(tmpStr) < 0 ) return 0; if((currValInt < pow(10,tmpStr.length()-1)) && (currValInt != 0)) return 0; return 1; }}; 0 nitishmishra9376 days ago public boolean isValid(String s) { // Write your code here StringBuilder b = new StringBuilder(); int subCount = 0; int dotCount = 0; /*if(s.equals("00.00.00.00") || s.equals("000.000.000.000")) { return false; }*/ for(int i = 0; i < s.length(); ++i) { if(s.charAt(i) == '.') { if(dotCount > 3) { return false; } ++dotCount; try { Integer num = Integer.valueOf(b.toString()); if(num > -1 && num < 256) { subCount = 0; b.setLength(0); } else { return false; } } catch (NumberFormatException e) { return false; } } else { ++subCount; if(subCount > 3) { return false; } else { if(b.length() != 0 && b.toString().equals("0")) { return false; } b.append(s.charAt(i)); } } } return dotCount == 3; } 0 ayushmahobia016 days ago int isValid(string s) { // code here int count = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '.') { count++; } } if (count != 3) return 0; unordered_set<string> st; for (int i = 0; i < 256; i++) { st.insert(to_string(i)); } count = 0; string temp = ""; for (int i = 0; i < s.length(); i++) { if (s[i] != '.') { temp += s[i]; } else { if (st.count(temp) != 0) { count++; } temp = ""; } } if (st.count(temp) != 0) { count++; } if (count == 4) return 1; else return 0; } 0 wajid945711 week ago // good question class Solution { private: int solve(string str, char sep){ string temp = ""; int c=0; int count=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; if(temp.size()>3|| temp=="00" || ((temp[0]>='a' && temp[0]<='z') || (temp[0]>='A' && temp[0]<='Z')) ){ return 0; } } else{ c++; if(temp.size()==0 || (temp.size()>=2 && temp[0]=='0')|| temp.size()>3){ return 0; } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = ""; } } for(int i=0;i<str.size();i++){ if(str[i]=='.'){ count++; } } if(count>3){ return 0; } if(stoi(temp)<0 || stoi(temp)>255 || (temp.size()>=2 && temp[0]=='0')){ return 0; } if(c<3 || c>3){ return 0; } return 1; } public: int isValid(string s) { return solve(s,'.'); }}; +1 kartikeyashokgautam1 week ago Easy JAVA Solution :- public boolean isValid(String s) { int count = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='.') count++; } if(count!=3) return false; HashSet<String> hs = new HashSet<>(); for(int i=0;i<256;i++) { hs.add(Integer.toString(i)); } count = 0; String temp = ""; for(int i=0;i<s.length();i++) { if(s.charAt(i)!='.') { temp+= s.charAt(i); } else { if(hs.contains(temp)) { count++; } temp = ""; } } if(hs.contains(temp)) { count++; } if(count == 4) { return true; } return false; } -1 roshan852k1 week ago class Solution { private: int solve(string str, char sep){ string temp = ""; int c=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; } else{ c++; if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = ""; } } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } if(c<3){ return 0; } return 1; } public: int isValid(string s) { // code here return solve(s,'.'); }}; +2 jack11431 week ago Executed in 0.01sec class Solution { public: int isValid(string s) { // code here int i = 0, count = 0; while(i < s.size()){ string tmp; while(i < s.size() and s[i] != '.' and s[i] >= '0' and s[i] <= '9')tmp += s[i++]; //only accepting integer if(tmp.size() == 0 || tmp.size() > 3 || stoi(tmp) > 255 || stoi(tmp) < 0)return 0; // valid number checking if(tmp.size() >= 2 and tmp[0] == '0')return 0; //chekcing leading zeros; if(s[i] == '.')count++; i++; } if(count < 3 || count > 3)return 0; //checking 32bit return 1; } 0 sumitsinghrajput786gwalior2 weeks ago //completed in java class Solution { public boolean isValid(String s) { // Write your code here if(s.compareTo("")==0){ return false; } if(s.length()<7)return false; int dot = 0; for(int i=0;i<s.length();i++){ if('.' == s.charAt(i)){ dot++; } } if(dot!=3)return false; String S = s.replace(".","@"); String[] str = S.split("@"); if(str.length != 4){ return false; } boolean ans = true; for(int i=0;i<4;i++){ if(str[i].length()<4){ try{ int n = Integer.parseInt(str[i]); if(0<=n && n<=255){ if(str[i].length()>1 && (n>=0 && n<=9))return false; continue; } else{ return false; } } catch(Exception e){ return false; } } else{ return false; } } return true; }} 0 minipandey3322 weeks ago //Anybody tells me what's wrong in below code. int isValid(string s) { // code here int dot=0; int r=0; for(int i=0; i<s.length(); i++) // 222.111.111.111 { if(s[i]>=0 && s[i] <= 9) { int x = atoi(s[i]); r = r*10 + x; } else if(s[i] == '.') { dot++; if(r>255 || r<0) return 0; r=0; } else return 0; } if(dot==3) return 1; else return 0; }}; +1 dtu_top_coder2 weeks ago 1st Try Solution Accepted C++ Code : class Solution { public: int isValid(string s) { string str=""; int count=0; s.push_back('.'); for(int i=0;i<s.size();i++) { if(s[i]=='.') { if(!check(str)) return false; str=""; count++; } else { str+=s[i]; } } if(count==4) return true; return false; } bool check(string s) { if(s=="" || (s[0]=='0' && s.size()>1)) return false; int a=atoi(s.c_str()); for(auto c:s) if(c<'0' || c>'9') return false; if(a>=0 && a<=255) return true; return false; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 781, "s": 238, "text": "Write a program to Validate an IPv4 Address.\nAccording to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 .\nA valid IPv4 Address is of the form x1.x2.x3.x4 where 0 <= (x1, x2, x3, x4) <= 255.\nThus, we can write the generalized form of an IPv4 address as (0-255).(0-255).(0-255).(0-255).\nNote: Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid." }, { "code": null, "e": 974, "s": 781, "text": "Your task is to complete the function isValid which returns 1 if the given IPv4 address is valid else returns 0. The function takes the IPv4 address as the only argument in the form of string." }, { "code": null, "e": 985, "s": 974, "text": "Example 1:" }, { "code": null, "e": 1167, "s": 985, "text": "Input:\nIPv4 address = 222.111.111.111\nOutput: 1\nExplanation: Here, the IPv4 address is as\nper the criteria mentioned and also all\nfour decimal numbers lies in the mentioned\nrange.\n\n" }, { "code": null, "e": 1178, "s": 1167, "text": "Example 2:" }, { "code": null, "e": 1312, "s": 1178, "text": "Input:\nIPv4 address = 5555..555\nOutput: 0\nExplanation: 5555..555 is not a valid\nIPv4 address, as the middle two portions\nare missing." }, { "code": null, "e": 1487, "s": 1312, "text": "Your Task:\nComplete the function isValid() which takes the address in the form of string s as an input parameter and returns 1 if this is a valid address otherwise returns 0." }, { "code": null, "e": 1931, "s": 1487, "text": "Expected Time Complexity: O(N), N = length of the string.\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1<=length of string <=50\n\nNote: The Input/Output format and Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1933, "s": 1931, "text": "0" }, { "code": null, "e": 1956, "s": 1933, "text": "mukesh kumar2 days ago" }, { "code": null, "e": 3294, "s": 1956, "text": "class Solution { public: int isValid(string s) { if(s.size() < 7) //minimum lenght of ip address 0.0.0.0 return 0; //check for minimum and maximum three dots size_t _count = std::count(s.begin(), s.end(), '.'); if( _count != 3) return 0; string tmpStr(s); string currVal; int currValInt; int pos; while(_count > 0) { pos = tmpStr.find('.'); currVal = tmpStr.substr(0, pos); if(!isdigit(currVal[0])) //to check a.b.c.d return 0; currValInt = stoi(currVal); if(currValInt == 0 && currVal.size()>1) //000.000.000.000 break; if(currVal.size() > 3) //3343.46546.323.11 break; if(currValInt > 255 || currValInt < 0 ) //300.333.266.32 break; if((currValInt < pow(10,currVal.length()-1)) && (currValInt != 0)) //01.022.22.44 return 0; tmpStr = tmpStr.substr(pos + 1); _count--; } if(_count > 0) return 0; //Now validate the last element of the IP address i.e. out of x1.x2.x3.x4 validate x4 currValInt = stoi(tmpStr); if(currValInt == 0 && tmpStr.size() > 1) return 0; if(tmpStr.size() == 0 || tmpStr.size() > 3) return 0; if(stoi(tmpStr) > 255 || stoi(tmpStr) < 0 ) return 0; if((currValInt < pow(10,tmpStr.length()-1)) && (currValInt != 0)) return 0; return 1; }};" }, { "code": null, "e": 3296, "s": 3294, "text": "0" }, { "code": null, "e": 3322, "s": 3296, "text": "nitishmishra9376 days ago" }, { "code": null, "e": 4518, "s": 3322, "text": " public boolean isValid(String s) { // Write your code here StringBuilder b = new StringBuilder(); int subCount = 0; int dotCount = 0; /*if(s.equals(\"00.00.00.00\") || s.equals(\"000.000.000.000\")) { return false; }*/ for(int i = 0; i < s.length(); ++i) { if(s.charAt(i) == '.') { if(dotCount > 3) { return false; } ++dotCount; try { Integer num = Integer.valueOf(b.toString()); if(num > -1 && num < 256) { subCount = 0; b.setLength(0); } else { return false; } } catch (NumberFormatException e) { return false; } } else { ++subCount; if(subCount > 3) { return false; } else { if(b.length() != 0 && b.toString().equals(\"0\")) { return false; } b.append(s.charAt(i)); } } } return dotCount == 3; }" }, { "code": null, "e": 4520, "s": 4518, "text": "0" }, { "code": null, "e": 4545, "s": 4520, "text": "ayushmahobia016 days ago" }, { "code": null, "e": 4761, "s": 4545, "text": " int isValid(string s) { // code here int count = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '.') { count++; } } if (count != 3) return 0;" }, { "code": null, "e": 4861, "s": 4761, "text": " unordered_set<string> st; for (int i = 0; i < 256; i++) { st.insert(to_string(i)); }" }, { "code": null, "e": 5250, "s": 4861, "text": " count = 0; string temp = \"\"; for (int i = 0; i < s.length(); i++) { if (s[i] != '.') { temp += s[i]; } else { if (st.count(temp) != 0) { count++; } temp = \"\"; } } if (st.count(temp) != 0) { count++; } if (count == 4) return 1; else return 0; }" }, { "code": null, "e": 5252, "s": 5250, "text": "0" }, { "code": null, "e": 5273, "s": 5252, "text": "wajid945711 week ago" }, { "code": null, "e": 5290, "s": 5273, "text": "// good question" }, { "code": null, "e": 6129, "s": 5292, "text": "class Solution { private: int solve(string str, char sep){ string temp = \"\"; int c=0; int count=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; if(temp.size()>3|| temp==\"00\" || ((temp[0]>='a' && temp[0]<='z') || (temp[0]>='A' && temp[0]<='Z')) ){ return 0; } } else{ c++; if(temp.size()==0 || (temp.size()>=2 && temp[0]=='0')|| temp.size()>3){ return 0; } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = \"\"; } } for(int i=0;i<str.size();i++){ if(str[i]=='.'){ count++; } } if(count>3){ return 0; }" }, { "code": null, "e": 6239, "s": 6129, "text": " if(stoi(temp)<0 || stoi(temp)>255 || (temp.size()>=2 && temp[0]=='0')){ return 0; }" }, { "code": null, "e": 6374, "s": 6239, "text": " if(c<3 || c>3){ return 0; } return 1; } public: int isValid(string s) { return solve(s,'.'); }};" }, { "code": null, "e": 6377, "s": 6374, "text": "+1" }, { "code": null, "e": 6407, "s": 6377, "text": "kartikeyashokgautam1 week ago" }, { "code": null, "e": 6429, "s": 6407, "text": "Easy JAVA Solution :-" }, { "code": null, "e": 6637, "s": 6431, "text": " public boolean isValid(String s) { int count = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='.') count++; } if(count!=3) return false;" }, { "code": null, "e": 7355, "s": 6637, "text": " HashSet<String> hs = new HashSet<>(); for(int i=0;i<256;i++) { hs.add(Integer.toString(i)); } count = 0; String temp = \"\"; for(int i=0;i<s.length();i++) { if(s.charAt(i)!='.') { temp+= s.charAt(i); } else { if(hs.contains(temp)) { count++; } temp = \"\"; } } if(hs.contains(temp)) { count++; } if(count == 4) { return true; } return false;" }, { "code": null, "e": 7360, "s": 7355, "text": " }" }, { "code": null, "e": 7363, "s": 7360, "text": "-1" }, { "code": null, "e": 7384, "s": 7363, "text": "roshan852k1 week ago" }, { "code": null, "e": 8014, "s": 7384, "text": "class Solution { private: int solve(string str, char sep){ string temp = \"\"; int c=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; } else{ c++; if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = \"\"; } } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } if(c<3){ return 0; } return 1; } public: int isValid(string s) { // code here return solve(s,'.'); }};" }, { "code": null, "e": 8017, "s": 8014, "text": "+2" }, { "code": null, "e": 8036, "s": 8017, "text": "jack11431 week ago" }, { "code": null, "e": 8056, "s": 8036, "text": "Executed in 0.01sec" }, { "code": null, "e": 8745, "s": 8056, "text": "class Solution {\n public:\n int isValid(string s) {\n // code here\n int i = 0, count = 0;\n while(i < s.size()){\n string tmp;\n while(i < s.size() and s[i] != '.' and s[i] >= '0' and s[i] <= '9')tmp += s[i++]; //only accepting integer\n if(tmp.size() == 0 || tmp.size() > 3 || stoi(tmp) > 255 || stoi(tmp) < 0)return 0; // valid number checking\n if(tmp.size() >= 2 and tmp[0] == '0')return 0; //chekcing leading zeros;\n if(s[i] == '.')count++;\n i++;\n }\n if(count < 3 || count > 3)return 0; //checking 32bit\n return 1;\n }" }, { "code": null, "e": 8747, "s": 8745, "text": "0" }, { "code": null, "e": 8785, "s": 8747, "text": "sumitsinghrajput786gwalior2 weeks ago" }, { "code": null, "e": 8805, "s": 8785, "text": "//completed in java" }, { "code": null, "e": 8822, "s": 8805, "text": "class Solution {" }, { "code": null, "e": 9882, "s": 8822, "text": " public boolean isValid(String s) { // Write your code here if(s.compareTo(\"\")==0){ return false; } if(s.length()<7)return false; int dot = 0; for(int i=0;i<s.length();i++){ if('.' == s.charAt(i)){ dot++; } } if(dot!=3)return false; String S = s.replace(\".\",\"@\"); String[] str = S.split(\"@\"); if(str.length != 4){ return false; } boolean ans = true; for(int i=0;i<4;i++){ if(str[i].length()<4){ try{ int n = Integer.parseInt(str[i]); if(0<=n && n<=255){ if(str[i].length()>1 && (n>=0 && n<=9))return false; continue; } else{ return false; } } catch(Exception e){ return false; } } else{ return false; } } return true; }}" }, { "code": null, "e": 9884, "s": 9882, "text": "0" }, { "code": null, "e": 9909, "s": 9884, "text": "minipandey3322 weeks ago" }, { "code": null, "e": 9956, "s": 9909, "text": "//Anybody tells me what's wrong in below code." }, { "code": null, "e": 10647, "s": 9956, "text": "int isValid(string s) { // code here int dot=0; int r=0; for(int i=0; i<s.length(); i++) // 222.111.111.111 { if(s[i]>=0 && s[i] <= 9) { int x = atoi(s[i]); r = r*10 + x; } else if(s[i] == '.') { dot++; if(r>255 || r<0) return 0; r=0; } else return 0; } if(dot==3) return 1; else return 0; }};" }, { "code": null, "e": 10650, "s": 10647, "text": "+1" }, { "code": null, "e": 10675, "s": 10650, "text": "dtu_top_coder2 weeks ago" }, { "code": null, "e": 10701, "s": 10675, "text": "1st Try Solution Accepted" }, { "code": null, "e": 10712, "s": 10701, "text": "C++ Code :" }, { "code": null, "e": 11675, "s": 10714, "text": "class Solution { public: int isValid(string s) { string str=\"\"; int count=0; s.push_back('.'); for(int i=0;i<s.size();i++) { if(s[i]=='.') { if(!check(str)) return false; str=\"\"; count++; } else { str+=s[i]; } } if(count==4) return true; return false; } bool check(string s) { if(s==\"\" || (s[0]=='0' && s.size()>1)) return false; int a=atoi(s.c_str()); for(auto c:s) if(c<'0' || c>'9') return false; if(a>=0 && a<=255) return true; return false; }};" }, { "code": null, "e": 11821, "s": 11675, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 11857, "s": 11821, "text": " Login to access your submissions. " }, { "code": null, "e": 11867, "s": 11857, "text": "\nProblem\n" }, { "code": null, "e": 11877, "s": 11867, "text": "\nContest\n" }, { "code": null, "e": 11940, "s": 11877, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 12088, "s": 11940, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 12296, "s": 12088, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 12402, "s": 12296, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Shell Script to Check if Every Passed Argument is a File or Directory
04 Oct, 2021 While automating things in Linux we always work on the file and directories. And sometimes we pass the files and directories as the arguments to the shell scripts. And we have to determine whether the provided argument is a file or a directory, and today we are going to see how to check whether provide argument is the file or directory. Before moving on further we need to know something about the file comparison in the bash shell which we can use with the if statement. Here is the same option that can be used with the if statement in bash shell-like -d file - This option determines whether the provided file exists on the system and is it the directory. -f file - This option determine the whether provided file is exist on the system and is it file. Algorithm: First check the provides argument is the directory or not using the if statement using the -d option for the first argument using the $1 parameter. If it is true then print the message that the provided argument is the directory.If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then the print the message that provided the argument is the file.If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory. First check the provides argument is the directory or not using the if statement using the -d option for the first argument using the $1 parameter. If it is true then print the message that the provided argument is the directory. If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then the print the message that provided the argument is the file. If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory. Script: #!/bin/sh #Using -d option we are checking whether the first argument is a directory or not. #$1 refers to the first argument if [ -d $1 ] then echo "The provided argument is the directory." #Using -f option we are checking whether the first argument is a file or not. elif [ -f $1 ] then echo "The provided argument is the file." #if the provided argument is not file and directory then it does not exist on the system. else echo "The given argument does not exist on the file system." fi To Execute the Script use the following commands: ./script_name.sh filename # For files ./script_name.sh foldername # For folders Now let’s do the same thing for all provided arguments. We traverse through all arguments using the for loop with $@ variable.$@ refers to all of a shell script’s command-line arguments. Use the above algorithm with the for loop in the shell as follows: Algorithm: Use for loop in Bash and traverse through all passed arguments using $@ argument.Inside for loop check, the provides argument is the directory or not using the if statement using the -d option for the first argument using $1 parameter. If it is true then print the message that the provided argument is the directory.If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then print a message that provided the argument in the file.If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory. Use for loop in Bash and traverse through all passed arguments using $@ argument. Inside for loop check, the provides argument is the directory or not using the if statement using the -d option for the first argument using $1 parameter. If it is true then print the message that the provided argument is the directory. If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then print a message that provided the argument in the file. If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory. Script: #!/bin/sh #traversing through all arguments using for loop for i in "$@" do #Using -d option we are checking whether the first argument is a directory or not. if [ -d $i ] then echo "The provided argument $i is the directory." #Using -f option we are checking whether the first argument is a file or not. elif [ -f $i ] then echo "The provided argument $i is the file." #if the provided argument is not file and directory then it does not exist on the system. else echo "The given argument does not exist on the file system." fi done To Execute the Script use the following commands: ./script.sh filename folder #for both files and folders simmytarika5 Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2021" }, { "code": null, "e": 584, "s": 28, "text": "While automating things in Linux we always work on the file and directories. And sometimes we pass the files and directories as the arguments to the shell scripts. And we have to determine whether the provided argument is a file or a directory, and today we are going to see how to check whether provide argument is the file or directory. Before moving on further we need to know something about the file comparison in the bash shell which we can use with the if statement. Here is the same option that can be used with the if statement in bash shell-like" }, { "code": null, "e": 792, "s": 584, "text": "-d file - This option determines whether the provided \nfile exists on the system and is it the directory.\n-f file - This option determine the whether provided \nfile is exist on the system and is it file." }, { "code": null, "e": 803, "s": 792, "text": "Algorithm:" }, { "code": null, "e": 1444, "s": 803, "text": "First check the provides argument is the directory or not using the if statement using the -d option for the first argument using the $1 parameter. If it is true then print the message that the provided argument is the directory.If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then the print the message that provided the argument is the file.If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory." }, { "code": null, "e": 1674, "s": 1444, "text": "First check the provides argument is the directory or not using the if statement using the -d option for the first argument using the $1 parameter. If it is true then print the message that the provided argument is the directory." }, { "code": null, "e": 1902, "s": 1674, "text": "If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then the print the message that provided the argument is the file." }, { "code": null, "e": 2087, "s": 1902, "text": "If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory." }, { "code": null, "e": 2095, "s": 2087, "text": "Script:" }, { "code": null, "e": 2612, "s": 2095, "text": "#!/bin/sh\n#Using -d option we are checking whether the first argument is a directory or not.\n#$1 refers to the first argument\nif [ -d $1 ]\nthen\n echo \"The provided argument is the directory.\"\n#Using -f option we are checking whether the first argument is a file or not.\nelif [ -f $1 ]\nthen\n echo \"The provided argument is the file.\"\n#if the provided argument is not file and directory then it does not exist on the system. \nelse\n echo \"The given argument does not exist on the file system.\"\nfi" }, { "code": null, "e": 2662, "s": 2612, "text": "To Execute the Script use the following commands:" }, { "code": null, "e": 2743, "s": 2662, "text": "./script_name.sh filename # For files\n./script_name.sh foldername # For folders" }, { "code": null, "e": 2997, "s": 2743, "text": "Now let’s do the same thing for all provided arguments. We traverse through all arguments using the for loop with $@ variable.$@ refers to all of a shell script’s command-line arguments. Use the above algorithm with the for loop in the shell as follows:" }, { "code": null, "e": 3008, "s": 2997, "text": "Algorithm:" }, { "code": null, "e": 3731, "s": 3008, "text": "Use for loop in Bash and traverse through all passed arguments using $@ argument.Inside for loop check, the provides argument is the directory or not using the if statement using the -d option for the first argument using $1 parameter. If it is true then print the message that the provided argument is the directory.If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then print a message that provided the argument in the file.If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory." }, { "code": null, "e": 3813, "s": 3731, "text": "Use for loop in Bash and traverse through all passed arguments using $@ argument." }, { "code": null, "e": 4050, "s": 3813, "text": "Inside for loop check, the provides argument is the directory or not using the if statement using the -d option for the first argument using $1 parameter. If it is true then print the message that the provided argument is the directory." }, { "code": null, "e": 4272, "s": 4050, "text": "If the argument is not the directory then check it for the file. Use the -f option and if statement for the first argument using the $1 parameter. If it is true then print a message that provided the argument in the file." }, { "code": null, "e": 4457, "s": 4272, "text": "If both conditions are false then it is clear that the provided argument is neither file and nor directory. Then print the message the given argument is neither file and nor directory." }, { "code": null, "e": 4465, "s": 4457, "text": "Script:" }, { "code": null, "e": 5130, "s": 4465, "text": "#!/bin/sh\n\n#traversing through all arguments using for loop\nfor i in \"$@\"\ndo\n #Using -d option we are checking whether the first argument is a directory or not.\n if [ -d $i ]\n then\n echo \"The provided argument $i is the directory.\"\n #Using -f option we are checking whether the first argument is a file or not.\n elif [ -f $i ]\n then\n echo \"The provided argument $i is the file.\"\n #if the provided argument is not file and directory then it does not exist on the system. \n else\n echo \"The given argument does not exist on the file system.\"\n fi\ndone" }, { "code": null, "e": 5180, "s": 5130, "text": "To Execute the Script use the following commands:" }, { "code": null, "e": 5236, "s": 5180, "text": "./script.sh filename folder #for both files and folders" }, { "code": null, "e": 5249, "s": 5236, "text": "simmytarika5" }, { "code": null, "e": 5256, "s": 5249, "text": "Picked" }, { "code": null, "e": 5269, "s": 5256, "text": "Shell Script" }, { "code": null, "e": 5280, "s": 5269, "text": "Linux-Unix" } ]
Python Program for Fibonacci numbers
24 May, 2022 The Fibonacci numbers are the numbers in the following integer sequence.0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. Method 1 ( Use recursion ) : Python3 # Function for nth Fibonacci numberdef Fibonacci(n): # Check if input is 0 then it will # print incorrect input if n < 0: print("Incorrect input") # Check if n is 0 # then it will return 0 elif n == 0: return 0 # Check if n is 1,2 # it will return 1 elif n == 1 or n == 2: return 1 else: return Fibonacci(n-1) + Fibonacci(n-2) # Driver Programprint(Fibonacci(9)) # This code is contributed by Saket Modi# then corrected and improved by Himanshu Kanojiya 34 Method 2 ( Use Dynamic Programming ) : Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Python3 # Function for nth fibonacci# number - Dynamic Programming# Taking 1st two fibonacci numbers as 0 and 1FibArray = [0, 1] def fibonacci(n): # Check is n is less # than 0 if n < 0: print("Incorrect input") # Check is n is less # than len(FibArray) elif n < len(FibArray): return FibArray[n] else: FibArray.append(fibonacci(n - 1) + fibonacci(n - 2)) return FibArray[n] # Driver Programprint(fibonacci(9)) # This code is contributed by Saket Modi 34 Method 3 ( Space Optimized): Python # Function for nth fibonacci# number - Space Optimisation# Taking 1st two fibonacci numbers as 0 and 1 def fibonacci(n): a = 0 b = 1 # Check is n is less # than 0 if n < 0: print("Incorrect input") # Check is n is equal # to 0 elif n == 0: return 0 # Check if n is equal to 1 elif n == 1: return b else: for i in range(1, n): c = a + b a = b b = c return b # Driver Programprint(fibonacci(9)) # This code is contributed by Saket Modi# Then corrected and improved by Himanshu Kanojiya 34 Please refer complete article on Program for Fibonacci numbers for more details! grohith70 himanshukanojiya adnanirshad158 akshaysingh98088 simranarora5sos amartyaghoshgfg andreyneyvanov Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to add two numbers Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python | Convert set into a list Appending to list in Python dictionary Python | Convert a list into a tuple Python program to find sum of elements in list Python Program for Bubble Sort Add a key:value pair to dictionary in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2022" }, { "code": null, "e": 277, "s": 52, "text": "The Fibonacci numbers are the numbers in the following integer sequence.0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation " }, { "code": null, "e": 298, "s": 277, "text": " Fn = Fn-1 + Fn-2" }, { "code": null, "e": 317, "s": 298, "text": "with seed values " }, { "code": null, "e": 339, "s": 317, "text": " F0 = 0 and F1 = 1." }, { "code": null, "e": 370, "s": 339, "text": "Method 1 ( Use recursion ) : " }, { "code": null, "e": 378, "s": 370, "text": "Python3" }, { "code": "# Function for nth Fibonacci numberdef Fibonacci(n): # Check if input is 0 then it will # print incorrect input if n < 0: print(\"Incorrect input\") # Check if n is 0 # then it will return 0 elif n == 0: return 0 # Check if n is 1,2 # it will return 1 elif n == 1 or n == 2: return 1 else: return Fibonacci(n-1) + Fibonacci(n-2) # Driver Programprint(Fibonacci(9)) # This code is contributed by Saket Modi# then corrected and improved by Himanshu Kanojiya", "e": 896, "s": 378, "text": null }, { "code": null, "e": 900, "s": 896, "text": "34\n" }, { "code": null, "e": 941, "s": 900, "text": "Method 2 ( Use Dynamic Programming ) : " }, { "code": null, "e": 950, "s": 941, "text": "Chapters" }, { "code": null, "e": 977, "s": 950, "text": "descriptions off, selected" }, { "code": null, "e": 1027, "s": 977, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1050, "s": 1027, "text": "captions off, selected" }, { "code": null, "e": 1058, "s": 1050, "text": "English" }, { "code": null, "e": 1082, "s": 1058, "text": "This is a modal window." }, { "code": null, "e": 1151, "s": 1082, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1173, "s": 1151, "text": "End of dialog window." }, { "code": null, "e": 1181, "s": 1173, "text": "Python3" }, { "code": "# Function for nth fibonacci# number - Dynamic Programming# Taking 1st two fibonacci numbers as 0 and 1FibArray = [0, 1] def fibonacci(n): # Check is n is less # than 0 if n < 0: print(\"Incorrect input\") # Check is n is less # than len(FibArray) elif n < len(FibArray): return FibArray[n] else: FibArray.append(fibonacci(n - 1) + fibonacci(n - 2)) return FibArray[n] # Driver Programprint(fibonacci(9)) # This code is contributed by Saket Modi", "e": 1693, "s": 1181, "text": null }, { "code": null, "e": 1697, "s": 1693, "text": "34\n" }, { "code": null, "e": 1728, "s": 1697, "text": "Method 3 ( Space Optimized): " }, { "code": null, "e": 1735, "s": 1728, "text": "Python" }, { "code": "# Function for nth fibonacci# number - Space Optimisation# Taking 1st two fibonacci numbers as 0 and 1 def fibonacci(n): a = 0 b = 1 # Check is n is less # than 0 if n < 0: print(\"Incorrect input\") # Check is n is equal # to 0 elif n == 0: return 0 # Check if n is equal to 1 elif n == 1: return b else: for i in range(1, n): c = a + b a = b b = c return b # Driver Programprint(fibonacci(9)) # This code is contributed by Saket Modi# Then corrected and improved by Himanshu Kanojiya", "e": 2341, "s": 1735, "text": null }, { "code": null, "e": 2345, "s": 2341, "text": "34\n" }, { "code": null, "e": 2427, "s": 2345, "text": "Please refer complete article on Program for Fibonacci numbers for more details! " }, { "code": null, "e": 2437, "s": 2427, "text": "grohith70" }, { "code": null, "e": 2454, "s": 2437, "text": "himanshukanojiya" }, { "code": null, "e": 2469, "s": 2454, "text": "adnanirshad158" }, { "code": null, "e": 2486, "s": 2469, "text": "akshaysingh98088" }, { "code": null, "e": 2502, "s": 2486, "text": "simranarora5sos" }, { "code": null, "e": 2518, "s": 2502, "text": "amartyaghoshgfg" }, { "code": null, "e": 2533, "s": 2518, "text": "andreyneyvanov" }, { "code": null, "e": 2549, "s": 2533, "text": "Python Programs" }, { "code": null, "e": 2647, "s": 2549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2681, "s": 2647, "text": "Python program to add two numbers" }, { "code": null, "e": 2722, "s": 2681, "text": "Python Program for factorial of a number" }, { "code": null, "e": 2777, "s": 2722, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 2823, "s": 2777, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 2856, "s": 2823, "text": "Python | Convert set into a list" }, { "code": null, "e": 2895, "s": 2856, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 2932, "s": 2895, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 2979, "s": 2932, "text": "Python program to find sum of elements in list" }, { "code": null, "e": 3010, "s": 2979, "text": "Python Program for Bubble Sort" } ]
Publish Jupiter Notebook File as Web App
08 Jan, 2021 In Jupyter Notebook we always build some models, do some plotting on given Dataset, and many more. But we can also publish our Jupyter file as a web-app. It will show only the output of each code rather than showing the source code. In this article, we will look into the process of publishing a Jupyter Notebook file on Github as a Web-app. To convert Jupyter Notebook file into an HTML file follow the below steps: Step 1: Open Jupyter Notebook and Click the three-dot menu in the top left corner and select Python. Step 2: Write some useful code. It may be Markdown or Code shell. For example, here we have written some markdown cells, one arithmetic code, and a CSV file’s data read code. Markdown Cell Code Cell Step 3: Make a copy of the notebook. Step 4: Remove all Markdown cells that are not necessary. Step 5: Run only those cells whose output you want to display as a web-app. Because only display output will be shown in our web-app. Step 6: To prevent other outputs from being displayed, just add a semicolon at the end of the code and rerun the kernel. For example, here, to prevent the display of the output of data.head(), we have added a “;” at the line of code. Step 7: Save your notebook. Note that it is in the same directory as your Jupyter lab installation. Step 8: Open the terminal and run the below command: jupyter nbconvert Your-File-Name.ipynb --no-input --no-prompt You will now have a file named ‘Your-File-Name.html’ After the HTML file is generated, publish it on Github using the below steps: Step 1: Create a GitHub repository (index.html) and ensure that you initialize it with a read.me file. Login to your GitHub account Go to Home Page Click on the + Nav option Create a new repository. Step 2: Once the repository is ready, rename our GeeksForGeeks.html (Which we have created in step 1) file to ‘index.html’. Make sure your file and dashboard name is the same else it will not show up. Step 3: Once all files are successfully uploaded, remove all content from the read.me file. (Do not delete the file, it just needs to be empty).To upload your file: Go to your repository. Click on Add file. Upload the files. Step 4: Go to the settings of your repository and enable GitHub pages. To do so follow the below steps: Go to setting. Select Branch option as main. Click on save. This will publish our website. Step 5: Visit the link of the newly created GitHub page and your dashboard should appear. Note: It is mandatory to publish your HTML file as index.html. Otherwise, you may receive erroneous output. Output: Technical Scripter 2020 Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jan, 2021" }, { "code": null, "e": 286, "s": 52, "text": "In Jupyter Notebook we always build some models, do some plotting on given Dataset, and many more. But we can also publish our Jupyter file as a web-app. It will show only the output of each code rather than showing the source code. " }, { "code": null, "e": 395, "s": 286, "text": "In this article, we will look into the process of publishing a Jupyter Notebook file on Github as a Web-app." }, { "code": null, "e": 470, "s": 395, "text": "To convert Jupyter Notebook file into an HTML file follow the below steps:" }, { "code": null, "e": 571, "s": 470, "text": "Step 1: Open Jupyter Notebook and Click the three-dot menu in the top left corner and select Python." }, { "code": null, "e": 746, "s": 571, "text": "Step 2: Write some useful code. It may be Markdown or Code shell. For example, here we have written some markdown cells, one arithmetic code, and a CSV file’s data read code." }, { "code": null, "e": 760, "s": 746, "text": "Markdown Cell" }, { "code": null, "e": 770, "s": 760, "text": "Code Cell" }, { "code": null, "e": 807, "s": 770, "text": "Step 3: Make a copy of the notebook." }, { "code": null, "e": 865, "s": 807, "text": "Step 4: Remove all Markdown cells that are not necessary." }, { "code": null, "e": 999, "s": 865, "text": "Step 5: Run only those cells whose output you want to display as a web-app. Because only display output will be shown in our web-app." }, { "code": null, "e": 1233, "s": 999, "text": "Step 6: To prevent other outputs from being displayed, just add a semicolon at the end of the code and rerun the kernel. For example, here, to prevent the display of the output of data.head(), we have added a “;” at the line of code." }, { "code": null, "e": 1333, "s": 1233, "text": "Step 7: Save your notebook. Note that it is in the same directory as your Jupyter lab installation." }, { "code": null, "e": 1386, "s": 1333, "text": "Step 8: Open the terminal and run the below command:" }, { "code": null, "e": 1448, "s": 1386, "text": "jupyter nbconvert Your-File-Name.ipynb --no-input --no-prompt" }, { "code": null, "e": 1502, "s": 1448, "text": " You will now have a file named ‘Your-File-Name.html’" }, { "code": null, "e": 1580, "s": 1502, "text": "After the HTML file is generated, publish it on Github using the below steps:" }, { "code": null, "e": 1683, "s": 1580, "text": "Step 1: Create a GitHub repository (index.html) and ensure that you initialize it with a read.me file." }, { "code": null, "e": 1712, "s": 1683, "text": "Login to your GitHub account" }, { "code": null, "e": 1728, "s": 1712, "text": "Go to Home Page" }, { "code": null, "e": 1754, "s": 1728, "text": "Click on the + Nav option" }, { "code": null, "e": 1779, "s": 1754, "text": "Create a new repository." }, { "code": null, "e": 1980, "s": 1779, "text": "Step 2: Once the repository is ready, rename our GeeksForGeeks.html (Which we have created in step 1) file to ‘index.html’. Make sure your file and dashboard name is the same else it will not show up." }, { "code": null, "e": 2146, "s": 1980, "text": "Step 3: Once all files are successfully uploaded, remove all content from the read.me file. (Do not delete the file, it just needs to be empty).To upload your file: " }, { "code": null, "e": 2169, "s": 2146, "text": "Go to your repository." }, { "code": null, "e": 2188, "s": 2169, "text": "Click on Add file." }, { "code": null, "e": 2206, "s": 2188, "text": "Upload the files." }, { "code": null, "e": 2310, "s": 2206, "text": "Step 4: Go to the settings of your repository and enable GitHub pages. To do so follow the below steps:" }, { "code": null, "e": 2325, "s": 2310, "text": "Go to setting." }, { "code": null, "e": 2355, "s": 2325, "text": "Select Branch option as main." }, { "code": null, "e": 2370, "s": 2355, "text": "Click on save." }, { "code": null, "e": 2401, "s": 2370, "text": "This will publish our website." }, { "code": null, "e": 2491, "s": 2401, "text": "Step 5: Visit the link of the newly created GitHub page and your dashboard should appear." }, { "code": null, "e": 2605, "s": 2491, "text": "Note: It is mandatory to publish your HTML file as index.html.\n Otherwise, you may receive erroneous output." }, { "code": null, "e": 2613, "s": 2605, "text": "Output:" }, { "code": null, "e": 2637, "s": 2613, "text": "Technical Scripter 2020" }, { "code": null, "e": 2656, "s": 2637, "text": "Technical Scripter" }, { "code": null, "e": 2665, "s": 2656, "text": "TechTips" } ]
Sort a string according to the order defined by another string
06 Jul, 2022 Given two strings (of lowercase letters), a pattern, and a string. The task is to sort strings according to the order defined by the pattern. It may be assumed that the pattern has all characters of the string and all characters in the pattern appear only once. Examples: Input : pat = "bca", str = "abc" Output : str = "bca" Input : pat = "bxyzca", str = "abcabcabc" Output : str = "bbbcccaaa" Input : pat = "wcyuogmlrdfphitxjakqvzbnes", str = "jcdokai" Output : str = "codijak" Approach 1: The idea is to first count occurrences of all characters in str and store these counts in a count array. Then traverse pattern from left to right, and for each character pat[i], see how many times it appears in count array and copy this character these many times to str.Below is the implementation of the above idea. Implementation: C++ Java Python3 C# Javascript // C++ program to sort a string according to the// order defined by a pattern string#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Sort str according to the order defined by pattern.void sortByPattern(string& str, string pat){ // Create a count array store count of characters in str. int count[MAX_CHAR] = { 0 }; // Count number of occurrences of each character // in str. for (int i = 0; i < str.length(); i++) count[str[i] - 'a']++; // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.length(); i++) for (int j = 0; j < count[pat[i] - 'a']; j++) str[index++] = pat[i];} // Driver codeint main(){ string pat = "bca"; string str = "abc"; sortByPattern(str, pat); cout << str; return 0;} // Java program to sort a string according to the// order defined by a pattern string class GFG { static int MAX_CHAR = 26; // Sort str according to the order defined by pattern. static void sortByPattern(char[] str, char[] pat) { // Create a count array stor // count of characters in str. int count[] = new int[MAX_CHAR]; // Count number of occurrences of // each character in str. for (int i = 0; i < str.length; i++) { count[str[i] - 'a']++; } // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.length; i++) { for (int j = 0; j < count[pat[i] - 'a']; j++) { str[index++] = pat[i]; } } } // Driver code public static void main(String args[]) { char[] pat = "bca".toCharArray(); char[] str = "abc".toCharArray(); sortByPattern(str, pat); System.out.println(String.valueOf(str)); }} // This code has been contributed by 29AjayKumar # Python3 program to sort a string according to# the order defined by a pattern stringMAX_CHAR = 26 # Sort str according to the order defined by pattern.def sortByPattern(str, pat): global MAX_CHAR # Create a count array store count # of characters in str. count = [0] * MAX_CHAR # Count number of occurrences of # each character in str. for i in range (0, len(str)): count[ord(str[i]) - 97] += 1 # Traverse the pattern and print every characters # same number of times as it appears in str. This # loop takes O(m + n) time where m is length of # pattern and n is length of str. index = 0; str = "" for i in range (0, len(pat)): j = 0 while(j < count[ord(pat[i]) - ord('a')]): str += pat[i] j = j + 1 index += 1 return str # Driver codepat = "bca"str = "abc"print(sortByPattern(str, pat)) # This code is contributed by ihritik // C# program to sort a string according to the// order defined by a pattern stringusing System; class GFG { static int MAX_CHAR = 26; // Sort str according to the order defined by pattern. static void sortByPattern(char[] str, char[] pat) { // Create a count array stor // count of characters in str. int[] count = new int[MAX_CHAR]; // Count number of occurrences of // each character in str. for (int i = 0; i < str.Length; i++) { count[str[i] - 'a']++; } // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.Length; i++) { for (int j = 0; j < count[pat[i] - 'a']; j++) { str[index++] = pat[i]; } } } // Driver code public static void Main(String[] args) { char[] pat = "bca".ToCharArray(); char[] str = "abc".ToCharArray(); sortByPattern(str, pat); Console.WriteLine(String.Join("", str)); }} /* This code contributed by PrinciRaj1992 */ <script>// Javascript program to sort a string according to the// order defined by a pattern stringlet MAX_CHAR = 26; // Sort str according to the order defined by pattern.function sortByPattern(str,pat){ // Create a count array stor // count of characters in str. let count = new Array(MAX_CHAR); for(let i = 0; i < MAX_CHAR; i++) { count[i] = 0; } // Count number of occurrences of // each character in str. for (let i = 0; i < str.length; i++) { count[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. let index = 0; for (let i = 0; i < pat.length; i++) { for (let j = 0; j < count[pat[i].charCodeAt(0) - 'a'.charCodeAt(0)]; j++) { str[index++] = pat[i]; } }} // Driver codelet pat = "bca".split("");let str = "abc".split("");sortByPattern(str, pat);document.write((str).join("")); // This code is contributed by rag2127</script> bca Time complexity: O(m+n) where m is the length of the pattern and n is the length of str.Auxiliary Space: O(1) Approach 2: Using STL We can pass a comparator to the sort() function in C++ and sort the string according to the pattern. C++ Javascript #include <bits/stdc++.h>using namespace std; // Declaring a vector globally that stores which character// is occurring firstvector<int> position(26, -1); //Comparator functionbool cmp(char& char1, char& char2){ return position[char1 - 'a'] < position[char2 - 'a'];} int main(){ // Pattern string pat = "wcyuogmlrdfphitxjakqvzbnes"; for (int i = 0; i < pat.length(); i++) { if (position[pat[i] - 'a'] == -1) position[pat[i] - 'a'] = i; } // String to be sorted string str = "jcdokai"; // Passing a comparator to sort function sort(str.begin(), str.end(), cmp); cout << str;} <script> // Declaring a vector globally that stores which character// is occurring firstlet position = new Array(26).fill(-1); //Comparator functionfunction cmp(char1, char2){ return position[char1.charCodeAt(0) - 'a'.charCodeAt(0)] - position[char2.charCodeAt(0) - 'a'.charCodeAt(0)];} // driver code // Patternlet pat = "wcyuogmlrdfphitxjakqvzbnes"; for (let i = 0; i <br pat.length; i++) { if (position[pat.charCodeAt(i) - 'a'.charCodeAt(0)] == -1) position[pat.charCodeAt(i) - 'a'.charCodeAt(0)] = i;} // String to be sortedlet str = "jcdokai"; // Passing a comparator to sort functionstr = str.split("").sort(cmp).join("");document.write(str,"</br>"); // This code is contributed by Shinjan Patra </script> codijak Time complexity: O(m+nlogn) where m is the length of the pattern and n is the length of str. Auxiliary Space: O(1) Exercise: In the above solution, it is assumed that the pattern has all characters of str. Consider a modified version where the pattern may not have all characters and the task is to put all remaining characters (in the string but not in the pattern) at the end. The remaining characters need to be put in alphabetically sorted order.Hint: In the second loop, when increasing the index and putting the character in str, we can also decrease the count at that time. And finally, we traverse the count array to put the remaining characters in alphabetically sorted order. This article is contributed by Sanjay Khadda. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 29AjayKumar princiraj1992 ihritik nidhi_biet rag2127 bhuwanesh sweetyty shinjanpatra anandkumarshivam2266 hardikkoriintern Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 314, "s": 52, "text": "Given two strings (of lowercase letters), a pattern, and a string. The task is to sort strings according to the order defined by the pattern. It may be assumed that the pattern has all characters of the string and all characters in the pattern appear only once." }, { "code": null, "e": 325, "s": 314, "text": "Examples: " }, { "code": null, "e": 538, "s": 325, "text": "Input : pat = \"bca\", str = \"abc\"\nOutput : str = \"bca\"\n\nInput : pat = \"bxyzca\", str = \"abcabcabc\"\nOutput : str = \"bbbcccaaa\"\n\nInput : pat = \"wcyuogmlrdfphitxjakqvzbnes\", str = \"jcdokai\"\nOutput : str = \"codijak\"" }, { "code": null, "e": 869, "s": 538, "text": "Approach 1: The idea is to first count occurrences of all characters in str and store these counts in a count array. Then traverse pattern from left to right, and for each character pat[i], see how many times it appears in count array and copy this character these many times to str.Below is the implementation of the above idea. " }, { "code": null, "e": 885, "s": 869, "text": "Implementation:" }, { "code": null, "e": 889, "s": 885, "text": "C++" }, { "code": null, "e": 894, "s": 889, "text": "Java" }, { "code": null, "e": 902, "s": 894, "text": "Python3" }, { "code": null, "e": 905, "s": 902, "text": "C#" }, { "code": null, "e": 916, "s": 905, "text": "Javascript" }, { "code": "// C++ program to sort a string according to the// order defined by a pattern string#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Sort str according to the order defined by pattern.void sortByPattern(string& str, string pat){ // Create a count array store count of characters in str. int count[MAX_CHAR] = { 0 }; // Count number of occurrences of each character // in str. for (int i = 0; i < str.length(); i++) count[str[i] - 'a']++; // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.length(); i++) for (int j = 0; j < count[pat[i] - 'a']; j++) str[index++] = pat[i];} // Driver codeint main(){ string pat = \"bca\"; string str = \"abc\"; sortByPattern(str, pat); cout << str; return 0;}", "e": 1877, "s": 916, "text": null }, { "code": "// Java program to sort a string according to the// order defined by a pattern string class GFG { static int MAX_CHAR = 26; // Sort str according to the order defined by pattern. static void sortByPattern(char[] str, char[] pat) { // Create a count array stor // count of characters in str. int count[] = new int[MAX_CHAR]; // Count number of occurrences of // each character in str. for (int i = 0; i < str.length; i++) { count[str[i] - 'a']++; } // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.length; i++) { for (int j = 0; j < count[pat[i] - 'a']; j++) { str[index++] = pat[i]; } } } // Driver code public static void main(String args[]) { char[] pat = \"bca\".toCharArray(); char[] str = \"abc\".toCharArray(); sortByPattern(str, pat); System.out.println(String.valueOf(str)); }} // This code has been contributed by 29AjayKumar", "e": 3090, "s": 1877, "text": null }, { "code": "# Python3 program to sort a string according to# the order defined by a pattern stringMAX_CHAR = 26 # Sort str according to the order defined by pattern.def sortByPattern(str, pat): global MAX_CHAR # Create a count array store count # of characters in str. count = [0] * MAX_CHAR # Count number of occurrences of # each character in str. for i in range (0, len(str)): count[ord(str[i]) - 97] += 1 # Traverse the pattern and print every characters # same number of times as it appears in str. This # loop takes O(m + n) time where m is length of # pattern and n is length of str. index = 0; str = \"\" for i in range (0, len(pat)): j = 0 while(j < count[ord(pat[i]) - ord('a')]): str += pat[i] j = j + 1 index += 1 return str # Driver codepat = \"bca\"str = \"abc\"print(sortByPattern(str, pat)) # This code is contributed by ihritik", "e": 4046, "s": 3090, "text": null }, { "code": "// C# program to sort a string according to the// order defined by a pattern stringusing System; class GFG { static int MAX_CHAR = 26; // Sort str according to the order defined by pattern. static void sortByPattern(char[] str, char[] pat) { // Create a count array stor // count of characters in str. int[] count = new int[MAX_CHAR]; // Count number of occurrences of // each character in str. for (int i = 0; i < str.Length; i++) { count[str[i] - 'a']++; } // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.Length; i++) { for (int j = 0; j < count[pat[i] - 'a']; j++) { str[index++] = pat[i]; } } } // Driver code public static void Main(String[] args) { char[] pat = \"bca\".ToCharArray(); char[] str = \"abc\".ToCharArray(); sortByPattern(str, pat); Console.WriteLine(String.Join(\"\", str)); }} /* This code contributed by PrinciRaj1992 */", "e": 5266, "s": 4046, "text": null }, { "code": "<script>// Javascript program to sort a string according to the// order defined by a pattern stringlet MAX_CHAR = 26; // Sort str according to the order defined by pattern.function sortByPattern(str,pat){ // Create a count array stor // count of characters in str. let count = new Array(MAX_CHAR); for(let i = 0; i < MAX_CHAR; i++) { count[i] = 0; } // Count number of occurrences of // each character in str. for (let i = 0; i < str.length; i++) { count[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. let index = 0; for (let i = 0; i < pat.length; i++) { for (let j = 0; j < count[pat[i].charCodeAt(0) - 'a'.charCodeAt(0)]; j++) { str[index++] = pat[i]; } }} // Driver codelet pat = \"bca\".split(\"\");let str = \"abc\".split(\"\");sortByPattern(str, pat);document.write((str).join(\"\")); // This code is contributed by rag2127</script>", "e": 6462, "s": 5266, "text": null }, { "code": null, "e": 6466, "s": 6462, "text": "bca" }, { "code": null, "e": 6578, "s": 6466, "text": "Time complexity: O(m+n) where m is the length of the pattern and n is the length of str.Auxiliary Space: O(1) " }, { "code": null, "e": 6600, "s": 6578, "text": "Approach 2: Using STL" }, { "code": null, "e": 6701, "s": 6600, "text": "We can pass a comparator to the sort() function in C++ and sort the string according to the pattern." }, { "code": null, "e": 6705, "s": 6701, "text": "C++" }, { "code": null, "e": 6716, "s": 6705, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Declaring a vector globally that stores which character// is occurring firstvector<int> position(26, -1); //Comparator functionbool cmp(char& char1, char& char2){ return position[char1 - 'a'] < position[char2 - 'a'];} int main(){ // Pattern string pat = \"wcyuogmlrdfphitxjakqvzbnes\"; for (int i = 0; i < pat.length(); i++) { if (position[pat[i] - 'a'] == -1) position[pat[i] - 'a'] = i; } // String to be sorted string str = \"jcdokai\"; // Passing a comparator to sort function sort(str.begin(), str.end(), cmp); cout << str;}", "e": 7342, "s": 6716, "text": null }, { "code": "<script> // Declaring a vector globally that stores which character// is occurring firstlet position = new Array(26).fill(-1); //Comparator functionfunction cmp(char1, char2){ return position[char1.charCodeAt(0) - 'a'.charCodeAt(0)] - position[char2.charCodeAt(0) - 'a'.charCodeAt(0)];} // driver code // Patternlet pat = \"wcyuogmlrdfphitxjakqvzbnes\"; for (let i = 0; i <br pat.length; i++) { if (position[pat.charCodeAt(i) - 'a'.charCodeAt(0)] == -1) position[pat.charCodeAt(i) - 'a'.charCodeAt(0)] = i;} // String to be sortedlet str = \"jcdokai\"; // Passing a comparator to sort functionstr = str.split(\"\").sort(cmp).join(\"\");document.write(str,\"</br>\"); // This code is contributed by Shinjan Patra </script>", "e": 8074, "s": 7342, "text": null }, { "code": null, "e": 8082, "s": 8074, "text": "codijak" }, { "code": null, "e": 8198, "s": 8082, "text": "Time complexity: O(m+nlogn) where m is the length of the pattern and n is the length of str. Auxiliary Space: O(1)" }, { "code": null, "e": 8769, "s": 8198, "text": "Exercise: In the above solution, it is assumed that the pattern has all characters of str. Consider a modified version where the pattern may not have all characters and the task is to put all remaining characters (in the string but not in the pattern) at the end. The remaining characters need to be put in alphabetically sorted order.Hint: In the second loop, when increasing the index and putting the character in str, we can also decrease the count at that time. And finally, we traverse the count array to put the remaining characters in alphabetically sorted order." }, { "code": null, "e": 9067, "s": 8769, "text": "This article is contributed by Sanjay Khadda. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 9079, "s": 9067, "text": "29AjayKumar" }, { "code": null, "e": 9093, "s": 9079, "text": "princiraj1992" }, { "code": null, "e": 9101, "s": 9093, "text": "ihritik" }, { "code": null, "e": 9112, "s": 9101, "text": "nidhi_biet" }, { "code": null, "e": 9120, "s": 9112, "text": "rag2127" }, { "code": null, "e": 9130, "s": 9120, "text": "bhuwanesh" }, { "code": null, "e": 9139, "s": 9130, "text": "sweetyty" }, { "code": null, "e": 9152, "s": 9139, "text": "shinjanpatra" }, { "code": null, "e": 9173, "s": 9152, "text": "anandkumarshivam2266" }, { "code": null, "e": 9190, "s": 9173, "text": "hardikkoriintern" }, { "code": null, "e": 9198, "s": 9190, "text": "Strings" }, { "code": null, "e": 9206, "s": 9198, "text": "Strings" } ]
Print array elements that are divisible by at-least one other
22 Jun, 2022 Given an array of length N that contains only integers, the task is to print the special numbers of array. A number in this array is called Special number if it is divisible by at least one other number in the array.Examples : Input : 1 2 3 Output : 2 3 Explanation : both 2 and 3 are divisible by 1.Input : 2 3 4 6 8 9 Output : 4 6 8 9 Explanation : 2 and 3 are not divisible by any other element. Rest of the element are divisible by at-least 1 element. 6 is divisible by both 2 and 3, 4 divisible by 2, 8 divisible by 2 and 4 both, 9 divisible by 3.Input : 3 5 7 11 Output : Explanation : all elements are relatively prime so no special number. A simple solution is to traverse through all elements, then check for every element if it is divisible by any other. Time complexity of this solution is O(n2)Another solution that works better when there are many elements with not very big values. Store all array elements into hash and find out the max element in array then up-to max element find out the multiples of a given number then if multiple of array element is in hash then that number is divisible by at-least one element of array . To remove duplicate values we store the value into set because if array has 2, 3, and 6 then only 6 is divisible by at-least one element of array, both 2 and 3 divides 6 so 6 will be stored only one time. C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find special numbersvoid divisibilityCheck(int arr[], int n){ // Storing all array elements in a hash // and finding maximum element in the array unordered_set<int> s; int max_ele = INT_MIN; for (int i = 0; i < n; i++) { s.insert(arr[i]); // Update the maximum element of the array max_ele = max(max_ele, arr[i]); } // Traversing the array elements and storing the array // multiples that are present in s in res unordered_set<int> res; for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) { // Checking the factors of current element for (int j = arr[i] * 2; j <= max_ele; j += arr[i]) { // If current factor is already part // of the array then store it if (s.find(j) != s.end()) res.insert(j); } } } // For non-distinct elmments // To store the frequency of elements unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; unordered_map<int, int>::iterator it; vector<int> ans; for (it = mp.begin(); it != mp.end(); it++) { // If frequency is at least 2 if (it->second >= 2) { if (res.find(it->first) == res.end()) { // If frequency is greater than 1 and // the number is not divisible by // any other number int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // If frequency is greater than 1 and the number // is divisible by any other number if (res.find(it->first) != res.end()) { int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // Print the elements that are divisible by // at least one other element from the array for (auto x : ans) cout << x << " ";} // Driver codeint main(){ int arr[] = { 2, 3, 8, 6, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); divisibilityCheck(arr, n); return 0;} // Java program to find special// numbers in an arrayimport java.io.*;import java.util.*; class GFG { // Function to find // special numbers static void divisibilityCheck(List<Integer> arr, int n) { // Storing all array elements // in a hash and finding maximum // element in array List<Integer> s = new ArrayList<Integer>(); int max_ele = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { s.add(arr.get(i)); // finding maximum // element of array max_ele = Math.max(max_ele, arr.get(i)); } // traversing array element and // storing the array multiples // that are present in s in res. LinkedHashSet<Integer> res = new LinkedHashSet<Integer>(); for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr.get(i) != 0) // checking the factor // of current element for (int j = arr.get(i) * 2; j <= max_ele; j += arr.get(i)) { // if factor is already // part of array element // then store it if (s.contains(j)) res.add(j); } } // displaying elements that // are divisible by at least // one other in array List<Integer> list = new ArrayList<Integer>(res); Collections.reverse(list); for (Integer temp : list) System.out.print(temp + " "); } // Driver Code public static void main(String args[]) { List<Integer> arr = Arrays.asList(2, 3, 8, 6, 9, 10); int n = arr.size(); divisibilityCheck(arr, n); }} // This code is contributed by// Manish Shaw(manishshaw1) # Python3 program to find special numbers# in an arrayimport math as mt # Function to find special numbersdef divisibilityCheck(arr, n): # Storing all array elements in a hash # and finding maximum element in array s = dict() max_ele = -10**9 for i in range(n): s[arr[i]] = 1 # finding maximum element of array max_ele = max(max_ele, arr[i]) # traversing array element and storing # the array multiples that are present # in s in res. res = dict() for i in range(n): # Check for non-zero values only if (arr[i] != 0): # checking the factor of current element for j in range(arr[i] * 2, max_ele + 1, arr[i]): # if factor is already part of # array element then store it if (j in s.keys()): res[j] = 1 # displaying elements that are divisible # by at least one other in array for x in res: print(x, end = " ") # Driver codearr = [ 2, 3, 8, 6, 9, 10]n = len(arr)divisibilityCheck(arr, n) # This code is contributed by# Mohit Kumar 29 // C# program to find special// numbers in an arrayusing System;using System.Linq;using System.Collections.Generic; class GFG { // Function to find // special numbers static void divisibilityCheck(List<int> arr, int n) { // Storing all array elements // in a hash and finding maximum // element in array List<int> s = new List<int>(); int max_ele = Int32.MinValue; for (int i = 0; i < n; i++) { s.Add(arr[i]); // finding maximum element of array max_ele = Math.Max(max_ele, arr[i]); } // traversing array element and // storing the array multiples // that are present in s in res. HashSet<int> res = new HashSet<int>(); for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) // checking the factor // of current element for (int j = arr[i] * 2; j <= max_ele; j += arr[i]) { // if factor is already part // of array element then store it if (s.Contains(j)) res.Add(j); } } // displaying elements that // are divisible by at least // one other in array foreach(int i in res.Reverse()) Console.Write(i + " "); } // Driver Code static void Main() { List<int> arr = new List<int>() { 2, 3, 8, 6, 9, 10 }; int n = arr.Count; divisibilityCheck(arr, n); }} // This code is contributed by// Manish Shaw(manishshaw1) <script> // JavaScript implementation of the approach // Function to find special numbersfunction divisibilityCheck(arr, n) { // Storing all array elements in a hash // and finding maximum element in the array let s = new Set(); let max_ele = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; i++) { s.add(arr[i]); // Update the maximum element of the array max_ele = Math.max(max_ele, arr[i]); } // Traversing the array elements and storing the array // multiples that are present in s in res let res = new Set(); for (let i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) { // Checking the factors of current element for (let j = arr[i] * 2; j <= max_ele; j += arr[i]) { // If current factor is already part // of the array then store it if (s.has(j)) res.add(j); } } } // For non-distinct elmments // To store the frequency of elements let mp = new Map(); for (let i = 0; i < n; i++) { if (mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1) } else { mp.set(arr[i], 1) } } let ans = []; for (let it of mp) { // If frequency is at least 2 if (it[1] >= 2) { if (res.has(it[0])) { // If frequency is greater than 1 and // the number is not divisible by // any other number let val = it[1]; // Then we push the element number of // times it is present in the vector while (val--) ans.push(it[0]); } } // If frequency is greater than 1 and the number // is divisible by any other number if (res.has(it[0])) { let val = it[1]; // Then we push the element number of // times it is present in the vector while (val--) ans.push(it[0]); } } // Print the elements that are divisible by // at least one other element from the array for (let x of ans.sort((a, b) => a - b)) document.write(x + " ");} // Driver code let arr = [2, 3, 8, 6, 9, 10];let n = arr.length divisibilityCheck(arr, n); </script> 6 8 9 10 Time Complexity: O(n x m), where n is the size of array and m is the maximum element in arrayAuxiliary Space: O(n) Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Note: If we need results to be printed in sorted order, we can use set in place of unordered_set. manishshaw1 mohit kumar 29 vardan96 gfgking Kirti_Mangal adi1212 cpp-unordered_set divisibility Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 283, "s": 54, "text": "Given an array of length N that contains only integers, the task is to print the special numbers of array. A number in this array is called Special number if it is divisible by at least one other number in the array.Examples : " }, { "code": null, "e": 704, "s": 283, "text": "Input : 1 2 3 Output : 2 3 Explanation : both 2 and 3 are divisible by 1.Input : 2 3 4 6 8 9 Output : 4 6 8 9 Explanation : 2 and 3 are not divisible by any other element. Rest of the element are divisible by at-least 1 element. 6 is divisible by both 2 and 3, 4 divisible by 2, 8 divisible by 2 and 4 both, 9 divisible by 3.Input : 3 5 7 11 Output : Explanation : all elements are relatively prime so no special number." }, { "code": null, "e": 1408, "s": 706, "text": "A simple solution is to traverse through all elements, then check for every element if it is divisible by any other. Time complexity of this solution is O(n2)Another solution that works better when there are many elements with not very big values. Store all array elements into hash and find out the max element in array then up-to max element find out the multiples of a given number then if multiple of array element is in hash then that number is divisible by at-least one element of array . To remove duplicate values we store the value into set because if array has 2, 3, and 6 then only 6 is divisible by at-least one element of array, both 2 and 3 divides 6 so 6 will be stored only one time. " }, { "code": null, "e": 1412, "s": 1408, "text": "C++" }, { "code": null, "e": 1417, "s": 1412, "text": "Java" }, { "code": null, "e": 1425, "s": 1417, "text": "Python3" }, { "code": null, "e": 1428, "s": 1425, "text": "C#" }, { "code": null, "e": 1439, "s": 1428, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find special numbersvoid divisibilityCheck(int arr[], int n){ // Storing all array elements in a hash // and finding maximum element in the array unordered_set<int> s; int max_ele = INT_MIN; for (int i = 0; i < n; i++) { s.insert(arr[i]); // Update the maximum element of the array max_ele = max(max_ele, arr[i]); } // Traversing the array elements and storing the array // multiples that are present in s in res unordered_set<int> res; for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) { // Checking the factors of current element for (int j = arr[i] * 2; j <= max_ele; j += arr[i]) { // If current factor is already part // of the array then store it if (s.find(j) != s.end()) res.insert(j); } } } // For non-distinct elmments // To store the frequency of elements unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; unordered_map<int, int>::iterator it; vector<int> ans; for (it = mp.begin(); it != mp.end(); it++) { // If frequency is at least 2 if (it->second >= 2) { if (res.find(it->first) == res.end()) { // If frequency is greater than 1 and // the number is not divisible by // any other number int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // If frequency is greater than 1 and the number // is divisible by any other number if (res.find(it->first) != res.end()) { int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // Print the elements that are divisible by // at least one other element from the array for (auto x : ans) cout << x << \" \";} // Driver codeint main(){ int arr[] = { 2, 3, 8, 6, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); divisibilityCheck(arr, n); return 0;}", "e": 3862, "s": 1439, "text": null }, { "code": "// Java program to find special// numbers in an arrayimport java.io.*;import java.util.*; class GFG { // Function to find // special numbers static void divisibilityCheck(List<Integer> arr, int n) { // Storing all array elements // in a hash and finding maximum // element in array List<Integer> s = new ArrayList<Integer>(); int max_ele = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { s.add(arr.get(i)); // finding maximum // element of array max_ele = Math.max(max_ele, arr.get(i)); } // traversing array element and // storing the array multiples // that are present in s in res. LinkedHashSet<Integer> res = new LinkedHashSet<Integer>(); for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr.get(i) != 0) // checking the factor // of current element for (int j = arr.get(i) * 2; j <= max_ele; j += arr.get(i)) { // if factor is already // part of array element // then store it if (s.contains(j)) res.add(j); } } // displaying elements that // are divisible by at least // one other in array List<Integer> list = new ArrayList<Integer>(res); Collections.reverse(list); for (Integer temp : list) System.out.print(temp + \" \"); } // Driver Code public static void main(String args[]) { List<Integer> arr = Arrays.asList(2, 3, 8, 6, 9, 10); int n = arr.size(); divisibilityCheck(arr, n); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 5760, "s": 3862, "text": null }, { "code": "# Python3 program to find special numbers# in an arrayimport math as mt # Function to find special numbersdef divisibilityCheck(arr, n): # Storing all array elements in a hash # and finding maximum element in array s = dict() max_ele = -10**9 for i in range(n): s[arr[i]] = 1 # finding maximum element of array max_ele = max(max_ele, arr[i]) # traversing array element and storing # the array multiples that are present # in s in res. res = dict() for i in range(n): # Check for non-zero values only if (arr[i] != 0): # checking the factor of current element for j in range(arr[i] * 2, max_ele + 1, arr[i]): # if factor is already part of # array element then store it if (j in s.keys()): res[j] = 1 # displaying elements that are divisible # by at least one other in array for x in res: print(x, end = \" \") # Driver codearr = [ 2, 3, 8, 6, 9, 10]n = len(arr)divisibilityCheck(arr, n) # This code is contributed by# Mohit Kumar 29", "e": 6923, "s": 5760, "text": null }, { "code": "// C# program to find special// numbers in an arrayusing System;using System.Linq;using System.Collections.Generic; class GFG { // Function to find // special numbers static void divisibilityCheck(List<int> arr, int n) { // Storing all array elements // in a hash and finding maximum // element in array List<int> s = new List<int>(); int max_ele = Int32.MinValue; for (int i = 0; i < n; i++) { s.Add(arr[i]); // finding maximum element of array max_ele = Math.Max(max_ele, arr[i]); } // traversing array element and // storing the array multiples // that are present in s in res. HashSet<int> res = new HashSet<int>(); for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) // checking the factor // of current element for (int j = arr[i] * 2; j <= max_ele; j += arr[i]) { // if factor is already part // of array element then store it if (s.Contains(j)) res.Add(j); } } // displaying elements that // are divisible by at least // one other in array foreach(int i in res.Reverse()) Console.Write(i + \" \"); } // Driver Code static void Main() { List<int> arr = new List<int>() { 2, 3, 8, 6, 9, 10 }; int n = arr.Count; divisibilityCheck(arr, n); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 8663, "s": 6923, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to find special numbersfunction divisibilityCheck(arr, n) { // Storing all array elements in a hash // and finding maximum element in the array let s = new Set(); let max_ele = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; i++) { s.add(arr[i]); // Update the maximum element of the array max_ele = Math.max(max_ele, arr[i]); } // Traversing the array elements and storing the array // multiples that are present in s in res let res = new Set(); for (let i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) { // Checking the factors of current element for (let j = arr[i] * 2; j <= max_ele; j += arr[i]) { // If current factor is already part // of the array then store it if (s.has(j)) res.add(j); } } } // For non-distinct elmments // To store the frequency of elements let mp = new Map(); for (let i = 0; i < n; i++) { if (mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1) } else { mp.set(arr[i], 1) } } let ans = []; for (let it of mp) { // If frequency is at least 2 if (it[1] >= 2) { if (res.has(it[0])) { // If frequency is greater than 1 and // the number is not divisible by // any other number let val = it[1]; // Then we push the element number of // times it is present in the vector while (val--) ans.push(it[0]); } } // If frequency is greater than 1 and the number // is divisible by any other number if (res.has(it[0])) { let val = it[1]; // Then we push the element number of // times it is present in the vector while (val--) ans.push(it[0]); } } // Print the elements that are divisible by // at least one other element from the array for (let x of ans.sort((a, b) => a - b)) document.write(x + \" \");} // Driver code let arr = [2, 3, 8, 6, 9, 10];let n = arr.length divisibilityCheck(arr, n); </script>", "e": 11000, "s": 8663, "text": null }, { "code": null, "e": 11009, "s": 11000, "text": "6 8 9 10" }, { "code": null, "e": 11126, "s": 11011, "text": "Time Complexity: O(n x m), where n is the size of array and m is the maximum element in arrayAuxiliary Space: O(n)" }, { "code": null, "e": 11393, "s": 11126, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 11492, "s": 11393, "text": "Note: If we need results to be printed in sorted order, we can use set in place of unordered_set. " }, { "code": null, "e": 11504, "s": 11492, "text": "manishshaw1" }, { "code": null, "e": 11519, "s": 11504, "text": "mohit kumar 29" }, { "code": null, "e": 11528, "s": 11519, "text": "vardan96" }, { "code": null, "e": 11536, "s": 11528, "text": "gfgking" }, { "code": null, "e": 11549, "s": 11536, "text": "Kirti_Mangal" }, { "code": null, "e": 11557, "s": 11549, "text": "adi1212" }, { "code": null, "e": 11575, "s": 11557, "text": "cpp-unordered_set" }, { "code": null, "e": 11588, "s": 11575, "text": "divisibility" }, { "code": null, "e": 11595, "s": 11588, "text": "Arrays" }, { "code": null, "e": 11600, "s": 11595, "text": "Hash" }, { "code": null, "e": 11607, "s": 11600, "text": "Arrays" }, { "code": null, "e": 11612, "s": 11607, "text": "Hash" } ]
Dispatch Decorator in Python
08 May, 2020 Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. Example: # defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case "func" def inner1(): print("Hello, this is before function execution") # calling the actual function now # inside the wrapper function. func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() Output: Hello, this is before function execution This is inside the function !! This is after function execution A Dispatch decorator is used to select between different implementations of the same abstract method based on the signature, or list of types. Example: # Python program to demonstrate# dispatch decorator from multipledispatch import dispatch @dispatch(int)def func(x): return x * 2 @dispatch(float)def func(x): return x / 2 # Driver codeprint(func(2))print(func(2.0)) Output: 4 1.0 In the above example, the @dispatch(int) statement suggests that the Dispatcher ‘func’ is created and then allocates the ‘int’ type as the key and dispatcher ‘func’ as the value and allocates it to the ith index in the namespace (dictionary). Now you all must be wondering what is a namespace? Don’t worry let’s have a look at the namespace. A namespace is nothing but a dictionary that is used by the dispatch decorator. The dispatch decorator creates a dispatcher object with the name of the function and stores this object as a key-value pair. This dictionary is used to map a functions like func in the above example to a dispatcher object like Disptacher('func'). By default, the namespace used is the global namespace in multipledispatch.core.global_namespace. For additional security, one can establish their own namespaces using a dictionary. Example: from multipledispatch import dispatch nsp = {} @dispatch(int, namespace = nsp)def func(x): return x * 2 @dispatch(float, namespace = nsp)def func(x): return x / 2 # Driver codeprint(func(2))print(func(2.0))print(nsp) Output: 4 1.0 {'func': <dispatched func>} Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 May, 2020" }, { "code": null, "e": 294, "s": 28, "text": "Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it." }, { "code": null, "e": 303, "s": 294, "text": "Example:" }, { "code": "# defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case \"func\" def inner1(): print(\"Hello, this is before function execution\") # calling the actual function now # inside the wrapper function. func() print(\"This is after function execution\") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print(\"This is inside the function !!\") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() ", "e": 1118, "s": 303, "text": null }, { "code": null, "e": 1126, "s": 1118, "text": "Output:" }, { "code": null, "e": 1232, "s": 1126, "text": "Hello, this is before function execution\nThis is inside the function !!\nThis is after function execution\n" }, { "code": null, "e": 1375, "s": 1232, "text": "A Dispatch decorator is used to select between different implementations of the same abstract method based on the signature, or list of types." }, { "code": null, "e": 1384, "s": 1375, "text": "Example:" }, { "code": "# Python program to demonstrate# dispatch decorator from multipledispatch import dispatch @dispatch(int)def func(x): return x * 2 @dispatch(float)def func(x): return x / 2 # Driver codeprint(func(2))print(func(2.0))", "e": 1612, "s": 1384, "text": null }, { "code": null, "e": 1620, "s": 1612, "text": "Output:" }, { "code": null, "e": 1626, "s": 1620, "text": "4\n1.0" }, { "code": null, "e": 1869, "s": 1626, "text": "In the above example, the @dispatch(int) statement suggests that the Dispatcher ‘func’ is created and then allocates the ‘int’ type as the key and dispatcher ‘func’ as the value and allocates it to the ith index in the namespace (dictionary)." }, { "code": null, "e": 1968, "s": 1869, "text": "Now you all must be wondering what is a namespace? Don’t worry let’s have a look at the namespace." }, { "code": null, "e": 2295, "s": 1968, "text": "A namespace is nothing but a dictionary that is used by the dispatch decorator. The dispatch decorator creates a dispatcher object with the name of the function and stores this object as a key-value pair. This dictionary is used to map a functions like func in the above example to a dispatcher object like Disptacher('func')." }, { "code": null, "e": 2477, "s": 2295, "text": "By default, the namespace used is the global namespace in multipledispatch.core.global_namespace. For additional security, one can establish their own namespaces using a dictionary." }, { "code": null, "e": 2486, "s": 2477, "text": "Example:" }, { "code": "from multipledispatch import dispatch nsp = {} @dispatch(int, namespace = nsp)def func(x): return x * 2 @dispatch(float, namespace = nsp)def func(x): return x / 2 # Driver codeprint(func(2))print(func(2.0))print(nsp)", "e": 2715, "s": 2486, "text": null }, { "code": null, "e": 2723, "s": 2715, "text": "Output:" }, { "code": null, "e": 2757, "s": 2723, "text": "4\n1.0\n{'func': <dispatched func>}" }, { "code": null, "e": 2775, "s": 2757, "text": "Python Decorators" }, { "code": null, "e": 2782, "s": 2775, "text": "Python" } ]
Program for Variance and Standard Deviation of an array
16 Jul, 2021 Given an array, we need to calculate the variance and standard deviation of the elements of the array. Examples : Input : arr[] = [1, 2, 3, 4, 5] Output : Variance = 2 Standard Deviation = 1 Input : arr[] = [7, 7, 8, 8, 3] Output : Variance = 3 Standard Deviation = 1 We have discussed program to find mean of an array. Mean is average of element. Mean of arr[0..n-1] = ∑(arr[i]) / n where 0 <= i < nVariance is sum of squared differences from the mean divided by number of elements.Variance = ∑(arr[i] – mean)2 / nStandard Deviation is square root of variance Standard Deviation = √(variance)Please refer Mean, Variance and Standard Deviation for details. Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // CPP program to find variance// and standard deviation of// given array.#include <bits/stdc++.h>using namespace std; // Function for calculating varianceint variance(int a[], int n){ // Compute mean (average of elements) int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; double mean = (double)sum / (double)n; // Compute sum squared // differences with mean. double sqDiff = 0; for (int i = 0; i < n; i++) sqDiff += (a[i] - mean) * (a[i] - mean); return sqDiff / n;} double standardDeviation(int arr[], int n){ return sqrt(variance(arr, n));} // Driver Codeint main(){ int arr[] = {600, 470, 170, 430, 300}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Variance: " << variance(arr, n) << "\n"; cout << "Standard Deviation: " << standardDeviation(arr, n) << "\n"; return 0;} // Java program to find variance// and standard deviation of// given array.import java.io.*; class GFG{ // Function for calculating // variance static double variance(double a[], int n) { // Compute mean (average // of elements) double sum = 0; for (int i = 0; i < n; i++) sum += a[i]; double mean = (double)sum / (double)n; // Compute sum squared // differences with mean. double sqDiff = 0; for (int i = 0; i < n; i++) sqDiff += (a[i] - mean) * (a[i] - mean); return (double)sqDiff / n; } static double standardDeviation(double arr[], int n) { return Math.sqrt(variance(arr, n)); } // Driver Code public static void main (String[] args) { double arr[] = {600, 470, 170, 430, 300}; int n = arr.length; System.out.println( "Variance: " + variance(arr, n)); System.out.println ("Standard Deviation: " + standardDeviation(arr, n)); }} // This code is contributed by vt_m. # Python 3 program to find variance# and standard deviation of# given array.import math # Function for calculating variancedef variance(a, n): # Compute mean (average of # elements) sum = 0 for i in range(0 ,n): sum += a[i] mean = sum /n # Compute sum squared # differences with mean. sqDiff = 0 for i in range(0 ,n): sqDiff += ((a[i] - mean) * (a[i] - mean)) return sqDiff / n def standardDeviation(arr, n): return math.sqrt(variance(arr, n)) # Driver Codearr = [600, 470, 170, 430, 300]n = len(arr)print("Variance: ", int(variance(arr, n)))print("Standard Deviation: ", round(standardDeviation(arr, n), 3)) # This code is contributed by Smitha // C# program to find variance and// standard deviation of given array.using System; class GFG{ // Function for calculating // variance static float variance(double []a, int n) { // Compute mean (average // of elements) double sum = 0; for (int i = 0; i < n; i++) sum += a[i]; double mean = (double)sum / (double)n; // Compute sum squared // differences with mean. double sqDiff = 0; for (int i = 0; i < n; i++) sqDiff += (a[i] - mean) * (a[i] - mean); return (float)sqDiff / n; } static float standardDeviation(double []arr, int n) { return (float)Math.Sqrt(variance(arr, n)); } // Driver Code public static void Main () { double []arr = {600, 470, 170, 430, 300}; int n = arr.Length; Console.WriteLine( "Variance: " + variance(arr, n)); Console.WriteLine ("Standard Deviation: " + standardDeviation(arr, n)); }} // This code is contributed by vt_m. <?php// PHP program to find variance// and standard deviation of// given array. // Function for calculating.// variancefunction variance( $a, $n){ // Compute mean (average // of elements) $sum = 0; for ( $i = 0; $i < $n; $i++) $sum += $a[$i]; $mean = $sum / $n; // Compute sum squared // differences with mean. $sqDiff = 0; for ( $i = 0; $i < $n; $i++) $sqDiff += ($a[$i] - $mean) * ($a[$i] - $mean); return $sqDiff / $n;} function standardDeviation($arr, $n){ return sqrt(variance($arr, $n));} // Driver Code$arr = array(600, 470, 170, 430, 300);$n = count($arr);echo "Variance: " , variance($arr, $n) , "\n";echo"Standard Deviation: " , standardDeviation($arr, $n) ,"\n"; // This code is contributed by anuj_67.?> <script> // JavaScript program to find variance and// standard deviation of given array. // Function for calculating // variance function variance(a, n) { // Compute mean (average of elements) var sum = 0; for (var i = 0; i < n; i++){ sum += a[i]; } var mean = sum / n; // Compute sum squared // differences with mean. var sqDiff = 0; for (var i = 0; i < n; i++) { sqDiff += (a[i] - mean) * (a[i] - mean); } return sqDiff / n; } function standardDeviation(arr , n) { return Math.sqrt(variance(arr, n)); } // Driver Code var arr = [600, 470, 170, 430, 300] var n = arr.length; document.write( "Variance: " + variance(arr, n) + "<br>"); document.write ("Standard Deviation: " + standardDeviation(arr, n).toFixed(3)); </script> Output: Variance: 21704 Standard Deviation: 147.323 Time complexity of the program is O(n).This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Smitha Dinesh Semwal Akanksha_Rai bunnyram19 2019ucp1423 statistical-algorithms Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jul, 2021" }, { "code": null, "e": 168, "s": 52, "text": "Given an array, we need to calculate the variance and standard deviation of the elements of the array. Examples : " }, { "code": null, "e": 346, "s": 168, "text": "Input : arr[] = [1, 2, 3, 4, 5]\nOutput : Variance = 2\n Standard Deviation = 1 \n\nInput : arr[] = [7, 7, 8, 8, 3]\nOutput : Variance = 3\n Standard Deviation = 1" }, { "code": null, "e": 401, "s": 348, "text": "We have discussed program to find mean of an array. " }, { "code": null, "e": 741, "s": 401, "text": "Mean is average of element. Mean of arr[0..n-1] = ∑(arr[i]) / n where 0 <= i < nVariance is sum of squared differences from the mean divided by number of elements.Variance = ∑(arr[i] – mean)2 / nStandard Deviation is square root of variance Standard Deviation = √(variance)Please refer Mean, Variance and Standard Deviation for details. " }, { "code": null, "e": 790, "s": 741, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 794, "s": 790, "text": "C++" }, { "code": null, "e": 799, "s": 794, "text": "Java" }, { "code": null, "e": 808, "s": 799, "text": "Python 3" }, { "code": null, "e": 811, "s": 808, "text": "C#" }, { "code": null, "e": 815, "s": 811, "text": "PHP" }, { "code": null, "e": 826, "s": 815, "text": "Javascript" }, { "code": "// CPP program to find variance// and standard deviation of// given array.#include <bits/stdc++.h>using namespace std; // Function for calculating varianceint variance(int a[], int n){ // Compute mean (average of elements) int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; double mean = (double)sum / (double)n; // Compute sum squared // differences with mean. double sqDiff = 0; for (int i = 0; i < n; i++) sqDiff += (a[i] - mean) * (a[i] - mean); return sqDiff / n;} double standardDeviation(int arr[], int n){ return sqrt(variance(arr, n));} // Driver Codeint main(){ int arr[] = {600, 470, 170, 430, 300}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Variance: \" << variance(arr, n) << \"\\n\"; cout << \"Standard Deviation: \" << standardDeviation(arr, n) << \"\\n\"; return 0;}", "e": 1742, "s": 826, "text": null }, { "code": "// Java program to find variance// and standard deviation of// given array.import java.io.*; class GFG{ // Function for calculating // variance static double variance(double a[], int n) { // Compute mean (average // of elements) double sum = 0; for (int i = 0; i < n; i++) sum += a[i]; double mean = (double)sum / (double)n; // Compute sum squared // differences with mean. double sqDiff = 0; for (int i = 0; i < n; i++) sqDiff += (a[i] - mean) * (a[i] - mean); return (double)sqDiff / n; } static double standardDeviation(double arr[], int n) { return Math.sqrt(variance(arr, n)); } // Driver Code public static void main (String[] args) { double arr[] = {600, 470, 170, 430, 300}; int n = arr.length; System.out.println( \"Variance: \" + variance(arr, n)); System.out.println (\"Standard Deviation: \" + standardDeviation(arr, n)); }} // This code is contributed by vt_m.", "e": 2959, "s": 1742, "text": null }, { "code": "# Python 3 program to find variance# and standard deviation of# given array.import math # Function for calculating variancedef variance(a, n): # Compute mean (average of # elements) sum = 0 for i in range(0 ,n): sum += a[i] mean = sum /n # Compute sum squared # differences with mean. sqDiff = 0 for i in range(0 ,n): sqDiff += ((a[i] - mean) * (a[i] - mean)) return sqDiff / n def standardDeviation(arr, n): return math.sqrt(variance(arr, n)) # Driver Codearr = [600, 470, 170, 430, 300]n = len(arr)print(\"Variance: \", int(variance(arr, n)))print(\"Standard Deviation: \", round(standardDeviation(arr, n), 3)) # This code is contributed by Smitha", "e": 3676, "s": 2959, "text": null }, { "code": "// C# program to find variance and// standard deviation of given array.using System; class GFG{ // Function for calculating // variance static float variance(double []a, int n) { // Compute mean (average // of elements) double sum = 0; for (int i = 0; i < n; i++) sum += a[i]; double mean = (double)sum / (double)n; // Compute sum squared // differences with mean. double sqDiff = 0; for (int i = 0; i < n; i++) sqDiff += (a[i] - mean) * (a[i] - mean); return (float)sqDiff / n; } static float standardDeviation(double []arr, int n) { return (float)Math.Sqrt(variance(arr, n)); } // Driver Code public static void Main () { double []arr = {600, 470, 170, 430, 300}; int n = arr.Length; Console.WriteLine( \"Variance: \" + variance(arr, n)); Console.WriteLine (\"Standard Deviation: \" + standardDeviation(arr, n)); }} // This code is contributed by vt_m.", "e": 4966, "s": 3676, "text": null }, { "code": "<?php// PHP program to find variance// and standard deviation of// given array. // Function for calculating.// variancefunction variance( $a, $n){ // Compute mean (average // of elements) $sum = 0; for ( $i = 0; $i < $n; $i++) $sum += $a[$i]; $mean = $sum / $n; // Compute sum squared // differences with mean. $sqDiff = 0; for ( $i = 0; $i < $n; $i++) $sqDiff += ($a[$i] - $mean) * ($a[$i] - $mean); return $sqDiff / $n;} function standardDeviation($arr, $n){ return sqrt(variance($arr, $n));} // Driver Code$arr = array(600, 470, 170, 430, 300);$n = count($arr);echo \"Variance: \" , variance($arr, $n) , \"\\n\";echo\"Standard Deviation: \" , standardDeviation($arr, $n) ,\"\\n\"; // This code is contributed by anuj_67.?>", "e": 5757, "s": 4966, "text": null }, { "code": "<script> // JavaScript program to find variance and// standard deviation of given array. // Function for calculating // variance function variance(a, n) { // Compute mean (average of elements) var sum = 0; for (var i = 0; i < n; i++){ sum += a[i]; } var mean = sum / n; // Compute sum squared // differences with mean. var sqDiff = 0; for (var i = 0; i < n; i++) { sqDiff += (a[i] - mean) * (a[i] - mean); } return sqDiff / n; } function standardDeviation(arr , n) { return Math.sqrt(variance(arr, n)); } // Driver Code var arr = [600, 470, 170, 430, 300] var n = arr.length; document.write( \"Variance: \" + variance(arr, n) + \"<br>\"); document.write (\"Standard Deviation: \" + standardDeviation(arr, n).toFixed(3)); </script>", "e": 6809, "s": 5757, "text": null }, { "code": null, "e": 6819, "s": 6809, "text": "Output: " }, { "code": null, "e": 6863, "s": 6819, "text": "Variance: 21704\nStandard Deviation: 147.323" }, { "code": null, "e": 7326, "s": 6863, "text": "Time complexity of the program is O(n).This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7331, "s": 7326, "text": "vt_m" }, { "code": null, "e": 7352, "s": 7331, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 7365, "s": 7352, "text": "Akanksha_Rai" }, { "code": null, "e": 7376, "s": 7365, "text": "bunnyram19" }, { "code": null, "e": 7388, "s": 7376, "text": "2019ucp1423" }, { "code": null, "e": 7411, "s": 7388, "text": "statistical-algorithms" }, { "code": null, "e": 7418, "s": 7411, "text": "Arrays" }, { "code": null, "e": 7425, "s": 7418, "text": "Arrays" }, { "code": null, "e": 7523, "s": 7425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7591, "s": 7523, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7635, "s": 7591, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7667, "s": 7635, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7715, "s": 7667, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 7729, "s": 7715, "text": "Linear Search" }, { "code": null, "e": 7752, "s": 7729, "text": "Introduction to Arrays" }, { "code": null, "e": 7837, "s": 7752, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 7864, "s": 7837, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 7896, "s": 7864, "text": "Introduction to Data Structures" } ]
C++ Program to Implement Hash Tables with Double Hashing
A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched. Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of using a second hash function to key when a collision occurs. This is a C++ program to Implement Hash Tables chaining with double hashing. For search a key: Begin Declare Function SearchKey(int k, HashTable *ht) int hashVal= HashFunc1(k, ht->s) int stepSize= HashFunc2(k, ht->s) while (ht->t[hashVal].info != Emp and ht->t[hashVal].e != k) hashVal = hashVal + stepSize hashVal = hashVal % ht->s return hashVal End For insert: Begin. Declare Function Insert(int k, HashTable *ht) int pos = SearchKey(k, ht) if (ht->t[pos].info != Legi ) ht->t[pos].info = Legi ht->t[pos].e = k End For Display: Begin Declare function display(HashTable *ht) for (int i = 0; i < ht->s; i++) int v= ht->t[i].e; if (!v) Print "Position: " Print the position of the pointer Print " Element: Null" else Print "Position: " Print the position of the pointer Print " Element: " Print the element End. For rehash function: Begin Declare function Rehash(HashTable *ht) int s = ht->s HashTableEntry *t= ht->t ht = initiateTable(2*s) for (int i = 0; i < s; i++) if (t[i].info == Legi) Insert(t[i].e, ht) free(t) return ht End. Live Demo #include <iostream> #include <cstdlib> #define T_S 5 using namespace std; enum EntryType {Legi, Emp}; struct HashTableEntry { int e; enum EntryType info; }; struct HashTable { int s; HashTableEntry *t; }; int HashFunc1(int k, int s) { return k % s; } int HashFunc2(int k, int s) { return (k * s - 1) % s; } HashTable *initiateTable(int s) { HashTable *ht; if (s < T_S) { cout<<"Table Size is Too Small"<<endl; return NULL; } ht= new HashTable; if (ht == NULL) { cout<<"Out of Space"<<endl; return NULL; } ht->s = s; ht->t = new HashTableEntry[ht->s]; if (ht->t== NULL) { cout<<"Table Size is Too Small"<<endl; return NULL; } for (int i = 0; i < ht->s; i++) { ht->t[i].info = Emp; ht->t[i].e=NULL; } return ht; } int SearchKey(int k, HashTable *ht) { int hashVal= HashFunc1(k, ht->s); int stepSize= HashFunc2(k, ht->s); while (ht->t[hashVal].info != Emp && ht->t[hashVal].e != k) { hashVal = hashVal + stepSize; hashVal = hashVal % ht->s; } return hashVal; } void Insert(int k, HashTable *ht) { int pos = SearchKey(k, ht); if (ht->t[pos].info != Legi ) { ht->t[pos].info = Legi; ht->t[pos].e = k; } } void display(HashTable *ht) { for (int i = 0; i < ht->s; i++) { int v= ht->t[i].e; if (!v) cout<<"Position: "<<i + 1<<" Element: Null"<<endl; else cout<<"Position: "<<i + 1<<" Element: "<<v<<endl; } } HashTable *Rehash(HashTable *ht) { int s = ht->s; HashTableEntry *t= ht->t; ht = initiateTable(2*s); for (int i = 0; i < s; i++) { if (t[i].info == Legi) Insert(t[i].e, ht); } free(t); return ht; } int main() { int v, s, pos, i = 1; int c; HashTable *ht; while(1) { cout<<"1.Initialize size of the table"<<endl; cout<<"2.Insert element into the table"<<endl; cout<<"3.Display Hash Table"<<endl; cout<<"4.Rehash Hash Table"<<endl; cout<<"5.Exit"<<endl; cout<<"Enter your choice: "; cin>>c; switch(c) { case 1: cout<<"Enter size of the Hash Table: "; cin>>s; ht = initiateTable(s); break; case 2: if (i > ht->s) { cout<<"Table is Full, Rehash the table"<<endl; continue; } cout<<"Enter element to be inserted: "; cin>>v; Insert(v, ht); i++; break; case 3: display(ht); break; case 4: ht= Rehash(ht); break; case 5: exit(1); default: cout<<"\nEnter correct option\n"; } } return 0; } 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 1 Enter size of the Hash Table: 4 Table Size is Too Small Enter your choice: 1 Enter size of the Hash Table: 10 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 1 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 3 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 4 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 5 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 6 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 7 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 8 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 9 Enter correct option 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 9 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 10 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 11 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Table is Full, Rehash the table 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 12 Enter correct option 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Table is Full, Rehash the table 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Table is Full, Rehash the table 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 3 Position: 1 Element: 10 Position: 2 Element: 1 Position: 3 Element: 11 Position: 4 Element: 3 Position: 5 Element: 4 Position: 6 Element: 5 Position: 7 Element: 6 Position: 8 Element: 7 Position: 9 Element: 8 Position: 10 Element: 9 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 4 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 3 Position: 1 Element: Null Position: 2 Element: 1 Position: 3 Element: Null Position: 4 Element: 3 Position: 5 Element: 4 Position: 6 Element: 5 Position: 7 Element: 6 Position: 8 Element: 7 Position: 9 Element: 8 Position: 10 Element: 9 Position: 11 Element: 10 Position: 12 Element: 11 Position: 13 Element: Null Position: 14 Element: Null Position: 15 Element: Null Position: 16 Element: Null Position: 17 Element: Null Position: 18 Element: Null Position: 19 Element: Null Position: 20 Element: Null 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 2 Enter element to be inserted: 20 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 3 Position: 1 Element: 20 Position: 2 Element: 1 Position: 3 Element: Null Position: 4 Element: 3 Position: 5 Element: 4 Position: 6 Element: 5 Position: 7 Element: 6 Position: 8 Element: 7 Position: 9 Element: 8 Position: 10 Element: 9 Position: 11 Element: 10 Position: 12 Element: 11 Position: 13 Element: Null Position: 14 Element: Null Position: 15 Element: Null Position: 16 Element: Null Position: 17 Element: Null Position: 18 Element: Null Position: 19 Element: Null Position: 20 Element: Null 1.Initialize size of the table 2.Insert element into the table 3.Display Hash Table 4.Rehash Hash Table 5.Exit Enter your choice: 5
[ { "code": null, "e": 1380, "s": 1187, "text": "A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched." }, { "code": null, "e": 1554, "s": 1380, "text": "Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of using a second hash function to key when a collision occurs." }, { "code": null, "e": 1631, "s": 1554, "text": "This is a C++ program to Implement Hash Tables chaining with double hashing." }, { "code": null, "e": 1649, "s": 1631, "text": "For search a key:" }, { "code": null, "e": 1966, "s": 1649, "text": "Begin\n Declare Function SearchKey(int k, HashTable *ht)\n int hashVal= HashFunc1(k, ht->s)\n int stepSize= HashFunc2(k, ht->s)\n while (ht->t[hashVal].info != Emp and\n ht->t[hashVal].e != k)\n hashVal = hashVal + stepSize\n hashVal = hashVal % ht->s\n return hashVal\nEnd" }, { "code": null, "e": 1978, "s": 1966, "text": "For insert:" }, { "code": null, "e": 2165, "s": 1978, "text": "Begin.\n Declare Function Insert(int k, HashTable *ht)\n int pos = SearchKey(k, ht)\n if (ht->t[pos].info != Legi )\n ht->t[pos].info = Legi\n ht->t[pos].e = k\nEnd" }, { "code": null, "e": 2178, "s": 2165, "text": "For Display:" }, { "code": null, "e": 2588, "s": 2178, "text": "Begin\n Declare function display(HashTable *ht)\n for (int i = 0; i < ht->s; i++)\n int v= ht->t[i].e;\n if (!v)\n Print \"Position: \"\n Print the position of the pointer\n Print \" Element: Null\"\n else\n Print \"Position: \"\n Print the position of the pointer\n Print \" Element: \"\n Print the element\nEnd." }, { "code": null, "e": 2609, "s": 2588, "text": "For rehash function:" }, { "code": null, "e": 2870, "s": 2609, "text": "Begin\n Declare function Rehash(HashTable *ht)\n int s = ht->s\n HashTableEntry *t= ht->t\n ht = initiateTable(2*s)\n for (int i = 0; i < s; i++)\n if (t[i].info == Legi)\n Insert(t[i].e, ht)\n free(t)\n return ht\nEnd." }, { "code": null, "e": 2881, "s": 2870, "text": " Live Demo" }, { "code": null, "e": 5657, "s": 2881, "text": "#include <iostream>\n#include <cstdlib>\n#define T_S 5\nusing namespace std;\nenum EntryType {Legi, Emp};\nstruct HashTableEntry {\n int e;\n enum EntryType info;\n};\nstruct HashTable {\n int s;\n HashTableEntry *t;\n};\nint HashFunc1(int k, int s) {\n return k % s;\n}\nint HashFunc2(int k, int s) {\n return (k * s - 1) % s;\n}\nHashTable *initiateTable(int s) {\n HashTable *ht;\n if (s < T_S) {\n cout<<\"Table Size is Too Small\"<<endl;\n return NULL;\n }\n ht= new HashTable;\n if (ht == NULL) {\n cout<<\"Out of Space\"<<endl;\n return NULL;\n }\n ht->s = s;\n ht->t = new HashTableEntry[ht->s];\n if (ht->t== NULL) {\n cout<<\"Table Size is Too Small\"<<endl;\n return NULL;\n }\n for (int i = 0; i < ht->s; i++) {\n ht->t[i].info = Emp;\n ht->t[i].e=NULL;\n }\n return ht;\n}\nint SearchKey(int k, HashTable *ht) {\n int hashVal= HashFunc1(k, ht->s);\n int stepSize= HashFunc2(k, ht->s);\n while (ht->t[hashVal].info != Emp &&\n ht->t[hashVal].e != k) {\n hashVal = hashVal + stepSize;\n hashVal = hashVal % ht->s;\n }\n return hashVal;\n}\nvoid Insert(int k, HashTable *ht) {\n int pos = SearchKey(k, ht);\n if (ht->t[pos].info != Legi ) {\n ht->t[pos].info = Legi;\n ht->t[pos].e = k;\n }\n}\nvoid display(HashTable *ht) {\n for (int i = 0; i < ht->s; i++) {\n int v= ht->t[i].e;\n if (!v)\n cout<<\"Position: \"<<i + 1<<\" Element: Null\"<<endl;\n else\n cout<<\"Position: \"<<i + 1<<\" Element: \"<<v<<endl;\n }\n}\nHashTable *Rehash(HashTable *ht) {\n int s = ht->s;\n HashTableEntry *t= ht->t;\n ht = initiateTable(2*s);\n for (int i = 0; i < s; i++) {\n if (t[i].info == Legi)\n Insert(t[i].e, ht);\n }\n free(t);\n return ht;\n}\nint main() {\n int v, s, pos, i = 1;\n int c;\n HashTable *ht;\n while(1) {\n cout<<\"1.Initialize size of the table\"<<endl;\n cout<<\"2.Insert element into the table\"<<endl;\n cout<<\"3.Display Hash Table\"<<endl;\n cout<<\"4.Rehash Hash Table\"<<endl;\n cout<<\"5.Exit\"<<endl;\n cout<<\"Enter your choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Enter size of the Hash Table: \";\n cin>>s;\n ht = initiateTable(s);\n break;\n case 2:\n if (i > ht->s) {\n cout<<\"Table is Full, Rehash the table\"<<endl;\n continue;\n }\n cout<<\"Enter element to be inserted: \";\n cin>>v;\n Insert(v, ht);\n i++;\n break;\n case 3:\n display(ht);\n break;\n case 4:\n ht= Rehash(ht);\n break;\n case 5:\n exit(1);\n default:\n cout<<\"\\nEnter correct option\\n\";\n }\n }\n return 0;\n}" }, { "code": null, "e": 10402, "s": 5657, "text": "1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 1\nEnter size of the Hash Table: 4\nTable Size is Too Small\nEnter your choice: 1\nEnter size of the Hash Table: 10\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 1\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 3\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 4\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 5\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 6\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 7\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 8\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice:\n9\nEnter correct option\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 9\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 10\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 11\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nTable is Full, Rehash the table\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 12\nEnter correct option\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nTable is Full, Rehash the table\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nTable is Full, Rehash the table\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 3\nPosition: 1 Element: 10\nPosition: 2 Element: 1\nPosition: 3 Element: 11\nPosition: 4 Element: 3\nPosition: 5 Element: 4\nPosition: 6 Element: 5\nPosition: 7 Element: 6\nPosition: 8 Element: 7\nPosition: 9 Element: 8\nPosition: 10 Element: 9\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 4\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 3\nPosition: 1 Element: Null\nPosition: 2 Element: 1\nPosition: 3 Element: Null\nPosition: 4 Element: 3\nPosition: 5 Element: 4\nPosition: 6 Element: 5\nPosition: 7 Element: 6\nPosition: 8 Element: 7\nPosition: 9 Element: 8\nPosition: 10 Element: 9\nPosition: 11 Element: 10\nPosition: 12 Element: 11\nPosition: 13 Element: Null\nPosition: 14 Element: Null\nPosition: 15 Element: Null\nPosition: 16 Element: Null\nPosition: 17 Element: Null\nPosition: 18 Element: Null\nPosition: 19 Element: Null\nPosition: 20 Element: Null\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 2\nEnter element to be inserted: 20\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 3\nPosition: 1 Element: 20\nPosition: 2 Element: 1\nPosition: 3 Element: Null\nPosition: 4 Element: 3\nPosition: 5 Element: 4\nPosition: 6 Element: 5\nPosition: 7 Element: 6\nPosition: 8 Element: 7\nPosition: 9 Element: 8\nPosition: 10 Element: 9\nPosition: 11 Element: 10\nPosition: 12 Element: 11\nPosition: 13 Element: Null\nPosition: 14 Element: Null\nPosition: 15 Element: Null\nPosition: 16 Element: Null\nPosition: 17 Element: Null\nPosition: 18 Element: Null\nPosition: 19 Element: Null\nPosition: 20 Element: Null\n1.Initialize size of the table\n2.Insert element into the table\n3.Display Hash Table\n4.Rehash Hash Table\n5.Exit\nEnter your choice: 5" } ]
Python | Automate Google Search using Selenium
11 May, 2020 Google search can be automated using Python script in just 2 minutes. This can be done using selenium (a browser automation tool). Selenium is a portable framework for testing web applications. It can automatically perform the same interactions that any you need to perform manually and this is a small example of it. Mastering Selenium will help you automate your day to day tasks like controlling your tweets, Whatsapp texting and even just googling without actually opening a browser in just 15-30 lines of python code. The limits of automation is endless with selenium. Seleniumpip install selenium Chrome browserChromedriverDownload the chrome browser from here (choose the version for your system)After downloading, extract it and then copy the file in the folder of the script. Seleniumpip install selenium pip install selenium Chrome browser ChromedriverDownload the chrome browser from here (choose the version for your system)After downloading, extract it and then copy the file in the folder of the script. This can be done in two ways, by taking input from the user and by giving input in the command line itself. # Method 1Asking the user for input. from selenium import webdriver # Taking input from usersearch_string = input("Input the URL or string you want to search for:") # This is done to structure the string # into search url.(This can be ignored)search_string = search_string.replace(' ', '+') # Assigning the browser variable with chromedriver of Chrome.# Any other browser and its respective webdriver # like geckodriver for Mozilla Firefox can be usedbrowser = webdriver.Chrome('chromedriver') for i in range(1): matched_elements = browser.get("https://www.google.com/search?q=" + search_string + "&start=" + str(i)) After saving the above script in script.py, run it in the command prompt as: python script.py # Method 2 Taking search string in the command line itself. from selenium import webdriverimport sys # function to convert a list into stringdef convert(s): str1 = "" return(str1.join(s)) # Assign the arguments passed to a variable search_stringsearch_string = sys.argv[1:] # The argument passed to the program is accepted# as list, it is needed to convert that into stringsearch_string = convert(search_string) # This is done to structure the string # into search url.(This can be ignored)search_string = search_string.replace(' ', '+') # Assigning the browser variable with chromedriver of Chrome.# Any other browser and its respective webdriver # like geckodriver for Mozilla Firefox can be usedbrowser = webdriver.Chrome('chromedriver') for i in range(1): matched_elements = browser.get("https://www.google.com/search?q=" + search_string + "&start=" + str(i)) After saving the above script in script.py, run it in the command prompt as: python script.py "geeksforgeeks" alpeshkaushal python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2020" }, { "code": null, "e": 628, "s": 54, "text": "Google search can be automated using Python script in just 2 minutes. This can be done using selenium (a browser automation tool). Selenium is a portable framework for testing web applications. It can automatically perform the same interactions that any you need to perform manually and this is a small example of it. Mastering Selenium will help you automate your day to day tasks like controlling your tweets, Whatsapp texting and even just googling without actually opening a browser in just 15-30 lines of python code. The limits of automation is endless with selenium." }, { "code": null, "e": 841, "s": 628, "text": "Seleniumpip install selenium \nChrome browserChromedriverDownload the chrome browser from here (choose the version for your system)After downloading, extract it and then copy the file in the folder of the script." }, { "code": null, "e": 873, "s": 841, "text": "Seleniumpip install selenium \n" }, { "code": null, "e": 897, "s": 873, "text": "pip install selenium \n" }, { "code": null, "e": 912, "s": 897, "text": "Chrome browser" }, { "code": null, "e": 1080, "s": 912, "text": "ChromedriverDownload the chrome browser from here (choose the version for your system)After downloading, extract it and then copy the file in the folder of the script." }, { "code": null, "e": 1188, "s": 1080, "text": "This can be done in two ways, by taking input from the user and by giving input in the command line itself." }, { "code": null, "e": 1225, "s": 1188, "text": "# Method 1Asking the user for input." }, { "code": "from selenium import webdriver # Taking input from usersearch_string = input(\"Input the URL or string you want to search for:\") # This is done to structure the string # into search url.(This can be ignored)search_string = search_string.replace(' ', '+') # Assigning the browser variable with chromedriver of Chrome.# Any other browser and its respective webdriver # like geckodriver for Mozilla Firefox can be usedbrowser = webdriver.Chrome('chromedriver') for i in range(1): matched_elements = browser.get(\"https://www.google.com/search?q=\" + search_string + \"&start=\" + str(i))", "e": 1849, "s": 1225, "text": null }, { "code": null, "e": 1926, "s": 1849, "text": "After saving the above script in script.py, run it in the command prompt as:" }, { "code": null, "e": 1944, "s": 1926, "text": "python script.py\n" }, { "code": null, "e": 1955, "s": 1944, "text": "# Method 2" }, { "code": null, "e": 2004, "s": 1955, "text": "Taking search string in the command line itself." }, { "code": "from selenium import webdriverimport sys # function to convert a list into stringdef convert(s): str1 = \"\" return(str1.join(s)) # Assign the arguments passed to a variable search_stringsearch_string = sys.argv[1:] # The argument passed to the program is accepted# as list, it is needed to convert that into stringsearch_string = convert(search_string) # This is done to structure the string # into search url.(This can be ignored)search_string = search_string.replace(' ', '+') # Assigning the browser variable with chromedriver of Chrome.# Any other browser and its respective webdriver # like geckodriver for Mozilla Firefox can be usedbrowser = webdriver.Chrome('chromedriver') for i in range(1): matched_elements = browser.get(\"https://www.google.com/search?q=\" + search_string + \"&start=\" + str(i))", "e": 2873, "s": 2004, "text": null }, { "code": null, "e": 2950, "s": 2873, "text": "After saving the above script in script.py, run it in the command prompt as:" }, { "code": null, "e": 2983, "s": 2950, "text": "python script.py \"geeksforgeeks\"" }, { "code": null, "e": 2997, "s": 2983, "text": "alpeshkaushal" }, { "code": null, "e": 3012, "s": 2997, "text": "python-utility" }, { "code": null, "e": 3019, "s": 3012, "text": "Python" } ]
How to set the GOPATH environment variable on Ubuntu?
Before setting up GOPATH or GOROOT on the local environment of yours, we must check whether you have correctly installed Go or not. Just type the following command on any user of the machine, where you think you have installed Go − go version If it outputs nothing or something like go is not present, then instead of setting the GOPATH first I would recommend that you first download the go binary from this link and then install it on your local machine. Normally the output for the case that you have Go installed will look something like this − immukul@192 linux-questions-code % go version go version go1.16.3 darwin/amd64 GOPATH is nothing but an environment variable path that needs to be set that tells the Go binary to where to look for the code that you will be writing. In order to set the GOPATH, one must know how to set an environment variable in Linux based operating systems. While there are different bash files that can be present on one’s system, on Ubuntu or other Linux based operating systems, it is generally recommended to make use of the bash_rc which you can open with typing the following command in your terminal. vi ~/.bashrc And if by any chance you are using mac os like me, then the following command will open the zshrc file, which does the same work for you as bashrc in Ubuntu. vi ~/.zshrc It is a good practice to note that the GOPATH can be set to any directory in your system, just make sure that Go is installed on that user if you are using Linux or macOS. To set GOPATH, open the bashrc/ bash_profle/zshrc file and type the following commands in it and then save the file. export GOPATH=/root/go_projects As you can clearly see in the above command where I am exporting a directory, I choose to keep my Go code inside the /root/go_projects directory. While you are free to choose any directory you like, it is recommended that you create a separate new folder for GOPATH. Now inside the go_projects folder, we need to have the three subfolders, mainly − pkg − the directory that will contain the packages and shared object files if any. pkg − the directory that will contain the packages and shared object files if any. src − the directory where all the code you will write will be stored. src − the directory where all the code you will write will be stored. bin − the directory which will contain all the binary executables that you will make. bin − the directory which will contain all the binary executables that you will make. While there are three directories that must be present inside the GOPATH folder, we usually end up spending most of our time inside the src directory where the code that you will write will go. Setting the GOROOT is also important. To do that we need to open the bashrc file again and type in the below command and then source it. export GOROOT=/usr/local/go Now just source the bashrc file with the help of the command shown below − source ~/.bashrc It is always a good habit to check whether your environment variables are set properly or not and you can do that by just typing the following command to your terminal − echo $GOPATH The output must be the path of the directory that you set as an environment variable. /root/go_projects
[ { "code": null, "e": 1319, "s": 1187, "text": "Before setting up GOPATH or GOROOT on the local environment of yours, we must check whether you have correctly installed Go or not." }, { "code": null, "e": 1419, "s": 1319, "text": "Just type the following command on any user of the machine, where you think you have installed Go −" }, { "code": null, "e": 1430, "s": 1419, "text": "go version" }, { "code": null, "e": 1644, "s": 1430, "text": "If it outputs nothing or something like go is not present, then instead of setting the GOPATH first I would recommend that you first download the go binary from this link and then install it on your local machine." }, { "code": null, "e": 1736, "s": 1644, "text": "Normally the output for the case that you have Go installed will look something like this −" }, { "code": null, "e": 1815, "s": 1736, "text": "immukul@192 linux-questions-code % go version\ngo version go1.16.3 darwin/amd64" }, { "code": null, "e": 2079, "s": 1815, "text": "GOPATH is nothing but an environment variable path that needs to be set that tells the Go binary to where to look for the code that you will be writing. In order to set the GOPATH, one must know how to set an environment variable in Linux based operating systems." }, { "code": null, "e": 2329, "s": 2079, "text": "While there are different bash files that can be present on one’s system, on Ubuntu or other Linux based operating systems, it is generally recommended to make use of the bash_rc which you can open with typing the following command in your terminal." }, { "code": null, "e": 2342, "s": 2329, "text": "vi ~/.bashrc" }, { "code": null, "e": 2500, "s": 2342, "text": "And if by any chance you are using mac os like me, then the following command will open the zshrc file, which does the same work for you as bashrc in Ubuntu." }, { "code": null, "e": 2512, "s": 2500, "text": "vi ~/.zshrc" }, { "code": null, "e": 2801, "s": 2512, "text": "It is a good practice to note that the GOPATH can be set to any directory in your system, just make sure that Go is installed on that user if you are using Linux or macOS. To set GOPATH, open the bashrc/ bash_profle/zshrc file and type the following commands in it and then save the file." }, { "code": null, "e": 2833, "s": 2801, "text": "export GOPATH=/root/go_projects" }, { "code": null, "e": 3182, "s": 2833, "text": "As you can clearly see in the above command where I am exporting a directory, I choose to keep my Go code inside the /root/go_projects directory. While you are free to choose any directory you like, it is recommended that you create a separate new folder for GOPATH. Now inside the go_projects folder, we need to have the three subfolders, mainly −" }, { "code": null, "e": 3265, "s": 3182, "text": "pkg − the directory that will contain the packages and shared object files if any." }, { "code": null, "e": 3348, "s": 3265, "text": "pkg − the directory that will contain the packages and shared object files if any." }, { "code": null, "e": 3418, "s": 3348, "text": "src − the directory where all the code you will write will be stored." }, { "code": null, "e": 3488, "s": 3418, "text": "src − the directory where all the code you will write will be stored." }, { "code": null, "e": 3574, "s": 3488, "text": "bin − the directory which will contain all the binary executables that you will make." }, { "code": null, "e": 3660, "s": 3574, "text": "bin − the directory which will contain all the binary executables that you will make." }, { "code": null, "e": 3854, "s": 3660, "text": "While there are three directories that must be present inside the GOPATH folder, we usually end up spending most of our time inside the src directory where the code that you will write will go." }, { "code": null, "e": 3991, "s": 3854, "text": "Setting the GOROOT is also important. To do that we need to open the bashrc file again and type in the below command and then source it." }, { "code": null, "e": 4019, "s": 3991, "text": "export GOROOT=/usr/local/go" }, { "code": null, "e": 4094, "s": 4019, "text": "Now just source the bashrc file with the help of the command shown below −" }, { "code": null, "e": 4111, "s": 4094, "text": "source ~/.bashrc" }, { "code": null, "e": 4281, "s": 4111, "text": "It is always a good habit to check whether your environment variables are set properly or not and you can do that by just typing the following command to your terminal −" }, { "code": null, "e": 4294, "s": 4281, "text": "echo $GOPATH" }, { "code": null, "e": 4380, "s": 4294, "text": "The output must be the path of the directory that you set as an environment variable." }, { "code": null, "e": 4399, "s": 4380, "text": "/root/go_projects\n" } ]
Python – popup menu in wxPython
15 May, 2020 In this article we are going to know how can we create a popupmenu in wxPython. We will write a code when we click right on screen a popup menu will show up with menu items names as ‘one’ and ‘two’. Syntax : wx.Window.PopupMenu(self, menu, pos) Parameters : Code Example : import wx class PopMenu(wx.Menu): def __init__(self, parent): super(PopMenu, self).__init__() self.parent = parent # menu item 1 popmenu = wx.MenuItem(self, wx.NewId(), 'one ') self.Append(popmenu) # menu item 2 popmenu2 = wx.MenuItem(self, wx.NewId(), 'two') self.Append(popmenu2) class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.SetSize((600, 400)) self.SetTitle('Popup Menu') self.Centre() def OnRightDown(self, e): # sow popu menu self.PopupMenu(PopMenu(self), e.GetPosition()) def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output : Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2020" }, { "code": null, "e": 227, "s": 28, "text": "In this article we are going to know how can we create a popupmenu in wxPython. We will write a code when we click right on screen a popup menu will show up with menu items names as ‘one’ and ‘two’." }, { "code": null, "e": 236, "s": 227, "text": "Syntax :" }, { "code": null, "e": 274, "s": 236, "text": "wx.Window.PopupMenu(self, menu, pos)\n" }, { "code": null, "e": 287, "s": 274, "text": "Parameters :" }, { "code": null, "e": 302, "s": 287, "text": "Code Example :" }, { "code": "import wx class PopMenu(wx.Menu): def __init__(self, parent): super(PopMenu, self).__init__() self.parent = parent # menu item 1 popmenu = wx.MenuItem(self, wx.NewId(), 'one ') self.Append(popmenu) # menu item 2 popmenu2 = wx.MenuItem(self, wx.NewId(), 'two') self.Append(popmenu2) class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.SetSize((600, 400)) self.SetTitle('Popup Menu') self.Centre() def OnRightDown(self, e): # sow popu menu self.PopupMenu(PopMenu(self), e.GetPosition()) def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 1200, "s": 302, "text": null }, { "code": null, "e": 1209, "s": 1200, "text": "Output :" }, { "code": null, "e": 1220, "s": 1209, "text": "Python-gui" }, { "code": null, "e": 1236, "s": 1220, "text": "Python-wxPython" }, { "code": null, "e": 1243, "s": 1236, "text": "Python" } ]
Maximum sum submatrix
26 Nov, 2021 Prerequisite: Kadane’s algorithm Given a 2D array arr[][] of dimension N*M, the task is to find the maximum sum sub-matrix from the matrix arr[][]. Examples: Input: arr[][] = {{0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2}}Output: 15Explanation: The submatrix {{9, 2}, {-4, 1}, {-1, 8}} has a sum 15, which is the maximum sum possible. Input: arr[][] = {{1, 2}, {-5, -7}}Output: 3 Naive Approach: The simplest approach is to generate all possible submatrices from the given matrix and calculate their sum. Finally, print the maximum sum obtained. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum sum submatrixvoid maxSubmatrixSum( vector<vector<int> > matrix){ // Stores the number of rows // and columns in the matrix int r = matrix.size(); int c = matrix[0].size(); // Stores maximum submatrix sum int maxSubmatrix = 0; // Take each row as starting row for (int i = 0; i < r; i++) { // Take each column as the // starting column for (int j = 0; j < c; j++) { // Take each row as the // ending row for (int k = i; k < r; k++) { // Take each column as // the ending column for (int l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) int sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (int m = i; m <= k; m++) { for (int n = j; n <= l; n++) { sumSubmatrix += matrix[m][n]; } } // Update the maximum sum maxSubmatrix = max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer cout << maxSubmatrix;} // Driver Codeint main(){ vector<vector<int> > matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; maxSubmatrixSum(matrix); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find maximum sum submatrixstatic void maxSubmatrixSum(int[][] matrix){ // Stores the number of rows // and columns in the matrix int r = matrix.length; int c = matrix[0].length; // Stores maximum submatrix sum int maxSubmatrix = 0; // Take each row as starting row for (int i = 0; i < r; i++) { // Take each column as the // starting column for (int j = 0; j < c; j++) { // Take each row as the // ending row for (int k = i; k < r; k++) { // Take each column as // the ending column for (int l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) int sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (int m = i; m <= k; m++) { for (int n = j; n <= l; n++) { sumSubmatrix += matrix[m][n]; } } // Update the maximum sum maxSubmatrix = Math.max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer System.out.println(maxSubmatrix);} // Driver Codepublic static void main(String[] args){ int[][] matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; maxSubmatrixSum(matrix);}} // This code is contributed by susmitakundugoaldanga. # Python3 program for the above approach # Function to find maximum sum submatrixdef maxSubmatrixSum(matrix): # Stores the number of rows # and columns in the matrix r = len(matrix) c = len(matrix[0]) # Stores maximum submatrix sum maxSubmatrix = 0 # Take each row as starting row for i in range(r): # Take each column as the # starting column for j in range(c): # Take each row as the # ending row for k in range(i, r): # Take each column as # the ending column for l in range(j, c): # Stores the sum of submatrix # having topleft index(i, j) # and bottom right index (k, l) sumSubmatrix = 0 # Iterate the submatrix # row-wise and calculate its sum for m in range(i, k + 1): for n in range(j, l + 1): sumSubmatrix += matrix[m][n] # Update the maximum sum maxSubmatrix= max(maxSubmatrix, sumSubmatrix) # Print the answer print (maxSubmatrix) # Driver Codeif __name__ == '__main__': matrix = [ [ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ] ] maxSubmatrixSum(matrix) # This code is contributed by mohit kumar 29. // C# program to implement// the above approachusing System;public class GFG{// Function to find maximum sum submatrixstatic void maxSubmatrixSum(int[,] matrix){ // Stores the number of rows // and columns in the matrix int r = matrix.GetLength(0); int c = matrix.GetLength(1); // Stores maximum submatrix sum int maxSubmatrix = 0; // Take each row as starting row for (int i = 0; i < r; i++) { // Take each column as the // starting column for (int j = 0; j < c; j++) { // Take each row as the // ending row for (int k = i; k < r; k++) { // Take each column as // the ending column for (int l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) int sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (int m = i; m <= k; m++) { for (int n = j; n <= l; n++) { sumSubmatrix += matrix[m, n]; } } // Update the maximum sum maxSubmatrix = Math.Max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer Console.WriteLine(maxSubmatrix);} // Driver Codepublic static void Main(String []args){ int[,] matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; maxSubmatrixSum(matrix);}} // This code is contributed by sanjoy_62. <script> // Javascript program for the above approach // Function to find maximum sum submatrix function maxSubmatrixSum(matrix) { // Stores the number of rows // and columns in the matrix var r = matrix.length; var c = matrix[0].length; // Stores maximum submatrix sum var maxSubmatrix = 0; // Take each row as starting row for (i = 0; i < r; i++) { // Take each column as the // starting column for (j = 0; j < c; j++) { // Take each row as the // ending row for (k = i; k < r; k++) { // Take each column as // the ending column for (l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) var sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (m = i; m <= k; m++) { for (n = j; n <= l; n++) { sumSubmatrix += matrix[m][n]; } } // Update the maximum sum maxSubmatrix = Math.max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer document.write(maxSubmatrix); } // Driver Code var matrix = [ [ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ] ]; maxSubmatrixSum(matrix); // This code contributed by umadevi9616 </script> 15 Time Complexity: O(N6)Auxiliary Space: O(1) Efficient Approach using Kadane’s Algorithm: The above approach can be optimized using the following observations: Fix starting and ending column of the required sub-matrix say start and end respectively. Now, iterate each row and add row sum from starting to ending column to sumSubmatrix and insert this in an array. After iterating each row, perform Kadane’s Algorithm on this newly created array. If the sum obtained by applying Kadane’s algorithm is greater than the overall maximum sum, update the overall maximum sum. In the above step, the row sum from starting to ending column can be calculated in constant time by creating an auxiliary matrix of size N*M containing the prefix sum of each row. Follow the steps below to solve the problem: Initialize a variable, say maxSum as INT_MIN, to store the maximum subarray sum. Create a matrix prefMatrix[N][M] that stores the prefix array sum of every row of the given matrix. Traverse the matrix row-wise using i as the row index and j as the column index and perform the following steps:If the value of i is 0, then set prefMatrix[i][j] = A[i][j].Otherwise, set prefMatrix[i][j] = prefMatrix[i][j – 1] + A[i][j]. If the value of i is 0, then set prefMatrix[i][j] = A[i][j]. Otherwise, set prefMatrix[i][j] = prefMatrix[i][j – 1] + A[i][j]. Now for all possible combinations of starting and ending index of the columns of submatrix over the range [0, M] perform the following steps:Initialize an auxiliary array A[] to stores the maximum sum for each row of the current submatrix.Find the sum from starting to ending column using prefMatrix as follows:If the value of start is positive, then store the required sum S as prefMatrix[i][end] – prefMatrix[i][start – 1].Otherwise, update S as prefMatrix[i][end].Insert S in an array arr[].After iterating all rows in the submatrix, perform Kadane’s algorithm on the array A[] and update the maximum sum maxSum as the maximum of maxSum and value obtained by performing the Kadane’s Algorithm in this step. Initialize an auxiliary array A[] to stores the maximum sum for each row of the current submatrix. Find the sum from starting to ending column using prefMatrix as follows:If the value of start is positive, then store the required sum S as prefMatrix[i][end] – prefMatrix[i][start – 1].Otherwise, update S as prefMatrix[i][end]. If the value of start is positive, then store the required sum S as prefMatrix[i][end] – prefMatrix[i][start – 1]. Otherwise, update S as prefMatrix[i][end]. Insert S in an array arr[]. After iterating all rows in the submatrix, perform Kadane’s algorithm on the array A[] and update the maximum sum maxSum as the maximum of maxSum and value obtained by performing the Kadane’s Algorithm in this step. After completing the above steps, print the value of maxSum as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum continuous// maximum sum in the arrayint kadane(vector<int> v){ // Stores current and maximum sum int currSum = 0; int maxSum = INT_MIN; // Traverse the array v for (int i = 0; i < (int)v.size(); i++) { // Add the value of the // current element currSum += v[i]; // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum;} // Function to find the maximum// submatrix sumvoid maxSubmatrixSum( vector<vector<int> > A){ // Store the rows and columns // of the matrix int r = A.size(); int c = A[0].size(); // Create an auxiliary matrix int** prefix = new int*[r]; // Traverse the matrix, prefix // and initialize it will all 0s for (int i = 0; i < r; i++) { prefix[i] = new int; for (int j = 0; j < c; j++) { prefix[i][j] = 0; } } // Calculate prefix sum of all // rows of matrix A[][] and // store in matrix prefix[] for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { // Update the prefix[][] if (j == 0) prefix[i][j] = A[i][j]; else prefix[i][j] = A[i][j] + prefix[i][j - 1]; } } // Store the maximum submatrix sum int maxSum = INT_MIN; // Iterate for starting column for (int i = 0; i < c; i++) { // Iterate for last column for (int j = i; j < c; j++) { // To store current array // elements vector<int> v; // Traverse every row for (int k = 0; k < r; k++) { // Store the sum of the // kth row int el = 0; // Update the prefix // sum if (i == 0) el = prefix[k][j]; else el = prefix[k][j] - prefix[k][i - 1]; // Push it in a vector v.push_back(el); } // Update the maximum // overall sum maxSum = max(maxSum, kadane(v)); } } // Print the answer cout << maxSum << "\n";} // Driver Codeint main(){ vector<vector<int> > matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; // Function Call maxSubmatrixSum(matrix); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find maximum continuous // maximum sum in the array static int kadane(Vector<Integer> v) { // Stores current and maximum sum int currSum = 0; int maxSum = Integer.MIN_VALUE; // Traverse the array v for (int i = 0; i < (int)v.size(); i++) { // Add the value of the // current element currSum += v.get(i); // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum; } // Function to find the maximum // submatrix sum static void maxSubmatrixSum(int [][]A) { // Store the rows and columns // of the matrix int r = A.length; int c = A[0].length; // Create an auxiliary matrix int [][]prefix = new int[r][]; // Traverse the matrix, prefix // and initialize it will all 0s for (int i = 0; i < r; i++) { prefix[i] = new int; for (int j = 0; j < c; j++) { prefix[i][j] = 0; } } // Calculate prefix sum of all // rows of matrix A[][] and // store in matrix prefix[] for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { // Update the prefix[][] if (j == 0) prefix[i][j] = A[i][j]; else prefix[i][j] = A[i][j] + prefix[i][j - 1]; } } // Store the maximum submatrix sum int maxSum = Integer.MIN_VALUE; // Iterate for starting column for (int i = 0; i < c; i++) { // Iterate for last column for (int j = i; j < c; j++) { // To store current array // elements Vector<Integer> v = new Vector<Integer>(); // Traverse every row for (int k = 0; k < r; k++) { // Store the sum of the // kth row int el = 0; // Update the prefix // sum if (i == 0) el = prefix[k][j]; else el = prefix[k][j] - prefix[k][i - 1]; // Push it in a vector v.add(el); } // Update the maximum // overall sum maxSum = Math.max(maxSum, kadane(v)); } } // Print the answer System.out.print(maxSum+ "\n"); } // Driver Code public static void main(String[] args) { int [][]matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; // Function Call maxSubmatrixSum(matrix); }} // This code is contributed by 29AjayKumar # Python3 program for the above approachimport sys # Function to find maximum continuous# maximum sum in the arraydef kadane(v): # Stores current and maximum sum currSum = 0 maxSum = -sys.maxsize - 1 # Traverse the array v for i in range(len(v)): # Add the value of the # current element currSum += v[i] # Update the maximum sum if (currSum > maxSum): maxSum = currSum if (currSum < 0): currSum = 0 # Return the maximum sum return maxSum # Function to find the maximum# submatrix sumdef maxSubmatrixSum(A): # Store the rows and columns # of the matrix r = len(A) c = len(A[0]) # Create an auxiliary matrix # Traverse the matrix, prefix # and initialize it will all 0s prefix = [[0 for i in range(c)] for j in range(r)] # Calculate prefix sum of all # rows of matrix A[][] and # store in matrix prefix[] for i in range(r): for j in range(c): # Update the prefix[][] if (j == 0): prefix[i][j] = A[i][j] else: prefix[i][j] = A[i][j] + prefix[i][j - 1] # Store the maximum submatrix sum maxSum = -sys.maxsize - 1 # Iterate for starting column for i in range(c): # Iterate for last column for j in range(i, c): # To store current array # elements v = [] # Traverse every row for k in range(r): # Store the sum of the # kth row el = 0 # Update the prefix # sum if (i == 0): el = prefix[k][j] else: el = prefix[k][j] - prefix[k][i - 1] # Push it in a vector v.append(el) # Update the maximum # overall sum maxSum = max(maxSum, kadane(v)) # Print the answer print(maxSum) # Driver Codematrix = [ [ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ] ] # Function CallmaxSubmatrixSum(matrix) # This code is contributed by rag2127 // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find maximum continuous // maximum sum in the array static int kadane(List<int> v) { // Stores current and maximum sum int currSum = 0; int maxSum = int.MinValue; // Traverse the array v for (int i = 0; i < (int)v.Count; i++) { // Add the value of the // current element currSum += v[i]; // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum; } // Function to find the maximum // submatrix sum static void maxSubmatrixSum(int [,]A) { // Store the rows and columns // of the matrix int r = A.GetLength(0); int c = A.GetLength(1); // Create an auxiliary matrix int [,]prefix = new int[r,c]; // Traverse the matrix, prefix // and initialize it will all 0s for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { prefix[i,j] = 0; } } // Calculate prefix sum of all // rows of matrix [,]A and // store in matrix prefix[] for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { // Update the prefix[,] if (j == 0) prefix[i,j] = A[i,j]; else prefix[i,j] = A[i,j] + prefix[i,j - 1]; } } // Store the maximum submatrix sum int maxSum = int.MinValue; // Iterate for starting column for (int i = 0; i < c; i++) { // Iterate for last column for (int j = i; j < c; j++) { // To store current array // elements List<int> v = new List<int>(); // Traverse every row for (int k = 0; k < r; k++) { // Store the sum of the // kth row int el = 0; // Update the prefix // sum if (i == 0) el = prefix[k,j]; else el = prefix[k,j] - prefix[k,i - 1]; // Push it in a vector v.Add(el); } // Update the maximum // overall sum maxSum = Math.Max(maxSum, kadane(v)); } } // Print the answer Console.Write(maxSum+ "\n"); } // Driver Code public static void Main(String[] args) { int [,]matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; // Function Call maxSubmatrixSum(matrix); }} // This code is contributed by 29AjayKumar <script>// Javascript program for the above approach // Function to find maximum continuous// maximum sum in the array function kadane(v){ // Stores current and maximum sum let currSum = 0; let maxSum = Number.MIN_VALUE; // Traverse the array v for (let i = 0; i < v.length; i++) { // Add the value of the // current element currSum += v[i]; // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum;} // Function to find the maximum// submatrix sumfunction maxSubmatrixSum(A){ // Store the rows and columns // of the matrix let r = A.length; let c = A[0].length; // Create an auxiliary matrix let prefix = new Array(r); // Traverse the matrix, prefix // and initialize it will all 0s for (let i = 0; i < r; i++) { prefix[i] = new Array(c); for (let j = 0; j < c; j++) { prefix[i][j] = 0; } } // Calculate prefix sum of all // rows of matrix A[][] and // store in matrix prefix[] for (let i = 0; i < r; i++) { for (let j = 0; j < c; j++) { // Update the prefix[][] if (j == 0) prefix[i][j] = A[i][j]; else prefix[i][j] = A[i][j] + prefix[i][j - 1]; } } // Store the maximum submatrix sum let maxSum = Number.MIN_VALUE; // Iterate for starting column for (let i = 0; i < c; i++) { // Iterate for last column for (let j = i; j < c; j++) { // To store current array // elements let v = []; // Traverse every row for (let k = 0; k < r; k++) { // Store the sum of the // kth row let el = 0; // Update the prefix // sum if (i == 0) el = prefix[k][j]; else el = prefix[k][j] - prefix[k][i - 1]; // Push it in a vector v.push(el); } // Update the maximum // overall sum maxSum = Math.max(maxSum, kadane(v)); } } // Print the answer document.write(maxSum+ "<br>");} // Driver Codelet matrix=[[ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ]];// Function CallmaxSubmatrixSum(matrix); // This code is contributed by unknown2108</script> 15 Time Complexity: O(N3)Auxiliary Space: O(N2) mohit kumar 29 susmitakundugoaldanga sanjoy_62 29AjayKumar rag2127 umadevi9616 unknown2108 ankita_saini prefix-sum subarray subarray-sum submatrix Technical Scripter 2020 Dynamic Programming Mathematical Matrix Technical Scripter prefix-sum Dynamic Programming Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Find if there is a path between two vertices in an undirected graph 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
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Nov, 2021" }, { "code": null, "e": 85, "s": 52, "text": "Prerequisite: Kadane’s algorithm" }, { "code": null, "e": 200, "s": 85, "text": "Given a 2D array arr[][] of dimension N*M, the task is to find the maximum sum sub-matrix from the matrix arr[][]." }, { "code": null, "e": 210, "s": 200, "text": "Examples:" }, { "code": null, "e": 410, "s": 210, "text": "Input: arr[][] = {{0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2}}Output: 15Explanation: The submatrix {{9, 2}, {-4, 1}, {-1, 8}} has a sum 15, which is the maximum sum possible." }, { "code": null, "e": 455, "s": 410, "text": "Input: arr[][] = {{1, 2}, {-5, -7}}Output: 3" }, { "code": null, "e": 621, "s": 455, "text": "Naive Approach: The simplest approach is to generate all possible submatrices from the given matrix and calculate their sum. Finally, print the maximum sum obtained." }, { "code": null, "e": 672, "s": 621, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 676, "s": 672, "text": "C++" }, { "code": null, "e": 681, "s": 676, "text": "Java" }, { "code": null, "e": 689, "s": 681, "text": "Python3" }, { "code": null, "e": 692, "s": 689, "text": "C#" }, { "code": null, "e": 703, "s": 692, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum sum submatrixvoid maxSubmatrixSum( vector<vector<int> > matrix){ // Stores the number of rows // and columns in the matrix int r = matrix.size(); int c = matrix[0].size(); // Stores maximum submatrix sum int maxSubmatrix = 0; // Take each row as starting row for (int i = 0; i < r; i++) { // Take each column as the // starting column for (int j = 0; j < c; j++) { // Take each row as the // ending row for (int k = i; k < r; k++) { // Take each column as // the ending column for (int l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) int sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (int m = i; m <= k; m++) { for (int n = j; n <= l; n++) { sumSubmatrix += matrix[m][n]; } } // Update the maximum sum maxSubmatrix = max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer cout << maxSubmatrix;} // Driver Codeint main(){ vector<vector<int> > matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; maxSubmatrixSum(matrix); return 0;}", "e": 2491, "s": 703, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find maximum sum submatrixstatic void maxSubmatrixSum(int[][] matrix){ // Stores the number of rows // and columns in the matrix int r = matrix.length; int c = matrix[0].length; // Stores maximum submatrix sum int maxSubmatrix = 0; // Take each row as starting row for (int i = 0; i < r; i++) { // Take each column as the // starting column for (int j = 0; j < c; j++) { // Take each row as the // ending row for (int k = i; k < r; k++) { // Take each column as // the ending column for (int l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) int sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (int m = i; m <= k; m++) { for (int n = j; n <= l; n++) { sumSubmatrix += matrix[m][n]; } } // Update the maximum sum maxSubmatrix = Math.max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer System.out.println(maxSubmatrix);} // Driver Codepublic static void main(String[] args){ int[][] matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; maxSubmatrixSum(matrix);}} // This code is contributed by susmitakundugoaldanga.", "e": 4297, "s": 2491, "text": null }, { "code": "# Python3 program for the above approach # Function to find maximum sum submatrixdef maxSubmatrixSum(matrix): # Stores the number of rows # and columns in the matrix r = len(matrix) c = len(matrix[0]) # Stores maximum submatrix sum maxSubmatrix = 0 # Take each row as starting row for i in range(r): # Take each column as the # starting column for j in range(c): # Take each row as the # ending row for k in range(i, r): # Take each column as # the ending column for l in range(j, c): # Stores the sum of submatrix # having topleft index(i, j) # and bottom right index (k, l) sumSubmatrix = 0 # Iterate the submatrix # row-wise and calculate its sum for m in range(i, k + 1): for n in range(j, l + 1): sumSubmatrix += matrix[m][n] # Update the maximum sum maxSubmatrix= max(maxSubmatrix, sumSubmatrix) # Print the answer print (maxSubmatrix) # Driver Codeif __name__ == '__main__': matrix = [ [ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ] ] maxSubmatrixSum(matrix) # This code is contributed by mohit kumar 29.", "e": 5750, "s": 4297, "text": null }, { "code": "// C# program to implement// the above approachusing System;public class GFG{// Function to find maximum sum submatrixstatic void maxSubmatrixSum(int[,] matrix){ // Stores the number of rows // and columns in the matrix int r = matrix.GetLength(0); int c = matrix.GetLength(1); // Stores maximum submatrix sum int maxSubmatrix = 0; // Take each row as starting row for (int i = 0; i < r; i++) { // Take each column as the // starting column for (int j = 0; j < c; j++) { // Take each row as the // ending row for (int k = i; k < r; k++) { // Take each column as // the ending column for (int l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) int sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (int m = i; m <= k; m++) { for (int n = j; n <= l; n++) { sumSubmatrix += matrix[m, n]; } } // Update the maximum sum maxSubmatrix = Math.Max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer Console.WriteLine(maxSubmatrix);} // Driver Codepublic static void Main(String []args){ int[,] matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; maxSubmatrixSum(matrix);}} // This code is contributed by sanjoy_62.", "e": 7557, "s": 5750, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find maximum sum submatrix function maxSubmatrixSum(matrix) { // Stores the number of rows // and columns in the matrix var r = matrix.length; var c = matrix[0].length; // Stores maximum submatrix sum var maxSubmatrix = 0; // Take each row as starting row for (i = 0; i < r; i++) { // Take each column as the // starting column for (j = 0; j < c; j++) { // Take each row as the // ending row for (k = i; k < r; k++) { // Take each column as // the ending column for (l = j; l < c; l++) { // Stores the sum of submatrix // having topleft index(i, j) // and bottom right index (k, l) var sumSubmatrix = 0; // Iterate the submatrix // row-wise and calculate its sum for (m = i; m <= k; m++) { for (n = j; n <= l; n++) { sumSubmatrix += matrix[m][n]; } } // Update the maximum sum maxSubmatrix = Math.max(maxSubmatrix, sumSubmatrix); } } } } // Print the answer document.write(maxSubmatrix); } // Driver Code var matrix = [ [ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ] ]; maxSubmatrixSum(matrix); // This code contributed by umadevi9616 </script>", "e": 9357, "s": 7557, "text": null }, { "code": null, "e": 9360, "s": 9357, "text": "15" }, { "code": null, "e": 9406, "s": 9362, "text": "Time Complexity: O(N6)Auxiliary Space: O(1)" }, { "code": null, "e": 9521, "s": 9406, "text": "Efficient Approach using Kadane’s Algorithm: The above approach can be optimized using the following observations:" }, { "code": null, "e": 9611, "s": 9521, "text": "Fix starting and ending column of the required sub-matrix say start and end respectively." }, { "code": null, "e": 9931, "s": 9611, "text": "Now, iterate each row and add row sum from starting to ending column to sumSubmatrix and insert this in an array. After iterating each row, perform Kadane’s Algorithm on this newly created array. If the sum obtained by applying Kadane’s algorithm is greater than the overall maximum sum, update the overall maximum sum." }, { "code": null, "e": 10111, "s": 9931, "text": "In the above step, the row sum from starting to ending column can be calculated in constant time by creating an auxiliary matrix of size N*M containing the prefix sum of each row." }, { "code": null, "e": 10156, "s": 10111, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 10237, "s": 10156, "text": "Initialize a variable, say maxSum as INT_MIN, to store the maximum subarray sum." }, { "code": null, "e": 10337, "s": 10237, "text": "Create a matrix prefMatrix[N][M] that stores the prefix array sum of every row of the given matrix." }, { "code": null, "e": 10575, "s": 10337, "text": "Traverse the matrix row-wise using i as the row index and j as the column index and perform the following steps:If the value of i is 0, then set prefMatrix[i][j] = A[i][j].Otherwise, set prefMatrix[i][j] = prefMatrix[i][j – 1] + A[i][j]." }, { "code": null, "e": 10636, "s": 10575, "text": "If the value of i is 0, then set prefMatrix[i][j] = A[i][j]." }, { "code": null, "e": 10702, "s": 10636, "text": "Otherwise, set prefMatrix[i][j] = prefMatrix[i][j – 1] + A[i][j]." }, { "code": null, "e": 11412, "s": 10702, "text": "Now for all possible combinations of starting and ending index of the columns of submatrix over the range [0, M] perform the following steps:Initialize an auxiliary array A[] to stores the maximum sum for each row of the current submatrix.Find the sum from starting to ending column using prefMatrix as follows:If the value of start is positive, then store the required sum S as prefMatrix[i][end] – prefMatrix[i][start – 1].Otherwise, update S as prefMatrix[i][end].Insert S in an array arr[].After iterating all rows in the submatrix, perform Kadane’s algorithm on the array A[] and update the maximum sum maxSum as the maximum of maxSum and value obtained by performing the Kadane’s Algorithm in this step." }, { "code": null, "e": 11511, "s": 11412, "text": "Initialize an auxiliary array A[] to stores the maximum sum for each row of the current submatrix." }, { "code": null, "e": 11740, "s": 11511, "text": "Find the sum from starting to ending column using prefMatrix as follows:If the value of start is positive, then store the required sum S as prefMatrix[i][end] – prefMatrix[i][start – 1].Otherwise, update S as prefMatrix[i][end]." }, { "code": null, "e": 11855, "s": 11740, "text": "If the value of start is positive, then store the required sum S as prefMatrix[i][end] – prefMatrix[i][start – 1]." }, { "code": null, "e": 11898, "s": 11855, "text": "Otherwise, update S as prefMatrix[i][end]." }, { "code": null, "e": 11926, "s": 11898, "text": "Insert S in an array arr[]." }, { "code": null, "e": 12142, "s": 11926, "text": "After iterating all rows in the submatrix, perform Kadane’s algorithm on the array A[] and update the maximum sum maxSum as the maximum of maxSum and value obtained by performing the Kadane’s Algorithm in this step." }, { "code": null, "e": 12217, "s": 12142, "text": "After completing the above steps, print the value of maxSum as the result." }, { "code": null, "e": 12268, "s": 12217, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 12272, "s": 12268, "text": "C++" }, { "code": null, "e": 12277, "s": 12272, "text": "Java" }, { "code": null, "e": 12285, "s": 12277, "text": "Python3" }, { "code": null, "e": 12288, "s": 12285, "text": "C#" }, { "code": null, "e": 12299, "s": 12288, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum continuous// maximum sum in the arrayint kadane(vector<int> v){ // Stores current and maximum sum int currSum = 0; int maxSum = INT_MIN; // Traverse the array v for (int i = 0; i < (int)v.size(); i++) { // Add the value of the // current element currSum += v[i]; // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum;} // Function to find the maximum// submatrix sumvoid maxSubmatrixSum( vector<vector<int> > A){ // Store the rows and columns // of the matrix int r = A.size(); int c = A[0].size(); // Create an auxiliary matrix int** prefix = new int*[r]; // Traverse the matrix, prefix // and initialize it will all 0s for (int i = 0; i < r; i++) { prefix[i] = new int; for (int j = 0; j < c; j++) { prefix[i][j] = 0; } } // Calculate prefix sum of all // rows of matrix A[][] and // store in matrix prefix[] for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { // Update the prefix[][] if (j == 0) prefix[i][j] = A[i][j]; else prefix[i][j] = A[i][j] + prefix[i][j - 1]; } } // Store the maximum submatrix sum int maxSum = INT_MIN; // Iterate for starting column for (int i = 0; i < c; i++) { // Iterate for last column for (int j = i; j < c; j++) { // To store current array // elements vector<int> v; // Traverse every row for (int k = 0; k < r; k++) { // Store the sum of the // kth row int el = 0; // Update the prefix // sum if (i == 0) el = prefix[k][j]; else el = prefix[k][j] - prefix[k][i - 1]; // Push it in a vector v.push_back(el); } // Update the maximum // overall sum maxSum = max(maxSum, kadane(v)); } } // Print the answer cout << maxSum << \"\\n\";} // Driver Codeint main(){ vector<vector<int> > matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; // Function Call maxSubmatrixSum(matrix); return 0;}", "e": 15040, "s": 12299, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find maximum continuous // maximum sum in the array static int kadane(Vector<Integer> v) { // Stores current and maximum sum int currSum = 0; int maxSum = Integer.MIN_VALUE; // Traverse the array v for (int i = 0; i < (int)v.size(); i++) { // Add the value of the // current element currSum += v.get(i); // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum; } // Function to find the maximum // submatrix sum static void maxSubmatrixSum(int [][]A) { // Store the rows and columns // of the matrix int r = A.length; int c = A[0].length; // Create an auxiliary matrix int [][]prefix = new int[r][]; // Traverse the matrix, prefix // and initialize it will all 0s for (int i = 0; i < r; i++) { prefix[i] = new int; for (int j = 0; j < c; j++) { prefix[i][j] = 0; } } // Calculate prefix sum of all // rows of matrix A[][] and // store in matrix prefix[] for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { // Update the prefix[][] if (j == 0) prefix[i][j] = A[i][j]; else prefix[i][j] = A[i][j] + prefix[i][j - 1]; } } // Store the maximum submatrix sum int maxSum = Integer.MIN_VALUE; // Iterate for starting column for (int i = 0; i < c; i++) { // Iterate for last column for (int j = i; j < c; j++) { // To store current array // elements Vector<Integer> v = new Vector<Integer>(); // Traverse every row for (int k = 0; k < r; k++) { // Store the sum of the // kth row int el = 0; // Update the prefix // sum if (i == 0) el = prefix[k][j]; else el = prefix[k][j] - prefix[k][i - 1]; // Push it in a vector v.add(el); } // Update the maximum // overall sum maxSum = Math.max(maxSum, kadane(v)); } } // Print the answer System.out.print(maxSum+ \"\\n\"); } // Driver Code public static void main(String[] args) { int [][]matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; // Function Call maxSubmatrixSum(matrix); }} // This code is contributed by 29AjayKumar", "e": 17661, "s": 15040, "text": null }, { "code": "# Python3 program for the above approachimport sys # Function to find maximum continuous# maximum sum in the arraydef kadane(v): # Stores current and maximum sum currSum = 0 maxSum = -sys.maxsize - 1 # Traverse the array v for i in range(len(v)): # Add the value of the # current element currSum += v[i] # Update the maximum sum if (currSum > maxSum): maxSum = currSum if (currSum < 0): currSum = 0 # Return the maximum sum return maxSum # Function to find the maximum# submatrix sumdef maxSubmatrixSum(A): # Store the rows and columns # of the matrix r = len(A) c = len(A[0]) # Create an auxiliary matrix # Traverse the matrix, prefix # and initialize it will all 0s prefix = [[0 for i in range(c)] for j in range(r)] # Calculate prefix sum of all # rows of matrix A[][] and # store in matrix prefix[] for i in range(r): for j in range(c): # Update the prefix[][] if (j == 0): prefix[i][j] = A[i][j] else: prefix[i][j] = A[i][j] + prefix[i][j - 1] # Store the maximum submatrix sum maxSum = -sys.maxsize - 1 # Iterate for starting column for i in range(c): # Iterate for last column for j in range(i, c): # To store current array # elements v = [] # Traverse every row for k in range(r): # Store the sum of the # kth row el = 0 # Update the prefix # sum if (i == 0): el = prefix[k][j] else: el = prefix[k][j] - prefix[k][i - 1] # Push it in a vector v.append(el) # Update the maximum # overall sum maxSum = max(maxSum, kadane(v)) # Print the answer print(maxSum) # Driver Codematrix = [ [ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ] ] # Function CallmaxSubmatrixSum(matrix) # This code is contributed by rag2127", "e": 20020, "s": 17661, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find maximum continuous // maximum sum in the array static int kadane(List<int> v) { // Stores current and maximum sum int currSum = 0; int maxSum = int.MinValue; // Traverse the array v for (int i = 0; i < (int)v.Count; i++) { // Add the value of the // current element currSum += v[i]; // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum; } // Function to find the maximum // submatrix sum static void maxSubmatrixSum(int [,]A) { // Store the rows and columns // of the matrix int r = A.GetLength(0); int c = A.GetLength(1); // Create an auxiliary matrix int [,]prefix = new int[r,c]; // Traverse the matrix, prefix // and initialize it will all 0s for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { prefix[i,j] = 0; } } // Calculate prefix sum of all // rows of matrix [,]A and // store in matrix prefix[] for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { // Update the prefix[,] if (j == 0) prefix[i,j] = A[i,j]; else prefix[i,j] = A[i,j] + prefix[i,j - 1]; } } // Store the maximum submatrix sum int maxSum = int.MinValue; // Iterate for starting column for (int i = 0; i < c; i++) { // Iterate for last column for (int j = i; j < c; j++) { // To store current array // elements List<int> v = new List<int>(); // Traverse every row for (int k = 0; k < r; k++) { // Store the sum of the // kth row int el = 0; // Update the prefix // sum if (i == 0) el = prefix[k,j]; else el = prefix[k,j] - prefix[k,i - 1]; // Push it in a vector v.Add(el); } // Update the maximum // overall sum maxSum = Math.Max(maxSum, kadane(v)); } } // Print the answer Console.Write(maxSum+ \"\\n\"); } // Driver Code public static void Main(String[] args) { int [,]matrix = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2 } }; // Function Call maxSubmatrixSum(matrix); }} // This code is contributed by 29AjayKumar", "e": 22606, "s": 20020, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find maximum continuous// maximum sum in the array function kadane(v){ // Stores current and maximum sum let currSum = 0; let maxSum = Number.MIN_VALUE; // Traverse the array v for (let i = 0; i < v.length; i++) { // Add the value of the // current element currSum += v[i]; // Update the maximum sum if (currSum > maxSum) { maxSum = currSum; } if (currSum < 0) { currSum = 0; } } // Return the maximum sum return maxSum;} // Function to find the maximum// submatrix sumfunction maxSubmatrixSum(A){ // Store the rows and columns // of the matrix let r = A.length; let c = A[0].length; // Create an auxiliary matrix let prefix = new Array(r); // Traverse the matrix, prefix // and initialize it will all 0s for (let i = 0; i < r; i++) { prefix[i] = new Array(c); for (let j = 0; j < c; j++) { prefix[i][j] = 0; } } // Calculate prefix sum of all // rows of matrix A[][] and // store in matrix prefix[] for (let i = 0; i < r; i++) { for (let j = 0; j < c; j++) { // Update the prefix[][] if (j == 0) prefix[i][j] = A[i][j]; else prefix[i][j] = A[i][j] + prefix[i][j - 1]; } } // Store the maximum submatrix sum let maxSum = Number.MIN_VALUE; // Iterate for starting column for (let i = 0; i < c; i++) { // Iterate for last column for (let j = i; j < c; j++) { // To store current array // elements let v = []; // Traverse every row for (let k = 0; k < r; k++) { // Store the sum of the // kth row let el = 0; // Update the prefix // sum if (i == 0) el = prefix[k][j]; else el = prefix[k][j] - prefix[k][i - 1]; // Push it in a vector v.push(el); } // Update the maximum // overall sum maxSum = Math.max(maxSum, kadane(v)); } } // Print the answer document.write(maxSum+ \"<br>\");} // Driver Codelet matrix=[[ 0, -2, -7, 0 ], [ 9, 2, -6, 2 ], [ -4, 1, -4, 1 ], [ -1, 8, 0, -2 ]];// Function CallmaxSubmatrixSum(matrix); // This code is contributed by unknown2108</script>", "e": 25085, "s": 22606, "text": null }, { "code": null, "e": 25088, "s": 25085, "text": "15" }, { "code": null, "e": 25135, "s": 25090, "text": "Time Complexity: O(N3)Auxiliary Space: O(N2)" }, { "code": null, "e": 25150, "s": 25135, "text": "mohit kumar 29" }, { "code": null, "e": 25172, "s": 25150, "text": "susmitakundugoaldanga" }, { "code": null, "e": 25182, "s": 25172, "text": "sanjoy_62" }, { "code": null, "e": 25194, "s": 25182, "text": "29AjayKumar" }, { "code": null, "e": 25202, "s": 25194, "text": "rag2127" }, { "code": null, "e": 25214, "s": 25202, "text": "umadevi9616" }, { "code": null, "e": 25226, "s": 25214, "text": "unknown2108" }, { "code": null, "e": 25239, "s": 25226, "text": "ankita_saini" }, { "code": null, "e": 25250, "s": 25239, "text": "prefix-sum" }, { "code": null, "e": 25259, "s": 25250, "text": "subarray" }, { "code": null, "e": 25272, "s": 25259, "text": "subarray-sum" }, { "code": null, "e": 25282, "s": 25272, "text": "submatrix" }, { "code": null, "e": 25306, "s": 25282, "text": "Technical Scripter 2020" }, { "code": null, "e": 25326, "s": 25306, "text": "Dynamic Programming" }, { "code": null, "e": 25339, "s": 25326, "text": "Mathematical" }, { "code": null, "e": 25346, "s": 25339, "text": "Matrix" }, { "code": null, "e": 25365, "s": 25346, "text": "Technical Scripter" }, { "code": null, "e": 25376, "s": 25365, "text": "prefix-sum" }, { "code": null, "e": 25396, "s": 25376, "text": "Dynamic Programming" }, { "code": null, "e": 25409, "s": 25396, "text": "Mathematical" }, { "code": null, "e": 25416, "s": 25409, "text": "Matrix" }, { "code": null, "e": 25514, "s": 25416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25541, "s": 25514, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 25579, "s": 25541, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 25612, "s": 25579, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 25631, "s": 25612, "text": "Coin Change | DP-7" }, { "code": null, "e": 25699, "s": 25631, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 25742, "s": 25699, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 25802, "s": 25742, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 25817, "s": 25802, "text": "C++ Data Types" }, { "code": null, "e": 25841, "s": 25817, "text": "Merge two sorted arrays" } ]
How to convert an Object {} to an Array [] of key-value pairs in JavaScript?
10 May, 2022 The task is to convert an Object {} to an Array [] of key-value pairs using JavaScript. Introduction: Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types, while the array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. We can convert an Object {} to an Array [] of key-value pairs using methods discussed below: Method 1: In this method, we will use Object.keys() and map() to achieve this. Approach: By using Object.keys(), we are extracting keys from the Object then this key passed to map() function which maps the key and corresponding value as an array, as described in the below example. Syntax: Object.keys(obj) Parameter: obj: It is the object whose enumerable properties are to be returned. map(function callback(currentValue[, index[, array]]){ // Return element for new_array } Parameter: callback: Function that produces an element of the new Array Example: javascript <script> // An Object var obj = { "1": 5, "2": 7, "3": 0, "4": 0, "5": 0 }; // Using Object.keys() and map() function // to convert an Object {} to an // Array [] of key-value pairs var result = Object.keys(obj).map(function (key) { // Using Number() to convert key to number type // Using obj[key] to retrieve key value return [Number(key), obj[key]]; }); // Printing values for(var i = 0; i < result.length; i++) { for(var z = 0; z < result[i].length; z++) { document.write(result[i][z] + " "); } document.write("</br>"); } </script> Output: 1 5 2 7 3 0 4 0 5 0 Method 2: In this method, we will use Object.entries() to achieve this. Approach: We will use Object.entries() which is available in JavaScript. Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter. The ordering of the properties is the same as that given by looping over the property values of the object manually. Syntax: Object.entries(obj) Parameter: obj: It is the object whose enumerable own property [key, value] pairs are to be returned. Example: javascript <script> // An Object var obj = { "1": 500, "2": 15, "5": 4, "4": 480, "10": 87 }; // Using Object.entries() function // to convert an Object {} to an // Array [] of key-value pairs var result = Object.entries(obj); // Printing values for(var i = 0; i < result.length; i++) { for(var z = 0; z < result[i].length; z++) { document.write(result[i][z] + " "); } document.write("</br>"); } </script> Output: 1 500 2 15 4 480 5 4 10 87 surinderdawra388 javascript-array javascript-object Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n10 May, 2022" }, { "code": null, "e": 142, "s": 53, "text": "The task is to convert an Object {} to an Array [] of key-value pairs using JavaScript. " }, { "code": null, "e": 792, "s": 142, "text": "Introduction: Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types, while the array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. We can convert an Object {} to an Array [] of key-value pairs using methods discussed below: " }, { "code": null, "e": 872, "s": 792, "text": "Method 1: In this method, we will use Object.keys() and map() to achieve this. " }, { "code": null, "e": 1076, "s": 872, "text": "Approach: By using Object.keys(), we are extracting keys from the Object then this key passed to map() function which maps the key and corresponding value as an array, as described in the below example. " }, { "code": null, "e": 1084, "s": 1076, "text": "Syntax:" }, { "code": null, "e": 1101, "s": 1084, "text": "Object.keys(obj)" }, { "code": null, "e": 1182, "s": 1101, "text": "Parameter: obj: It is the object whose enumerable properties are to be returned." }, { "code": null, "e": 1275, "s": 1182, "text": "map(function callback(currentValue[, index[, array]]){\n // Return element for new_array\n}" }, { "code": null, "e": 1347, "s": 1275, "text": "Parameter: callback: Function that produces an element of the new Array" }, { "code": null, "e": 1357, "s": 1347, "text": "Example: " }, { "code": null, "e": 1368, "s": 1357, "text": "javascript" }, { "code": "<script> // An Object var obj = { \"1\": 5, \"2\": 7, \"3\": 0, \"4\": 0, \"5\": 0 }; // Using Object.keys() and map() function // to convert an Object {} to an // Array [] of key-value pairs var result = Object.keys(obj).map(function (key) { // Using Number() to convert key to number type // Using obj[key] to retrieve key value return [Number(key), obj[key]]; }); // Printing values for(var i = 0; i < result.length; i++) { for(var z = 0; z < result[i].length; z++) { document.write(result[i][z] + \" \"); } document.write(\"</br>\"); } </script>", "e": 2007, "s": 1368, "text": null }, { "code": null, "e": 2015, "s": 2007, "text": "Output:" }, { "code": null, "e": 2035, "s": 2015, "text": "1 5\n2 7\n3 0\n4 0\n5 0" }, { "code": null, "e": 2108, "s": 2035, "text": "Method 2: In this method, we will use Object.entries() to achieve this. " }, { "code": null, "e": 2452, "s": 2108, "text": "Approach: We will use Object.entries() which is available in JavaScript. Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter. The ordering of the properties is the same as that given by looping over the property values of the object manually. " }, { "code": null, "e": 2460, "s": 2452, "text": "Syntax:" }, { "code": null, "e": 2480, "s": 2460, "text": "Object.entries(obj)" }, { "code": null, "e": 2583, "s": 2480, "text": "Parameter: obj: It is the object whose enumerable own property [key, value] pairs are to be returned. " }, { "code": null, "e": 2593, "s": 2583, "text": "Example: " }, { "code": null, "e": 2604, "s": 2593, "text": "javascript" }, { "code": "<script> // An Object var obj = { \"1\": 500, \"2\": 15, \"5\": 4, \"4\": 480, \"10\": 87 }; // Using Object.entries() function // to convert an Object {} to an // Array [] of key-value pairs var result = Object.entries(obj); // Printing values for(var i = 0; i < result.length; i++) { for(var z = 0; z < result[i].length; z++) { document.write(result[i][z] + \" \"); } document.write(\"</br>\"); } </script> ", "e": 3087, "s": 2604, "text": null }, { "code": null, "e": 3095, "s": 3087, "text": "Output:" }, { "code": null, "e": 3122, "s": 3095, "text": "1 500\n2 15\n4 480\n5 4\n10 87" }, { "code": null, "e": 3139, "s": 3122, "text": "surinderdawra388" }, { "code": null, "e": 3156, "s": 3139, "text": "javascript-array" }, { "code": null, "e": 3174, "s": 3156, "text": "javascript-object" }, { "code": null, "e": 3181, "s": 3174, "text": "Picked" }, { "code": null, "e": 3192, "s": 3181, "text": "JavaScript" }, { "code": null, "e": 3209, "s": 3192, "text": "Web Technologies" }, { "code": null, "e": 3236, "s": 3209, "text": "Web technologies Questions" }, { "code": null, "e": 3334, "s": 3236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3395, "s": 3334, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3467, "s": 3395, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3507, "s": 3467, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3560, "s": 3507, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3601, "s": 3560, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3634, "s": 3601, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3696, "s": 3634, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3757, "s": 3696, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3807, "s": 3757, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to remove unused space for arraylist Listview in Android?
This example demonstrates How to remove unused space for arraylist Listview in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/refresh" android:text = "Refresh" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> <ListView android:id = "@+id/listView" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name and record number as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class MainActivity extends AppCompatActivity { EditText name; ArrayAdapter arrayAdapter; ArrayList<String> array_list; Set set = new HashSet(); private ListView listView; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); array_list = new ArrayList<String>(); array_list.ensureCapacity(20); name = findViewById(R.id.name); listView = findViewById(R.id.listView); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { set.add(name.getText().toString()); array_list.clear(); array_list.addAll(set); Collections.sort(array_list, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); array_list.trimToSize(); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { name.setError("Enter NAME"); } } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result, we are inserting value as abc and check listview it is storing value in middle of sairam and a. Click here to download the project code
[ { "code": null, "e": 1275, "s": 1187, "text": "This example demonstrates How to remove unused space for arraylist Listview in Android." }, { "code": null, "e": 1404, "s": 1275, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1469, "s": 1404, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2619, "s": 1469, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 2815, "s": 2619, "text": "In the above code, we have taken name and record number as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview." }, { "code": null, "e": 2872, "s": 2815, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5049, "s": 2872, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.Set;\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n ArrayAdapter arrayAdapter;\n ArrayList<String> array_list;\n Set set = new HashSet();\n private ListView listView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n array_list = new ArrayList<String>();\n array_list.ensureCapacity(20);\n name = findViewById(R.id.name);\n listView = findViewById(R.id.listView);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n set.add(name.getText().toString());\n array_list.clear();\n array_list.addAll(set);\n Collections.sort(array_list, new Comparator<String>() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }\n });\n array_list.trimToSize();\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 5396, "s": 5049, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5513, "s": 5396, "text": "In the above result, we are inserting value as abc and check listview it is storing value in middle of sairam and a." }, { "code": null, "e": 5553, "s": 5513, "text": "Click here to download the project code" } ]
Calculate n + nn + nnn + ... + n(m times) in Python - GeeksforGeeks
05 Nov, 2019 The program is to find a mathematical series, where we need to accept the value of n and m. n is the base number and m is the number of times till which the series run. Examples: Input : 2 + 22 + 222 + 2222 + 22222 Output : 24690 Input : 12 + 1212 + 121212 Output : 122436 We first convert the numbers into string format and concatenate them regularly. Later, we convert them back to integer and add them upto mth term. as shown in the following program. # Python program to sum the given series # Returns sum of n + nn + nnn + .... (m times)def Series(n, m): # Converting the number to string str_n = str(n) # Initializing result as number and string sums = n sum_str = str(n) # Adding remaining terms for i in range(1, m): # Concatenating the string making n, nn, nnn... sum_str = sum_str + str_n # Before adding converting back to integer sums = sums + int(sum_str) return sums # Driver Coden = 2m = 5total = Series(n, m)print(total) Output: 24690 nidhi_biet large-numbers series Python series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24097, "s": 24069, "text": "\n05 Nov, 2019" }, { "code": null, "e": 24266, "s": 24097, "text": "The program is to find a mathematical series, where we need to accept the value of n and m. n is the base number and m is the number of times till which the series run." }, { "code": null, "e": 24276, "s": 24266, "text": "Examples:" }, { "code": null, "e": 24373, "s": 24276, "text": "Input : 2 + 22 + 222 + 2222 + 22222 \nOutput : 24690\n\nInput : 12 + 1212 + 121212\nOutput : 122436\n" }, { "code": null, "e": 24555, "s": 24373, "text": "We first convert the numbers into string format and concatenate them regularly. Later, we convert them back to integer and add them upto mth term. as shown in the following program." }, { "code": "# Python program to sum the given series # Returns sum of n + nn + nnn + .... (m times)def Series(n, m): # Converting the number to string str_n = str(n) # Initializing result as number and string sums = n sum_str = str(n) # Adding remaining terms for i in range(1, m): # Concatenating the string making n, nn, nnn... sum_str = sum_str + str_n # Before adding converting back to integer sums = sums + int(sum_str) return sums # Driver Coden = 2m = 5total = Series(n, m)print(total)", "e": 25118, "s": 24555, "text": null }, { "code": null, "e": 25126, "s": 25118, "text": "Output:" }, { "code": null, "e": 25133, "s": 25126, "text": "24690\n" }, { "code": null, "e": 25144, "s": 25133, "text": "nidhi_biet" }, { "code": null, "e": 25158, "s": 25144, "text": "large-numbers" }, { "code": null, "e": 25165, "s": 25158, "text": "series" }, { "code": null, "e": 25172, "s": 25165, "text": "Python" }, { "code": null, "e": 25179, "s": 25172, "text": "series" }, { "code": null, "e": 25277, "s": 25179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25286, "s": 25277, "text": "Comments" }, { "code": null, "e": 25299, "s": 25286, "text": "Old Comments" }, { "code": null, "e": 25317, "s": 25299, "text": "Python Dictionary" }, { "code": null, "e": 25339, "s": 25317, "text": "Enumerate() in Python" }, { "code": null, "e": 25371, "s": 25339, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25413, "s": 25371, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25439, "s": 25413, "text": "Python String | replace()" }, { "code": null, "e": 25464, "s": 25439, "text": "sum() function in Python" }, { "code": null, "e": 25501, "s": 25464, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25557, "s": 25501, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25586, "s": 25557, "text": "*args and **kwargs in Python" } ]
What are different types of parameters to a method in C#?
Methods in C# are generally the block of codes or statements in a program which gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides better readability of the code. There might be certain situations the user wants to execute a method but sometimes that method requires some valuable inputs in order to execute and complete its tasks. These input values are known as Parameters. Parameters can be passed to a method in the following ways − Value Parameters Value Parameters Reference Parameters Reference Parameters Output Parameters Output Parameters Value Parameters copies the actual value of an argument into the formal parameter of the function. When a simple variable is passed as the parameter to any method, it is passed as a value. This means that the value contained by the variable that is passed as the parameter is copied to the variables of the method, and if inside the method these values are changed or modified, the change is not reflected in the actual passed variable. Most of the primitive data types such as integer, double, Boolean etc. are passed by value. Live Demo using System; namespace MyApplication{ public class Program{ public static void Main(){ int x = 5, y = 5; Console.WriteLine($"Value before calling the method. x = {x}, y = {y}"); ValueParamter(x, y); Console.WriteLine($"Value after calling the method. x = {x}, y = {y}"); } public static void ValueParamter(int x, int y){ x = 10; y = 10; int z = x + y; Console.WriteLine($"Sum of x and y = {z}"); } } } The output of the above code is as follows &mius; Value before calling the method. x = 5, y = 5 Sum of x and y = 20 Value after calling the method. x = 5, y = 5 Reference Parameters copies the reference to the memory location of an argument into the formal parameter. Normally, all the objects are passed by reference as parameter to the method. The method operates on the references of the variables passed in the parameters rather than operating on their values. This results in the modification of variables in the calling function when they are modified in the called function. This means that changes made to the parameter affect the argument. Live Demo using System; namespace MyApplication{ public class Program{ public static void Main(){ int x = 5, y = 5; Console.WriteLine($"Value before calling the method. x = {x}, y = {y}"); RefParamter(ref x, ref y); Console.WriteLine($"Value after calling the method. x = {x}, y = {y}"); } public static void RefParamter(ref int x, ref int y){ x = 10; y = 10; int z = x + y; Console.WriteLine($"Sum of x and y = {z}"); } } } The output of the above code is as follows − Value before calling the method. x = 5, y = 5 Sum of x and y = 20 Value after calling the method. x = 10, y = 10 Output Parameters helps in returning more than one value. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. The variable supplied for the output parameter need not be assigned a value. Output parameters are particularly useful when you need to return values from a method through the parameters without assigning an initial value to the parameter. Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it. Live Demo using System; namespace MyApplication{ public class Program{ public static void Main(){ int result; OutParamter(out result); Console.WriteLine($"Result: {result}"); } public static void OutParamter(out int result){ int x = 10, y = 10; result = x + y; } } } The output of the above code is as follows: Result: 20
[ { "code": null, "e": 1331, "s": 1062, "text": "Methods in C# are generally the block of codes or statements in a program which gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides better readability of the code." }, { "code": null, "e": 1544, "s": 1331, "text": "There might be certain situations the user wants to execute a method but sometimes that method requires some valuable inputs in order to execute and complete its tasks. These input values are known as Parameters." }, { "code": null, "e": 1605, "s": 1544, "text": "Parameters can be passed to a method in the following ways −" }, { "code": null, "e": 1622, "s": 1605, "text": "Value Parameters" }, { "code": null, "e": 1639, "s": 1622, "text": "Value Parameters" }, { "code": null, "e": 1660, "s": 1639, "text": "Reference Parameters" }, { "code": null, "e": 1681, "s": 1660, "text": "Reference Parameters" }, { "code": null, "e": 1699, "s": 1681, "text": "Output Parameters" }, { "code": null, "e": 1717, "s": 1699, "text": "Output Parameters" }, { "code": null, "e": 2246, "s": 1717, "text": "Value Parameters copies the actual value of an argument into the formal parameter of the function. When a simple variable is passed as the parameter to any method, it is passed as a value. This means that the value contained by the variable that is passed as the parameter is copied to the variables of the method, and if inside the method these values are changed or modified, the change is not reflected in the actual passed variable. Most of the primitive data types such as integer, double, Boolean etc. are passed by value." }, { "code": null, "e": 2257, "s": 2246, "text": " Live Demo" }, { "code": null, "e": 2762, "s": 2257, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n int x = 5, y = 5;\n Console.WriteLine($\"Value before calling the method. x = {x}, y = {y}\");\n ValueParamter(x, y);\n Console.WriteLine($\"Value after calling the method. x = {x}, y = {y}\");\n }\n public static void ValueParamter(int x, int y){\n x = 10;\n y = 10;\n int z = x + y;\n Console.WriteLine($\"Sum of x and y = {z}\");\n }\n }\n}" }, { "code": null, "e": 2812, "s": 2762, "text": "The output of the above code is as follows &mius;" }, { "code": null, "e": 2923, "s": 2812, "text": "Value before calling the method. x = 5, y = 5\nSum of x and y = 20\nValue after calling the method. x = 5, y = 5" }, { "code": null, "e": 3411, "s": 2923, "text": "Reference Parameters copies the reference to the memory location of an argument into the formal parameter. Normally, all the objects are passed by reference as parameter to the method. The method operates on the references of the variables passed in the parameters rather than operating on their values. This results in the modification of variables in the calling function when they are modified in the called function. This means that changes made to the parameter affect the argument." }, { "code": null, "e": 3422, "s": 3411, "text": " Live Demo" }, { "code": null, "e": 3939, "s": 3422, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n int x = 5, y = 5;\n Console.WriteLine($\"Value before calling the method. x = {x}, y = {y}\");\n RefParamter(ref x, ref y);\n Console.WriteLine($\"Value after calling the method. x = {x}, y = {y}\");\n }\n public static void RefParamter(ref int x, ref int y){\n x = 10;\n y = 10;\n int z = x + y;\n Console.WriteLine($\"Sum of x and y = {z}\");\n }\n }\n}" }, { "code": null, "e": 3984, "s": 3939, "text": "The output of the above code is as follows −" }, { "code": null, "e": 4097, "s": 3984, "text": "Value before calling the method. x = 5, y = 5\nSum of x and y = 20\nValue after calling the method. x = 10, y = 10" }, { "code": null, "e": 4674, "s": 4097, "text": "Output Parameters helps in returning more than one value. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. The variable supplied for the output parameter need not be assigned a value. Output parameters are particularly useful when you need to return values from a method through the parameters without assigning an initial value to the parameter. Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it." }, { "code": null, "e": 4685, "s": 4674, "text": " Live Demo" }, { "code": null, "e": 5017, "s": 4685, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n int result;\n OutParamter(out result);\n Console.WriteLine($\"Result: {result}\");\n }\n public static void OutParamter(out int result){\n int x = 10, y = 10;\n result = x + y;\n }\n }\n}" }, { "code": null, "e": 5072, "s": 5017, "text": "The output of the above code is as follows:\nResult: 20" } ]
Linear Discriminant Analysis — An Introduction | by Pritha Saha | Towards Data Science
LDA is a dimensionality reduction algorithm, similar to PCA. However while PCA is an unsupervised algorithm that focusses on maximising variance in a dataset, LDA is a supervised algorithm that maximises separability between classes. In a classification problem set up the objective is to ensure maximum separability or discrimination of classes. Suppose we have a dataset with two columns — one explanatory variable and a binary target variable (with values 1 and 0). The distribution of the binary variable is as per below: The green dots represent 1 and the red ones represent 0. Since there is only one explanatory variable, it is denoted by one axis (X). However, if we try to place a linear divider to demarcate the data points, we will not be able to do it successfully since the points are scattered across the axis. Hence it seems that one explanatory variable is not enough to predict the binary outcome. So we will bring in another feature X2 and check the distribution of points in the 2 dimensional space. It seems that in 2 dimensional space the demarcation of outputs is better than before. However, increasing dimensions might not be a good idea in a dataset which already has several features. In those situations, LDA comes to our rescue by minimising the dimensions. In the below figure the target classes are projected on a new axis: The classes are now easily demarcated. LDA transforms the original features to a new axis, called Linear Discriminant (LD), thereby reducing dimensions and ensuring maximum separability of the classes. In order to put this separability in numerical terms, we would need a metric that measures the separability. Calculating the difference between means of the two classes could be one such measure. The higher difference would indicate an increased distance between the points. However, this method does not take the spread of the data into cognisance. Hence even a higher mean cannot ensure that some of the classes don’t overlap with each other. The second measure is taking both the mean and variance within classes into consideration. To ensure maximum separability we would then maximise the difference between means while minimising the variance. The score is calculated as (M1-M2)2/(S12+S22). If there are three explanatory variables- X1, X2, X3, LDA will transform them into three axes — LD1, LD2 and LD3. These three axes would rank first, second and third on the basis of the calculated score. Hence LDA helps us to both reduce dimensions and classify target values. We will go through an example to see how LDA achieves both the objectives. The below data shows a fictional dataset by IBM, which records employee data and attrition. The objective is to predict attrition of employees, based on different factors like age, years worked, nature of travel, education etc. sns.countplot(train['Attrition'])plt.show() There are around 1470 records, out of which 237 employees have left the organisation and 1233 haven’t. Yes has been coded as 1 and No is coded as 0. Attrition of employees if not predicted correctly can lead to losing valuable people, resulting in reduced efficiency of the organisation, reduced morale among team members etc. Hence it is necessary to correctly predict which employee is likely to leave. In other words, if we predict an employee will stay, but actually the employee leaves the company, the number of False Negatives increase. Our objective would be to minimise False Negatives and hence increase Recall (TP/(TP+FN)). We will try classifying the classes using KNN: knn=KNeighborsClassifier(n_neighbors=10,weights='distance',algorithm='auto', p=3)start_time = time.time()knn.fit(X_train_sc,y_train)end_time = time.time()time_knn = end_time-start_timeprint(time_knn)pred = knn.predict(X_test_sc)print(confusion_matrix(y_test,pred))print(classification_report(y_test,pred)) Time taken to fit KNN : 0.0058078765869140625 Recall is very poor for the employees who left at 0.05. We will now use LDA as a classification algorithm and check the results. lda_0 = LDA()lda_0.fit(X_train_sc, y_train)y_test_pred_0 = lda_0.predict(X_test_sc)print(confusion_matrix(y_test, y_test_pred_0))print(classification_report(y_test, y_test_pred_0)) Recall has increased drastically to 0.36 Finally, we will transform the training set with LDA and then use KNN. #Transformation by LDAlda_1 = LDA(n_components = 1, solver='eigen', shrinkage='auto')X_train_lda = lda_1.fit_transform(X_train_lda, y_train_lda)X_test_lda = lda_1.transform(X_test_lda) This is followed by Standard Scaling. sc3 = StandardScaler()X_train_lda_sc = sc3.fit_transform(X_train_lda)X_test_lda_sc = sc3.transform(X_test_lda) Now we apply KNN on the transformed data. knn=KNeighborsClassifier(n_neighbors=8,weights='distance',algorithm='auto', p=3)start_time = time.time()knn.fit(X_train_lda_sc,y_train_lda)end_time = time.time()time_lda = end_time-start_timeprint(time_lda)print(confusion_matrix(y_test_lda,pred))print(classification_report(y_test_lda,pred)) Time taken to run KNN on transformed data: 0.0024199485778808594 Recall is now increased by 6%. Also, the time taken by KNN to fit the LDA transformed data is 50% of the time taken by KNN alone. The entire code is available here. Hope I have been able to demonstrate the use of LDA, both for classification and transforming data into different axes! Stay tuned for more! As always, any feedback is appreciated.
[ { "code": null, "e": 406, "s": 172, "text": "LDA is a dimensionality reduction algorithm, similar to PCA. However while PCA is an unsupervised algorithm that focusses on maximising variance in a dataset, LDA is a supervised algorithm that maximises separability between classes." }, { "code": null, "e": 519, "s": 406, "text": "In a classification problem set up the objective is to ensure maximum separability or discrimination of classes." }, { "code": null, "e": 698, "s": 519, "text": "Suppose we have a dataset with two columns — one explanatory variable and a binary target variable (with values 1 and 0). The distribution of the binary variable is as per below:" }, { "code": null, "e": 997, "s": 698, "text": "The green dots represent 1 and the red ones represent 0. Since there is only one explanatory variable, it is denoted by one axis (X). However, if we try to place a linear divider to demarcate the data points, we will not be able to do it successfully since the points are scattered across the axis." }, { "code": null, "e": 1191, "s": 997, "text": "Hence it seems that one explanatory variable is not enough to predict the binary outcome. So we will bring in another feature X2 and check the distribution of points in the 2 dimensional space." }, { "code": null, "e": 1526, "s": 1191, "text": "It seems that in 2 dimensional space the demarcation of outputs is better than before. However, increasing dimensions might not be a good idea in a dataset which already has several features. In those situations, LDA comes to our rescue by minimising the dimensions. In the below figure the target classes are projected on a new axis:" }, { "code": null, "e": 1728, "s": 1526, "text": "The classes are now easily demarcated. LDA transforms the original features to a new axis, called Linear Discriminant (LD), thereby reducing dimensions and ensuring maximum separability of the classes." }, { "code": null, "e": 2173, "s": 1728, "text": "In order to put this separability in numerical terms, we would need a metric that measures the separability. Calculating the difference between means of the two classes could be one such measure. The higher difference would indicate an increased distance between the points. However, this method does not take the spread of the data into cognisance. Hence even a higher mean cannot ensure that some of the classes don’t overlap with each other." }, { "code": null, "e": 2378, "s": 2173, "text": "The second measure is taking both the mean and variance within classes into consideration. To ensure maximum separability we would then maximise the difference between means while minimising the variance." }, { "code": null, "e": 2425, "s": 2378, "text": "The score is calculated as (M1-M2)2/(S12+S22)." }, { "code": null, "e": 2629, "s": 2425, "text": "If there are three explanatory variables- X1, X2, X3, LDA will transform them into three axes — LD1, LD2 and LD3. These three axes would rank first, second and third on the basis of the calculated score." }, { "code": null, "e": 2702, "s": 2629, "text": "Hence LDA helps us to both reduce dimensions and classify target values." }, { "code": null, "e": 3005, "s": 2702, "text": "We will go through an example to see how LDA achieves both the objectives. The below data shows a fictional dataset by IBM, which records employee data and attrition. The objective is to predict attrition of employees, based on different factors like age, years worked, nature of travel, education etc." }, { "code": null, "e": 3049, "s": 3005, "text": "sns.countplot(train['Attrition'])plt.show()" }, { "code": null, "e": 3198, "s": 3049, "text": "There are around 1470 records, out of which 237 employees have left the organisation and 1233 haven’t. Yes has been coded as 1 and No is coded as 0." }, { "code": null, "e": 3684, "s": 3198, "text": "Attrition of employees if not predicted correctly can lead to losing valuable people, resulting in reduced efficiency of the organisation, reduced morale among team members etc. Hence it is necessary to correctly predict which employee is likely to leave. In other words, if we predict an employee will stay, but actually the employee leaves the company, the number of False Negatives increase. Our objective would be to minimise False Negatives and hence increase Recall (TP/(TP+FN))." }, { "code": null, "e": 3731, "s": 3684, "text": "We will try classifying the classes using KNN:" }, { "code": null, "e": 4037, "s": 3731, "text": "knn=KNeighborsClassifier(n_neighbors=10,weights='distance',algorithm='auto', p=3)start_time = time.time()knn.fit(X_train_sc,y_train)end_time = time.time()time_knn = end_time-start_timeprint(time_knn)pred = knn.predict(X_test_sc)print(confusion_matrix(y_test,pred))print(classification_report(y_test,pred))" }, { "code": null, "e": 4083, "s": 4037, "text": "Time taken to fit KNN : 0.0058078765869140625" }, { "code": null, "e": 4139, "s": 4083, "text": "Recall is very poor for the employees who left at 0.05." }, { "code": null, "e": 4212, "s": 4139, "text": "We will now use LDA as a classification algorithm and check the results." }, { "code": null, "e": 4393, "s": 4212, "text": "lda_0 = LDA()lda_0.fit(X_train_sc, y_train)y_test_pred_0 = lda_0.predict(X_test_sc)print(confusion_matrix(y_test, y_test_pred_0))print(classification_report(y_test, y_test_pred_0))" }, { "code": null, "e": 4434, "s": 4393, "text": "Recall has increased drastically to 0.36" }, { "code": null, "e": 4505, "s": 4434, "text": "Finally, we will transform the training set with LDA and then use KNN." }, { "code": null, "e": 4690, "s": 4505, "text": "#Transformation by LDAlda_1 = LDA(n_components = 1, solver='eigen', shrinkage='auto')X_train_lda = lda_1.fit_transform(X_train_lda, y_train_lda)X_test_lda = lda_1.transform(X_test_lda)" }, { "code": null, "e": 4728, "s": 4690, "text": "This is followed by Standard Scaling." }, { "code": null, "e": 4839, "s": 4728, "text": "sc3 = StandardScaler()X_train_lda_sc = sc3.fit_transform(X_train_lda)X_test_lda_sc = sc3.transform(X_test_lda)" }, { "code": null, "e": 4881, "s": 4839, "text": "Now we apply KNN on the transformed data." }, { "code": null, "e": 5173, "s": 4881, "text": "knn=KNeighborsClassifier(n_neighbors=8,weights='distance',algorithm='auto', p=3)start_time = time.time()knn.fit(X_train_lda_sc,y_train_lda)end_time = time.time()time_lda = end_time-start_timeprint(time_lda)print(confusion_matrix(y_test_lda,pred))print(classification_report(y_test_lda,pred))" }, { "code": null, "e": 5238, "s": 5173, "text": "Time taken to run KNN on transformed data: 0.0024199485778808594" }, { "code": null, "e": 5269, "s": 5238, "text": "Recall is now increased by 6%." }, { "code": null, "e": 5368, "s": 5269, "text": "Also, the time taken by KNN to fit the LDA transformed data is 50% of the time taken by KNN alone." }, { "code": null, "e": 5403, "s": 5368, "text": "The entire code is available here." }, { "code": null, "e": 5523, "s": 5403, "text": "Hope I have been able to demonstrate the use of LDA, both for classification and transforming data into different axes!" } ]
Predicting Customer Churn with Neural Networks in Keras | by Kenny Hunt | Towards Data Science
This is a big one for organisations everywhere and one of the main areas in which we see high adoption rate of machine learning, this is probably down to the fact that we are predicting customer behaviour. “Churn” is the term used to describe when a customer stops using a certain organisation’s services. This is a really powerful KPI for subscription services, who make most of their income from repeating (usually monthly) payments. Netflix is a great example of a subscription company, they’re also an organisation that is close to the bleeding edge of tech. Netflix uses Deep Learning techniques to predict if a customer is going to leave before they actually do, this means they can take preventative action to ensure they stay. Without going too far down the rabbit hole, here goes... Netflix collect a LOT of data on individuals, what you watch, when you watch it, everything you like and dislike etc etc. They can use this data in combination with Deep Learning classification techniques to work out when they think a customer will leave. The simple explanation could be something like “if a customer doesn’t watch anything for N days then its realistic to expect they will churn soon”. Analysing all that harvested data using a Neural Network will enable the organisation to build profiles of their customers based on the data they have available. Once a bunch of users are categorised, Netflix can decide what action to take if a customer is highlighted a a suspected churn. e.g. they can understand which customers they want to keep — and offer these guys discounts and promotions — then also identify which customers are ‘lost causes’ and can be let go. The IBM Telco Dataset has been doing the rounds on the internet for over a year now, so I guess now is as good time as any to have a crack at using it to predict customer churn. I will need to borrow some code from elsewhere. I lifted the data prep code directly from this blog post. This allowed me to spend a bit more time tweaking the model and (attempting) to gain a bit more accuracy. This is pretty simple, its pretty much a straight copy/paste job into your own notebook. On scouring the internet I found a whole load of people distributing code that imported incorrect libraries. The main thing to look out for here is the second block where I import the Keras modules. Plenty of posts (I assume it all originated from the same post) have become confused between importing Keras libraries and TensorFlow libraries. A good rule of thumb here is to ensure that you are EITHER: Only importing Keras stuff: They will start with ‘Keras.’ e.g. from keras.models import... Only importing TensorFlow Keras libraries, these start with TensorFlow.Keras. e.g. from TensorFlow.Keras.models import... import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split import keras from keras.models import Sequential from keras.layers import InputLayer from keras.layers import Dense from keras.layers import Dropout from keras.constraints import maxnorm Read the test data in a pandas DataFrame (grab the CSV by clicking the link to the IBM dataset at the top). data = pd.read_csv('churn.csv') Once we have the data in a Pandas DF we can use the stolen preprocessing code to get the data into a format that is optimised for the neural network. Essentially we are doing the following things: Converting categorical variables into numerical variables (e.g. Yes/No to 0/1). Getting the column formats right so they are all in numeric format Filling in any nulls. data.SeniorCitizen.replace([0, 1], ["No", "Yes"], inplace= True) data.TotalCharges.replace([" "], ["0"], inplace= True) data.TotalCharges = data.TotalCharges.astype(float) data.drop("customerID", axis= 1, inplace= True) data.Churn.replace(["Yes", "No"], [1, 0], inplace= True) Once we have a clean dataset we can use pandas get_dummies functionality to replace all our categorical columns with ‘dummy’ numeric ‘indicatior’ columns. Similar to what the code above is doing, but this will strip out the whole data set. data = pd.get_dummies(data) Like any model, we should be splitting our data into a training and validation (or test set). First we split our dataset down into X and y. X contains all the variables that we are using the make the predictions. y contains just the outcomes (whether or not the customer churned). X = data.drop("Churn", axis= 1) y = data.Churn Next we use a standard train_test_split to split the data into training and testing (validation) sets. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state= 1234) Now we have our datasets at the ready, lets build a model. One great thing about Keras is that we can very simply build a neural network based on layers. It looks a bit like this diagram. First we tell Keras what type of model we want to employ. Mostly you’ll be using sequential models. model = Sequential() Next lets first build the input layer. Its the red layer on the diagram. There are a few things to notice here. We are using dense layers throughout this NN, I wont go into the differences between different layers and neural networks but most of the time you will be using either Dense or LSTM layers. More info here. The first number — 16 is the number of nodes (or circles in the above diagram. We start with 16, we can change this later on to see how it impacts our accuracy. Its important that you set the input_dim argument it must match the amount of columns in our X_train dataset. We can simply count the columns in the dataset and type it as I have done below — but realistically you will want to use X_train.shape[1] to automatically compute the value. Activation Functions — you should really read up on these at some point — ill probably do another post specifically on these, but for the time being just know that our layers all use ‘Relu’ except for the output layer (which we will get to later. As a general rule of thumb — “if you are unsure, use relu” model.add(Dense(16, input_dim=46, activation='relu', kernel_constraint=maxnorm(3))) We add in a Dropout Layer. The dropout layer ensures that we remove a set percentage (in this case 0.2 or 20%) of the data each time we iterate through the neural network. This is optional but worth including in your code to stop it from overfitting. You can change the different drop out rates to experiment to try to get more accuracy. model.add(Dropout(rate=0.2)) Now we add in what’s called a hidden layer, we can have as many of these as we like, but its worth thinking about the additional computational power required to make NN’s with a large number of hidden layers work. Notice the ‘kernal_constraint’ argument? This deals with the scaling of the weights required to make the “dropout” layers function effectively. Again more info in the documentation, but I guess all you need to know is that by nature a NN will automatically trial and error all the different weightings of the variables in the dataset (this is why we use a neural net in the first place), the kernel_constraint argument adds control around this process. model.add(Dense(8, activation='relu', kernel_constraint=maxnorm(3))) Add in another Dropout layer to avoid overfitting. model.add(Dropout(rate=0.2)) Lastly we add an output layer: this defines the final output from our neural network. There are a few things you need to keep in mind here: Our first argument is the number 1. This is because the out of our NN is one column containing an indicator which will specify whether our customer will churn or not. The activation function is different. For a single (yes/no) classification model we use ‘sigmoid’ there are many different functions available, for example if we are building a network that classifies multiple outcomes (for example grouping customers into specific groups) we may use a ‘softmax’ activation function. model.add(Dense(1, activation='sigmoid')) So now i’ve described each individual layer, ill show the whole lot squeezed together. model = Sequential() model.add(Dense(16, input_dim=46, activation='relu', kernel_constraint=maxnorm(3)))model.add(Dropout(rate=0.2)) model.add(Dense(8, activation='relu', kernel_constraint=maxnorm(3))) model.add(Dropout(rate=0.2)) model.add(Dense(1, activation='sigmoid')) Next we compile our model (stick it all together and tell it how it should work). We use the compile method to achieve this. It takes three arguments: An optimizer. This could be the string identifier of an existing optimizer (we use ‘Adam’ ), its possible to play around with these and see which is best, you can also split it out and manually adjust the learning rate to benefit from greater accuracy, but we will use the defaults. See: optimizers. A loss function. This is the objective that the model will try to minimize. As this is a single classification problem, we will use ‘binary_crossentropy’. See: losses. A list of metrics. For any classification problem we to set this to ‘accuracy’. model.compile(loss = "binary_crossentropy", optimizer = 'adam', metrics=['accuracy']) Quick one liner to fit the model, notice we fit BOTH the test and validation data sets into our model here, this way the Keras will tell us how we performed on both data sets at once. There are a couple of arguments we need to look out for here. Epochs = this is the number of times we travel up and down the neural network — more epochs can mean more accuracy, but also more processing time, also too many epochs can lead to overfitting. You can adjust this anytime, so try some different values to see what happens to your results. batch_size = this is how many batches of records are put through the neural network at once. A smaller batch size is less accurate but quicker. Again, you can experiment by changing this number directly in the code. history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=40, batch_size=10) Once we run the above code, we will get an indication of how well the model performs — you will see it running through the epochs and providing accuracy scores for training (acc) and test (val_acc) sets. Once its done its thing, all that’s left to do is visualise the results. plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() The last thing we need to do is save the model, this is so that we can deploy it to production later — AWS SageMaker / Azure / Google all have different ways to do this, but generally youll need both a JSON and a WEIGHTS file. # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk") So there we have it. One neural network that produced around 79% accuracy for customer churn. Of course we can spend more time playing around with learning rates, activation functions, number of nodes, number of epochs etc to try and make it more accurate, but hopefully this is a solid baseline to start your investigation. Next ill look into how we can deploy this code to production — it gets tricky. Originally published at http://drunkendatascience.com on May 27, 2019.
[ { "code": null, "e": 378, "s": 172, "text": "This is a big one for organisations everywhere and one of the main areas in which we see high adoption rate of machine learning, this is probably down to the fact that we are predicting customer behaviour." }, { "code": null, "e": 608, "s": 378, "text": "“Churn” is the term used to describe when a customer stops using a certain organisation’s services. This is a really powerful KPI for subscription services, who make most of their income from repeating (usually monthly) payments." }, { "code": null, "e": 907, "s": 608, "text": "Netflix is a great example of a subscription company, they’re also an organisation that is close to the bleeding edge of tech. Netflix uses Deep Learning techniques to predict if a customer is going to leave before they actually do, this means they can take preventative action to ensure they stay." }, { "code": null, "e": 964, "s": 907, "text": "Without going too far down the rabbit hole, here goes..." }, { "code": null, "e": 1368, "s": 964, "text": "Netflix collect a LOT of data on individuals, what you watch, when you watch it, everything you like and dislike etc etc. They can use this data in combination with Deep Learning classification techniques to work out when they think a customer will leave. The simple explanation could be something like “if a customer doesn’t watch anything for N days then its realistic to expect they will churn soon”." }, { "code": null, "e": 1839, "s": 1368, "text": "Analysing all that harvested data using a Neural Network will enable the organisation to build profiles of their customers based on the data they have available. Once a bunch of users are categorised, Netflix can decide what action to take if a customer is highlighted a a suspected churn. e.g. they can understand which customers they want to keep — and offer these guys discounts and promotions — then also identify which customers are ‘lost causes’ and can be let go." }, { "code": null, "e": 2017, "s": 1839, "text": "The IBM Telco Dataset has been doing the rounds on the internet for over a year now, so I guess now is as good time as any to have a crack at using it to predict customer churn." }, { "code": null, "e": 2229, "s": 2017, "text": "I will need to borrow some code from elsewhere. I lifted the data prep code directly from this blog post. This allowed me to spend a bit more time tweaking the model and (attempting) to gain a bit more accuracy." }, { "code": null, "e": 2517, "s": 2229, "text": "This is pretty simple, its pretty much a straight copy/paste job into your own notebook. On scouring the internet I found a whole load of people distributing code that imported incorrect libraries. The main thing to look out for here is the second block where I import the Keras modules." }, { "code": null, "e": 2722, "s": 2517, "text": "Plenty of posts (I assume it all originated from the same post) have become confused between importing Keras libraries and TensorFlow libraries. A good rule of thumb here is to ensure that you are EITHER:" }, { "code": null, "e": 2813, "s": 2722, "text": "Only importing Keras stuff: They will start with ‘Keras.’ e.g. from keras.models import..." }, { "code": null, "e": 2935, "s": 2813, "text": "Only importing TensorFlow Keras libraries, these start with TensorFlow.Keras. e.g. from TensorFlow.Keras.models import..." }, { "code": null, "e": 3251, "s": 2935, "text": "import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split import keras from keras.models import Sequential from keras.layers import InputLayer from keras.layers import Dense from keras.layers import Dropout from keras.constraints import maxnorm" }, { "code": null, "e": 3359, "s": 3251, "text": "Read the test data in a pandas DataFrame (grab the CSV by clicking the link to the IBM dataset at the top)." }, { "code": null, "e": 3391, "s": 3359, "text": "data = pd.read_csv('churn.csv')" }, { "code": null, "e": 3588, "s": 3391, "text": "Once we have the data in a Pandas DF we can use the stolen preprocessing code to get the data into a format that is optimised for the neural network. Essentially we are doing the following things:" }, { "code": null, "e": 3668, "s": 3588, "text": "Converting categorical variables into numerical variables (e.g. Yes/No to 0/1)." }, { "code": null, "e": 3735, "s": 3668, "text": "Getting the column formats right so they are all in numeric format" }, { "code": null, "e": 3757, "s": 3735, "text": "Filling in any nulls." }, { "code": null, "e": 4034, "s": 3757, "text": "data.SeniorCitizen.replace([0, 1], [\"No\", \"Yes\"], inplace= True) data.TotalCharges.replace([\" \"], [\"0\"], inplace= True) data.TotalCharges = data.TotalCharges.astype(float) data.drop(\"customerID\", axis= 1, inplace= True) data.Churn.replace([\"Yes\", \"No\"], [1, 0], inplace= True)" }, { "code": null, "e": 4274, "s": 4034, "text": "Once we have a clean dataset we can use pandas get_dummies functionality to replace all our categorical columns with ‘dummy’ numeric ‘indicatior’ columns. Similar to what the code above is doing, but this will strip out the whole data set." }, { "code": null, "e": 4302, "s": 4274, "text": "data = pd.get_dummies(data)" }, { "code": null, "e": 4396, "s": 4302, "text": "Like any model, we should be splitting our data into a training and validation (or test set)." }, { "code": null, "e": 4442, "s": 4396, "text": "First we split our dataset down into X and y." }, { "code": null, "e": 4515, "s": 4442, "text": "X contains all the variables that we are using the make the predictions." }, { "code": null, "e": 4583, "s": 4515, "text": "y contains just the outcomes (whether or not the customer churned)." }, { "code": null, "e": 4630, "s": 4583, "text": "X = data.drop(\"Churn\", axis= 1) y = data.Churn" }, { "code": null, "e": 4733, "s": 4630, "text": "Next we use a standard train_test_split to split the data into training and testing (validation) sets." }, { "code": null, "e": 4827, "s": 4733, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state= 1234)" }, { "code": null, "e": 4886, "s": 4827, "text": "Now we have our datasets at the ready, lets build a model." }, { "code": null, "e": 5015, "s": 4886, "text": "One great thing about Keras is that we can very simply build a neural network based on layers. It looks a bit like this diagram." }, { "code": null, "e": 5115, "s": 5015, "text": "First we tell Keras what type of model we want to employ. Mostly you’ll be using sequential models." }, { "code": null, "e": 5136, "s": 5115, "text": "model = Sequential()" }, { "code": null, "e": 5248, "s": 5136, "text": "Next lets first build the input layer. Its the red layer on the diagram. There are a few things to notice here." }, { "code": null, "e": 5454, "s": 5248, "text": "We are using dense layers throughout this NN, I wont go into the differences between different layers and neural networks but most of the time you will be using either Dense or LSTM layers. More info here." }, { "code": null, "e": 5615, "s": 5454, "text": "The first number — 16 is the number of nodes (or circles in the above diagram. We start with 16, we can change this later on to see how it impacts our accuracy." }, { "code": null, "e": 5899, "s": 5615, "text": "Its important that you set the input_dim argument it must match the amount of columns in our X_train dataset. We can simply count the columns in the dataset and type it as I have done below — but realistically you will want to use X_train.shape[1] to automatically compute the value." }, { "code": null, "e": 6205, "s": 5899, "text": "Activation Functions — you should really read up on these at some point — ill probably do another post specifically on these, but for the time being just know that our layers all use ‘Relu’ except for the output layer (which we will get to later. As a general rule of thumb — “if you are unsure, use relu”" }, { "code": null, "e": 6289, "s": 6205, "text": "model.add(Dense(16, input_dim=46, activation='relu', kernel_constraint=maxnorm(3)))" }, { "code": null, "e": 6627, "s": 6289, "text": "We add in a Dropout Layer. The dropout layer ensures that we remove a set percentage (in this case 0.2 or 20%) of the data each time we iterate through the neural network. This is optional but worth including in your code to stop it from overfitting. You can change the different drop out rates to experiment to try to get more accuracy." }, { "code": null, "e": 6656, "s": 6627, "text": "model.add(Dropout(rate=0.2))" }, { "code": null, "e": 6870, "s": 6656, "text": "Now we add in what’s called a hidden layer, we can have as many of these as we like, but its worth thinking about the additional computational power required to make NN’s with a large number of hidden layers work." }, { "code": null, "e": 7323, "s": 6870, "text": "Notice the ‘kernal_constraint’ argument? This deals with the scaling of the weights required to make the “dropout” layers function effectively. Again more info in the documentation, but I guess all you need to know is that by nature a NN will automatically trial and error all the different weightings of the variables in the dataset (this is why we use a neural net in the first place), the kernel_constraint argument adds control around this process." }, { "code": null, "e": 7392, "s": 7323, "text": "model.add(Dense(8, activation='relu', kernel_constraint=maxnorm(3)))" }, { "code": null, "e": 7443, "s": 7392, "text": "Add in another Dropout layer to avoid overfitting." }, { "code": null, "e": 7472, "s": 7443, "text": "model.add(Dropout(rate=0.2))" }, { "code": null, "e": 7612, "s": 7472, "text": "Lastly we add an output layer: this defines the final output from our neural network. There are a few things you need to keep in mind here:" }, { "code": null, "e": 7779, "s": 7612, "text": "Our first argument is the number 1. This is because the out of our NN is one column containing an indicator which will specify whether our customer will churn or not." }, { "code": null, "e": 8096, "s": 7779, "text": "The activation function is different. For a single (yes/no) classification model we use ‘sigmoid’ there are many different functions available, for example if we are building a network that classifies multiple outcomes (for example grouping customers into specific groups) we may use a ‘softmax’ activation function." }, { "code": null, "e": 8138, "s": 8096, "text": "model.add(Dense(1, activation='sigmoid'))" }, { "code": null, "e": 8225, "s": 8138, "text": "So now i’ve described each individual layer, ill show the whole lot squeezed together." }, { "code": null, "e": 8498, "s": 8225, "text": "model = Sequential() model.add(Dense(16, input_dim=46, activation='relu', kernel_constraint=maxnorm(3)))model.add(Dropout(rate=0.2)) model.add(Dense(8, activation='relu', kernel_constraint=maxnorm(3))) model.add(Dropout(rate=0.2)) model.add(Dense(1, activation='sigmoid'))" }, { "code": null, "e": 8580, "s": 8498, "text": "Next we compile our model (stick it all together and tell it how it should work)." }, { "code": null, "e": 8649, "s": 8580, "text": "We use the compile method to achieve this. It takes three arguments:" }, { "code": null, "e": 8949, "s": 8649, "text": "An optimizer. This could be the string identifier of an existing optimizer (we use ‘Adam’ ), its possible to play around with these and see which is best, you can also split it out and manually adjust the learning rate to benefit from greater accuracy, but we will use the defaults. See: optimizers." }, { "code": null, "e": 9117, "s": 8949, "text": "A loss function. This is the objective that the model will try to minimize. As this is a single classification problem, we will use ‘binary_crossentropy’. See: losses." }, { "code": null, "e": 9197, "s": 9117, "text": "A list of metrics. For any classification problem we to set this to ‘accuracy’." }, { "code": null, "e": 9283, "s": 9197, "text": "model.compile(loss = \"binary_crossentropy\", optimizer = 'adam', metrics=['accuracy'])" }, { "code": null, "e": 9467, "s": 9283, "text": "Quick one liner to fit the model, notice we fit BOTH the test and validation data sets into our model here, this way the Keras will tell us how we performed on both data sets at once." }, { "code": null, "e": 9529, "s": 9467, "text": "There are a couple of arguments we need to look out for here." }, { "code": null, "e": 9817, "s": 9529, "text": "Epochs = this is the number of times we travel up and down the neural network — more epochs can mean more accuracy, but also more processing time, also too many epochs can lead to overfitting. You can adjust this anytime, so try some different values to see what happens to your results." }, { "code": null, "e": 10033, "s": 9817, "text": "batch_size = this is how many batches of records are put through the neural network at once. A smaller batch size is less accurate but quicker. Again, you can experiment by changing this number directly in the code." }, { "code": null, "e": 10131, "s": 10033, "text": "history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=40, batch_size=10)" }, { "code": null, "e": 10335, "s": 10131, "text": "Once we run the above code, we will get an indication of how well the model performs — you will see it running through the epochs and providing accuracy scores for training (acc) and test (val_acc) sets." }, { "code": null, "e": 10408, "s": 10335, "text": "Once its done its thing, all that’s left to do is visualise the results." }, { "code": null, "e": 10608, "s": 10408, "text": "plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()" }, { "code": null, "e": 10835, "s": 10608, "text": "The last thing we need to do is save the model, this is so that we can deploy it to production later — AWS SageMaker / Azure / Google all have different ways to do this, but generally youll need both a JSON and a WEIGHTS file." }, { "code": null, "e": 11049, "s": 10835, "text": "# serialize model to JSON model_json = model.to_json() with open(\"model.json\", \"w\") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights(\"model.h5\") print(\"Saved model to disk\")" }, { "code": null, "e": 11374, "s": 11049, "text": "So there we have it. One neural network that produced around 79% accuracy for customer churn. Of course we can spend more time playing around with learning rates, activation functions, number of nodes, number of epochs etc to try and make it more accurate, but hopefully this is a solid baseline to start your investigation." }, { "code": null, "e": 11453, "s": 11374, "text": "Next ill look into how we can deploy this code to production — it gets tricky." } ]