title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Pair plot and PairGrid in Details | by Rashida Nasrin Sucky | Towards Data Science
When I first learn to make the pairplots, I used them in every project for some time. I still use them a lot. Pair plots are several bivariate distributions in one plot and can be made using just one simple function. Even The most basic one is very useful in a data analytics project where there are several continuous variables. We know that a scatter plot is widely used to present the relationship between two continuous variables. Pair plot puts several scatter plots in one plot and also provides the distribution diagonally. This article is a tutorial on how to make Pairplots of different styles. This article will cover: Pair plot using Pandas and MatplotlibMore Stylish and informative Pair plots using Seaborn libraryUse of the ‘PairGrid’ function to make more dynamic pair plots Pair plot using Pandas and Matplotlib More Stylish and informative Pair plots using Seaborn library Use of the ‘PairGrid’ function to make more dynamic pair plots I used this famous dataset called the ‘nhanes’ dataset. I find it useful because it has a lot of continuous and categorical features. Please feel free to download the dataset from this link to follow along: github.com The column names may look a bit strange if this dataset is new to you. But don’t worry about it. I will explain what they mean when I will use them. Let’s import the dataset first import pandas as pddf = pd.read_csv("nhanes_2015_2016.csv") The dataset is pretty big. So, I cannot show a screenshot here. These are the columns in the dataset: df.columns Output: Index(['SEQN', 'ALQ101', 'ALQ110', 'ALQ130', 'SMQ020', 'RIAGENDR', 'RIDAGEYR', 'RIDRETH1', 'DMDCITZN', 'DMDEDUC2', 'DMDMARTL', 'DMDHHSIZ', 'WTINT2YR', 'SDMVPSU', 'SDMVSTRA', 'INDFMPIR', 'BPXSY1', 'BPXDI1', 'BPXSY2', 'BPXDI2', 'BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML', 'BMXARMC', 'BMXWAIST', 'HIQ210'], dtype='object') We will start with the most basic ‘pairplot’ using the Pandas library. It is called ‘scatter_matrix’ in Pandas library. Before that, I should mention I will use a part of the dataset. Because if I use too many features the scatter_matrix or pair plot whatever you call it, will not be very helpful. Each plot in it will be too small. Five continuous variables were chosen for this demonstration: ‘BMXWT’, ‘BMXHT’, ‘BMXBMI’, ‘BMXLEG’, ‘BMXARML’. They represent the weight, height, BMI, leg length, and arm length of the population. We need to import scatter_matrix from the pandas' library and then simply use the scatter_matrix function. import matplotlib.pyplot as pltfrom pandas.plotting import scatter_matrixscatter_matrix(df[['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML']], figsize = (10, 10))plt.show() Output: You get the bivariate to scatter plots of all the combinations from the variable that is given. Each variable is plotted against the rest of the variables. Diagonal plots are the distributions of each variable given to the scatter_matrix function. This same plot can be obtained using the seaborn library. As you know seaborn library comes with some default style. So, the most basic pairplot is also a bit more stylish than the scatter_matrix. Instead of the histogram, I chose density plot for diagonal plots. I will make the density plots for the diagonals just for a little variation. So, I will specify ‘diag_kind = ‘kde’. If you want to keep the histogram just avoid specifying anything. Because the default type is the histogram. import seaborn as snsd = df[['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML']]sns.pairplot(d, diag_kind = 'kde') The next plot includes one more variable to this default plot. This time I will get all the plots in the pair plot segregated by the gender variable. At the same time, I am adding some transparency using the alpha parameter and an edge color as well. d = df[['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML', 'RIAGENDR']]sns.pairplot(d, diag_kind = 'kde', hue = 'RIAGENDR', plot_kws={'alpha':0.5, 'edgecolor': 'k'}) Output: Paiplot and scatter_matrix both are based on scatter plots. PairGrid brings a bit more flexibility to it. Using PairGrid, an empty grid can be generated. And later you can fill this up as you like. Let’s see this in action: g = sns.PairGrid(df, vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'], hue = 'RIAGENDR') This line of code will provide an empty grid as follows: Now, we will fill up those empty boxes. I will use the histograms for the diagonal plots and the rest will stay the scatter plot as before. It does not have to be a scatter plot. It can be any other bivariate plot. We will see an example in a bit: g.map_diag(plt.hist, alpha = 0.6)g.map_offdiag(plt.scatter, alpha = 0.5)g.add_legend() We segregated the plots using the gender parameter to see the distributions and scatter plots separately for males and females using the ‘hue’ parameter. The next plots use a continuous variable as a hue parameter. I chose ‘BPXSY1’ which means the systolic blood pressure for this. I am also going to add a condition to the dataset. I will use the data only for the ‘age’ over 60. g = sns.PairGrid(df[df["RIDAGEYR"]>60], vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'], hue = "BPXSY1")g.map_diag(sns.histplot, hue = None)g.map_offdiag(sns.scatterplot)g.add_legend() You can see the dots in the scatter plots are of different shades. Lighter the color lower the systolic blood pressure and darker the color higher the systolic blood pressure. Look! The lower triangle and the upper triangle have almost the same plots. If you just switch the axis of the plots of the lower triangles, you get the plots of upper triangles. So, if you want to see different types of plots in the lower and the upper triangle of the Pairplot, PairGrid provides that flexibility. We just have to mention map_upper for the upper triangle of the pairplot and map_lower for the lower triangle. g = sns.PairGrid(df[df["RIDAGEYR"]>60], vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'], hue = "RIAGENDR")g.map_lower(plt.scatter, alpha = 0.6)g.map_diag(plt.hist, alpha = 0.7) This will plot only the diagonals and the lower triangle. Let’s fill up the upper triangle as well. I will put the density plots with shades. g.map_upper(sns.kdeplot, shade =True) I think it can be more useful to have two different types of plots instead of almost the same plots in both the triangles. Again, if you do not want any other type, you can totally avoid either the upper or lower triangle. Here I am using diag_sharey = False to avoid the upper triangle. g = sns.PairGrid(df[df["RIDAGEYR"]>60], diag_sharey = False, corner = True, vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'],hue = "RIAGENDR")g.map_lower(plt.scatter, alpha = 0.6)g.map_diag(plt.hist, alpha = 0.7) Output: Here it is! The triangle is totally gone! Here I tried to introduce a few different ways to make and use pairplots. I also introduced PairGrids for more flexibility to the pair plots. Hopefully, this was helpful and you will try the documentation for more styles and options. Here is the video from of the same content: Please feel free to follow me on Twitter.
[ { "code": null, "e": 776, "s": 172, "text": "When I first learn to make the pairplots, I used them in every project for some time. I still use them a lot. Pair plots are several bivariate distributions in one plot and can be made using just one simple function. Even The most basic one is very useful in a data analytics project where there are several continuous variables. We know that a scatter plot is widely used to present the relationship between two continuous variables. Pair plot puts several scatter plots in one plot and also provides the distribution diagonally. This article is a tutorial on how to make Pairplots of different styles." }, { "code": null, "e": 801, "s": 776, "text": "This article will cover:" }, { "code": null, "e": 962, "s": 801, "text": "Pair plot using Pandas and MatplotlibMore Stylish and informative Pair plots using Seaborn libraryUse of the ‘PairGrid’ function to make more dynamic pair plots" }, { "code": null, "e": 1000, "s": 962, "text": "Pair plot using Pandas and Matplotlib" }, { "code": null, "e": 1062, "s": 1000, "text": "More Stylish and informative Pair plots using Seaborn library" }, { "code": null, "e": 1125, "s": 1062, "text": "Use of the ‘PairGrid’ function to make more dynamic pair plots" }, { "code": null, "e": 1332, "s": 1125, "text": "I used this famous dataset called the ‘nhanes’ dataset. I find it useful because it has a lot of continuous and categorical features. Please feel free to download the dataset from this link to follow along:" }, { "code": null, "e": 1343, "s": 1332, "text": "github.com" }, { "code": null, "e": 1492, "s": 1343, "text": "The column names may look a bit strange if this dataset is new to you. But don’t worry about it. I will explain what they mean when I will use them." }, { "code": null, "e": 1523, "s": 1492, "text": "Let’s import the dataset first" }, { "code": null, "e": 1583, "s": 1523, "text": "import pandas as pddf = pd.read_csv(\"nhanes_2015_2016.csv\")" }, { "code": null, "e": 1685, "s": 1583, "text": "The dataset is pretty big. So, I cannot show a screenshot here. These are the columns in the dataset:" }, { "code": null, "e": 1696, "s": 1685, "text": "df.columns" }, { "code": null, "e": 1704, "s": 1696, "text": "Output:" }, { "code": null, "e": 2029, "s": 1704, "text": "Index(['SEQN', 'ALQ101', 'ALQ110', 'ALQ130', 'SMQ020', 'RIAGENDR', 'RIDAGEYR', 'RIDRETH1', 'DMDCITZN', 'DMDEDUC2', 'DMDMARTL', 'DMDHHSIZ', 'WTINT2YR', 'SDMVPSU', 'SDMVSTRA', 'INDFMPIR', 'BPXSY1', 'BPXDI1', 'BPXSY2', 'BPXDI2', 'BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML', 'BMXARMC', 'BMXWAIST', 'HIQ210'], dtype='object')" }, { "code": null, "e": 2149, "s": 2029, "text": "We will start with the most basic ‘pairplot’ using the Pandas library. It is called ‘scatter_matrix’ in Pandas library." }, { "code": null, "e": 2560, "s": 2149, "text": "Before that, I should mention I will use a part of the dataset. Because if I use too many features the scatter_matrix or pair plot whatever you call it, will not be very helpful. Each plot in it will be too small. Five continuous variables were chosen for this demonstration: ‘BMXWT’, ‘BMXHT’, ‘BMXBMI’, ‘BMXLEG’, ‘BMXARML’. They represent the weight, height, BMI, leg length, and arm length of the population." }, { "code": null, "e": 2667, "s": 2560, "text": "We need to import scatter_matrix from the pandas' library and then simply use the scatter_matrix function." }, { "code": null, "e": 2840, "s": 2667, "text": "import matplotlib.pyplot as pltfrom pandas.plotting import scatter_matrixscatter_matrix(df[['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML']], figsize = (10, 10))plt.show()" }, { "code": null, "e": 2848, "s": 2840, "text": "Output:" }, { "code": null, "e": 3096, "s": 2848, "text": "You get the bivariate to scatter plots of all the combinations from the variable that is given. Each variable is plotted against the rest of the variables. Diagonal plots are the distributions of each variable given to the scatter_matrix function." }, { "code": null, "e": 3360, "s": 3096, "text": "This same plot can be obtained using the seaborn library. As you know seaborn library comes with some default style. So, the most basic pairplot is also a bit more stylish than the scatter_matrix. Instead of the histogram, I chose density plot for diagonal plots." }, { "code": null, "e": 3585, "s": 3360, "text": "I will make the density plots for the diagonals just for a little variation. So, I will specify ‘diag_kind = ‘kde’. If you want to keep the histogram just avoid specifying anything. Because the default type is the histogram." }, { "code": null, "e": 3698, "s": 3585, "text": "import seaborn as snsd = df[['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML']]sns.pairplot(d, diag_kind = 'kde')" }, { "code": null, "e": 3949, "s": 3698, "text": "The next plot includes one more variable to this default plot. This time I will get all the plots in the pair plot segregated by the gender variable. At the same time, I am adding some transparency using the alpha parameter and an edge color as well." }, { "code": null, "e": 4113, "s": 3949, "text": "d = df[['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML', 'RIAGENDR']]sns.pairplot(d, diag_kind = 'kde', hue = 'RIAGENDR', plot_kws={'alpha':0.5, 'edgecolor': 'k'})" }, { "code": null, "e": 4121, "s": 4113, "text": "Output:" }, { "code": null, "e": 4227, "s": 4121, "text": "Paiplot and scatter_matrix both are based on scatter plots. PairGrid brings a bit more flexibility to it." }, { "code": null, "e": 4345, "s": 4227, "text": "Using PairGrid, an empty grid can be generated. And later you can fill this up as you like. Let’s see this in action:" }, { "code": null, "e": 4442, "s": 4345, "text": "g = sns.PairGrid(df, vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'], hue = 'RIAGENDR')" }, { "code": null, "e": 4499, "s": 4442, "text": "This line of code will provide an empty grid as follows:" }, { "code": null, "e": 4747, "s": 4499, "text": "Now, we will fill up those empty boxes. I will use the histograms for the diagonal plots and the rest will stay the scatter plot as before. It does not have to be a scatter plot. It can be any other bivariate plot. We will see an example in a bit:" }, { "code": null, "e": 4834, "s": 4747, "text": "g.map_diag(plt.hist, alpha = 0.6)g.map_offdiag(plt.scatter, alpha = 0.5)g.add_legend()" }, { "code": null, "e": 5215, "s": 4834, "text": "We segregated the plots using the gender parameter to see the distributions and scatter plots separately for males and females using the ‘hue’ parameter. The next plots use a continuous variable as a hue parameter. I chose ‘BPXSY1’ which means the systolic blood pressure for this. I am also going to add a condition to the dataset. I will use the data only for the ‘age’ over 60." }, { "code": null, "e": 5412, "s": 5215, "text": "g = sns.PairGrid(df[df[\"RIDAGEYR\"]>60], vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'], hue = \"BPXSY1\")g.map_diag(sns.histplot, hue = None)g.map_offdiag(sns.scatterplot)g.add_legend()" }, { "code": null, "e": 5588, "s": 5412, "text": "You can see the dots in the scatter plots are of different shades. Lighter the color lower the systolic blood pressure and darker the color higher the systolic blood pressure." }, { "code": null, "e": 6015, "s": 5588, "text": "Look! The lower triangle and the upper triangle have almost the same plots. If you just switch the axis of the plots of the lower triangles, you get the plots of upper triangles. So, if you want to see different types of plots in the lower and the upper triangle of the Pairplot, PairGrid provides that flexibility. We just have to mention map_upper for the upper triangle of the pairplot and map_lower for the lower triangle." }, { "code": null, "e": 6219, "s": 6015, "text": "g = sns.PairGrid(df[df[\"RIDAGEYR\"]>60], vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'], hue = \"RIAGENDR\")g.map_lower(plt.scatter, alpha = 0.6)g.map_diag(plt.hist, alpha = 0.7)" }, { "code": null, "e": 6277, "s": 6219, "text": "This will plot only the diagonals and the lower triangle." }, { "code": null, "e": 6361, "s": 6277, "text": "Let’s fill up the upper triangle as well. I will put the density plots with shades." }, { "code": null, "e": 6399, "s": 6361, "text": "g.map_upper(sns.kdeplot, shade =True)" }, { "code": null, "e": 6522, "s": 6399, "text": "I think it can be more useful to have two different types of plots instead of almost the same plots in both the triangles." }, { "code": null, "e": 6687, "s": 6522, "text": "Again, if you do not want any other type, you can totally avoid either the upper or lower triangle. Here I am using diag_sharey = False to avoid the upper triangle." }, { "code": null, "e": 6908, "s": 6687, "text": "g = sns.PairGrid(df[df[\"RIDAGEYR\"]>60], diag_sharey = False, corner = True, vars = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML'],hue = \"RIAGENDR\")g.map_lower(plt.scatter, alpha = 0.6)g.map_diag(plt.hist, alpha = 0.7)" }, { "code": null, "e": 6916, "s": 6908, "text": "Output:" }, { "code": null, "e": 6958, "s": 6916, "text": "Here it is! The triangle is totally gone!" }, { "code": null, "e": 7192, "s": 6958, "text": "Here I tried to introduce a few different ways to make and use pairplots. I also introduced PairGrids for more flexibility to the pair plots. Hopefully, this was helpful and you will try the documentation for more styles and options." }, { "code": null, "e": 7236, "s": 7192, "text": "Here is the video from of the same content:" } ]
Mongoose | findOneAndDelete() Function - GeeksforGeeks
20 May, 2020 The findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find only one document matching the// condition(age >= 5) and delete itUser.findOneAndDelete({age: {$gte:5} }, function (err, docs) { if (err){ console.log(err) } else{ console.log("Deleted User : ", docs); }}); Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the particular user is deleted as shown below: The project structure will look like this: Make sure you have installed mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After the function is executed, You can see in the database that the particular user is deleted as shown below: So this is how you can use the mongoose findOneAndDelete() function which finds a matching document, removes it, and passes the found document (if any) to the callback. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Spring Boot JpaRepository with Example Aggregation in MongoDB MongoDB - db.collection.Find() Method MongoDB - Check the existence of the fields in the specified collection Mongoose Populate() Method Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.readFile() Method Node.js fs.writeFile() Method
[ { "code": null, "e": 24128, "s": 24100, "text": "\n20 May, 2020" }, { "code": null, "e": 24264, "s": 24128, "text": "The findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback." }, { "code": null, "e": 24297, "s": 24264, "text": "Installation of mongoose module:" }, { "code": null, "e": 24692, "s": 24297, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 24815, "s": 24692, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 24836, "s": 24815, "text": "npm install mongoose" }, { "code": null, "e": 24963, "s": 24836, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 24984, "s": 24963, "text": "npm version mongoose" }, { "code": null, "e": 25131, "s": 24984, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 25145, "s": 25131, "text": "node index.js" }, { "code": null, "e": 25164, "s": 25145, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find only one document matching the// condition(age >= 5) and delete itUser.findOneAndDelete({age: {$gte:5} }, function (err, docs) { if (err){ console.log(err) } else{ console.log(\"Deleted User : \", docs); }});", "e": 25718, "s": 25164, "text": null }, { "code": null, "e": 25744, "s": 25718, "text": "Steps to run the program:" }, { "code": null, "e": 26219, "s": 25744, "text": "The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the particular user is deleted as shown below:" }, { "code": null, "e": 26262, "s": 26219, "text": "The project structure will look like this:" }, { "code": null, "e": 26352, "s": 26262, "text": "Make sure you have installed mongoose module using following command:npm install mongoose" }, { "code": null, "e": 26373, "s": 26352, "text": "npm install mongoose" }, { "code": null, "e": 26555, "s": 26373, "text": "Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 26607, "s": 26555, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 26621, "s": 26607, "text": "node index.js" }, { "code": null, "e": 26733, "s": 26621, "text": "After the function is executed, You can see in the database that the particular user is deleted as shown below:" }, { "code": null, "e": 26902, "s": 26733, "text": "So this is how you can use the mongoose findOneAndDelete() function which finds a matching document, removes it, and passes the found document (if any) to the callback." }, { "code": null, "e": 26911, "s": 26902, "text": "Mongoose" }, { "code": null, "e": 26919, "s": 26911, "text": "MongoDB" }, { "code": null, "e": 26927, "s": 26919, "text": "Node.js" }, { "code": null, "e": 26944, "s": 26927, "text": "Web Technologies" }, { "code": null, "e": 27042, "s": 26944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27051, "s": 27042, "text": "Comments" }, { "code": null, "e": 27064, "s": 27051, "text": "Old Comments" }, { "code": null, "e": 27103, "s": 27064, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 27126, "s": 27103, "text": "Aggregation in MongoDB" }, { "code": null, "e": 27164, "s": 27126, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 27236, "s": 27164, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 27263, "s": 27236, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27296, "s": 27263, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27344, "s": 27296, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27377, "s": 27344, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27406, "s": 27377, "text": "Node.js fs.readFile() Method" } ]
PHP - Simple XML GET
XML Get has used to get the node values from xml file. The following example shows, How to get the data from xml. Note.xml is xml file, It can accessed by php file. <SUBJECT> <COURSE>Android</COURSE> <COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY> <PRICE>$10</PRICE> </SUBJECT> Index page has rights to get access the xml data by using implexml_load_file(). <?php $xml = simplexml_load_file("note.xml") or die("Error: Object Creation failure"); ?> <html> <head> <body> <?php echo $xml->COURSE . "<br>"; echo $xml->COUNTRY . "<br>"; echo $xml->COMPANY . "<br>"; echo $xml->PRICE; ?> </body> </head> </html> It will produce the following result − The below code is having information about how to get node values from xml file and XML should be as follows − <?xml version = "1.0" encoding = "utf-8"?> <tutorialspoint> <course category = "JAVA"> <title lang = "en">Java</title> <tutor>Gopal</tutor> <duration></duration> <price>$30</price> </course> <course category = "HADOOP"> <title lang = "en">Hadoop</title>. <tutor>Satish</tutor> <duration>3>/duration> <price>$50</price> </course> <course category = "HTML"> <title lang = "en">html</title> <tutor>raju</tutor> <duration>5</duration> <price>$50</price> </course> <course category = "WEB"> <title lang = "en">Web Technologies</title> <tutor>Javed</tutor> <duration>10</duration> <price>$60</price> </course> </tutorialspoint> PHP code should be as follows <html> <body> <?php $xml = simplexml_load_file("books.xml") or die("Error: Cannot create object"); foreach($xml->children() as $books) { echo $books->title . "<br> "; echo $books->tutor . "<br> "; echo $books->duration . "<br> "; echo $books->price . "<hr>"; } ?> </body> </html> It will produce the following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2871, "s": 2757, "text": "XML Get has used to get the node values from xml file. The following example shows, How to get the data from xml." }, { "code": null, "e": 2922, "s": 2871, "text": "Note.xml is xml file, It can accessed by php file." }, { "code": null, "e": 3058, "s": 2922, "text": "<SUBJECT>\n <COURSE>Android</COURSE>\n <COUNTRY>India</COUNTRY>\n <COMPANY>TutorialsPoint</COMPANY>\n <PRICE>$10</PRICE>\n</SUBJECT>" }, { "code": null, "e": 3138, "s": 3058, "text": "Index page has rights to get access the xml data by using implexml_load_file()." }, { "code": null, "e": 3508, "s": 3138, "text": "<?php\n $xml = simplexml_load_file(\"note.xml\") or die(\"Error: Object Creation failure\");\n?>\n\n<html>\n <head>\n \n <body>\n \n <?php\n echo $xml->COURSE . \"<br>\";\n echo $xml->COUNTRY . \"<br>\";\n echo $xml->COMPANY . \"<br>\";\n echo $xml->PRICE;\n ?>\n \n </body>\n \n </head>\n</html>" }, { "code": null, "e": 3547, "s": 3508, "text": "It will produce the following result −" }, { "code": null, "e": 3658, "s": 3547, "text": "The below code is having information about how to get node values from xml file and XML should be as follows −" }, { "code": null, "e": 4417, "s": 3658, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<tutorialspoint>\n \n <course category = \"JAVA\">\n <title lang = \"en\">Java</title>\n <tutor>Gopal</tutor>\n <duration></duration>\n <price>$30</price>\n </course>\n \n <course category = \"HADOOP\">\n <title lang = \"en\">Hadoop</title>.\n <tutor>Satish</tutor>\n <duration>3>/duration>\n <price>$50</price>\n </course>\n \n <course category = \"HTML\">\n <title lang = \"en\">html</title>\n <tutor>raju</tutor>\n <duration>5</duration>\n <price>$50</price>\n </course>\n \n <course category = \"WEB\">\n <title lang = \"en\">Web Technologies</title>\n <tutor>Javed</tutor>\n <duration>10</duration>\n <price>$60</price>\n </course>\n\n</tutorialspoint>" }, { "code": null, "e": 4447, "s": 4417, "text": "PHP code should be as follows" }, { "code": null, "e": 4845, "s": 4447, "text": "<html>\n <body>\n \n <?php\n $xml = simplexml_load_file(\"books.xml\") or die(\"Error: Cannot create object\");\n \n foreach($xml->children() as $books) { \n echo $books->title . \"<br> \"; \n echo $books->tutor . \"<br> \"; \n echo $books->duration . \"<br> \";\n echo $books->price . \"<hr>\"; \n }\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 4884, "s": 4845, "text": "It will produce the following result −" }, { "code": null, "e": 4917, "s": 4884, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4933, "s": 4917, "text": " Malhar Lathkar" }, { "code": null, "e": 4966, "s": 4933, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4977, "s": 4966, "text": " Syed Raza" }, { "code": null, "e": 5012, "s": 4977, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5029, "s": 5012, "text": " Frahaan Hussain" }, { "code": null, "e": 5062, "s": 5029, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5077, "s": 5062, "text": " Nivedita Jain" }, { "code": null, "e": 5112, "s": 5077, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5124, "s": 5112, "text": " Azaz Patel" }, { "code": null, "e": 5159, "s": 5124, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5187, "s": 5159, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5194, "s": 5187, "text": " Print" }, { "code": null, "e": 5205, "s": 5194, "text": " Add Notes" } ]
Java program to count words in a given string
The words in a given string can be counted using a while loop. An example of this is given as follows − String = Sky is blue Number of words = 3 A program that demonstrates this is given as follows. Live Demo public class Example { public static void main(String args[]) { int flag = 0; int count = 0; int i = 0; String str = "The sunset is beautiful"; while (i < str.length()) { if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') { flag = 0; }else if (flag == 0) { flag = 1; count++; } i++; } System.out.println("The string is: " + str); System.out.println("No of words in the above string are: " + count); } } The output of the above program is as follows. The string is : The sunset is beautiful No of words in the above string are : 4 Now let us understand the above program. First, the string str is defined. Then a while loop is used to obtain the number of words in the string. This is done using the flag variable that is initially initialized to 0. The code snippet that demonstrates this is given as follows. int flag = 0; int count = 0; int i = 0; String str = "The sunset is beautiful"; while (i < str.length()) { if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') { flag = 0; }else if (flag == 0) { flag = 1; count++; } i++; } Finally, the string and the number of words in it are displayed. The code snippet that demonstrates this is given as follows. System.out.println("The string is: " + str); System.out.println("No of words in the above string are: " + count);
[ { "code": null, "e": 1166, "s": 1062, "text": "The words in a given string can be counted using a while loop. An example of this is given as follows −" }, { "code": null, "e": 1207, "s": 1166, "text": "String = Sky is blue\nNumber of words = 3" }, { "code": null, "e": 1261, "s": 1207, "text": "A program that demonstrates this is given as follows." }, { "code": null, "e": 1272, "s": 1261, "text": " Live Demo" }, { "code": null, "e": 1826, "s": 1272, "text": "public class Example {\n public static void main(String args[]) {\n int flag = 0;\n int count = 0;\n int i = 0;\n String str = \"The sunset is beautiful\";\n while (i < str.length()) {\n if (str.charAt(i) == ' ' || str.charAt(i) == '\\n' || str.charAt(i) == '\\t') {\n flag = 0;\n }else if (flag == 0) {\n flag = 1;\n count++;\n }\n i++;\n }\n System.out.println(\"The string is: \" + str);\n System.out.println(\"No of words in the above string are: \" + count);\n }\n}" }, { "code": null, "e": 1873, "s": 1826, "text": "The output of the above program is as follows." }, { "code": null, "e": 1953, "s": 1873, "text": "The string is : The sunset is beautiful\nNo of words in the above string are : 4" }, { "code": null, "e": 1994, "s": 1953, "text": "Now let us understand the above program." }, { "code": null, "e": 2233, "s": 1994, "text": "First, the string str is defined. Then a while loop is used to obtain the number of words in the string. This is done using the flag variable that is initially initialized to 0. The code snippet that demonstrates this is given as follows." }, { "code": null, "e": 2509, "s": 2233, "text": "int flag = 0;\nint count = 0;\nint i = 0;\nString str = \"The sunset is beautiful\";\nwhile (i < str.length()) {\n if (str.charAt(i) == ' ' || str.charAt(i) == '\\n' || str.charAt(i) == '\\t') {\n flag = 0;\n }else if (flag == 0) {\n flag = 1;\n count++;\n }\n i++;\n}" }, { "code": null, "e": 2635, "s": 2509, "text": "Finally, the string and the number of words in it are displayed. The code snippet that demonstrates this is given as follows." }, { "code": null, "e": 2749, "s": 2635, "text": "System.out.println(\"The string is: \" + str);\nSystem.out.println(\"No of words in the above string are: \" + count);" } ]
Semaphores in Operating System
Semaphores are integer variables that are used to solve the critical section problem by using two atomic operations, wait and signal that are used for process synchronization. The definitions of wait and signal are as follows − WaitThe wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed. The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed. wait(S) { while (S<=0); S--; } SignalThe signal operation increments the value of its argument S. The signal operation increments the value of its argument S. signal(S) { S++; } There are two main types of semaphores i.e. counting semaphores and binary semaphores. Details about these are given as follows − Counting SemaphoresThese are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources. If the resources are added, semaphore count automatically incremented and if the resources are removed, the count is decremented. These are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources. If the resources are added, semaphore count automatically incremented and if the resources are removed, the count is decremented. Binary SemaphoresThe binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0. It is sometimes easier to implement binary semaphores than counting semaphores. The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0. It is sometimes easier to implement binary semaphores than counting semaphores. Some of the advantages of semaphores are as follows − Semaphores allow only one process into the critical section. They follow the mutual exclusion principle strictly and are much more efficient than some other methods of synchronization. There is no resource wastage because of busy waiting in semaphores as processor time is not wasted unnecessarily to check if a condition is fulfilled to allow a process to access the critical section. Semaphores are implemented in the machine independent code of the microkernel. So they are machine independent. Some of the disadvantages of semaphores are as follows − Semaphores are complicated so the wait and signal operations must be implemented in the correct order to prevent deadlocks. Semaphores are impractical for last scale use as their use leads to loss of modularity. This happens because the wait and signal operations prevent the creation of a structured layout for the system. Semaphores may lead to a priority inversion where low priority processes may access the critical section first and high priority processes later.
[ { "code": null, "e": 1238, "s": 1062, "text": "Semaphores are integer variables that are used to solve the critical section problem by using two atomic operations, wait and signal that are used for process synchronization." }, { "code": null, "e": 1290, "s": 1238, "text": "The definitions of wait and signal are as follows −" }, { "code": null, "e": 1430, "s": 1290, "text": "WaitThe wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed." }, { "code": null, "e": 1566, "s": 1430, "text": "The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed." }, { "code": null, "e": 1604, "s": 1566, "text": "wait(S)\n{\n while (S<=0);\n\n S--;\n}" }, { "code": null, "e": 1671, "s": 1604, "text": "SignalThe signal operation increments the value of its argument S." }, { "code": null, "e": 1732, "s": 1671, "text": "The signal operation increments the value of its argument S." }, { "code": null, "e": 1754, "s": 1732, "text": "signal(S)\n{\n S++;\n}" }, { "code": null, "e": 1884, "s": 1754, "text": "There are two main types of semaphores i.e. counting semaphores and binary semaphores. Details about these are given as follows −" }, { "code": null, "e": 2232, "s": 1884, "text": "Counting SemaphoresThese are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources. If the resources are added, semaphore count automatically incremented and if the resources are removed, the count is decremented." }, { "code": null, "e": 2561, "s": 2232, "text": "These are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources. If the resources are added, semaphore count automatically incremented and if the resources are removed, the count is decremented." }, { "code": null, "e": 2860, "s": 2561, "text": "Binary SemaphoresThe binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0. It is sometimes easier to implement binary semaphores than counting semaphores." }, { "code": null, "e": 3142, "s": 2860, "text": "The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0. It is sometimes easier to implement binary semaphores than counting semaphores." }, { "code": null, "e": 3196, "s": 3142, "text": "Some of the advantages of semaphores are as follows −" }, { "code": null, "e": 3381, "s": 3196, "text": "Semaphores allow only one process into the critical section. They follow the mutual exclusion principle strictly and are much more efficient than some other methods of synchronization." }, { "code": null, "e": 3582, "s": 3381, "text": "There is no resource wastage because of busy waiting in semaphores as processor time is not wasted unnecessarily to check if a condition is fulfilled to allow a process to access the critical section." }, { "code": null, "e": 3694, "s": 3582, "text": "Semaphores are implemented in the machine independent code of the microkernel. So they are machine independent." }, { "code": null, "e": 3751, "s": 3694, "text": "Some of the disadvantages of semaphores are as follows −" }, { "code": null, "e": 3875, "s": 3751, "text": "Semaphores are complicated so the wait and signal operations must be implemented in the correct order to prevent deadlocks." }, { "code": null, "e": 4075, "s": 3875, "text": "Semaphores are impractical for last scale use as their use leads to loss of modularity. This happens because the wait and signal operations prevent the creation of a structured layout for the system." }, { "code": null, "e": 4221, "s": 4075, "text": "Semaphores may lead to a priority inversion where low priority processes may access the critical section first and high priority processes later." } ]
Java Program to add and remove elements from a set which maintains the insertion order
Create a LinkedHashSet − LinkedHashSet<Integer>set = new LinkedHashSet<Integer>(); Now, add elements to the Set − set.add(20); set.add(60); set.add(80); set.add(120); set.add(150); set.add(200); For removing the elements − set.remove(150); set.remove(260); Above process of insertion and deletion won’t affect the insertion order. Live Demo import java.util.LinkedHashSet; public class Demo { public static void main(String[] args) { LinkedHashSet<Integer>set = new LinkedHashSet<Integer>(); set.add(20); set.add(60); set.add(80); set.add(120); set.add(150); set.add(200); set.add(220); set.add(260); set.add(380); System.out.println("Set = "+set); set.remove(150); set.remove(260); System.out.println("Updated Set = "+set); set.remove(60); System.out.println("Updated Set = "+set); } } Set = [20, 60, 80, 120, 150, 200, 220, 260, 380] Updated Set = [20, 60, 80, 120, 200, 220, 380] Updated Set = [20, 80, 120, 200, 220, 380]
[ { "code": null, "e": 1087, "s": 1062, "text": "Create a LinkedHashSet −" }, { "code": null, "e": 1145, "s": 1087, "text": "LinkedHashSet<Integer>set = new LinkedHashSet<Integer>();" }, { "code": null, "e": 1176, "s": 1145, "text": "Now, add elements to the Set −" }, { "code": null, "e": 1257, "s": 1176, "text": "set.add(20);\nset.add(60);\nset.add(80);\nset.add(120);\nset.add(150);\nset.add(200);" }, { "code": null, "e": 1285, "s": 1257, "text": "For removing the elements −" }, { "code": null, "e": 1319, "s": 1285, "text": "set.remove(150);\nset.remove(260);" }, { "code": null, "e": 1393, "s": 1319, "text": "Above process of insertion and deletion won’t affect the insertion order." }, { "code": null, "e": 1404, "s": 1393, "text": " Live Demo" }, { "code": null, "e": 1952, "s": 1404, "text": "import java.util.LinkedHashSet;\npublic class Demo {\n public static void main(String[] args) {\n LinkedHashSet<Integer>set = new LinkedHashSet<Integer>();\n set.add(20);\n set.add(60);\n set.add(80);\n set.add(120);\n set.add(150);\n set.add(200);\n set.add(220);\n set.add(260);\n set.add(380);\n System.out.println(\"Set = \"+set);\n set.remove(150);\n set.remove(260);\n System.out.println(\"Updated Set = \"+set);\n set.remove(60);\n System.out.println(\"Updated Set = \"+set);\n }\n}" }, { "code": null, "e": 2091, "s": 1952, "text": "Set = [20, 60, 80, 120, 150, 200, 220, 260, 380]\nUpdated Set = [20, 60, 80, 120, 200, 220, 380]\nUpdated Set = [20, 80, 120, 200, 220, 380]" } ]
Lodash _.truncate() Method - GeeksforGeeks
18 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.truncate() method of String in lodash is used to truncate the stated string if it is longer than the specified string length. The last characters of the string which are truncated are replaced with the stated omission string which is by defaults “...”. Syntax: _.truncate([string=''], [options={}]) Parameters: This method accepts two parameters as mentioned above and described below: [string=”]: It is the string to be truncated. [options={}]: It is the options object. Here, the options field are as follows: [options.length]: It is the maximum string length which is by default 30.[options.omission=’...’]: It is the string which will indicate that the stated text is omitted.[options.separator] (RegExp|string): It is the separator pattern which is to be truncated. [options.length]: It is the maximum string length which is by default 30. [options.omission=’...’]: It is the string which will indicate that the stated text is omitted. [options.separator] (RegExp|string): It is the separator pattern which is to be truncated. Return Value: This method returns the truncated string. Example 1: Javascript // Requiring lodash libraryconst _ = require('lodash'); // Calling _.truncate() method with // its parameterlet res = _.truncate( 'GeeksforGeeks is a computer science portal.'); // Displays outputconsole.log(res); Output: GeeksforGeeks is a computer... Here, the stated string is longer than the maximum length of the string so its truncated and the truncated string to be returned in the output must be of length 30 including the omission string. Example 2: Javascript // Requiring lodash libraryconst _ = require('lodash'); // Calling _.truncate() method with // its parameterlet res = _.truncate( 'GeeksforGeeks, is a computer science portal.', { 'length': 22, 'omission': '***' }); // Displays outputconsole.log(res); Output: GeeksforGeeks, is a*** Here, the maximum length of the string as well as omission string both are specified. So, the resultant output is returned according to that. JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24722, "s": 24694, "text": "\n18 Sep, 2020" }, { "code": null, "e": 24862, "s": 24722, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 25121, "s": 24862, "text": "The _.truncate() method of String in lodash is used to truncate the stated string if it is longer than the specified string length. The last characters of the string which are truncated are replaced with the stated omission string which is by defaults “...”." }, { "code": null, "e": 25129, "s": 25121, "text": "Syntax:" }, { "code": null, "e": 25168, "s": 25129, "text": "_.truncate([string=''], [options={}])\n" }, { "code": null, "e": 25255, "s": 25168, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 25301, "s": 25255, "text": "[string=”]: It is the string to be truncated." }, { "code": null, "e": 25341, "s": 25301, "text": "[options={}]: It is the options object." }, { "code": null, "e": 25381, "s": 25341, "text": "Here, the options field are as follows:" }, { "code": null, "e": 25640, "s": 25381, "text": "[options.length]: It is the maximum string length which is by default 30.[options.omission=’...’]: It is the string which will indicate that the stated text is omitted.[options.separator] (RegExp|string): It is the separator pattern which is to be truncated." }, { "code": null, "e": 25714, "s": 25640, "text": "[options.length]: It is the maximum string length which is by default 30." }, { "code": null, "e": 25810, "s": 25714, "text": "[options.omission=’...’]: It is the string which will indicate that the stated text is omitted." }, { "code": null, "e": 25901, "s": 25810, "text": "[options.separator] (RegExp|string): It is the separator pattern which is to be truncated." }, { "code": null, "e": 25957, "s": 25901, "text": "Return Value: This method returns the truncated string." }, { "code": null, "e": 25968, "s": 25957, "text": "Example 1:" }, { "code": null, "e": 25979, "s": 25968, "text": "Javascript" }, { "code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling _.truncate() method with // its parameterlet res = _.truncate( 'GeeksforGeeks is a computer science portal.'); // Displays outputconsole.log(res);", "e": 26196, "s": 25979, "text": null }, { "code": null, "e": 26204, "s": 26196, "text": "Output:" }, { "code": null, "e": 26235, "s": 26204, "text": "GeeksforGeeks is a computer..." }, { "code": null, "e": 26430, "s": 26235, "text": "Here, the stated string is longer than the maximum length of the string so its truncated and the truncated string to be returned in the output must be of length 30 including the omission string." }, { "code": null, "e": 26443, "s": 26430, "text": "Example 2: " }, { "code": null, "e": 26454, "s": 26443, "text": "Javascript" }, { "code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling _.truncate() method with // its parameterlet res = _.truncate( 'GeeksforGeeks, is a computer science portal.', { 'length': 22, 'omission': '***' }); // Displays outputconsole.log(res);", "e": 26719, "s": 26454, "text": null }, { "code": null, "e": 26727, "s": 26719, "text": "Output:" }, { "code": null, "e": 26750, "s": 26727, "text": "GeeksforGeeks, is a***" }, { "code": null, "e": 26892, "s": 26750, "text": "Here, the maximum length of the string as well as omission string both are specified. So, the resultant output is returned according to that." }, { "code": null, "e": 26910, "s": 26892, "text": "JavaScript-Lodash" }, { "code": null, "e": 26921, "s": 26910, "text": "JavaScript" }, { "code": null, "e": 26938, "s": 26921, "text": "Web Technologies" }, { "code": null, "e": 27036, "s": 26938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27081, "s": 27036, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27142, "s": 27081, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27214, "s": 27142, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27260, "s": 27214, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27301, "s": 27260, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27343, "s": 27301, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27376, "s": 27343, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27419, "s": 27376, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27481, "s": 27419, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to connect a progress bar to a function in Tkinter?
A Progress Bar helps to visualize the state of a running process. We have used and interacted with many progress bars such as getting the status of downloading a file from the internet, Loading a file on the local system, etc. Let us suppose that we want to create and connect a progress bar in our application. We will create a full-width progress bar by using ProgressBar(win, options) method. It can be configured through a button that enables and disables it. #Import the required Libraries from tkinter import * from tkinter import ttk import time #Create an instance of tkinter frame win= Tk() #Set the geometry win.geometry("750x250") #Define a function to Show a Progress Bar #Create a ProgressBar in a function def run_progress(): my_progress= ttk.Progressbar(win, orient= HORIZONTAL, length= 500, mode= 'determinate') my_progress['value']+=500 my_progress.pack(pady=40) button.config(state= "disable") #Create a Button button=ttk.Button(win, text= "Run",command= run_progress) button.place(x= 340, y= 100) win.mainloop() Now run the above code to display a window that contains a progress bar. In the given output, if we will click the "Run" Button, it will start running the Progress Bar.
[ { "code": null, "e": 1289, "s": 1062, "text": "A Progress Bar helps to visualize the state of a running process. We have used and interacted with many progress bars such as getting the status of downloading a file from the internet, Loading a file on the local system, etc." }, { "code": null, "e": 1526, "s": 1289, "text": "Let us suppose that we want to create and connect a progress bar in our application. We will create a full-width progress bar by using ProgressBar(win, options) method. It can be configured through a button that enables and disables it." }, { "code": null, "e": 2110, "s": 1526, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\nimport time\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry\nwin.geometry(\"750x250\")\n\n#Define a function to Show a Progress Bar\n#Create a ProgressBar in a function\ndef run_progress():\n my_progress= ttk.Progressbar(win, orient= HORIZONTAL, length= 500, mode= 'determinate')\n my_progress['value']+=500\n my_progress.pack(pady=40)\n button.config(state= \"disable\")\n\n#Create a Button\nbutton=ttk.Button(win, text= \"Run\",command= run_progress)\nbutton.place(x= 340, y= 100)\n\nwin.mainloop()" }, { "code": null, "e": 2183, "s": 2110, "text": "Now run the above code to display a window that contains a progress bar." }, { "code": null, "e": 2279, "s": 2183, "text": "In the given output, if we will click the \"Run\" Button, it will start running the Progress Bar." } ]
Python Program to Form a New String where the First Character and the Last Character have been Exchanged
When it is required to form a new string where the first and last characters are exchanged, a method can be defined that uses indexing to form the new string. Below is the demonstration of the same − Live Demo def exchange_val(my_string): return my_string[-1:] + my_string[1:-1] + my_string[:1] my_string = “Hi there how are you” print(“The string is :”) print(my_string) print(“The modified string is :”) print(exchange_val(my_string)) The string is : Hi there how are you The modified string is : ui there how are yoH A method named ‘exchange_val’ is defined that takes a string as a parameter. A method named ‘exchange_val’ is defined that takes a string as a parameter. It uses indexing to exchange the first and last characters of a string. It uses indexing to exchange the first and last characters of a string. Outside the method, a string is defined, and is displayed on the console. Outside the method, a string is defined, and is displayed on the console. This method is called by passing the string as a parameter to it. This method is called by passing the string as a parameter to it. This is displayed as output on the console. This is displayed as output on the console.
[ { "code": null, "e": 1221, "s": 1062, "text": "When it is required to form a new string where the first and last characters are exchanged, a method can be defined that uses indexing to form the new string." }, { "code": null, "e": 1262, "s": 1221, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1273, "s": 1262, "text": " Live Demo" }, { "code": null, "e": 1504, "s": 1273, "text": "def exchange_val(my_string):\n return my_string[-1:] + my_string[1:-1] + my_string[:1]\n\nmy_string = “Hi there how are you”\nprint(“The string is :”)\nprint(my_string)\nprint(“The modified string is :”)\nprint(exchange_val(my_string))" }, { "code": null, "e": 1587, "s": 1504, "text": "The string is :\nHi there how are you\nThe modified string is :\nui there how are yoH" }, { "code": null, "e": 1664, "s": 1587, "text": "A method named ‘exchange_val’ is defined that takes a string as a parameter." }, { "code": null, "e": 1741, "s": 1664, "text": "A method named ‘exchange_val’ is defined that takes a string as a parameter." }, { "code": null, "e": 1813, "s": 1741, "text": "It uses indexing to exchange the first and last characters of a string." }, { "code": null, "e": 1885, "s": 1813, "text": "It uses indexing to exchange the first and last characters of a string." }, { "code": null, "e": 1959, "s": 1885, "text": "Outside the method, a string is defined, and is displayed on the console." }, { "code": null, "e": 2033, "s": 1959, "text": "Outside the method, a string is defined, and is displayed on the console." }, { "code": null, "e": 2099, "s": 2033, "text": "This method is called by passing the string as a parameter to it." }, { "code": null, "e": 2165, "s": 2099, "text": "This method is called by passing the string as a parameter to it." }, { "code": null, "e": 2209, "s": 2165, "text": "This is displayed as output on the console." }, { "code": null, "e": 2253, "s": 2209, "text": "This is displayed as output on the console." } ]
Tryit Editor v3.6 - Show Node.js Command Prompt
var fs = require('fs'); ​ //create a file named mynewfile1.txt: fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { if (err) throw err;
[ { "code": null, "e": 24, "s": 0, "text": "var fs = require('fs');" }, { "code": null, "e": 26, "s": 24, "text": "​" }, { "code": null, "e": 64, "s": 26, "text": "//create a file named mynewfile1.txt:" }, { "code": null, "e": 131, "s": 64, "text": "fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {" } ]
Spotify Genre Classification Algorithm | by Caelan Dwyer | Towards Data Science
This article assumes a basic understanding of machine learning algorithms and data science techniques. Article outline: Supervised machine learning Classification — multi-class Dataset — preliminary analysis & feature selection Algorithm selection — SVM, Logistic Regression, Random Forest Model performance — accuracy scores Improvements — hyperparameter tuning & ensemble learning Conclusions — more data! As with all technologies there are buzzwords, supervised learning is an umbrella term to describe an area of machine learning (the most frequently used in practice) where the data being used is labelled. The goal of a supervised learning algorithm is to leverage a dataset to produce a model that takes a feature vector (x) as input and outputs variable (Y). An algorithm is used to learn the mapping function from input to output, this is then used with new unseen input data to predict the output variables for that data. A classification algorithm takes a dataset of labelled examples as inputs to produce a model that can take unlabeled new data and automatically assign labels to the unlabeled example. If the classification problem has a set of two labels (for instance “spam” or “not spam”) then it is a binary classification problem. Multi-class classification is a problem where the number of labels within the set is three or greater. The problem that we are looking at is a multi-class as there are many genres within the set. The dataset being examined is a collection of song information. It is available on Kaggle and Github alongside my python code. The data has been split into labelled training data and unlabeled test data. Id — an arbitrary unique track identifier title — track title artist — singer or band year — year of release (or re-release) bpm — beats per minute (tempo) nrgy — energy: the higher the value the more energetic dnce — danceability: the higher the value, the easier it is to dance to this song dB — loudness (dB): the higher the value, the louder the song live — liveness: the higher the value, the more likely the song is a live recording val — valence: the higher the value, the more positive mood for the song dur — duration: the length of the song acous — acousticness: the higher the value the more acoustic the song is spch — speechiness: the higher the value the more spoken word the song contains pop — popularity: the higher the value the more popular the song is top genre — genre of the track (and the target variable for this problem) There were 15 null values identified within the training set within the top_genre column. The missingo library provides a great visualization for missing values, making it easy to identify the columns that have null values. The 15 null values were dropped. import missingno as msnomsno.bar(class_train, color="dodgerblue", sort="ascending", figsize=(10,5), fontsize=12)class_train["top genre"].isnull().value_counts()# dropping NULL valuesclass_train = class_train.dropna(axis=0) Prior to any model creation it is good practice to check for multicollinearity, which is correlation between the independent features within the dataset. The easiest way to check this is with a correlation heatmap. It is clear there is no multicollinearity. # Plot linear correlation matrixfig, ax = plt.subplots(figsize=(15,10))sns.heatmap(class_train.corr(), annot=True, cmap='YlGnBu', vmin=-1, vmax=1, center=0, ax=ax)plt.title('LINEAR CORRELATION MATRIX - CLASS_TRAIN')plt.show() The pop (popularity) column can be used to create another column that signifies if a song is liked (1) or not (2). Histograms can then be used to display the “Like” distribution for each of the features in the dataset. This is an example of feature engineering. conditions = [ (class_train['pop'] >= 55), (class_train['pop'] < 55) ]values = [1, 2]class_train['like'] = np.select(conditions, values)# for all featurespos_bpm = class_train[class_train['like'] == 1]['bpm']neg_bpm = class_train[class_train['like'] == 2]['bpm']pos_nrgy = class_train[class_train['like'] == 1]['nrgy']neg_nrgy = class_train[class_train['like'] == 2]['nrgy']pos_db = class_train[class_train['like'] == 1]['dB']neg_db = class_train[class_train['like'] == 2]['dB']pos_live = class_train[class_train['like'] == 1]['live']neg_live = class_train[class_train['like'] == 2]['live']pos_dur = class_train[class_train['like'] == 1]['dur']neg_dur = class_train[class_train['like'] == 2]['dur']pos_acous = class_train[class_train['like'] == 1]['acous']neg_acous = class_train[class_train['like'] == 2]['acous']pos_spch = class_train[class_train['like'] == 1]['spch']neg_spch = class_train[class_train['like'] == 2]['spch']pos_val = class_train[class_train['like'] == 1]['val']neg_val = class_train[class_train['like'] == 2]['val']pos_dnce = class_train[class_train['like'] == 1]['dnce']neg_dnce = class_train[class_train['like'] == 2]['dnce']fig2 = plt.figure(figsize=(20,20))#dnceax3 = fig2.add_subplot(331)ax3.set_xlabel('Danceability')ax3.set_ylabel('Count')ax3.set_title('Song Danceability Like Distribution')pos_dnce.hist(alpha=0.5, bins=30)ax4 = fig2.add_subplot(331)neg_dnce.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])#durationax5 = fig2.add_subplot(332)ax5.set_xlabel('Duration')ax5.set_ylabel('Count')ax5.set_title('Song Duration Like Distribution')pos_dur.hist(alpha=0.5, bins=30)ax6 = fig2.add_subplot(332)neg_dur.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# loudness (dB)ax7 = fig2.add_subplot(333)ax7.set_xlabel('Loudness -dB')ax7.set_ylabel('Count')ax7.set_title('Song Loudness Like Distribution')plt.legend(['Like', 'Dislike'])pos_db.hist(alpha=0.5, bins=30)ax8 = fig2.add_subplot(333)neg_db.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# energyax9 = fig2.add_subplot(334)ax9.set_xlabel('Energy')ax9.set_ylabel('Count')ax9.set_title('Song Energy Like Distribution')pos_nrgy.hist(alpha=0.5, bins=30)ax9 = fig2.add_subplot(334)neg_nrgy.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# liveax10 = fig2.add_subplot(335)ax10.set_xlabel('Liveness')ax10.set_ylabel('Count')ax10.set_title('Liveness - Like Distribution')pos_live.hist(alpha=0.5, bins=30)ax11 = fig2.add_subplot(335)neg_live.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# valax12 = fig2.add_subplot(336)ax12.set_xlabel('Valence')ax12.set_ylabel('Count')ax12.set_title('Valence (Mood?) - Like Distribution')pos_val.hist(alpha=0.5, bins=30)ax13 = fig2.add_subplot(336)neg_val.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# acousax14 = fig2.add_subplot(337)ax14.set_xlabel('Acousticness')ax14.set_ylabel('Count')ax14.set_title('Acousticness - Like Distribution')pos_acous.hist(alpha=0.5, bins=30)ax15 = fig2.add_subplot(337)neg_acous.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# speechax16 = fig2.add_subplot(338)ax16.set_xlabel('Speech')ax16.set_ylabel('Count')ax16.set_title('Speech - Like Distribution')pos_spch.hist(alpha=0.5, bins=30)ax17 = fig2.add_subplot(338)neg_spch.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# bpmax18 = fig2.add_subplot(339)ax18.set_xlabel('Beats Per Minute')ax18.set_ylabel('Count')ax18.set_title('Song BPM - Like Distribution')pos_bpm.hist(alpha=0.5, bins=30)ax19 = fig2.add_subplot(339)neg_bpm.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike']) The distribution of songs to genre within the training set was then investigated. Within the training set, there were 86 unique genre names, which is far too many. Upon further investigation, many of these genre names were simply geographical differentials, for instance, “British rock” and “album rock” — which could be grouped within a “rock” category. Therefore the genres were generalized further, reducing the number of genres from 86 to 20. class_train = class_train.replace({'top genre': {"album rock": "rock", "glam rock": "rock", "dance rock":"rock", "art rock":"rock", "soft rock":"rock", "country rock": "rock", "classic rock":"rock", "blues rock":"rock", "celtic rock":"rock", "australian rock":"rock", "german alternative rock":"rock", "alternative rock":"rock", "dance pop":"pop", "brill building pop": "pop", "europop": "pop", "barbadian pop": "pop", "classic uk pop":"pop", "new wave pop":"pop", "canadian pop":"pop", "art pop":"pop", "belgian pop": "pop", "britpop": "pop", "italian pop":"pop", "classic danish pop": "pop", "bow pop": "pop", "baroque pop": "pop", "bubblegum pop": "pop", "afropop":"pop", "hip pop":"pop", "atl hip hop": "hip hop", "east coast hip hop": "hip hop", "detroit hip hop":"hip hop", "bronx hip hop": "hip hop", "bubblegum dance": "dance", "eurodance":"dance", "belgian dance":"dance", "german dance": "dance", "classic soul": "soul", "british soul": "soul", "chicago soul": "soul", "british folk": "folk", "american folk revival":"folk", "drone folk":"folk","canadian folk":"folk", "deep adult standards":"adult standards", "glam metal": "metal", "alternative metal": "metal", "acoustic blues":"blues", "british blues":"blues", "louisiana blues":"blues", "g funk":"funk", "brit funk":"funk", "afrobeat":"dance", "british invasion":"rock", "doo-wop":"blues", "boy band":"pop", "merseybeat":"rock-and-roll", "blue":"blues", "bebop":"jazz", "avant-garde jazz":"jazz", "boogaloo": "latin", "big room": "trance", "bubble trance":"trance", "glam punk":"rock", "australian talent show":"pop", "mellow gold":"rock", "hi-nrg": "dance", "neo mellow": "pop", "yodeling":"folk", "classic girl group":"pop", "british dance band":"jazz", "deep house":"dance", "uk garage": "dance", "chicago rap":"hip hop"}}) The pie chart below shows the top 10 genres only to maintain a readable aesthetic. It is clear that the majority of the songs in the training dataset belong to the rock and pop category- the effect of this will be discussed in the conclusions. # Find percent of each genredf_genre = class_train['top genre'].value_counts()[:10].sort_values(ascending=False) / len(class_train)sizes = df_genre.values.tolist()labels = df_genre.index.values.tolist()# Pie chart for genrefig1, ax1 = plt.subplots(figsize=(10,10))ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=False, textprops={'fontsize': 14})ax1.axis('equal')plt.title("Most Popular Genres\n" + "(limited to top 10 genres)", bbox={'facecolor':'0.8', 'pad':5})plt.show() The distribution of the features was then looked at. The reason for this is we want each of the feature’s histograms to display a normal distribution. import matplotlib.pyplot as plt%matplotlib inlineclass_train.hist(bins=20, figsize=(15,15))plt.show() The histograms above show that some variables are skewed (acous, live, spch), are reason for this skew could be outliers. Therefore the skew could be remedied by removing potential outliers. Outliers can be identified using Box-plots, and a z-score. Data points with a z-score of more than 3 are removed. Removing outliers to reduce noise can improve a model’s performance and prevent overfitting. import seaborn as sns# acousticsns.boxplot(x=class_train['acous']) # no visible outliers# dursns.boxplot(x=class_train['dur']) # OUTLIERS !!# livesns.boxplot(x=class_train['live']) #OUTLIERS !!# spchsns.boxplot(x=class_train['spch']) #OUTLIERS !!class_train = class_train[np.abs(class_train.dur-class_train.dur.mean()) <= (3*class_train.dur.std())]# keep only the ones that are within +3 to -3 standard deviations in the column 'live'.class_train = class_train[np.abs(class_train.live-class_train.live.mean()) <= (3*class_train.live.std())]# keep only the ones that are within +3 to -3 standard deviations in the column 'live'.class_train= df[np.abs(class_train.spch-class_train.spch.mean()) <= (3*class_train.spch.std())]# keep only the ones that are within +3 to -3 standard deviations in the column 'spch'. The features that will be used within the model creation process are columns 3 to 13. The features that were dropped are Title, Artist and Id. The features selected for the model training were: ‘year’, ‘bpm’, ‘nrgy’, ‘dnce’, ‘dB’, ‘spch’, ‘pop’, ‘live’, ‘acous’. The training set was then separated using the train_test_split function to further partition the data into a 75% / 25% split. By further splitting the training dataset we have created a validation set. y = class_train.values[:,14]X = class_train.values[:,3:13]from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) These three sections are very much intertwined. As the algorithm selected is largely determined by how it performs in comparison to others, and in turn, improvements are very much an iterative process. The Support Vector Machine (SVM) algorithm is a good choice for analysis as the training set has a small number of instances and a large number of features. This is suitable as the SVM algorithm can deal with high bias/low variance. The OneVersusRest is a heuristic method that involves splitting the training data into multiple binary classification problems. As previously noted this problem has been identified as multi-label. However the SVM algorithm requires that the positive label has a numeric value of +1 and the negative label have a value of -1. Thus using the OneVersusRest technique a binary classifier it trained on each binary classification problem and predictions are made upon the most confident model. from sklearn import datasetsfrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import LinearSVCfrom sklearn.multiclass import OneVsRestClassifierstd_scaler = StandardScaler()X_scaled_train = std_scaler.fit_transform(X_train)X_scaled_train = std_scaler.fit_transform(X_train)X_scaled_train = std_scaler.fit_transform(X_train)svm_clf = OneVsRestClassifier(LinearSVC(C=1, loss = "hinge", random_state = 1))svm_clf.fit(X_scaled_train, y_train) Scaling was carried out before building our SVM as they are sensitive to feature scales. This was to prevent the widest possible street in the model from being too close to the decision boundary. Hyperparameters are not optimized by the learning algorithm and have to be done by us, the data analysts. Grid search is the most simple method for hyperparameter tuning, and it is available within scikit-learn Python machine learning library. On the first run of the model using the hyperparameter of C=1 the accuracy was very low at 26%. Grid search was used to reduce C (one of the algorithm’s hyperparameters) to 0.01. This will prevent overfitting. SVCpipe = Pipeline([('scale', StandardScaler()), ('SVC',LinearSVC())])# Gridsearch to determine the value of Cparam_grid = {'SVC__C':np.arange(0.01,100,10)}linearSVC = GridSearchCV(SVCpipe,param_grid,cv=5,return_train_score=True)linearSVC.fit(X_train,y_train)print(linearSVC.best_params_)svm_clf = OneVsRestClassifier(LinearSVC(C=0.01, loss = "hinge", random_state=1))preds = svm_clf.predict(X_scaled_train)from sklearn.metrics import classification_reportprint(classification_report(y_train,preds)) The final model accuracy that was achieved was 46%. Where accuracy is the number of correctly classified examples divided by the total number of classified examples. The Logistic Regression algorithm, which is a classification algorithm, not a regression can be used for both binary and multi-class problems. The accuracy score obtained was 50%. from sklearn.linear_model import LogisticRegressionovr_clf = OneVsRestClassifier(LogisticRegression(max_iter=1000, random_state=1))ovr_clf.fit(X_train, y_train)y_test_pred = ovr_clf.predict(X_test)from sklearn.metrics import accuracy_scoreconfusion_matrix(y_test, y_test_pred)print(accuracy_score(y_test, y_test_pred)) The Random Forest algorithm uses a modified tree learning algorithm to inspect a random subset of the features at each split in the “learning” process. This avoids the correlation of trees. Random Forest reduces the variance of the final model, reducing overfitting. Random Forest achieved an accuracy score of 46%. from sklearn.ensemble import RandomForestClassifierrnd_clf = RandomForestClassifier(n_estimators=25, max_leaf_nodes=16, n_jobs=-1, random_state=1)rnd_clf.fit(X_train, y_train)ypred = rnd_clf.predict(X_test)print(accuracy_score(y_test, ypred)) The best 3 models were selected to use for Ensemble learning: SVM, Logistic Regression and Random Forest. A hard voting classifier was used as it achieves high accuracy. from sklearn.ensemble import RandomForestClassifierfrom sklearn.ensemble import VotingClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVClog_clf = OneVsRestClassifier(LogisticRegression(max_iter=1000, penalty = "l2", C=1, random_state=1))rnd_clf = RandomForestClassifier(random_state=1)svm_clf = OneVsRestClassifier(LinearSVC(C=0.01, loss = "hinge", random_state = 1))voting_clf = VotingClassifier(estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],voting='hard')voting_clf.fit(X_train, y_train)from sklearn.metrics import accuracy_scorefor clf in (log_clf, rnd_clf, svm_clf, voting_clf): clf.fit(X_train, y_train) ypred = clf.predict(X_test) print(clf.__class__.__name__, accuracy_score(y_test, ypred)) The Logistic Regression and Voting Classifier had the same score. The Voting Classifier was selected as it is more robust as it reduces the spread of the predictions and model performance. When submitted to the Kaggle Competition... an acceptable 17th place (out of 50 teams). The accuracy score was significantly lower when the selected model was applied to the test data (once submitted to the Kaggle competition). This is called overfitting, whereby the model where it predicts well the labels of the training data, but makes frequent errors when applied to new data. This means that the model has a high variance. Possible solutions to Overfitting that were attempted: adding more Data removing outliers dimensionality reduction (via PCA) By identifying the 15 null values and manually adding the genre labels within the training set it was attempted to increase the overall sample size. However, removing outliers using the z-score is then largely counterproductive. Overall the amount of data that was available to train the model was very limited and this is probably what led to overfitting. # reload the dataclass_train = pd.read_csv("CS98XClassificationTrain.csv")class_test = pd.read_csv("CS98XClassificationTest.csv")# update the genres for the missing valuesclass_train.loc[class_train['title'] == 'Unchained Melody', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'Someone Elses Roses', 'top genre'] = 'adult standards'class_train.loc[class_train['title'] == 'Drinks On The House', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'Pachuko Hop', 'top genre'] = 'blues'class_train.loc[class_train['title'] == 'Little Things Means A Lot', 'top genre'] = 'blues'class_train.loc[class_train['title'] == 'The Lady Is A Tramp', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'If I Give My Heart To You', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'Happy Days And Lonely Nights','top genre'] = 'rock'class_train.loc[class_train['title'] == 'Stairway Of Love','top genre'] = 'rock'class_train.loc[class_train['title'] == 'You', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'No Other Love' , 'top genre'] = 'adult standards' class_train.loc[class_train['title'] == "Hot Diggity" , 'top genre'] = 'folk'class_train.loc[class_train['title'] == "Ain't That Just the Way" , 'top genre'] = 'r&b'class_train.loc[class_train['title'] == "I Promised Myself" , 'top genre'] = 'pop'# dropping NULL values (I've Waited So Long Anthony Newley = ? (Dance/ Electronic))class_train = class_train.dropna(axis=0)# check again for null valuesclass_train.info() PCA (Principal Component Analysis) is a dimensionality reduction method. Dimensionality reduction removes redundant and highly correlated features in the dataset. It also helps reduce the overall noise in the data. from sklearn.decomposition import PCApca = PCA()X_train = pca.fit_transform(X_train)X_test = pca.transform(X_test)explained_variance = pca.explained_variance_ratio_pca = PCA(n_components=0.95)X_reduced = pca.fit_transform(X_train)print(pca.explained_variance_ratio_)pca = PCA(n_components=6)X_train = pca.fit_transform(X_train)X_test = pca.transform(X_test) Using PCA to reduce the dimensionality showed no improvement on the Kaggle Score. PCA is most effective when features have a strong correlation to each other. As highlighted earlier with the Correlation heatmap there are no strong correlations between features within the training dataset. While the model did not perform brilliantly on the test data hopefully there were some useful lessons learned and visualizations that can be recast for your future projects! An excellent free resource to learn more about ML is the Hundred Page Machine Learning Book by Andriy Burkov.
[ { "code": null, "e": 150, "s": 47, "text": "This article assumes a basic understanding of machine learning algorithms and data science techniques." }, { "code": null, "e": 167, "s": 150, "text": "Article outline:" }, { "code": null, "e": 195, "s": 167, "text": "Supervised machine learning" }, { "code": null, "e": 224, "s": 195, "text": "Classification — multi-class" }, { "code": null, "e": 275, "s": 224, "text": "Dataset — preliminary analysis & feature selection" }, { "code": null, "e": 337, "s": 275, "text": "Algorithm selection — SVM, Logistic Regression, Random Forest" }, { "code": null, "e": 373, "s": 337, "text": "Model performance — accuracy scores" }, { "code": null, "e": 430, "s": 373, "text": "Improvements — hyperparameter tuning & ensemble learning" }, { "code": null, "e": 455, "s": 430, "text": "Conclusions — more data!" }, { "code": null, "e": 979, "s": 455, "text": "As with all technologies there are buzzwords, supervised learning is an umbrella term to describe an area of machine learning (the most frequently used in practice) where the data being used is labelled. The goal of a supervised learning algorithm is to leverage a dataset to produce a model that takes a feature vector (x) as input and outputs variable (Y). An algorithm is used to learn the mapping function from input to output, this is then used with new unseen input data to predict the output variables for that data." }, { "code": null, "e": 1163, "s": 979, "text": "A classification algorithm takes a dataset of labelled examples as inputs to produce a model that can take unlabeled new data and automatically assign labels to the unlabeled example." }, { "code": null, "e": 1493, "s": 1163, "text": "If the classification problem has a set of two labels (for instance “spam” or “not spam”) then it is a binary classification problem. Multi-class classification is a problem where the number of labels within the set is three or greater. The problem that we are looking at is a multi-class as there are many genres within the set." }, { "code": null, "e": 1620, "s": 1493, "text": "The dataset being examined is a collection of song information. It is available on Kaggle and Github alongside my python code." }, { "code": null, "e": 1697, "s": 1620, "text": "The data has been split into labelled training data and unlabeled test data." }, { "code": null, "e": 1739, "s": 1697, "text": "Id — an arbitrary unique track identifier" }, { "code": null, "e": 1759, "s": 1739, "text": "title — track title" }, { "code": null, "e": 1783, "s": 1759, "text": "artist — singer or band" }, { "code": null, "e": 1822, "s": 1783, "text": "year — year of release (or re-release)" }, { "code": null, "e": 1853, "s": 1822, "text": "bpm — beats per minute (tempo)" }, { "code": null, "e": 1908, "s": 1853, "text": "nrgy — energy: the higher the value the more energetic" }, { "code": null, "e": 1990, "s": 1908, "text": "dnce — danceability: the higher the value, the easier it is to dance to this song" }, { "code": null, "e": 2052, "s": 1990, "text": "dB — loudness (dB): the higher the value, the louder the song" }, { "code": null, "e": 2136, "s": 2052, "text": "live — liveness: the higher the value, the more likely the song is a live recording" }, { "code": null, "e": 2209, "s": 2136, "text": "val — valence: the higher the value, the more positive mood for the song" }, { "code": null, "e": 2248, "s": 2209, "text": "dur — duration: the length of the song" }, { "code": null, "e": 2321, "s": 2248, "text": "acous — acousticness: the higher the value the more acoustic the song is" }, { "code": null, "e": 2401, "s": 2321, "text": "spch — speechiness: the higher the value the more spoken word the song contains" }, { "code": null, "e": 2469, "s": 2401, "text": "pop — popularity: the higher the value the more popular the song is" }, { "code": null, "e": 2543, "s": 2469, "text": "top genre — genre of the track (and the target variable for this problem)" }, { "code": null, "e": 2800, "s": 2543, "text": "There were 15 null values identified within the training set within the top_genre column. The missingo library provides a great visualization for missing values, making it easy to identify the columns that have null values. The 15 null values were dropped." }, { "code": null, "e": 3023, "s": 2800, "text": "import missingno as msnomsno.bar(class_train, color=\"dodgerblue\", sort=\"ascending\", figsize=(10,5), fontsize=12)class_train[\"top genre\"].isnull().value_counts()# dropping NULL valuesclass_train = class_train.dropna(axis=0)" }, { "code": null, "e": 3281, "s": 3023, "text": "Prior to any model creation it is good practice to check for multicollinearity, which is correlation between the independent features within the dataset. The easiest way to check this is with a correlation heatmap. It is clear there is no multicollinearity." }, { "code": null, "e": 3507, "s": 3281, "text": "# Plot linear correlation matrixfig, ax = plt.subplots(figsize=(15,10))sns.heatmap(class_train.corr(), annot=True, cmap='YlGnBu', vmin=-1, vmax=1, center=0, ax=ax)plt.title('LINEAR CORRELATION MATRIX - CLASS_TRAIN')plt.show()" }, { "code": null, "e": 3769, "s": 3507, "text": "The pop (popularity) column can be used to create another column that signifies if a song is liked (1) or not (2). Histograms can then be used to display the “Like” distribution for each of the features in the dataset. This is an example of feature engineering." }, { "code": null, "e": 7315, "s": 3769, "text": "conditions = [ (class_train['pop'] >= 55), (class_train['pop'] < 55) ]values = [1, 2]class_train['like'] = np.select(conditions, values)# for all featurespos_bpm = class_train[class_train['like'] == 1]['bpm']neg_bpm = class_train[class_train['like'] == 2]['bpm']pos_nrgy = class_train[class_train['like'] == 1]['nrgy']neg_nrgy = class_train[class_train['like'] == 2]['nrgy']pos_db = class_train[class_train['like'] == 1]['dB']neg_db = class_train[class_train['like'] == 2]['dB']pos_live = class_train[class_train['like'] == 1]['live']neg_live = class_train[class_train['like'] == 2]['live']pos_dur = class_train[class_train['like'] == 1]['dur']neg_dur = class_train[class_train['like'] == 2]['dur']pos_acous = class_train[class_train['like'] == 1]['acous']neg_acous = class_train[class_train['like'] == 2]['acous']pos_spch = class_train[class_train['like'] == 1]['spch']neg_spch = class_train[class_train['like'] == 2]['spch']pos_val = class_train[class_train['like'] == 1]['val']neg_val = class_train[class_train['like'] == 2]['val']pos_dnce = class_train[class_train['like'] == 1]['dnce']neg_dnce = class_train[class_train['like'] == 2]['dnce']fig2 = plt.figure(figsize=(20,20))#dnceax3 = fig2.add_subplot(331)ax3.set_xlabel('Danceability')ax3.set_ylabel('Count')ax3.set_title('Song Danceability Like Distribution')pos_dnce.hist(alpha=0.5, bins=30)ax4 = fig2.add_subplot(331)neg_dnce.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])#durationax5 = fig2.add_subplot(332)ax5.set_xlabel('Duration')ax5.set_ylabel('Count')ax5.set_title('Song Duration Like Distribution')pos_dur.hist(alpha=0.5, bins=30)ax6 = fig2.add_subplot(332)neg_dur.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# loudness (dB)ax7 = fig2.add_subplot(333)ax7.set_xlabel('Loudness -dB')ax7.set_ylabel('Count')ax7.set_title('Song Loudness Like Distribution')plt.legend(['Like', 'Dislike'])pos_db.hist(alpha=0.5, bins=30)ax8 = fig2.add_subplot(333)neg_db.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# energyax9 = fig2.add_subplot(334)ax9.set_xlabel('Energy')ax9.set_ylabel('Count')ax9.set_title('Song Energy Like Distribution')pos_nrgy.hist(alpha=0.5, bins=30)ax9 = fig2.add_subplot(334)neg_nrgy.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# liveax10 = fig2.add_subplot(335)ax10.set_xlabel('Liveness')ax10.set_ylabel('Count')ax10.set_title('Liveness - Like Distribution')pos_live.hist(alpha=0.5, bins=30)ax11 = fig2.add_subplot(335)neg_live.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# valax12 = fig2.add_subplot(336)ax12.set_xlabel('Valence')ax12.set_ylabel('Count')ax12.set_title('Valence (Mood?) - Like Distribution')pos_val.hist(alpha=0.5, bins=30)ax13 = fig2.add_subplot(336)neg_val.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# acousax14 = fig2.add_subplot(337)ax14.set_xlabel('Acousticness')ax14.set_ylabel('Count')ax14.set_title('Acousticness - Like Distribution')pos_acous.hist(alpha=0.5, bins=30)ax15 = fig2.add_subplot(337)neg_acous.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# speechax16 = fig2.add_subplot(338)ax16.set_xlabel('Speech')ax16.set_ylabel('Count')ax16.set_title('Speech - Like Distribution')pos_spch.hist(alpha=0.5, bins=30)ax17 = fig2.add_subplot(338)neg_spch.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])# bpmax18 = fig2.add_subplot(339)ax18.set_xlabel('Beats Per Minute')ax18.set_ylabel('Count')ax18.set_title('Song BPM - Like Distribution')pos_bpm.hist(alpha=0.5, bins=30)ax19 = fig2.add_subplot(339)neg_bpm.hist(alpha=0.5, bins=30)plt.legend(['Like', 'Dislike'])" }, { "code": null, "e": 7762, "s": 7315, "text": "The distribution of songs to genre within the training set was then investigated. Within the training set, there were 86 unique genre names, which is far too many. Upon further investigation, many of these genre names were simply geographical differentials, for instance, “British rock” and “album rock” — which could be grouped within a “rock” category. Therefore the genres were generalized further, reducing the number of genres from 86 to 20." }, { "code": null, "e": 10043, "s": 7762, "text": "class_train = class_train.replace({'top genre': {\"album rock\": \"rock\", \"glam rock\": \"rock\", \"dance rock\":\"rock\", \"art rock\":\"rock\", \"soft rock\":\"rock\", \"country rock\": \"rock\", \"classic rock\":\"rock\", \"blues rock\":\"rock\", \"celtic rock\":\"rock\", \"australian rock\":\"rock\", \"german alternative rock\":\"rock\", \"alternative rock\":\"rock\", \"dance pop\":\"pop\", \"brill building pop\": \"pop\", \"europop\": \"pop\", \"barbadian pop\": \"pop\", \"classic uk pop\":\"pop\", \"new wave pop\":\"pop\", \"canadian pop\":\"pop\", \"art pop\":\"pop\", \"belgian pop\": \"pop\", \"britpop\": \"pop\", \"italian pop\":\"pop\", \"classic danish pop\": \"pop\", \"bow pop\": \"pop\", \"baroque pop\": \"pop\", \"bubblegum pop\": \"pop\", \"afropop\":\"pop\", \"hip pop\":\"pop\", \"atl hip hop\": \"hip hop\", \"east coast hip hop\": \"hip hop\", \"detroit hip hop\":\"hip hop\", \"bronx hip hop\": \"hip hop\", \"bubblegum dance\": \"dance\", \"eurodance\":\"dance\", \"belgian dance\":\"dance\", \"german dance\": \"dance\", \"classic soul\": \"soul\", \"british soul\": \"soul\", \"chicago soul\": \"soul\", \"british folk\": \"folk\", \"american folk revival\":\"folk\", \"drone folk\":\"folk\",\"canadian folk\":\"folk\", \"deep adult standards\":\"adult standards\", \"glam metal\": \"metal\", \"alternative metal\": \"metal\", \"acoustic blues\":\"blues\", \"british blues\":\"blues\", \"louisiana blues\":\"blues\", \"g funk\":\"funk\", \"brit funk\":\"funk\", \"afrobeat\":\"dance\", \"british invasion\":\"rock\", \"doo-wop\":\"blues\", \"boy band\":\"pop\", \"merseybeat\":\"rock-and-roll\", \"blue\":\"blues\", \"bebop\":\"jazz\", \"avant-garde jazz\":\"jazz\", \"boogaloo\": \"latin\", \"big room\": \"trance\", \"bubble trance\":\"trance\", \"glam punk\":\"rock\", \"australian talent show\":\"pop\", \"mellow gold\":\"rock\", \"hi-nrg\": \"dance\", \"neo mellow\": \"pop\", \"yodeling\":\"folk\", \"classic girl group\":\"pop\", \"british dance band\":\"jazz\", \"deep house\":\"dance\", \"uk garage\": \"dance\", \"chicago rap\":\"hip hop\"}})" }, { "code": null, "e": 10287, "s": 10043, "text": "The pie chart below shows the top 10 genres only to maintain a readable aesthetic. It is clear that the majority of the songs in the training dataset belong to the rock and pop category- the effect of this will be discussed in the conclusions." }, { "code": null, "e": 10769, "s": 10287, "text": "# Find percent of each genredf_genre = class_train['top genre'].value_counts()[:10].sort_values(ascending=False) / len(class_train)sizes = df_genre.values.tolist()labels = df_genre.index.values.tolist()# Pie chart for genrefig1, ax1 = plt.subplots(figsize=(10,10))ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=False, textprops={'fontsize': 14})ax1.axis('equal')plt.title(\"Most Popular Genres\\n\" + \"(limited to top 10 genres)\", bbox={'facecolor':'0.8', 'pad':5})plt.show()" }, { "code": null, "e": 10920, "s": 10769, "text": "The distribution of the features was then looked at. The reason for this is we want each of the feature’s histograms to display a normal distribution." }, { "code": null, "e": 11022, "s": 10920, "text": "import matplotlib.pyplot as plt%matplotlib inlineclass_train.hist(bins=20, figsize=(15,15))plt.show()" }, { "code": null, "e": 11420, "s": 11022, "text": "The histograms above show that some variables are skewed (acous, live, spch), are reason for this skew could be outliers. Therefore the skew could be remedied by removing potential outliers. Outliers can be identified using Box-plots, and a z-score. Data points with a z-score of more than 3 are removed. Removing outliers to reduce noise can improve a model’s performance and prevent overfitting." }, { "code": null, "e": 12230, "s": 11420, "text": "import seaborn as sns# acousticsns.boxplot(x=class_train['acous']) # no visible outliers# dursns.boxplot(x=class_train['dur']) # OUTLIERS !!# livesns.boxplot(x=class_train['live']) #OUTLIERS !!# spchsns.boxplot(x=class_train['spch']) #OUTLIERS !!class_train = class_train[np.abs(class_train.dur-class_train.dur.mean()) <= (3*class_train.dur.std())]# keep only the ones that are within +3 to -3 standard deviations in the column 'live'.class_train = class_train[np.abs(class_train.live-class_train.live.mean()) <= (3*class_train.live.std())]# keep only the ones that are within +3 to -3 standard deviations in the column 'live'.class_train= df[np.abs(class_train.spch-class_train.spch.mean()) <= (3*class_train.spch.std())]# keep only the ones that are within +3 to -3 standard deviations in the column 'spch'." }, { "code": null, "e": 12493, "s": 12230, "text": "The features that will be used within the model creation process are columns 3 to 13. The features that were dropped are Title, Artist and Id. The features selected for the model training were: ‘year’, ‘bpm’, ‘nrgy’, ‘dnce’, ‘dB’, ‘spch’, ‘pop’, ‘live’, ‘acous’." }, { "code": null, "e": 12695, "s": 12493, "text": "The training set was then separated using the train_test_split function to further partition the data into a 75% / 25% split. By further splitting the training dataset we have created a validation set." }, { "code": null, "e": 12896, "s": 12695, "text": "y = class_train.values[:,14]X = class_train.values[:,3:13]from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)" }, { "code": null, "e": 13098, "s": 12896, "text": "These three sections are very much intertwined. As the algorithm selected is largely determined by how it performs in comparison to others, and in turn, improvements are very much an iterative process." }, { "code": null, "e": 13820, "s": 13098, "text": "The Support Vector Machine (SVM) algorithm is a good choice for analysis as the training set has a small number of instances and a large number of features. This is suitable as the SVM algorithm can deal with high bias/low variance. The OneVersusRest is a heuristic method that involves splitting the training data into multiple binary classification problems. As previously noted this problem has been identified as multi-label. However the SVM algorithm requires that the positive label has a numeric value of +1 and the negative label have a value of -1. Thus using the OneVersusRest technique a binary classifier it trained on each binary classification problem and predictions are made upon the most confident model." }, { "code": null, "e": 14274, "s": 13820, "text": "from sklearn import datasetsfrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import LinearSVCfrom sklearn.multiclass import OneVsRestClassifierstd_scaler = StandardScaler()X_scaled_train = std_scaler.fit_transform(X_train)X_scaled_train = std_scaler.fit_transform(X_train)X_scaled_train = std_scaler.fit_transform(X_train)svm_clf = OneVsRestClassifier(LinearSVC(C=1, loss = \"hinge\", random_state = 1))svm_clf.fit(X_scaled_train, y_train)" }, { "code": null, "e": 14470, "s": 14274, "text": "Scaling was carried out before building our SVM as they are sensitive to feature scales. This was to prevent the widest possible street in the model from being too close to the decision boundary." }, { "code": null, "e": 14924, "s": 14470, "text": "Hyperparameters are not optimized by the learning algorithm and have to be done by us, the data analysts. Grid search is the most simple method for hyperparameter tuning, and it is available within scikit-learn Python machine learning library. On the first run of the model using the hyperparameter of C=1 the accuracy was very low at 26%. Grid search was used to reduce C (one of the algorithm’s hyperparameters) to 0.01. This will prevent overfitting." }, { "code": null, "e": 15442, "s": 14924, "text": "SVCpipe = Pipeline([('scale', StandardScaler()), ('SVC',LinearSVC())])# Gridsearch to determine the value of Cparam_grid = {'SVC__C':np.arange(0.01,100,10)}linearSVC = GridSearchCV(SVCpipe,param_grid,cv=5,return_train_score=True)linearSVC.fit(X_train,y_train)print(linearSVC.best_params_)svm_clf = OneVsRestClassifier(LinearSVC(C=0.01, loss = \"hinge\", random_state=1))preds = svm_clf.predict(X_scaled_train)from sklearn.metrics import classification_reportprint(classification_report(y_train,preds))" }, { "code": null, "e": 15608, "s": 15442, "text": "The final model accuracy that was achieved was 46%. Where accuracy is the number of correctly classified examples divided by the total number of classified examples." }, { "code": null, "e": 15788, "s": 15608, "text": "The Logistic Regression algorithm, which is a classification algorithm, not a regression can be used for both binary and multi-class problems. The accuracy score obtained was 50%." }, { "code": null, "e": 16107, "s": 15788, "text": "from sklearn.linear_model import LogisticRegressionovr_clf = OneVsRestClassifier(LogisticRegression(max_iter=1000, random_state=1))ovr_clf.fit(X_train, y_train)y_test_pred = ovr_clf.predict(X_test)from sklearn.metrics import accuracy_scoreconfusion_matrix(y_test, y_test_pred)print(accuracy_score(y_test, y_test_pred))" }, { "code": null, "e": 16423, "s": 16107, "text": "The Random Forest algorithm uses a modified tree learning algorithm to inspect a random subset of the features at each split in the “learning” process. This avoids the correlation of trees. Random Forest reduces the variance of the final model, reducing overfitting. Random Forest achieved an accuracy score of 46%." }, { "code": null, "e": 16666, "s": 16423, "text": "from sklearn.ensemble import RandomForestClassifierrnd_clf = RandomForestClassifier(n_estimators=25, max_leaf_nodes=16, n_jobs=-1, random_state=1)rnd_clf.fit(X_train, y_train)ypred = rnd_clf.predict(X_test)print(accuracy_score(y_test, ypred))" }, { "code": null, "e": 16836, "s": 16666, "text": "The best 3 models were selected to use for Ensemble learning: SVM, Logistic Regression and Random Forest. A hard voting classifier was used as it achieves high accuracy." }, { "code": null, "e": 17599, "s": 16836, "text": "from sklearn.ensemble import RandomForestClassifierfrom sklearn.ensemble import VotingClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVClog_clf = OneVsRestClassifier(LogisticRegression(max_iter=1000, penalty = \"l2\", C=1, random_state=1))rnd_clf = RandomForestClassifier(random_state=1)svm_clf = OneVsRestClassifier(LinearSVC(C=0.01, loss = \"hinge\", random_state = 1))voting_clf = VotingClassifier(estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],voting='hard')voting_clf.fit(X_train, y_train)from sklearn.metrics import accuracy_scorefor clf in (log_clf, rnd_clf, svm_clf, voting_clf): clf.fit(X_train, y_train) ypred = clf.predict(X_test) print(clf.__class__.__name__, accuracy_score(y_test, ypred))" }, { "code": null, "e": 17788, "s": 17599, "text": "The Logistic Regression and Voting Classifier had the same score. The Voting Classifier was selected as it is more robust as it reduces the spread of the predictions and model performance." }, { "code": null, "e": 17876, "s": 17788, "text": "When submitted to the Kaggle Competition... an acceptable 17th place (out of 50 teams)." }, { "code": null, "e": 18217, "s": 17876, "text": "The accuracy score was significantly lower when the selected model was applied to the test data (once submitted to the Kaggle competition). This is called overfitting, whereby the model where it predicts well the labels of the training data, but makes frequent errors when applied to new data. This means that the model has a high variance." }, { "code": null, "e": 18272, "s": 18217, "text": "Possible solutions to Overfitting that were attempted:" }, { "code": null, "e": 18289, "s": 18272, "text": "adding more Data" }, { "code": null, "e": 18307, "s": 18289, "text": "removing outliers" }, { "code": null, "e": 18342, "s": 18307, "text": "dimensionality reduction (via PCA)" }, { "code": null, "e": 18699, "s": 18342, "text": "By identifying the 15 null values and manually adding the genre labels within the training set it was attempted to increase the overall sample size. However, removing outliers using the z-score is then largely counterproductive. Overall the amount of data that was available to train the model was very limited and this is probably what led to overfitting." }, { "code": null, "e": 20218, "s": 18699, "text": "# reload the dataclass_train = pd.read_csv(\"CS98XClassificationTrain.csv\")class_test = pd.read_csv(\"CS98XClassificationTest.csv\")# update the genres for the missing valuesclass_train.loc[class_train['title'] == 'Unchained Melody', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'Someone Elses Roses', 'top genre'] = 'adult standards'class_train.loc[class_train['title'] == 'Drinks On The House', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'Pachuko Hop', 'top genre'] = 'blues'class_train.loc[class_train['title'] == 'Little Things Means A Lot', 'top genre'] = 'blues'class_train.loc[class_train['title'] == 'The Lady Is A Tramp', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'If I Give My Heart To You', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'Happy Days And Lonely Nights','top genre'] = 'rock'class_train.loc[class_train['title'] == 'Stairway Of Love','top genre'] = 'rock'class_train.loc[class_train['title'] == 'You', 'top genre'] = 'pop'class_train.loc[class_train['title'] == 'No Other Love' , 'top genre'] = 'adult standards' class_train.loc[class_train['title'] == \"Hot Diggity\" , 'top genre'] = 'folk'class_train.loc[class_train['title'] == \"Ain't That Just the Way\" , 'top genre'] = 'r&b'class_train.loc[class_train['title'] == \"I Promised Myself\" , 'top genre'] = 'pop'# dropping NULL values (I've Waited So Long Anthony Newley = ? (Dance/ Electronic))class_train = class_train.dropna(axis=0)# check again for null valuesclass_train.info()" }, { "code": null, "e": 20433, "s": 20218, "text": "PCA (Principal Component Analysis) is a dimensionality reduction method. Dimensionality reduction removes redundant and highly correlated features in the dataset. It also helps reduce the overall noise in the data." }, { "code": null, "e": 20791, "s": 20433, "text": "from sklearn.decomposition import PCApca = PCA()X_train = pca.fit_transform(X_train)X_test = pca.transform(X_test)explained_variance = pca.explained_variance_ratio_pca = PCA(n_components=0.95)X_reduced = pca.fit_transform(X_train)print(pca.explained_variance_ratio_)pca = PCA(n_components=6)X_train = pca.fit_transform(X_train)X_test = pca.transform(X_test)" }, { "code": null, "e": 21081, "s": 20791, "text": "Using PCA to reduce the dimensionality showed no improvement on the Kaggle Score. PCA is most effective when features have a strong correlation to each other. As highlighted earlier with the Correlation heatmap there are no strong correlations between features within the training dataset." }, { "code": null, "e": 21255, "s": 21081, "text": "While the model did not perform brilliantly on the test data hopefully there were some useful lessons learned and visualizations that can be recast for your future projects!" } ]
Java - The Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code. The methods declared by Enumeration are summarized in the following table − boolean hasMoreElements( ) When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated. Object nextElement( ) This returns the next object in the enumeration as a generic Object reference. Following is an example showing usage of Enumeration. import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration days; Vector dayNames = new Vector(); dayNames.add("Sunday"); dayNames.add("Monday"); dayNames.add("Tuesday"); dayNames.add("Wednesday"); dayNames.add("Thursday"); dayNames.add("Friday"); dayNames.add("Saturday"); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } This will produce the following result − Sunday Monday Tuesday Wednesday Thursday Friday Saturday 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2514, "s": 2377, "text": "The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects." }, { "code": null, "e": 2837, "s": 2514, "text": "This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code." }, { "code": null, "e": 2913, "s": 2837, "text": "The methods declared by Enumeration are summarized in the following table −" }, { "code": null, "e": 2940, "s": 2913, "text": "boolean hasMoreElements( )" }, { "code": null, "e": 3080, "s": 2940, "text": "When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated." }, { "code": null, "e": 3102, "s": 3080, "text": "Object nextElement( )" }, { "code": null, "e": 3181, "s": 3102, "text": "This returns the next object in the enumeration as a generic Object reference." }, { "code": null, "e": 3235, "s": 3181, "text": "Following is an example showing usage of Enumeration." }, { "code": null, "e": 3801, "s": 3235, "text": "import java.util.Vector;\nimport java.util.Enumeration;\n\npublic class EnumerationTester {\n\n public static void main(String args[]) {\n Enumeration days;\n Vector dayNames = new Vector();\n \n dayNames.add(\"Sunday\");\n dayNames.add(\"Monday\");\n dayNames.add(\"Tuesday\");\n dayNames.add(\"Wednesday\");\n dayNames.add(\"Thursday\");\n dayNames.add(\"Friday\");\n dayNames.add(\"Saturday\");\n days = dayNames.elements();\n \n while (days.hasMoreElements()) {\n System.out.println(days.nextElement()); \n }\n }\n}" }, { "code": null, "e": 3842, "s": 3801, "text": "This will produce the following result −" }, { "code": null, "e": 3900, "s": 3842, "text": "Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n" }, { "code": null, "e": 3933, "s": 3900, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3949, "s": 3933, "text": " Malhar Lathkar" }, { "code": null, "e": 3982, "s": 3949, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3998, "s": 3982, "text": " Malhar Lathkar" }, { "code": null, "e": 4033, "s": 3998, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4047, "s": 4033, "text": " Anadi Sharma" }, { "code": null, "e": 4081, "s": 4047, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4095, "s": 4081, "text": " Tushar Kale" }, { "code": null, "e": 4132, "s": 4095, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4147, "s": 4132, "text": " Monica Mittal" }, { "code": null, "e": 4180, "s": 4147, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4199, "s": 4180, "text": " Arnab Chakraborty" }, { "code": null, "e": 4206, "s": 4199, "text": " Print" }, { "code": null, "e": 4217, "s": 4206, "text": " Add Notes" } ]
CSS | transform-origin Property - GeeksforGeeks
06 Nov, 2019 The transform-origin property of CSS is used to specify the origin of rotation of an element. It is the point about which an element is rotated. It can be used for both 2D and 3D rotations. Syntax: transform-origin: position | initial | inherit Property Values: position: This specifies the position of the origin of rotation. It takes 3 values corresponding to the distance from the left edge of the box, the distance from the top edge of the box and the z-axis of rotation.The values could be specified in length units, percentages or keywords. The z-axis value is always specified using length units.Example 1: Specifying the position in length units<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 10px 30px; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html>Output:Example 2: Specifying the position in percentage<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 50% 75%; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html>Output:Example 3: Specifying the position in keywords<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: bottom left; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html>Output: The values could be specified in length units, percentages or keywords. The z-axis value is always specified using length units. Example 1: Specifying the position in length units <!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 10px 30px; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html> Output: Example 2: Specifying the position in percentage <!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 50% 75%; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html> Output: Example 3: Specifying the position in keywords <!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: bottom left; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html> Output: initial: This is used to set the property to its default value.Example:<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: initial; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html>Output: Example: <!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: initial; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html> Output: inherit: This is used to inherit the property from its parent.Example:<!DOCTYPE html><html> <head> <style> /* this acts as the parent */ .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; /* set the property of the parent */ transform-origin: bottom left; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); /* inherits the property of the parent */ transform-origin: inherit; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html>Output: Example: <!DOCTYPE html><html> <head> <style> /* this acts as the parent */ .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; /* set the property of the parent */ transform-origin: bottom left; } .box { position: absolute; border: 1px solid; background: url("https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); /* inherits the property of the parent */ transform-origin: inherit; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class="outer"> <div class="box"></div> </div></body> </html> Output: Supported Browsers: The browser supported by transform-origin property are listed below: Chrome 35.0 Internet Explorer 10.0 Firefox 16.0 Safari 9.0 Opera 23.0 shubham_singh CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24985, "s": 24957, "text": "\n06 Nov, 2019" }, { "code": null, "e": 25175, "s": 24985, "text": "The transform-origin property of CSS is used to specify the origin of rotation of an element. It is the point about which an element is rotated. It can be used for both 2D and 3D rotations." }, { "code": null, "e": 25183, "s": 25175, "text": "Syntax:" }, { "code": null, "e": 25230, "s": 25183, "text": "transform-origin: position | initial | inherit" }, { "code": null, "e": 25247, "s": 25230, "text": "Property Values:" }, { "code": null, "e": 28469, "s": 25247, "text": "position: This specifies the position of the origin of rotation. It takes 3 values corresponding to the distance from the left edge of the box, the distance from the top edge of the box and the z-axis of rotation.The values could be specified in length units, percentages or keywords. The z-axis value is always specified using length units.Example 1: Specifying the position in length units<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 10px 30px; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>Output:Example 2: Specifying the position in percentage<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 50% 75%; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>Output:Example 3: Specifying the position in keywords<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: bottom left; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>Output:" }, { "code": null, "e": 28598, "s": 28469, "text": "The values could be specified in length units, percentages or keywords. The z-axis value is always specified using length units." }, { "code": null, "e": 28649, "s": 28598, "text": "Example 1: Specifying the position in length units" }, { "code": "<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 10px 30px; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>", "e": 29551, "s": 28649, "text": null }, { "code": null, "e": 29559, "s": 29551, "text": "Output:" }, { "code": null, "e": 29608, "s": 29559, "text": "Example 2: Specifying the position in percentage" }, { "code": "<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: 50% 75%; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>", "e": 30514, "s": 29608, "text": null }, { "code": null, "e": 30522, "s": 30514, "text": "Output:" }, { "code": null, "e": 30569, "s": 30522, "text": "Example 3: Specifying the position in keywords" }, { "code": "<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: bottom left; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>", "e": 31479, "s": 30569, "text": null }, { "code": null, "e": 31487, "s": 31479, "text": "Output:" }, { "code": null, "e": 32470, "s": 31487, "text": "initial: This is used to set the property to its default value.Example:<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: initial; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>Output:" }, { "code": null, "e": 32479, "s": 32470, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); transform-origin: initial; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>", "e": 33384, "s": 32479, "text": null }, { "code": null, "e": 33392, "s": 33384, "text": "Output:" }, { "code": null, "e": 34559, "s": 33392, "text": "inherit: This is used to inherit the property from its parent.Example:<!DOCTYPE html><html> <head> <style> /* this acts as the parent */ .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; /* set the property of the parent */ transform-origin: bottom left; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); /* inherits the property of the parent */ transform-origin: inherit; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>Output:" }, { "code": null, "e": 34568, "s": 34559, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> /* this acts as the parent */ .outer { margin: 50px; border: 1px dotted; position: relative; height: 100px; width: 400px; background-color: lightgreen; /* set the property of the parent */ transform-origin: bottom left; } .box { position: absolute; border: 1px solid; background: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" ) no-repeat; background-size: cover; height: 100px; width: 400px; transform: rotate(15deg); /* inherits the property of the parent */ transform-origin: inherit; } </style></head> <body> <h1>CSS transform-origin Property</h1> <p>The CSS transform-origin Property is used to set the origin of the element's transformation</p> <div class=\"outer\"> <div class=\"box\"></div> </div></body> </html>", "e": 35658, "s": 34568, "text": null }, { "code": null, "e": 35666, "s": 35658, "text": "Output:" }, { "code": null, "e": 35755, "s": 35666, "text": "Supported Browsers: The browser supported by transform-origin property are listed below:" }, { "code": null, "e": 35767, "s": 35755, "text": "Chrome 35.0" }, { "code": null, "e": 35790, "s": 35767, "text": "Internet Explorer 10.0" }, { "code": null, "e": 35803, "s": 35790, "text": "Firefox 16.0" }, { "code": null, "e": 35814, "s": 35803, "text": "Safari 9.0" }, { "code": null, "e": 35825, "s": 35814, "text": "Opera 23.0" }, { "code": null, "e": 35839, "s": 35825, "text": "shubham_singh" }, { "code": null, "e": 35854, "s": 35839, "text": "CSS-Properties" }, { "code": null, "e": 35861, "s": 35854, "text": "Picked" }, { "code": null, "e": 35865, "s": 35861, "text": "CSS" }, { "code": null, "e": 35882, "s": 35865, "text": "Web Technologies" }, { "code": null, "e": 35980, "s": 35882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35989, "s": 35980, "text": "Comments" }, { "code": null, "e": 36002, "s": 35989, "text": "Old Comments" }, { "code": null, "e": 36039, "s": 36002, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 36068, "s": 36039, "text": "Form validation using jQuery" }, { "code": null, "e": 36107, "s": 36068, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 36149, "s": 36107, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 36184, "s": 36149, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 36240, "s": 36184, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 36273, "s": 36240, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36316, "s": 36273, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36377, "s": 36316, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to Install and Configure MS SQL (Beta) on CentOS 7
In this article, we will learn about – How to install and configure MS SQL on CentOS 7. Microsoft has recently announced that they are planning to release the MS SQL for Linux. Specially the beta versions for RedHat enterprises Linux, Centos & Ubuntu but only with 64-bit editions. A machine with a minimum of 4 GB RAM and 30 GB Hard disk space. A machine installed with CentOS 7. A user with root privileges or root user. Since MS SQL is not available with the default CentOS repository, we needed to add the MS SSQL repository details to the local yum repository. To install the MS SQL Server using the command line, we needed to add the repository to the local yum repo. # curl https://packages.microsoft.com/config/rhel/7/mssql-server.repo > /etc/yum.repos.d/mssql-server.repo % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 220 100 220 0 0 257 0 --:--:-- --:--:-- --:--:-- 257 Once the repository is updated, we will run the below command to install the MS-SQL server # yum update # yum install -y mssql-server ... ... Resolving Dependencies --> Running transaction check ---> Package mssql-server.x86_64 0:14.0.1.246-6 will be installed --> Processing Dependency: bzip2 for package: mssql-server-14.0.1.246-6.x86_64 --> Processing Dependency: gdb for package: mssql-server-14.0.1.246-6.x86_64 --> Running transaction check ---> Package bzip2.x86_64 0:1.0.6-13.el7 will be installed ---> Package gdb.x86_64 0:7.6.1-80.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: mssql-server x86_64 14.0.1.246-6 packages-microsoft-com-mssql-server 138 M Installing for dependencies: bzip2 x86_64 1.0.6-13.el7 base 52 k gdb x86_64 7.6.1-80.el7 base 2.4 M Transaction Summary ================================================================================ Install 1 Package (+2 Dependent packages) ... ... +-------------------------------------------------------------------+ | Please run /opt/mssql/bin/sqlservr-setup to complete the setup of | | Microsoft(R) SQL Server(R). | +-------------------------------------------------------------------+ Verifying : mssql-server-14.0.1.246-6.x86_64 1/3 Verifying : gdb-7.6.1-80.el7.x86_64 2/3 Verifying : bzip2-1.0.6-13.el7.x86_64 3/3 Installed: mssql-server.x86_64 0:14.0.1.246-6 Dependency Installed: bzip2.x86_64 0:1.0.6-13.el7 gdb.x86_64 0:7.6.1-80.el7 Complete! Once the installation is completed, we will run sqlservr-setup script to setup password of the SA; we needed to give a strong password for the SA account (with a min of 8 characters, lower and upper case letters with numbers from 1 to 10 or any non-alpha numeric characters) # sudo /opt/mssql/bin/sqlservr-setup Microsoft(R) SQL Server(R) Setup You can abort setup at any time by pressing Ctrl-C. Start this program with the --help option for information about running it in unattended mode. Please enter a password for the system administrator (SA) account: Please confirm the password for the system administrator (SA) account: Setting a password for the system administrator (SA) account Do you wish to start the SQL Server service now? [y/n]: Y Do you wish to enable SQL Server to start on boot? [y/n]: y Created symlink from /etc/systemd/system/multi-user.target.wants/mssql-server.service to /usr/lib/systemd/system/mssql-server.service. Created symlink from /etc/systemd/system/multi-user.target.wants/mssql-server-telemetry.service to /usr/lib/systemd/system/mssql-server-telemetry.service. Setup completed successfully. Once the configuration is done, we will restart the MS SQL services and will see the status of the services with the below command – To restart the services # systemctl start mssql-server See the status of the services # systemctl status mssql-server mssql-server.service - Microsoft(R) SQL Server(R) Database EngineLoaded: loaded (/usr/lib/systemd/system/mssql-server.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2016-12-02 15:52:33 IST; 5min ago Main PID: 2299 (sqlservr) CGroup: /system.slice/mssql-server.service ├─2299 /opt/mssql/bin/sqlservr └─2307 /opt/mssql/bin/sqlservr Dec 02 15:52:37 localhost.localdomain sqlservr[2299]: 2016-12-02 10:22:37.31 spid17s.... Dec 02 15:52:37 localhost.localdomain systemd[1]: [/usr/lib/systemd/system/mssql-ser...' Dec 02 15:52:37 localhost.localdomain sqlservr[2299]: 2016-12-02 10:22:37.53 spid6s .... .. .. Dec 02 15:57:40 localhost.localdomain sqlservr[2299]: 2016-12-02 10:27:40.21 spid51 ...' Dec 02 15:57:43 localhost.localdomain systemd[1]: Started Microsoft(R) SQL Server(R)....Hint: Some lines were eclipsed, use -l to show in full. We needed to open the firewall settings so that MS SQL can be accessed, below is the command to open the firewalls # sudo firewall-cmd --zone=public --add-port=1433/tcp --permanent # sudo firewall-cmd –reload We needed to download the Microsoft repository. # curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/msprod.repo % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 193 100 193 0 0 213 0 --:--:-- --:--:-- --:--:-- 213 Once the repository is installed on the local machine, we can use the below command to install the MS SQL tools with the below command – # yum install mssql-tools Loaded plugins: fastestmirror packages-microsoft-com-prod | 2.9 kB 00:00:00 packages-microsoft-com-prod/primary_db | 4.6 kB 00:00:00 Loading mirror speeds from cached hostfile * base: mirrors.digipower.vn * extras: mirror.digistar.vn * updates: mirror.digistar.vn Resolving Dependencies ======================================================================================== Package Arch Version Repository Size ======================================================================================== Installing: mssql-tools x86_64 14.0.1.246-1 packages-microsoft-com-prod 249 k Installing for dependencies: libtool-ltdl x86_64 2.4.2-21.el7_2 updates 49 k msodbcsql x86_64 13.0.1.0-1 packages-microsoft-com-prod 3.8 M unixODBC-utf16 x86_64 2.3.1-1 packages-microsoft-com-prod 329 k Transaction Summary ======================================================================================== Install 1 Package (+3 Dependent packages) Total download size: 4.5 M Installed size: 4.5 M Is this ok [y/d/N]: ^CN Exiting on user command Your transaction was saved, rerun it with: yum load-transaction /tmp/yum_save_tx.2016-12-02.17-18.RpEVqg.yumtx Do you accept the license terms? (Enter YES or NO)YES Installing : msodbcsql-13.0.1.0-1.x86_64 3/4 The license terms for this product can be downloaded from http://go.microsoft.com/fwlink/?LinkId=746949 and found in /usr/share/doc/mssql-tools/LICENSE.txt . By entering 'YES,' you indicate that you accept the license terms. Do you accept the license terms? (Enter YES or NO)YES Dependency Installed: libtool-ltdl.x86_64 0:2.4.2-21.el7_2 msodbcsql.x86_64 0:13.0.1.0-1 unixODBC-utf16.x86_64 0:2.3.1-1 Complete! Once the tools are installed on the machine, we will test the below commands and general syntax to connect to the MS SQL server. Syntax # sqlcmd –S IP-ADDRESS –U SA –P ‘<YOUR SYSTEM PASSWORD’ # sqlcmd sqlcmd -S localhost -U SA -P Test@1234 1>CREATE DATABASE TEST1; 2>GO; 3>quit In the above article, we have learnt – How to install MS SQL Server, MS SQL command line tools to connect to the server. Also we have learnt – How to change or setup the SA account password for the MS SQL.
[ { "code": null, "e": 1344, "s": 1062, "text": "In this article, we will learn about – How to install and configure MS SQL on CentOS 7. Microsoft has recently announced that they are planning to release the MS SQL for Linux. Specially the beta versions for RedHat enterprises Linux, Centos & Ubuntu but only with 64-bit editions." }, { "code": null, "e": 1408, "s": 1344, "text": "A machine with a minimum of 4 GB RAM and 30 GB Hard disk space." }, { "code": null, "e": 1443, "s": 1408, "text": "A machine installed with CentOS 7." }, { "code": null, "e": 1485, "s": 1443, "text": "A user with root privileges or root user." }, { "code": null, "e": 1628, "s": 1485, "text": "Since MS SQL is not available with the default CentOS repository, we needed to add the MS SSQL repository details to the local yum repository." }, { "code": null, "e": 1736, "s": 1628, "text": "To install the MS SQL Server using the command line, we needed to add the repository to the local yum repo." }, { "code": null, "e": 2000, "s": 1736, "text": "# curl https://packages.microsoft.com/config/rhel/7/mssql-server.repo > /etc/yum.repos.d/mssql-server.repo\n% Total % Received % Xferd Average Speed Time Time Time Current\nDload Upload Total Spent Left Speed\n100 220 100 220 0 0 257 0 --:--:-- --:--:-- --:--:-- 257" }, { "code": null, "e": 2091, "s": 2000, "text": "Once the repository is updated, we will run the below command to install the MS-SQL server" }, { "code": null, "e": 3662, "s": 2091, "text": "# yum update\n# yum install -y mssql-server\n...\n...\nResolving Dependencies\n--> Running transaction check\n---> Package mssql-server.x86_64 0:14.0.1.246-6 will be installed\n--> Processing Dependency: bzip2 for package: mssql-server-14.0.1.246-6.x86_64\n--> Processing Dependency: gdb for package: mssql-server-14.0.1.246-6.x86_64\n--> Running transaction check\n---> Package bzip2.x86_64 0:1.0.6-13.el7 will be installed\n---> Package gdb.x86_64 0:7.6.1-80.el7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n================================================================================\nPackage Arch Version Repository Size\n================================================================================\nInstalling:\nmssql-server x86_64 14.0.1.246-6 packages-microsoft-com-mssql-server 138 M\nInstalling for dependencies:\nbzip2 x86_64 1.0.6-13.el7 base 52 k\ngdb x86_64 7.6.1-80.el7 base 2.4 M\nTransaction Summary\n================================================================================\nInstall 1 Package (+2 Dependent packages)\n...\n...\n+-------------------------------------------------------------------+\n| Please run /opt/mssql/bin/sqlservr-setup to complete the setup of |\n| Microsoft(R) SQL Server(R). |\n+-------------------------------------------------------------------+\nVerifying : mssql-server-14.0.1.246-6.x86_64 1/3\nVerifying : gdb-7.6.1-80.el7.x86_64 2/3\nVerifying : bzip2-1.0.6-13.el7.x86_64 3/3\nInstalled:\nmssql-server.x86_64 0:14.0.1.246-6\nDependency Installed:\nbzip2.x86_64 0:1.0.6-13.el7 gdb.x86_64 0:7.6.1-80.el7\nComplete!" }, { "code": null, "e": 3937, "s": 3662, "text": "Once the installation is completed, we will run sqlservr-setup script to setup password of the SA; we needed to give a strong password for the SA account (with a min of 8 characters, lower and upper case letters with numbers from 1 to 10 or any non-alpha numeric characters)" }, { "code": null, "e": 4791, "s": 3937, "text": "# sudo /opt/mssql/bin/sqlservr-setup\nMicrosoft(R) SQL Server(R) Setup\nYou can abort setup at any time by pressing Ctrl-C. Start this program\nwith the --help option for information about running it in unattended\nmode.\nPlease enter a password for the system administrator (SA) account:\nPlease confirm the password for the system administrator (SA) account:\nSetting a password for the system administrator (SA) account\nDo you wish to start the SQL Server service now? [y/n]: Y\nDo you wish to enable SQL Server to start on boot? [y/n]: y\nCreated symlink from /etc/systemd/system/multi-user.target.wants/mssql-server.service to /usr/lib/systemd/system/mssql-server.service.\nCreated symlink from /etc/systemd/system/multi-user.target.wants/mssql-server-telemetry.service to /usr/lib/systemd/system/mssql-server-telemetry.service.\nSetup completed successfully." }, { "code": null, "e": 4924, "s": 4791, "text": "Once the configuration is done, we will restart the MS SQL services and will see the status of the services with the below command –" }, { "code": null, "e": 4948, "s": 4924, "text": "To restart the services" }, { "code": null, "e": 4979, "s": 4948, "text": "# systemctl start mssql-server" }, { "code": null, "e": 5010, "s": 4979, "text": "See the status of the services" }, { "code": null, "e": 5909, "s": 5010, "text": "# systemctl status mssql-server\nmssql-server.service - Microsoft(R) SQL Server(R) Database EngineLoaded: loaded (/usr/lib/systemd/system/mssql-server.service; enabled; vendor preset: disabled)\nActive: active (running) since Fri 2016-12-02 15:52:33 IST; 5min ago\nMain PID: 2299 (sqlservr)\nCGroup: /system.slice/mssql-server.service\n├─2299 /opt/mssql/bin/sqlservr\n└─2307 /opt/mssql/bin/sqlservr\nDec 02 15:52:37 localhost.localdomain sqlservr[2299]: 2016-12-02 10:22:37.31 spid17s....\nDec 02 15:52:37 localhost.localdomain systemd[1]: [/usr/lib/systemd/system/mssql-ser...'\nDec 02 15:52:37 localhost.localdomain sqlservr[2299]: 2016-12-02 10:22:37.53 spid6s ....\n..\n..\nDec 02 15:57:40 localhost.localdomain sqlservr[2299]: 2016-12-02 10:27:40.21 spid51 ...'\nDec 02 15:57:43 localhost.localdomain systemd[1]: Started Microsoft(R) SQL Server(R)....Hint: Some lines were eclipsed, use -l to show in full." }, { "code": null, "e": 6024, "s": 5909, "text": "We needed to open the firewall settings so that MS SQL can be accessed, below is the command to open the firewalls" }, { "code": null, "e": 6118, "s": 6024, "text": "# sudo firewall-cmd --zone=public --add-port=1433/tcp --permanent\n# sudo firewall-cmd –reload" }, { "code": null, "e": 6166, "s": 6118, "text": "We needed to download the Microsoft repository." }, { "code": null, "e": 6461, "s": 6166, "text": "# curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/msprod.repo\n% Total % Received % Xferd Average Speed Time Time Time Current\nDload Upload Total Spent Left Speed\n0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\n100 193 100 193 0 0 213 0 --:--:-- --:--:-- --:--:-- 213" }, { "code": null, "e": 6598, "s": 6461, "text": "Once the repository is installed on the local machine, we can use the below command to install the MS SQL tools with the below command –" }, { "code": null, "e": 8275, "s": 6598, "text": "# yum install mssql-tools\nLoaded plugins: fastestmirror\npackages-microsoft-com-prod | 2.9 kB 00:00:00\npackages-microsoft-com-prod/primary_db | 4.6 kB 00:00:00\nLoading mirror speeds from cached hostfile\n* base: mirrors.digipower.vn\n* extras: mirror.digistar.vn\n* updates: mirror.digistar.vn\nResolving Dependencies\n========================================================================================\nPackage Arch Version Repository Size\n========================================================================================\nInstalling:\nmssql-tools x86_64 14.0.1.246-1 packages-microsoft-com-prod 249 k\nInstalling for dependencies:\nlibtool-ltdl x86_64 2.4.2-21.el7_2 updates 49 k\nmsodbcsql x86_64 13.0.1.0-1 packages-microsoft-com-prod 3.8 M\nunixODBC-utf16 x86_64 2.3.1-1 packages-microsoft-com-prod 329 k\nTransaction Summary\n========================================================================================\nInstall 1 Package (+3 Dependent packages)\nTotal download size: 4.5 M\nInstalled size: 4.5 M\nIs this ok [y/d/N]: ^CN\nExiting on user command\nYour transaction was saved, rerun it with:\nyum load-transaction /tmp/yum_save_tx.2016-12-02.17-18.RpEVqg.yumtx\nDo you accept the license terms? (Enter YES or NO)YES\nInstalling : msodbcsql-13.0.1.0-1.x86_64 3/4\nThe license terms for this product can be downloaded from\nhttp://go.microsoft.com/fwlink/?LinkId=746949 and found in\n/usr/share/doc/mssql-tools/LICENSE.txt . By entering 'YES,'\nyou indicate that you accept the license terms.\nDo you accept the license terms? (Enter YES or NO)YES\nDependency Installed:\nlibtool-ltdl.x86_64 0:2.4.2-21.el7_2 msodbcsql.x86_64 0:13.0.1.0-1\nunixODBC-utf16.x86_64 0:2.3.1-1\nComplete!" }, { "code": null, "e": 8404, "s": 8275, "text": "Once the tools are installed on the machine, we will test the below commands and general syntax to connect to the MS SQL server." }, { "code": null, "e": 8411, "s": 8404, "text": "Syntax" }, { "code": null, "e": 8553, "s": 8411, "text": "# sqlcmd –S IP-ADDRESS –U SA –P ‘<YOUR SYSTEM PASSWORD’\n# sqlcmd sqlcmd -S localhost -U SA -P Test@1234\n1>CREATE DATABASE TEST1;\n2>GO;\n3>quit" }, { "code": null, "e": 8759, "s": 8553, "text": "In the above article, we have learnt – How to install MS SQL Server, MS SQL command line tools to connect to the server. Also we have learnt – How to change or setup the SA account password for the MS SQL." } ]
How to replace only the first repeated value in a string in MySQL
For this, you can use REGEXP_REPLACE(). Let’s say our string is − This is my first MySQL query. This is the first tutorial. I am learning for the first time. We need to replace only the 1st occurrence of a specific word, let’s say “first”. The output should be − This is my second MySQL query. This is the first tutorial. I am learning for the first time. Let us create a table − mysql> create table demo26 −> ( −> value text −> ); Query OK, 0 rows affected (2.04 sec) Insert some records into the table with the help of insert command − mysql> insert into demo26 values('This is my first MySQL query. This is the first tutorial. I am learning for the first time.'); Query OK, 1 row affected (0.10 sec) Display records from the table using select statement − mysql> select *from demo26; This will produce the following output − +---------------------------------------------------------------------------------------------+ | value | +---------------------------------------------------------------------------------------------+ | This is my first MySQL query. This is the first tutorial. I am learning for the first time. | +---------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) Following is the query to replace only 1st occurrence − mysql> update demo26 −> set value = REGEXP_REPLACE(value, 'first', 'second', 1, 1 ) ; Query OK, 1 row affected (0.19 sec) Rows matched: 1 Changed: 1 Warnings: 0 Display records from the table using select statement − mysql> select *from demo26; This will produce the following output − +----------------------------------------------------------------------------------------------+ | value | +----------------------------------------------------------------------------------------------+ | This is my second MySQL query. This is the first tutorial. I am learning for the first time. | +----------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1128, "s": 1062, "text": "For this, you can use REGEXP_REPLACE(). Let’s say our string is −" }, { "code": null, "e": 1220, "s": 1128, "text": "This is my first MySQL query. This is the first tutorial. I am learning for the first time." }, { "code": null, "e": 1325, "s": 1220, "text": "We need to replace only the 1st occurrence of a specific word, let’s say “first”. The output should be −" }, { "code": null, "e": 1418, "s": 1325, "text": "This is my second MySQL query. This is the first tutorial. I am learning for the first time." }, { "code": null, "e": 1442, "s": 1418, "text": "Let us create a table −" }, { "code": null, "e": 1531, "s": 1442, "text": "mysql> create table demo26\n−> (\n−> value text\n−> );\nQuery OK, 0 rows affected (2.04 sec)" }, { "code": null, "e": 1600, "s": 1531, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 1765, "s": 1600, "text": "mysql> insert into demo26 values('This is my first MySQL query. This is the first tutorial. I am learning for the first time.');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1821, "s": 1765, "text": "Display records from the table using select statement −" }, { "code": null, "e": 1849, "s": 1821, "text": "mysql> select *from demo26;" }, { "code": null, "e": 1890, "s": 1849, "text": "This will produce the following output −" }, { "code": null, "e": 2394, "s": 1890, "text": "+---------------------------------------------------------------------------------------------+\n| value |\n+---------------------------------------------------------------------------------------------+\n| This is my first MySQL query. This is the first tutorial. I am learning for the first time. |\n+---------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2450, "s": 2394, "text": "Following is the query to replace only 1st occurrence −" }, { "code": null, "e": 2611, "s": 2450, "text": "mysql> update demo26\n−> set value = REGEXP_REPLACE(value, 'first', 'second', 1, 1 ) ;\nQuery OK, 1 row affected (0.19 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2667, "s": 2611, "text": "Display records from the table using select statement −" }, { "code": null, "e": 2695, "s": 2667, "text": "mysql> select *from demo26;" }, { "code": null, "e": 2736, "s": 2695, "text": "This will produce the following output −" }, { "code": null, "e": 3245, "s": 2736, "text": "+----------------------------------------------------------------------------------------------+\n| value |\n+----------------------------------------------------------------------------------------------+\n| This is my second MySQL query. This is the first tutorial. I am learning for the first time. |\n+----------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" } ]
Python | Multiply 2d numpy array corresponding to 1d array - GeeksforGeeks
15 Mar, 2019 Given a two numpy arrays, the task is to multiply 2d numpy array with 1d numpy array each row corresponding to one element in numpy. Let’s discuss a few methods for a given task. Method #1: Using np.newaxis() # Python code to demonstrate# multiplication of 2d array# with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])ini_array2 = np.array([0, 2, 3]) # printing initial arraysprint("initial array", str(ini_array1)) # Multiplying arraysresult = ini_array1 * ini_array2[:, np.newaxis] # printing resultprint("New resulting array: ", result) initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]] Method #2: Using axis as none # Python code to demonstrate# multiplication of 2d array# with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])ini_array2 = np.array([0, 2, 3]) # printing initial arraysprint("initial array", str(ini_array1)) # Multiplying arraysresult = ini_array1 * ini_array2[:, None] # printing resultprint("New resulting array: ", result) initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]] Method #3: Using transpose() # python code to demonstrate# multiplication of 2d array# with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])ini_array2 = np.array([0, 2, 3]) # printing initial arraysprint("initial array", str(ini_array1)) # Multiplying arraysresult = (ini_array1.T * ini_array2).T # printing resultprint("New resulting array: ", result) initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[ 0 0 0] [ 4 8 10] [ 3 6 9]] Python numpy-program Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n15 Mar, 2019" }, { "code": null, "e": 24471, "s": 24292, "text": "Given a two numpy arrays, the task is to multiply 2d numpy array with 1d numpy array each row corresponding to one element in numpy. Let’s discuss a few methods for a given task." }, { "code": null, "e": 24501, "s": 24471, "text": "Method #1: Using np.newaxis()" }, { "code": "# Python code to demonstrate# multiplication of 2d array# with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])ini_array2 = np.array([0, 2, 3]) # printing initial arraysprint(\"initial array\", str(ini_array1)) # Multiplying arraysresult = ini_array1 * ini_array2[:, np.newaxis] # printing resultprint(\"New resulting array: \", result)", "e": 24875, "s": 24501, "text": null }, { "code": null, "e": 24977, "s": 24875, "text": "initial array [[1 2 3]\n [2 4 5]\n [1 2 3]]\nNew resulting array: [[ 0 0 0]\n [ 4 8 10]\n [ 3 6 9]]\n" }, { "code": null, "e": 25008, "s": 24977, "text": " Method #2: Using axis as none" }, { "code": "# Python code to demonstrate# multiplication of 2d array# with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])ini_array2 = np.array([0, 2, 3]) # printing initial arraysprint(\"initial array\", str(ini_array1)) # Multiplying arraysresult = ini_array1 * ini_array2[:, None] # printing resultprint(\"New resulting array: \", result)", "e": 25376, "s": 25008, "text": null }, { "code": null, "e": 25478, "s": 25376, "text": "initial array [[1 2 3]\n [2 4 5]\n [1 2 3]]\nNew resulting array: [[ 0 0 0]\n [ 4 8 10]\n [ 3 6 9]]\n" }, { "code": null, "e": 25508, "s": 25478, "text": " Method #3: Using transpose()" }, { "code": "# python code to demonstrate# multiplication of 2d array# with 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])ini_array2 = np.array([0, 2, 3]) # printing initial arraysprint(\"initial array\", str(ini_array1)) # Multiplying arraysresult = (ini_array1.T * ini_array2).T # printing resultprint(\"New resulting array: \", result)", "e": 25873, "s": 25508, "text": null }, { "code": null, "e": 25975, "s": 25873, "text": "initial array [[1 2 3]\n [2 4 5]\n [1 2 3]]\nNew resulting array: [[ 0 0 0]\n [ 4 8 10]\n [ 3 6 9]]\n" }, { "code": null, "e": 25996, "s": 25975, "text": "Python numpy-program" }, { "code": null, "e": 26009, "s": 25996, "text": "Python-numpy" }, { "code": null, "e": 26016, "s": 26009, "text": "Python" }, { "code": null, "e": 26114, "s": 26016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26146, "s": 26114, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26202, "s": 26146, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26244, "s": 26202, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26286, "s": 26244, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26308, "s": 26286, "text": "Defaultdict in Python" }, { "code": null, "e": 26347, "s": 26308, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26378, "s": 26347, "text": "Python | os.path.join() method" }, { "code": null, "e": 26433, "s": 26378, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26462, "s": 26433, "text": "Create a directory in Python" } ]
How to call the constructor of a superclass from a constructor in java?
Whenever you inherit/extend a class, a copy of superclass’s members is created in the subclass object and thus, using the subclass object you can access the members of both classes. In the following example we have a class named SuperClass with a method with name demo(). We are extending this class with another class (SubClass). Now, you create an object of the subclass and call the method demo(). class SuperClass{ public void demo() { System.out.println("demo method"); } } public class SubClass extends SuperClass { public static void main(String args[]) { SubClass obj = new SubClass(); obj.demo(); } } demo method In inheritance constructors are not inherited. You need to call them explicitly using the super keyword. If a Super class have parameterized constructor. You need to accept these parameters in the sub class’s constructor and within it, you need to invoke the super class’s constructor using “super()” as − public Student(String name, int age, String branch, int Student_id){ super(name, age); this.branch = branch; this.Student_id = Student_id; } Following java program demonstrates how to call a super class’s constructor from the constructor of the sub class using the super keyword. class Person{ public String name; public int age; public Person(String name, int age){ this.name = name; this.age = age; } public void displayPerson() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); } } public class Student extends Person { public String branch; public int Student_id; public Student(String name, int age, String branch, int Student_id){ super(name, age); this.branch = branch; this.Student_id = Student_id; } public void displayStudent() { System.out.println("Data of the Student class: "); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Branch: "+this.branch); System.out.println("Student ID: "+this.Student_id); } public static void main(String[] args) throws CloneNotSupportedException { Person person = new Student("Krishna", 20, "IT", 1256); person.displayPerson(); } } Data of the Person class: Name: Krishna Age: 20
[ { "code": null, "e": 1244, "s": 1062, "text": "Whenever you inherit/extend a class, a copy of superclass’s members is created in the subclass object and thus, using the subclass object you can access the members of both classes." }, { "code": null, "e": 1393, "s": 1244, "text": "In the following example we have a class named SuperClass with a method with name demo(). We are extending this class with another class (SubClass)." }, { "code": null, "e": 1463, "s": 1393, "text": "Now, you create an object of the subclass and call the method demo()." }, { "code": null, "e": 1702, "s": 1463, "text": "class SuperClass{\n public void demo() {\n System.out.println(\"demo method\");\n }\n}\npublic class SubClass extends SuperClass {\n public static void main(String args[]) {\n SubClass obj = new SubClass();\n obj.demo();\n }\n}" }, { "code": null, "e": 1714, "s": 1702, "text": "demo method" }, { "code": null, "e": 1819, "s": 1714, "text": "In inheritance constructors are not inherited. You need to call them explicitly using the super keyword." }, { "code": null, "e": 2020, "s": 1819, "text": "If a Super class have parameterized constructor. You need to accept these parameters in the sub class’s constructor and within it, you need to invoke the super class’s constructor using “super()” as −" }, { "code": null, "e": 2170, "s": 2020, "text": "public Student(String name, int age, String branch, int Student_id){\n super(name, age);\n this.branch = branch;\n this.Student_id = Student_id;\n}" }, { "code": null, "e": 2309, "s": 2170, "text": "Following java program demonstrates how to call a super class’s constructor from the constructor of the sub class using the super keyword." }, { "code": null, "e": 3367, "s": 2309, "text": "class Person{\n public String name;\n public int age;\n public Person(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayPerson() {\n System.out.println(\"Data of the Person class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n }\n}\npublic class Student extends Person {\n public String branch;\n public int Student_id;\n public Student(String name, int age, String branch, int Student_id){\n super(name, age);\n this.branch = branch;\n this.Student_id = Student_id;\n }\n public void displayStudent() {\n System.out.println(\"Data of the Student class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Branch: \"+this.branch);\n System.out.println(\"Student ID: \"+this.Student_id);\n }\n public static void main(String[] args) throws CloneNotSupportedException {\n Person person = new Student(\"Krishna\", 20, \"IT\", 1256);\n person.displayPerson();\n }\n}" }, { "code": null, "e": 3415, "s": 3367, "text": "Data of the Person class:\nName: Krishna\nAge: 20" } ]
GATE | GATE CS 2010 | Question 6 - GeeksforGeeks
19 Oct, 2020 The minterm expansion of f(P, Q, R) = PQ + QR’ + PR’ is(A) m2 + m4 + m6 + m7(B) m0 + m1 + m3 + m5(C) m0 + m1 + m6 + m7(D) m2 + m3 + m4 + m5Answer: (A)Explanation: K-map, = PQ + QR’ + PR’ = PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’ = PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’ = PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4) = m2 + m4 + m6 + m7 Option (A) is correct.Quiz of this Question madarsh986 GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-2) | Question 65
[ { "code": null, "e": 24413, "s": 24385, "text": "\n19 Oct, 2020" }, { "code": null, "e": 24583, "s": 24413, "text": "The minterm expansion of f(P, Q, R) = PQ + QR’ + PR’ is(A) m2 + m4 + m6 + m7(B) m0 + m1 + m3 + m5(C) m0 + m1 + m6 + m7(D) m2 + m3 + m4 + m5Answer: (A)Explanation: K-map," }, { "code": null, "e": 24742, "s": 24583, "text": "= PQ + QR’ + PR’ \n= PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’\n= PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’ \n= PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4) \n= m2 + m4 + m6 + m7 " }, { "code": null, "e": 24786, "s": 24742, "text": "Option (A) is correct.Quiz of this Question" }, { "code": null, "e": 24797, "s": 24786, "text": "madarsh986" }, { "code": null, "e": 24810, "s": 24797, "text": "GATE-CS-2010" }, { "code": null, "e": 24828, "s": 24810, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 24833, "s": 24828, "text": "GATE" }, { "code": null, "e": 24931, "s": 24833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24940, "s": 24931, "text": "Comments" }, { "code": null, "e": 24953, "s": 24940, "text": "Old Comments" }, { "code": null, "e": 24987, "s": 24953, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25020, "s": 24987, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25062, "s": 25020, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25104, "s": 25062, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25146, "s": 25104, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25180, "s": 25146, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25222, "s": 25180, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25256, "s": 25222, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25298, "s": 25256, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" } ]
Multithreading in C
Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris. The following routine is used to create a POSIX thread − #include <pthread.h> pthread_create (thread, attr, start_routine, arg) Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters. The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads. There is following routine which we use to terminate a POSIX thread – #include <pthread.h> pthread_exit (status) Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist. If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes. #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; printf("Hello World! Thread ID, %d\n", tid); pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i); if (rc) { printf("Error:unable to create thread, %d\n", rc); exit(-1); } } pthread_exit(NULL); } $gcc test.cpp -lpthread $./a.out main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Hello World! Thread ID, 0 Hello World! Thread ID, 1 Hello World! Thread ID, 2 Hello World! Thread ID, 3 Hello World! Thread ID, 4
[ { "code": null, "e": 1298, "s": 1062, "text": "Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based." }, { "code": null, "e": 1464, "s": 1298, "text": "Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program." }, { "code": null, "e": 1644, "s": 1464, "text": "A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution." }, { "code": null, "e": 1795, "s": 1644, "text": "C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature." }, { "code": null, "e": 2064, "s": 1795, "text": "This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris." }, { "code": null, "e": 2121, "s": 2064, "text": "The following routine is used to create a POSIX thread −" }, { "code": null, "e": 2192, "s": 2121, "text": "#include <pthread.h>\npthread_create (thread, attr, start_routine, arg)" }, { "code": null, "e": 2381, "s": 2192, "text": "Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters." }, { "code": null, "e": 2597, "s": 2381, "text": "The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads." }, { "code": null, "e": 2667, "s": 2597, "text": "There is following routine which we use to terminate a POSIX thread –" }, { "code": null, "e": 2710, "s": 2667, "text": "#include <pthread.h>\npthread_exit (status)" }, { "code": null, "e": 2887, "s": 2710, "text": "Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist." }, { "code": null, "e": 3087, "s": 2887, "text": "If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes." }, { "code": null, "e": 3705, "s": 3087, "text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\nusing namespace std;\n#define NUM_THREADS 5\nvoid *PrintHello(void *threadid) {\n long tid;\n tid = (long)threadid;\n printf(\"Hello World! Thread ID, %d\\n\", tid);\n pthread_exit(NULL);\n}\nint main () {\n pthread_t threads[NUM_THREADS];\n int rc;\n int i;\n for( i = 0; i < NUM_THREADS; i++ ) {\n cout << \"main() : creating thread, \" << i << endl;\n rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);\n if (rc) {\n printf(\"Error:unable to create thread, %d\\n\", rc);\n exit(-1);\n }\n }\n pthread_exit(NULL);\n}" }, { "code": null, "e": 4008, "s": 3705, "text": "$gcc test.cpp -lpthread\n$./a.out\nmain() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nHello World! Thread ID, 0\nHello World! Thread ID, 1\nHello World! Thread ID, 2\nHello World! Thread ID, 3\nHello World! Thread ID, 4" } ]
Building MobileNet from Scratch Using TensorFlow | by Arjun Sarkar | Towards Data Science
Previously I have discussed the architecture of MobileNet and its most important layer “Depthwise Separable Convolutions” in the story — Understanding Depthwise Separable Convolutions and the efficiency of MobileNets. Next, we will see how to implement this architecture from scratch using TensorFlow. Figure 2 shows the MobileNet architecture that we will implement in code. The network starts with Vonv, BatchNorm, ReLU block, and follows multiple MobileNet blocks from thereon. It finally ends with an Average Pooling and a Fully connected layer, with a Softmax activation. We see the architecture has the pattern — Conv dw/s1, followed by Conv/s1, and so on. Here dw is the depthwise layer with the number of strides, followed by the Conv layer with the number of strides. These two lines are the MobileNet block. The ‘Filter Shape’ column gives the details about the kernel size and the number of filters to be used. The last number of the column gives the number of filters. We see the filter number gradually increase from 32 to 64, 64 to 128, 128 to 256, and so on. The last column shows how the size of the image changes as we go deeper into the network. The input size is chosen as 224*224 pixels, with 3 channels and the output layer classifies 1000 classes. Few things to keep in mind while constructing the network: All layers are followed by a Batch Normalization and a ReLU nonlinearity.Unlike normal CNN models which have a Conv2D layer, MobileNet’s have Depthwise Conv layers, as seen in Figure 3. To understand this layer better please refer to — Depthwise Convolutional Blocks. All layers are followed by a Batch Normalization and a ReLU nonlinearity. Unlike normal CNN models which have a Conv2D layer, MobileNet’s have Depthwise Conv layers, as seen in Figure 3. To understand this layer better please refer to — Depthwise Convolutional Blocks. Import all the necessary layers from the TensorFlow libraryWriting a helper function for the MobileNet blockBuilding the stem of the modelUse the helper function to build the main part of the model Import all the necessary layers from the TensorFlow library Writing a helper function for the MobileNet block Building the stem of the model Use the helper function to build the main part of the model Importing the layers import tensorflow as tf#import all necessary layersfrom tensorflow.keras.layers import Input, DepthwiseConv2Dfrom tensorflow.keras.layers import Conv2D, BatchNormalizationfrom tensorflow.keras.layers import ReLU, AvgPool2D, Flatten, Densefrom tensorflow.keras import Model Keras has a DepthwiseConv layer already built-in, so we do not need to create it from scratch. MobileNet block For creating the function for the MobileNet block, we need the following steps: Input to the function: Input to the function: a. A tensor (x) b. the number of filters for the convolutional layer (filters) c. the strides for the Depthwise convolutional layer (strides) 2. Run (Figure 3 — right side image): a. applying a 3x3 Dethwise convolutional layer with strides followed by a Batch Normalization layer and a ReLU activation b. Applying a 1x1 Convolutional layer with filters followed by a batch normalization layer and a ReLU activation 3. Return the tensor (output) These 3 steps are implemented in the code blocks below. # MobileNet blockdef mobilnet_block (x, filters, strides): x = DepthwiseConv2D(kernel_size = 3, strides = strides, padding = 'same')(x) x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters = filters, kernel_size = 1, strides = 1)(x) x = BatchNormalization()(x) x = ReLU()(x) return x Building the stem of the Model As seen in Figure 2, the first layer is Conv/s2 with filter shape 3x3x3x32. #stem of the modelinput = Input(shape = (224,224,3))x = Conv2D(filters = 32, kernel_size = 3, strides = 2, padding = 'same')(input)x = BatchNormalization()(x)x = ReLU()(x) The main part of the Model # main part of the modelx = mobilnet_block(x, filters = 64, strides = 1)x = mobilnet_block(x, filters = 128, strides = 2)x = mobilnet_block(x, filters = 128, strides = 1)x = mobilnet_block(x, filters = 256, strides = 2)x = mobilnet_block(x, filters = 256, strides = 1)x = mobilnet_block(x, filters = 512, strides = 2)for _ in range (5): x = mobilnet_block(x, filters = 512, strides = 1)x = mobilnet_block(x, filters = 1024, strides = 2)x = mobilnet_block(x, filters = 1024, strides = 1)x = AvgPool2D (pool_size = 7, strides = 1, data_format='channels_first')(x)output = Dense (units = 1000, activation = 'softmax')(x)model = Model(inputs=input, outputs=output)model.summary() Plotting the Model #plot the modeltf.keras.utils.plot_model(model, to_file='model.png', show_shapes=True, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96) import tensorflow as tf#import all necessary layersfrom tensorflow.keras.layers import Input, DepthwiseConv2Dfrom tensorflow.keras.layers import Conv2D, BatchNormalizationfrom tensorflow.keras.layers import ReLU, AvgPool2D, Flatten, Densefrom tensorflow.keras import Model# MobileNet blockdef mobilnet_block (x, filters, strides): x = DepthwiseConv2D(kernel_size = 3, strides = strides, padding = 'same')(x) x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters = filters, kernel_size = 1, strides = 1)(x) x = BatchNormalization()(x) x = ReLU()(x) return x#stem of the modelinput = Input(shape = (224,224,3))x = Conv2D(filters = 32, kernel_size = 3, strides = 2, padding = 'same')(input)x = BatchNormalization()(x)x = ReLU()(x)# main part of the modelx = mobilnet_block(x, filters = 64, strides = 1)x = mobilnet_block(x, filters = 128, strides = 2)x = mobilnet_block(x, filters = 128, strides = 1)x = mobilnet_block(x, filters = 256, strides = 2)x = mobilnet_block(x, filters = 256, strides = 1)x = mobilnet_block(x, filters = 512, strides = 2)for _ in range (5): x = mobilnet_block(x, filters = 512, strides = 1)x = mobilnet_block(x, filters = 1024, strides = 2)x = mobilnet_block(x, filters = 1024, strides = 1)x = AvgPool2D (pool_size = 7, strides = 1, data_format='channels_first')(x)output = Dense (units = 1000, activation = 'softmax')(x)model = Model(inputs=input, outputs=output)model.summary()#plot the modeltf.keras.utils.plot_model(model, to_file='model.png', show_shapes=True, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96) MobileNet is one of the smallest Deep Neural networks that are fast and efficient and can be run on devices without high-end GPUs. Implementation of these networks is very simple when using a framework such as Keras (on TensorFlow). For learning about how to implement other famous CNN architectures using TensorFlow, kindly visit the links below - XceptionResNetVGGDenseNet Xception ResNet VGG DenseNet Howard, A.G., Zhu, M., Chen, B., Kalenichenko, D., Wang, W., Weyand, T., Andreetto, M., & Adam, H. (2017). MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications. ArXiv, abs/1704.04861.
[ { "code": null, "e": 264, "s": 46, "text": "Previously I have discussed the architecture of MobileNet and its most important layer “Depthwise Separable Convolutions” in the story — Understanding Depthwise Separable Convolutions and the efficiency of MobileNets." }, { "code": null, "e": 348, "s": 264, "text": "Next, we will see how to implement this architecture from scratch using TensorFlow." }, { "code": null, "e": 623, "s": 348, "text": "Figure 2 shows the MobileNet architecture that we will implement in code. The network starts with Vonv, BatchNorm, ReLU block, and follows multiple MobileNet blocks from thereon. It finally ends with an Average Pooling and a Fully connected layer, with a Softmax activation." }, { "code": null, "e": 864, "s": 623, "text": "We see the architecture has the pattern — Conv dw/s1, followed by Conv/s1, and so on. Here dw is the depthwise layer with the number of strides, followed by the Conv layer with the number of strides. These two lines are the MobileNet block." }, { "code": null, "e": 1120, "s": 864, "text": "The ‘Filter Shape’ column gives the details about the kernel size and the number of filters to be used. The last number of the column gives the number of filters. We see the filter number gradually increase from 32 to 64, 64 to 128, 128 to 256, and so on." }, { "code": null, "e": 1316, "s": 1120, "text": "The last column shows how the size of the image changes as we go deeper into the network. The input size is chosen as 224*224 pixels, with 3 channels and the output layer classifies 1000 classes." }, { "code": null, "e": 1375, "s": 1316, "text": "Few things to keep in mind while constructing the network:" }, { "code": null, "e": 1643, "s": 1375, "text": "All layers are followed by a Batch Normalization and a ReLU nonlinearity.Unlike normal CNN models which have a Conv2D layer, MobileNet’s have Depthwise Conv layers, as seen in Figure 3. To understand this layer better please refer to — Depthwise Convolutional Blocks." }, { "code": null, "e": 1717, "s": 1643, "text": "All layers are followed by a Batch Normalization and a ReLU nonlinearity." }, { "code": null, "e": 1912, "s": 1717, "text": "Unlike normal CNN models which have a Conv2D layer, MobileNet’s have Depthwise Conv layers, as seen in Figure 3. To understand this layer better please refer to — Depthwise Convolutional Blocks." }, { "code": null, "e": 2110, "s": 1912, "text": "Import all the necessary layers from the TensorFlow libraryWriting a helper function for the MobileNet blockBuilding the stem of the modelUse the helper function to build the main part of the model" }, { "code": null, "e": 2170, "s": 2110, "text": "Import all the necessary layers from the TensorFlow library" }, { "code": null, "e": 2220, "s": 2170, "text": "Writing a helper function for the MobileNet block" }, { "code": null, "e": 2251, "s": 2220, "text": "Building the stem of the model" }, { "code": null, "e": 2311, "s": 2251, "text": "Use the helper function to build the main part of the model" }, { "code": null, "e": 2332, "s": 2311, "text": "Importing the layers" }, { "code": null, "e": 2605, "s": 2332, "text": "import tensorflow as tf#import all necessary layersfrom tensorflow.keras.layers import Input, DepthwiseConv2Dfrom tensorflow.keras.layers import Conv2D, BatchNormalizationfrom tensorflow.keras.layers import ReLU, AvgPool2D, Flatten, Densefrom tensorflow.keras import Model" }, { "code": null, "e": 2700, "s": 2605, "text": "Keras has a DepthwiseConv layer already built-in, so we do not need to create it from scratch." }, { "code": null, "e": 2716, "s": 2700, "text": "MobileNet block" }, { "code": null, "e": 2796, "s": 2716, "text": "For creating the function for the MobileNet block, we need the following steps:" }, { "code": null, "e": 2819, "s": 2796, "text": "Input to the function:" }, { "code": null, "e": 2842, "s": 2819, "text": "Input to the function:" }, { "code": null, "e": 2858, "s": 2842, "text": "a. A tensor (x)" }, { "code": null, "e": 2921, "s": 2858, "text": "b. the number of filters for the convolutional layer (filters)" }, { "code": null, "e": 2984, "s": 2921, "text": "c. the strides for the Depthwise convolutional layer (strides)" }, { "code": null, "e": 3022, "s": 2984, "text": "2. Run (Figure 3 — right side image):" }, { "code": null, "e": 3144, "s": 3022, "text": "a. applying a 3x3 Dethwise convolutional layer with strides followed by a Batch Normalization layer and a ReLU activation" }, { "code": null, "e": 3257, "s": 3144, "text": "b. Applying a 1x1 Convolutional layer with filters followed by a batch normalization layer and a ReLU activation" }, { "code": null, "e": 3287, "s": 3257, "text": "3. Return the tensor (output)" }, { "code": null, "e": 3343, "s": 3287, "text": "These 3 steps are implemented in the code blocks below." }, { "code": null, "e": 3668, "s": 3343, "text": "# MobileNet blockdef mobilnet_block (x, filters, strides): x = DepthwiseConv2D(kernel_size = 3, strides = strides, padding = 'same')(x) x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters = filters, kernel_size = 1, strides = 1)(x) x = BatchNormalization()(x) x = ReLU()(x) return x" }, { "code": null, "e": 3699, "s": 3668, "text": "Building the stem of the Model" }, { "code": null, "e": 3775, "s": 3699, "text": "As seen in Figure 2, the first layer is Conv/s2 with filter shape 3x3x3x32." }, { "code": null, "e": 3947, "s": 3775, "text": "#stem of the modelinput = Input(shape = (224,224,3))x = Conv2D(filters = 32, kernel_size = 3, strides = 2, padding = 'same')(input)x = BatchNormalization()(x)x = ReLU()(x)" }, { "code": null, "e": 3974, "s": 3947, "text": "The main part of the Model" }, { "code": null, "e": 4654, "s": 3974, "text": "# main part of the modelx = mobilnet_block(x, filters = 64, strides = 1)x = mobilnet_block(x, filters = 128, strides = 2)x = mobilnet_block(x, filters = 128, strides = 1)x = mobilnet_block(x, filters = 256, strides = 2)x = mobilnet_block(x, filters = 256, strides = 1)x = mobilnet_block(x, filters = 512, strides = 2)for _ in range (5): x = mobilnet_block(x, filters = 512, strides = 1)x = mobilnet_block(x, filters = 1024, strides = 2)x = mobilnet_block(x, filters = 1024, strides = 1)x = AvgPool2D (pool_size = 7, strides = 1, data_format='channels_first')(x)output = Dense (units = 1000, activation = 'softmax')(x)model = Model(inputs=input, outputs=output)model.summary()" }, { "code": null, "e": 4673, "s": 4654, "text": "Plotting the Model" }, { "code": null, "e": 4843, "s": 4673, "text": "#plot the modeltf.keras.utils.plot_model(model, to_file='model.png', show_shapes=True, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)" }, { "code": null, "e": 6459, "s": 4843, "text": "import tensorflow as tf#import all necessary layersfrom tensorflow.keras.layers import Input, DepthwiseConv2Dfrom tensorflow.keras.layers import Conv2D, BatchNormalizationfrom tensorflow.keras.layers import ReLU, AvgPool2D, Flatten, Densefrom tensorflow.keras import Model# MobileNet blockdef mobilnet_block (x, filters, strides): x = DepthwiseConv2D(kernel_size = 3, strides = strides, padding = 'same')(x) x = BatchNormalization()(x) x = ReLU()(x) x = Conv2D(filters = filters, kernel_size = 1, strides = 1)(x) x = BatchNormalization()(x) x = ReLU()(x) return x#stem of the modelinput = Input(shape = (224,224,3))x = Conv2D(filters = 32, kernel_size = 3, strides = 2, padding = 'same')(input)x = BatchNormalization()(x)x = ReLU()(x)# main part of the modelx = mobilnet_block(x, filters = 64, strides = 1)x = mobilnet_block(x, filters = 128, strides = 2)x = mobilnet_block(x, filters = 128, strides = 1)x = mobilnet_block(x, filters = 256, strides = 2)x = mobilnet_block(x, filters = 256, strides = 1)x = mobilnet_block(x, filters = 512, strides = 2)for _ in range (5): x = mobilnet_block(x, filters = 512, strides = 1)x = mobilnet_block(x, filters = 1024, strides = 2)x = mobilnet_block(x, filters = 1024, strides = 1)x = AvgPool2D (pool_size = 7, strides = 1, data_format='channels_first')(x)output = Dense (units = 1000, activation = 'softmax')(x)model = Model(inputs=input, outputs=output)model.summary()#plot the modeltf.keras.utils.plot_model(model, to_file='model.png', show_shapes=True, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)" }, { "code": null, "e": 6692, "s": 6459, "text": "MobileNet is one of the smallest Deep Neural networks that are fast and efficient and can be run on devices without high-end GPUs. Implementation of these networks is very simple when using a framework such as Keras (on TensorFlow)." }, { "code": null, "e": 6808, "s": 6692, "text": "For learning about how to implement other famous CNN architectures using TensorFlow, kindly visit the links below -" }, { "code": null, "e": 6834, "s": 6808, "text": "XceptionResNetVGGDenseNet" }, { "code": null, "e": 6843, "s": 6834, "text": "Xception" }, { "code": null, "e": 6850, "s": 6843, "text": "ResNet" }, { "code": null, "e": 6854, "s": 6850, "text": "VGG" }, { "code": null, "e": 6863, "s": 6854, "text": "DenseNet" } ]
Comparable in Java - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Comparable is an interface in Java and it comes from java.lang package. This interface is used to compare objects in a class and sorts them according to the natural/reversed order. Hence by using this interface we can sort an array of custom objects. Lists and arrays of objects that implement Comparable interface can be sorted automatically by Collections.sort() and Arrays.sort() methods. The object will be arranged depending upon the co­mpareTo() method available in the implemented class. Let us discuss the Comparable interface in detail with examples in this tutorial. Using Comparable interface we can sort : String objects Wrapper class objects User-defined class objects String objects Wrapper class objects User-defined class objects public int compareTo(Object o); This method compares the object for the specified object for order. It returns the below values when comparing the object corresponding to 3 cases as: Firstly, if the first element is less than the second element it returns “-1′′. In the case that the first element equals to the second element, it returns “0”. The last case in which the first element is greater than the second element, it returns “1”. For example, we are going to sort the Students’ age in the Student object using the comparable interface and compareTo() method. class Student implements Comparable<Student>{ int id; String name; String regNumber; int age; String gender; public Student(int id, String name, String regNumber, int age, String gender) { this.id = id; this.name = name; this.regNumber = regNumber; this.age = age; this.gender = gender; } @Override public int compareTo(Student student) { if (age == student.age) { return 0; } else if (age > student.age) { return 1; } else { return -1; } } } Creating a program ComparableDemo.java for accessing the student class. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ComparableDemo { public static void main(String[] args) { List <Student> list = new ArrayList <Student>(); list.add(new Student(1, "ChandraShekhar", "2015011501", 24, "M")); list.add(new Student(2, "John", "5623521", 35, "M")); list.add(new Student(3, "Smith", "986623", 30, "M")); list.add(new Student(4, "Joi", "856421", 23, "F")); Collections.sort(list); int size = list.size(); for (int i = 0; i < size; i++) { Student student = list.get(i); System.out.print(student.age + " \n"); } } } 23 24 30 35 Let us see the same example shown above with a small change. As a result, sorting will be done on the age in reverse order. class Student implements Comparable<Student>{ int id; String name; String regNumber; int age; String gender; public Student(int id, String name, String regNumber, int age, String gender) { this.id = id; this.name = name; this.regNumber = regNumber; this.age = age; this.gender = gender; } @Override public int compareTo(Student student) { if (age == student.age) { return 0; } else if (age < student.age) { return 1; } else { return -1; } } } In the above program ‘Comparable2.java’, we did a small correction compared to the ‘Comaparable.java’. That is we changed the condition from age>student.age to age<student.age which returns 1 if the first element is less than the second element. Therefore we get the students’ age in the reverse order. Now, we create a program ‘ComparableDemo2.java’ same as the ‘Comparable.java’ without any change for accessing the student class. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ComparableDemo { public static void main(String[] args) { List <Student> list = new ArrayList <Student>(); list.add(new Student(1, "ChandraShekhar", "2015011501", 24, "M")); list.add(new Student(2, "John", "5623521", 35, "M")); list.add(new Student(3, "Smith", "986623", 30, "M")); list.add(new Student(4, "Joi", "856421", 23, "F")); Collections.sort(list); int size = list.size(); for (int i = 0; i < size; i++) { Student student = list.get(i); System.out.print(student.age + " \n"); } } } 35 30 24 23 Hence, we can see that the age given in the list is sorted in reverse order. To sum up, for comparing single bean properties we can use the Comparable interface and override the method compareTo(Object o). Happy Learning 🙂 Comparator vs Comparable in Java Comparator in Java User defined sorting with Java 8 Comparator String sorting in Java Java 8 Getting Min and Max values from a Stream Hibernate Filter Example Xml Configuration Hibernate Native SQL Query Example ArrayList in Java How HashMap Works In Java What are Lambda Expressions in Java 8 Collection Framework & Collection Interfaces in Java Java Class Example Tutorials Java 8 Stream Filter Example with Objects Java variable types Example Lambda Expressions in Java Comparator vs Comparable in Java Comparator in Java User defined sorting with Java 8 Comparator String sorting in Java Java 8 Getting Min and Max values from a Stream Hibernate Filter Example Xml Configuration Hibernate Native SQL Query Example ArrayList in Java How HashMap Works In Java What are Lambda Expressions in Java 8 Collection Framework & Collection Interfaces in Java Java Class Example Tutorials Java 8 Stream Filter Example with Objects Java variable types Example Lambda Expressions in Java Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 649, "s": 398, "text": "Comparable is an interface in Java and it comes from java.lang package. This interface is used to compare objects in a class and sorts them according to the natural/reversed order. Hence by using this interface we can sort an array of custom objects." }, { "code": null, "e": 975, "s": 649, "text": "Lists and arrays of objects that implement Comparable interface can be sorted automatically by Collections.sort() and Arrays.sort() methods. The object will be arranged depending upon the co­mpareTo() method available in the implemented class. Let us discuss the Comparable interface in detail with examples in this tutorial." }, { "code": null, "e": 1016, "s": 975, "text": "Using Comparable interface we can sort :" }, { "code": null, "e": 1082, "s": 1016, "text": "\nString objects\nWrapper class objects\nUser-defined class objects\n" }, { "code": null, "e": 1097, "s": 1082, "text": "String objects" }, { "code": null, "e": 1119, "s": 1097, "text": "Wrapper class objects" }, { "code": null, "e": 1146, "s": 1119, "text": "User-defined class objects" }, { "code": null, "e": 1329, "s": 1146, "text": "public int compareTo(Object o);\nThis method compares the object for the specified object for order. It returns the below values when comparing the object corresponding to 3 cases as:" }, { "code": null, "e": 1409, "s": 1329, "text": "Firstly, if the first element is less than the second element it returns “-1′′." }, { "code": null, "e": 1490, "s": 1409, "text": "In the case that the first element equals to the second element, it returns “0”." }, { "code": null, "e": 1583, "s": 1490, "text": "The last case in which the first element is greater than the second element, it returns “1”." }, { "code": null, "e": 1712, "s": 1583, "text": "For example, we are going to sort the Students’ age in the Student object using the comparable interface and compareTo() method." }, { "code": null, "e": 2299, "s": 1712, "text": "class Student implements Comparable<Student>{\n int id;\n String name;\n String regNumber;\n int age;\n String gender;\n public Student(int id, String name, String regNumber, int age, String gender) {\n this.id = id;\n this.name = name;\n this.regNumber = regNumber;\n this.age = age;\n this.gender = gender;\n }\n @Override public int compareTo(Student student) {\n if (age == student.age) {\n return 0;\n } else if (age > student.age) {\n return 1;\n } else {\n return -1;\n }\n }\n}" }, { "code": null, "e": 2371, "s": 2299, "text": "Creating a program ComparableDemo.java for accessing the student class." }, { "code": null, "e": 3061, "s": 2371, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List; \npublic class ComparableDemo {\n public static void main(String[] args) {\n List <Student> list = new ArrayList <Student>();\n list.add(new Student(1, \"ChandraShekhar\", \"2015011501\", 24, \"M\"));\n list.add(new Student(2, \"John\", \"5623521\", 35, \"M\"));\n list.add(new Student(3, \"Smith\", \"986623\", 30, \"M\"));\n list.add(new Student(4, \"Joi\", \"856421\", 23, \"F\"));\n Collections.sort(list);\n int size = list.size();\n for (int i = 0; i < size; i++) {\n Student student = list.get(i);\n System.out.print(student.age + \" \\n\");\n }\n }\n}" }, { "code": null, "e": 3073, "s": 3061, "text": "23\n24\n30\n35" }, { "code": null, "e": 3197, "s": 3073, "text": "Let us see the same example shown above with a small change. As a result, sorting will be done on the age in reverse order." }, { "code": null, "e": 3784, "s": 3197, "text": "class Student implements Comparable<Student>{\n int id;\n String name;\n String regNumber;\n int age;\n String gender;\n public Student(int id, String name, String regNumber, int age, String gender) {\n this.id = id;\n this.name = name;\n this.regNumber = regNumber;\n this.age = age;\n this.gender = gender;\n }\n @Override public int compareTo(Student student) {\n if (age == student.age) {\n return 0;\n } else if (age < student.age) {\n return 1;\n } else {\n return -1;\n }\n }\n}" }, { "code": null, "e": 4217, "s": 3784, "text": "In the above program ‘Comparable2.java’, we did a small correction compared to the ‘Comaparable.java’. That is we changed the condition from age>student.age to age<student.age which returns 1 if the first element is less than the second element. Therefore we get the students’ age in the reverse order. Now, we create a program ‘ComparableDemo2.java’ same as the ‘Comparable.java’ without any change for accessing the student class." }, { "code": null, "e": 4907, "s": 4217, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List; \npublic class ComparableDemo {\n public static void main(String[] args) {\n List <Student> list = new ArrayList <Student>();\n list.add(new Student(1, \"ChandraShekhar\", \"2015011501\", 24, \"M\"));\n list.add(new Student(2, \"John\", \"5623521\", 35, \"M\"));\n list.add(new Student(3, \"Smith\", \"986623\", 30, \"M\"));\n list.add(new Student(4, \"Joi\", \"856421\", 23, \"F\"));\n Collections.sort(list);\n int size = list.size();\n for (int i = 0; i < size; i++) {\n Student student = list.get(i);\n System.out.print(student.age + \" \\n\");\n }\n }\n}" }, { "code": null, "e": 4919, "s": 4907, "text": "35\n30\n24\n23" }, { "code": null, "e": 5125, "s": 4919, "text": "Hence, we can see that the age given in the list is sorted in reverse order. To sum up, for comparing single bean properties we can use the Comparable interface and override the method compareTo(Object o)." }, { "code": null, "e": 5142, "s": 5125, "text": "Happy Learning 🙂" }, { "code": null, "e": 5650, "s": 5142, "text": "\nComparator vs Comparable in Java\nComparator in Java\nUser defined sorting with Java 8 Comparator\nString sorting in Java\nJava 8 Getting Min and Max values from a Stream\nHibernate Filter Example Xml Configuration\nHibernate Native SQL Query Example\nArrayList in Java\nHow HashMap Works In Java\nWhat are Lambda Expressions in Java 8\nCollection Framework & Collection Interfaces in Java\nJava Class Example Tutorials\nJava 8 Stream Filter Example with Objects\nJava variable types Example\nLambda Expressions in Java\n" }, { "code": null, "e": 5683, "s": 5650, "text": "Comparator vs Comparable in Java" }, { "code": null, "e": 5702, "s": 5683, "text": "Comparator in Java" }, { "code": null, "e": 5746, "s": 5702, "text": "User defined sorting with Java 8 Comparator" }, { "code": null, "e": 5769, "s": 5746, "text": "String sorting in Java" }, { "code": null, "e": 5817, "s": 5769, "text": "Java 8 Getting Min and Max values from a Stream" }, { "code": null, "e": 5860, "s": 5817, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 5895, "s": 5860, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 5913, "s": 5895, "text": "ArrayList in Java" }, { "code": null, "e": 5939, "s": 5913, "text": "How HashMap Works In Java" }, { "code": null, "e": 5977, "s": 5939, "text": "What are Lambda Expressions in Java 8" }, { "code": null, "e": 6030, "s": 5977, "text": "Collection Framework & Collection Interfaces in Java" }, { "code": null, "e": 6059, "s": 6030, "text": "Java Class Example Tutorials" }, { "code": null, "e": 6101, "s": 6059, "text": "Java 8 Stream Filter Example with Objects" }, { "code": null, "e": 6129, "s": 6101, "text": "Java variable types Example" }, { "code": null, "e": 6156, "s": 6129, "text": "Lambda Expressions in Java" }, { "code": null, "e": 6162, "s": 6160, "text": "Δ" }, { "code": null, "e": 6186, "s": 6162, "text": " Install Java on Mac OS" }, { "code": null, "e": 6214, "s": 6186, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 6243, "s": 6214, "text": " Install Minikube on Windows" }, { "code": null, "e": 6278, "s": 6243, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 6305, "s": 6278, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 6332, "s": 6305, "text": " Install Gradle on Windows" }, { "code": null, "e": 6361, "s": 6332, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 6387, "s": 6361, "text": " Install PuTTY on windows" }, { "code": null, "e": 6413, "s": 6387, "text": " Install Mysql on Windows" }, { "code": null, "e": 6449, "s": 6413, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 6483, "s": 6449, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 6509, "s": 6483, "text": " Install Maven on Windows" }, { "code": null, "e": 6534, "s": 6509, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 6568, "s": 6534, "text": " Install Maven on Windows Command" }, { "code": null, "e": 6603, "s": 6568, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 6627, "s": 6603, "text": " Install Ant on Windows" }, { "code": null, "e": 6656, "s": 6627, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 6688, "s": 6656, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 6721, "s": 6688, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 6746, "s": 6721, "text": " Java8 – Install Windows" }, { "code": null, "e": 6763, "s": 6746, "text": " Java8 – foreach" }, { "code": null, "e": 6791, "s": 6763, "text": " Java8 – forEach with index" }, { "code": null, "e": 6822, "s": 6791, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 6854, "s": 6822, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 6874, "s": 6854, "text": " Java8 – GroupingBy" }, { "code": null, "e": 6894, "s": 6874, "text": " Java8 – SummingInt" }, { "code": null, "e": 6918, "s": 6894, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 6948, "s": 6918, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 6980, "s": 6948, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 7016, "s": 6980, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 7060, "s": 7016, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 7092, "s": 7060, "text": " Howto – Convert List to String" }, { "code": null, "e": 7133, "s": 7092, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 7170, "s": 7133, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 7210, "s": 7170, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 7239, "s": 7210, "text": " Howto – Convert List to Map" }, { "code": null, "e": 7271, "s": 7239, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 7291, "s": 7271, "text": " Howto – Sort a Map" }, { "code": null, "e": 7313, "s": 7291, "text": " Howto – Filter a Map" }, { "code": null, "e": 7343, "s": 7313, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 7394, "s": 7343, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 7430, "s": 7394, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 7462, "s": 7430, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 7497, "s": 7462, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 7520, "s": 7497, "text": " Howto – Merge Streams" }, { "code": null, "e": 7567, "s": 7520, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 7592, "s": 7567, "text": " Howto -Get Stream count" }, { "code": null, "e": 7636, "s": 7592, "text": " Howto – Get Min and Max values in a Stream" } ]
Powershell - Create File
New-Item cmdlet is used to create a file by passing the path using -Path as path of the file and -ItemType as File. In this example, we'll create a file in D:\Temp\Test Folder with name "Test File.txt" Type the following command in PowerShell ISE Console New-Item -Path 'D:\temp\Test Folder\Test File.txt' -ItemType File You will see the following output. Directory: D:\temp Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 4/3/2018 7:14 PM 0 Test File.txt You can see the same in Windows Explorer where Test File.txt is created in D:/temp/Test Folder directory. 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2150, "s": 2034, "text": "New-Item cmdlet is used to create a file by passing the path using -Path as path of the file and -ItemType as File." }, { "code": null, "e": 2236, "s": 2150, "text": "In this example, we'll create a file in D:\\Temp\\Test Folder with name \"Test File.txt\"" }, { "code": null, "e": 2289, "s": 2236, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2355, "s": 2289, "text": "New-Item -Path 'D:\\temp\\Test Folder\\Test File.txt' -ItemType File" }, { "code": null, "e": 2390, "s": 2355, "text": "You will see the following output." }, { "code": null, "e": 2668, "s": 2390, "text": "Directory: D:\\temp\n\nMode LastWriteTime Length Name \n---- ------------- ------ ---- \n-a--- 4/3/2018 7:14 PM 0 Test File.txt \n" }, { "code": null, "e": 2774, "s": 2668, "text": "You can see the same in Windows Explorer where Test File.txt is created in D:/temp/Test Folder directory." }, { "code": null, "e": 2809, "s": 2774, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2830, "s": 2809, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2865, "s": 2830, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2878, "s": 2865, "text": " Vijay Saini" }, { "code": null, "e": 2915, "s": 2878, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2927, "s": 2915, "text": " Fettah Ben" }, { "code": null, "e": 2934, "s": 2927, "text": " Print" }, { "code": null, "e": 2945, "s": 2934, "text": " Add Notes" } ]
JavaScript Arithmetic
Arithmetic operators perform arithmetic on numbers (literals or variables). A typical arithmetic operation operates on two numbers. The two numbers can be literals: or variables: or expressions: The numbers (in an arithmetic operation) are called operands. The operation (to be performed between the two operands) is defined by an operator. The addition operator (+) adds numbers: The subtraction operator (-) subtracts numbers. The multiplication operator (*) multiplies numbers. The division operator (/) divides numbers. The modulus operator (%) returns the division remainder. In arithmetic, the division of two integers produces a quotient and a remainder. In mathematics, the result of a modulo operation is the remainder of an arithmetic division. The increment operator (++) increments numbers. The decrement operator (--) decrements numbers. The exponentiation operator (**) raises the first operand to the power of the second operand. x ** y produces the same result as Math.pow(x,y): Operator precedence describes the order in which operations are performed in an arithmetic expression. Is the result of example above the same as 150 * 3, or is it the same as 100 + 150? Is the addition or the multiplication done first? As in traditional school mathematics, the multiplication is done first. Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-). And (as in school mathematics) the precedence can be changed by using parentheses: When using parentheses, the operations inside the parentheses are computed first. When many operations have the same precedence (like addition and subtraction), they are computed from left to right: Pale red entries indicates ECMAScript 2015 (ES6) or higher. Expressions in parentheses are fully computed before the value is used in the rest of the expression. Divide 10 by 2, and alert the result. alert(10 2); Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 76, "s": 0, "text": "Arithmetic operators perform arithmetic on numbers (literals or variables)." }, { "code": null, "e": 132, "s": 76, "text": "A typical arithmetic operation operates on two numbers." }, { "code": null, "e": 165, "s": 132, "text": "The two numbers can be literals:" }, { "code": null, "e": 179, "s": 165, "text": "or variables:" }, { "code": null, "e": 195, "s": 179, "text": "or expressions:" }, { "code": null, "e": 257, "s": 195, "text": "The numbers (in an arithmetic operation) are called operands." }, { "code": null, "e": 341, "s": 257, "text": "The operation (to be performed between the two operands) is defined by an operator." }, { "code": null, "e": 381, "s": 341, "text": "The addition operator (+) adds numbers:" }, { "code": null, "e": 429, "s": 381, "text": "The subtraction operator (-) subtracts numbers." }, { "code": null, "e": 481, "s": 429, "text": "The multiplication operator (*) multiplies numbers." }, { "code": null, "e": 524, "s": 481, "text": "The division operator (/) divides numbers." }, { "code": null, "e": 581, "s": 524, "text": "The modulus operator (%) returns the division remainder." }, { "code": null, "e": 662, "s": 581, "text": "In arithmetic, the division of two integers produces a quotient\nand a remainder." }, { "code": null, "e": 756, "s": 662, "text": "In mathematics, the result of a modulo operation is the remainder of an arithmetic division.\n" }, { "code": null, "e": 804, "s": 756, "text": "The increment operator (++) increments numbers." }, { "code": null, "e": 852, "s": 804, "text": "The decrement operator (--) decrements numbers." }, { "code": null, "e": 946, "s": 852, "text": "The exponentiation operator (**) raises the first operand to the power of the second operand." }, { "code": null, "e": 996, "s": 946, "text": "x ** y produces the same result as Math.pow(x,y):" }, { "code": null, "e": 1100, "s": 996, "text": "Operator precedence describes the order in which operations are performed in \nan arithmetic expression." }, { "code": null, "e": 1185, "s": 1100, "text": "Is the result of example above the same as 150 * 3, or is it the same as 100 \n+ 150?" }, { "code": null, "e": 1235, "s": 1185, "text": "Is the addition or the multiplication done first?" }, { "code": null, "e": 1307, "s": 1235, "text": "As in traditional school mathematics, the multiplication is done first." }, { "code": null, "e": 1406, "s": 1307, "text": "Multiplication (*) and division (/) have higher precedence than \naddition (+) and subtraction (-)." }, { "code": null, "e": 1490, "s": 1406, "text": "And (as in school mathematics) the precedence can be changed by using \nparentheses:" }, { "code": null, "e": 1574, "s": 1490, "text": "When using parentheses, the operations inside the parentheses are computed \nfirst. " }, { "code": null, "e": 1694, "s": 1574, "text": "When many operations have the same precedence (like addition and \nsubtraction), they are computed from left to \nright: " }, { "code": null, "e": 1754, "s": 1694, "text": "Pale red entries indicates ECMAScript 2015 (ES6) or higher." }, { "code": null, "e": 1857, "s": 1754, "text": "Expressions in parentheses are fully computed before the value is \nused in the rest of the expression." }, { "code": null, "e": 1895, "s": 1857, "text": "Divide 10 by 2, and alert the result." }, { "code": null, "e": 1910, "s": 1895, "text": "alert(10 2);\n" }, { "code": null, "e": 1929, "s": 1910, "text": "Start the Exercise" }, { "code": null, "e": 1962, "s": 1929, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2004, "s": 1962, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2111, "s": 2004, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2130, "s": 2111, "text": "help@w3schools.com" } ]
PHP $_ENV
$_ENV is another superglobal associative array in PHP. It stores environment variables available to current script. $HTTP_ENV_VARS also contains the same information, but is not a superglobal, and now been deprecated. Environment variables are imported into global namespace. Most of these variables are provided by the shell under which PHP parser is running. Hence, list of environment variables may be different on different platforms. This array also includes CGI variables in case whether PHP is running as a server module orCGI processor. PHP library has getenv()function to retrieve list of all environment variables or value of a specific environment variable Following script displays values of all available environment variables <?php $arr=getenv(); foreach ($arr as $key=>$val) echo "$key=>$val "; ?> To obtain value of specific variable use its name as argument for getenv() function Live Demo <?php echo "Path: " . getenv("PATH"); ?> Browser will display result similar to following Path: /usr/local/bin/factor:/root/.sdkman/candidates/kotlin/current/bin:/usr/GNUstep/System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/scriba/bin:/usr/local/smlnj/bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/local/dart/bin:/usr/libexec/sdcc:/usr/local/icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/pash/Source/PashConsole/bin/Debug/:.:/root/.sdkman/candidates/kotlin/current/bin:/usr/bin:/sbin:/bin PHP also has putenv() function to create a new environment variable. The environment variable will only exist for the duration of the current request. Changing value of certain environment variables should be avoided. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). The safe_mode_protected_env_vars directive in php.ini contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). Live Demo <?php putenv("PHP_TEMPUSER=GUEST"); echo "Temp user: " . getenv("PHP_TEMPUSER"); ?> Browser will display result as following Temp user: GUEST
[ { "code": null, "e": 1280, "s": 1062, "text": "$_ENV is another superglobal associative array in PHP. It stores environment variables available to current script. $HTTP_ENV_VARS also contains the same information, but is not a superglobal, and now been deprecated." }, { "code": null, "e": 1501, "s": 1280, "text": "Environment variables are imported into global namespace. Most of these variables are provided by the shell under which PHP parser is running. Hence, list of environment variables may be different on different platforms." }, { "code": null, "e": 1607, "s": 1501, "text": "This array also includes CGI variables in case whether PHP is running as a server module orCGI processor." }, { "code": null, "e": 1730, "s": 1607, "text": "PHP library has getenv()function to retrieve list of all environment variables or value of a specific environment variable" }, { "code": null, "e": 1802, "s": 1730, "text": "Following script displays values of all available environment variables" }, { "code": null, "e": 1875, "s": 1802, "text": "<?php\n$arr=getenv();\nforeach ($arr as $key=>$val)\necho \"$key=>$val\n\";\n?>" }, { "code": null, "e": 1959, "s": 1875, "text": "To obtain value of specific variable use its name as argument for getenv() function" }, { "code": null, "e": 1970, "s": 1959, "text": " Live Demo" }, { "code": null, "e": 2011, "s": 1970, "text": "<?php\necho \"Path: \" . getenv(\"PATH\");\n?>" }, { "code": null, "e": 2060, "s": 2011, "text": "Browser will display result similar to following" }, { "code": null, "e": 2518, "s": 2060, "text": "Path: /usr/local/bin/factor:/root/.sdkman/candidates/kotlin/current/bin:/usr/GNUstep/System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/scriba/bin:/usr/local/smlnj/bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/local/dart/bin:/usr/libexec/sdcc:/usr/local/icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/pash/Source/PashConsole/bin/Debug/:.:/root/.sdkman/candidates/kotlin/current/bin:/usr/bin:/sbin:/bin" }, { "code": null, "e": 2669, "s": 2518, "text": "PHP also has putenv() function to create a new environment variable. The environment variable will only exist for the duration of the current request." }, { "code": null, "e": 2842, "s": 2669, "text": "Changing value of certain environment variables should be avoided. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR)." }, { "code": null, "e": 3012, "s": 2842, "text": "The safe_mode_protected_env_vars directive in php.ini contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv()." }, { "code": null, "e": 3023, "s": 3012, "text": " Live Demo" }, { "code": null, "e": 3107, "s": 3023, "text": "<?php\nputenv(\"PHP_TEMPUSER=GUEST\");\necho \"Temp user: \" . getenv(\"PHP_TEMPUSER\");\n?>" }, { "code": null, "e": 3148, "s": 3107, "text": "Browser will display result as following" }, { "code": null, "e": 3165, "s": 3148, "text": "Temp user: GUEST" } ]
Dart - Const And Final Keyword - GeeksforGeeks
10 Sep, 2021 Dart supports the assignment of constant value to a variable. These are done by the use of the following keyword: const keywordfinal keyword const keyword final keyword These keywords are used to keep the value of a variable static throughout the code base, meaning once the variable is defined its state cannot be altered. There are no limitations if these keywords have a defined data type or not. The final keyword is used to hardcode the values of the variable and it cannot be altered in future, neither any kind of operations performed on these variables can alter its value (state). // Without datatype final variable_name; // With datatype final data_type variable_name; Example: Using the final keywords in a Dart program. Dart void main() { // Assigning value to geek1 // variable without datatype final geek1 = "Geeks For Geeks"; // Printing variable geek1 print(geek1); // Assigning value to geek2 // variable with datatype final String geek2 = "Geeks For Geeks Again!!"; // Printing variable geek2 print(geek2);} Output: Geeks For Geeks Geeks For Geeks Again!! If we try to reassign the same variable then it will display error. The Const keyword in Dart behaves exactly like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable. Example: Using const keywords in a Dart program. Dart void main() { // Assigning value to geek1 // variable without datatype const geek1 = "Geeks For Geeks"; // Printing variable geek1 print(geek1); // Assigning value to // geek2 variable with datatype const String geek2 = "Geeks For Geeks Again!!"; // Printing variable geek2 print(geek2);} Output: Geeks For Geeks Geeks For Geeks Again!! Example: Assigning value without const keyword and then by const keyword. Without Const Keyword Dart // Declaring a functiongfg() => [1, 2]; // Main functionvoid main() { // Assigning value // through function var geek1 = gfg(); var geek2 = gfg(); // Printing result // false print(geek1 == geek2); print(geek1); print(geek2);} Output : false [1, 2] [1, 2] With Const Keyword: Dart // Declaring a functiongfg() => const[1, 2]; // Main functionvoid main() { // Assigning value // through function var geek1 = gfg(); var geek2 = gfg(); // Printing result // true print(geek1 == geek2); print(geek1); print(geek2);} Output : true [1, 2] [1, 2] It is necessary to create them from the data available during the compile time. For instance: setting string “GeeksForGeeks” is fine but setting the current time is not.They are deeply and transitively immutable.They are canonicalised. It is necessary to create them from the data available during the compile time. For instance: setting string “GeeksForGeeks” is fine but setting the current time is not. They are deeply and transitively immutable. They are canonicalised. xerosanyam anikakapoor Dart-Keywords Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Row and Column Widgets Flutter - BoxShadow Widget Dart Tutorial How to Append or Concatenate Strings in Dart? ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget
[ { "code": null, "e": 23969, "s": 23941, "text": "\n10 Sep, 2021" }, { "code": null, "e": 24083, "s": 23969, "text": "Dart supports the assignment of constant value to a variable. These are done by the use of the following keyword:" }, { "code": null, "e": 24110, "s": 24083, "text": "const keywordfinal keyword" }, { "code": null, "e": 24124, "s": 24110, "text": "const keyword" }, { "code": null, "e": 24138, "s": 24124, "text": "final keyword" }, { "code": null, "e": 24369, "s": 24138, "text": "These keywords are used to keep the value of a variable static throughout the code base, meaning once the variable is defined its state cannot be altered. There are no limitations if these keywords have a defined data type or not." }, { "code": null, "e": 24559, "s": 24369, "text": "The final keyword is used to hardcode the values of the variable and it cannot be altered in future, neither any kind of operations performed on these variables can alter its value (state)." }, { "code": null, "e": 24650, "s": 24559, "text": "// Without datatype\nfinal variable_name;\n\n// With datatype\nfinal data_type variable_name;" }, { "code": null, "e": 24703, "s": 24650, "text": "Example: Using the final keywords in a Dart program." }, { "code": null, "e": 24708, "s": 24703, "text": "Dart" }, { "code": "void main() { // Assigning value to geek1 // variable without datatype final geek1 = \"Geeks For Geeks\"; // Printing variable geek1 print(geek1); // Assigning value to geek2 // variable with datatype final String geek2 = \"Geeks For Geeks Again!!\"; // Printing variable geek2 print(geek2);}", "e": 25020, "s": 24708, "text": null }, { "code": null, "e": 25030, "s": 25020, "text": " Output:" }, { "code": null, "e": 25070, "s": 25030, "text": "Geeks For Geeks\nGeeks For Geeks Again!!" }, { "code": null, "e": 25138, "s": 25070, "text": "If we try to reassign the same variable then it will display error." }, { "code": null, "e": 25502, "s": 25140, "text": "The Const keyword in Dart behaves exactly like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable." }, { "code": null, "e": 25551, "s": 25502, "text": "Example: Using const keywords in a Dart program." }, { "code": null, "e": 25556, "s": 25551, "text": "Dart" }, { "code": "void main() { // Assigning value to geek1 // variable without datatype const geek1 = \"Geeks For Geeks\"; // Printing variable geek1 print(geek1); // Assigning value to // geek2 variable with datatype const String geek2 = \"Geeks For Geeks Again!!\"; // Printing variable geek2 print(geek2);}", "e": 25868, "s": 25556, "text": null }, { "code": null, "e": 25877, "s": 25868, "text": " Output:" }, { "code": null, "e": 25917, "s": 25877, "text": "Geeks For Geeks\nGeeks For Geeks Again!!" }, { "code": null, "e": 25993, "s": 25919, "text": "Example: Assigning value without const keyword and then by const keyword." }, { "code": null, "e": 26015, "s": 25993, "text": "Without Const Keyword" }, { "code": null, "e": 26020, "s": 26015, "text": "Dart" }, { "code": "// Declaring a functiongfg() => [1, 2]; // Main functionvoid main() { // Assigning value // through function var geek1 = gfg(); var geek2 = gfg(); // Printing result // false print(geek1 == geek2); print(geek1); print(geek2);}", "e": 26259, "s": 26020, "text": null }, { "code": null, "e": 26268, "s": 26259, "text": "Output :" }, { "code": null, "e": 26288, "s": 26268, "text": "false\n[1, 2]\n[1, 2]" }, { "code": null, "e": 26310, "s": 26290, "text": "With Const Keyword:" }, { "code": null, "e": 26315, "s": 26310, "text": "Dart" }, { "code": "// Declaring a functiongfg() => const[1, 2]; // Main functionvoid main() { // Assigning value // through function var geek1 = gfg(); var geek2 = gfg(); // Printing result // true print(geek1 == geek2); print(geek1); print(geek2);}", "e": 26558, "s": 26315, "text": null }, { "code": null, "e": 26568, "s": 26558, "text": " Output :" }, { "code": null, "e": 26587, "s": 26568, "text": "true\n[1, 2]\n[1, 2]" }, { "code": null, "e": 26823, "s": 26587, "text": "It is necessary to create them from the data available during the compile time. For instance: setting string “GeeksForGeeks” is fine but setting the current time is not.They are deeply and transitively immutable.They are canonicalised." }, { "code": null, "e": 26993, "s": 26823, "text": "It is necessary to create them from the data available during the compile time. For instance: setting string “GeeksForGeeks” is fine but setting the current time is not." }, { "code": null, "e": 27037, "s": 26993, "text": "They are deeply and transitively immutable." }, { "code": null, "e": 27061, "s": 27037, "text": "They are canonicalised." }, { "code": null, "e": 27074, "s": 27063, "text": "xerosanyam" }, { "code": null, "e": 27086, "s": 27074, "text": "anikakapoor" }, { "code": null, "e": 27100, "s": 27086, "text": "Dart-Keywords" }, { "code": null, "e": 27105, "s": 27100, "text": "Dart" }, { "code": null, "e": 27203, "s": 27105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27235, "s": 27203, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 27274, "s": 27235, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27300, "s": 27274, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27333, "s": 27300, "text": "Flutter - Row and Column Widgets" }, { "code": null, "e": 27360, "s": 27333, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 27374, "s": 27360, "text": "Dart Tutorial" }, { "code": null, "e": 27420, "s": 27374, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 27446, "s": 27420, "text": "ListView Class in Flutter" }, { "code": null, "e": 27472, "s": 27446, "text": "Flutter - Flexible Widget" } ]
LSTM Autoencoder for Extreme Rare Event Classification in Keras | by Chitta Ranjan | Towards Data Science
<<Download the free book, Understanding Deep Learning, to learn more>> This post is a continuation of my previous post Extreme Rare Event Classification using Autoencoders. In the previous post, we talked about the challenges in an extremely rare event data with less than 1% positively labeled data. We built an Autoencoder Classifier for such processes using the concepts of Anomaly Detection. However, the data we have is a time series. But earlier we used a Dense layer Autoencoder that does not use the temporal features in the data. Therefore, in this post, we will improve on our approach by building an LSTM Autoencoder. Here, we will learn: data preparation steps for an LSTM model, building and implementing LSTM autoencoder, and using LSTM autoencoder for rare-event classification. Quick recap on LSTM: LSTM is a type of Recurrent Neural Network (RNN). RNNs, in general, and LSTM, specifically, are used on sequential or time series data. These models are capable of automatically extracting effect of past events. LSTM are known for its ability to extract both long- and short- term effects of pasts event. In the following, we will go directly to developing an LSTM Autoencoder. It is recommended to read Step-by-step understanding LSTM Autoencoder layers to better understand and further improve the network below. About the data problem in brief, we have real-world data on sheet breaks from a paper manufacturing. Our objective is to predict the break in advance. Please refer to Extreme Rare Event Classification using Autoencoders for the details on the data, problem, and the classification approach. In our problem, we have a multivariate time-series data. A multivariate time-series data contains multiple variables observed over a period of time. We will build an LSTM autoencoder on this multivariate time-series to perform rare-event classification. As described in [1], this is achieved by using an anomaly detection approach: we build an autoencoder on the normal (negatively labeled) data, use it to reconstruct a new sample, if the reconstruction error is high, we label it as a sheet-break. LSTM requires few special data-preprocessing steps. In the following, we will give sufficient attention to these steps. Let’s get to the implementation. I like to put together the libraries and global constants first. %matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport numpy as npfrom pylab import rcParamsimport tensorflow as tffrom keras import optimizers, Sequentialfrom keras.models import Modelfrom keras.utils import plot_modelfrom keras.layers import Dense, LSTM, RepeatVector, TimeDistributedfrom keras.callbacks import ModelCheckpoint, TensorBoardfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, precision_recall_curvefrom sklearn.metrics import recall_score, classification_report, auc, roc_curvefrom sklearn.metrics import precision_recall_fscore_support, f1_scorefrom numpy.random import seedseed(7)from tensorflow import set_random_seedset_random_seed(11)from sklearn.model_selection import train_test_splitSEED = 123 #used to help randomly select the data pointsDATA_SPLIT_PCT = 0.2rcParams['figure.figsize'] = 8, 6LABELS = ["Normal","Break"] As mentioned before, LSTM requires a few specific steps in the data preparation. The input to LSTMs are 3-dimensional arrays created from the time-series data. This is an error prone step so we will look at the details. The data is taken from [2]. The link to the data is here. df = pd.read_csv("data/processminer-rare-event-mts - data.csv") df.head(n=5) # visualize the data. As also mentioned in [1], the objective of this rare-event problem is to predict a sheet-break before it occurs. We will try to predict the break up to 4 minutes in advance. For this data, this is equivalent to shifting the labels up by two rows. It can be done directly with df.y=df.y.shift(-2). However, here we require to do the following, For any row n with label 1, make (n-2):(n-1) as 1. With this, we are teaching the classifier to predict up to 4 minutes ahead. And, remove row n. Row n is removed because we are not interested in teaching the classifier to predict a break when it has already happened. We develop the following function to perform this curve shifting. sign = lambda x: (1, -1)[x < 0]def curve_shift(df, shift_by): ''' This function will shift the binary labels in a dataframe. The curve shift will be with respect to the 1s. For example, if shift is -2, the following process will happen: if row n is labeled as 1, then - Make row (n+shift_by):(n+shift_by-1) = 1. - Remove row n. i.e. the labels will be shifted up to 2 rows up. Inputs: df A pandas dataframe with a binary labeled column. This labeled column should be named as 'y'. shift_by An integer denoting the number of rows to shift. Output df A dataframe with the binary labels shifted by shift. ''' vector = df['y'].copy() for s in range(abs(shift_by)): tmp = vector.shift(sign(shift_by)) tmp = tmp.fillna(0) vector += tmp labelcol = 'y' # Add vector to the df df.insert(loc=0, column=labelcol+'tmp', value=vector) # Remove the rows with labelcol == 1. df = df.drop(df[df[labelcol] == 1].index) # Drop labelcol and rename the tmp col as labelcol df = df.drop(labelcol, axis=1) df = df.rename(columns={labelcol+'tmp': labelcol}) # Make the labelcol binary df.loc[df[labelcol] > 0, labelcol] = 1 return df We will now shift our data and verify if the shifting is correct. In the subsequent sections, we have few more test steps. It is recommended to use them to ensure the data preparation steps are working as expected. print('Before shifting') # Positive labeled rows before shifting.one_indexes = df.index[df['y'] == 1]display(df.iloc[(np.where(np.array(input_y) == 1)[0][0]-5):(np.where(np.array(input_y) == 1)[0][0]+1), ])# Shift the response column y by 2 rows to do a 4-min ahead prediction.df = curve_shift(df, shift_by = -2)print('After shifting') # Validating if the shift happened correctly.display(df.iloc[(one_indexes[0]-4):(one_indexes[0]+1), 0:5].head(n=5)) If we note here, we moved the positive label at 5/1/99 8:38 to n-1 and n-2 timestamps, and dropped row n. Also, there is a time difference of more than 2 minutes between a break row and the next row. This is because, when a break occurs, the machine stays in the break status for a while. During this time, we have y = 1 for consecutive rows. In the provided data, these consecutive break rows are deleted to prevent the classifier from learning to predict a break after it has already happened. Refer [2] for details. Before moving forward, we clean up the data by dropping the time, and two other categorical columns. # Remove time column, and the categorical columnsdf = df.drop(['time', 'x28', 'x61'], axis=1) LSTM is a bit more demanding than other models. Significant amount of time and attention may go in preparing the data that fits an LSTM. However, it is generally worth the effort. The input data to an LSTM model is a 3-dimensional array. The shape of the array is samples x lookback x features. Let’s understand them, samples: This is simply the number of observations, or in other words, the number of data points. lookback: LSTM models are meant to look at the past. Meaning, at time t the LSTM will process data up to (t-lookback) to make a prediction. features: It is the number of features present in the input data. First, we will extract the features and response. input_X = df.loc[:, df.columns != 'y'].values # converts the df to a numpy arrayinput_y = df['y'].valuesn_features = input_X.shape[1] # number of features The input_X here is a 2-dimensional array of size samples x features. We want to be able to transform such a 2D array into a 3D array of size: samples x lookback x features. Refer to Figure 1 above for a visual understanding. For that, we develop a function temporalize . def temporalize(X, y, lookback): ''' Inputs X A 2D numpy array ordered by time of shape: (n_observations x n_features) y A 1D numpy array with indexes aligned with X, i.e. y[i] should correspond to X[i]. Shape: n_observations. lookback The window size to look back in the past records. Shape: a scalar. Output output_X A 3D numpy array of shape: ((n_observations-lookback-1) x lookback x n_features) output_y A 1D array of shape: (n_observations-lookback-1), aligned with X. ''' output_X = [] output_y = [] for i in range(len(X) - lookback - 1): t = [] for j in range(1, lookback + 1): # Gather the past records upto the lookback period t.append(X[[(i + j + 1)], :]) output_X.append(t) output_y.append(y[i + lookback + 1]) return np.squeeze(np.array(output_X)), np.array(output_y) To test and demonstrate this function, we will look at an example below with lookback = 5 . print('First instance of y = 1 in the original data')display(df.iloc[(np.where(np.array(input_y) == 1)[0][0]-5):(np.where(np.array(input_y) == 1)[0][0]+1), ])lookback = 5 # Equivalent to 10 min of past data.# Temporalize the dataX, y = temporalize(X = input_X, y = input_y, lookback = lookback)print('For the same instance of y = 1, we are keeping past 5 samples in the 3D predictor array, X.')display(pd.DataFrame(np.concatenate(X[np.where(np.array(y) == 1)[0][0]], axis=0 ))) What we are looking for here is, In the original data, y = 1 at row 257. With lookback = 5 we want the LSTM to look at the 5 rows before row 257 (including itself). In the 3D array, X, each 2D block at X[i,:,:] denotes the prediction data that corresponds to y[i] . To draw an analogy, in regression y[i] corresponds to a 1D vector X[i,:] ; in LSTM y[i] corresponds to a 2D array X[i,:,:] . This 2D block X[i,:,:] should have the predictors at input_X[i,:] and the previous rows up to the given lookback . As we can see in the output above, the X[i,:,:] block in the bottom is the same as the five past rows of y=1 shown on the top. Similarly, this is applied for the entire data, for all y’s. The example here is shown for an instance of y=1 for easier visualization. This is straightforward with the sklearn function. X_train, X_test, y_train, y_test = train_test_split(np.array(X), np.array(y), test_size=DATA_SPLIT_PCT, random_state=SEED)X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=DATA_SPLIT_PCT, random_state=SEED) For training the autoencoder, we will be using the X coming from only the negatively labeled data. Therefore, we separate the X corresponding to y = 0. X_train_y0 = X_train[y_train==0]X_train_y1 = X_train[y_train==1]X_valid_y0 = X_valid[y_valid==0]X_valid_y1 = X_valid[y_valid==1] We will reshape the X’s into the required 3D dimension: sample x lookback x features. X_train = X_train.reshape(X_train.shape[0], lookback, n_features)X_train_y0 = X_train_y0.reshape(X_train_y0.shape[0], lookback, n_features)X_train_y1 = X_train_y1.reshape(X_train_y1.shape[0], lookback, n_features)X_valid = X_valid.reshape(X_valid.shape[0], lookback, n_features)X_valid_y0 = X_valid_y0.reshape(X_valid_y0.shape[0], lookback, n_features)X_valid_y1 = X_valid_y1.reshape(X_valid_y1.shape[0], lookback, n_features)X_test = X_test.reshape(X_test.shape[0], lookback, n_features) It is usually better to use a standardized data (transformed to Gaussian with mean 0 and standard deviation 1) for autoencoders. One common standardization mistake is: we normalize the entire data and then split into train-test. This is incorrect. Test data should be completely unseen to anything during the modeling. We should, therefore, normalize the training data, and use its summary statistics to normalize the test data (for normalization, these statistics are the mean and variances of each feature). Standardizing this data is a bit tricky. This is because the X matrices are 3D, and we want the standardization to happen with respect to the original 2D data. To do this, we will require two UDFs. flatten : This function will re-create the original 2D array from which the 3D arrays were created. This function is the inverse of temporalize, meaning X = flatten(temporalize(X)). scale : This function will scale a 3D array that we created as inputs to the LSTM. def flatten(X): ''' Flatten a 3D array. Input X A 3D array for lstm, where the array is sample x timesteps x features. Output flattened_X A 2D array, sample x features. ''' flattened_X = np.empty((X.shape[0], X.shape[2])) # sample x features array. for i in range(X.shape[0]): flattened_X[i] = X[i, (X.shape[1]-1), :] return(flattened_X)def scale(X, scaler): ''' Scale 3D array. Inputs X A 3D array for lstm, where the array is sample x timesteps x features. scaler A scaler object, e.g., sklearn.preprocessing.StandardScaler, sklearn.preprocessing.normalize Output X Scaled 3D array. ''' for i in range(X.shape[0]): X[i, :, :] = scaler.transform(X[i, :, :]) return X Why didn’t we first normalize the original 2D data and then create the 3D arrays? Because, to do this we will: split the data into train and test, followed by their normalization. However, when we create the 3D arrays on the test data, we lose the initial rows of samples up till the lookback. Splitting into train-valid-test will cause this for both the validation and test sets. We will fit a Standardization object from sklearn. This function standardizes the data to Normal(0, 1). Note that we require to flatten the X_train_y0 array to pass to the fit function. # Initialize a scaler using the training data.scaler = StandardScaler().fit(flatten(X_train_y0)) We will use our UDF, scale, to standardize X_train_y0 with the fitted transform object scaler. X_train_y0_scaled = scale(X_train_y0, scaler) Make sure the scale worked correctly? A correct transformation of X_train will ensure that the means and variances of each column of the flattened X_train are 0 and 1, respectively. We test this. a = flatten(X_train_y0_scaled)print('colwise mean', np.mean(a, axis=0).round(6))print('colwise variance', np.var(a, axis=0)) All the means and variances outputted above are 0 and 1, respectively. Therefore, the scaling is correct. We will now scale the validation and test sets. We will again use the scaler object on these sets. X_valid_scaled = scale(X_valid, scaler)X_valid_y0_scaled = scale(X_valid_y0, scaler)X_test_scaled = scale(X_test, scaler) We will, first, initialize few variables. timesteps = X_train_y0_scaled.shape[1] # equal to the lookbackn_features = X_train_y0_scaled.shape[2] # 59epochs = 200batch = 64lr = 0.0001 We, now, develop a simple architecture. lstm_autoencoder = Sequential()# Encoderlstm_autoencoder.add(LSTM(32, activation='relu', input_shape=(timesteps, n_features), return_sequences=True))lstm_autoencoder.add(LSTM(16, activation='relu', return_sequences=False))lstm_autoencoder.add(RepeatVector(timesteps))# Decoderlstm_autoencoder.add(LSTM(16, activation='relu', return_sequences=True))lstm_autoencoder.add(LSTM(32, activation='relu', return_sequences=True))lstm_autoencoder.add(TimeDistributed(Dense(n_features)))lstm_autoencoder.summary() From the summary(), the total number of parameters are 5,331. This is about half of the training size. Hence, this is an appropriate model to fit. To have a bigger architecture, we will need to add regularization, e.g. Dropout, which will be covered in the next post. Now, we will train the autoencoder. adam = optimizers.Adam(lr)lstm_autoencoder.compile(loss='mse', optimizer=adam)cp = ModelCheckpoint(filepath="lstm_autoencoder_classifier.h5", save_best_only=True, verbose=0)tb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)lstm_autoencoder_history = lstm_autoencoder.fit(X_train_y0_scaled, X_train_y0_scaled, epochs=epochs, batch_size=batch, validation_data=(X_valid_y0_scaled, X_valid_y0_scaled), verbose=2).history Plotting the change in the loss over the epochs. plt.plot(lstm_autoencoder_history['loss'], linewidth=2, label='Train')plt.plot(lstm_autoencoder_history['val_loss'], linewidth=2, label='Valid')plt.legend(loc='upper right')plt.title('Model loss')plt.ylabel('Loss')plt.xlabel('Epoch')plt.show() Similar to the previous post [1], here we show how we can use an Autoencoder reconstruction error for the rare-event classification. We follow this concept: the autoencoder is expected to reconstruct a noif the reconstruction error is high, we will classify it as a sheet-break. We will need to determine the threshold for this. Also, note that here we will be using the entire validation set containing both y = 0 or 1. valid_x_predictions = lstm_autoencoder.predict(X_valid_scaled)mse = np.mean(np.power(flatten(X_valid_scaled) - flatten(valid_x_predictions), 2), axis=1)error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': y_valid.tolist()})precision_rt, recall_rt, threshold_rt = precision_recall_curve(error_df.True_class, error_df.Reconstruction_error)plt.plot(threshold_rt, precision_rt[1:], label="Precision",linewidth=5)plt.plot(threshold_rt, recall_rt[1:], label="Recall",linewidth=5)plt.title('Precision and recall for different threshold values')plt.xlabel('Threshold')plt.ylabel('Precision/Recall')plt.legend()plt.show() Note that we have to flatten the arrays to compute the mse. Now, we will perform classification on the test data. We should not estimate the classification threshold from the test data. It will result in overfitting. test_x_predictions = lstm_autoencoder.predict(X_test_scaled)mse = np.mean(np.power(flatten(X_test_scaled) - flatten(test_x_predictions), 2), axis=1)error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': y_test.tolist()})threshold_fixed = 0.3groups = error_df.groupby('True_class')fig, ax = plt.subplots()for name, group in groups: ax.plot(group.index, group.Reconstruction_error, marker='o', ms=3.5, linestyle='', label= "Break" if name == 1 else "Normal")ax.hlines(threshold_fixed, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')ax.legend()plt.title("Reconstruction error for different classes")plt.ylabel("Reconstruction error")plt.xlabel("Data point index")plt.show(); In Figure 4, the orange and blue dot above the threshold line represents the True Positive and False Positive, respectively. As we can see, we have good number of false positives. Let’s see the accuracy results. Confusion Matrix pred_y = [1 if e > threshold_fixed else 0 for e in error_df.Reconstruction_error.values]conf_matrix = confusion_matrix(error_df.True_class, pred_y)plt.figure(figsize=(6, 6))sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt="d");plt.title("Confusion matrix")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show() ROC Curve and AUC false_pos_rate, true_pos_rate, thresholds = roc_curve(error_df.True_class, error_df.Reconstruction_error)roc_auc = auc(false_pos_rate, true_pos_rate,)plt.plot(false_pos_rate, true_pos_rate, linewidth=5, label='AUC = %0.3f'% roc_auc)plt.plot([0,1],[0,1], linewidth=5)plt.xlim([-0.01, 1])plt.ylim([0, 1.01])plt.legend(loc='lower right')plt.title('Receiver operating characteristic curve (ROC)')plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show() We see approximately 10% improvement in the AUC compared to the dense layer Autoencoder in [1]. From the Confusion Matrix in Figure 5, we could predict 10 out of 39 break instances. As also discussed in [1], this is significant for a paper mill. However, the improvement we achieved in comparison to the dense layer Autoencoder is minor. The primary reason is LSTM model has more parameters to estimate. It becomes important to use regularization with LSTMs. Regularization and other model improvements will be discussed in the next post. github.com In the next article, we will learn tuning an Autoencoder. We will go over, CNN LSTM Autoencoder, Dropout layer, LSTM Dropout (Dropout_U and Dropout_W) Gaussian-dropout layer SELU activation, and alpha-dropout with SELU activation. This post continued the work on extreme rare event binary labeled data in [1]. To utilize the temporal patterns, LSTM Autoencoders is used to build a rare event classifier for a multivariate time-series process. Details about the data preprocessing steps for LSTM model are discussed. A simple LSTM Autoencoder model is trained and used for classification. Some improvement in the accuracy over a Dense Autoencoder is found. For further improvement, we will look at ways to improve an Autoencoder with Dropout and other techniques in the next post. It is recommended to read Step-by-step understanding LSTM Autoencoder layers to clear the LSTM network concepts. Extreme Rare Event Classification using Autoencoders in KerasRanjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717Time-series forecasting with deep learning & LSTM autoencodersComplete code: LSTM Autoencoder Extreme Rare Event Classification using Autoencoders in Keras Ranjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717 Time-series forecasting with deep learning & LSTM autoencoders Complete code: LSTM Autoencoder Disclaimer: The scope of this post is limited to a tutorial for building an LSTM Autoencoder and using it as a rare-event classifier. A practitioner is expected to achieve better results for this data by network tuning. The purpose of the article is helping Data Scientists implement an LSTM Autoencoder.
[ { "code": null, "e": 118, "s": 47, "text": "<<Download the free book, Understanding Deep Learning, to learn more>>" }, { "code": null, "e": 443, "s": 118, "text": "This post is a continuation of my previous post Extreme Rare Event Classification using Autoencoders. In the previous post, we talked about the challenges in an extremely rare event data with less than 1% positively labeled data. We built an Autoencoder Classifier for such processes using the concepts of Anomaly Detection." }, { "code": null, "e": 676, "s": 443, "text": "However, the data we have is a time series. But earlier we used a Dense layer Autoencoder that does not use the temporal features in the data. Therefore, in this post, we will improve on our approach by building an LSTM Autoencoder." }, { "code": null, "e": 697, "s": 676, "text": "Here, we will learn:" }, { "code": null, "e": 739, "s": 697, "text": "data preparation steps for an LSTM model," }, { "code": null, "e": 787, "s": 739, "text": "building and implementing LSTM autoencoder, and" }, { "code": null, "e": 841, "s": 787, "text": "using LSTM autoencoder for rare-event classification." }, { "code": null, "e": 862, "s": 841, "text": "Quick recap on LSTM:" }, { "code": null, "e": 998, "s": 862, "text": "LSTM is a type of Recurrent Neural Network (RNN). RNNs, in general, and LSTM, specifically, are used on sequential or time series data." }, { "code": null, "e": 1074, "s": 998, "text": "These models are capable of automatically extracting effect of past events." }, { "code": null, "e": 1167, "s": 1074, "text": "LSTM are known for its ability to extract both long- and short- term effects of pasts event." }, { "code": null, "e": 1377, "s": 1167, "text": "In the following, we will go directly to developing an LSTM Autoencoder. It is recommended to read Step-by-step understanding LSTM Autoencoder layers to better understand and further improve the network below." }, { "code": null, "e": 1668, "s": 1377, "text": "About the data problem in brief, we have real-world data on sheet breaks from a paper manufacturing. Our objective is to predict the break in advance. Please refer to Extreme Rare Event Classification using Autoencoders for the details on the data, problem, and the classification approach." }, { "code": null, "e": 2000, "s": 1668, "text": "In our problem, we have a multivariate time-series data. A multivariate time-series data contains multiple variables observed over a period of time. We will build an LSTM autoencoder on this multivariate time-series to perform rare-event classification. As described in [1], this is achieved by using an anomaly detection approach:" }, { "code": null, "e": 2065, "s": 2000, "text": "we build an autoencoder on the normal (negatively labeled) data," }, { "code": null, "e": 2101, "s": 2065, "text": "use it to reconstruct a new sample," }, { "code": null, "e": 2168, "s": 2101, "text": "if the reconstruction error is high, we label it as a sheet-break." }, { "code": null, "e": 2288, "s": 2168, "text": "LSTM requires few special data-preprocessing steps. In the following, we will give sufficient attention to these steps." }, { "code": null, "e": 2321, "s": 2288, "text": "Let’s get to the implementation." }, { "code": null, "e": 2386, "s": 2321, "text": "I like to put together the libraries and global constants first." }, { "code": null, "e": 3367, "s": 2386, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport numpy as npfrom pylab import rcParamsimport tensorflow as tffrom keras import optimizers, Sequentialfrom keras.models import Modelfrom keras.utils import plot_modelfrom keras.layers import Dense, LSTM, RepeatVector, TimeDistributedfrom keras.callbacks import ModelCheckpoint, TensorBoardfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, precision_recall_curvefrom sklearn.metrics import recall_score, classification_report, auc, roc_curvefrom sklearn.metrics import precision_recall_fscore_support, f1_scorefrom numpy.random import seedseed(7)from tensorflow import set_random_seedset_random_seed(11)from sklearn.model_selection import train_test_splitSEED = 123 #used to help randomly select the data pointsDATA_SPLIT_PCT = 0.2rcParams['figure.figsize'] = 8, 6LABELS = [\"Normal\",\"Break\"]" }, { "code": null, "e": 3587, "s": 3367, "text": "As mentioned before, LSTM requires a few specific steps in the data preparation. The input to LSTMs are 3-dimensional arrays created from the time-series data. This is an error prone step so we will look at the details." }, { "code": null, "e": 3645, "s": 3587, "text": "The data is taken from [2]. The link to the data is here." }, { "code": null, "e": 3745, "s": 3645, "text": "df = pd.read_csv(\"data/processminer-rare-event-mts - data.csv\") df.head(n=5) # visualize the data." }, { "code": null, "e": 4088, "s": 3745, "text": "As also mentioned in [1], the objective of this rare-event problem is to predict a sheet-break before it occurs. We will try to predict the break up to 4 minutes in advance. For this data, this is equivalent to shifting the labels up by two rows. It can be done directly with df.y=df.y.shift(-2). However, here we require to do the following," }, { "code": null, "e": 4220, "s": 4088, "text": "For any row n with label 1, make (n-2):(n-1) as 1. With this, we are teaching the classifier to predict up to 4 minutes ahead. And," }, { "code": null, "e": 4357, "s": 4220, "text": "remove row n. Row n is removed because we are not interested in teaching the classifier to predict a break when it has already happened." }, { "code": null, "e": 4423, "s": 4357, "text": "We develop the following function to perform this curve shifting." }, { "code": null, "e": 5670, "s": 4423, "text": "sign = lambda x: (1, -1)[x < 0]def curve_shift(df, shift_by): ''' This function will shift the binary labels in a dataframe. The curve shift will be with respect to the 1s. For example, if shift is -2, the following process will happen: if row n is labeled as 1, then - Make row (n+shift_by):(n+shift_by-1) = 1. - Remove row n. i.e. the labels will be shifted up to 2 rows up. Inputs: df A pandas dataframe with a binary labeled column. This labeled column should be named as 'y'. shift_by An integer denoting the number of rows to shift. Output df A dataframe with the binary labels shifted by shift. ''' vector = df['y'].copy() for s in range(abs(shift_by)): tmp = vector.shift(sign(shift_by)) tmp = tmp.fillna(0) vector += tmp labelcol = 'y' # Add vector to the df df.insert(loc=0, column=labelcol+'tmp', value=vector) # Remove the rows with labelcol == 1. df = df.drop(df[df[labelcol] == 1].index) # Drop labelcol and rename the tmp col as labelcol df = df.drop(labelcol, axis=1) df = df.rename(columns={labelcol+'tmp': labelcol}) # Make the labelcol binary df.loc[df[labelcol] > 0, labelcol] = 1 return df" }, { "code": null, "e": 5885, "s": 5670, "text": "We will now shift our data and verify if the shifting is correct. In the subsequent sections, we have few more test steps. It is recommended to use them to ensure the data preparation steps are working as expected." }, { "code": null, "e": 6339, "s": 5885, "text": "print('Before shifting') # Positive labeled rows before shifting.one_indexes = df.index[df['y'] == 1]display(df.iloc[(np.where(np.array(input_y) == 1)[0][0]-5):(np.where(np.array(input_y) == 1)[0][0]+1), ])# Shift the response column y by 2 rows to do a 4-min ahead prediction.df = curve_shift(df, shift_by = -2)print('After shifting') # Validating if the shift happened correctly.display(df.iloc[(one_indexes[0]-4):(one_indexes[0]+1), 0:5].head(n=5))" }, { "code": null, "e": 6858, "s": 6339, "text": "If we note here, we moved the positive label at 5/1/99 8:38 to n-1 and n-2 timestamps, and dropped row n. Also, there is a time difference of more than 2 minutes between a break row and the next row. This is because, when a break occurs, the machine stays in the break status for a while. During this time, we have y = 1 for consecutive rows. In the provided data, these consecutive break rows are deleted to prevent the classifier from learning to predict a break after it has already happened. Refer [2] for details." }, { "code": null, "e": 6959, "s": 6858, "text": "Before moving forward, we clean up the data by dropping the time, and two other categorical columns." }, { "code": null, "e": 7053, "s": 6959, "text": "# Remove time column, and the categorical columnsdf = df.drop(['time', 'x28', 'x61'], axis=1)" }, { "code": null, "e": 7233, "s": 7053, "text": "LSTM is a bit more demanding than other models. Significant amount of time and attention may go in preparing the data that fits an LSTM. However, it is generally worth the effort." }, { "code": null, "e": 7371, "s": 7233, "text": "The input data to an LSTM model is a 3-dimensional array. The shape of the array is samples x lookback x features. Let’s understand them," }, { "code": null, "e": 7469, "s": 7371, "text": "samples: This is simply the number of observations, or in other words, the number of data points." }, { "code": null, "e": 7609, "s": 7469, "text": "lookback: LSTM models are meant to look at the past. Meaning, at time t the LSTM will process data up to (t-lookback) to make a prediction." }, { "code": null, "e": 7675, "s": 7609, "text": "features: It is the number of features present in the input data." }, { "code": null, "e": 7725, "s": 7675, "text": "First, we will extract the features and response." }, { "code": null, "e": 7882, "s": 7725, "text": "input_X = df.loc[:, df.columns != 'y'].values # converts the df to a numpy arrayinput_y = df['y'].valuesn_features = input_X.shape[1] # number of features" }, { "code": null, "e": 8108, "s": 7882, "text": "The input_X here is a 2-dimensional array of size samples x features. We want to be able to transform such a 2D array into a 3D array of size: samples x lookback x features. Refer to Figure 1 above for a visual understanding." }, { "code": null, "e": 8154, "s": 8108, "text": "For that, we develop a function temporalize ." }, { "code": null, "e": 9141, "s": 8154, "text": "def temporalize(X, y, lookback): ''' Inputs X A 2D numpy array ordered by time of shape: (n_observations x n_features) y A 1D numpy array with indexes aligned with X, i.e. y[i] should correspond to X[i]. Shape: n_observations. lookback The window size to look back in the past records. Shape: a scalar. Output output_X A 3D numpy array of shape: ((n_observations-lookback-1) x lookback x n_features) output_y A 1D array of shape: (n_observations-lookback-1), aligned with X. ''' output_X = [] output_y = [] for i in range(len(X) - lookback - 1): t = [] for j in range(1, lookback + 1): # Gather the past records upto the lookback period t.append(X[[(i + j + 1)], :]) output_X.append(t) output_y.append(y[i + lookback + 1]) return np.squeeze(np.array(output_X)), np.array(output_y)" }, { "code": null, "e": 9233, "s": 9141, "text": "To test and demonstrate this function, we will look at an example below with lookback = 5 ." }, { "code": null, "e": 9712, "s": 9233, "text": "print('First instance of y = 1 in the original data')display(df.iloc[(np.where(np.array(input_y) == 1)[0][0]-5):(np.where(np.array(input_y) == 1)[0][0]+1), ])lookback = 5 # Equivalent to 10 min of past data.# Temporalize the dataX, y = temporalize(X = input_X, y = input_y, lookback = lookback)print('For the same instance of y = 1, we are keeping past 5 samples in the 3D predictor array, X.')display(pd.DataFrame(np.concatenate(X[np.where(np.array(y) == 1)[0][0]], axis=0 )))" }, { "code": null, "e": 9745, "s": 9712, "text": "What we are looking for here is," }, { "code": null, "e": 9785, "s": 9745, "text": "In the original data, y = 1 at row 257." }, { "code": null, "e": 9877, "s": 9785, "text": "With lookback = 5 we want the LSTM to look at the 5 rows before row 257 (including itself)." }, { "code": null, "e": 10103, "s": 9877, "text": "In the 3D array, X, each 2D block at X[i,:,:] denotes the prediction data that corresponds to y[i] . To draw an analogy, in regression y[i] corresponds to a 1D vector X[i,:] ; in LSTM y[i] corresponds to a 2D array X[i,:,:] ." }, { "code": null, "e": 10218, "s": 10103, "text": "This 2D block X[i,:,:] should have the predictors at input_X[i,:] and the previous rows up to the given lookback ." }, { "code": null, "e": 10345, "s": 10218, "text": "As we can see in the output above, the X[i,:,:] block in the bottom is the same as the five past rows of y=1 shown on the top." }, { "code": null, "e": 10481, "s": 10345, "text": "Similarly, this is applied for the entire data, for all y’s. The example here is shown for an instance of y=1 for easier visualization." }, { "code": null, "e": 10532, "s": 10481, "text": "This is straightforward with the sklearn function." }, { "code": null, "e": 10771, "s": 10532, "text": "X_train, X_test, y_train, y_test = train_test_split(np.array(X), np.array(y), test_size=DATA_SPLIT_PCT, random_state=SEED)X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=DATA_SPLIT_PCT, random_state=SEED)" }, { "code": null, "e": 10923, "s": 10771, "text": "For training the autoencoder, we will be using the X coming from only the negatively labeled data. Therefore, we separate the X corresponding to y = 0." }, { "code": null, "e": 11052, "s": 10923, "text": "X_train_y0 = X_train[y_train==0]X_train_y1 = X_train[y_train==1]X_valid_y0 = X_valid[y_valid==0]X_valid_y1 = X_valid[y_valid==1]" }, { "code": null, "e": 11138, "s": 11052, "text": "We will reshape the X’s into the required 3D dimension: sample x lookback x features." }, { "code": null, "e": 11627, "s": 11138, "text": "X_train = X_train.reshape(X_train.shape[0], lookback, n_features)X_train_y0 = X_train_y0.reshape(X_train_y0.shape[0], lookback, n_features)X_train_y1 = X_train_y1.reshape(X_train_y1.shape[0], lookback, n_features)X_valid = X_valid.reshape(X_valid.shape[0], lookback, n_features)X_valid_y0 = X_valid_y0.reshape(X_valid_y0.shape[0], lookback, n_features)X_valid_y1 = X_valid_y1.reshape(X_valid_y1.shape[0], lookback, n_features)X_test = X_test.reshape(X_test.shape[0], lookback, n_features)" }, { "code": null, "e": 11756, "s": 11627, "text": "It is usually better to use a standardized data (transformed to Gaussian with mean 0 and standard deviation 1) for autoencoders." }, { "code": null, "e": 12137, "s": 11756, "text": "One common standardization mistake is: we normalize the entire data and then split into train-test. This is incorrect. Test data should be completely unseen to anything during the modeling. We should, therefore, normalize the training data, and use its summary statistics to normalize the test data (for normalization, these statistics are the mean and variances of each feature)." }, { "code": null, "e": 12297, "s": 12137, "text": "Standardizing this data is a bit tricky. This is because the X matrices are 3D, and we want the standardization to happen with respect to the original 2D data." }, { "code": null, "e": 12335, "s": 12297, "text": "To do this, we will require two UDFs." }, { "code": null, "e": 12517, "s": 12335, "text": "flatten : This function will re-create the original 2D array from which the 3D arrays were created. This function is the inverse of temporalize, meaning X = flatten(temporalize(X))." }, { "code": null, "e": 12600, "s": 12517, "text": "scale : This function will scale a 3D array that we created as inputs to the LSTM." }, { "code": null, "e": 13403, "s": 12600, "text": "def flatten(X): ''' Flatten a 3D array. Input X A 3D array for lstm, where the array is sample x timesteps x features. Output flattened_X A 2D array, sample x features. ''' flattened_X = np.empty((X.shape[0], X.shape[2])) # sample x features array. for i in range(X.shape[0]): flattened_X[i] = X[i, (X.shape[1]-1), :] return(flattened_X)def scale(X, scaler): ''' Scale 3D array. Inputs X A 3D array for lstm, where the array is sample x timesteps x features. scaler A scaler object, e.g., sklearn.preprocessing.StandardScaler, sklearn.preprocessing.normalize Output X Scaled 3D array. ''' for i in range(X.shape[0]): X[i, :, :] = scaler.transform(X[i, :, :]) return X" }, { "code": null, "e": 13784, "s": 13403, "text": "Why didn’t we first normalize the original 2D data and then create the 3D arrays? Because, to do this we will: split the data into train and test, followed by their normalization. However, when we create the 3D arrays on the test data, we lose the initial rows of samples up till the lookback. Splitting into train-valid-test will cause this for both the validation and test sets." }, { "code": null, "e": 13970, "s": 13784, "text": "We will fit a Standardization object from sklearn. This function standardizes the data to Normal(0, 1). Note that we require to flatten the X_train_y0 array to pass to the fit function." }, { "code": null, "e": 14067, "s": 13970, "text": "# Initialize a scaler using the training data.scaler = StandardScaler().fit(flatten(X_train_y0))" }, { "code": null, "e": 14162, "s": 14067, "text": "We will use our UDF, scale, to standardize X_train_y0 with the fitted transform object scaler." }, { "code": null, "e": 14208, "s": 14162, "text": "X_train_y0_scaled = scale(X_train_y0, scaler)" }, { "code": null, "e": 14246, "s": 14208, "text": "Make sure the scale worked correctly?" }, { "code": null, "e": 14404, "s": 14246, "text": "A correct transformation of X_train will ensure that the means and variances of each column of the flattened X_train are 0 and 1, respectively. We test this." }, { "code": null, "e": 14529, "s": 14404, "text": "a = flatten(X_train_y0_scaled)print('colwise mean', np.mean(a, axis=0).round(6))print('colwise variance', np.var(a, axis=0))" }, { "code": null, "e": 14734, "s": 14529, "text": "All the means and variances outputted above are 0 and 1, respectively. Therefore, the scaling is correct. We will now scale the validation and test sets. We will again use the scaler object on these sets." }, { "code": null, "e": 14856, "s": 14734, "text": "X_valid_scaled = scale(X_valid, scaler)X_valid_y0_scaled = scale(X_valid_y0, scaler)X_test_scaled = scale(X_test, scaler)" }, { "code": null, "e": 14898, "s": 14856, "text": "We will, first, initialize few variables." }, { "code": null, "e": 15040, "s": 14898, "text": "timesteps = X_train_y0_scaled.shape[1] # equal to the lookbackn_features = X_train_y0_scaled.shape[2] # 59epochs = 200batch = 64lr = 0.0001" }, { "code": null, "e": 15080, "s": 15040, "text": "We, now, develop a simple architecture." }, { "code": null, "e": 15583, "s": 15080, "text": "lstm_autoencoder = Sequential()# Encoderlstm_autoencoder.add(LSTM(32, activation='relu', input_shape=(timesteps, n_features), return_sequences=True))lstm_autoencoder.add(LSTM(16, activation='relu', return_sequences=False))lstm_autoencoder.add(RepeatVector(timesteps))# Decoderlstm_autoencoder.add(LSTM(16, activation='relu', return_sequences=True))lstm_autoencoder.add(LSTM(32, activation='relu', return_sequences=True))lstm_autoencoder.add(TimeDistributed(Dense(n_features)))lstm_autoencoder.summary()" }, { "code": null, "e": 15851, "s": 15583, "text": "From the summary(), the total number of parameters are 5,331. This is about half of the training size. Hence, this is an appropriate model to fit. To have a bigger architecture, we will need to add regularization, e.g. Dropout, which will be covered in the next post." }, { "code": null, "e": 15887, "s": 15851, "text": "Now, we will train the autoencoder." }, { "code": null, "e": 16639, "s": 15887, "text": "adam = optimizers.Adam(lr)lstm_autoencoder.compile(loss='mse', optimizer=adam)cp = ModelCheckpoint(filepath=\"lstm_autoencoder_classifier.h5\", save_best_only=True, verbose=0)tb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)lstm_autoencoder_history = lstm_autoencoder.fit(X_train_y0_scaled, X_train_y0_scaled, epochs=epochs, batch_size=batch, validation_data=(X_valid_y0_scaled, X_valid_y0_scaled), verbose=2).history" }, { "code": null, "e": 16688, "s": 16639, "text": "Plotting the change in the loss over the epochs." }, { "code": null, "e": 16932, "s": 16688, "text": "plt.plot(lstm_autoencoder_history['loss'], linewidth=2, label='Train')plt.plot(lstm_autoencoder_history['val_loss'], linewidth=2, label='Valid')plt.legend(loc='upper right')plt.title('Model loss')plt.ylabel('Loss')plt.xlabel('Epoch')plt.show()" }, { "code": null, "e": 17211, "s": 16932, "text": "Similar to the previous post [1], here we show how we can use an Autoencoder reconstruction error for the rare-event classification. We follow this concept: the autoencoder is expected to reconstruct a noif the reconstruction error is high, we will classify it as a sheet-break." }, { "code": null, "e": 17353, "s": 17211, "text": "We will need to determine the threshold for this. Also, note that here we will be using the entire validation set containing both y = 0 or 1." }, { "code": null, "e": 18004, "s": 17353, "text": "valid_x_predictions = lstm_autoencoder.predict(X_valid_scaled)mse = np.mean(np.power(flatten(X_valid_scaled) - flatten(valid_x_predictions), 2), axis=1)error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': y_valid.tolist()})precision_rt, recall_rt, threshold_rt = precision_recall_curve(error_df.True_class, error_df.Reconstruction_error)plt.plot(threshold_rt, precision_rt[1:], label=\"Precision\",linewidth=5)plt.plot(threshold_rt, recall_rt[1:], label=\"Recall\",linewidth=5)plt.title('Precision and recall for different threshold values')plt.xlabel('Threshold')plt.ylabel('Precision/Recall')plt.legend()plt.show()" }, { "code": null, "e": 18064, "s": 18004, "text": "Note that we have to flatten the arrays to compute the mse." }, { "code": null, "e": 18118, "s": 18064, "text": "Now, we will perform classification on the test data." }, { "code": null, "e": 18221, "s": 18118, "text": "We should not estimate the classification threshold from the test data. It will result in overfitting." }, { "code": null, "e": 18974, "s": 18221, "text": "test_x_predictions = lstm_autoencoder.predict(X_test_scaled)mse = np.mean(np.power(flatten(X_test_scaled) - flatten(test_x_predictions), 2), axis=1)error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': y_test.tolist()})threshold_fixed = 0.3groups = error_df.groupby('True_class')fig, ax = plt.subplots()for name, group in groups: ax.plot(group.index, group.Reconstruction_error, marker='o', ms=3.5, linestyle='', label= \"Break\" if name == 1 else \"Normal\")ax.hlines(threshold_fixed, ax.get_xlim()[0], ax.get_xlim()[1], colors=\"r\", zorder=100, label='Threshold')ax.legend()plt.title(\"Reconstruction error for different classes\")plt.ylabel(\"Reconstruction error\")plt.xlabel(\"Data point index\")plt.show();" }, { "code": null, "e": 19154, "s": 18974, "text": "In Figure 4, the orange and blue dot above the threshold line represents the True Positive and False Positive, respectively. As we can see, we have good number of false positives." }, { "code": null, "e": 19186, "s": 19154, "text": "Let’s see the accuracy results." }, { "code": null, "e": 19203, "s": 19186, "text": "Confusion Matrix" }, { "code": null, "e": 19555, "s": 19203, "text": "pred_y = [1 if e > threshold_fixed else 0 for e in error_df.Reconstruction_error.values]conf_matrix = confusion_matrix(error_df.True_class, pred_y)plt.figure(figsize=(6, 6))sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt=\"d\");plt.title(\"Confusion matrix\")plt.ylabel('True class')plt.xlabel('Predicted class')plt.show()" }, { "code": null, "e": 19573, "s": 19555, "text": "ROC Curve and AUC" }, { "code": null, "e": 20041, "s": 19573, "text": "false_pos_rate, true_pos_rate, thresholds = roc_curve(error_df.True_class, error_df.Reconstruction_error)roc_auc = auc(false_pos_rate, true_pos_rate,)plt.plot(false_pos_rate, true_pos_rate, linewidth=5, label='AUC = %0.3f'% roc_auc)plt.plot([0,1],[0,1], linewidth=5)plt.xlim([-0.01, 1])plt.ylim([0, 1.01])plt.legend(loc='lower right')plt.title('Receiver operating characteristic curve (ROC)')plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show()" }, { "code": null, "e": 20379, "s": 20041, "text": "We see approximately 10% improvement in the AUC compared to the dense layer Autoencoder in [1]. From the Confusion Matrix in Figure 5, we could predict 10 out of 39 break instances. As also discussed in [1], this is significant for a paper mill. However, the improvement we achieved in comparison to the dense layer Autoencoder is minor." }, { "code": null, "e": 20580, "s": 20379, "text": "The primary reason is LSTM model has more parameters to estimate. It becomes important to use regularization with LSTMs. Regularization and other model improvements will be discussed in the next post." }, { "code": null, "e": 20591, "s": 20580, "text": "github.com" }, { "code": null, "e": 20666, "s": 20591, "text": "In the next article, we will learn tuning an Autoencoder. We will go over," }, { "code": null, "e": 20688, "s": 20666, "text": "CNN LSTM Autoencoder," }, { "code": null, "e": 20703, "s": 20688, "text": "Dropout layer," }, { "code": null, "e": 20742, "s": 20703, "text": "LSTM Dropout (Dropout_U and Dropout_W)" }, { "code": null, "e": 20765, "s": 20742, "text": "Gaussian-dropout layer" }, { "code": null, "e": 20786, "s": 20765, "text": "SELU activation, and" }, { "code": null, "e": 20822, "s": 20786, "text": "alpha-dropout with SELU activation." }, { "code": null, "e": 21371, "s": 20822, "text": "This post continued the work on extreme rare event binary labeled data in [1]. To utilize the temporal patterns, LSTM Autoencoders is used to build a rare event classifier for a multivariate time-series process. Details about the data preprocessing steps for LSTM model are discussed. A simple LSTM Autoencoder model is trained and used for classification. Some improvement in the accuracy over a Dense Autoencoder is found. For further improvement, we will look at ways to improve an Autoencoder with Dropout and other techniques in the next post." }, { "code": null, "e": 21484, "s": 21371, "text": "It is recommended to read Step-by-step understanding LSTM Autoencoder layers to clear the LSTM network concepts." }, { "code": null, "e": 21795, "s": 21484, "text": "Extreme Rare Event Classification using Autoencoders in KerasRanjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717Time-series forecasting with deep learning & LSTM autoencodersComplete code: LSTM Autoencoder" }, { "code": null, "e": 21857, "s": 21795, "text": "Extreme Rare Event Classification using Autoencoders in Keras" }, { "code": null, "e": 22014, "s": 21857, "text": "Ranjan, C., Mustonen, M., Paynabar, K., & Pourak, K. (2018). Dataset: Rare Event Classification in Multivariate Time Series. arXiv preprint arXiv:1809.10717" }, { "code": null, "e": 22077, "s": 22014, "text": "Time-series forecasting with deep learning & LSTM autoencoders" }, { "code": null, "e": 22109, "s": 22077, "text": "Complete code: LSTM Autoencoder" } ]
How to remove active nav-tab when click outside of nav-tab in Bootstrap ? - GeeksforGeeks
31 Jul, 2019 Bootstrap has the class called “collapse navbar-collapse” which collapses the navigation bar when the user changes the screen resolution. The java-script along-with it at the bottom of the code triggers the collapsed menu in such a way that when the user clicks the hamburger icon of the menu and navigates to the required link, it again collapses the menu after the click. The scroll event works only for scrollable elements and also for the browser window. It basically attaches a function to run which says that the navbar should collapse when a scroll event occurs, here, it being the navigation of user to different links on the navbar. Example: <!DOCTYPE html><html lang="en"> <head> <title>Navigation Bar</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <h2 style="text-align:center;">Collapsing Navbar</h2> <nav class="navbar navbar-expand-sm bg-success navbar-light"> <!-- Brand/logo --> <a class="navbar-brand" href="#"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/gfg_transparent_white_small.png" alt="logo" style="width:40px;"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapse_Navbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapse_Navbar"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" data-toggle="tab" href="#home"> Home </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#algo"> Algo </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#ds"> DS </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#lang"> Languages </a> </li> </ul> </div> </nav> </div> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane" id="home" role="tabpanel">A</div> <div class="tab-pane" id="algo" role="tabpanel">B</div> <div class="tab-pane" id="ds" role="tabpanel">C</div> <div class="tab-pane" id="lang" role="tabpanel">D</div> </div> <script>$(document).on('click', '.nav-link.active', function() { var href = $(this).attr('href').substring(1); //alert(href); $(this).removeClass('active'); $('.tab-pane[id="' + href + '"]').removeClass('active'); });$(document).mouseup(function(e) { var container = $("#tablist"); // target ID or class // if the target of the click isn't the container nor a descendant of the container if (!container.is(e.target) && container.has(e.target).length === 0) { // get Event here $('.active').removeClass('active'); }}); </script></body> </html> Output: Bootstrap-4 Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to change the background color of the active nav-item? How to Use Bootstrap with React? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 24438, "s": 24410, "text": "\n31 Jul, 2019" }, { "code": null, "e": 25080, "s": 24438, "text": "Bootstrap has the class called “collapse navbar-collapse” which collapses the navigation bar when the user changes the screen resolution. The java-script along-with it at the bottom of the code triggers the collapsed menu in such a way that when the user clicks the hamburger icon of the menu and navigates to the required link, it again collapses the menu after the click. The scroll event works only for scrollable elements and also for the browser window. It basically attaches a function to run which says that the navbar should collapse when a scroll event occurs, here, it being the navigation of user to different links on the navbar." }, { "code": null, "e": 25089, "s": 25080, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Navigation Bar</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <h2 style=\"text-align:center;\">Collapsing Navbar</h2> <nav class=\"navbar navbar-expand-sm bg-success navbar-light\"> <!-- Brand/logo --> <a class=\"navbar-brand\" href=\"#\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/gfg_transparent_white_small.png\" alt=\"logo\" style=\"width:40px;\"> </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#collapse_Navbar\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"collapse_Navbar\"> <ul class=\"navbar-nav\"> <li class=\"nav-item active\"> <a class=\"nav-link\" data-toggle=\"tab\" href=\"#home\"> Home </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"tab\" href=\"#algo\"> Algo </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"tab\" href=\"#ds\"> DS </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"tab\" href=\"#lang\"> Languages </a> </li> </ul> </div> </nav> </div> <!-- Tab panes --> <div class=\"tab-content\"> <div class=\"tab-pane\" id=\"home\" role=\"tabpanel\">A</div> <div class=\"tab-pane\" id=\"algo\" role=\"tabpanel\">B</div> <div class=\"tab-pane\" id=\"ds\" role=\"tabpanel\">C</div> <div class=\"tab-pane\" id=\"lang\" role=\"tabpanel\">D</div> </div> <script>$(document).on('click', '.nav-link.active', function() { var href = $(this).attr('href').substring(1); //alert(href); $(this).removeClass('active'); $('.tab-pane[id=\"' + href + '\"]').removeClass('active'); });$(document).mouseup(function(e) { var container = $(\"#tablist\"); // target ID or class // if the target of the click isn't the container nor a descendant of the container if (!container.is(e.target) && container.has(e.target).length === 0) { // get Event here $('.active').removeClass('active'); }}); </script></body> </html> ", "e": 28656, "s": 25089, "text": null }, { "code": null, "e": 28664, "s": 28656, "text": "Output:" }, { "code": null, "e": 28676, "s": 28664, "text": "Bootstrap-4" }, { "code": null, "e": 28691, "s": 28676, "text": "Bootstrap-Misc" }, { "code": null, "e": 28698, "s": 28691, "text": "Picked" }, { "code": null, "e": 28708, "s": 28698, "text": "Bootstrap" }, { "code": null, "e": 28725, "s": 28708, "text": "Web Technologies" }, { "code": null, "e": 28823, "s": 28725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28832, "s": 28823, "text": "Comments" }, { "code": null, "e": 28845, "s": 28832, "text": "Old Comments" }, { "code": null, "e": 28886, "s": 28845, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 28927, "s": 28886, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 28990, "s": 28927, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 29049, "s": 28990, "text": "How to change the background color of the active nav-item?" }, { "code": null, "e": 29082, "s": 29049, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 29124, "s": 29082, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29157, "s": 29124, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29207, "s": 29157, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29269, "s": 29207, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to check windows certificate expiry date using PowerShell?
To get the particular windows certificate expiry date from the particular store, we first need the full path of that certificate along with a thumbprint. If the thumbprint is not known to you, we can use the friendly name. With the thumbprint, Get-ChildItem Cert:\LocalMachine\root\0563B8630D62D75 | fl * When you run the above command, it will get all the details of the certificate having thumbprint 0563B8630D62D75. There you can see there are two fields listed, NotAfter and NotBefore which shows the expiry and start dates respectively. To filter them out, Get-ChildItem Cert:\LocalMachine\root\0563B8630D62D75 | Select FriendlyName, NotAfter,NotBefore FriendlyName NotAfter NotBefore ------------ -------- --------- DigiCert 11/9/2031 4:00:00 PM 11/9/2006 4:00:00 PM With the FriendlyName property, Get-ChildItem Cert:\LocalMachine\root\ | where{$_.FriendlyName -eq “DigiCert”} | Select FriendlyName, NotAfter,NotBefore To get the details from the remote computer, use the Invoke-Command. Invoke-Command -ComputerName Test1PC, Test2PC -ScriptBlock { Get-ChildItem Cert:\LocalMachine\root\ | where{$_.FriendlyName -eq “DigiCert”} | Select FriendlyName, NotAfter,NotBefore }
[ { "code": null, "e": 1285, "s": 1062, "text": "To get the particular windows certificate expiry date from the particular store, we first need the full path of that certificate along with a thumbprint. If the thumbprint is not known to you, we can use the friendly name." }, { "code": null, "e": 1306, "s": 1285, "text": "With the thumbprint," }, { "code": null, "e": 1367, "s": 1306, "text": "Get-ChildItem Cert:\\LocalMachine\\root\\0563B8630D62D75 | fl *" }, { "code": null, "e": 1481, "s": 1367, "text": "When you run the above command, it will get all the details of the certificate having thumbprint 0563B8630D62D75." }, { "code": null, "e": 1624, "s": 1481, "text": "There you can see there are two fields listed, NotAfter and NotBefore which shows the expiry and start dates respectively. To filter them out," }, { "code": null, "e": 1720, "s": 1624, "text": "Get-ChildItem Cert:\\LocalMachine\\root\\0563B8630D62D75 | Select FriendlyName, NotAfter,NotBefore" }, { "code": null, "e": 1844, "s": 1720, "text": "FriendlyName NotAfter NotBefore\n------------ -------- ---------\nDigiCert 11/9/2031 4:00:00 PM 11/9/2006 4:00:00 PM" }, { "code": null, "e": 1876, "s": 1844, "text": "With the FriendlyName property," }, { "code": null, "e": 1997, "s": 1876, "text": "Get-ChildItem Cert:\\LocalMachine\\root\\ | where{$_.FriendlyName -eq “DigiCert”} | Select FriendlyName, NotAfter,NotBefore" }, { "code": null, "e": 2066, "s": 1997, "text": "To get the details from the remote computer, use the Invoke-Command." }, { "code": null, "e": 2253, "s": 2066, "text": "Invoke-Command -ComputerName Test1PC, Test2PC -ScriptBlock {\n Get-ChildItem Cert:\\LocalMachine\\root\\ | where{$_.FriendlyName -eq “DigiCert”} | Select FriendlyName, NotAfter,NotBefore\n}" } ]
JavaScript Function Literals
JavaScript 1.2 introduces the concept of function literals which is another new way of defining functions. A function literal is an expression that defines an unnamed function. The syntax for a function literal is much like a function statement, except that it is used as an expression rather than a statement and no function name is required. <script type = "text/javascript"> <!-- var variablename = function(Argument List) { Function Body }; //--> </script> Syntactically, you can specify a function name while creating a literal function as follows. <script type = "text/javascript"> <!-- var variablename = function FunctionName(Argument List) { Function Body }; //--> </script> But this name does not have any significance, so it is not worthwhile. Try the following example. It shows the usage of function literals. <html> <head> <script type = "text/javascript"> <!-- var func = function(x,y) { return x*y }; function secondFunction() { var result; result = func(10,20); document.write ( result ); } //--> </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "secondFunction()" value = "Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html> Click the following button to call the function Use different parameters inside the function and then try... 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2643, "s": 2466, "text": "JavaScript 1.2 introduces the concept of function literals which is another new way of defining functions. A function literal is an expression that defines an unnamed function." }, { "code": null, "e": 2810, "s": 2643, "text": "The syntax for a function literal is much like a function statement, except that it is used as an expression rather than a statement and no function name is required." }, { "code": null, "e": 2956, "s": 2810, "text": "<script type = \"text/javascript\">\n <!--\n var variablename = function(Argument List) {\n Function Body \n };\n //-->\n</script>\n" }, { "code": null, "e": 3049, "s": 2956, "text": "Syntactically, you can specify a function name while creating a literal function as follows." }, { "code": null, "e": 3207, "s": 3049, "text": "<script type = \"text/javascript\">\n <!--\n var variablename = function FunctionName(Argument List) {\n Function Body\n };\n //-->\n</script>\n" }, { "code": null, "e": 3278, "s": 3207, "text": "But this name does not have any significance, so it is not worthwhile." }, { "code": null, "e": 3346, "s": 3278, "text": "Try the following example. It shows the usage of function literals." }, { "code": null, "e": 3996, "s": 3346, "text": "<html>\n <head>\n <script type = \"text/javascript\">\n <!--\n var func = function(x,y) { \n return x*y \n };\n function secondFunction() {\n var result;\n result = func(10,20);\n document.write ( result );\n }\n //-->\n </script>\n </head>\n \n <body>\n <p>Click the following button to call the function</p>\n \n <form>\n <input type = \"button\" onclick = \"secondFunction()\" value = \"Call Function\">\n </form>\n \n <p>Use different parameters inside the function and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 4044, "s": 3996, "text": "Click the following button to call the function" }, { "code": null, "e": 4105, "s": 4044, "text": "Use different parameters inside the function and then try..." }, { "code": null, "e": 4140, "s": 4105, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4154, "s": 4140, "text": " Anadi Sharma" }, { "code": null, "e": 4188, "s": 4154, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 4202, "s": 4188, "text": " Lets Kode It" }, { "code": null, "e": 4237, "s": 4202, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4254, "s": 4237, "text": " Frahaan Hussain" }, { "code": null, "e": 4289, "s": 4254, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4306, "s": 4289, "text": " Frahaan Hussain" }, { "code": null, "e": 4339, "s": 4306, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4367, "s": 4339, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4401, "s": 4367, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4429, "s": 4401, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4436, "s": 4429, "text": " Print" }, { "code": null, "e": 4447, "s": 4436, "text": " Add Notes" } ]
Vehicle Crashes & Machine Learning | by Abdishakur | Towards Data Science
Road accidents constitute a major problem in our societies around the world. The World Health Organization(WHO) estimated that 1.25 million deaths were related to road traffic injuries in the year 2010. For the year 2016, the USA alone had recorded 37, 461 motor vehicle crash-related deaths, averaging around 102 people per day. In Europe, the statistics also indicate that each minute, there are 50 road deaths recorded in the year 2017. Can machine learning help us understand the causes and the factors that affect car crash severity? In this article, we will do a complete machine learning pipeline from getting data through APIs, performing exploratory data analysis and formulating a real-world problem into a machine learning model. The complete code and Jupyter notebooks are available in this Github Gist. The whole process is carried out in Google Colab using their free GPU/TPU environment so you can directly open the notebook from Github and experiment it in Google Colab. The Crash Analysis System (CAS) data is available in different formats and APIs. It is simple to grab them through API interfaces, instead of downloading to your local machine. This is beneficial, as we will access the latest updated data every time we run the Jupyter notebook. I find this particular problem, the vehicle accidents, to be strongly related to location (Geography), so we will grab the Geojson file, instead of the usual CSV file, so that we can perform geographic data analysis without creating geometries from latitude and longitude and deal with coordinate reference systems and projections. We will use Geopandas library to read the data. If you are familiar with Pandas library, then you should feel home as Geopandas is built on top pandas. Geopandas is a high-level library that makes working with geographic data in Python easier as it allows pandas functionality and data types to allow spatial operations on geographic geometries. It is well integrated with the Python ecosystem and depends much on pandas, Matplotlib and shapely library for geometric operations. # Get the data from url and request it as json fileurl = 'https://opendata.arcgis.com/datasets/a163c5addf2c4b7f9079f08751bd2e1a_0.geojson'geojson = requests.get(url).json()# Read the data as GeodataFrame in Geopandascrs = {'init': 'epsg:3851'} # Coordinate reference system (CRS) for Newzealandgdf = gpd.GeoDataFrame.from_features(geojson['features'], crs=crs) In New Zealand, the total fatalities in crash accidents since the year 2000, up to 2018 is 6922. While the total number of serious injuries and minor injuries in car accidents reach 45044, 205895 respectively. Although this dataset records all crashes reported to NZ Police, we have to consider that all crashes are not reported to NZ police especially non-fatal crashes. Most of the crashes are non-injury crashes while fatal crashes are the least. In terms of fatality counts, most of the crashes have 0 fatality rate. Over the years, the overall statistics show a decline in crash severity and fatalities, but as you can see from the line chart, there seems to be an upward increase of fatality count from 2016. On the other hand, 2017 had a peak of Serious injuries and minor injuries. Roads and other related attributes also indicate crash severity as well as fatality level. So let us explore the relationship between them. In relation to fatality counts and the number of lanes in a road, 2 lanes seem to have a higher percentage than any other number. Straight roads seem to be less related to fatalities while most of the fatalities are related to some sort of road curvature (Easy, Moderate and Severe). Let us look at the traffic laws and their relationship with crash severity and fatality. The speed limit is a good measure to explore this relationship. 90 km/h is the deadliest speed limit followed by 100. Exploring the weather also shows that mist and strong wind have the highest percentage in terms of fatality counts. Rain, snow, and frost count also for a high percentage. The geographic data visualizations indicate clearly where clashes happen. As you might have expected, most crashes happen along roads and mostly in cities. Let us have a look at crashes aggregated in cluster map in Auckland. We can approach the modeling part of this problem in different ways. We could take it as a regression problem and predict the number of fatalities based on the attributes of the crash dataset. We can also approach it as a classification problem and predict the severity of the crash based on the crash dataset. In this example, I will approach it as a regression problem. Feel free to build a classification model if you want to give it a try. It will basically be the same approach. I will not do any feature engineering in this case, I think the attributes we have are enough to build a baseline, and we can always revisit this and do feature engineering later to boost our model accuracy. We first need to convert the categorical features into numerical values. We can use Sklearn library to do that like this: # Label encoderfrom sklearn.preprocessing import LabelEncoderlblE = LabelEncoder()for i in df: if df[i].dtype == 'object': lblE.fit(df[i]) df[i] = lblE.transform(df[i]) Then we split the data into dependent and independent variables as well as training and validation set to later evaluate our model results. # Let us split our data into training and validation setsX_train, X_test, y_train, y_test = train_test_split(df.drop('fatalCount', axis=1), df.fatalCount, test_size=0.33, random_state=42) Now we are ready to apply a machine learning model to our data. I usually start with Random Forest, a tree-based algorithm, which performs well on many datasets. m = RandomForestRegressor(n_estimators=50)m.fit(X_train, y_train)print_score(m)Output:RMSE Train:0.017368616661096157, RMSE Valid:0.042981327685985046, Accuracy Train: 0.977901052706869, Accuracy Valid: 0.8636075084646185 As you can the simple Random forest model gave us an accuracy of 86% on the validation set and after some initial fine-tuning and using feature importance selection, the model could be boosted to 87%. We could go further and do some improvements in our model, create new features or use some other algorithms to increase the model performance but for now, this is enough for this article purpose.Here are some of the most important features from our Random Forest model. I hope you have enjoyed reading this article. If you want to try and experiment the code, it is available as GitHub Gist and you can directly open the Notebook in Google Colab. You can reach me on Twitter @shakasom.
[ { "code": null, "e": 710, "s": 171, "text": "Road accidents constitute a major problem in our societies around the world. The World Health Organization(WHO) estimated that 1.25 million deaths were related to road traffic injuries in the year 2010. For the year 2016, the USA alone had recorded 37, 461 motor vehicle crash-related deaths, averaging around 102 people per day. In Europe, the statistics also indicate that each minute, there are 50 road deaths recorded in the year 2017. Can machine learning help us understand the causes and the factors that affect car crash severity?" }, { "code": null, "e": 1158, "s": 710, "text": "In this article, we will do a complete machine learning pipeline from getting data through APIs, performing exploratory data analysis and formulating a real-world problem into a machine learning model. The complete code and Jupyter notebooks are available in this Github Gist. The whole process is carried out in Google Colab using their free GPU/TPU environment so you can directly open the notebook from Github and experiment it in Google Colab." }, { "code": null, "e": 1769, "s": 1158, "text": "The Crash Analysis System (CAS) data is available in different formats and APIs. It is simple to grab them through API interfaces, instead of downloading to your local machine. This is beneficial, as we will access the latest updated data every time we run the Jupyter notebook. I find this particular problem, the vehicle accidents, to be strongly related to location (Geography), so we will grab the Geojson file, instead of the usual CSV file, so that we can perform geographic data analysis without creating geometries from latitude and longitude and deal with coordinate reference systems and projections." }, { "code": null, "e": 2248, "s": 1769, "text": "We will use Geopandas library to read the data. If you are familiar with Pandas library, then you should feel home as Geopandas is built on top pandas. Geopandas is a high-level library that makes working with geographic data in Python easier as it allows pandas functionality and data types to allow spatial operations on geographic geometries. It is well integrated with the Python ecosystem and depends much on pandas, Matplotlib and shapely library for geometric operations." }, { "code": null, "e": 2609, "s": 2248, "text": "# Get the data from url and request it as json fileurl = 'https://opendata.arcgis.com/datasets/a163c5addf2c4b7f9079f08751bd2e1a_0.geojson'geojson = requests.get(url).json()# Read the data as GeodataFrame in Geopandascrs = {'init': 'epsg:3851'} # Coordinate reference system (CRS) for Newzealandgdf = gpd.GeoDataFrame.from_features(geojson['features'], crs=crs)" }, { "code": null, "e": 3130, "s": 2609, "text": "In New Zealand, the total fatalities in crash accidents since the year 2000, up to 2018 is 6922. While the total number of serious injuries and minor injuries in car accidents reach 45044, 205895 respectively. Although this dataset records all crashes reported to NZ Police, we have to consider that all crashes are not reported to NZ police especially non-fatal crashes. Most of the crashes are non-injury crashes while fatal crashes are the least. In terms of fatality counts, most of the crashes have 0 fatality rate." }, { "code": null, "e": 3399, "s": 3130, "text": "Over the years, the overall statistics show a decline in crash severity and fatalities, but as you can see from the line chart, there seems to be an upward increase of fatality count from 2016. On the other hand, 2017 had a peak of Serious injuries and minor injuries." }, { "code": null, "e": 3823, "s": 3399, "text": "Roads and other related attributes also indicate crash severity as well as fatality level. So let us explore the relationship between them. In relation to fatality counts and the number of lanes in a road, 2 lanes seem to have a higher percentage than any other number. Straight roads seem to be less related to fatalities while most of the fatalities are related to some sort of road curvature (Easy, Moderate and Severe)." }, { "code": null, "e": 4030, "s": 3823, "text": "Let us look at the traffic laws and their relationship with crash severity and fatality. The speed limit is a good measure to explore this relationship. 90 km/h is the deadliest speed limit followed by 100." }, { "code": null, "e": 4202, "s": 4030, "text": "Exploring the weather also shows that mist and strong wind have the highest percentage in terms of fatality counts. Rain, snow, and frost count also for a high percentage." }, { "code": null, "e": 4358, "s": 4202, "text": "The geographic data visualizations indicate clearly where clashes happen. As you might have expected, most crashes happen along roads and mostly in cities." }, { "code": null, "e": 4427, "s": 4358, "text": "Let us have a look at crashes aggregated in cluster map in Auckland." }, { "code": null, "e": 5119, "s": 4427, "text": "We can approach the modeling part of this problem in different ways. We could take it as a regression problem and predict the number of fatalities based on the attributes of the crash dataset. We can also approach it as a classification problem and predict the severity of the crash based on the crash dataset. In this example, I will approach it as a regression problem. Feel free to build a classification model if you want to give it a try. It will basically be the same approach. I will not do any feature engineering in this case, I think the attributes we have are enough to build a baseline, and we can always revisit this and do feature engineering later to boost our model accuracy." }, { "code": null, "e": 5241, "s": 5119, "text": "We first need to convert the categorical features into numerical values. We can use Sklearn library to do that like this:" }, { "code": null, "e": 5427, "s": 5241, "text": "# Label encoderfrom sklearn.preprocessing import LabelEncoderlblE = LabelEncoder()for i in df: if df[i].dtype == 'object': lblE.fit(df[i]) df[i] = lblE.transform(df[i])" }, { "code": null, "e": 5567, "s": 5427, "text": "Then we split the data into dependent and independent variables as well as training and validation set to later evaluate our model results." }, { "code": null, "e": 5755, "s": 5567, "text": "# Let us split our data into training and validation setsX_train, X_test, y_train, y_test = train_test_split(df.drop('fatalCount', axis=1), df.fatalCount, test_size=0.33, random_state=42)" }, { "code": null, "e": 5917, "s": 5755, "text": "Now we are ready to apply a machine learning model to our data. I usually start with Random Forest, a tree-based algorithm, which performs well on many datasets." }, { "code": null, "e": 6139, "s": 5917, "text": "m = RandomForestRegressor(n_estimators=50)m.fit(X_train, y_train)print_score(m)Output:RMSE Train:0.017368616661096157, RMSE Valid:0.042981327685985046, Accuracy Train: 0.977901052706869, Accuracy Valid: 0.8636075084646185" }, { "code": null, "e": 6610, "s": 6139, "text": "As you can the simple Random forest model gave us an accuracy of 86% on the validation set and after some initial fine-tuning and using feature importance selection, the model could be boosted to 87%. We could go further and do some improvements in our model, create new features or use some other algorithms to increase the model performance but for now, this is enough for this article purpose.Here are some of the most important features from our Random Forest model." }, { "code": null, "e": 6787, "s": 6610, "text": "I hope you have enjoyed reading this article. If you want to try and experiment the code, it is available as GitHub Gist and you can directly open the Notebook in Google Colab." } ]
HTML | type Attribute - GeeksforGeeks
06 Jul, 2021 The HTML type Attribute is used to specify the type of button for <button> elements. It is also used in the <input> element to specify the type of input to display. For embed elements like link, object, script, source, and style used to specify the Internet Media Type. Syntax: <element type="value"> Supported Tags: <a> <area> <embed> <input> <link> <menu> <object> <script> <source> <style> The below example illustrates the use of type attribute in HTML: Example: html <!DOCTYPE html><html> <head> <title> HTML type Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h3>HTML type Attribute</h3> <form action="#" method="get"> Username: <input type="text" name="uname"> <br><br> Password: <input type="password" name="pwd"> <br><br> <button type="submit" value="submit"> Submit </button> <button type="reset" value="reset"> Reset </button> </form> </body></html> Output: Supported Browsers: The browser supported by HTML type attributes are listed below: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24589, "s": 24561, "text": "\n06 Jul, 2021" }, { "code": null, "e": 24861, "s": 24589, "text": "The HTML type Attribute is used to specify the type of button for <button> elements. It is also used in the <input> element to specify the type of input to display. For embed elements like link, object, script, source, and style used to specify the Internet Media Type. " }, { "code": null, "e": 24870, "s": 24861, "text": "Syntax: " }, { "code": null, "e": 24894, "s": 24870, "text": "<element type=\"value\"> " }, { "code": null, "e": 24911, "s": 24894, "text": "Supported Tags: " }, { "code": null, "e": 24915, "s": 24911, "text": "<a>" }, { "code": null, "e": 24922, "s": 24915, "text": "<area>" }, { "code": null, "e": 24930, "s": 24922, "text": "<embed>" }, { "code": null, "e": 24938, "s": 24930, "text": "<input>" }, { "code": null, "e": 24945, "s": 24938, "text": "<link>" }, { "code": null, "e": 24952, "s": 24945, "text": "<menu>" }, { "code": null, "e": 24961, "s": 24952, "text": "<object>" }, { "code": null, "e": 24970, "s": 24961, "text": "<script>" }, { "code": null, "e": 24979, "s": 24970, "text": "<source>" }, { "code": null, "e": 24987, "s": 24979, "text": "<style>" }, { "code": null, "e": 25052, "s": 24987, "text": "The below example illustrates the use of type attribute in HTML:" }, { "code": null, "e": 25062, "s": 25052, "text": "Example: " }, { "code": null, "e": 25067, "s": 25062, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML type Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h3>HTML type Attribute</h3> <form action=\"#\" method=\"get\"> Username: <input type=\"text\" name=\"uname\"> <br><br> Password: <input type=\"password\" name=\"pwd\"> <br><br> <button type=\"submit\" value=\"submit\"> Submit </button> <button type=\"reset\" value=\"reset\"> Reset </button> </form> </body></html> ", "e": 25757, "s": 25067, "text": null }, { "code": null, "e": 25767, "s": 25757, "text": "Output: " }, { "code": null, "e": 25852, "s": 25767, "text": "Supported Browsers: The browser supported by HTML type attributes are listed below: " }, { "code": null, "e": 25866, "s": 25852, "text": "Google Chrome" }, { "code": null, "e": 25884, "s": 25866, "text": "Internet Explorer" }, { "code": null, "e": 25892, "s": 25884, "text": "Firefox" }, { "code": null, "e": 25899, "s": 25892, "text": "Safari" }, { "code": null, "e": 25905, "s": 25899, "text": "Opera" }, { "code": null, "e": 26044, "s": 25907, "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": 26064, "s": 26044, "text": "hritikbhatnagar2182" }, { "code": null, "e": 26080, "s": 26064, "text": "HTML-Attributes" }, { "code": null, "e": 26085, "s": 26080, "text": "HTML" }, { "code": null, "e": 26102, "s": 26085, "text": "Web Technologies" }, { "code": null, "e": 26107, "s": 26102, "text": "HTML" }, { "code": null, "e": 26205, "s": 26107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26214, "s": 26205, "text": "Comments" }, { "code": null, "e": 26227, "s": 26214, "text": "Old Comments" }, { "code": null, "e": 26275, "s": 26227, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26312, "s": 26275, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26362, "s": 26312, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26412, "s": 26362, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26436, "s": 26412, "text": "REST API (Introduction)" }, { "code": null, "e": 26492, "s": 26436, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26525, "s": 26492, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26568, "s": 26525, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26629, "s": 26568, "text": "Difference between var, let and const keywords in JavaScript" } ]
C# Program to display a string in reverse alphabetic order
Set a string array and convert it to character array − string str = "Amit"; char[] arr = str.ToCharArray(); Now, use the Reverse method to display the above string in reverse alphabetic order − Array.Reverse(arr); Here is the complete code − Live Demo using System; using System.Linq; using System.IO; class Program { static void Main() { string str = "Amit"; char[] arr = str.ToCharArray(); Console.WriteLine("Original String: "+str); // Reverse Array.Reverse(arr); Console.WriteLine("Reversed String: "+new string(arr)); } } Original String: Amit Reversed String: timA
[ { "code": null, "e": 1117, "s": 1062, "text": "Set a string array and convert it to character array −" }, { "code": null, "e": 1170, "s": 1117, "text": "string str = \"Amit\";\nchar[] arr = str.ToCharArray();" }, { "code": null, "e": 1256, "s": 1170, "text": "Now, use the Reverse method to display the above string in reverse alphabetic order −" }, { "code": null, "e": 1276, "s": 1256, "text": "Array.Reverse(arr);" }, { "code": null, "e": 1304, "s": 1276, "text": "Here is the complete code −" }, { "code": null, "e": 1315, "s": 1304, "text": " Live Demo" }, { "code": null, "e": 1632, "s": 1315, "text": "using System;\nusing System.Linq;\nusing System.IO;\nclass Program {\n static void Main() {\n string str = \"Amit\";\n char[] arr = str.ToCharArray();\n Console.WriteLine(\"Original String: \"+str);\n // Reverse\n Array.Reverse(arr);\n Console.WriteLine(\"Reversed String: \"+new string(arr));\n }\n}" }, { "code": null, "e": 1676, "s": 1632, "text": "Original String: Amit\nReversed String: timA" } ]
Popularity Ranking of Programming Languages | by Vahid Vaezian | Towards Data Science
There has never been a unanimous agreement on what the most popular programming languages are, and probably never will be. Yet we believe that there is merit in trying to come up with ways to rank the popularity of programming languages. It helps us to see the trends over time and gives us hints as to what to focus on. In the ever-changing world of technology, it is important to stay ahead of the curve. The analysis that follows is on data from Stack Overflow (SO). The SO website is arguably the biggest and the most popular Q&A website in the developer community (“developer” in the general sense of anyone who writes code). Currently, it has about 10 million visits per day and has had 12.6 million users who were active on the website beyond simple visits (e.g. posted a question/answer or made a comment/edit). We believe that ranking programming languages based on their popularity on SO is a good estimate of their actual popularity. We have calculated a popularity index for programming languages which is the average of three factors: Number of questions asked daily, number of daily distinct users and view count of questions. To identify a language, we consider the tags assigned to the posts. For example for JavaScript we consider the following tags: tags like ‘%javascript%’ or tags like ‘%jquery%’ or tags like ‘%js>%’ — tag ends with ‘js’ e.g. ‘node.js’or tags like ‘%extjs%’ — includes ‘extjs4’ and others For daily question count, we calculate the number of questions that were asked in each day for each programming language. To calculate the Distinct Users Count, we count the number of distinct users who asked/answered a question, posted a comment or edited a question/answer for each programming language in each day. Every post in SO has an attribute showing how many times the post has been viewed. We normalize this number by dividing it by the number of days that the post has been visible. This gives us the Normalized View Count for that post. We then sum the view counts for each programming language for each day. Note that since the variance of the normalized view count for the recent posts is high, we do not include these posts in the calculation. As a result, this measure is two month behind the other two measures. For further details on how the index is calculated see the GitHub repository. Let’s now explore trends using some Line Charts. Note that you can follow along using this interactive dashboard (from the top-right choose the desired filters.) Note: The following analysis is based on the SO data until the end of July 2020. The data behind the interactive dashboard will be updated each quarter. Starting with the top five most popular programming languages (based on our index), if we look at the yearly data, we see that JavaScript has held the crown for the past 10 years, although Python now a close second, is catching up quickly. The other three, namely Java, SQL and HTML/CSS have been slightly declining in popularity in the past seven years. If we look at the quarterly data, JavaScript is still at the top, although it is neck and neck with Python. The interesting part is the monthly data. June 2020 was the first time in the past 10 years that JavaScript lost its position at the top. Given the pace of growth of Python, it seems Python is going to be a top contender for some time. Data Science has been a hot topic in recent years. In the following chart we can see that Python and R have had high growth rates in the past years. Scala has kept its popularity more or less, and Julia’s popularity has been minuscule so far. Note that to make it a fair comparison, only the data science part of Python is considered for this comparison (see the GitHub Repository for more details). Among Relational Database Management Systems (RDBMS), MySQL is still the most popular, although its popularity has been declining. The same applies to SQL Server. On the other hand, PostgreSQL’s popularity has been constantly increasing in the past decade. There hasn’t been much change in popularity of Oracle. Regarding Mobile development languages, we see some considerable changes. Swift was introduced in June 2014, which caused a major hit on popularity of Objective-C. A similar story happened for Kotlin and Java (mobile). In 2017 Google included Kotlin in Android Studio and Since May 2019, it is the preferred programming language for Android app developers. To see the calculated popularity index in action over the past 10 years, click on the play button at the bottom-left of the chart below. You can also use the slider at the bottom to move to a specific time range. Note: The chart will be updated with new data one month after the beginning of every quarter (as explained above, the ViewCount measure lags two month behind the other two measures, which causes the index to lag two month behind as well, as it is the average of the three measures). If you have suggestions for improving the index, please let me know, either in the comments or by creating an issue in the GitHub Repository.
[ { "code": null, "e": 579, "s": 172, "text": "There has never been a unanimous agreement on what the most popular programming languages are, and probably never will be. Yet we believe that there is merit in trying to come up with ways to rank the popularity of programming languages. It helps us to see the trends over time and gives us hints as to what to focus on. In the ever-changing world of technology, it is important to stay ahead of the curve." }, { "code": null, "e": 1117, "s": 579, "text": "The analysis that follows is on data from Stack Overflow (SO). The SO website is arguably the biggest and the most popular Q&A website in the developer community (“developer” in the general sense of anyone who writes code). Currently, it has about 10 million visits per day and has had 12.6 million users who were active on the website beyond simple visits (e.g. posted a question/answer or made a comment/edit). We believe that ranking programming languages based on their popularity on SO is a good estimate of their actual popularity." }, { "code": null, "e": 1440, "s": 1117, "text": "We have calculated a popularity index for programming languages which is the average of three factors: Number of questions asked daily, number of daily distinct users and view count of questions. To identify a language, we consider the tags assigned to the posts. For example for JavaScript we consider the following tags:" }, { "code": null, "e": 1602, "s": 1440, "text": " tags like ‘%javascript%’ or tags like ‘%jquery%’ or tags like ‘%js>%’ — tag ends with ‘js’ e.g. ‘node.js’or tags like ‘%extjs%’ — includes ‘extjs4’ and others" }, { "code": null, "e": 1724, "s": 1602, "text": "For daily question count, we calculate the number of questions that were asked in each day for each programming language." }, { "code": null, "e": 1920, "s": 1724, "text": "To calculate the Distinct Users Count, we count the number of distinct users who asked/answered a question, posted a comment or edited a question/answer for each programming language in each day." }, { "code": null, "e": 2432, "s": 1920, "text": "Every post in SO has an attribute showing how many times the post has been viewed. We normalize this number by dividing it by the number of days that the post has been visible. This gives us the Normalized View Count for that post. We then sum the view counts for each programming language for each day. Note that since the variance of the normalized view count for the recent posts is high, we do not include these posts in the calculation. As a result, this measure is two month behind the other two measures." }, { "code": null, "e": 2510, "s": 2432, "text": "For further details on how the index is calculated see the GitHub repository." }, { "code": null, "e": 2672, "s": 2510, "text": "Let’s now explore trends using some Line Charts. Note that you can follow along using this interactive dashboard (from the top-right choose the desired filters.)" }, { "code": null, "e": 2825, "s": 2672, "text": "Note: The following analysis is based on the SO data until the end of July 2020. The data behind the interactive dashboard will be updated each quarter." }, { "code": null, "e": 3180, "s": 2825, "text": "Starting with the top five most popular programming languages (based on our index), if we look at the yearly data, we see that JavaScript has held the crown for the past 10 years, although Python now a close second, is catching up quickly. The other three, namely Java, SQL and HTML/CSS have been slightly declining in popularity in the past seven years." }, { "code": null, "e": 3524, "s": 3180, "text": "If we look at the quarterly data, JavaScript is still at the top, although it is neck and neck with Python. The interesting part is the monthly data. June 2020 was the first time in the past 10 years that JavaScript lost its position at the top. Given the pace of growth of Python, it seems Python is going to be a top contender for some time." }, { "code": null, "e": 3924, "s": 3524, "text": "Data Science has been a hot topic in recent years. In the following chart we can see that Python and R have had high growth rates in the past years. Scala has kept its popularity more or less, and Julia’s popularity has been minuscule so far. Note that to make it a fair comparison, only the data science part of Python is considered for this comparison (see the GitHub Repository for more details)." }, { "code": null, "e": 4236, "s": 3924, "text": "Among Relational Database Management Systems (RDBMS), MySQL is still the most popular, although its popularity has been declining. The same applies to SQL Server. On the other hand, PostgreSQL’s popularity has been constantly increasing in the past decade. There hasn’t been much change in popularity of Oracle." }, { "code": null, "e": 4593, "s": 4236, "text": "Regarding Mobile development languages, we see some considerable changes. Swift was introduced in June 2014, which caused a major hit on popularity of Objective-C. A similar story happened for Kotlin and Java (mobile). In 2017 Google included Kotlin in Android Studio and Since May 2019, it is the preferred programming language for Android app developers." }, { "code": null, "e": 4806, "s": 4593, "text": "To see the calculated popularity index in action over the past 10 years, click on the play button at the bottom-left of the chart below. You can also use the slider at the bottom to move to a specific time range." }, { "code": null, "e": 5089, "s": 4806, "text": "Note: The chart will be updated with new data one month after the beginning of every quarter (as explained above, the ViewCount measure lags two month behind the other two measures, which causes the index to lag two month behind as well, as it is the average of the three measures)." } ]
How to change the background color of a plot created by using plot function in R?
To change the focus of a plot we can do multiple things and one such thing is changing the background of the plot. If the background color of a plot is different than white then obviously it will get attention of the readers because this is unusual as most of the times the plots have white backgrounds, hence if we want to attract readers on the plot then we might use this technique. It can be done by using par(bg= "color_name"). Creating a simple histogram − Live Demo > x<-rnorm(100) > hist(x) Creating histogram with different background colors − > par(bg="green") > hist(x) > par(bg="yellow") > hist(x) par(bg="blue") > hist(x)
[ { "code": null, "e": 1495, "s": 1062, "text": "To change the focus of a plot we can do multiple things and one such thing is changing the background of the plot. If the background color of a plot is different than white then obviously it will get attention of the readers because this is unusual as most of the times the plots have white backgrounds, hence if we want to attract readers on the plot then we might use this technique. It can be done by using par(bg= \"color_name\")." }, { "code": null, "e": 1525, "s": 1495, "text": "Creating a simple histogram −" }, { "code": null, "e": 1536, "s": 1525, "text": " Live Demo" }, { "code": null, "e": 1562, "s": 1536, "text": "> x<-rnorm(100)\n> hist(x)" }, { "code": null, "e": 1616, "s": 1562, "text": "Creating histogram with different background colors −" }, { "code": null, "e": 1644, "s": 1616, "text": "> par(bg=\"green\")\n> hist(x)" }, { "code": null, "e": 1673, "s": 1644, "text": "> par(bg=\"yellow\")\n> hist(x)" }, { "code": null, "e": 1698, "s": 1673, "text": "par(bg=\"blue\")\n> hist(x)" } ]
jQuery Examples - $("ul li:first")
"$("ul li:first")" get only the first <li> element of the <ul>. Here is the simple syntax to use this selector − $("tagname child-element:first") Here is the description of all the parameters used by this selector − tagname − Any standard container tag name like ol, ul etc. tagname − Any standard container tag name like ol, ul etc. child-element − list items li child-element − list items li :first − filter to get first element. :first − filter to get first element. This selector returns the first element. <html> <head> <title>The Selector Example</title> <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { /* Select link with an id of first and a class of big.*/ $("ul li:first").css("background-color", "yellow"); }); </script> </head> <body> <ul> <li><a id = "first" class="big" href="#">Big</a></li> <li><a id = "first" class="medium" href="#">Medium</a></li> <li><a id = "first" class="small" href="#">Small</a></li> </ul> </body> </html> This will produce following result − Big Medium Small Print Add Notes Bookmark this page
[ { "code": null, "e": 1752, "s": 1688, "text": "\"$(\"ul li:first\")\" get only the first <li> element of the <ul>." }, { "code": null, "e": 1801, "s": 1752, "text": "Here is the simple syntax to use this selector −" }, { "code": null, "e": 1835, "s": 1801, "text": "$(\"tagname child-element:first\")\n" }, { "code": null, "e": 1905, "s": 1835, "text": "Here is the description of all the parameters used by this selector −" }, { "code": null, "e": 1964, "s": 1905, "text": "tagname − Any standard container tag name like ol, ul etc." }, { "code": null, "e": 2023, "s": 1964, "text": "tagname − Any standard container tag name like ol, ul etc." }, { "code": null, "e": 2053, "s": 2023, "text": "child-element − list items li" }, { "code": null, "e": 2083, "s": 2053, "text": "child-element − list items li" }, { "code": null, "e": 2121, "s": 2083, "text": ":first − filter to get first element." }, { "code": null, "e": 2159, "s": 2121, "text": ":first − filter to get first element." }, { "code": null, "e": 2200, "s": 2159, "text": "This selector returns the first element." }, { "code": null, "e": 2929, "s": 2200, "text": "<html>\n <head>\n <title>The Selector Example</title>\n <script type = \"text/javascript\" \n src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n /* Select link with an id of first and a class of big.*/\n $(\"ul li:first\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <ul>\n <li><a id = \"first\" class=\"big\" href=\"#\">Big</a></li>\n <li><a id = \"first\" class=\"medium\" href=\"#\">Medium</a></li>\n <li><a id = \"first\" class=\"small\" href=\"#\">Small</a></li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 2966, "s": 2929, "text": "This will produce following result −" }, { "code": null, "e": 2970, "s": 2966, "text": "Big" }, { "code": null, "e": 2977, "s": 2970, "text": "Medium" }, { "code": null, "e": 2983, "s": 2977, "text": "Small" }, { "code": null, "e": 2990, "s": 2983, "text": " Print" }, { "code": null, "e": 3001, "s": 2990, "text": " Add Notes" } ]
3 Steps to Build and Deploy your NLP model as a Microservice on Azure | by Ricardo Carvalho | Towards Data Science
After spending countless hours training your model, you now need to make it available for other applications or services. Depending on how you approach the deployment to the cloud, this process may take several hours or just a few minutes. More importantly, your deployment choice should be based on your scalability and budget requirements. Here I will show a quick way to deploy an NLP model to Azure as a microservice directly using Python code (instead of building containers) for deployment. This tutorial works for any ML model, not just NLP. The setup I will show is probably one of the simplest available, and the settings will have a minimal cost to maintain. Before you start, make sure to prepare as follows: Create an Azure account with a valid Subscription: If you don’t already have an account with a valid subscription, you can create a new account for Azure and receive two weeks of trial.Install Azure CLI: We will use commands to create the resources on Azure (instead of using the Azure Portal UI). This approach has the most maintainability, as we have scripts for each resource we create, making it easier to evolve and reproduce. Click here to see how to install Azure CLI.Install Azure Functions Core Tools: Before deploying our microservice to Azure, we will create and test everything locally without spending a dime. Azure Functions Core Tools will provide the local development experience for designing, developing, testing, running, and debugging Azure Functions. Click here to see how to install it. Create an Azure account with a valid Subscription: If you don’t already have an account with a valid subscription, you can create a new account for Azure and receive two weeks of trial. Install Azure CLI: We will use commands to create the resources on Azure (instead of using the Azure Portal UI). This approach has the most maintainability, as we have scripts for each resource we create, making it easier to evolve and reproduce. Click here to see how to install Azure CLI. Install Azure Functions Core Tools: Before deploying our microservice to Azure, we will create and test everything locally without spending a dime. Azure Functions Core Tools will provide the local development experience for designing, developing, testing, running, and debugging Azure Functions. Click here to see how to install it. Below we will go through the following three steps: 1. Create and test an Azure function locally2. Create the resources on Azure3. Deploy the function to Azure Ideally, we want to test everything out locally before deploying to Azure. Local testing lets us make sure everything is working and won’t spend any unnecessary money debugging online. That being said, using monitoring tools like “Application Insights” on Azure is still worth it and necessary to make sure your apps are running smoothly. But that’s outside the scope of this post. Below, first, we use the terminal to create and activate the python environment. Then we create a FunctionApp project locally, which will organize multiple functions together. Finally, we create the function getSentiment which will be triggered by an HTTP request. # Create and activate an environmentpython3 -m venv .venvsource .venv/bin/activate# Create a FunctionApp Project Locallyfunc init --worker-runtime python# Create a Functionfunc new --name getSentiment --template "HTTP trigger" --authlevel anonymous Now we can edit the function in the file getSentiment\__init__.py , adding the following code (modify for your model): The function created above will receive a text parameter and return the input text with the corresponding sentiment analysis obtained from the Hugging Face’s model “DistilBERT base uncased finetuned SST-2”. Since we’ve added a few libraries for the code above, make sure to update your requirements.txt file as follows: And after that, install the libraries on the environment we created above: pip install -r requirements.txt Now we are ready to test the function locally. To do this, you need to run: func start You should get something like this as the output in the terminal: So we can go to the URL listed above, passing the parameter text to test the model. For example: http://localhost:7071/api/getSentiment?text=I%20really%20like%20bananas The output should be: Now that everything is running locally as expected, we can create the resources needed on Azure and deploy our microservice. You can do the following steps via the Azure Portal by clicking on each resource and choosing the settings. But that is hard to maintain. So, in general, it’s recommended to use scripts. So below, we run a few commands in the terminal to create the following resources, which are the minimum needed to deploy a Function on Azure: Resource Group: A resource group is just a way to hold multiple related resources for an Azure solution. Storage Account: An Azure storage account centralizes data objects, such as blobs, file shares, queues, tables, and disks. It gives a unique namespace for storage. We will use the standard type (cheapest), mostly recommended for files, blobs, and tables. FunctionApp: A function app is a resource that groups functions as a logical unit for easier management, deployment, scaling, and sharing of resources. We will use the most basic consumption plan to host the function app and specify the storage account created. # Login to your Azure Account from the Command Lineaz login# Create a Resource Groupaz group create --name rgSENT --location westus# Create a Storage Accountaz storage account create --name stracc2sent --location westus --resource-group rgSENT --sku Standard_LRS# Create a FunctionAppaz functionapp create --name nlpfuncsa --resource-group rgSENT --os-type linux --consumption-plan-location westus --storage-account stracc2sent --functions-version 3 --runtime python --runtime-version 3.9 Please note that I used nlpfuncsaas the name of the FunctionApp. This name must be unique on Azure, so please use a different one for your app. If the command above returns Operation returned an invalid status ‘Conflict’ , this might be the reason. So make sure to use a different (and unique) name for your FunctionApp. Finally, we can deploy our local project’s code to the FunctionApp created on Azure, using the following command: func azure functionapp publish nlpfuncsa This process takes a while due to the remote building. In the end, you should get the following result: Now you can go to the URL listed above, passing the parameter text to test your model. For example: https://nlpfuncsa.azurewebsites.net/api/getsentiment?text=I%20really%20like%20bananas The output should be the same that we saw locally: That’s it. Now you have your NLP model deployed to Azure. Here’s the Github repository with all the code submitted to Azure. If you want to delete everything you created, go to the Azure Portal, find “Resource Group”, click on the resource group created (if you followed this post exactly, it should be “rgSENT”), then click on “Delete resource group”. Since all of the resources created are under the same resource group, doing the above will delete everything. If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission.
[ { "code": null, "e": 294, "s": 172, "text": "After spending countless hours training your model, you now need to make it available for other applications or services." }, { "code": null, "e": 514, "s": 294, "text": "Depending on how you approach the deployment to the cloud, this process may take several hours or just a few minutes. More importantly, your deployment choice should be based on your scalability and budget requirements." }, { "code": null, "e": 669, "s": 514, "text": "Here I will show a quick way to deploy an NLP model to Azure as a microservice directly using Python code (instead of building containers) for deployment." }, { "code": null, "e": 721, "s": 669, "text": "This tutorial works for any ML model, not just NLP." }, { "code": null, "e": 841, "s": 721, "text": "The setup I will show is probably one of the simplest available, and the settings will have a minimal cost to maintain." }, { "code": null, "e": 892, "s": 841, "text": "Before you start, make sure to prepare as follows:" }, { "code": null, "e": 1701, "s": 892, "text": "Create an Azure account with a valid Subscription: If you don’t already have an account with a valid subscription, you can create a new account for Azure and receive two weeks of trial.Install Azure CLI: We will use commands to create the resources on Azure (instead of using the Azure Portal UI). This approach has the most maintainability, as we have scripts for each resource we create, making it easier to evolve and reproduce. Click here to see how to install Azure CLI.Install Azure Functions Core Tools: Before deploying our microservice to Azure, we will create and test everything locally without spending a dime. Azure Functions Core Tools will provide the local development experience for designing, developing, testing, running, and debugging Azure Functions. Click here to see how to install it." }, { "code": null, "e": 1887, "s": 1701, "text": "Create an Azure account with a valid Subscription: If you don’t already have an account with a valid subscription, you can create a new account for Azure and receive two weeks of trial." }, { "code": null, "e": 2178, "s": 1887, "text": "Install Azure CLI: We will use commands to create the resources on Azure (instead of using the Azure Portal UI). This approach has the most maintainability, as we have scripts for each resource we create, making it easier to evolve and reproduce. Click here to see how to install Azure CLI." }, { "code": null, "e": 2512, "s": 2178, "text": "Install Azure Functions Core Tools: Before deploying our microservice to Azure, we will create and test everything locally without spending a dime. Azure Functions Core Tools will provide the local development experience for designing, developing, testing, running, and debugging Azure Functions. Click here to see how to install it." }, { "code": null, "e": 2564, "s": 2512, "text": "Below we will go through the following three steps:" }, { "code": null, "e": 2672, "s": 2564, "text": "1. Create and test an Azure function locally2. Create the resources on Azure3. Deploy the function to Azure" }, { "code": null, "e": 3054, "s": 2672, "text": "Ideally, we want to test everything out locally before deploying to Azure. Local testing lets us make sure everything is working and won’t spend any unnecessary money debugging online. That being said, using monitoring tools like “Application Insights” on Azure is still worth it and necessary to make sure your apps are running smoothly. But that’s outside the scope of this post." }, { "code": null, "e": 3319, "s": 3054, "text": "Below, first, we use the terminal to create and activate the python environment. Then we create a FunctionApp project locally, which will organize multiple functions together. Finally, we create the function getSentiment which will be triggered by an HTTP request." }, { "code": null, "e": 3568, "s": 3319, "text": "# Create and activate an environmentpython3 -m venv .venvsource .venv/bin/activate# Create a FunctionApp Project Locallyfunc init --worker-runtime python# Create a Functionfunc new --name getSentiment --template \"HTTP trigger\" --authlevel anonymous" }, { "code": null, "e": 3687, "s": 3568, "text": "Now we can edit the function in the file getSentiment\\__init__.py , adding the following code (modify for your model):" }, { "code": null, "e": 3894, "s": 3687, "text": "The function created above will receive a text parameter and return the input text with the corresponding sentiment analysis obtained from the Hugging Face’s model “DistilBERT base uncased finetuned SST-2”." }, { "code": null, "e": 4007, "s": 3894, "text": "Since we’ve added a few libraries for the code above, make sure to update your requirements.txt file as follows:" }, { "code": null, "e": 4082, "s": 4007, "text": "And after that, install the libraries on the environment we created above:" }, { "code": null, "e": 4114, "s": 4082, "text": "pip install -r requirements.txt" }, { "code": null, "e": 4190, "s": 4114, "text": "Now we are ready to test the function locally. To do this, you need to run:" }, { "code": null, "e": 4201, "s": 4190, "text": "func start" }, { "code": null, "e": 4267, "s": 4201, "text": "You should get something like this as the output in the terminal:" }, { "code": null, "e": 4364, "s": 4267, "text": "So we can go to the URL listed above, passing the parameter text to test the model. For example:" }, { "code": null, "e": 4436, "s": 4364, "text": "http://localhost:7071/api/getSentiment?text=I%20really%20like%20bananas" }, { "code": null, "e": 4458, "s": 4436, "text": "The output should be:" }, { "code": null, "e": 4583, "s": 4458, "text": "Now that everything is running locally as expected, we can create the resources needed on Azure and deploy our microservice." }, { "code": null, "e": 4770, "s": 4583, "text": "You can do the following steps via the Azure Portal by clicking on each resource and choosing the settings. But that is hard to maintain. So, in general, it’s recommended to use scripts." }, { "code": null, "e": 4913, "s": 4770, "text": "So below, we run a few commands in the terminal to create the following resources, which are the minimum needed to deploy a Function on Azure:" }, { "code": null, "e": 5018, "s": 4913, "text": "Resource Group: A resource group is just a way to hold multiple related resources for an Azure solution." }, { "code": null, "e": 5273, "s": 5018, "text": "Storage Account: An Azure storage account centralizes data objects, such as blobs, file shares, queues, tables, and disks. It gives a unique namespace for storage. We will use the standard type (cheapest), mostly recommended for files, blobs, and tables." }, { "code": null, "e": 5535, "s": 5273, "text": "FunctionApp: A function app is a resource that groups functions as a logical unit for easier management, deployment, scaling, and sharing of resources. We will use the most basic consumption plan to host the function app and specify the storage account created." }, { "code": null, "e": 6024, "s": 5535, "text": "# Login to your Azure Account from the Command Lineaz login# Create a Resource Groupaz group create --name rgSENT --location westus# Create a Storage Accountaz storage account create --name stracc2sent --location westus --resource-group rgSENT --sku Standard_LRS# Create a FunctionAppaz functionapp create --name nlpfuncsa --resource-group rgSENT --os-type linux --consumption-plan-location westus --storage-account stracc2sent --functions-version 3 --runtime python --runtime-version 3.9" }, { "code": null, "e": 6345, "s": 6024, "text": "Please note that I used nlpfuncsaas the name of the FunctionApp. This name must be unique on Azure, so please use a different one for your app. If the command above returns Operation returned an invalid status ‘Conflict’ , this might be the reason. So make sure to use a different (and unique) name for your FunctionApp." }, { "code": null, "e": 6459, "s": 6345, "text": "Finally, we can deploy our local project’s code to the FunctionApp created on Azure, using the following command:" }, { "code": null, "e": 6500, "s": 6459, "text": "func azure functionapp publish nlpfuncsa" }, { "code": null, "e": 6604, "s": 6500, "text": "This process takes a while due to the remote building. In the end, you should get the following result:" }, { "code": null, "e": 6704, "s": 6604, "text": "Now you can go to the URL listed above, passing the parameter text to test your model. For example:" }, { "code": null, "e": 6790, "s": 6704, "text": "https://nlpfuncsa.azurewebsites.net/api/getsentiment?text=I%20really%20like%20bananas" }, { "code": null, "e": 6841, "s": 6790, "text": "The output should be the same that we saw locally:" }, { "code": null, "e": 6966, "s": 6841, "text": "That’s it. Now you have your NLP model deployed to Azure. Here’s the Github repository with all the code submitted to Azure." }, { "code": null, "e": 7304, "s": 6966, "text": "If you want to delete everything you created, go to the Azure Portal, find “Resource Group”, click on the resource group created (if you followed this post exactly, it should be “rgSENT”), then click on “Delete resource group”. Since all of the resources created are under the same resource group, doing the above will delete everything." } ]
How to set the font of the content present in the ComboBox in C#? - GeeksforGeeks
27 Jun, 2019 In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the font of the content present in your ComboBox by using Font Property. You can set this property using two different methods: 1. Design-Time: It is the easiest method to set the font of the elements present in the ComboBox control using the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ComboBox control to set the font of the elements present in the ComboBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the font of the elements present in the ComboBox programmatically with the help of given syntax: public virtual System.Drawing.Font Font { get; set; } Here, the Font indicates the font applied to the ComboBox content. Following steps are used to set the font of the ComboBox elements: Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); // Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); Step 2: After creating ComboBox, set the font of the ComboBox elements.// Set the font of the combobox elements mybox.Font = new Font("Chiller", 12); // Set the font of the combobox elements mybox.Font = new Font("Chiller", 12); Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form this.Controls.Add(mybox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Font = new Font("Chiller", 12); l.Size = new Size(99, 18); l.Text = "Select city name"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = "My_Cobo_Box"; mybox.Font = new Font("Chiller", 12); mybox.Items.Add("Mumbai"); mybox.Items.Add("Delhi"); mybox.Items.Add("Jaipur"); mybox.Items.Add("Kolkata"); mybox.Items.Add("Bengaluru"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output: // Add this ComboBox to form this.Controls.Add(mybox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Font = new Font("Chiller", 12); l.Size = new Size(99, 18); l.Text = "Select city name"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = "My_Cobo_Box"; mybox.Font = new Font("Chiller", 12); mybox.Items.Add("Mumbai"); mybox.Items.Add("Delhi"); mybox.Items.Add("Jaipur"); mybox.Items.Add("Kolkata"); mybox.Items.Add("Bengaluru"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# Top 50 C# Interview Questions & Answers Partial Classes in C# HashSet in C# with Examples C# | Inheritance C# | How to insert an element in an Array? C# | List Class Lambda Expressions in C# C# | Generics - Introduction What is Regular Expression in C#?
[ { "code": null, "e": 24222, "s": 24194, "text": "\n27 Jun, 2019" }, { "code": null, "e": 24617, "s": 24222, "text": "In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the font of the content present in your ComboBox by using Font Property. You can set this property using two different methods:" }, { "code": null, "e": 24749, "s": 24617, "text": "1. Design-Time: It is the easiest method to set the font of the elements present in the ComboBox control using the following steps:" }, { "code": null, "e": 24865, "s": 24749, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 25046, "s": 24865, "text": "Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need." }, { "code": null, "e": 25192, "s": 25046, "text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to set the font of the elements present in the ComboBox.Output:" }, { "code": null, "e": 25200, "s": 25192, "text": "Output:" }, { "code": null, "e": 25389, "s": 25200, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the font of the elements present in the ComboBox programmatically with the help of given syntax:" }, { "code": null, "e": 25443, "s": 25389, "text": "public virtual System.Drawing.Font Font { get; set; }" }, { "code": null, "e": 25577, "s": 25443, "text": "Here, the Font indicates the font applied to the ComboBox content. Following steps are used to set the font of the ComboBox elements:" }, { "code": null, "e": 25746, "s": 25577, "text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 25822, "s": 25746, "text": "// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 25973, "s": 25822, "text": "Step 2: After creating ComboBox, set the font of the ComboBox elements.// Set the font of the combobox elements\nmybox.Font = new Font(\"Chiller\", 12);\n" }, { "code": null, "e": 26053, "s": 25973, "text": "// Set the font of the combobox elements\nmybox.Font = new Font(\"Chiller\", 12);\n" }, { "code": null, "e": 27417, "s": 26053, "text": "Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Font = new Font(\"Chiller\", 12); l.Size = new Size(99, 18); l.Text = \"Select city name\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = \"My_Cobo_Box\"; mybox.Font = new Font(\"Chiller\", 12); mybox.Items.Add(\"Mumbai\"); mybox.Items.Add(\"Delhi\"); mybox.Items.Add(\"Jaipur\"); mybox.Items.Add(\"Kolkata\"); mybox.Items.Add(\"Bengaluru\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:" }, { "code": null, "e": 27473, "s": 27417, "text": "// Add this ComboBox to form\nthis.Controls.Add(mybox);\n" }, { "code": null, "e": 27482, "s": 27473, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Font = new Font(\"Chiller\", 12); l.Size = new Size(99, 18); l.Text = \"Select city name\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = \"My_Cobo_Box\"; mybox.Font = new Font(\"Chiller\", 12); mybox.Items.Add(\"Mumbai\"); mybox.Items.Add(\"Delhi\"); mybox.Items.Add(\"Jaipur\"); mybox.Items.Add(\"Kolkata\"); mybox.Items.Add(\"Bengaluru\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}", "e": 28706, "s": 27482, "text": null }, { "code": null, "e": 28714, "s": 28706, "text": "Output:" }, { "code": null, "e": 28717, "s": 28714, "text": "C#" }, { "code": null, "e": 28815, "s": 28717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28824, "s": 28815, "text": "Comments" }, { "code": null, "e": 28837, "s": 28824, "text": "Old Comments" }, { "code": null, "e": 28860, "s": 28837, "text": "Extension Method in C#" }, { "code": null, "e": 28900, "s": 28860, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28922, "s": 28900, "text": "Partial Classes in C#" }, { "code": null, "e": 28950, "s": 28922, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28967, "s": 28950, "text": "C# | Inheritance" }, { "code": null, "e": 29010, "s": 28967, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 29026, "s": 29010, "text": "C# | List Class" }, { "code": null, "e": 29051, "s": 29026, "text": "Lambda Expressions in C#" }, { "code": null, "e": 29080, "s": 29051, "text": "C# | Generics - Introduction" } ]
Become a video analysis expert using python | by Kunal Dhariwal | Towards Data Science
The task of generating highlights for any sport is quite tedious and difficult. It involves a lot of tech and other software, hardware needs. You also need to invest in a lot of time to do it. If you’re into such a video company or department then it is okay, but if you’re a normal user just like me, you wouldn’t want to do it that way. I’ll be using python to get this done in just a few steps. There won’t be any external software involved. Just pure python and Also, we don’t have to rely on machine learning or deep learning techniques to do it. We will be using speech analysis for this task. When something exciting happens during a game, there is a rise in the commentator’s voice. Let’s take cricket for example. Whenever a batsman hits a boundary or a bowler takes a wicket, there is a rise in the commentator’s voice. Both the audience and the commentators have high pitch during that event. We can use these changes in audio to capture interesting moments from a video. The process we’ll be following is added down below: Input the video file Extract the audio Break the audio into chunks Compute short-time energy of every chunk Classify every chunk as excitement or not (based on a threshold value) Merge all the excitement-clips to form the video highlights Generate the final video highlights Remember, We won’t use any external software here. 1. Download the video input: https://bit.ly/2lKfVa6 You can choose any other video of your favourite sport too. 2. Extract the audio: For extracting the audio and other operations on the video file, we’ll be using a package called moviepy. a. Install the package. pip install moviepy b. Input the file path in this code. # AudioExtract.pyimport moviepy.editor as mpclip = mp.VideoFileClip("filepath//videoplayback.mp4").subclip(1, 1380)clip.audio.write_audiofile("filepath//audio.wav") In the above code, mp.VideoFileClip is where we feed in our video file. subclip, we specify the the time limit for which we need the audio. *Not required if you want full clip audio* audio.write_audiofile, we specify the output path and file name here. That’s it, We have extracted the audio in 2 simple steps. 3. Break the audio into chunks: We’ll be using the audio that we just extracted in step 2. librosa is a python package for music and audio analysis. import librosaimport IPython.display as ipdfilename = "filepath\\audio.wav"# loading the file with a sampling ratex, sr = librosa.load(filename, sr=16000)# To get duration of the audio clip in minutesint(librosa.get_duration(x, sr) / 60)# Dividing into chunks of 5 seconds max_slice = 10window_length = max_slice * sr# Playing the audio chunka = x[21 * window_length:22 * window_length]ipd.Audio(a, rate=sr) Here, I’ve set the sampling rate as 16000, you can set it as per your convenience and requirement. Now, I have divided the audio into chunks of 10 seconds each, since we want to find out whether a particular audio chunk contains a rise in the audio voice or not. You can set time limit as per your choice, Try different time limits for different outputs. Also, we’ll play the audio chunk just for a check. 4. Compute short-time energy of every chunk: import numpy as nps_energy = np.array([sum(abs(x[i:i + window_length] ** 2)) for i in range(0, len(x), window_length)]) The energy or power of an audio signal refers to the loudness of the sound. It is computed by the sum of the square of the amplitude of an audio signal in the time domain. When energy is computed for a chunk of an entire audio signal, then it is known as Short Time Energy. Let’s plot it: import matplotlib.pyplot as pltplt.hist(s_energy)plt.show() 5. Classify every chunk as excitement or not (based on a threshold value): import pandas as pddf = pd.DataFrame(columns=['energy', 'start', 'end'])thresh = 180row_index = 0for i in range(len(s_energy)): value = energy[i] if value >= thresh: i = np.where(s_energy == value)[0] df.loc[row_index, 'energy'] = value df.loc[row_index, 'start'] = i[0] * 10 df.loc[row_index, 'end'] = (i[0] + 1) * 10 row_index = row_index + 1 I am creating a dataframe based on the energy data. I chose the threshold as 180, you can choose it as per your choice and by seeing the graph above. And then merge consecutive time intervals of audio clips into one: temp = []i = 0j = 0n = len(df) - 2m = len(df) - 1while (i <= n): j = i + 1 while (j <= m): if (df['end'][i] == df['start'][j]): df.loc[i, 'end'] = df.loc[j, 'end'] temp.append(j) j = j + 1 else: i = j breakdf.drop(temp, axis=0, inplace=True)print(df) 6. Merge all the excitement-clips to form the video highlights start = np.array(df['start'])end = np.array(df['end'])for i in range(len(df)): if i != 0: start_lim = start[i] - 10 else: start_lim = start[i] end_lim = end[i] filename = "highlight" + str(i + 1) + ".mp4" ffmpeg_extract_subclip("filepath//videofile.mp4", start_lim, end_lim, targetname=filename) This code will generate the highlights from each of the chunk based on the amplitude and then it will save these files in your system. You are not done yet, You have to merge all 14 files into one to actually create the highlights. 7. Generate the final video highlights # Final_joined.pyfrom moviepy.editor import VideoFileClip, concatenate_videoclipsclip1 = VideoFileClip("filename\\highlight1.mp4")clip2 = VideoFileClip("filename\\highlight2.mp4")clip3 = VideoFileClip("filename\\highlight3.mp4")clip4 = VideoFileClip("filename\\highlight5.mp4")clip5 = VideoFileClip("filename\\highlight6.mp4")clip6 = VideoFileClip("filename\\highlight7.mp4")clip7 = VideoFileClip("filename\\highlight8.mp4")clip8 = VideoFileClip("filename\\highlight9.mp4")clip9 = VideoFileClip("filename\\highlight10.mp4")clip10 = VideoFileClip("filename\\highlight11.mp4")clip11= VideoFileClip("filename\\highlight12.mp4")clip12 = VideoFileClip("filename\\highlight13.mp4")clip13= VideoFileClip("filename\\highlight14.mp4")clip14= VideoFileClip("filename\\highlight4.mp4")final_clip = concatenate_videoclips([clip1,clip2,clip3,clip4,clip5,clip6,clip7,clip8,clip9,clip9,clip10,clip11,clip12,clip13,clip14])final_clip.write_videofile("filepath\\Final_Highlights.mp4") We are using concatenate to merge all the files into one. After this the final file will be generated. Complete code: https://bit.ly/2lE55mi You can get the video demo here: https://bit.ly/2lDEd5V If you encounter any error or need any help, you can always comment or ping me on LinkedIn. LinkedIn: https://bit.ly/2u4YPoF Reference: https://bit.ly/2kry0tB I hope that this has helped you to enhance your knowledge base :) Follow me for more! Thanks for your read and valuable time!
[ { "code": null, "e": 771, "s": 171, "text": "The task of generating highlights for any sport is quite tedious and difficult. It involves a lot of tech and other software, hardware needs. You also need to invest in a lot of time to do it. If you’re into such a video company or department then it is okay, but if you’re a normal user just like me, you wouldn’t want to do it that way. I’ll be using python to get this done in just a few steps. There won’t be any external software involved. Just pure python and Also, we don’t have to rely on machine learning or deep learning techniques to do it. We will be using speech analysis for this task." }, { "code": null, "e": 1154, "s": 771, "text": "When something exciting happens during a game, there is a rise in the commentator’s voice. Let’s take cricket for example. Whenever a batsman hits a boundary or a bowler takes a wicket, there is a rise in the commentator’s voice. Both the audience and the commentators have high pitch during that event. We can use these changes in audio to capture interesting moments from a video." }, { "code": null, "e": 1206, "s": 1154, "text": "The process we’ll be following is added down below:" }, { "code": null, "e": 1227, "s": 1206, "text": "Input the video file" }, { "code": null, "e": 1245, "s": 1227, "text": "Extract the audio" }, { "code": null, "e": 1273, "s": 1245, "text": "Break the audio into chunks" }, { "code": null, "e": 1314, "s": 1273, "text": "Compute short-time energy of every chunk" }, { "code": null, "e": 1385, "s": 1314, "text": "Classify every chunk as excitement or not (based on a threshold value)" }, { "code": null, "e": 1445, "s": 1385, "text": "Merge all the excitement-clips to form the video highlights" }, { "code": null, "e": 1481, "s": 1445, "text": "Generate the final video highlights" }, { "code": null, "e": 1532, "s": 1481, "text": "Remember, We won’t use any external software here." }, { "code": null, "e": 1584, "s": 1532, "text": "1. Download the video input: https://bit.ly/2lKfVa6" }, { "code": null, "e": 1644, "s": 1584, "text": "You can choose any other video of your favourite sport too." }, { "code": null, "e": 1666, "s": 1644, "text": "2. Extract the audio:" }, { "code": null, "e": 1772, "s": 1666, "text": "For extracting the audio and other operations on the video file, we’ll be using a package called moviepy." }, { "code": null, "e": 1796, "s": 1772, "text": "a. Install the package." }, { "code": null, "e": 1816, "s": 1796, "text": "pip install moviepy" }, { "code": null, "e": 1853, "s": 1816, "text": "b. Input the file path in this code." }, { "code": null, "e": 2018, "s": 1853, "text": "# AudioExtract.pyimport moviepy.editor as mpclip = mp.VideoFileClip(\"filepath//videoplayback.mp4\").subclip(1, 1380)clip.audio.write_audiofile(\"filepath//audio.wav\")" }, { "code": null, "e": 2090, "s": 2018, "text": "In the above code, mp.VideoFileClip is where we feed in our video file." }, { "code": null, "e": 2201, "s": 2090, "text": "subclip, we specify the the time limit for which we need the audio. *Not required if you want full clip audio*" }, { "code": null, "e": 2271, "s": 2201, "text": "audio.write_audiofile, we specify the output path and file name here." }, { "code": null, "e": 2329, "s": 2271, "text": "That’s it, We have extracted the audio in 2 simple steps." }, { "code": null, "e": 2361, "s": 2329, "text": "3. Break the audio into chunks:" }, { "code": null, "e": 2420, "s": 2361, "text": "We’ll be using the audio that we just extracted in step 2." }, { "code": null, "e": 2478, "s": 2420, "text": "librosa is a python package for music and audio analysis." }, { "code": null, "e": 2886, "s": 2478, "text": "import librosaimport IPython.display as ipdfilename = \"filepath\\\\audio.wav\"# loading the file with a sampling ratex, sr = librosa.load(filename, sr=16000)# To get duration of the audio clip in minutesint(librosa.get_duration(x, sr) / 60)# Dividing into chunks of 5 seconds max_slice = 10window_length = max_slice * sr# Playing the audio chunka = x[21 * window_length:22 * window_length]ipd.Audio(a, rate=sr)" }, { "code": null, "e": 3292, "s": 2886, "text": "Here, I’ve set the sampling rate as 16000, you can set it as per your convenience and requirement. Now, I have divided the audio into chunks of 10 seconds each, since we want to find out whether a particular audio chunk contains a rise in the audio voice or not. You can set time limit as per your choice, Try different time limits for different outputs. Also, we’ll play the audio chunk just for a check." }, { "code": null, "e": 3337, "s": 3292, "text": "4. Compute short-time energy of every chunk:" }, { "code": null, "e": 3457, "s": 3337, "text": "import numpy as nps_energy = np.array([sum(abs(x[i:i + window_length] ** 2)) for i in range(0, len(x), window_length)])" }, { "code": null, "e": 3731, "s": 3457, "text": "The energy or power of an audio signal refers to the loudness of the sound. It is computed by the sum of the square of the amplitude of an audio signal in the time domain. When energy is computed for a chunk of an entire audio signal, then it is known as Short Time Energy." }, { "code": null, "e": 3746, "s": 3731, "text": "Let’s plot it:" }, { "code": null, "e": 3806, "s": 3746, "text": "import matplotlib.pyplot as pltplt.hist(s_energy)plt.show()" }, { "code": null, "e": 3881, "s": 3806, "text": "5. Classify every chunk as excitement or not (based on a threshold value):" }, { "code": null, "e": 4267, "s": 3881, "text": "import pandas as pddf = pd.DataFrame(columns=['energy', 'start', 'end'])thresh = 180row_index = 0for i in range(len(s_energy)): value = energy[i] if value >= thresh: i = np.where(s_energy == value)[0] df.loc[row_index, 'energy'] = value df.loc[row_index, 'start'] = i[0] * 10 df.loc[row_index, 'end'] = (i[0] + 1) * 10 row_index = row_index + 1" }, { "code": null, "e": 4484, "s": 4267, "text": "I am creating a dataframe based on the energy data. I chose the threshold as 180, you can choose it as per your choice and by seeing the graph above. And then merge consecutive time intervals of audio clips into one:" }, { "code": null, "e": 4810, "s": 4484, "text": "temp = []i = 0j = 0n = len(df) - 2m = len(df) - 1while (i <= n): j = i + 1 while (j <= m): if (df['end'][i] == df['start'][j]): df.loc[i, 'end'] = df.loc[j, 'end'] temp.append(j) j = j + 1 else: i = j breakdf.drop(temp, axis=0, inplace=True)print(df)" }, { "code": null, "e": 4873, "s": 4810, "text": "6. Merge all the excitement-clips to form the video highlights" }, { "code": null, "e": 5198, "s": 4873, "text": "start = np.array(df['start'])end = np.array(df['end'])for i in range(len(df)): if i != 0: start_lim = start[i] - 10 else: start_lim = start[i] end_lim = end[i] filename = \"highlight\" + str(i + 1) + \".mp4\" ffmpeg_extract_subclip(\"filepath//videofile.mp4\", start_lim, end_lim, targetname=filename)" }, { "code": null, "e": 5430, "s": 5198, "text": "This code will generate the highlights from each of the chunk based on the amplitude and then it will save these files in your system. You are not done yet, You have to merge all 14 files into one to actually create the highlights." }, { "code": null, "e": 5469, "s": 5430, "text": "7. Generate the final video highlights" }, { "code": null, "e": 6437, "s": 5469, "text": "# Final_joined.pyfrom moviepy.editor import VideoFileClip, concatenate_videoclipsclip1 = VideoFileClip(\"filename\\\\highlight1.mp4\")clip2 = VideoFileClip(\"filename\\\\highlight2.mp4\")clip3 = VideoFileClip(\"filename\\\\highlight3.mp4\")clip4 = VideoFileClip(\"filename\\\\highlight5.mp4\")clip5 = VideoFileClip(\"filename\\\\highlight6.mp4\")clip6 = VideoFileClip(\"filename\\\\highlight7.mp4\")clip7 = VideoFileClip(\"filename\\\\highlight8.mp4\")clip8 = VideoFileClip(\"filename\\\\highlight9.mp4\")clip9 = VideoFileClip(\"filename\\\\highlight10.mp4\")clip10 = VideoFileClip(\"filename\\\\highlight11.mp4\")clip11= VideoFileClip(\"filename\\\\highlight12.mp4\")clip12 = VideoFileClip(\"filename\\\\highlight13.mp4\")clip13= VideoFileClip(\"filename\\\\highlight14.mp4\")clip14= VideoFileClip(\"filename\\\\highlight4.mp4\")final_clip = concatenate_videoclips([clip1,clip2,clip3,clip4,clip5,clip6,clip7,clip8,clip9,clip9,clip10,clip11,clip12,clip13,clip14])final_clip.write_videofile(\"filepath\\\\Final_Highlights.mp4\")" }, { "code": null, "e": 6540, "s": 6437, "text": "We are using concatenate to merge all the files into one. After this the final file will be generated." }, { "code": null, "e": 6578, "s": 6540, "text": "Complete code: https://bit.ly/2lE55mi" }, { "code": null, "e": 6634, "s": 6578, "text": "You can get the video demo here: https://bit.ly/2lDEd5V" }, { "code": null, "e": 6726, "s": 6634, "text": "If you encounter any error or need any help, you can always comment or ping me on LinkedIn." }, { "code": null, "e": 6759, "s": 6726, "text": "LinkedIn: https://bit.ly/2u4YPoF" }, { "code": null, "e": 6793, "s": 6759, "text": "Reference: https://bit.ly/2kry0tB" }, { "code": null, "e": 6859, "s": 6793, "text": "I hope that this has helped you to enhance your knowledge base :)" }, { "code": null, "e": 6879, "s": 6859, "text": "Follow me for more!" } ]
How to create a upload file button in ReactJS? - GeeksforGeeks
03 Aug, 2021 As we know that uploading is a very important step in any application, so we can create a simple upload file button in ReactJS using the following approach. Material UI for React has this component available for us and it is very easy to integrate. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core npm install @material-ui/icons Project Structure: It will look like the following. Project Structure Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import Button from '@material-ui/core/Button';import PhotoCamera from '@material-ui/icons/PhotoCamera';import IconButton from '@material-ui/core/IconButton'; const App = () => { return ( <div style={{ display: 'flex', margin: 'auto', width: 400, flexWrap: 'wrap', }}> <div style={{ width: '100%', float: 'left' }}> <h3>How to use create button to choose file in ReactJS?</h3> <br /> </div> <input type="file" accept="image/*" style={{ display: 'none' }} id="contained-button-file" /> <label htmlFor="contained-button-file"> <Button variant="contained" color="primary" component="span"> Upload </Button> </label> <h3> OR </h3> <input accept="image/*" id="icon-button-file" type="file" style={{ display: 'none' }} /> <label htmlFor="icon-button-file"> <IconButton color="primary" aria-label="upload picture" component="span"> <PhotoCamera /> </IconButton> </label> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Now click on any of either button and now you can choose any file to upload. This is how we can create the upload file button in ReactJS. angle361 JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Form validation using HTML and JavaScript Difference Between PUT and PATCH Request How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? Create a Responsive Navbar using ReactJS How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 25034, "s": 25006, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25284, "s": 25034, "text": "As we know that uploading is a very important step in any application, so we can create a simple upload file button in ReactJS using the following approach. Material UI for React has this component available for us and it is very easy to integrate. " }, { "code": null, "e": 25334, "s": 25284, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25398, "s": 25334, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25430, "s": 25398, "text": "npx create-react-app foldername" }, { "code": null, "e": 25530, "s": 25430, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25544, "s": 25530, "text": "cd foldername" }, { "code": null, "e": 25653, "s": 25544, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25714, "s": 25653, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 25766, "s": 25714, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25784, "s": 25766, "text": "Project Structure" }, { "code": null, "e": 25922, "s": 25784, "text": "Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 25933, "s": 25922, "text": "Javascript" }, { "code": "import React from 'react';import Button from '@material-ui/core/Button';import PhotoCamera from '@material-ui/icons/PhotoCamera';import IconButton from '@material-ui/core/IconButton'; const App = () => { return ( <div style={{ display: 'flex', margin: 'auto', width: 400, flexWrap: 'wrap', }}> <div style={{ width: '100%', float: 'left' }}> <h3>How to use create button to choose file in ReactJS?</h3> <br /> </div> <input type=\"file\" accept=\"image/*\" style={{ display: 'none' }} id=\"contained-button-file\" /> <label htmlFor=\"contained-button-file\"> <Button variant=\"contained\" color=\"primary\" component=\"span\"> Upload </Button> </label> <h3> OR </h3> <input accept=\"image/*\" id=\"icon-button-file\" type=\"file\" style={{ display: 'none' }} /> <label htmlFor=\"icon-button-file\"> <IconButton color=\"primary\" aria-label=\"upload picture\" component=\"span\"> <PhotoCamera /> </IconButton> </label> </div> );} export default App;", "e": 27032, "s": 25933, "text": null }, { "code": null, "e": 27148, "s": 27035, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27160, "s": 27150, "text": "npm start" }, { "code": null, "e": 27259, "s": 27160, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27401, "s": 27263, "text": "Now click on any of either button and now you can choose any file to upload. This is how we can create the upload file button in ReactJS." }, { "code": null, "e": 27412, "s": 27403, "text": "angle361" }, { "code": null, "e": 27423, "s": 27412, "text": "JavaScript" }, { "code": null, "e": 27431, "s": 27423, "text": "ReactJS" }, { "code": null, "e": 27448, "s": 27431, "text": "Web Technologies" }, { "code": null, "e": 27546, "s": 27448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27555, "s": 27546, "text": "Comments" }, { "code": null, "e": 27568, "s": 27555, "text": "Old Comments" }, { "code": null, "e": 27629, "s": 27568, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27701, "s": 27629, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27746, "s": 27701, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27788, "s": 27746, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27829, "s": 27788, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27872, "s": 27829, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27917, "s": 27872, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27982, "s": 27917, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28023, "s": 27982, "text": "Create a Responsive Navbar using ReactJS" } ]
PHP program to find the maximum element in an array
To find the maximum element in an array, the PHP code is as follows − Live Demo <?php function get_max_value($my_array){ $n = count($my_array); $max_val = $my_array[0]; for ($i = 1; $i < $n; $i++) if ($max_val < $my_array[$i]) $max_val = $my_array[$i]; return $max_val; } $my_array = array(56, 78, 91, 44, 0, 11); print_r("The highest value of the array is "); echo(get_max_value($my_array)); echo("\n"); ?> The highest value of the array is91 A function named ‘get_max_value()’ is defined, that takes an array as parameter. Inside this function, the count function is used to find the number of elements in the array, and it is assigned to a variable − $n = count($my_array); The first element in the array is assigned to a variable, and the array is iterated over, and adjacent values in the array are compared, and the highest value amongst all of them is given as output − $max_val = $my_array[0]; for ($i = 1; $i < $n; $i++) if ($max_val < $my_array[$i]) $max_val = $my_array[$i]; return $max_val; Outside the function, the array is defined, and the function is called by passing this array as a parameter. The output is displayed on the screen − $my_array = array(56, 78, 91, 44, 0, 11); print_r("The highest value of the array is"); echo(get_max_value($my_array));
[ { "code": null, "e": 1132, "s": 1062, "text": "To find the maximum element in an array, the PHP code is as follows −" }, { "code": null, "e": 1143, "s": 1132, "text": " Live Demo" }, { "code": null, "e": 1534, "s": 1143, "text": "<?php\n function get_max_value($my_array){\n $n = count($my_array);\n $max_val = $my_array[0];\n for ($i = 1; $i < $n; $i++)\n if ($max_val < $my_array[$i])\n $max_val = $my_array[$i];\n return $max_val;\n }\n $my_array = array(56, 78, 91, 44, 0, 11);\n print_r(\"The highest value of the array is \");\n echo(get_max_value($my_array));\n echo(\"\\n\");\n?>" }, { "code": null, "e": 1570, "s": 1534, "text": "The highest value of the array is91" }, { "code": null, "e": 1780, "s": 1570, "text": "A function named ‘get_max_value()’ is defined, that takes an array as parameter. Inside this\nfunction, the count function is used to find the number of elements in the array, and it is assigned to\na variable −" }, { "code": null, "e": 1803, "s": 1780, "text": "$n = count($my_array);" }, { "code": null, "e": 2003, "s": 1803, "text": "The first element in the array is assigned to a variable, and the array is iterated over, and adjacent\nvalues in the array are compared, and the highest value amongst all of them is given as output −" }, { "code": null, "e": 2138, "s": 2003, "text": "$max_val = $my_array[0];\nfor ($i = 1; $i < $n; $i++)\n if ($max_val < $my_array[$i])\n $max_val = $my_array[$i];\nreturn $max_val;" }, { "code": null, "e": 2287, "s": 2138, "text": "Outside the function, the array is defined, and the function is called by passing this array as a\nparameter. The output is displayed on the screen −" }, { "code": null, "e": 2407, "s": 2287, "text": "$my_array = array(56, 78, 91, 44, 0, 11);\nprint_r(\"The highest value of the array is\");\necho(get_max_value($my_array));" } ]
ES6 - split()
This method splits a String object into an array of strings by separating the string into substrings. string.split([separator][, limit]); separator − Specifies the character to use for separating the string. Ifseparator is omitted, the array returned contains one element consisting of the entire string. separator − Specifies the character to use for separating the string. Ifseparator is omitted, the array returned contains one element consisting of the entire string. limit − Integer specifying a limit on the number of splits to be found. limit − Integer specifying a limit on the number of splits to be found. The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array. var str = "Apples are round, and apples are juicy."; var splitted = str.split(" ", 3); console.log(splitted) [ 'Apples', 'are', 'round,' ] 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2379, "s": 2277, "text": "This method splits a String object into an array of strings by separating the string into substrings." }, { "code": null, "e": 2417, "s": 2379, "text": "string.split([separator][, limit]); \n" }, { "code": null, "e": 2584, "s": 2417, "text": "separator − Specifies the character to use for separating the string. Ifseparator is omitted, the array returned contains one element consisting of the entire string." }, { "code": null, "e": 2751, "s": 2584, "text": "separator − Specifies the character to use for separating the string. Ifseparator is omitted, the array returned contains one element consisting of the entire string." }, { "code": null, "e": 2823, "s": 2751, "text": "limit − Integer specifying a limit on the number of splits to be found." }, { "code": null, "e": 2895, "s": 2823, "text": "limit − Integer specifying a limit on the number of splits to be found." }, { "code": null, "e": 3047, "s": 2895, "text": "The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array." }, { "code": null, "e": 3161, "s": 3047, "text": "var str = \"Apples are round, and apples are juicy.\"; \nvar splitted = str.split(\" \", 3); \nconsole.log(splitted) " }, { "code": null, "e": 3194, "s": 3161, "text": "[ 'Apples', 'are', 'round,' ] \n" }, { "code": null, "e": 3229, "s": 3194, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3243, "s": 3229, "text": " Sharad Kumar" }, { "code": null, "e": 3276, "s": 3243, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 3294, "s": 3276, "text": " Richa Maheshwari" }, { "code": null, "e": 3327, "s": 3294, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3341, "s": 3327, "text": " Anadi Sharma" }, { "code": null, "e": 3376, "s": 3341, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3393, "s": 3376, "text": " Gowthami Swarna" }, { "code": null, "e": 3426, "s": 3393, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3442, "s": 3426, "text": " Deepti Trivedi" }, { "code": null, "e": 3477, "s": 3442, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3485, "s": 3477, "text": " Shweta" }, { "code": null, "e": 3492, "s": 3485, "text": " Print" }, { "code": null, "e": 3503, "s": 3492, "text": " Add Notes" } ]
Output of Java Program | Set 8
02 Aug, 2021 Difficulty level : IntermediatePredict the output of following Java Programs.Program 1: Java class GfG{ public static void main(String args[]) { String s1 = new String("geeksforgeeks"); String s2 = new String("geeksforgeeks"); if (s1 == s2) System.out.println("Equal"); else System.out.println("Not equal"); }} Output: Not equal Explanation: Since, s1 and s2 are two different objects the references are not the same, and the == operator compares object reference. So it prints “Not equal”, to compare the actual characters in the string .equals() method must be used. Program 2: Java class Person{ private void who() { System.out.println("Inside private method Person(who)"); } public static void whoAmI() { System.out.println("Inside static method, Person(whoAmI)"); } public void whoAreYou() { who(); System.out.println("Inside virtual method, Person(whoAreYou)"); }} class Kid extends Person{ private void who() { System.out.println("Kid(who)"); } public static void whoAmI() { System.out.println("Kid(whoAmI)"); } public void whoAreYou() { who(); System.out.println("Kid(whoAreYou)"); }}public class Gfg{ public static void main(String args[]) { Person p = new Kid(); p.whoAmI(); p.whoAreYou(); }} Output: Inside static method, Person(whoAmI) Kid(who) Kid(whoAreYou) Explanation: Static binding (or compile time) happens for static methods. Here p.whoAmI() calls the static method so it is called during compile time hence results in static binding and prints the method in Person class. Whereas p.whoAreYou() calls the method in Kid class since by default Java takes it as a virtual method i.e, dynamic binding. Program 3: Java class GfG{ public static void main(String args[]) { try { System.out.println("First statement of try block"); int num=45/3; System.out.println(num); } catch(Exception e) { System.out.println("Gfg caught Exception"); } finally { System.out.println("finally block"); } System.out.println("Main method"); }} Output: First statement of try block 15 finally block Main method Explanation: Since there is no exception, the catch block is not called, but the finally block is always executed after a try block whether the exception is handled or not. Program 4: Java class One implements Runnable{ public void run() { System.out.print(Thread.currentThread().getName()); }}class Two implements Runnable{ public void run() { new One().run(); new Thread(new One(),"gfg2").run(); new Thread(new One(),"gfg3").start(); }}class Three{ public static void main (String[] args) { new Thread(new Two(),"gfg1").start(); }} Output: gfg1gfg1gfg3 Explanation : Initially new Thread is started with name gfg1 then in class Two the first run method runs the thread with the name gfg1, then after that a new thread is created calling run method but since a new thread can be created by calling start method only so the previous thread does the action and again gfg1 is printed.Now a new thread is created by calling the start method so a new thread starts with gfg3 name and hence prints gfg3.This article is contributed by Pratik Agarwal. 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. lkki surinderdawra388 Java-Output Java Program Output Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Aug, 2021" }, { "code": null, "e": 143, "s": 54, "text": "Difficulty level : IntermediatePredict the output of following Java Programs.Program 1: " }, { "code": null, "e": 148, "s": 143, "text": "Java" }, { "code": "class GfG{ public static void main(String args[]) { String s1 = new String(\"geeksforgeeks\"); String s2 = new String(\"geeksforgeeks\"); if (s1 == s2) System.out.println(\"Equal\"); else System.out.println(\"Not equal\"); }}", "e": 425, "s": 148, "text": null }, { "code": null, "e": 435, "s": 425, "text": "Output: " }, { "code": null, "e": 445, "s": 435, "text": "Not equal" }, { "code": null, "e": 699, "s": 445, "text": "Explanation: Since, s1 and s2 are two different objects the references are not the same, and the == operator compares object reference. So it prints “Not equal”, to compare the actual characters in the string .equals() method must be used. Program 2: " }, { "code": null, "e": 704, "s": 699, "text": "Java" }, { "code": "class Person{ private void who() { System.out.println(\"Inside private method Person(who)\"); } public static void whoAmI() { System.out.println(\"Inside static method, Person(whoAmI)\"); } public void whoAreYou() { who(); System.out.println(\"Inside virtual method, Person(whoAreYou)\"); }} class Kid extends Person{ private void who() { System.out.println(\"Kid(who)\"); } public static void whoAmI() { System.out.println(\"Kid(whoAmI)\"); } public void whoAreYou() { who(); System.out.println(\"Kid(whoAreYou)\"); }}public class Gfg{ public static void main(String args[]) { Person p = new Kid(); p.whoAmI(); p.whoAreYou(); }}", "e": 1471, "s": 704, "text": null }, { "code": null, "e": 1481, "s": 1471, "text": "Output: " }, { "code": null, "e": 1542, "s": 1481, "text": "Inside static method, Person(whoAmI)\nKid(who)\nKid(whoAreYou)" }, { "code": null, "e": 1901, "s": 1542, "text": "Explanation: Static binding (or compile time) happens for static methods. Here p.whoAmI() calls the static method so it is called during compile time hence results in static binding and prints the method in Person class. Whereas p.whoAreYou() calls the method in Kid class since by default Java takes it as a virtual method i.e, dynamic binding. Program 3: " }, { "code": null, "e": 1906, "s": 1901, "text": "Java" }, { "code": "class GfG{ public static void main(String args[]) { try { System.out.println(\"First statement of try block\"); int num=45/3; System.out.println(num); } catch(Exception e) { System.out.println(\"Gfg caught Exception\"); } finally { System.out.println(\"finally block\"); } System.out.println(\"Main method\"); }}", "e": 2345, "s": 1906, "text": null }, { "code": null, "e": 2355, "s": 2345, "text": "Output: " }, { "code": null, "e": 2413, "s": 2355, "text": "First statement of try block\n15\nfinally block\nMain method" }, { "code": null, "e": 2600, "s": 2413, "text": "Explanation: Since there is no exception, the catch block is not called, but the finally block is always executed after a try block whether the exception is handled or not. Program 4: " }, { "code": null, "e": 2605, "s": 2600, "text": "Java" }, { "code": "class One implements Runnable{ public void run() { System.out.print(Thread.currentThread().getName()); }}class Two implements Runnable{ public void run() { new One().run(); new Thread(new One(),\"gfg2\").run(); new Thread(new One(),\"gfg3\").start(); }}class Three{ public static void main (String[] args) { new Thread(new Two(),\"gfg1\").start(); }}", "e": 3012, "s": 2605, "text": null }, { "code": null, "e": 3022, "s": 3012, "text": "Output: " }, { "code": null, "e": 3035, "s": 3022, "text": "gfg1gfg1gfg3" }, { "code": null, "e": 3901, "s": 3035, "text": "Explanation : Initially new Thread is started with name gfg1 then in class Two the first run method runs the thread with the name gfg1, then after that a new thread is created calling run method but since a new thread can be created by calling start method only so the previous thread does the action and again gfg1 is printed.Now a new thread is created by calling the start method so a new thread starts with gfg3 name and hence prints gfg3.This article is contributed by Pratik Agarwal. 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": 3906, "s": 3901, "text": "lkki" }, { "code": null, "e": 3923, "s": 3906, "text": "surinderdawra388" }, { "code": null, "e": 3935, "s": 3923, "text": "Java-Output" }, { "code": null, "e": 3940, "s": 3935, "text": "Java" }, { "code": null, "e": 3955, "s": 3940, "text": "Program Output" }, { "code": null, "e": 3960, "s": 3955, "text": "Java" } ]
Difference between Assertions and Triggers in DBMS
21 Sep, 2021 1. What are Assertions? When a constraint involves 2 (or) more tables, the table constraint mechanism is sometimes hard and results may not come as expected. To cover such situation SQL supports the creation of assertions that are constraints not associated with only one table. And an assertion statement should ensure a certain condition will always exist in the database. DBMS always checks the assertion whenever modifications are done in the corresponding table. Syntax – CREATE ASSERTION [ assertion_name ] CHECK ( [ condition ] ); Example – CREATE TABLE sailors (sid int,sname varchar(20), rating int,primary key(sid), CHECK(rating >= 1 AND rating <=10) CHECK((select count(s.sid) from sailors s) + (select count(b.bid)from boats b)<100) ); In the above example, we enforcing CHECK constraint that the number of boats and sailors should be less than 100. So here we are able to CHECK constraints of two tablets simultaneously. 2. What are Triggers? A trigger is a database object that is associated with the table, it will be activated when a defined action is executed for the table. The trigger can be executed when we run the following statements: INSERTUPDATEDELETE INSERT UPDATE DELETE And it can be invoked before or after the event. Syntax – create trigger [trigger_name] [before | after] {insert | update | delete} on [table_name] [for each row] [trigger_body] Example – create trigger t1 before UPDATE on sailors for each row begin if new.age>60 then set new.age=old.age; else set new.age=new.age; end if; end; $ In the above example, we are creating triggers before updates. so, if the new age is greater than 60 we should not update else we should update. We can call this trigger by using “$” symbol. Difference between Assertions and Triggers : Assertions can’t modify the data and they are not linked to any specific tables or events in the database but Triggers are more powerful because they can check conditions and also modify the data within the tables inside a database, unlike assertions. sweetyty DBMS-SQL DBMS Difference Between GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Difference between OLAP and OLTP in DBMS MySQL | Regular expressions (Regexp) Relational Model in DBMS What is Temporary Table in SQL? Difference between BFS and DFS Class method vs Static method in Python Difference Between Method Overloading and Method Overriding in Java Difference between var, let and const keywords in JavaScript Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Sep, 2021" }, { "code": null, "e": 523, "s": 54, "text": "1. What are Assertions? When a constraint involves 2 (or) more tables, the table constraint mechanism is sometimes hard and results may not come as expected. To cover such situation SQL supports the creation of assertions that are constraints not associated with only one table. And an assertion statement should ensure a certain condition will always exist in the database. DBMS always checks the assertion whenever modifications are done in the corresponding table. " }, { "code": null, "e": 533, "s": 523, "text": "Syntax – " }, { "code": null, "e": 595, "s": 533, "text": "CREATE ASSERTION [ assertion_name ]\nCHECK ( [ condition ] );" }, { "code": null, "e": 607, "s": 595, "text": "Example – " }, { "code": null, "e": 808, "s": 607, "text": "CREATE TABLE sailors (sid int,sname varchar(20), rating int,primary key(sid),\nCHECK(rating >= 1 AND rating <=10)\nCHECK((select count(s.sid) from sailors s) + (select count(b.bid)from boats b)<100) ); " }, { "code": null, "e": 995, "s": 808, "text": "In the above example, we enforcing CHECK constraint that the number of boats and sailors should be less than 100. So here we are able to CHECK constraints of two tablets simultaneously. " }, { "code": null, "e": 1220, "s": 995, "text": "2. What are Triggers? A trigger is a database object that is associated with the table, it will be activated when a defined action is executed for the table. The trigger can be executed when we run the following statements: " }, { "code": null, "e": 1239, "s": 1220, "text": "INSERTUPDATEDELETE" }, { "code": null, "e": 1246, "s": 1239, "text": "INSERT" }, { "code": null, "e": 1253, "s": 1246, "text": "UPDATE" }, { "code": null, "e": 1260, "s": 1253, "text": "DELETE" }, { "code": null, "e": 1310, "s": 1260, "text": "And it can be invoked before or after the event. " }, { "code": null, "e": 1321, "s": 1310, "text": "Syntax – " }, { "code": null, "e": 1467, "s": 1321, "text": "create trigger [trigger_name] \n[before | after] \n{insert | update | delete} \non [table_name] \n[for each row] \n[trigger_body] " }, { "code": null, "e": 1479, "s": 1467, "text": "Example – " }, { "code": null, "e": 1646, "s": 1479, "text": "create trigger t1 before UPDATE on sailors\nfor each row\nbegin\n if new.age>60 then\n set new.age=old.age;\n else\n set new.age=new.age;\n end if;\nend;\n$ " }, { "code": null, "e": 1838, "s": 1646, "text": "In the above example, we are creating triggers before updates. so, if the new age is greater than 60 we should not update else we should update. We can call this trigger by using “$” symbol. " }, { "code": null, "e": 1884, "s": 1838, "text": "Difference between Assertions and Triggers : " }, { "code": null, "e": 2137, "s": 1884, "text": "Assertions can’t modify the data and they are not linked to any specific tables or events in the database but Triggers are more powerful because they can check conditions and also modify the data within the tables inside a database, unlike assertions. " }, { "code": null, "e": 2148, "s": 2139, "text": "sweetyty" }, { "code": null, "e": 2157, "s": 2148, "text": "DBMS-SQL" }, { "code": null, "e": 2162, "s": 2157, "text": "DBMS" }, { "code": null, "e": 2181, "s": 2162, "text": "Difference Between" }, { "code": null, "e": 2189, "s": 2181, "text": "GATE CS" }, { "code": null, "e": 2193, "s": 2189, "text": "SQL" }, { "code": null, "e": 2198, "s": 2193, "text": "DBMS" }, { "code": null, "e": 2202, "s": 2198, "text": "SQL" }, { "code": null, "e": 2300, "s": 2202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2341, "s": 2300, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 2382, "s": 2341, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 2419, "s": 2382, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 2444, "s": 2419, "text": "Relational Model in DBMS" }, { "code": null, "e": 2476, "s": 2444, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2507, "s": 2476, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2547, "s": 2507, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2615, "s": 2547, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2676, "s": 2615, "text": "Difference between var, let and const keywords in JavaScript" } ]
Smart calculator in Python
11 Jan, 2022 Problem – This smart calculator works on the text statement also. The user need not provide algebraic expression always. It fetches the word form the command (given by the user) and then formulates the expression.Examples: Input : Hi calculator plz find the lcm of 4 and 8. Output : 8 Input : Hi smart plz find the multiplication of 3 and 9. Output : 27 Input : Hi smart plz end the program. Output : Thanks for enjoy with me. Code : Python code for smart calculation Python3 # main python proghramresponse=['Welcome to smart calculator','My name is MONTY', 'Thanks for enjoy with me ','Sorry ,this is beyond my ability'] # fetching tokens from the text commanddef extract_from_text(text): l=[] for t in text.split(' '): try: l.append(float(t)) except ValueError: pass return l # calculating LCMdef lcm(a,b): L=a if a>b else b while L<=a*b: if L%a==0 and L%b==0: return L L+=1 # calculating HCFdef hcf(a,b): H=a if a<b else b while H>=1: if a%H==0 and b%H==0: return H H-=1 # Additiondef add(a,b): return a+b # Subtractiondef sub(a,b): return a-b # Multiplicationdef mul(a,b): return a*b # Divisiondef div(a,b): return a/b # Remainderdef mod(a,b): return a%b # Response to command# printing - "Thanks for enjoy with me" on exitdef end(): print(response[2]) input('press enter key to exit') exit() def myname(): print(response[1])def sorry(): print(response[3]) # Operations - performed on the basis of text tokensoperations={'ADD':add,'PLUS':add,'SUM':add,'ADDITION':add, 'SUB':sub,'SUBTRACT':sub, 'MINUS':sub, 'DIFFERENCE':sub,'LCM':lcm,'HCF':hcf, 'PRODUCT':mul, 'MULTIPLY':mul,'MULTIPLICATION':mul, 'DIVISION':div,'MOD':mod,'REMAINDER' :mod,'MODULAS':mod} # commandscommands={'NAME':myname,'EXIT':end,'END':end,'CLOSE':end} print('--------------'+response[0]+'------------')print('--------------'+response[1]+'--------------------') while True: print() text=input('enter your queries: ') for word in text.split(' '): if word.upper() in operations.keys(): try: l = extract_from_text(text) r = operations[word.upper()] (l[0],l[1]) print(r) except: print('something went wrong going plz enter again !!') finally: break elif word.upper() in commands.keys(): commands[word.upper()]() break else: sorry() Output: --------------Welcome to smart calculator------------ --------------My name is MONTY-------------------- enter your queries: tell me the hcf of 4 and 8 4.0 enter your queries: hi plz tell me 7 + 8 Sorry ,this is beyond my ability enter your queries: pls add 7 and 8 15.0 varshagumber28 Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 252, "s": 28, "text": "Problem – This smart calculator works on the text statement also. The user need not provide algebraic expression always. It fetches the word form the command (given by the user) and then formulates the expression.Examples: " }, { "code": null, "e": 468, "s": 252, "text": "Input : Hi calculator plz find the lcm of 4 and 8. \nOutput : 8 \n\nInput : Hi smart plz find the multiplication of 3 and 9. \nOutput : 27 \n\nInput : Hi smart plz end the program. \nOutput : Thanks for enjoy with me." }, { "code": null, "e": 513, "s": 468, "text": " Code : Python code for smart calculation " }, { "code": null, "e": 521, "s": 513, "text": "Python3" }, { "code": "# main python proghramresponse=['Welcome to smart calculator','My name is MONTY', 'Thanks for enjoy with me ','Sorry ,this is beyond my ability'] # fetching tokens from the text commanddef extract_from_text(text): l=[] for t in text.split(' '): try: l.append(float(t)) except ValueError: pass return l # calculating LCMdef lcm(a,b): L=a if a>b else b while L<=a*b: if L%a==0 and L%b==0: return L L+=1 # calculating HCFdef hcf(a,b): H=a if a<b else b while H>=1: if a%H==0 and b%H==0: return H H-=1 # Additiondef add(a,b): return a+b # Subtractiondef sub(a,b): return a-b # Multiplicationdef mul(a,b): return a*b # Divisiondef div(a,b): return a/b # Remainderdef mod(a,b): return a%b # Response to command# printing - \"Thanks for enjoy with me\" on exitdef end(): print(response[2]) input('press enter key to exit') exit() def myname(): print(response[1])def sorry(): print(response[3]) # Operations - performed on the basis of text tokensoperations={'ADD':add,'PLUS':add,'SUM':add,'ADDITION':add, 'SUB':sub,'SUBTRACT':sub, 'MINUS':sub, 'DIFFERENCE':sub,'LCM':lcm,'HCF':hcf, 'PRODUCT':mul, 'MULTIPLY':mul,'MULTIPLICATION':mul, 'DIVISION':div,'MOD':mod,'REMAINDER' :mod,'MODULAS':mod} # commandscommands={'NAME':myname,'EXIT':end,'END':end,'CLOSE':end} print('--------------'+response[0]+'------------')print('--------------'+response[1]+'--------------------') while True: print() text=input('enter your queries: ') for word in text.split(' '): if word.upper() in operations.keys(): try: l = extract_from_text(text) r = operations[word.upper()] (l[0],l[1]) print(r) except: print('something went wrong going plz enter again !!') finally: break elif word.upper() in commands.keys(): commands[word.upper()]() break else: sorry()", "e": 2660, "s": 521, "text": null }, { "code": null, "e": 2669, "s": 2660, "text": "Output: " }, { "code": null, "e": 2950, "s": 2669, "text": "--------------Welcome to smart calculator------------\n--------------My name is MONTY--------------------\n\n\nenter your queries: tell me the hcf of 4 and 8\n4.0\n\n\nenter your queries: hi plz tell me 7 + 8\nSorry ,this is beyond my ability\n\n\nenter your queries: pls add 7 and 8\n15.0" }, { "code": null, "e": 2965, "s": 2950, "text": "varshagumber28" }, { "code": null, "e": 2972, "s": 2965, "text": "Python" }, { "code": null, "e": 2988, "s": 2972, "text": "Python Programs" } ]
Swift – Operators
02 Feb, 2022 Swift is a general-purpose, multi-paradigm, and compiled programming language which is developed by Apple Inc. In Swift, an operator is a symbol that tells the compiler to perform the manipulations in the given expression. Just like other programming languages, the working of operators in Swift is also the same. We can perform multiple operations using operators in our programs there are multiple operators available in Swift. In this article, we will learn all types of operators which are present in the Swift programming language. + (Addition): This operator is used to add two variables. – (Subtraction): This operator is used to subtract the second variable from the first. / (Division): This operator is used to divide the first variable from the second. * (Multiplication): This operator is used to multiply the first variable with the second. % (Modulus): This operator gives the remainder after division first from second. Swift // Swift program to illustrate the // use of arithmetic changesimport Swift // Creating two variables a and bvar a = 5var b = 4 // Adding two numbervar sum = a + bprint("Addition:", sum) // Subtracting two numbervar sub = a - bprint("Subtraction:", sub) // Dividing two numbervar div = a / bprint("Divide:", div) // Multiplying two numbervar mul = a * bprint("Multiply:", mul) // Finding Modulusvar mod = a % bprint("Modulus:", mod) Output: Addition: 9 Subtraction: 1 Divide: 1 Multiply: 20 Modulus: 1 = (Equal): This operator is used to assign values from the right side variable to the left side variable. += (Plus equal to): This operator is used to add the right variable to the left variable and assign the result to the left variable. -= (Minus equal to): This operator is used to subtract the right variable from the left variable and assign the result to the left variable. /= (Divide equal to): This operator is used to divide the left variable with the left variable and assigns the result to the left variable. *= (Multiply equal to): This operator is used to multiply the right variable with the left variable and assign the result to the left variable. %= (Modulus equal to): This operator is used to take modulus using two variables and assigns the result to the left variable Swift // Swift program to illustrate the // use of assignment operatorsimport Swift // Creating two variables a & bvar a = 5var b = 1 // Plus equal toa += bprint("Result of += operator: ", a) // Minus equal toa -= bprint("Result of -= operator: ", a) // Divide equal toa /= bprint("Result of /= operator: ", a) // Multiply equal toa *= bprint("Result of *= operator: ", a) // Modulus equal toa %= bprint("Result of %= operator: ", a) Output: 6 5 5 5 0 << (Left Shift): The left variable value is moved left by the number of bits mentioned by the right variable. >> (Right Shift): The left variable value is moved right by the number of bits mentioned by the right variable. & (Binary AND): This operator copies bits to the result if the bits are set in both variables. | (Binary OR): This operator copies bits to the result if the bits are set in any variables. ^ (Binary XOR): This operator copies bits to the result if the bits are set on only one variable. ~ (Tilde): This operator gives binary one’s complement of the variable Swift // Swift program to illustrate the // use of bitwise operatorsimport Swift // Creating variables a and bvar a = 2var b = 1 // Left shift operatorprint("Bitwise left shift operator: ", a << b) // Right shift operatorprint("Bitwise right shift operator: ", a >> b) // AND operator operatorprint("AND operator: ", a & b) // OR operatorprint("OR operator: ", a | b) // XOR operatorprint("XOR operator: ", a ^ b) // Tilde operatorprint("Tilde operator: ", ~a) Output: 4 1 0 3 3 -3 < (Less than): If the value of the left variable is less than the value of the right variable then the condition becomes true. > (Greater than): If the value of the left variable is greater than the value of the right variable then the condition becomes true. == (Equal to equal to): If the value of both variables is equal then the condition becomes true. <= (Less than Equal to): If the value of the left variable is less than or equal to the value of the right variable then the condition becomes true. >= (Greater than Equal to): If the value of the left variable is greater than or equal to the value of the right variable then the condition becomes true. != (Not equal to): If the value of both variables is not equal then the condition becomes true. Swift // Swift program to illustrate the // use of Comparison operatorsimport Swift // Creating two variables a & bvar a = 2var b = 1 // Less than operatorprint(a < b) // Greater than operatorprint(a > b) // Equal to operatorprint(a == b) // Not equal to operatorprint(a != b) // Less than equal to operatorprint(a <= b) // Greater than equal to operatorprint(a >= b) Output: false true false true false true && (Logical AND): If both the side conditions are true, then the condition becomes true. || (Logical OR): If any side condition is true, then the condition becomes true. ! (Logical NOT): This operator is to reverse the logical state. Swift // Swift program to illustrate the // use of Logical Operatorsimport Swift // Creating variables a, b & cvar a = 1var b = 2var c = 3 // Logical AND operatorif (a < b && b < c){ print("Both condition is true")} // Logical OR operatorif (a < b || a > c){ print("Only one condition is true")} // Logical NOT operatorif (true && !false){ print("Logic reversed")} Output: Both condition is true Only one condition is true Logic reversed Cond ? A : B (Ternary Operator): If the condition becomes true, then value A will be assigned otherwise the value B will be assigned. (A ?? B) (Nil-coalescing Operator): If the user didn’t pass any value to the variable then the default value will be nil. ++ (Increment): This operator has been used to increase the value of the variable by 1. — (Decrement): This operator is used to decrease the value of the variable by 1. Swift // Swift program to illustrate the use of// Ternary and Nil-coalescing Operator import Swift // Creating variables a, bvar a = 1var b = 2 // Ternary operatorvar c = a < b ? 3 : 4print(c) let name: String? = nil // Nil-Coalescing Operatorlet newName = name ?? "GFG" // If we don't pass GFG then the// default value will be nil in newNameprint(newName) Output: 3 GFG (a...b) (Closed Range Operator) — It runs from a to b including the values a and b. It is used in mostly used in for-in loops. (a..<b) (Half-Open Range Operator) — It runs from a to b, but it doesn’t include the value of b. It is used in mostly used in for-in loops. [a...] (One-Sided Range Operator) — It will run for ranges that continue as far as possible in one direction. Swift // Swift program to illustrate the use of// range Operatorsimport Swift // Closed Range Operator - It will print up to 3for i in 1...3 { print("closed = \(i)")} // Half open Range Operator - It will only print up to 2for i in 1..<3 { print("half = \(i)")} // One sided Range Operator - It will print all// values in array from index 0let values = [ 1, 2, 3, 4 ]for i in values[0...] { print("One sided = \(i)")} Output: closed = 1 closed = 2 closed = 3 half = 1 half = 2 One sided = 1 One sided = 2 One sided = 3 One sided = 4 In swift operator, precedence is used to find the grouping terms in the given expression. Also, used to evaluate the expression. For example, y = 3 + 4 * 2, here * has the highest precedence so first, we solve 4 *2 and then we add the result with 3. Precedence will decrease while we visit the bottom of the table given below. sagartomar9927 Picked Swift-Basics Swift Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2022" }, { "code": null, "e": 565, "s": 28, "text": "Swift is a general-purpose, multi-paradigm, and compiled programming language which is developed by Apple Inc. In Swift, an operator is a symbol that tells the compiler to perform the manipulations in the given expression. Just like other programming languages, the working of operators in Swift is also the same. We can perform multiple operations using operators in our programs there are multiple operators available in Swift. In this article, we will learn all types of operators which are present in the Swift programming language." }, { "code": null, "e": 623, "s": 565, "text": "+ (Addition): This operator is used to add two variables." }, { "code": null, "e": 710, "s": 623, "text": "– (Subtraction): This operator is used to subtract the second variable from the first." }, { "code": null, "e": 792, "s": 710, "text": "/ (Division): This operator is used to divide the first variable from the second." }, { "code": null, "e": 882, "s": 792, "text": "* (Multiplication): This operator is used to multiply the first variable with the second." }, { "code": null, "e": 963, "s": 882, "text": "% (Modulus): This operator gives the remainder after division first from second." }, { "code": null, "e": 969, "s": 963, "text": "Swift" }, { "code": "// Swift program to illustrate the // use of arithmetic changesimport Swift // Creating two variables a and bvar a = 5var b = 4 // Adding two numbervar sum = a + bprint(\"Addition:\", sum) // Subtracting two numbervar sub = a - bprint(\"Subtraction:\", sub) // Dividing two numbervar div = a / bprint(\"Divide:\", div) // Multiplying two numbervar mul = a * bprint(\"Multiply:\", mul) // Finding Modulusvar mod = a % bprint(\"Modulus:\", mod)", "e": 1408, "s": 969, "text": null }, { "code": null, "e": 1416, "s": 1408, "text": "Output:" }, { "code": null, "e": 1477, "s": 1416, "text": "Addition: 9\nSubtraction: 1\nDivide: 1\nMultiply: 20\nModulus: 1" }, { "code": null, "e": 1583, "s": 1477, "text": "= (Equal): This operator is used to assign values from the right side variable to the left side variable." }, { "code": null, "e": 1716, "s": 1583, "text": "+= (Plus equal to): This operator is used to add the right variable to the left variable and assign the result to the left variable." }, { "code": null, "e": 1857, "s": 1716, "text": "-= (Minus equal to): This operator is used to subtract the right variable from the left variable and assign the result to the left variable." }, { "code": null, "e": 1997, "s": 1857, "text": "/= (Divide equal to): This operator is used to divide the left variable with the left variable and assigns the result to the left variable." }, { "code": null, "e": 2141, "s": 1997, "text": "*= (Multiply equal to): This operator is used to multiply the right variable with the left variable and assign the result to the left variable." }, { "code": null, "e": 2266, "s": 2141, "text": "%= (Modulus equal to): This operator is used to take modulus using two variables and assigns the result to the left variable" }, { "code": null, "e": 2272, "s": 2266, "text": "Swift" }, { "code": "// Swift program to illustrate the // use of assignment operatorsimport Swift // Creating two variables a & bvar a = 5var b = 1 // Plus equal toa += bprint(\"Result of += operator: \", a) // Minus equal toa -= bprint(\"Result of -= operator: \", a) // Divide equal toa /= bprint(\"Result of /= operator: \", a) // Multiply equal toa *= bprint(\"Result of *= operator: \", a) // Modulus equal toa %= bprint(\"Result of %= operator: \", a)", "e": 2706, "s": 2272, "text": null }, { "code": null, "e": 2714, "s": 2706, "text": "Output:" }, { "code": null, "e": 2724, "s": 2714, "text": "6\n5\n5\n5\n0" }, { "code": null, "e": 2834, "s": 2724, "text": "<< (Left Shift): The left variable value is moved left by the number of bits mentioned by the right variable." }, { "code": null, "e": 2946, "s": 2834, "text": ">> (Right Shift): The left variable value is moved right by the number of bits mentioned by the right variable." }, { "code": null, "e": 3041, "s": 2946, "text": "& (Binary AND): This operator copies bits to the result if the bits are set in both variables." }, { "code": null, "e": 3134, "s": 3041, "text": "| (Binary OR): This operator copies bits to the result if the bits are set in any variables." }, { "code": null, "e": 3232, "s": 3134, "text": "^ (Binary XOR): This operator copies bits to the result if the bits are set on only one variable." }, { "code": null, "e": 3303, "s": 3232, "text": "~ (Tilde): This operator gives binary one’s complement of the variable" }, { "code": null, "e": 3309, "s": 3303, "text": "Swift" }, { "code": "// Swift program to illustrate the // use of bitwise operatorsimport Swift // Creating variables a and bvar a = 2var b = 1 // Left shift operatorprint(\"Bitwise left shift operator: \", a << b) // Right shift operatorprint(\"Bitwise right shift operator: \", a >> b) // AND operator operatorprint(\"AND operator: \", a & b) // OR operatorprint(\"OR operator: \", a | b) // XOR operatorprint(\"XOR operator: \", a ^ b) // Tilde operatorprint(\"Tilde operator: \", ~a)", "e": 3771, "s": 3309, "text": null }, { "code": null, "e": 3779, "s": 3771, "text": "Output:" }, { "code": null, "e": 3792, "s": 3779, "text": "4\n1\n0\n3\n3\n-3" }, { "code": null, "e": 3919, "s": 3792, "text": "< (Less than): If the value of the left variable is less than the value of the right variable then the condition becomes true." }, { "code": null, "e": 4052, "s": 3919, "text": "> (Greater than): If the value of the left variable is greater than the value of the right variable then the condition becomes true." }, { "code": null, "e": 4149, "s": 4052, "text": "== (Equal to equal to): If the value of both variables is equal then the condition becomes true." }, { "code": null, "e": 4298, "s": 4149, "text": "<= (Less than Equal to): If the value of the left variable is less than or equal to the value of the right variable then the condition becomes true." }, { "code": null, "e": 4453, "s": 4298, "text": ">= (Greater than Equal to): If the value of the left variable is greater than or equal to the value of the right variable then the condition becomes true." }, { "code": null, "e": 4549, "s": 4453, "text": "!= (Not equal to): If the value of both variables is not equal then the condition becomes true." }, { "code": null, "e": 4555, "s": 4549, "text": "Swift" }, { "code": "// Swift program to illustrate the // use of Comparison operatorsimport Swift // Creating two variables a & bvar a = 2var b = 1 // Less than operatorprint(a < b) // Greater than operatorprint(a > b) // Equal to operatorprint(a == b) // Not equal to operatorprint(a != b) // Less than equal to operatorprint(a <= b) // Greater than equal to operatorprint(a >= b)", "e": 4924, "s": 4555, "text": null }, { "code": null, "e": 4932, "s": 4924, "text": "Output:" }, { "code": null, "e": 4965, "s": 4932, "text": "false\ntrue\nfalse\ntrue\nfalse\ntrue" }, { "code": null, "e": 5054, "s": 4965, "text": "&& (Logical AND): If both the side conditions are true, then the condition becomes true." }, { "code": null, "e": 5135, "s": 5054, "text": "|| (Logical OR): If any side condition is true, then the condition becomes true." }, { "code": null, "e": 5199, "s": 5135, "text": "! (Logical NOT): This operator is to reverse the logical state." }, { "code": null, "e": 5205, "s": 5199, "text": "Swift" }, { "code": "// Swift program to illustrate the // use of Logical Operatorsimport Swift // Creating variables a, b & cvar a = 1var b = 2var c = 3 // Logical AND operatorif (a < b && b < c){ print(\"Both condition is true\")} // Logical OR operatorif (a < b || a > c){ print(\"Only one condition is true\")} // Logical NOT operatorif (true && !false){ print(\"Logic reversed\")}", "e": 5577, "s": 5205, "text": null }, { "code": null, "e": 5585, "s": 5577, "text": "Output:" }, { "code": null, "e": 5650, "s": 5585, "text": "Both condition is true\nOnly one condition is true\nLogic reversed" }, { "code": null, "e": 5784, "s": 5650, "text": "Cond ? A : B (Ternary Operator): If the condition becomes true, then value A will be assigned otherwise the value B will be assigned." }, { "code": null, "e": 5906, "s": 5784, "text": "(A ?? B) (Nil-coalescing Operator): If the user didn’t pass any value to the variable then the default value will be nil." }, { "code": null, "e": 5994, "s": 5906, "text": "++ (Increment): This operator has been used to increase the value of the variable by 1." }, { "code": null, "e": 6075, "s": 5994, "text": "— (Decrement): This operator is used to decrease the value of the variable by 1." }, { "code": null, "e": 6081, "s": 6075, "text": "Swift" }, { "code": "// Swift program to illustrate the use of// Ternary and Nil-coalescing Operator import Swift // Creating variables a, bvar a = 1var b = 2 // Ternary operatorvar c = a < b ? 3 : 4print(c) let name: String? = nil // Nil-Coalescing Operatorlet newName = name ?? \"GFG\" // If we don't pass GFG then the// default value will be nil in newNameprint(newName)", "e": 6437, "s": 6081, "text": null }, { "code": null, "e": 6445, "s": 6437, "text": "Output:" }, { "code": null, "e": 6451, "s": 6445, "text": "3\nGFG" }, { "code": null, "e": 6578, "s": 6451, "text": "(a...b) (Closed Range Operator) — It runs from a to b including the values a and b. It is used in mostly used in for-in loops." }, { "code": null, "e": 6718, "s": 6578, "text": "(a..<b) (Half-Open Range Operator) — It runs from a to b, but it doesn’t include the value of b. It is used in mostly used in for-in loops." }, { "code": null, "e": 6828, "s": 6718, "text": "[a...] (One-Sided Range Operator) — It will run for ranges that continue as far as possible in one direction." }, { "code": null, "e": 6834, "s": 6828, "text": "Swift" }, { "code": "// Swift program to illustrate the use of// range Operatorsimport Swift // Closed Range Operator - It will print up to 3for i in 1...3 { print(\"closed = \\(i)\")} // Half open Range Operator - It will only print up to 2for i in 1..<3 { print(\"half = \\(i)\")} // One sided Range Operator - It will print all// values in array from index 0let values = [ 1, 2, 3, 4 ]for i in values[0...] { print(\"One sided = \\(i)\")}", "e": 7258, "s": 6834, "text": null }, { "code": null, "e": 7266, "s": 7258, "text": "Output:" }, { "code": null, "e": 7373, "s": 7266, "text": "closed = 1\nclosed = 2\nclosed = 3\nhalf = 1\nhalf = 2\nOne sided = 1\nOne sided = 2\nOne sided = 3\nOne sided = 4" }, { "code": null, "e": 7700, "s": 7373, "text": "In swift operator, precedence is used to find the grouping terms in the given expression. Also, used to evaluate the expression. For example, y = 3 + 4 * 2, here * has the highest precedence so first, we solve 4 *2 and then we add the result with 3. Precedence will decrease while we visit the bottom of the table given below." }, { "code": null, "e": 7715, "s": 7700, "text": "sagartomar9927" }, { "code": null, "e": 7722, "s": 7715, "text": "Picked" }, { "code": null, "e": 7735, "s": 7722, "text": "Swift-Basics" }, { "code": null, "e": 7741, "s": 7735, "text": "Swift" } ]
LinkedList push() Method in Java
10 Dec, 2018 The java.util.LinkedList.push() method is used to push an element at the starting(top) of the stack represented by LinkedList. This is similar to the addFirst() method of LinkedList and simply inserts the element at the first position or top of the linked list. Syntax: LinkedListObject.push(Object element) Parameters: The method accepts one parameter element of object type and represents the element to be inserted. The type ‘Object’ should be of same Stack represented by the LinkedList. Return Type: The return type of the method is void i.e. it doesn’t returns any value. Below programs illustrate the java.util.LinkedList.push() method: Program 1: // Java code to demonstrate push() methodimport java.util.LinkedList; public class GfG { // Main method public static void main(String[] args) { // Creating a LinkedList object to represent a stack. LinkedList<String> stack = new LinkedList<>(); // Pushing an element in the stack stack.push("I"); // Pushing an element in the stack stack.push("Like"); // Pushing an element in the stack stack.push("GeeksforGeeks"); // Printing the complete stack. System.out.println(stack); }} [GeeksforGeeks, Like, I] Program 2 : // Java code to demonstrate push() method import java.util.LinkedList; public class GfG { // main method public static void main(String[] args) { // Creating a LinkedList object to represent a stack. LinkedList<Integer> stack = new LinkedList<>(); // Pushing an element in the stack stack.push(30); // Pushing an element in the stack stack.push(20); // Pushing an element in the stack stack.push(10); // Printing the complete stack. System.out.println(stack); }} [10, 20, 30] Java - util package Java-Collections Java-Functions java-LinkedList Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2018" }, { "code": null, "e": 290, "s": 28, "text": "The java.util.LinkedList.push() method is used to push an element at the starting(top) of the stack represented by LinkedList. This is similar to the addFirst() method of LinkedList and simply inserts the element at the first position or top of the linked list." }, { "code": null, "e": 298, "s": 290, "text": "Syntax:" }, { "code": null, "e": 337, "s": 298, "text": "LinkedListObject.push(Object element)\n" }, { "code": null, "e": 521, "s": 337, "text": "Parameters: The method accepts one parameter element of object type and represents the element to be inserted. The type ‘Object’ should be of same Stack represented by the LinkedList." }, { "code": null, "e": 607, "s": 521, "text": "Return Type: The return type of the method is void i.e. it doesn’t returns any value." }, { "code": null, "e": 673, "s": 607, "text": "Below programs illustrate the java.util.LinkedList.push() method:" }, { "code": null, "e": 684, "s": 673, "text": "Program 1:" }, { "code": "// Java code to demonstrate push() methodimport java.util.LinkedList; public class GfG { // Main method public static void main(String[] args) { // Creating a LinkedList object to represent a stack. LinkedList<String> stack = new LinkedList<>(); // Pushing an element in the stack stack.push(\"I\"); // Pushing an element in the stack stack.push(\"Like\"); // Pushing an element in the stack stack.push(\"GeeksforGeeks\"); // Printing the complete stack. System.out.println(stack); }}", "e": 1256, "s": 684, "text": null }, { "code": null, "e": 1282, "s": 1256, "text": "[GeeksforGeeks, Like, I]\n" }, { "code": null, "e": 1294, "s": 1282, "text": "Program 2 :" }, { "code": "// Java code to demonstrate push() method import java.util.LinkedList; public class GfG { // main method public static void main(String[] args) { // Creating a LinkedList object to represent a stack. LinkedList<Integer> stack = new LinkedList<>(); // Pushing an element in the stack stack.push(30); // Pushing an element in the stack stack.push(20); // Pushing an element in the stack stack.push(10); // Printing the complete stack. System.out.println(stack); }}", "e": 1851, "s": 1294, "text": null }, { "code": null, "e": 1865, "s": 1851, "text": "[10, 20, 30]\n" }, { "code": null, "e": 1885, "s": 1865, "text": "Java - util package" }, { "code": null, "e": 1902, "s": 1885, "text": "Java-Collections" }, { "code": null, "e": 1917, "s": 1902, "text": "Java-Functions" }, { "code": null, "e": 1933, "s": 1917, "text": "java-LinkedList" }, { "code": null, "e": 1938, "s": 1933, "text": "Java" }, { "code": null, "e": 1943, "s": 1938, "text": "Java" }, { "code": null, "e": 1960, "s": 1943, "text": "Java-Collections" } ]
Int32.Equals Method in C# with Examples
04 Apr, 2019 Int32.Equals() Method is used to get a value which indicates whether the current instance is equal to a specified object or Int32 or not. There are two methods in the overload list of this method as follows: Equals(Int32) Method Equals(Object) Method This method is used to return a value indicating whether the current instance is equal to a specified Int32 value or not. Syntax: public bool Equals (int obj);Here, it takes a Int32 value to compare to this instance. Return Value: This method returns true if obj has the same value as this instance otherwise, false. Below programs illustrate the use of Int32.Equals(Int32) Method: Example 1: // C# program to demonstrate the// Int32.Equals(Int32) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 4562; // Declaring and initializing value2 int value2 = 2563; // using Equals(Int32) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }} 4562 is not equal to 2563 Example 2: // C# program to demonstrate the// Int32.Equals(Int32) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(455, 578); get(445, 445); get(10, 20); get(Int32.MaxValue, Int32.MinValue); } // defining get() method public static void get(int value1, int value2) { // using Equals(Int32) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }} 455 is not equal to 578 445 is equal to 445 10 is not equal to 20 2147483647 is not equal to -2147483648 This method is used to returns a value indicating whether the current instance is equal to a specified object or not. Syntax: public override bool Equals (object obj);Here, it takes an object to compare with this instance. Return Value: This method returns true if obj is an instance of Int32 and equals the value of this instance otherwise, false. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the// Int32.Equals(Object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 object value2 = 1 / 45; // using Equals(object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }} 10 is not equal to 0 Example 2: // C# program to demonstrate the// Int32.Equals(Object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(547, 585); get(555, 489); get(100, 100); get(745, 725); } // defining get() method public static void get(int value1, object value2) { // compare both Int32 value // using Equals(object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); }} 547 is not equal to 585 555 is not equal to 489 100 is equal to 100 745 is not equal to 725 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.int32.equals?view=netframework-4.7.2 CSharp-Int32-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Apr, 2019" }, { "code": null, "e": 236, "s": 28, "text": "Int32.Equals() Method is used to get a value which indicates whether the current instance is equal to a specified object or Int32 or not. There are two methods in the overload list of this method as follows:" }, { "code": null, "e": 257, "s": 236, "text": "Equals(Int32) Method" }, { "code": null, "e": 279, "s": 257, "text": "Equals(Object) Method" }, { "code": null, "e": 401, "s": 279, "text": "This method is used to return a value indicating whether the current instance is equal to a specified Int32 value or not." }, { "code": null, "e": 496, "s": 401, "text": "Syntax: public bool Equals (int obj);Here, it takes a Int32 value to compare to this instance." }, { "code": null, "e": 596, "s": 496, "text": "Return Value: This method returns true if obj has the same value as this instance otherwise, false." }, { "code": null, "e": 661, "s": 596, "text": "Below programs illustrate the use of Int32.Equals(Int32) Method:" }, { "code": null, "e": 672, "s": 661, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Int32.Equals(Int32) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 4562; // Declaring and initializing value2 int value2 = 2563; // using Equals(Int32) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", value1, value2); else Console.WriteLine(\"{0} is not equal to {1}\", value1, value2); }}", "e": 1351, "s": 672, "text": null }, { "code": null, "e": 1378, "s": 1351, "text": "4562 is not equal to 2563\n" }, { "code": null, "e": 1389, "s": 1378, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Int32.Equals(Int32) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(455, 578); get(445, 445); get(10, 20); get(Int32.MaxValue, Int32.MinValue); } // defining get() method public static void get(int value1, int value2) { // using Equals(Int32) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", value1, value2); else Console.WriteLine(\"{0} is not equal to {1}\", value1, value2); }}", "e": 2157, "s": 1389, "text": null }, { "code": null, "e": 2263, "s": 2157, "text": "455 is not equal to 578\n445 is equal to 445\n10 is not equal to 20\n2147483647 is not equal to -2147483648\n" }, { "code": null, "e": 2381, "s": 2263, "text": "This method is used to returns a value indicating whether the current instance is equal to a specified object or not." }, { "code": null, "e": 2486, "s": 2381, "text": "Syntax: public override bool Equals (object obj);Here, it takes an object to compare with this instance." }, { "code": null, "e": 2612, "s": 2486, "text": "Return Value: This method returns true if obj is an instance of Int32 and equals the value of this instance otherwise, false." }, { "code": null, "e": 2677, "s": 2612, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 2688, "s": 2677, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Int32.Equals(Object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 10; // Declaring and initializing value2 object value2 = 1 / 45; // using Equals(object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", value1, value2); else Console.WriteLine(\"{0} is not equal to {1}\", value1, value2); }}", "e": 3372, "s": 2688, "text": null }, { "code": null, "e": 3394, "s": 3372, "text": "10 is not equal to 0\n" }, { "code": null, "e": 3405, "s": 3394, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// Int32.Equals(Object) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(547, 585); get(555, 489); get(100, 100); get(745, 725); } // defining get() method public static void get(int value1, object value2) { // compare both Int32 value // using Equals(object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", value1, value2); else Console.WriteLine(\"{0} is not equal to {1}\", value1, value2); }}", "e": 4215, "s": 3405, "text": null }, { "code": null, "e": 4308, "s": 4215, "text": "547 is not equal to 585\n555 is not equal to 489\n100 is equal to 100\n745 is not equal to 725\n" }, { "code": null, "e": 4319, "s": 4308, "text": "Reference:" }, { "code": null, "e": 4407, "s": 4319, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.int32.equals?view=netframework-4.7.2" }, { "code": null, "e": 4427, "s": 4407, "text": "CSharp-Int32-Struct" }, { "code": null, "e": 4441, "s": 4427, "text": "CSharp-method" }, { "code": null, "e": 4444, "s": 4441, "text": "C#" } ]
Form Handling in ReactJS
In this article, we are going to see how to handle the forms properly in a React application. Handling Forms is one of the most crucial parts needed while building a real-world React application. It is all about taking the inputs from the user, validating it and displaying if there are errors in the data submitted by the user. In this example, we will build an Information Page that takes the information from the user, validates it and displays the result accordingly. Here, we have App.js as the parent component of the Details.js component. Details.js import React, { useState } from 'react'; const Details = () => { const [name, setName] = useState(''); const [number, setNumber] = useState(null); const [mssg, setMssg] = useState(null); const submit = (e) => { e.preventDefault(); if (!Number(number)) { setMssg('Phone Number should be of number type only'); } else { setMssg('Form Submitted!'); } }; return ( <form onSubmit={submit}> <input placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <input placeholder="Phone Number" value={number} onChange={(e) => setNumber(e.target.value)} /> <button>Submit</button> {mssg} </form> ); }; export default Details; App.js import React from 'react'; import Details from './Details'; const App = () => { return ( <div> <h1>Information Page:</h1> <Details /> </div> ); }; export default App; In the above example, we are taking the inputs from the user and storing it in the state of the application. If the phone number entered by the user is not of number type, then the error message will be displayed. This will produce the following result.
[ { "code": null, "e": 1156, "s": 1062, "text": "In this article, we are going to see how to handle the forms properly in a React application." }, { "code": null, "e": 1391, "s": 1156, "text": "Handling Forms is one of the most crucial parts needed while building a real-world React application. It is all about taking the inputs from the user, validating it and displaying if there are errors in the data submitted by the user." }, { "code": null, "e": 1534, "s": 1391, "text": "In this example, we will build an Information Page that takes the information from the user, validates it and displays the result accordingly." }, { "code": null, "e": 1608, "s": 1534, "text": "Here, we have App.js as the parent component of the Details.js component." }, { "code": null, "e": 1619, "s": 1608, "text": "Details.js" }, { "code": null, "e": 2406, "s": 1619, "text": "import React, { useState } from 'react';\n\nconst Details = () => {\n const [name, setName] = useState('');\n const [number, setNumber] = useState(null);\n const [mssg, setMssg] = useState(null);\n\n const submit = (e) => {\n e.preventDefault();\n if (!Number(number)) {\n setMssg('Phone Number should be of number type only');\n } else {\n setMssg('Form Submitted!');\n }\n };\n return (\n <form onSubmit={submit}>\n <input\n placeholder=\"Name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n />\n\n <input\n placeholder=\"Phone Number\"\n value={number}\n onChange={(e) => setNumber(e.target.value)}\n />\n <button>Submit</button>\n {mssg}\n </form>\n );\n};\nexport default Details;" }, { "code": null, "e": 2413, "s": 2406, "text": "App.js" }, { "code": null, "e": 2611, "s": 2413, "text": "import React from 'react';\nimport Details from './Details';\n\nconst App = () => {\n return (\n <div>\n <h1>Information Page:</h1>\n <Details />\n </div>\n );\n};\nexport default App;" }, { "code": null, "e": 2825, "s": 2611, "text": "In the above example, we are taking the inputs from the user and storing it in the state of the application. If the phone number entered by the user is not of number type, then the error message will be displayed." }, { "code": null, "e": 2865, "s": 2825, "text": "This will produce the following result." } ]
C program to draw a solar system using computer graphics - GeeksforGeeks
02 Jul, 2021 Prerequisite: Graphics.h, include graphics.h in CodeBlocks Required header files: #include <stdio.h> #include <conio.h> #include <graphics.h> #include <dos.h> #include <math.h> Functions used: getmaxx(): It returns the maximum X coordinate for current graphics mode and driver. setcolor(): It is used to set the current drawing color to the new color. outtextxy(): It is used to display the text or string at a specified point (x, y) on the screen. rectangle(): It is used to draw a rectangle.Coordinates of left top and right bottom corner are required to draw the rectangle.Left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of bottom right corner, bottom specifies the Y-coordinate of bottom right corner. Coordinates of left top and right bottom corner are required to draw the rectangle. Left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of bottom right corner, bottom specifies the Y-coordinate of bottom right corner. Approach: To draw a solar system, start with a concentric ellipse because all the planet’s paths are elliptical. Make a circle in the center of the ellipse and fill it with yellow paint to represent the sun. Draw different circles, fill them with different colors and then choose the correct coordinate to place all of these in the ellipse’s path. Change the positions of all the planets so that they appear to be moving on an ellipse. Below is the C program to draw the solar system using the above functions discussed: C // C program to draw solar system using// computer graphics#include <conio.h>#include <dos.h>#include <graphics.h>#include <math.h>#include <stdio.h> // Function to manipulates the position// of planets on the orbitvoid planetMotion(int xrad, int yrad, int midx, int midy, int x[70], int y[70]){ int i, j = 0; // Positions of planets in their // corresponding orbits for (i = 360; i > 0; i = i - 6) { x[j] = midx - (xrad * cos((i * 3.14) / 180)); y[j++] = midy - (yrad * sin((i * 3.14) / 180)); } return;} // Driver Codeint main(){ // Initialize graphic driver int gdriver = DETECT, gmode, err; int i = 0, midx, midy; int xrad[9], yrad[9], x[9][70], y[9][70]; int pos[9], planet[9], tmp; // Initialize graphics mode by // passing the three arguments // to initgraph() // &gdriver is the address of gdriver // variable, &gmode is the address of // gmode and "C:\\Turboc3\\BGI" is the // directory path where BGI files // are stored initgraph(&gdriver, &gmode, ""); err = graphresult(); if (err ! = grOk) { // Error occurred printf("Graphics Error: %s", grapherrormsg(err)); return 0; } // Mid positions at x and y-axis midx = getmaxx() - 220; midy = getmaxy() - 150; // Manipulating radius of all // the nine planets Planet[0] = 8; for (i = 1; i < 9; i++) { planet[i] = planet[i - 1] + 1; } // Offset position for the planets // on their corresponding orbit for (i = 0; i < 9; i++) { pos[i] = i * 6; } // Orbits for all 9 planets Xrad[0] = 70, yrad[0] = 40; for (i = 1; i < 9; i++) { xrad[i] = xrad[i - 1] + 38; yrad[i] = yrad[i - 1] + 20; } // Positions of planets on their // corresponding orbits for (i = 0; i < 9; i++) { planetMotion(xrad[i], yrad[i], midx, midy, x[i], y[i]); } while (!kbhit()) { // Drawing 9 orbits Setcolor(WHITE); for (i = 0; i < 9; i++) { setcolor(CYAN); ellipse(midx, midy, 0, 360, xrad[i], yrad[i]); } // Sun at the mid of solar system outtextxy(midx, midy, " SUN"); setcolor(YELLOW); setfillstyle(SOLID_FILL, YELLOW); circle(midx, midy, 30); floodfill(midx, midy, YELLOW); // Mercury in first orbit Setcolor(CYAN); Setfillstyle(SOLID_FILL, CYAN); Outtextxy(x[0][pos[0]], y[0][pos[0]], " MERCURY"); Pieslice(x[0][pos[0]], y[0][pos[0]], 0, 360, planet[0]); // Venus in second orbit Setcolor(GREEN); Setfillstyle(SOLID_FILL, GREEN); Outtextxy(x[1][pos[1]], y[1][pos[1]], " VENUS"); Pieslice(x[1][pos[1]], y[1][pos[1]], 0, 360, planet[1]); // Earth in third orbit Setcolor(BLUE); Setfillstyle(SOLID_FILL, BLUE); Outtextxy(x[2][pos[2]], y[2][pos[2]], " EARTH"); Pieslice(x[2][pos[2]], y[2][pos[2]], 0, 360, planet[2]); // Mars in fourth orbit Setcolor(RED); Setfillstyle(SOLID_FILL, RED); Outtextxy(x[3][pos[3]], y[3][pos[3]], " MARS"); Pieslice(x[3][pos[3]], y[3][pos[3]], 0, 360, planet[3]); // Jupiter in fifth orbit setcolor(BROWN); setfillstyle(SOLID_FILL, BROWN); outtextxy(x[4][pos[4]], y[4][pos[4]], " JUPITER"); pieslice(x[4][pos[4]], y[4][pos[4]], 0, 360, planet[4]); // Saturn in sixth orbit Setcolor(LIGHTGRAY); Setfillstyle(SOLID_FILL, LIGHTGRAY); Outtextxy(x[5][pos[5]], y[5][pos[5]], " SATURN"); Pieslice(x[5][pos[5]], y[5][pos[5]], 0, 360, planet[5]); // Uranus in seventh orbit Setcolor(LIGHTGREEN); Setfillstyle(SOLID_FILL, LIGHTGREEN); Outtextxy (x [6] [pos [6]], y [6] [pos [6]], “ URANUS"); pieslice (x [6] [pos [6]], y [6] [pos [6]], 0, 360, planet [6]); // Neptune in eighth orbit Setcolor (LIGHTBLUE); Setfillstyle (SOLID_FILL, LIGHTBLUE); Outtextxy (x [7] [pos [7]], y [7] [pos [7]], " NEPTUNE"); Pieslice (x [7] [pos [7]], y [7] [pos [7]], 0, 360, planet [7]); // Pluto in ninth orbit Setcolor (LIGHTRED); Setfillstyle (SOLID_FILL, LIGHTRED); Outtextxy (x [8] [pos [8]], y [8] [pos [8]], " PLUTO"); Pieslice (x [8] [pos [8]], y [8] [pos [8]], 0, 360, planet [8]); // Checking for one complete // rotation for (i = 0; i < 9; i++) { if (pos[i] <= 0) { pos[i] = 59; } else { pos[i] = pos[i] - 1; } } // Sleep for 100 milliseconds Delay (100); // Clears graphic screen Cleardevice (); } // Deallocate memory allocated // for graphic screen closegraph(); return 0;} Output: anikakapoor c-graphics computer-graphics C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Strings in C UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24234, "s": 24206, "text": "\n02 Jul, 2021" }, { "code": null, "e": 24293, "s": 24234, "text": "Prerequisite: Graphics.h, include graphics.h in CodeBlocks" }, { "code": null, "e": 24316, "s": 24293, "text": "Required header files:" }, { "code": null, "e": 24335, "s": 24316, "text": "#include <stdio.h>" }, { "code": null, "e": 24354, "s": 24335, "text": "#include <conio.h>" }, { "code": null, "e": 24376, "s": 24354, "text": "#include <graphics.h>" }, { "code": null, "e": 24393, "s": 24376, "text": "#include <dos.h>" }, { "code": null, "e": 24411, "s": 24393, "text": "#include <math.h>" }, { "code": null, "e": 24427, "s": 24411, "text": "Functions used:" }, { "code": null, "e": 24512, "s": 24427, "text": "getmaxx(): It returns the maximum X coordinate for current graphics mode and driver." }, { "code": null, "e": 24587, "s": 24512, "text": "setcolor(): It is used to set the current drawing color to the new color." }, { "code": null, "e": 24684, "s": 24587, "text": "outtextxy(): It is used to display the text or string at a specified point (x, y) on the screen." }, { "code": null, "e": 25029, "s": 24684, "text": "rectangle(): It is used to draw a rectangle.Coordinates of left top and right bottom corner are required to draw the rectangle.Left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of bottom right corner, bottom specifies the Y-coordinate of bottom right corner." }, { "code": null, "e": 25113, "s": 25029, "text": "Coordinates of left top and right bottom corner are required to draw the rectangle." }, { "code": null, "e": 25331, "s": 25113, "text": "Left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of bottom right corner, bottom specifies the Y-coordinate of bottom right corner." }, { "code": null, "e": 25341, "s": 25331, "text": "Approach:" }, { "code": null, "e": 25444, "s": 25341, "text": "To draw a solar system, start with a concentric ellipse because all the planet’s paths are elliptical." }, { "code": null, "e": 25539, "s": 25444, "text": "Make a circle in the center of the ellipse and fill it with yellow paint to represent the sun." }, { "code": null, "e": 25679, "s": 25539, "text": "Draw different circles, fill them with different colors and then choose the correct coordinate to place all of these in the ellipse’s path." }, { "code": null, "e": 25767, "s": 25679, "text": "Change the positions of all the planets so that they appear to be moving on an ellipse." }, { "code": null, "e": 25852, "s": 25767, "text": "Below is the C program to draw the solar system using the above functions discussed:" }, { "code": null, "e": 25854, "s": 25852, "text": "C" }, { "code": "// C program to draw solar system using// computer graphics#include <conio.h>#include <dos.h>#include <graphics.h>#include <math.h>#include <stdio.h> // Function to manipulates the position// of planets on the orbitvoid planetMotion(int xrad, int yrad, int midx, int midy, int x[70], int y[70]){ int i, j = 0; // Positions of planets in their // corresponding orbits for (i = 360; i > 0; i = i - 6) { x[j] = midx - (xrad * cos((i * 3.14) / 180)); y[j++] = midy - (yrad * sin((i * 3.14) / 180)); } return;} // Driver Codeint main(){ // Initialize graphic driver int gdriver = DETECT, gmode, err; int i = 0, midx, midy; int xrad[9], yrad[9], x[9][70], y[9][70]; int pos[9], planet[9], tmp; // Initialize graphics mode by // passing the three arguments // to initgraph() // &gdriver is the address of gdriver // variable, &gmode is the address of // gmode and \"C:\\\\Turboc3\\\\BGI\" is the // directory path where BGI files // are stored initgraph(&gdriver, &gmode, \"\"); err = graphresult(); if (err ! = grOk) { // Error occurred printf(\"Graphics Error: %s\", grapherrormsg(err)); return 0; } // Mid positions at x and y-axis midx = getmaxx() - 220; midy = getmaxy() - 150; // Manipulating radius of all // the nine planets Planet[0] = 8; for (i = 1; i < 9; i++) { planet[i] = planet[i - 1] + 1; } // Offset position for the planets // on their corresponding orbit for (i = 0; i < 9; i++) { pos[i] = i * 6; } // Orbits for all 9 planets Xrad[0] = 70, yrad[0] = 40; for (i = 1; i < 9; i++) { xrad[i] = xrad[i - 1] + 38; yrad[i] = yrad[i - 1] + 20; } // Positions of planets on their // corresponding orbits for (i = 0; i < 9; i++) { planetMotion(xrad[i], yrad[i], midx, midy, x[i], y[i]); } while (!kbhit()) { // Drawing 9 orbits Setcolor(WHITE); for (i = 0; i < 9; i++) { setcolor(CYAN); ellipse(midx, midy, 0, 360, xrad[i], yrad[i]); } // Sun at the mid of solar system outtextxy(midx, midy, \" SUN\"); setcolor(YELLOW); setfillstyle(SOLID_FILL, YELLOW); circle(midx, midy, 30); floodfill(midx, midy, YELLOW); // Mercury in first orbit Setcolor(CYAN); Setfillstyle(SOLID_FILL, CYAN); Outtextxy(x[0][pos[0]], y[0][pos[0]], \" MERCURY\"); Pieslice(x[0][pos[0]], y[0][pos[0]], 0, 360, planet[0]); // Venus in second orbit Setcolor(GREEN); Setfillstyle(SOLID_FILL, GREEN); Outtextxy(x[1][pos[1]], y[1][pos[1]], \" VENUS\"); Pieslice(x[1][pos[1]], y[1][pos[1]], 0, 360, planet[1]); // Earth in third orbit Setcolor(BLUE); Setfillstyle(SOLID_FILL, BLUE); Outtextxy(x[2][pos[2]], y[2][pos[2]], \" EARTH\"); Pieslice(x[2][pos[2]], y[2][pos[2]], 0, 360, planet[2]); // Mars in fourth orbit Setcolor(RED); Setfillstyle(SOLID_FILL, RED); Outtextxy(x[3][pos[3]], y[3][pos[3]], \" MARS\"); Pieslice(x[3][pos[3]], y[3][pos[3]], 0, 360, planet[3]); // Jupiter in fifth orbit setcolor(BROWN); setfillstyle(SOLID_FILL, BROWN); outtextxy(x[4][pos[4]], y[4][pos[4]], \" JUPITER\"); pieslice(x[4][pos[4]], y[4][pos[4]], 0, 360, planet[4]); // Saturn in sixth orbit Setcolor(LIGHTGRAY); Setfillstyle(SOLID_FILL, LIGHTGRAY); Outtextxy(x[5][pos[5]], y[5][pos[5]], \" SATURN\"); Pieslice(x[5][pos[5]], y[5][pos[5]], 0, 360, planet[5]); // Uranus in seventh orbit Setcolor(LIGHTGREEN); Setfillstyle(SOLID_FILL, LIGHTGREEN); Outtextxy (x [6] [pos [6]], y [6] [pos [6]], “ URANUS\"); pieslice (x [6] [pos [6]], y [6] [pos [6]], 0, 360, planet [6]); // Neptune in eighth orbit Setcolor (LIGHTBLUE); Setfillstyle (SOLID_FILL, LIGHTBLUE); Outtextxy (x [7] [pos [7]], y [7] [pos [7]], \" NEPTUNE\"); Pieslice (x [7] [pos [7]], y [7] [pos [7]], 0, 360, planet [7]); // Pluto in ninth orbit Setcolor (LIGHTRED); Setfillstyle (SOLID_FILL, LIGHTRED); Outtextxy (x [8] [pos [8]], y [8] [pos [8]], \" PLUTO\"); Pieslice (x [8] [pos [8]], y [8] [pos [8]], 0, 360, planet [8]); // Checking for one complete // rotation for (i = 0; i < 9; i++) { if (pos[i] <= 0) { pos[i] = 59; } else { pos[i] = pos[i] - 1; } } // Sleep for 100 milliseconds Delay (100); // Clears graphic screen Cleardevice (); } // Deallocate memory allocated // for graphic screen closegraph(); return 0;}", "e": 31472, "s": 25854, "text": null }, { "code": null, "e": 31480, "s": 31472, "text": "Output:" }, { "code": null, "e": 31492, "s": 31480, "text": "anikakapoor" }, { "code": null, "e": 31503, "s": 31492, "text": "c-graphics" }, { "code": null, "e": 31521, "s": 31503, "text": "computer-graphics" }, { "code": null, "e": 31532, "s": 31521, "text": "C Language" }, { "code": null, "e": 31543, "s": 31532, "text": "C Programs" }, { "code": null, "e": 31641, "s": 31543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31650, "s": 31641, "text": "Comments" }, { "code": null, "e": 31663, "s": 31650, "text": "Old Comments" }, { "code": null, "e": 31701, "s": 31663, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31727, "s": 31701, "text": "Exception Handling in C++" }, { "code": null, "e": 31747, "s": 31727, "text": "Multithreading in C" }, { "code": null, "e": 31769, "s": 31747, "text": "'this' pointer in C++" }, { "code": null, "e": 31807, "s": 31769, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31820, "s": 31807, "text": "Strings in C" }, { "code": null, "e": 31858, "s": 31820, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31899, "s": 31858, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31940, "s": 31899, "text": "C Program to read contents of Whole File" } ]
Check if list is sorted or not in Python
Lists are the most widely used data collectios in python. We may come across situation when we need to know if the given list is already sorted or not. In this article we will see the approaches to achieve this. We take a copy of the given list, apply sort function to it and store that copy as a new list. Then we compare it with the original list and check if they are equal or not. Live Demo listA = [11,23,42,51,67] #Given list print("Given list : ",listA) listA_copy = listA[:] # Apply sort to copy listA_copy.sort() if (listA == listA_copy): print("Yes, List is sorted.") else: print("No, List is not sorted.") # Checking again listB = [11,23,21,51,67] #Given list print("Given list : ",listB) listB_copy = listB[:] # Apply sort to copy listB_copy.sort() if (listB == listB_copy): print("Yes, List is sorted.") else: print("No, List is not sorted.") Running the above code gives us the following result − Given list : [11, 23, 42, 51, 67] Yes, List is sorted. Given list : [11, 23, 21, 51, 67] No, List is not sorted. We can use the all function to check if every element of the list is smaller than the element next to it and apply the range function to traverse through all the elements. Live Demo listA = [11,23,42,51,67] #Given list print("Given list : ",listA) # Apply all and range if (all(listA[i] <= listA[i + 1] for i in range(len(listA)-1))): print("Yes, List is sorted.") else: print("No, List is not sorted.") # Checking again listB = [11,23,21,51,67] print("Given list : ",listB) # Apply all and range if (all(listB[i] <= listB[i + 1] for i in range(len(listB)-1))): print("Yes, List is sorted.") else: print("No, List is not sorted.") Running the above code gives us the following result − Given list : [11, 23, 42, 51, 67] Yes, List is sorted. Given list : [11, 23, 21, 51, 67] No, List is not sorted.
[ { "code": null, "e": 1274, "s": 1062, "text": "Lists are the most widely used data collectios in python. We may come across situation when we need to know if the given list is already sorted or not. In this article we will see the approaches to achieve this." }, { "code": null, "e": 1447, "s": 1274, "text": "We take a copy of the given list, apply sort function to it and store that copy as a new list. Then we compare it with the original list and check if they are equal or not." }, { "code": null, "e": 1458, "s": 1447, "text": " Live Demo" }, { "code": null, "e": 1932, "s": 1458, "text": "listA = [11,23,42,51,67]\n#Given list\nprint(\"Given list : \",listA)\nlistA_copy = listA[:]\n# Apply sort to copy\nlistA_copy.sort()\nif (listA == listA_copy):\n print(\"Yes, List is sorted.\")\nelse:\n print(\"No, List is not sorted.\")\n\n# Checking again\nlistB = [11,23,21,51,67]\n#Given list\nprint(\"Given list : \",listB)\nlistB_copy = listB[:]\n# Apply sort to copy\nlistB_copy.sort()\nif (listB == listB_copy):\n print(\"Yes, List is sorted.\")\nelse:\n print(\"No, List is not sorted.\")" }, { "code": null, "e": 1987, "s": 1932, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2100, "s": 1987, "text": "Given list : [11, 23, 42, 51, 67]\nYes, List is sorted.\nGiven list : [11, 23, 21, 51, 67]\nNo, List is not sorted." }, { "code": null, "e": 2272, "s": 2100, "text": "We can use the all function to check if every element of the list is smaller than the element next to it and apply the range function to traverse through all the elements." }, { "code": null, "e": 2283, "s": 2272, "text": " Live Demo" }, { "code": null, "e": 2744, "s": 2283, "text": "listA = [11,23,42,51,67]\n#Given list\nprint(\"Given list : \",listA)\n# Apply all and range\nif (all(listA[i] <= listA[i + 1] for i in range(len(listA)-1))):\n print(\"Yes, List is sorted.\")\nelse:\n print(\"No, List is not sorted.\")\n# Checking again\nlistB = [11,23,21,51,67]\nprint(\"Given list : \",listB)\n# Apply all and range\nif (all(listB[i] <= listB[i + 1] for i in range(len(listB)-1))):\n print(\"Yes, List is sorted.\")\nelse:\n print(\"No, List is not sorted.\")" }, { "code": null, "e": 2799, "s": 2744, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2912, "s": 2799, "text": "Given list : [11, 23, 42, 51, 67]\nYes, List is sorted.\nGiven list : [11, 23, 21, 51, 67]\nNo, List is not sorted." } ]
Java - The Map.Entry Interface
The Map.Entry interface enables you to work with a map entry. The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object. Following table summarizes the methods declared by this interface − boolean equals(Object obj) Returns true if obj is a Map.Entry whose key and value are equal to that of the invoking object. Object getKey( ) Returns the key for this map entry. Object getValue( ) Returns the value for this map entry. int hashCode( ) Returns the hash code for this map entry. Object setValue(Object v) Sets the value for this map entry to v. A ClassCastException is thrown if v is not the correct type for the map. A NullPointerException is thrown if v is null and the map does not permit null keys. An UnsupportedOperationException is thrown if the map cannot be changed. Following is an example showing how Map.Entry can be used − import java.util.*; public class HashMapDemo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("Zara", new Double(3434.34)); hm.put("Mahnaz", new Double(123.22)); hm.put("Ayan", new Double(1378.00)); hm.put("Daisy", new Double(99.22)); hm.put("Qadir", new Double(-19.08)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into Zara's account double balance = ((Double)hm.get("Zara")).doubleValue(); hm.put("Zara", new Double(balance + 1000)); System.out.println("Zara's new balance: " + hm.get("Zara")); } } This will produce the following result − Daisy: 99.22 Ayan: 1378.0 Zara: 3434.34 Qadir: -19.08 Mahnaz: 123.22 Zara's new balance: 4434.34 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2439, "s": 2377, "text": "The Map.Entry interface enables you to work with a map entry." }, { "code": null, "e": 2584, "s": 2439, "text": "The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object." }, { "code": null, "e": 2652, "s": 2584, "text": "Following table summarizes the methods declared by this interface −" }, { "code": null, "e": 2679, "s": 2652, "text": "boolean equals(Object obj)" }, { "code": null, "e": 2776, "s": 2679, "text": "Returns true if obj is a Map.Entry whose key and value are equal to that of the invoking object." }, { "code": null, "e": 2793, "s": 2776, "text": "Object getKey( )" }, { "code": null, "e": 2829, "s": 2793, "text": "Returns the key for this map entry." }, { "code": null, "e": 2848, "s": 2829, "text": "Object getValue( )" }, { "code": null, "e": 2886, "s": 2848, "text": "Returns the value for this map entry." }, { "code": null, "e": 2902, "s": 2886, "text": "int hashCode( )" }, { "code": null, "e": 2944, "s": 2902, "text": "Returns the hash code for this map entry." }, { "code": null, "e": 2970, "s": 2944, "text": "Object setValue(Object v)" }, { "code": null, "e": 3241, "s": 2970, "text": "Sets the value for this map entry to v. A ClassCastException is thrown if v is not the correct type for the map. A NullPointerException is thrown if v is null and the map does not permit null keys. An UnsupportedOperationException is thrown if the map cannot be changed." }, { "code": null, "e": 3301, "s": 3241, "text": "Following is an example showing how Map.Entry can be used −" }, { "code": null, "e": 4309, "s": 3301, "text": "import java.util.*;\npublic class HashMapDemo {\n\n public static void main(String args[]) {\n // Create a hash map\n HashMap hm = new HashMap();\n\n // Put elements to the map\n hm.put(\"Zara\", new Double(3434.34));\n hm.put(\"Mahnaz\", new Double(123.22));\n hm.put(\"Ayan\", new Double(1378.00));\n hm.put(\"Daisy\", new Double(99.22));\n hm.put(\"Qadir\", new Double(-19.08));\n \n // Get a set of the entries\n Set set = hm.entrySet();\n \n // Get an iterator\n Iterator i = set.iterator();\n \n // Display elements \n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n \n // Deposit 1000 into Zara's account\n double balance = ((Double)hm.get(\"Zara\")).doubleValue();\n hm.put(\"Zara\", new Double(balance + 1000));\n System.out.println(\"Zara's new balance: \" + hm.get(\"Zara\"));\n }\n}" }, { "code": null, "e": 4350, "s": 4309, "text": "This will produce the following result −" }, { "code": null, "e": 4449, "s": 4350, "text": "Daisy: 99.22\nAyan: 1378.0\nZara: 3434.34\nQadir: -19.08\nMahnaz: 123.22\n\nZara's new balance: 4434.34\n" }, { "code": null, "e": 4482, "s": 4449, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4498, "s": 4482, "text": " Malhar Lathkar" }, { "code": null, "e": 4531, "s": 4498, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4547, "s": 4531, "text": " Malhar Lathkar" }, { "code": null, "e": 4582, "s": 4547, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4596, "s": 4582, "text": " Anadi Sharma" }, { "code": null, "e": 4630, "s": 4596, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4644, "s": 4630, "text": " Tushar Kale" }, { "code": null, "e": 4681, "s": 4644, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4696, "s": 4681, "text": " Monica Mittal" }, { "code": null, "e": 4729, "s": 4696, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4748, "s": 4729, "text": " Arnab Chakraborty" }, { "code": null, "e": 4755, "s": 4748, "text": " Print" }, { "code": null, "e": 4766, "s": 4755, "text": " Add Notes" } ]
Money Distributions | Practice | GeeksforGeeks
Find the number of ways in which N coins can be distributed among K pupils such that each pupil receives at least one coin each. Two distributions are said to be different only if they have at least one pupil who got a different number of coins. Example 1: Input: N = 7, K = 3 Output: 15 Explanation: Coin distribution can be any of the following 15 ways. {1,1,5}, {1,5,1}, {5,1,1}, {2,1,4}, {1,2,4}, {1,4,2} {2,4,1}, {4,1,2}, {4,2,1}, {3,1,3}, {1,3,3}, {3,3,1} {2,2,3}, {2,3,2}, {3,2,2} Example 2: Input: N = 5, K = 5 Output: 1 Explanation: {1, 1, 1, 1, 1} is the only way. Your Task: You don't need to read or print anything. Your task is to complete the function totalWays() which takes N and K as input parameters and returns the number of possible distributions modulo 10^9+7. Expected Time Complexity: O(N) Expected Space Complexity: O(N) Constraints: 1 <= N, K <= 100000 -1 sarkarrohit6505 months ago Java Solution : Approach : modulo inverse , nCr public long power(long a,long b , long mod){ long ans = 1L; while(b>0){ if((b&1)!=0 ){ ans = (ans*a)%mod; } a = (a*a)%mod; b>>=1; } return ans; } public int nCr(int N,int R){ long res= 1L; //long deno=1L; if(R > N-R){ R = N-R; } long mod =(long) 1e9+7; for(int i=0;i<R;i++){ res = (res *(N-i))%mod; res= res*power(i+1 , mod-2 ,mod)%mod; } return (int)res; } public int totalWays(int N, int K) { if(K > N)return 0; if(K==N)return 1; return nCr(N-1,K-1); } +5 sunnysaraff5 months ago Explanation:- (1) Sum of K persons coins = N (2) K1 + K2 + ... Kk = N where Ki≥0 has solution nCr(N+K-1,K-1) according to standard principles of partitioning in Binomial Theorem (You must have read about this in your lower classes) (3) Here, we have to do some modification since above formula works when every Ki≥0 but in our problem Ki≥1 So, Substitute, Ki - 1 = Ui (4) Transformed Eqn will be:- Sum of Ui = N - K (5) Now, Apply the above formula on this modified Equation. (6) Answer = nCr(N-1,K-1) +1 gowthamreddyuppunuri5 months ago int64_t power(int64_t a, int64_t b,int mod){ int64_t res = 1; while(b>0){ if(b%2 != 0){ res = (res*a)%mod; } b /= 2; a = (a*a)%mod; } return res; } int totalWays(int N, int K) { // Code here. if(K>N){ return 0;//no possible ways } // C(N+K-1,K-1);// if atleast 0 is can be given // C(N+K-1-K,K-1); // if atleast 1 to be given //i.e C(N-1,K-1) int n = N-1; int r = K-1; r = min(r,n-r); int mod = 1e9+7; int64_t ans = 1; for(int i=0,j=n; i<r; i++,j--){ ans = (ans*j)%mod; // ans = (ans/(i+1)); ans = ans*power(i+1,mod-2,mod)%mod; //completey perform modular division and multiplication //don't do partially } return ans; } +3 geminicode5 months ago This is working in Python !!! Donno if it's expected in the question. import math class Solution: def totalWays(self, n,k): # Code here # we need to find n-1 C k-1 if n<k : return 0 den = (math.factorial(k-1) * math.factorial(n-k)) ans = math.factorial(n-1) // den return ans%1000000007 +1 mastermind_5 months ago (C++) Combinatorics Solution, answer = , ~ O(32*N) Time , O(1) Space. const int mod = 1e9 + 7; int64_t expo(int64_t a, int64_t b) { int64_t ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; (a *= a) %= mod; b >>= 1; } return ans; } int totalWays(int n, int k) { if (n < k)return 0; int64_t ans = 1; for (int i = n - k + 1; i <= n - 1; i++)(ans *= i) %= mod; for (int i = 1; i <= k - 1; i++)(ans *= expo(i, mod - 2)) %= mod; return ans; } -3 asifalimnstu2 years ago asifalimnstu 0.02 sec c++https://practice.geeksforge... 0 Tourist ka Dost2 years ago Tourist ka Dost Getting memory error, while trying to solve in python. I'm getting correct answers in custom input and Compile & test. I think it's because of Python 32-bit installation. Please help! -3 Ashish4 years ago Ashish do we have to print the cases as well? If yes, then how? 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": 474, "s": 226, "text": "Find the number of ways in which N coins can be distributed among K pupils such that each pupil receives at least one coin each. Two distributions are said to be different only if they have at least one pupil who got a different number of coins.\n " }, { "code": null, "e": 485, "s": 474, "text": "Example 1:" }, { "code": null, "e": 721, "s": 485, "text": "Input: N = 7, K = 3\nOutput: 15\nExplanation: \nCoin distribution can be any of the following 15 ways. \n{1,1,5}, {1,5,1}, {5,1,1}, {2,1,4}, {1,2,4}, {1,4,2}\n{2,4,1}, {4,1,2}, {4,2,1}, {3,1,3}, {1,3,3}, {3,3,1}\n{2,2,3}, {2,3,2}, {3,2,2}\n\n\n" }, { "code": null, "e": 732, "s": 721, "text": "Example 2:" }, { "code": null, "e": 809, "s": 732, "text": "Input: N = 5, K = 5\nOutput: 1\nExplanation: {1, 1, 1, 1, 1} is the only way.\n" }, { "code": null, "e": 1020, "s": 811, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function totalWays() which takes N and K as input parameters and returns the number of possible distributions modulo 10^9+7.\n " }, { "code": null, "e": 1085, "s": 1020, "text": "Expected Time Complexity: O(N)\nExpected Space Complexity: O(N)\n " }, { "code": null, "e": 1118, "s": 1085, "text": "Constraints:\n1 <= N, K <= 100000" }, { "code": null, "e": 1121, "s": 1118, "text": "-1" }, { "code": null, "e": 1148, "s": 1121, "text": "sarkarrohit6505 months ago" }, { "code": null, "e": 1165, "s": 1148, "text": "Java Solution : " }, { "code": null, "e": 1198, "s": 1165, "text": "Approach : modulo inverse , nCr" }, { "code": null, "e": 1973, "s": 1198, "text": "public long power(long a,long b , long mod){\n \n long ans = 1L;\n while(b>0){\n if((b&1)!=0 ){\n ans = (ans*a)%mod;\n }\n a = (a*a)%mod;\n b>>=1;\n }\n return ans;\n }\n \n public int nCr(int N,int R){\n \n long res= 1L;\n //long deno=1L;\n if(R > N-R){\n R = N-R;\n }\n long mod =(long) 1e9+7;\n for(int i=0;i<R;i++){\n \n res = (res *(N-i))%mod;\n res= res*power(i+1 , mod-2 ,mod)%mod;\n \n }\n \n return (int)res;\n }\n public int totalWays(int N, int K)\n {\n if(K > N)return 0;\n if(K==N)return 1;\n \n return nCr(N-1,K-1);\n \n }" }, { "code": null, "e": 1976, "s": 1973, "text": "+5" }, { "code": null, "e": 2000, "s": 1976, "text": "sunnysaraff5 months ago" }, { "code": null, "e": 2015, "s": 2000, "text": "Explanation:- " }, { "code": null, "e": 2046, "s": 2015, "text": "(1) Sum of K persons coins = N" }, { "code": null, "e": 2236, "s": 2046, "text": "(2) K1 + K2 + ... Kk = N where Ki≥0 has solution nCr(N+K-1,K-1) according to standard principles of partitioning in Binomial Theorem (You must have read about this in your lower classes)" }, { "code": null, "e": 2372, "s": 2236, "text": "(3) Here, we have to do some modification since above formula works when every Ki≥0 but in our problem Ki≥1 So, Substitute, Ki - 1 = Ui" }, { "code": null, "e": 2420, "s": 2372, "text": "(4) Transformed Eqn will be:- Sum of Ui = N - K" }, { "code": null, "e": 2480, "s": 2420, "text": "(5) Now, Apply the above formula on this modified Equation." }, { "code": null, "e": 2506, "s": 2480, "text": "(6) Answer = nCr(N-1,K-1)" }, { "code": null, "e": 2509, "s": 2506, "text": "+1" }, { "code": null, "e": 2542, "s": 2509, "text": "gowthamreddyuppunuri5 months ago" }, { "code": null, "e": 3425, "s": 2542, "text": "int64_t power(int64_t a, int64_t b,int mod){\n\t int64_t res = 1;\n\t while(b>0){\n\t if(b%2 != 0){\n\t res = (res*a)%mod;\n\t }\n\t b /= 2;\n\t a = (a*a)%mod;\n\t }\n\t return res;\n\t}\n int totalWays(int N, int K) {\n // Code here.\n if(K>N){\n return 0;//no possible ways\n }\n // C(N+K-1,K-1);// if atleast 0 is can be given\n // C(N+K-1-K,K-1); // if atleast 1 to be given\n //i.e C(N-1,K-1)\n int n = N-1;\n int r = K-1;\n r = min(r,n-r);\n int mod = 1e9+7;\n int64_t ans = 1;\n for(int i=0,j=n; i<r; i++,j--){\n ans = (ans*j)%mod;\n // ans = (ans/(i+1));\n ans = ans*power(i+1,mod-2,mod)%mod;\n //completey perform modular division and multiplication\n //don't do partially\n }\n return ans;\n }" }, { "code": null, "e": 3428, "s": 3425, "text": "+3" }, { "code": null, "e": 3451, "s": 3428, "text": "geminicode5 months ago" }, { "code": null, "e": 3521, "s": 3451, "text": "This is working in Python !!! Donno if it's expected in the question." }, { "code": null, "e": 3769, "s": 3521, "text": "import math\nclass Solution:\n\tdef totalWays(self, n,k):\n\t\t# Code here\n\t\t# we need to find n-1 C k-1\n\t\tif n<k :\n\t\t return 0\n\t\tden = (math.factorial(k-1) * math.factorial(n-k))\n ans = math.factorial(n-1) // den\n return ans%1000000007" }, { "code": null, "e": 3772, "s": 3769, "text": "+1" }, { "code": null, "e": 3796, "s": 3772, "text": "mastermind_5 months ago" }, { "code": null, "e": 3879, "s": 3796, "text": "(C++) Combinatorics Solution, answer = , ~ O(32*N) Time , O(1) Space." }, { "code": null, "e": 4307, "s": 3879, "text": "const int mod = 1e9 + 7;\nint64_t expo(int64_t a, int64_t b) {\n int64_t ans = 1;\n while (b) {\n if (b & 1)(ans *= a) %= mod;\n (a *= a) %= mod;\n b >>= 1;\n }\n return ans;\n}\nint totalWays(int n, int k) {\n if (n < k)return 0;\n int64_t ans = 1;\n for (int i = n - k + 1; i <= n - 1; i++)(ans *= i) %= mod;\n for (int i = 1; i <= k - 1; i++)(ans *= expo(i, mod - 2)) %= mod;\n return ans;\n}" }, { "code": null, "e": 4310, "s": 4307, "text": "-3" }, { "code": null, "e": 4334, "s": 4310, "text": "asifalimnstu2 years ago" }, { "code": null, "e": 4347, "s": 4334, "text": "asifalimnstu" }, { "code": null, "e": 4390, "s": 4347, "text": "0.02 sec c++https://practice.geeksforge..." }, { "code": null, "e": 4392, "s": 4390, "text": "0" }, { "code": null, "e": 4419, "s": 4392, "text": "Tourist ka Dost2 years ago" }, { "code": null, "e": 4435, "s": 4419, "text": "Tourist ka Dost" }, { "code": null, "e": 4620, "s": 4435, "text": "Getting memory error, while trying to solve in python. I'm getting correct answers in custom input and Compile & test. I think it's because of Python 32-bit installation. Please help!" }, { "code": null, "e": 4623, "s": 4620, "text": "-3" }, { "code": null, "e": 4641, "s": 4623, "text": "Ashish4 years ago" }, { "code": null, "e": 4648, "s": 4641, "text": "Ashish" }, { "code": null, "e": 4705, "s": 4648, "text": "do we have to print the cases as well? If yes, then how?" }, { "code": null, "e": 4851, "s": 4705, "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": 4887, "s": 4851, "text": " Login to access your submissions. " }, { "code": null, "e": 4897, "s": 4887, "text": "\nProblem\n" }, { "code": null, "e": 4907, "s": 4897, "text": "\nContest\n" }, { "code": null, "e": 4970, "s": 4907, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5118, "s": 4970, "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": 5326, "s": 5118, "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": 5432, "s": 5326, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Program to convert Hexa-Decimal Number to its equivalent BCD - GeeksforGeeks
14 Dec, 2020 Given a HexaDecimal Number N, the task is to convert the number to its equivalent Binary Coded Decimal.Examples: Input: 11F Output: 0001 0001 1111 Explanation: Binary of 1 – 0001 Binary of F – 1111 Thus, Equivalent BCD is 0001 0001 1111Input: A D Output: 1010 1101 Explanation: Binary of A – 1010 Binary of D – 1101 Thus, Equivalent BCD is 1010 1101 Approach: The idea is to iterate over each digit of the given Hexa-Decimal number and find the four digit Binary Equivalent of that digit. Finally, print all the converted digits one by one.Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation to convert the given// HexaDecimal number to its equivalent BCD. #include <bits/stdc++.h>using namespace std; // Function to convert// HexaDecimal to its BCDvoid HexaDecimaltoBCD(string s){ int len = s.length(), check = 0; int num = 0, sum = 0, mul = 1; // Iterating through the digits for (int i = 0; i <= len - 1; i++) { // check whether s[i] is a character // or a integer between 0 to 9 // and compute its equivalent BCD if (s[i] >= 47 && s[i] <= 52) cout << bitset<4>(s[i]) << " "; else cout << bitset<4>(s[i] - 55) << " "; }} // Driver Codeint main(){ string s = "11F"; // Function Call HexaDecimaltoBCD(s); return 0;} // Java implementation to convert the given// HexaDecimal number to its equivalent BCD.public class Main{ // Function to convert // HexaDecimal to its BCD public static void HexaDecimaltoBCD(String s) { int len = s.length(), check = 0; int num = 0, sum = 0, mul = 1; // Iterating through the digits for (int i = 0; i <= len - 1; i++) { // check whether s[i] is a character // or a integer between 0 to 9 // and compute its equivalent BCD if (s.charAt(i) >= 47 && s.charAt(i) <= 52) { String result = Integer.toBinaryString((int)s.charAt(i)); System.out.print(result.substring(result.length() - 4) + " "); } else { String result = Integer.toBinaryString((int)s.charAt(i) - 55); System.out.print(result.substring(result.length() - 4) + " "); } } } public static void main(String[] args) { String s = "11F"; // Function Call HexaDecimaltoBCD(s); }} // This code is contributed by divyesh072019 # Python3 program to convert the given# HexaDecimal number to its equivalent BCD # Function to convert# Haxadecimal to BCDdef HexaDecimaltoBCD(str): # Iterating through the digits for i in range(len(str)): # Conversion into equivalent BCD print("{0:04b}".format( int(str[i], 16)), end = " ") # Driver codestr = "11F" # Function callHexaDecimaltoBCD(str) # This code is contributed by himanshu77 // C# implementation to convert the given// HexaDecimal number to its equivalent BCD.using System;class GFG { // Function to convert // HexaDecimal to its BCD static void HexaDecimaltoBCD(string s) { int len = s.Length; // Iterating through the digits for (int i = 0; i <= len - 1; i++) { // check whether s[i] is a character // or a integer between 0 to 9 // and compute its equivalent BCD if (s[i] >= 47 && s[i] <= 52) { string result = Convert.ToString((int)s[i], 2); Console.Write(result.Substring(result.Length - 4) + " "); } else { string result = Convert.ToString((int)s[i] - 55, 2); Console.Write(result.Substring(result.Length - 4) + " "); } } } static void Main() { string s = "11F"; // Function Call HexaDecimaltoBCD(s); }} // This code is contributed by diyeshrabadiya07 0001 0001 1111 himanshu77 divyesh072019 divyeshrabadiya07 base-conversion Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Program to find parity Write an Efficient Method to Check if a Number is Multiple of 3 Hamming code Implementation in C/C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24988, "s": 24960, "text": "\n14 Dec, 2020" }, { "code": null, "e": 25103, "s": 24988, "text": "Given a HexaDecimal Number N, the task is to convert the number to its equivalent Binary Coded Decimal.Examples: " }, { "code": null, "e": 25342, "s": 25103, "text": "Input: 11F Output: 0001 0001 1111 Explanation: Binary of 1 – 0001 Binary of F – 1111 Thus, Equivalent BCD is 0001 0001 1111Input: A D Output: 1010 1101 Explanation: Binary of A – 1010 Binary of D – 1101 Thus, Equivalent BCD is 1010 1101 " }, { "code": null, "e": 25587, "s": 25344, "text": "Approach: The idea is to iterate over each digit of the given Hexa-Decimal number and find the four digit Binary Equivalent of that digit. Finally, print all the converted digits one by one.Below is the implementation of the above approach: " }, { "code": null, "e": 25591, "s": 25587, "text": "C++" }, { "code": null, "e": 25596, "s": 25591, "text": "Java" }, { "code": null, "e": 25604, "s": 25596, "text": "Python3" }, { "code": null, "e": 25607, "s": 25604, "text": "C#" }, { "code": "// C++ implementation to convert the given// HexaDecimal number to its equivalent BCD. #include <bits/stdc++.h>using namespace std; // Function to convert// HexaDecimal to its BCDvoid HexaDecimaltoBCD(string s){ int len = s.length(), check = 0; int num = 0, sum = 0, mul = 1; // Iterating through the digits for (int i = 0; i <= len - 1; i++) { // check whether s[i] is a character // or a integer between 0 to 9 // and compute its equivalent BCD if (s[i] >= 47 && s[i] <= 52) cout << bitset<4>(s[i]) << \" \"; else cout << bitset<4>(s[i] - 55) << \" \"; }} // Driver Codeint main(){ string s = \"11F\"; // Function Call HexaDecimaltoBCD(s); return 0;}", "e": 26375, "s": 25607, "text": null }, { "code": "// Java implementation to convert the given// HexaDecimal number to its equivalent BCD.public class Main{ // Function to convert // HexaDecimal to its BCD public static void HexaDecimaltoBCD(String s) { int len = s.length(), check = 0; int num = 0, sum = 0, mul = 1; // Iterating through the digits for (int i = 0; i <= len - 1; i++) { // check whether s[i] is a character // or a integer between 0 to 9 // and compute its equivalent BCD if (s.charAt(i) >= 47 && s.charAt(i) <= 52) { String result = Integer.toBinaryString((int)s.charAt(i)); System.out.print(result.substring(result.length() - 4) + \" \"); } else { String result = Integer.toBinaryString((int)s.charAt(i) - 55); System.out.print(result.substring(result.length() - 4) + \" \"); } } } public static void main(String[] args) { String s = \"11F\"; // Function Call HexaDecimaltoBCD(s); }} // This code is contributed by divyesh072019", "e": 27521, "s": 26375, "text": null }, { "code": "# Python3 program to convert the given# HexaDecimal number to its equivalent BCD # Function to convert# Haxadecimal to BCDdef HexaDecimaltoBCD(str): # Iterating through the digits for i in range(len(str)): # Conversion into equivalent BCD print(\"{0:04b}\".format( int(str[i], 16)), end = \" \") # Driver codestr = \"11F\" # Function callHexaDecimaltoBCD(str) # This code is contributed by himanshu77", "e": 27959, "s": 27521, "text": null }, { "code": "// C# implementation to convert the given// HexaDecimal number to its equivalent BCD.using System;class GFG { // Function to convert // HexaDecimal to its BCD static void HexaDecimaltoBCD(string s) { int len = s.Length; // Iterating through the digits for (int i = 0; i <= len - 1; i++) { // check whether s[i] is a character // or a integer between 0 to 9 // and compute its equivalent BCD if (s[i] >= 47 && s[i] <= 52) { string result = Convert.ToString((int)s[i], 2); Console.Write(result.Substring(result.Length - 4) + \" \"); } else { string result = Convert.ToString((int)s[i] - 55, 2); Console.Write(result.Substring(result.Length - 4) + \" \"); } } } static void Main() { string s = \"11F\"; // Function Call HexaDecimaltoBCD(s); }} // This code is contributed by diyeshrabadiya07", "e": 28998, "s": 27959, "text": null }, { "code": null, "e": 29013, "s": 28998, "text": "0001 0001 1111" }, { "code": null, "e": 29026, "s": 29015, "text": "himanshu77" }, { "code": null, "e": 29040, "s": 29026, "text": "divyesh072019" }, { "code": null, "e": 29058, "s": 29040, "text": "divyeshrabadiya07" }, { "code": null, "e": 29074, "s": 29058, "text": "base-conversion" }, { "code": null, "e": 29084, "s": 29074, "text": "Bit Magic" }, { "code": null, "e": 29097, "s": 29084, "text": "Mathematical" }, { "code": null, "e": 29110, "s": 29097, "text": "Mathematical" }, { "code": null, "e": 29120, "s": 29110, "text": "Bit Magic" }, { "code": null, "e": 29218, "s": 29120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29269, "s": 29218, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 29306, "s": 29269, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 29329, "s": 29306, "text": "Program to find parity" }, { "code": null, "e": 29393, "s": 29329, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 29430, "s": 29393, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 29460, "s": 29430, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29520, "s": 29460, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29535, "s": 29520, "text": "C++ Data Types" }, { "code": null, "e": 29578, "s": 29535, "text": "Set in C++ Standard Template Library (STL)" } ]
How to detect click outside React component ? - GeeksforGeeks
11 Feb, 2022 We can use the createRef() method to create a reference for any element in the class-based component. Then we can check whether click event occurred in the component or outside the component. In the functional component, we can use the useRef() hook to create a reference for any element. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Filename- App.js: Using Class base Component Javascript import React from 'react';class App extends React.Component { constructor(props) { super(props); // Creating a reference this.box = React.createRef(); } componentDidMount() { // Adding a click event listener document.addEventListener('click', this.handleOutsideClick); } handleOutsideClick = (event) => { if (this.box && !this.box.current.contains(event.target)) { alert('you just clicked outside of box!'); } } render() { return <div style={{ margin: 300, width: 200, height: 200, backgroundColor: 'green' }} // Assigning the ref to div component ref={this.box}>{this.props.children}</div>; }} export default App; Filename- App.js:< Using Functional Component/p> Javascript import React, { useEffect, useRef } from 'react' function App(props) { const box = useRef(null); useOutsideAlerter(box); return (<div style={{ margin: 300, width: 200, height: 200, backgroundColor: 'green' }} ref={box}>{props.children}</div> )} export default App; function useOutsideAlerter(ref) { useEffect(() => { // Function for click event function handleOutsideClick(event) { if (ref.current && !ref.current.contains(event.target)) { alert("you just clicked outside of box!"); } } // Adding click event listener document.addEventListener("click", handleOutsideClick); return () => document.removeEventListener("click", handleOutsideClick); }, [ref]);} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: deritobrita Picked JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25312, "s": 25284, "text": "\n11 Feb, 2022" }, { "code": null, "e": 25505, "s": 25312, "text": "We can use the createRef() method to create a reference for any element in the class-based component. Then we can check whether click event occurred in the component or outside the component." }, { "code": null, "e": 25602, "s": 25505, "text": "In the functional component, we can use the useRef() hook to create a reference for any element." }, { "code": null, "e": 25652, "s": 25602, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25716, "s": 25652, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25748, "s": 25716, "text": "npx create-react-app foldername" }, { "code": null, "e": 25848, "s": 25748, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25862, "s": 25848, "text": "cd foldername" }, { "code": null, "e": 25914, "s": 25862, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25932, "s": 25914, "text": "Project Structure" }, { "code": null, "e": 26061, "s": 25932, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26106, "s": 26061, "text": "Filename- App.js: Using Class base Component" }, { "code": null, "e": 26117, "s": 26106, "text": "Javascript" }, { "code": "import React from 'react';class App extends React.Component { constructor(props) { super(props); // Creating a reference this.box = React.createRef(); } componentDidMount() { // Adding a click event listener document.addEventListener('click', this.handleOutsideClick); } handleOutsideClick = (event) => { if (this.box && !this.box.current.contains(event.target)) { alert('you just clicked outside of box!'); } } render() { return <div style={{ margin: 300, width: 200, height: 200, backgroundColor: 'green' }} // Assigning the ref to div component ref={this.box}>{this.props.children}</div>; }} export default App;", "e": 26799, "s": 26117, "text": null }, { "code": null, "e": 26848, "s": 26799, "text": "Filename- App.js:< Using Functional Component/p>" }, { "code": null, "e": 26859, "s": 26848, "text": "Javascript" }, { "code": "import React, { useEffect, useRef } from 'react' function App(props) { const box = useRef(null); useOutsideAlerter(box); return (<div style={{ margin: 300, width: 200, height: 200, backgroundColor: 'green' }} ref={box}>{props.children}</div> )} export default App; function useOutsideAlerter(ref) { useEffect(() => { // Function for click event function handleOutsideClick(event) { if (ref.current && !ref.current.contains(event.target)) { alert(\"you just clicked outside of box!\"); } } // Adding click event listener document.addEventListener(\"click\", handleOutsideClick); return () => document.removeEventListener(\"click\", handleOutsideClick); }, [ref]);}", "e": 27570, "s": 26859, "text": null }, { "code": null, "e": 27683, "s": 27570, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27693, "s": 27683, "text": "npm start" }, { "code": null, "e": 27792, "s": 27693, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27804, "s": 27792, "text": "deritobrita" }, { "code": null, "e": 27811, "s": 27804, "text": "Picked" }, { "code": null, "e": 27822, "s": 27811, "text": "JavaScript" }, { "code": null, "e": 27830, "s": 27822, "text": "ReactJS" }, { "code": null, "e": 27847, "s": 27830, "text": "Web Technologies" }, { "code": null, "e": 27945, "s": 27847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28006, "s": 27945, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28047, "s": 28006, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28087, "s": 28047, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28141, "s": 28087, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28189, "s": 28141, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28232, "s": 28189, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28277, "s": 28232, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 28342, "s": 28277, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28410, "s": 28342, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Interactive Neural Network Fun in Excel | by Tony Roberts | Towards Data Science
After reading Making deep neural networks paint to understand how they work by Paras Chopra I was inspired to delve into some experiments of my own. The images produced were intriguing, and I wanted to play around and get a feel for how they changed in response to changing the structure of the neural network. I encourage you to go back and read the original article, but as a brief summary it involves using Compositional Pattern Producing Networks (CPPN) with random weights to produce abstract images. The basic idea is that we construct a function c = f(x,y) that takes the input coordinates of a pixel x,y and returns the colour for that pixel, c using a CPPN. As in the original article, we’ll use PyTorch to create a CPPN. The following code is the result of lots of work by Paras Chopra and will be our starting point. Running the above neural network on a 512x512 input array results in an output image as shown below. The neural network is initialised with random weights, and the input array is scaled such that each input is between +0.5 and -0.5. There are a lot of variables to play with that will affect the resulting image. From the scaling of the inputs, the number of neurons at each stage, and the structure of the neural network itself. We could put this code in a Jupyter notebook and use change the inputs there, but each change we make is a change to the code itself and somehow doesn’t quite feel like a real interactive experience. Microsoft Excel might seem like an odd choice for an interactive playground for this type of task initially. Bear with me though... What we want to do is enter some information like the number of weights and how many layers, and have a new image presented to us. In essence, Excel simply runs functions when inputs change — and those functions can do anything, even show us an image in Excel! If we could have a worksheet in Excel with the parameters we want to change, and as soon as we make a change have the image update that would be make a great playground for getting a feel for how the inputs affect the output. Neural networks in Excel might sound like a hard task, but we’re not talking about implementing it in VBA! In fact, we won’t need to go anywhere near VBA as we can continue to use Python instead. PyXLL is an Excel add-in that embeds the Python runtime into Microsoft Excel. It allows us to write Excel functions entirely in Python, and so we can still use PyTorch for our neural network but all within Excel. Having access to all the Python tools really opens up what is possible with Excel. Rather than having complex logic encoded in VBA, software written in Python is simply exposed to Excel. Excel becomes our front end user interface tool, with Python taking care of the complex computation. PyXLL is the highest performing and easiest way to write Excel functions entirely in Python, which is perfect for complex workloads. You can download a free 30 day trial from https://www.pyxll.com/download.html. Our goal is to be able to construct our neural network in Excel and have complete control over the inputs. We’ll start by writing some Python functions and exposing them to Excel. Roughly, the functions we’ll need are: Create the layers (nn.Linear, nn.Tanh and nn.Sigmoid)Create a neural network from a set of layers (nn.Sequential)Run the neural network on a set of inputs and show the output Create the layers (nn.Linear, nn.Tanh and nn.Sigmoid) Create a neural network from a set of layers (nn.Sequential) Run the neural network on a set of inputs and show the output At this stage you might be wondering how we are going to represent some of these items in Excel. PyXLL lets us pass Python objects between Excel functions in a workbook, so having a function that returns a Python instance of nn.Linear or another Python function that takes a list of transformation layers is actually very simple. When a Python object is returned to Excel, what we see in Excel is just a handle to the Python object, and when that handle is passed to another Python function PyXLL fetches the object for that handle automatically. PyXLL also manages the life-cycle of these objects so when they are no longer needed they will be cleaned up automatically. To expose a Python function to Excel we use the @xl_func decorator from the pyxll module. Here are the first functions we need for creating the layers: The @xl_func decorator is all that’s needed to expose those functions to Excel! The nn_Linear function has type annotations which PyXLL uses to ensure the correct types are passed from Excel to the function, otherwise the numbers passed from Excel might come through as floats. All that’s needed is to add this module to the PyXLL config file, pyxll.cfg. For example, if your code was written to a Python module named “pytorch_abstract_art.py” in the folder “C:\MyCode\PyTorch-Abstract-Art\Modules”, you would update your pyxll.cfg file with the following settings: [PYTHON]pythonpath = C:\MyCode\PyTorch-Abstract-Art\Modules[PYXLL]modules = pytorch_abstract_art We can now call these functions from Excel to construct all the layers required required for the neural network. All of the inputs are entered in Excel, and we can even change the number and order of the layers interactively. To construct the neural network we just need another function that takes these layers and returns the neural network using nn.Sequential. PyXLL can accept arrays of arguments as well as just single values, so we can pass the whole set of layers as a single argument. The @xl_func decorator takes an optional function signature to tell PyXLL more about the argument and return types to expect. To tell PyXLL to convert the range of cells passed to it into a 1d list of objects we use the object[] type. If we wanted to pass a range as a 2d list of lists of objects instead we could use the object[][] type. When flattening from a 2d range of cells to a 1d list of values PyXLL takes cells from left to right and so the ordering of our layers in the above image will result in the correct arrangement. We can now add that new function nn_Sequential to our Excel worksheet and pass in the layers created earlier. The only things remaining now are to create an input set, initialise the weights, and show the resulting image. To do that we’ll use Excel’s Object Model to manipulate an image in Excel. Excel’s Object Model is exactly what you may have used if you’ve ever written any VBA, but you may not have realised that it can be called from Python just as easily as from VBA! The guide Python as a VBA Replacement explains how to call Excel from Python, and also covers some of the differences between VBA’s syntax and Python. The final function takes: The neural network objectThe name of the image object in ExcelScale and offset parameters for the inputsA random seed The neural network object The name of the image object in Excel Scale and offset parameters for the inputs A random seed To add the image that will show our result, in Excel click Developer → Insert →Image (Active X Control). To the left of the formula bar you will see the name of the image object. This will default to Image1, but you can edit this to any name you like. The following code gets the image from Excel, constructs the inputs, computes the outputs and updates the image. With this final function complete we can now pull it all together. All of the inputs to constructing the neural network are exposed on the sheet, as are the parameters controlling how the input data is created. We can add or remove layers, edit the number of features at each stage and even switch the activation functions. What’s really fun about this is that everything is in real-time. As soon as we make a change, the image updates. A couple of functions were left out of the above code to make it easier to read. You can find them below, or you can also get all of the code from the GitHub repo https://github.com/pyxll/pyxll-examples in the pytorch folder. Playing around with neural networks in Excel in this way has been really interesting and fun. More importantly than that though, it shows how even complex Python tasks can be integrated into Excel seamlessly. Excel’s strength is as a user-interface tool and, in my opinion, should not be used to store data, algorithms or business logic that can be better managed elsewhere. Anyone who’s used Excel for a while or has worked with a team that depends on Excel know the pain of VBA macros that can’t be tested, version controlled or even be consistent between different users’ workbooks. By moving the code outside of Excel you not only get the huge benefits of a modern language like Python, but you can also apply modern development practices to the code behind your spreadsheets. While not many people will want to actually construct and train neural networks in Excel, there is still value in being able to access neural networks from Excel. A large part of what makes machine learning useful is the ability to use it to assist decision making. If the decision makers are already using Excel, we can make it easy for them by exposing trained and tested machine learning solutions to them in Excel. This can be a much improved workflow over them using Excel to do some basic calculations, then breaking out to a custom tool or web app (or even worse, emailing someone in the data science group a spreadsheet!), and then putting those results back into Excel — which they will want to do, no matter how good you think your custom tool is ;) You can download the code and the example workbook from the GitHub repo https://github.com/pyxll/pyxll-examples in the pytorch folder. You will also need PyXLL, which you can download with a 30 day free trial from https://www.pyxll.com/download.html.
[ { "code": null, "e": 482, "s": 171, "text": "After reading Making deep neural networks paint to understand how they work by Paras Chopra I was inspired to delve into some experiments of my own. The images produced were intriguing, and I wanted to play around and get a feel for how they changed in response to changing the structure of the neural network." }, { "code": null, "e": 838, "s": 482, "text": "I encourage you to go back and read the original article, but as a brief summary it involves using Compositional Pattern Producing Networks (CPPN) with random weights to produce abstract images. The basic idea is that we construct a function c = f(x,y) that takes the input coordinates of a pixel x,y and returns the colour for that pixel, c using a CPPN." }, { "code": null, "e": 999, "s": 838, "text": "As in the original article, we’ll use PyTorch to create a CPPN. The following code is the result of lots of work by Paras Chopra and will be our starting point." }, { "code": null, "e": 1232, "s": 999, "text": "Running the above neural network on a 512x512 input array results in an output image as shown below. The neural network is initialised with random weights, and the input array is scaled such that each input is between +0.5 and -0.5." }, { "code": null, "e": 1629, "s": 1232, "text": "There are a lot of variables to play with that will affect the resulting image. From the scaling of the inputs, the number of neurons at each stage, and the structure of the neural network itself. We could put this code in a Jupyter notebook and use change the inputs there, but each change we make is a change to the code itself and somehow doesn’t quite feel like a real interactive experience." }, { "code": null, "e": 2248, "s": 1629, "text": "Microsoft Excel might seem like an odd choice for an interactive playground for this type of task initially. Bear with me though... What we want to do is enter some information like the number of weights and how many layers, and have a new image presented to us. In essence, Excel simply runs functions when inputs change — and those functions can do anything, even show us an image in Excel! If we could have a worksheet in Excel with the parameters we want to change, and as soon as we make a change have the image update that would be make a great playground for getting a feel for how the inputs affect the output." }, { "code": null, "e": 2444, "s": 2248, "text": "Neural networks in Excel might sound like a hard task, but we’re not talking about implementing it in VBA! In fact, we won’t need to go anywhere near VBA as we can continue to use Python instead." }, { "code": null, "e": 2945, "s": 2444, "text": "PyXLL is an Excel add-in that embeds the Python runtime into Microsoft Excel. It allows us to write Excel functions entirely in Python, and so we can still use PyTorch for our neural network but all within Excel. Having access to all the Python tools really opens up what is possible with Excel. Rather than having complex logic encoded in VBA, software written in Python is simply exposed to Excel. Excel becomes our front end user interface tool, with Python taking care of the complex computation." }, { "code": null, "e": 3157, "s": 2945, "text": "PyXLL is the highest performing and easiest way to write Excel functions entirely in Python, which is perfect for complex workloads. You can download a free 30 day trial from https://www.pyxll.com/download.html." }, { "code": null, "e": 3376, "s": 3157, "text": "Our goal is to be able to construct our neural network in Excel and have complete control over the inputs. We’ll start by writing some Python functions and exposing them to Excel. Roughly, the functions we’ll need are:" }, { "code": null, "e": 3551, "s": 3376, "text": "Create the layers (nn.Linear, nn.Tanh and nn.Sigmoid)Create a neural network from a set of layers (nn.Sequential)Run the neural network on a set of inputs and show the output" }, { "code": null, "e": 3605, "s": 3551, "text": "Create the layers (nn.Linear, nn.Tanh and nn.Sigmoid)" }, { "code": null, "e": 3666, "s": 3605, "text": "Create a neural network from a set of layers (nn.Sequential)" }, { "code": null, "e": 3728, "s": 3666, "text": "Run the neural network on a set of inputs and show the output" }, { "code": null, "e": 4399, "s": 3728, "text": "At this stage you might be wondering how we are going to represent some of these items in Excel. PyXLL lets us pass Python objects between Excel functions in a workbook, so having a function that returns a Python instance of nn.Linear or another Python function that takes a list of transformation layers is actually very simple. When a Python object is returned to Excel, what we see in Excel is just a handle to the Python object, and when that handle is passed to another Python function PyXLL fetches the object for that handle automatically. PyXLL also manages the life-cycle of these objects so when they are no longer needed they will be cleaned up automatically." }, { "code": null, "e": 4551, "s": 4399, "text": "To expose a Python function to Excel we use the @xl_func decorator from the pyxll module. Here are the first functions we need for creating the layers:" }, { "code": null, "e": 4829, "s": 4551, "text": "The @xl_func decorator is all that’s needed to expose those functions to Excel! The nn_Linear function has type annotations which PyXLL uses to ensure the correct types are passed from Excel to the function, otherwise the numbers passed from Excel might come through as floats." }, { "code": null, "e": 5117, "s": 4829, "text": "All that’s needed is to add this module to the PyXLL config file, pyxll.cfg. For example, if your code was written to a Python module named “pytorch_abstract_art.py” in the folder “C:\\MyCode\\PyTorch-Abstract-Art\\Modules”, you would update your pyxll.cfg file with the following settings:" }, { "code": null, "e": 5220, "s": 5117, "text": "[PYTHON]pythonpath = C:\\MyCode\\PyTorch-Abstract-Art\\Modules[PYXLL]modules = pytorch_abstract_art" }, { "code": null, "e": 5446, "s": 5220, "text": "We can now call these functions from Excel to construct all the layers required required for the neural network. All of the inputs are entered in Excel, and we can even change the number and order of the layers interactively." }, { "code": null, "e": 5839, "s": 5446, "text": "To construct the neural network we just need another function that takes these layers and returns the neural network using nn.Sequential. PyXLL can accept arrays of arguments as well as just single values, so we can pass the whole set of layers as a single argument. The @xl_func decorator takes an optional function signature to tell PyXLL more about the argument and return types to expect." }, { "code": null, "e": 6246, "s": 5839, "text": "To tell PyXLL to convert the range of cells passed to it into a 1d list of objects we use the object[] type. If we wanted to pass a range as a 2d list of lists of objects instead we could use the object[][] type. When flattening from a 2d range of cells to a 1d list of values PyXLL takes cells from left to right and so the ordering of our layers in the above image will result in the correct arrangement." }, { "code": null, "e": 6356, "s": 6246, "text": "We can now add that new function nn_Sequential to our Excel worksheet and pass in the layers created earlier." }, { "code": null, "e": 6468, "s": 6356, "text": "The only things remaining now are to create an input set, initialise the weights, and show the resulting image." }, { "code": null, "e": 6873, "s": 6468, "text": "To do that we’ll use Excel’s Object Model to manipulate an image in Excel. Excel’s Object Model is exactly what you may have used if you’ve ever written any VBA, but you may not have realised that it can be called from Python just as easily as from VBA! The guide Python as a VBA Replacement explains how to call Excel from Python, and also covers some of the differences between VBA’s syntax and Python." }, { "code": null, "e": 6899, "s": 6873, "text": "The final function takes:" }, { "code": null, "e": 7017, "s": 6899, "text": "The neural network objectThe name of the image object in ExcelScale and offset parameters for the inputsA random seed" }, { "code": null, "e": 7043, "s": 7017, "text": "The neural network object" }, { "code": null, "e": 7081, "s": 7043, "text": "The name of the image object in Excel" }, { "code": null, "e": 7124, "s": 7081, "text": "Scale and offset parameters for the inputs" }, { "code": null, "e": 7138, "s": 7124, "text": "A random seed" }, { "code": null, "e": 7390, "s": 7138, "text": "To add the image that will show our result, in Excel click Developer → Insert →Image (Active X Control). To the left of the formula bar you will see the name of the image object. This will default to Image1, but you can edit this to any name you like." }, { "code": null, "e": 7503, "s": 7390, "text": "The following code gets the image from Excel, constructs the inputs, computes the outputs and updates the image." }, { "code": null, "e": 7714, "s": 7503, "text": "With this final function complete we can now pull it all together. All of the inputs to constructing the neural network are exposed on the sheet, as are the parameters controlling how the input data is created." }, { "code": null, "e": 7940, "s": 7714, "text": "We can add or remove layers, edit the number of features at each stage and even switch the activation functions. What’s really fun about this is that everything is in real-time. As soon as we make a change, the image updates." }, { "code": null, "e": 8166, "s": 7940, "text": "A couple of functions were left out of the above code to make it easier to read. You can find them below, or you can also get all of the code from the GitHub repo https://github.com/pyxll/pyxll-examples in the pytorch folder." }, { "code": null, "e": 8375, "s": 8166, "text": "Playing around with neural networks in Excel in this way has been really interesting and fun. More importantly than that though, it shows how even complex Python tasks can be integrated into Excel seamlessly." }, { "code": null, "e": 8947, "s": 8375, "text": "Excel’s strength is as a user-interface tool and, in my opinion, should not be used to store data, algorithms or business logic that can be better managed elsewhere. Anyone who’s used Excel for a while or has worked with a team that depends on Excel know the pain of VBA macros that can’t be tested, version controlled or even be consistent between different users’ workbooks. By moving the code outside of Excel you not only get the huge benefits of a modern language like Python, but you can also apply modern development practices to the code behind your spreadsheets." }, { "code": null, "e": 9707, "s": 8947, "text": "While not many people will want to actually construct and train neural networks in Excel, there is still value in being able to access neural networks from Excel. A large part of what makes machine learning useful is the ability to use it to assist decision making. If the decision makers are already using Excel, we can make it easy for them by exposing trained and tested machine learning solutions to them in Excel. This can be a much improved workflow over them using Excel to do some basic calculations, then breaking out to a custom tool or web app (or even worse, emailing someone in the data science group a spreadsheet!), and then putting those results back into Excel — which they will want to do, no matter how good you think your custom tool is ;)" } ]
PostgreSQL – FORMAT Function
25 Aug, 2021 In PostgreSQL, the FORMAT() function is used to format arguments based on a format string. Syntax: FORMAT(format_string [, format_argument [, ....] ]) Let’s analyze the above syntax: The FORMAT() function is variadic, meaning, users can supply the arguments as an array marked with the VARIADIC keyword. The FORMAT() function considers the array’s elements as normal arguments and it treats NULL as an array of zero elements. The format_string sets the behaviour of the resulting formatted string. It also has text and format specifiers. In this function, the text arguments are copied directly to the result string and the format specifiers are placeholders for the arguments. Syntax of the format specifier: Syntax: %[position][flags][width]type Note that a format specifier begins with a “%” and it has three optional components position, flags, width, and a required component type. It is used to set the argument that is to be inserted in the result string. The position is in the form of n$ where n is the argument index. The first argument starts from 1. The default is the next argument in the list if the position component is not set. This component is used in conjunction with the width field, for instance, the flags can accept a minus sign (-) that instructs the format specifier’s output to be left-justified. It is an optional argument and is used to set the minimum number of characters to use for displaying the format specifier’s output. At this stage, padding can be done to fill up the empty spaces whereas in case the string is smaller than the specified width the result string can be padded left or right with the spaces needed to fill the width. In the exact opposite case, the result string is displayed without any alteration. The width argument can hold the following values: A positive integer value. An asterisk (*) to use the next function argument as the width. A string of the form *n$ to use the nth function argument as the width. It is used to define the type of the output string from the format specifier. It can hold the following values: s: It formats the argument value as a string. NULL values are treated as an empty strings. I: It treats the argument value as an SQL identifier. L: It makes the argument value as an SQL literal. I and L are generally used for constructing dynamic SQL statements. The double percentages (%%) can also be used for including the % sign As discussed earlier, the users pass a number of format arguments to the FORMAT() function. The FORMAT() function returns a formatted string. Example 1: The following statement uses the FORMAT() function to format a string: SELECT FORMAT('Hello, %s', 'Geeks!!'); Output: Example 2: The following statement uses the FORMAT() function to construct customer’s full names from first names and last names from the customers table of the sample database, ie, dvdrental: SELECT FORMAT('%s, %s', last_name, first_name) full_name FROM customer; ORDER BY full_name; Output: abhishek0719kadiyan PostgreSQL-function PostgreSQL-String-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 119, "s": 28, "text": "In PostgreSQL, the FORMAT() function is used to format arguments based on a format string." }, { "code": null, "e": 179, "s": 119, "text": "Syntax:\nFORMAT(format_string [, format_argument [, ....] ])" }, { "code": null, "e": 211, "s": 179, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 332, "s": 211, "text": "The FORMAT() function is variadic, meaning, users can supply the arguments as an array marked with the VARIADIC keyword." }, { "code": null, "e": 454, "s": 332, "text": "The FORMAT() function considers the array’s elements as normal arguments and it treats NULL as an array of zero elements." }, { "code": null, "e": 706, "s": 454, "text": "The format_string sets the behaviour of the resulting formatted string. It also has text and format specifiers. In this function, the text arguments are copied directly to the result string and the format specifiers are placeholders for the arguments." }, { "code": null, "e": 738, "s": 706, "text": "Syntax of the format specifier:" }, { "code": null, "e": 776, "s": 738, "text": "Syntax: %[position][flags][width]type" }, { "code": null, "e": 915, "s": 776, "text": "Note that a format specifier begins with a “%” and it has three optional components position, flags, width, and a required component type." }, { "code": null, "e": 1173, "s": 915, "text": "It is used to set the argument that is to be inserted in the result string. The position is in the form of n$ where n is the argument index. The first argument starts from 1. The default is the next argument in the list if the position component is not set." }, { "code": null, "e": 1352, "s": 1173, "text": "This component is used in conjunction with the width field, for instance, the flags can accept a minus sign (-) that instructs the format specifier’s output to be left-justified." }, { "code": null, "e": 1781, "s": 1352, "text": "It is an optional argument and is used to set the minimum number of characters to use for displaying the format specifier’s output. At this stage, padding can be done to fill up the empty spaces whereas in case the string is smaller than the specified width the result string can be padded left or right with the spaces needed to fill the width. In the exact opposite case, the result string is displayed without any alteration." }, { "code": null, "e": 1831, "s": 1781, "text": "The width argument can hold the following values:" }, { "code": null, "e": 1857, "s": 1831, "text": "A positive integer value." }, { "code": null, "e": 1921, "s": 1857, "text": "An asterisk (*) to use the next function argument as the width." }, { "code": null, "e": 1993, "s": 1921, "text": "A string of the form *n$ to use the nth function argument as the width." }, { "code": null, "e": 2071, "s": 1993, "text": "It is used to define the type of the output string from the format specifier." }, { "code": null, "e": 2105, "s": 2071, "text": "It can hold the following values:" }, { "code": null, "e": 2196, "s": 2105, "text": "s: It formats the argument value as a string. NULL values are treated as an empty strings." }, { "code": null, "e": 2250, "s": 2196, "text": "I: It treats the argument value as an SQL identifier." }, { "code": null, "e": 2300, "s": 2250, "text": "L: It makes the argument value as an SQL literal." }, { "code": null, "e": 2438, "s": 2300, "text": "I and L are generally used for constructing dynamic SQL statements. The double percentages (%%) can also be used for including the % sign" }, { "code": null, "e": 2530, "s": 2438, "text": "As discussed earlier, the users pass a number of format arguments to the FORMAT() function." }, { "code": null, "e": 2580, "s": 2530, "text": "The FORMAT() function returns a formatted string." }, { "code": null, "e": 2591, "s": 2580, "text": "Example 1:" }, { "code": null, "e": 2662, "s": 2591, "text": "The following statement uses the FORMAT() function to format a string:" }, { "code": null, "e": 2701, "s": 2662, "text": "SELECT FORMAT('Hello, %s', 'Geeks!!');" }, { "code": null, "e": 2709, "s": 2701, "text": "Output:" }, { "code": null, "e": 2720, "s": 2709, "text": "Example 2:" }, { "code": null, "e": 2902, "s": 2720, "text": "The following statement uses the FORMAT() function to construct customer’s full names from first names and last names from the customers table of the sample database, ie, dvdrental:" }, { "code": null, "e": 3010, "s": 2902, "text": "SELECT \n FORMAT('%s, %s', last_name, first_name) full_name \nFROM \n customer;\nORDER BY \n full_name;" }, { "code": null, "e": 3018, "s": 3010, "text": "Output:" }, { "code": null, "e": 3038, "s": 3018, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3058, "s": 3038, "text": "PostgreSQL-function" }, { "code": null, "e": 3085, "s": 3058, "text": "PostgreSQL-String-function" }, { "code": null, "e": 3096, "s": 3085, "text": "PostgreSQL" } ]
How To Add Identifier Column When Concatenating Pandas dataframes?
18 Apr, 2022 We generally want to concat two or more dataframes when working with some data. So, when we concat these dataframes we need to actually want to provide an identifier column in order to identify the concatenated dataframes. In this article, we’ll see with the help of examples of how we can do this. Example 1: To add an identifier column, we need to specify the identifiers as a list for the argument “keys” in concat() function, which creates a new multi-indexed dataframe with two dataframes concatenated. Now we’ll use reset_index to convert multi-indexed dataframe to a regular pandas dataframe. Python3 import pandas as pdimport numpy as np dict = {'Name':['Martha', 'Tim', 'Rob', 'Georgia'], 'Maths':[87, 91, 97, 95], 'Science':[83, 99, 84, 76] } df1 = pd.DataFrame(dict) dict = {'Name':['Amy', 'Maddy'], 'Maths':[89, 90], 'Science':[93, 81] } df2 = pd.DataFrame(dict) # Concatenating two dataframesdf = pd.concat([df1,df2],keys=['t1', 't2'])display(df) df = pd.concat([df1,df2], keys=['t1', 't2']).reset_index()display(df) Output: In the output, we can see a column with the identifiers of each dataframe where “t1” represents the first dataframe and “t2” represents the second dataframe. Example 2: We can do this similarly for any number of dataframes. In this example, we’ll combine three dataframes. Python3 import pandas as pdimport numpy as np dict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'], 'Maths': [87, 91, 97, 95], 'Science': [83, 99, 84, 76] } df1 = pd.DataFrame(dict) dict = {'Name': ['Amy', 'Maddy'], 'Maths': [89, 90], 'Science': [93, 81] } df2 = pd.DataFrame(dict) dict = {'Name': ['Rob', 'Rick', 'Anish'], 'Maths': [89, 90, 87], 'Science': [93, 81, 90] } df3 = pd.DataFrame(dict) # Concatenating Dataframesdf = pd.concat([df1, df2, df3], keys=['t1', 't2', 't3'])display(df) df = pd.concat([df1, df2, df3], keys=['t1', 't2', 't3']).reset_index()display(df) Output: In the output, we can see a column with the identifiers of each dataframe where “t1”, “t2” and “t3” represent first, second and third dataframe respectively. gabaa406 simranarora5sos 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. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Apr, 2022" }, { "code": null, "e": 327, "s": 28, "text": "We generally want to concat two or more dataframes when working with some data. So, when we concat these dataframes we need to actually want to provide an identifier column in order to identify the concatenated dataframes. In this article, we’ll see with the help of examples of how we can do this." }, { "code": null, "e": 338, "s": 327, "text": "Example 1:" }, { "code": null, "e": 628, "s": 338, "text": "To add an identifier column, we need to specify the identifiers as a list for the argument “keys” in concat() function, which creates a new multi-indexed dataframe with two dataframes concatenated. Now we’ll use reset_index to convert multi-indexed dataframe to a regular pandas dataframe." }, { "code": null, "e": 636, "s": 628, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np dict = {'Name':['Martha', 'Tim', 'Rob', 'Georgia'], 'Maths':[87, 91, 97, 95], 'Science':[83, 99, 84, 76] } df1 = pd.DataFrame(dict) dict = {'Name':['Amy', 'Maddy'], 'Maths':[89, 90], 'Science':[93, 81] } df2 = pd.DataFrame(dict) # Concatenating two dataframesdf = pd.concat([df1,df2],keys=['t1', 't2'])display(df) df = pd.concat([df1,df2], keys=['t1', 't2']).reset_index()display(df)", "e": 1099, "s": 636, "text": null }, { "code": null, "e": 1110, "s": 1102, "text": "Output:" }, { "code": null, "e": 1272, "s": 1114, "text": "In the output, we can see a column with the identifiers of each dataframe where “t1” represents the first dataframe and “t2” represents the second dataframe." }, { "code": null, "e": 1285, "s": 1274, "text": "Example 2:" }, { "code": null, "e": 1391, "s": 1287, "text": "We can do this similarly for any number of dataframes. In this example, we’ll combine three dataframes." }, { "code": null, "e": 1401, "s": 1393, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np dict = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'], 'Maths': [87, 91, 97, 95], 'Science': [83, 99, 84, 76] } df1 = pd.DataFrame(dict) dict = {'Name': ['Amy', 'Maddy'], 'Maths': [89, 90], 'Science': [93, 81] } df2 = pd.DataFrame(dict) dict = {'Name': ['Rob', 'Rick', 'Anish'], 'Maths': [89, 90, 87], 'Science': [93, 81, 90] } df3 = pd.DataFrame(dict) # Concatenating Dataframesdf = pd.concat([df1, df2, df3], keys=['t1', 't2', 't3'])display(df) df = pd.concat([df1, df2, df3], keys=['t1', 't2', 't3']).reset_index()display(df)", "e": 2058, "s": 1401, "text": null }, { "code": null, "e": 2069, "s": 2061, "text": "Output:" }, { "code": null, "e": 2232, "s": 2073, "text": "In the output, we can see a column with the identifiers of each dataframe where “t1”, “t2” and “t3” represent first, second and third dataframe respectively. " }, { "code": null, "e": 2243, "s": 2234, "text": "gabaa406" }, { "code": null, "e": 2259, "s": 2243, "text": "simranarora5sos" }, { "code": null, "e": 2284, "s": 2259, "text": "pandas-dataframe-program" }, { "code": null, "e": 2308, "s": 2284, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2331, "s": 2308, "text": "Python Pandas-exercise" }, { "code": null, "e": 2345, "s": 2331, "text": "Python-pandas" }, { "code": null, "e": 2352, "s": 2345, "text": "Python" }, { "code": null, "e": 2450, "s": 2352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2482, "s": 2450, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2509, "s": 2482, "text": "Python Classes and Objects" }, { "code": null, "e": 2530, "s": 2509, "text": "Python OOPs Concepts" }, { "code": null, "e": 2553, "s": 2530, "text": "Introduction To PYTHON" }, { "code": null, "e": 2609, "s": 2553, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2640, "s": 2609, "text": "Python | os.path.join() method" }, { "code": null, "e": 2682, "s": 2640, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2724, "s": 2682, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2763, "s": 2724, "text": "Python | Get unique values from a list" } ]
PostgreSQL – BIGINT Integer Data Type
28 Aug, 2020 PostgreSQL allows a type of integer type namely BIGINT. It requires 8 bytes of storage size and can store integers in the range of -9, 223, 372, 036, 854, 775, 808 to +9, 223, 372, 036, 854, 775, 807. Using BIGINT type is not only consuming a lot of storage but also decreasing the performance of the database, therefore, you should have a good reason to use it. It comes in handy for storing data like the number of stars in a galaxy, the scientific constants, etc. Syntax: variable_name BIGINT Now let’s look into some examples of use cases of SMALLINT integer type.Example 1:In this example we will create a table that stores the number of stars in various galaxies by using the below commands: CREATE TABLE galaxy( id SERIAL PRIMARY KEY, name VARCHAR (255) NOT NULL, stars BIGINT NOT NULL CHECK (stars> 0) ); Now let’s add some data to the table using the below command: INSERT INTO galaxy(name, stars) VALUES ('Milky_Way', 2500000000000), ('Bodes', 2700000000000), ('Cartwheel', 1300000000000), ('Comet', 5700000000000); Now let’s check our inserted data using the below commands: SELECT * FROM galaxy; Output:Example 2:In this example we will create a table that stores the value of various scientific constants by using the below commands: CREATE TABLE constants( id SERIAL PRIMARY KEY, name VARCHAR (255) NOT NULL, value BIGINT NOT NULL CHECK (value> 0) ); Now let’s add some data to the table using the below command: INSERT INTO constants(name, value) VALUES ('Mole', 602213950000000000), ('Rydberg_constant', 10973731568525000), ('Bohr_radius ', 13000000000); Now let’s check our inserted data using the below commands: SELECT * FROM constants; Output: postgreSQL-dataTypes PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 495, "s": 28, "text": "PostgreSQL allows a type of integer type namely BIGINT. It requires 8 bytes of storage size and can store integers in the range of -9, 223, 372, 036, 854, 775, 808 to +9, 223, 372, 036, 854, 775, 807. Using BIGINT type is not only consuming a lot of storage but also decreasing the performance of the database, therefore, you should have a good reason to use it. It comes in handy for storing data like the number of stars in a galaxy, the scientific constants, etc." }, { "code": null, "e": 524, "s": 495, "text": "Syntax: variable_name BIGINT" }, { "code": null, "e": 726, "s": 524, "text": "Now let’s look into some examples of use cases of SMALLINT integer type.Example 1:In this example we will create a table that stores the number of stars in various galaxies by using the below commands:" }, { "code": null, "e": 853, "s": 726, "text": "CREATE TABLE galaxy(\n id SERIAL PRIMARY KEY,\n name VARCHAR (255) NOT NULL,\n stars BIGINT NOT NULL CHECK (stars> 0)\n);" }, { "code": null, "e": 915, "s": 853, "text": "Now let’s add some data to the table using the below command:" }, { "code": null, "e": 1085, "s": 915, "text": "INSERT INTO galaxy(name, stars)\nVALUES\n ('Milky_Way', 2500000000000),\n ('Bodes', 2700000000000), \n ('Cartwheel', 1300000000000), \n ('Comet', 5700000000000);" }, { "code": null, "e": 1145, "s": 1085, "text": "Now let’s check our inserted data using the below commands:" }, { "code": null, "e": 1167, "s": 1145, "text": "SELECT * FROM galaxy;" }, { "code": null, "e": 1306, "s": 1167, "text": "Output:Example 2:In this example we will create a table that stores the value of various scientific constants by using the below commands:" }, { "code": null, "e": 1436, "s": 1306, "text": "CREATE TABLE constants(\n id SERIAL PRIMARY KEY,\n name VARCHAR (255) NOT NULL,\n value BIGINT NOT NULL CHECK (value> 0)\n);" }, { "code": null, "e": 1498, "s": 1436, "text": "Now let’s add some data to the table using the below command:" }, { "code": null, "e": 1655, "s": 1498, "text": "INSERT INTO constants(name, value)\nVALUES\n ('Mole', 602213950000000000),\n ('Rydberg_constant', 10973731568525000), \n ('Bohr_radius ', 13000000000);" }, { "code": null, "e": 1715, "s": 1655, "text": "Now let’s check our inserted data using the below commands:" }, { "code": null, "e": 1740, "s": 1715, "text": "SELECT * FROM constants;" }, { "code": null, "e": 1748, "s": 1740, "text": "Output:" }, { "code": null, "e": 1769, "s": 1748, "text": "postgreSQL-dataTypes" }, { "code": null, "e": 1780, "s": 1769, "text": "PostgreSQL" } ]
Program for n-th odd number
23 Apr, 2021 Given a number n, print the nth odd number. The 1st odd number is 1, 2nd is 3, and so on.Examples: Input : 3 Output : 5 First three odd numbers are 1, 3, 5, .. Input : 5 Output : 9 First 5 odd numbers are 1, 3, 5, 7, 9, .. The nth odd number is given by the formula 2*n-1. C++ Java Python3 C# PHP Javascript // CPP program to find the nth odd number#include <bits/stdc++.h>using namespace std; // Function to find the nth odd numberint nthOdd(int n){ return (2 * n - 1);} // Driver codeint main(){ int n = 10; cout << nthOdd(n); return 0;} // JAVA program to find the nth odd number class GFG{ // Function to find the nth odd number static int nthOdd(int n) { return (2 * n - 1); } // Driver code public static void main(String [] args) { int n = 10; System.out.println(nthOdd(n)); }} // This code is contributed// by ihritik # Python 3 program to find the# nth odd number # Function to find the nth odd numberdef nthOdd(n): return (2 * n - 1) # Driver codeif __name__=='__main__': n = 10 print(nthOdd(n)) # This code is contributed# by ihritik // C# program to find the nth odd numberusing System; class GFG{ // Function to find the nth odd numberstatic int nthOdd(int n){ return (2 * n - 1);} // Driver codepublic static void Main(){ int n = 10; Console.WriteLine(nthOdd(n));}} // This code is contributed// by inder_verma <?php// PHP program to find the// Nth odd number // Function to find the// Nth odd numberfunction nthOdd($n){ return (2 * $n - 1);} // Driver code$n = 10;echo nthOdd($n); // This code is contributed// by inder_verma?> <script> // Javascript program to find the nth odd number // Function to find the nth odd numberfunction nthOdd(n){ return (2 * n - 1);} // Driver code var n = 10;document.write( nthOdd(n)); </script> Output: 19 ihritik inderDuMCA rutvik_56 series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2021" }, { "code": null, "e": 129, "s": 28, "text": "Given a number n, print the nth odd number. The 1st odd number is 1, 2nd is 3, and so on.Examples: " }, { "code": null, "e": 254, "s": 129, "text": "Input : 3\nOutput : 5\nFirst three odd numbers are 1, 3, 5, ..\n\nInput : 5\nOutput : 9\nFirst 5 odd numbers are 1, 3, 5, 7, 9, .." }, { "code": null, "e": 308, "s": 258, "text": "The nth odd number is given by the formula 2*n-1." }, { "code": null, "e": 314, "s": 310, "text": "C++" }, { "code": null, "e": 319, "s": 314, "text": "Java" }, { "code": null, "e": 327, "s": 319, "text": "Python3" }, { "code": null, "e": 330, "s": 327, "text": "C#" }, { "code": null, "e": 334, "s": 330, "text": "PHP" }, { "code": null, "e": 345, "s": 334, "text": "Javascript" }, { "code": "// CPP program to find the nth odd number#include <bits/stdc++.h>using namespace std; // Function to find the nth odd numberint nthOdd(int n){ return (2 * n - 1);} // Driver codeint main(){ int n = 10; cout << nthOdd(n); return 0;}", "e": 589, "s": 345, "text": null }, { "code": "// JAVA program to find the nth odd number class GFG{ // Function to find the nth odd number static int nthOdd(int n) { return (2 * n - 1); } // Driver code public static void main(String [] args) { int n = 10; System.out.println(nthOdd(n)); }} // This code is contributed// by ihritik", "e": 934, "s": 589, "text": null }, { "code": "# Python 3 program to find the# nth odd number # Function to find the nth odd numberdef nthOdd(n): return (2 * n - 1) # Driver codeif __name__=='__main__': n = 10 print(nthOdd(n)) # This code is contributed# by ihritik", "e": 1172, "s": 934, "text": null }, { "code": "// C# program to find the nth odd numberusing System; class GFG{ // Function to find the nth odd numberstatic int nthOdd(int n){ return (2 * n - 1);} // Driver codepublic static void Main(){ int n = 10; Console.WriteLine(nthOdd(n));}} // This code is contributed// by inder_verma", "e": 1465, "s": 1172, "text": null }, { "code": "<?php// PHP program to find the// Nth odd number // Function to find the// Nth odd numberfunction nthOdd($n){ return (2 * $n - 1);} // Driver code$n = 10;echo nthOdd($n); // This code is contributed// by inder_verma?>", "e": 1686, "s": 1465, "text": null }, { "code": "<script> // Javascript program to find the nth odd number // Function to find the nth odd numberfunction nthOdd(n){ return (2 * n - 1);} // Driver code var n = 10;document.write( nthOdd(n)); </script>", "e": 1891, "s": 1686, "text": null }, { "code": null, "e": 1900, "s": 1891, "text": "Output: " }, { "code": null, "e": 1903, "s": 1900, "text": "19" }, { "code": null, "e": 1913, "s": 1905, "text": "ihritik" }, { "code": null, "e": 1924, "s": 1913, "text": "inderDuMCA" }, { "code": null, "e": 1934, "s": 1924, "text": "rutvik_56" }, { "code": null, "e": 1941, "s": 1934, "text": "series" }, { "code": null, "e": 1954, "s": 1941, "text": "Mathematical" }, { "code": null, "e": 1973, "s": 1954, "text": "School Programming" }, { "code": null, "e": 1986, "s": 1973, "text": "Mathematical" }, { "code": null, "e": 1993, "s": 1986, "text": "series" }, { "code": null, "e": 2091, "s": 1993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2115, "s": 2091, "text": "Merge two sorted arrays" }, { "code": null, "e": 2136, "s": 2115, "text": "Operators in C / C++" }, { "code": null, "e": 2150, "s": 2136, "text": "Prime Numbers" }, { "code": null, "e": 2203, "s": 2150, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 2240, "s": 2203, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 2258, "s": 2240, "text": "Python Dictionary" }, { "code": null, "e": 2283, "s": 2258, "text": "Reverse a string in Java" }, { "code": null, "e": 2299, "s": 2283, "text": "Arrays in C/C++" }, { "code": null, "e": 2322, "s": 2299, "text": "Introduction To PYTHON" } ]
Python – Nearest occurrence between two elements in a List
11 Jun, 2021 Given a list and two elements, x and y find the nearest occurrence index of element x from element y. Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6 Output : 1 Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index. Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 7, y = 6 Output : 3 Explanation : 7 is found at 3rd and 8th index, 6 is at 5th index, nearest is 3rd index. Method : Using list comprehension + loop + index() In this, we find all indices of y using list comprehension, and then get index of x using index(), post that loop is used to get index difference, the nearest index is returned as result. Python3 # Python3 code to demonstrate working of# Nearest occurrence of x from y in List# Using list comprehension + loop + index() # function to find index of nearest# occurrence between two elementsdef nearestOccurrenceIndex(test_list, x, y): # checking if both elements are present in list if x not in test_list or y not in test_list: return -1 # getting indices of x x_idx = [idx for idx in range(len(test_list)) if test_list[idx] == x] # getting y index y_idx = test_list.index(y) # getting min_dist index min_dist = 1000000 res = None for ele in x_idx: # checking for min ele, and updating index if abs(ele - y_idx) < min_dist: res = ele min_dist = abs(ele - y_idx) return res # initializing listinput_list = [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] # printing original listprint("The original list is : " + str(input_list)) # initializing xx = 4 # initializing yy = 6 # printing resultprint("Minimum distance index: ", nearestOccurrenceIndex(input_list, x, y)) Output: The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] Minimum distance index: 8 varshagumber28 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2021" }, { "code": null, "e": 130, "s": 28, "text": "Given a list and two elements, x and y find the nearest occurrence index of element x from element y." }, { "code": null, "e": 312, "s": 130, "text": "Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6 Output : 1 Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index." }, { "code": null, "e": 492, "s": 312, "text": "Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 7, y = 6 Output : 3 Explanation : 7 is found at 3rd and 8th index, 6 is at 5th index, nearest is 3rd index. " }, { "code": null, "e": 543, "s": 492, "text": "Method : Using list comprehension + loop + index()" }, { "code": null, "e": 731, "s": 543, "text": "In this, we find all indices of y using list comprehension, and then get index of x using index(), post that loop is used to get index difference, the nearest index is returned as result." }, { "code": null, "e": 739, "s": 731, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Nearest occurrence of x from y in List# Using list comprehension + loop + index() # function to find index of nearest# occurrence between two elementsdef nearestOccurrenceIndex(test_list, x, y): # checking if both elements are present in list if x not in test_list or y not in test_list: return -1 # getting indices of x x_idx = [idx for idx in range(len(test_list)) if test_list[idx] == x] # getting y index y_idx = test_list.index(y) # getting min_dist index min_dist = 1000000 res = None for ele in x_idx: # checking for min ele, and updating index if abs(ele - y_idx) < min_dist: res = ele min_dist = abs(ele - y_idx) return res # initializing listinput_list = [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] # printing original listprint(\"The original list is : \" + str(input_list)) # initializing xx = 4 # initializing yy = 6 # printing resultprint(\"Minimum distance index: \", nearestOccurrenceIndex(input_list, x, y))", "e": 1786, "s": 739, "text": null }, { "code": null, "e": 1794, "s": 1786, "text": "Output:" }, { "code": null, "e": 1892, "s": 1794, "text": "The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] Minimum distance index: 8 " }, { "code": null, "e": 1907, "s": 1892, "text": "varshagumber28" }, { "code": null, "e": 1928, "s": 1907, "text": "Python list-programs" }, { "code": null, "e": 1935, "s": 1928, "text": "Python" }, { "code": null, "e": 1951, "s": 1935, "text": "Python Programs" }, { "code": null, "e": 2049, "s": 1951, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2067, "s": 2049, "text": "Python Dictionary" }, { "code": null, "e": 2109, "s": 2067, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2135, "s": 2109, "text": "Python String | replace()" }, { "code": null, "e": 2167, "s": 2135, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2196, "s": 2167, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2218, "s": 2196, "text": "Defaultdict in Python" }, { "code": null, "e": 2257, "s": 2218, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2295, "s": 2257, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2332, "s": 2295, "text": "Python Program for Fibonacci numbers" } ]
Node.js URL.hash API
14 Oct, 2021 The url.hash is an inbuilt application programming interface of class URL within url module which is used to get and set the fragment portion of the URL. Syntax: url.hash Return value: It gets and sets the fragment portion of the URL. Below programs illustrate the use of url.hash Method: Example 1: Javascript // node program to demonstrate the // url.hash API as Setter // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram'); // Display href value of myURL before changeconsole.log("Before Change");console.log(myURL.href); // assigning fragment portion// using hash console.log();myURL.hash = 'rahim'; // Display href value of myURL after changeconsole.log("After Change");console.log(myURL.href); Output: Before Change https://example.org/foo#ram After Change https://example.org/foo#rahim Example 2: Javascript // node program to demonstrate the // url.hash API as Getter // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram'); // getting the fragment portion// using hash const hash = myURL.hash; // Display hash value console.log(hash); Output: #ram NOTE: The above program could be run by using the node myapp.js command. Reference: https://nodejs.org/dist/latest-v10.x/docs/api/url.html#url_url_hash AshishkrGoyal sweetyty Node-URL Web technologies Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Node.js forEach() function How to use an ES6 import in Node.js? What are the differences between npm and npx ?
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Oct, 2021" }, { "code": null, "e": 207, "s": 53, "text": "The url.hash is an inbuilt application programming interface of class URL within url module which is used to get and set the fragment portion of the URL." }, { "code": null, "e": 216, "s": 207, "text": "Syntax: " }, { "code": null, "e": 225, "s": 216, "text": "url.hash" }, { "code": null, "e": 289, "s": 225, "text": "Return value: It gets and sets the fragment portion of the URL." }, { "code": null, "e": 343, "s": 289, "text": "Below programs illustrate the use of url.hash Method:" }, { "code": null, "e": 356, "s": 343, "text": "Example 1: " }, { "code": null, "e": 367, "s": 356, "text": "Javascript" }, { "code": "// node program to demonstrate the // url.hash API as Setter // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram'); // Display href value of myURL before changeconsole.log(\"Before Change\");console.log(myURL.href); // assigning fragment portion// using hash console.log();myURL.hash = 'rahim'; // Display href value of myURL after changeconsole.log(\"After Change\");console.log(myURL.href);", "e": 794, "s": 367, "text": null }, { "code": null, "e": 803, "s": 794, "text": "Output: " }, { "code": null, "e": 889, "s": 803, "text": "Before Change\nhttps://example.org/foo#ram\n\nAfter Change\nhttps://example.org/foo#rahim" }, { "code": null, "e": 902, "s": 889, "text": "Example 2: " }, { "code": null, "e": 913, "s": 902, "text": "Javascript" }, { "code": "// node program to demonstrate the // url.hash API as Getter // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram'); // getting the fragment portion// using hash const hash = myURL.hash; // Display hash value console.log(hash);", "e": 1177, "s": 913, "text": null }, { "code": null, "e": 1186, "s": 1177, "text": "Output: " }, { "code": null, "e": 1191, "s": 1186, "text": "#ram" }, { "code": null, "e": 1265, "s": 1191, "text": "NOTE: The above program could be run by using the node myapp.js command. " }, { "code": null, "e": 1345, "s": 1265, "text": "Reference: https://nodejs.org/dist/latest-v10.x/docs/api/url.html#url_url_hash " }, { "code": null, "e": 1359, "s": 1345, "text": "AshishkrGoyal" }, { "code": null, "e": 1368, "s": 1359, "text": "sweetyty" }, { "code": null, "e": 1377, "s": 1368, "text": "Node-URL" }, { "code": null, "e": 1394, "s": 1377, "text": "Web technologies" }, { "code": null, "e": 1402, "s": 1394, "text": "Node.js" }, { "code": null, "e": 1500, "s": 1402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1548, "s": 1500, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1581, "s": 1548, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1611, "s": 1581, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 1631, "s": 1611, "text": "How to update NPM ?" }, { "code": null, "e": 1685, "s": 1631, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1725, "s": 1685, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 1757, "s": 1725, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1784, "s": 1757, "text": "Node.js forEach() function" }, { "code": null, "e": 1821, "s": 1784, "text": "How to use an ES6 import in Node.js?" } ]
Python – Binomial Distribution
16 Jul, 2020 Binomial distribution is a probability distribution that summarises the likelihood that a variable will take one of two independent values under a given set of parameters. The distribution is obtained by performing a number of Bernoulli trials. A Bernoulli trial is assumed to meet each of these criteria : There must be only 2 possible outcomes. Each outcome has a fixed probability of occurring. A success has the probability of p, and a failure has the probability of 1 – p. Each trial is completely independent of all others. The binomial random variable represents the number of successes(r) in n successive independent trials of a Bernoulli experiment. Probability of achieving r success and n-r failure is : Consider a random experiment of tossing a biased coin 6 times where the probability of getting a head is 0.6. If ‘getting a head’ is considered as ‘success’ then, the binomial distribution table will contain the probability of r successes for each possible value of r. This distribution has a mean equal to np and a variance of np(1-p). Using Python to obtain the distribution :Now, we will use Python to analyse the distribution(using SciPy) and plot the graph(using Matplotlib).Modules required : SciPy:SciPy is an Open Source Python library, used in mathematics, engineering, scientific and technical computing.Installation :pip install scipy Installation : pip install scipy Matplotlib:Matplotlib is a comprehensive Python library for plotting static and interactive graphs and visualisations. Installation :pip install matplotlib Installation : pip install matplotlib The scipy.stats module contains various functions for statistical calculations and tests. The stats() function of the scipy.stats.binom module can be used to calculate a binomial distribution using the values of n and p. Syntax : scipy.stats.binom.stats(n, p) It returns a tuple containing the mean and variance of the distribution in that order. scipy.stats.binom.pmf() function is used to obtain the probability mass function for a certain value of r, n and p. We can obtain the distribution by passing all possible values of r(0 to n). Syntax : scipy.stats.binom.pmf(r, n, p) Calculating distribution table : Approach : Define n and p. Define a list of values of r from 0 to n. Get mean and variance. For each r, calculate the pmf and store in a list. Code : from scipy.stats import binom# setting the values# of n and pn = 6p = 0.6# defining the list of r valuesr_values = list(range(n + 1))# obtaining the mean and variance mean, var = binom.stats(n, p)# list of pmf valuesdist = [binom.pmf(r, n, p) for r in r_values ]# printing the tableprint("r\tp(r)")for i in range(n + 1): print(str(r_values[i]) + "\t" + str(dist[i]))# printing mean and varianceprint("mean = "+str(mean))print("variance = "+str(var)) Output : r p(r) 0 0.004096000000000002 1 0.03686400000000005 2 0.13824000000000003 3 0.2764800000000001 4 0.31104 5 0.18662400000000007 6 0.04665599999999999 mean = 3.5999999999999996 variance = 1.44 Code: Plotting the graph using matplotlib.pyplot.bar() function to plot vertical bars. from scipy.stats import binomimport matplotlib.pyplot as plt# setting the values# of n and pn = 6p = 0.6# defining list of r valuesr_values = list(range(n + 1))# list of pmf valuesdist = [binom.pmf(r, n, p) for r in r_values ]# plotting the graph plt.bar(r_values, dist)plt.show() Output : Probability statistical-algorithms Python Probability Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jul, 2020" }, { "code": null, "e": 297, "s": 52, "text": "Binomial distribution is a probability distribution that summarises the likelihood that a variable will take one of two independent values under a given set of parameters. The distribution is obtained by performing a number of Bernoulli trials." }, { "code": null, "e": 359, "s": 297, "text": "A Bernoulli trial is assumed to meet each of these criteria :" }, { "code": null, "e": 399, "s": 359, "text": "There must be only 2 possible outcomes." }, { "code": null, "e": 530, "s": 399, "text": "Each outcome has a fixed probability of occurring. A success has the probability of p, and a failure has the probability of 1 – p." }, { "code": null, "e": 582, "s": 530, "text": "Each trial is completely independent of all others." }, { "code": null, "e": 711, "s": 582, "text": "The binomial random variable represents the number of successes(r) in n successive independent trials of a Bernoulli experiment." }, { "code": null, "e": 767, "s": 711, "text": "Probability of achieving r success and n-r failure is :" }, { "code": null, "e": 1036, "s": 767, "text": "Consider a random experiment of tossing a biased coin 6 times where the probability of getting a head is 0.6. If ‘getting a head’ is considered as ‘success’ then, the binomial distribution table will contain the probability of r successes for each possible value of r." }, { "code": null, "e": 1105, "s": 1036, "text": "This distribution has a mean equal to np and a variance of np(1-p). " }, { "code": null, "e": 1267, "s": 1105, "text": "Using Python to obtain the distribution :Now, we will use Python to analyse the distribution(using SciPy) and plot the graph(using Matplotlib).Modules required :" }, { "code": null, "e": 1415, "s": 1267, "text": "SciPy:SciPy is an Open Source Python library, used in mathematics, engineering, scientific and technical computing.Installation :pip install scipy\n" }, { "code": null, "e": 1430, "s": 1415, "text": "Installation :" }, { "code": null, "e": 1449, "s": 1430, "text": "pip install scipy\n" }, { "code": null, "e": 1606, "s": 1449, "text": "Matplotlib:Matplotlib is a comprehensive Python library for plotting static and interactive graphs and visualisations. Installation :pip install matplotlib\n" }, { "code": null, "e": 1621, "s": 1606, "text": "Installation :" }, { "code": null, "e": 1645, "s": 1621, "text": "pip install matplotlib\n" }, { "code": null, "e": 1866, "s": 1645, "text": "The scipy.stats module contains various functions for statistical calculations and tests. The stats() function of the scipy.stats.binom module can be used to calculate a binomial distribution using the values of n and p." }, { "code": null, "e": 1905, "s": 1866, "text": "Syntax : scipy.stats.binom.stats(n, p)" }, { "code": null, "e": 1992, "s": 1905, "text": "It returns a tuple containing the mean and variance of the distribution in that order." }, { "code": null, "e": 2184, "s": 1992, "text": "scipy.stats.binom.pmf() function is used to obtain the probability mass function for a certain value of r, n and p. We can obtain the distribution by passing all possible values of r(0 to n)." }, { "code": null, "e": 2224, "s": 2184, "text": "Syntax : scipy.stats.binom.pmf(r, n, p)" }, { "code": null, "e": 2257, "s": 2224, "text": "Calculating distribution table :" }, { "code": null, "e": 2268, "s": 2257, "text": "Approach :" }, { "code": null, "e": 2284, "s": 2268, "text": "Define n and p." }, { "code": null, "e": 2326, "s": 2284, "text": "Define a list of values of r from 0 to n." }, { "code": null, "e": 2349, "s": 2326, "text": "Get mean and variance." }, { "code": null, "e": 2400, "s": 2349, "text": "For each r, calculate the pmf and store in a list." }, { "code": null, "e": 2407, "s": 2400, "text": "Code :" }, { "code": "from scipy.stats import binom# setting the values# of n and pn = 6p = 0.6# defining the list of r valuesr_values = list(range(n + 1))# obtaining the mean and variance mean, var = binom.stats(n, p)# list of pmf valuesdist = [binom.pmf(r, n, p) for r in r_values ]# printing the tableprint(\"r\\tp(r)\")for i in range(n + 1): print(str(r_values[i]) + \"\\t\" + str(dist[i]))# printing mean and varianceprint(\"mean = \"+str(mean))print(\"variance = \"+str(var))", "e": 2860, "s": 2407, "text": null }, { "code": null, "e": 2869, "s": 2860, "text": "Output :" }, { "code": null, "e": 3085, "s": 2869, "text": "r p(r)\n0 0.004096000000000002\n1 0.03686400000000005\n2 0.13824000000000003\n3 0.2764800000000001\n4 0.31104\n5 0.18662400000000007\n6 0.04665599999999999\nmean = 3.5999999999999996\nvariance = 1.44\n" }, { "code": null, "e": 3172, "s": 3085, "text": "Code: Plotting the graph using matplotlib.pyplot.bar() function to plot vertical bars." }, { "code": "from scipy.stats import binomimport matplotlib.pyplot as plt# setting the values# of n and pn = 6p = 0.6# defining list of r valuesr_values = list(range(n + 1))# list of pmf valuesdist = [binom.pmf(r, n, p) for r in r_values ]# plotting the graph plt.bar(r_values, dist)plt.show()", "e": 3453, "s": 3172, "text": null }, { "code": null, "e": 3462, "s": 3453, "text": "Output :" }, { "code": null, "e": 3474, "s": 3462, "text": "Probability" }, { "code": null, "e": 3497, "s": 3474, "text": "statistical-algorithms" }, { "code": null, "e": 3504, "s": 3497, "text": "Python" }, { "code": null, "e": 3516, "s": 3504, "text": "Probability" }, { "code": null, "e": 3614, "s": 3516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3632, "s": 3614, "text": "Python Dictionary" }, { "code": null, "e": 3674, "s": 3632, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3696, "s": 3674, "text": "Enumerate() in Python" }, { "code": null, "e": 3731, "s": 3696, "text": "Read a file line by line in Python" }, { "code": null, "e": 3757, "s": 3731, "text": "Python String | replace()" }, { "code": null, "e": 3789, "s": 3757, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3818, "s": 3789, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3845, "s": 3818, "text": "Python Classes and Objects" }, { "code": null, "e": 3875, "s": 3845, "text": "Iterate over a list in Python" } ]
Get Flight Status using Python
17 May, 2022 Prerequisite Implementing Web Scraping in Python with BeautifulSoup In this article, we are going to write a python script to get Flight Status. Module needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 Requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Approach: Import module Create a URL get function Now merge the information into URL and pass the URL into the getdata() function and Convert that data into HTML code. Now find the required tag from the HTML code and traverse the result Implementation: Python3 # import moduleimport requestsfrom bs4 import BeautifulSoup # UDF for get HTML code# from URL def get_html(Airline_code, Flight_number, Date, Month, Year): def getdata(url): r = requests.get(url) return r.text # url url = "https://www.flightstats.com/v2/flight-tracker/"+Airline_code + \ "/"+Flight_number+"?year="+Year+"&month="+Month+"&date="+Date # pass the url # into getdata function htmldata = getdata(url) soup = BeautifulSoup(htmldata, 'html.parser') return(soup) # Get Flight number# from Html code def flight_no(soup): Flight_no = "" # Find div tag with # unique class name for i in soup.find("div", class_="ticket__FlightNumberContainer-s1rrbl5o-4 hgbvHg"): Flight_no = Flight_no + (i.get_text()) + " " return (Flight_no) # Get Airport name# from HTML code def airport(soup): Airport_name = [] # Find div tag with # unique class name for i in soup.find_all("div", class_="text-helper__TextHelper-s8bko4a-0 CPamx"): Airport_name.append(i.get_text()) return (Airport_name) # get status# from HTML code def status(soup, Airport_list): Time_status = [] Airport_List = [] Status_str = [] Gate = [] Gate_no = [] # Find div tag with # unique class name # to get Gate number for data in soup.find_all("div", class_="ticket__TGBLabel-s1rrbl5o-15 gcbyEH text-helper__TextHelper-s8bko4a-0 dfeqpK"): Gate.append(data.get_text()) for data in soup.find_all("div", class_="ticket__TGBValue-s1rrbl5o-16 icyRae text-helper__TextHelper-s8bko4a-0 cCfBRT"): Gate_no.append(data.get_text()) # Get status from # html code for i in soup.find_all("div", class_="text-helper__TextHelper-s8bko4a-0 bcmzUJ"): Status_str.append(i.get_text()) for i in soup.find_all("div", class_="text-helper__TextHelper-s8bko4a-0 cCfBRT"): Time_status.append(i.get_text()) # traverse the Data # from scraping data for item in range(4): if item == 0: print(Airport_list[0]) if item == 2: print("") print(Airport_list[1]) print(Status_str[item] + " : " + Time_status[item]) print(Gate[item] + " : " + Gate_no[item]) for item in range(len(Gate)): print(Gate[item] + " : " + Gate_no[item]) # Driver codeif __name__ == '__main__': # Input Data from geek Airline_code = 'G8' Flight_number = '134' Date = '23' Month = '10' Year = '2020' # Calling the get_html # with argument # function calling soup = get_html(Airline_code, Flight_number, Date, Month, Year) print("Flight number : ", flight_no(soup)) Airport_list = airport(soup) status(soup, Airport_list) Output: Flight number : G8 134 GoAir Jay Prakash Narayan International Airport Scheduled : 21:00 IST Terminal : N/A Estimated : 21:00 IST Gate : N/A Indira Gandhi International Airport Scheduled : 22:40 IST Terminal : T2 Estimated : 22:40 IST Gate : 205 Terminal : N/A Gate : N/A Terminal : T2 Gate : 205 gulshankumarar231 Python web-scraping-exercises Python-projects python-utility Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2022" }, { "code": null, "e": 120, "s": 52, "text": "Prerequisite Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 197, "s": 120, "text": "In this article, we are going to write a python script to get Flight Status." }, { "code": null, "e": 212, "s": 197, "text": "Module needed:" }, { "code": null, "e": 405, "s": 212, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 421, "s": 405, "text": "pip install bs4" }, { "code": null, "e": 603, "s": 421, "text": "Requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 624, "s": 603, "text": "pip install requests" }, { "code": null, "e": 634, "s": 624, "text": "Approach:" }, { "code": null, "e": 648, "s": 634, "text": "Import module" }, { "code": null, "e": 674, "s": 648, "text": "Create a URL get function" }, { "code": null, "e": 792, "s": 674, "text": "Now merge the information into URL and pass the URL into the getdata() function and Convert that data into HTML code." }, { "code": null, "e": 861, "s": 792, "text": "Now find the required tag from the HTML code and traverse the result" }, { "code": null, "e": 877, "s": 861, "text": "Implementation:" }, { "code": null, "e": 885, "s": 877, "text": "Python3" }, { "code": "# import moduleimport requestsfrom bs4 import BeautifulSoup # UDF for get HTML code# from URL def get_html(Airline_code, Flight_number, Date, Month, Year): def getdata(url): r = requests.get(url) return r.text # url url = \"https://www.flightstats.com/v2/flight-tracker/\"+Airline_code + \\ \"/\"+Flight_number+\"?year=\"+Year+\"&month=\"+Month+\"&date=\"+Date # pass the url # into getdata function htmldata = getdata(url) soup = BeautifulSoup(htmldata, 'html.parser') return(soup) # Get Flight number# from Html code def flight_no(soup): Flight_no = \"\" # Find div tag with # unique class name for i in soup.find(\"div\", class_=\"ticket__FlightNumberContainer-s1rrbl5o-4 hgbvHg\"): Flight_no = Flight_no + (i.get_text()) + \" \" return (Flight_no) # Get Airport name# from HTML code def airport(soup): Airport_name = [] # Find div tag with # unique class name for i in soup.find_all(\"div\", class_=\"text-helper__TextHelper-s8bko4a-0 CPamx\"): Airport_name.append(i.get_text()) return (Airport_name) # get status# from HTML code def status(soup, Airport_list): Time_status = [] Airport_List = [] Status_str = [] Gate = [] Gate_no = [] # Find div tag with # unique class name # to get Gate number for data in soup.find_all(\"div\", class_=\"ticket__TGBLabel-s1rrbl5o-15 gcbyEH text-helper__TextHelper-s8bko4a-0 dfeqpK\"): Gate.append(data.get_text()) for data in soup.find_all(\"div\", class_=\"ticket__TGBValue-s1rrbl5o-16 icyRae text-helper__TextHelper-s8bko4a-0 cCfBRT\"): Gate_no.append(data.get_text()) # Get status from # html code for i in soup.find_all(\"div\", class_=\"text-helper__TextHelper-s8bko4a-0 bcmzUJ\"): Status_str.append(i.get_text()) for i in soup.find_all(\"div\", class_=\"text-helper__TextHelper-s8bko4a-0 cCfBRT\"): Time_status.append(i.get_text()) # traverse the Data # from scraping data for item in range(4): if item == 0: print(Airport_list[0]) if item == 2: print(\"\") print(Airport_list[1]) print(Status_str[item] + \" : \" + Time_status[item]) print(Gate[item] + \" : \" + Gate_no[item]) for item in range(len(Gate)): print(Gate[item] + \" : \" + Gate_no[item]) # Driver codeif __name__ == '__main__': # Input Data from geek Airline_code = 'G8' Flight_number = '134' Date = '23' Month = '10' Year = '2020' # Calling the get_html # with argument # function calling soup = get_html(Airline_code, Flight_number, Date, Month, Year) print(\"Flight number : \", flight_no(soup)) Airport_list = airport(soup) status(soup, Airport_list)", "e": 3614, "s": 885, "text": null }, { "code": null, "e": 3622, "s": 3614, "text": "Output:" }, { "code": null, "e": 3922, "s": 3622, "text": "Flight number : G8 134 GoAir \nJay Prakash Narayan International Airport\nScheduled : 21:00 IST\nTerminal : N/A\nEstimated : 21:00 IST\nGate : N/A\n\nIndira Gandhi International Airport\nScheduled : 22:40 IST\nTerminal : T2\nEstimated : 22:40 IST\nGate : 205\nTerminal : N/A\nGate : N/A\nTerminal : T2\nGate : 205" }, { "code": null, "e": 3940, "s": 3922, "text": "gulshankumarar231" }, { "code": null, "e": 3970, "s": 3940, "text": "Python web-scraping-exercises" }, { "code": null, "e": 3986, "s": 3970, "text": "Python-projects" }, { "code": null, "e": 4001, "s": 3986, "text": "python-utility" }, { "code": null, "e": 4014, "s": 4001, "text": "Web-scraping" }, { "code": null, "e": 4021, "s": 4014, "text": "Python" } ]
Create Holiday Calendar using HTML and PHP
06 Jul, 2021 In this article, we will create a holiday calendar for a given month using the concept of tables in HTML, CSS for styling the calendar, and PHP. We will also display all the holidays in a given month, highlight them using a different color and display the holiday name whenever the mouse hovers over the highlighted date. We will use PHP for iterating over the dates and check if it is on the holiday list. If the mouse hovers on a holiday cell, it will trigger a JavaScript function that will display the holiday name below the calendar. Example: We will display the calendar for August 2021 as an example. We will create a list of all holidays in August 2021, highlight the holidays using CSS background-color property and display holiday names on mouse hover. HTML <!DOCTYPE html><html> <head> <title>August 2021</title> <style> table { background-color: yellow; } td { width: 40px; height: 40px; text-align: center; } .day { font-weight: bolder; background-color: lightpink; } .holiday { background-color: lightblue; } #field { font-weight: bolder; text-align: center; } </style> <script type="text/javascript"> function show(a) { document.getElementById('field').innerHTML = document.getElementById(a.id) .attributes["name"].value; setTimeout(function () { document.getElementById('field').innerHTML = ""; }, 5000); } </script></head> <body> <table align="center" border="1"> <tr> <td colspan="7"><b>August 2021</b></td> </tr> <tr class="day"> <td>Sun</td> <td>Mon</td> <td>Tue</td> <td>Wed</td> <td>Thu</td> <td>Fri</td> <td>Sat</td> </tr> <?php $holidays = array( 15 => "Independence Day", 19 => "Muharram", 21 => "Onam", 22 => "Raksha Bandhan", 30 => "Janmashtami" ); for($i = 1; $i <= 31; $i++) { if (in_array($i, array_keys($holidays))) { $x = $holidays[$i]; echo "<td class = holiday id='$i' name ='$x' onmouseover = show(this)>$i</td>"; } else { echo "<td id =$i>$i</td>"; } if($i % 7 == 0) { echo "</tr><tr>"; } } ?> </table> <br><br> <div id="field"></div></body> </html> Output: In the below output, when the mouse hovers over the “30 August” cell, it displays the holiday name as “Janmashtami”. holiday calendar with mouse hover CSS-Properties CSS-Questions HTML-Questions PHP-array PHP-Questions CSS HTML PHP Web Technologies HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2021" }, { "code": null, "e": 197, "s": 52, "text": "In this article, we will create a holiday calendar for a given month using the concept of tables in HTML, CSS for styling the calendar, and PHP." }, { "code": null, "e": 591, "s": 197, "text": "We will also display all the holidays in a given month, highlight them using a different color and display the holiday name whenever the mouse hovers over the highlighted date. We will use PHP for iterating over the dates and check if it is on the holiday list. If the mouse hovers on a holiday cell, it will trigger a JavaScript function that will display the holiday name below the calendar." }, { "code": null, "e": 816, "s": 591, "text": "Example: We will display the calendar for August 2021 as an example. We will create a list of all holidays in August 2021, highlight the holidays using CSS background-color property and display holiday names on mouse hover. " }, { "code": null, "e": 821, "s": 816, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>August 2021</title> <style> table { background-color: yellow; } td { width: 40px; height: 40px; text-align: center; } .day { font-weight: bolder; background-color: lightpink; } .holiday { background-color: lightblue; } #field { font-weight: bolder; text-align: center; } </style> <script type=\"text/javascript\"> function show(a) { document.getElementById('field').innerHTML = document.getElementById(a.id) .attributes[\"name\"].value; setTimeout(function () { document.getElementById('field').innerHTML = \"\"; }, 5000); } </script></head> <body> <table align=\"center\" border=\"1\"> <tr> <td colspan=\"7\"><b>August 2021</b></td> </tr> <tr class=\"day\"> <td>Sun</td> <td>Mon</td> <td>Tue</td> <td>Wed</td> <td>Thu</td> <td>Fri</td> <td>Sat</td> </tr> <?php $holidays = array( 15 => \"Independence Day\", 19 => \"Muharram\", 21 => \"Onam\", 22 => \"Raksha Bandhan\", 30 => \"Janmashtami\" ); for($i = 1; $i <= 31; $i++) { if (in_array($i, array_keys($holidays))) { $x = $holidays[$i]; echo \"<td class = holiday id='$i' name ='$x' onmouseover = show(this)>$i</td>\"; } else { echo \"<td id =$i>$i</td>\"; } if($i % 7 == 0) { echo \"</tr><tr>\"; } } ?> </table> <br><br> <div id=\"field\"></div></body> </html>", "e": 2779, "s": 821, "text": null }, { "code": null, "e": 2904, "s": 2779, "text": "Output: In the below output, when the mouse hovers over the “30 August” cell, it displays the holiday name as “Janmashtami”." }, { "code": null, "e": 2938, "s": 2904, "text": "holiday calendar with mouse hover" }, { "code": null, "e": 2953, "s": 2938, "text": "CSS-Properties" }, { "code": null, "e": 2967, "s": 2953, "text": "CSS-Questions" }, { "code": null, "e": 2982, "s": 2967, "text": "HTML-Questions" }, { "code": null, "e": 2992, "s": 2982, "text": "PHP-array" }, { "code": null, "e": 3006, "s": 2992, "text": "PHP-Questions" }, { "code": null, "e": 3010, "s": 3006, "text": "CSS" }, { "code": null, "e": 3015, "s": 3010, "text": "HTML" }, { "code": null, "e": 3019, "s": 3015, "text": "PHP" }, { "code": null, "e": 3036, "s": 3019, "text": "Web Technologies" }, { "code": null, "e": 3041, "s": 3036, "text": "HTML" }, { "code": null, "e": 3045, "s": 3041, "text": "PHP" }, { "code": null, "e": 3143, "s": 3045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3182, "s": 3143, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3221, "s": 3182, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3260, "s": 3221, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3289, "s": 3260, "text": "Form validation using jQuery" }, { "code": null, "e": 3326, "s": 3289, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3350, "s": 3326, "text": "REST API (Introduction)" }, { "code": null, "e": 3403, "s": 3350, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3463, "s": 3403, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3524, "s": 3463, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Logger log() Method in Java with Examples
27 Jun, 2019 The log() method of Logger is used to Log a message. If the logger is currently enabled for the given message level which is passed as parameter then a corresponding LogRecord is created and forwarded to all the registered Output Handler objects. But in logger class, there are seven different log() method depending upon the parameters passed to the method. log(Level level, String msg): This method is used to Log a message, with no arguments.only message will be written in logger Output.Syntax:public void log(Level level, String msg) Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msg which is the string message (or a key in the message catalog).Return value: This method returns nothingProgram 1: Method log(Level level, String msg)// Java program to demonstrate// Logger.log(Level level, String msg) method import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using log(Level level, String msg) logger.log(Level.INFO, "This is message 1"); logger.log(Level.WARNING, "This is message 2"); }}Outputlog(Level level, String msg, Object param1): This method is used to Log a message, with one object parameter.Syntax:public void log(Level level, String msg, Object param1) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is parameter to the messageReturn value: This method returns nothingProgram 2: Method log(Level level, String msg, Object param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object param1) logger.log(Level.INFO, "logging: {0} ", "message1"); logger.log(Level.SEVERE, "logging: {0} ", "message2"); }}Output:log(Level level, String msg, Object[] params): This method is used to Log a message, with an array of object arguments.Syntax:public void log(Level level, String msg, Object[] params) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is array of parameters to the messageReturn value: This method returns nothingProgram 3: Method log(Level level, String msg, Object[] param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object[] param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object[] param1) logger.log(Level.INFO, "logging: {0} {1}", new Object[] { "parameter1", "parameter2" }); logger.log(Level.WARNING, "logging: {0} {1} {2}", new Object[] { "p1", "p2", "p3" }); }}Output:log(Level level, String msg, Throwable thrown): This method is used to Log a message, with associated Throwable information.Syntax:public void log(Level level, String msg, Throwable thrown) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and thrown which is Throwable associated with log message.Return value: This method returns nothingProgram 4: Method log(Level level, String msg, Throwable thrown)// Java program to demonstrate// Logger.log(Level level, String msg, Throwable thrown) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Throwable thrown) logger.log(Level.SEVERE, "logging:", new RuntimeException("Error")); logger.log(Level.WARNING, "logging: ", new Exception("Exception")); }}Output:log(Level level, Throwable thrown, Supplier msgSupplier): This method is used to Log a lazily constructed message, with associated Throwable information.The message and the given Throwable are then stored in a LogRecord which is forwarded to all registered Output handlers.Syntax:public void log(Level level, Throwable thrown, Supplier msgSupplier) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, thrown which is the Throwable associated with log message and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 5: Method log(Level level, Throwable thrown, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, Throwable thrown, Supplier<String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger logs"); // log messages using // log(Level level, Throwable thrown, Supplier<String> msgSupplier) logger.log(Level.SEVERE, new RuntimeException("Error"), StrSupplier); }}Output:log(Level level, Supplier msgSupplier): This method is used to Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.Syntax:public void log(Level level, Supplier msgSupplier) Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 6: Method log(Level level, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, <String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger messages"); // log messages using // log(Level level, Supplier<String> msgSupplier) logger.log(Level.SEVERE, StrSupplier); }}Output:log(LogRecord record): This method is used to Log a LogRecord.Using logRecord we will log the info to logger Outputs.Syntax:public void log(LogRecord record) Parameters: This method accepts one parameter record which is the LogRecord to be published.Return value: This method returns nothingProgram 7: Method log(LogRecord record)// Java program to demonstrate// Logger.log(LogRecord record) import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // create logRecords LogRecord record1 = new LogRecord(Level.INFO, "Msg 1"); LogRecord record2 = new LogRecord(Level.INFO, "Msg 2"); // log messages using // log(LogRecord record) logger.log(record1); logger.log(record2); }}Output: log(Level level, String msg): This method is used to Log a message, with no arguments.only message will be written in logger Output.Syntax:public void log(Level level, String msg) Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msg which is the string message (or a key in the message catalog).Return value: This method returns nothingProgram 1: Method log(Level level, String msg)// Java program to demonstrate// Logger.log(Level level, String msg) method import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using log(Level level, String msg) logger.log(Level.INFO, "This is message 1"); logger.log(Level.WARNING, "This is message 2"); }}Output public void log(Level level, String msg) Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msg which is the string message (or a key in the message catalog). Return value: This method returns nothing Program 1: Method log(Level level, String msg) // Java program to demonstrate// Logger.log(Level level, String msg) method import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using log(Level level, String msg) logger.log(Level.INFO, "This is message 1"); logger.log(Level.WARNING, "This is message 2"); }} Output log(Level level, String msg, Object param1): This method is used to Log a message, with one object parameter.Syntax:public void log(Level level, String msg, Object param1) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is parameter to the messageReturn value: This method returns nothingProgram 2: Method log(Level level, String msg, Object param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object param1) logger.log(Level.INFO, "logging: {0} ", "message1"); logger.log(Level.SEVERE, "logging: {0} ", "message2"); }}Output: Syntax: public void log(Level level, String msg, Object param1) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is parameter to the message Return value: This method returns nothing Program 2: Method log(Level level, String msg, Object param1) // Java program to demonstrate// Logger.log(Level level, String msg, Object param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object param1) logger.log(Level.INFO, "logging: {0} ", "message1"); logger.log(Level.SEVERE, "logging: {0} ", "message2"); }} Output: log(Level level, String msg, Object[] params): This method is used to Log a message, with an array of object arguments.Syntax:public void log(Level level, String msg, Object[] params) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is array of parameters to the messageReturn value: This method returns nothingProgram 3: Method log(Level level, String msg, Object[] param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object[] param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object[] param1) logger.log(Level.INFO, "logging: {0} {1}", new Object[] { "parameter1", "parameter2" }); logger.log(Level.WARNING, "logging: {0} {1} {2}", new Object[] { "p1", "p2", "p3" }); }}Output: Syntax: public void log(Level level, String msg, Object[] params) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is array of parameters to the message Return value: This method returns nothing Program 3: Method log(Level level, String msg, Object[] param1) // Java program to demonstrate// Logger.log(Level level, String msg, Object[] param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object[] param1) logger.log(Level.INFO, "logging: {0} {1}", new Object[] { "parameter1", "parameter2" }); logger.log(Level.WARNING, "logging: {0} {1} {2}", new Object[] { "p1", "p2", "p3" }); }} Output: log(Level level, String msg, Throwable thrown): This method is used to Log a message, with associated Throwable information.Syntax:public void log(Level level, String msg, Throwable thrown) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and thrown which is Throwable associated with log message.Return value: This method returns nothingProgram 4: Method log(Level level, String msg, Throwable thrown)// Java program to demonstrate// Logger.log(Level level, String msg, Throwable thrown) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Throwable thrown) logger.log(Level.SEVERE, "logging:", new RuntimeException("Error")); logger.log(Level.WARNING, "logging: ", new Exception("Exception")); }}Output: Syntax: public void log(Level level, String msg, Throwable thrown) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and thrown which is Throwable associated with log message. Return value: This method returns nothing Program 4: Method log(Level level, String msg, Throwable thrown) // Java program to demonstrate// Logger.log(Level level, String msg, Throwable thrown) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Throwable thrown) logger.log(Level.SEVERE, "logging:", new RuntimeException("Error")); logger.log(Level.WARNING, "logging: ", new Exception("Exception")); }} Output: log(Level level, Throwable thrown, Supplier msgSupplier): This method is used to Log a lazily constructed message, with associated Throwable information.The message and the given Throwable are then stored in a LogRecord which is forwarded to all registered Output handlers.Syntax:public void log(Level level, Throwable thrown, Supplier msgSupplier) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, thrown which is the Throwable associated with log message and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 5: Method log(Level level, Throwable thrown, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, Throwable thrown, Supplier<String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger logs"); // log messages using // log(Level level, Throwable thrown, Supplier<String> msgSupplier) logger.log(Level.SEVERE, new RuntimeException("Error"), StrSupplier); }}Output: Syntax: public void log(Level level, Throwable thrown, Supplier msgSupplier) Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, thrown which is the Throwable associated with log message and msgSupplier which is a function, which when called, produces the desired log message. Return value: This method returns nothing Program 5: Method log(Level level, Throwable thrown, Supplier msgSupplier) // Java program to demonstrate// Logger.log(Level level, Throwable thrown, Supplier<String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger logs"); // log messages using // log(Level level, Throwable thrown, Supplier<String> msgSupplier) logger.log(Level.SEVERE, new RuntimeException("Error"), StrSupplier); }} Output: log(Level level, Supplier msgSupplier): This method is used to Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.Syntax:public void log(Level level, Supplier msgSupplier) Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 6: Method log(Level level, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, <String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger messages"); // log messages using // log(Level level, Supplier<String> msgSupplier) logger.log(Level.SEVERE, StrSupplier); }}Output: Syntax: public void log(Level level, Supplier msgSupplier) Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msgSupplier which is a function, which when called, produces the desired log message. Return value: This method returns nothing Program 6: Method log(Level level, Supplier msgSupplier) // Java program to demonstrate// Logger.log(Level level, <String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String("Logger messages"); // log messages using // log(Level level, Supplier<String> msgSupplier) logger.log(Level.SEVERE, StrSupplier); }} Output: log(LogRecord record): This method is used to Log a LogRecord.Using logRecord we will log the info to logger Outputs.Syntax:public void log(LogRecord record) Parameters: This method accepts one parameter record which is the LogRecord to be published.Return value: This method returns nothingProgram 7: Method log(LogRecord record)// Java program to demonstrate// Logger.log(LogRecord record) import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // create logRecords LogRecord record1 = new LogRecord(Level.INFO, "Msg 1"); LogRecord record2 = new LogRecord(Level.INFO, "Msg 2"); // log messages using // log(LogRecord record) logger.log(record1); logger.log(record2); }}Output: Syntax: public void log(LogRecord record) Parameters: This method accepts one parameter record which is the LogRecord to be published. Return value: This method returns nothing Program 7: Method log(LogRecord record) // Java program to demonstrate// Logger.log(LogRecord record) import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // create logRecords LogRecord record1 = new LogRecord(Level.INFO, "Msg 1"); LogRecord record2 = new LogRecord(Level.INFO, "Msg 2"); // log messages using // log(LogRecord record) logger.log(record1); logger.log(record2); }} Output: References: https://docs.oracle.com/javase/10/docs/api/java/util/Logger.html# Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jun, 2019" }, { "code": null, "e": 387, "s": 28, "text": "The log() method of Logger is used to Log a message. If the logger is currently enabled for the given message level which is passed as parameter then a corresponding LogRecord is created and forwarded to all the registered Output Handler objects. But in logger class, there are seven different log() method depending upon the parameters passed to the method." }, { "code": null, "e": 8463, "s": 387, "text": "log(Level level, String msg): This method is used to Log a message, with no arguments.only message will be written in logger Output.Syntax:public void log(Level level, String msg)\nParameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msg which is the string message (or a key in the message catalog).Return value: This method returns nothingProgram 1: Method log(Level level, String msg)// Java program to demonstrate// Logger.log(Level level, String msg) method import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using log(Level level, String msg) logger.log(Level.INFO, \"This is message 1\"); logger.log(Level.WARNING, \"This is message 2\"); }}Outputlog(Level level, String msg, Object param1): This method is used to Log a message, with one object parameter.Syntax:public void log(Level level, String msg, Object param1)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is parameter to the messageReturn value: This method returns nothingProgram 2: Method log(Level level, String msg, Object param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object param1) logger.log(Level.INFO, \"logging: {0} \", \"message1\"); logger.log(Level.SEVERE, \"logging: {0} \", \"message2\"); }}Output:log(Level level, String msg, Object[] params): This method is used to Log a message, with an array of object arguments.Syntax:public void log(Level level, String msg, Object[] params)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is array of parameters to the messageReturn value: This method returns nothingProgram 3: Method log(Level level, String msg, Object[] param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object[] param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object[] param1) logger.log(Level.INFO, \"logging: {0} {1}\", new Object[] { \"parameter1\", \"parameter2\" }); logger.log(Level.WARNING, \"logging: {0} {1} {2}\", new Object[] { \"p1\", \"p2\", \"p3\" }); }}Output:log(Level level, String msg, Throwable thrown): This method is used to Log a message, with associated Throwable information.Syntax:public void log(Level level, String msg, Throwable thrown)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and thrown which is Throwable associated with log message.Return value: This method returns nothingProgram 4: Method log(Level level, String msg, Throwable thrown)// Java program to demonstrate// Logger.log(Level level, String msg, Throwable thrown) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Throwable thrown) logger.log(Level.SEVERE, \"logging:\", new RuntimeException(\"Error\")); logger.log(Level.WARNING, \"logging: \", new Exception(\"Exception\")); }}Output:log(Level level, Throwable thrown, Supplier msgSupplier): This method is used to Log a lazily constructed message, with associated Throwable information.The message and the given Throwable are then stored in a LogRecord which is forwarded to all registered Output handlers.Syntax:public void log(Level level, Throwable thrown, Supplier msgSupplier)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, thrown which is the Throwable associated with log message and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 5: Method log(Level level, Throwable thrown, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, Throwable thrown, Supplier<String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger logs\"); // log messages using // log(Level level, Throwable thrown, Supplier<String> msgSupplier) logger.log(Level.SEVERE, new RuntimeException(\"Error\"), StrSupplier); }}Output:log(Level level, Supplier msgSupplier): This method is used to Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.Syntax:public void log(Level level, Supplier msgSupplier)\nParameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 6: Method log(Level level, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, <String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger messages\"); // log messages using // log(Level level, Supplier<String> msgSupplier) logger.log(Level.SEVERE, StrSupplier); }}Output:log(LogRecord record): This method is used to Log a LogRecord.Using logRecord we will log the info to logger Outputs.Syntax:public void log(LogRecord record)\nParameters: This method accepts one parameter record which is the LogRecord to be published.Return value: This method returns nothingProgram 7: Method log(LogRecord record)// Java program to demonstrate// Logger.log(LogRecord record) import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // create logRecords LogRecord record1 = new LogRecord(Level.INFO, \"Msg 1\"); LogRecord record2 = new LogRecord(Level.INFO, \"Msg 2\"); // log messages using // log(LogRecord record) logger.log(record1); logger.log(record2); }}Output:" }, { "code": null, "e": 9420, "s": 8463, "text": "log(Level level, String msg): This method is used to Log a message, with no arguments.only message will be written in logger Output.Syntax:public void log(Level level, String msg)\nParameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msg which is the string message (or a key in the message catalog).Return value: This method returns nothingProgram 1: Method log(Level level, String msg)// Java program to demonstrate// Logger.log(Level level, String msg) method import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using log(Level level, String msg) logger.log(Level.INFO, \"This is message 1\"); logger.log(Level.WARNING, \"This is message 2\"); }}Output" }, { "code": null, "e": 9462, "s": 9420, "text": "public void log(Level level, String msg)\n" }, { "code": null, "e": 9646, "s": 9462, "text": "Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msg which is the string message (or a key in the message catalog)." }, { "code": null, "e": 9688, "s": 9646, "text": "Return value: This method returns nothing" }, { "code": null, "e": 9735, "s": 9688, "text": "Program 1: Method log(Level level, String msg)" }, { "code": "// Java program to demonstrate// Logger.log(Level level, String msg) method import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using log(Level level, String msg) logger.log(Level.INFO, \"This is message 1\"); logger.log(Level.WARNING, \"This is message 2\"); }}", "e": 10236, "s": 9735, "text": null }, { "code": null, "e": 10243, "s": 10236, "text": "Output" }, { "code": null, "e": 11298, "s": 10243, "text": "log(Level level, String msg, Object param1): This method is used to Log a message, with one object parameter.Syntax:public void log(Level level, String msg, Object param1)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is parameter to the messageReturn value: This method returns nothingProgram 2: Method log(Level level, String msg, Object param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object param1) logger.log(Level.INFO, \"logging: {0} \", \"message1\"); logger.log(Level.SEVERE, \"logging: {0} \", \"message2\"); }}Output:" }, { "code": null, "e": 11306, "s": 11298, "text": "Syntax:" }, { "code": null, "e": 11363, "s": 11306, "text": "public void log(Level level, String msg, Object param1)\n" }, { "code": null, "e": 11590, "s": 11363, "text": "Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is parameter to the message" }, { "code": null, "e": 11632, "s": 11590, "text": "Return value: This method returns nothing" }, { "code": null, "e": 11694, "s": 11632, "text": "Program 2: Method log(Level level, String msg, Object param1)" }, { "code": "// Java program to demonstrate// Logger.log(Level level, String msg, Object param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object param1) logger.log(Level.INFO, \"logging: {0} \", \"message1\"); logger.log(Level.SEVERE, \"logging: {0} \", \"message2\"); }}", "e": 12242, "s": 11694, "text": null }, { "code": null, "e": 12250, "s": 12242, "text": "Output:" }, { "code": null, "e": 13436, "s": 12250, "text": "log(Level level, String msg, Object[] params): This method is used to Log a message, with an array of object arguments.Syntax:public void log(Level level, String msg, Object[] params)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is array of parameters to the messageReturn value: This method returns nothingProgram 3: Method log(Level level, String msg, Object[] param1)// Java program to demonstrate// Logger.log(Level level, String msg, Object[] param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object[] param1) logger.log(Level.INFO, \"logging: {0} {1}\", new Object[] { \"parameter1\", \"parameter2\" }); logger.log(Level.WARNING, \"logging: {0} {1} {2}\", new Object[] { \"p1\", \"p2\", \"p3\" }); }}Output:" }, { "code": null, "e": 13444, "s": 13436, "text": "Syntax:" }, { "code": null, "e": 13503, "s": 13444, "text": "public void log(Level level, String msg, Object[] params)\n" }, { "code": null, "e": 13740, "s": 13503, "text": "Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and param1 which is array of parameters to the message" }, { "code": null, "e": 13782, "s": 13740, "text": "Return value: This method returns nothing" }, { "code": null, "e": 13846, "s": 13782, "text": "Program 3: Method log(Level level, String msg, Object[] param1)" }, { "code": "// Java program to demonstrate// Logger.log(Level level, String msg, Object[] param1) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Object[] param1) logger.log(Level.INFO, \"logging: {0} {1}\", new Object[] { \"parameter1\", \"parameter2\" }); logger.log(Level.WARNING, \"logging: {0} {1} {2}\", new Object[] { \"p1\", \"p2\", \"p3\" }); }}", "e": 14501, "s": 13846, "text": null }, { "code": null, "e": 14509, "s": 14501, "text": "Output:" }, { "code": null, "e": 15670, "s": 14509, "text": "log(Level level, String msg, Throwable thrown): This method is used to Log a message, with associated Throwable information.Syntax:public void log(Level level, String msg, Throwable thrown)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and thrown which is Throwable associated with log message.Return value: This method returns nothingProgram 4: Method log(Level level, String msg, Throwable thrown)// Java program to demonstrate// Logger.log(Level level, String msg, Throwable thrown) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Throwable thrown) logger.log(Level.SEVERE, \"logging:\", new RuntimeException(\"Error\")); logger.log(Level.WARNING, \"logging: \", new Exception(\"Exception\")); }}Output:" }, { "code": null, "e": 15678, "s": 15670, "text": "Syntax:" }, { "code": null, "e": 15738, "s": 15678, "text": "public void log(Level level, String msg, Throwable thrown)\n" }, { "code": null, "e": 15979, "s": 15738, "text": "Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, msg which is the string message (or a key in the message catalog) and thrown which is Throwable associated with log message." }, { "code": null, "e": 16021, "s": 15979, "text": "Return value: This method returns nothing" }, { "code": null, "e": 16086, "s": 16021, "text": "Program 4: Method log(Level level, String msg, Throwable thrown)" }, { "code": "// Java program to demonstrate// Logger.log(Level level, String msg, Throwable thrown) import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // log messages using // log(Level level, String msg, Throwable thrown) logger.log(Level.SEVERE, \"logging:\", new RuntimeException(\"Error\")); logger.log(Level.WARNING, \"logging: \", new Exception(\"Exception\")); }}", "e": 16705, "s": 16086, "text": null }, { "code": null, "e": 16713, "s": 16705, "text": "Output:" }, { "code": null, "e": 18190, "s": 16713, "text": "log(Level level, Throwable thrown, Supplier msgSupplier): This method is used to Log a lazily constructed message, with associated Throwable information.The message and the given Throwable are then stored in a LogRecord which is forwarded to all registered Output handlers.Syntax:public void log(Level level, Throwable thrown, Supplier msgSupplier)\nParameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, thrown which is the Throwable associated with log message and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 5: Method log(Level level, Throwable thrown, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, Throwable thrown, Supplier<String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger logs\"); // log messages using // log(Level level, Throwable thrown, Supplier<String> msgSupplier) logger.log(Level.SEVERE, new RuntimeException(\"Error\"), StrSupplier); }}Output:" }, { "code": null, "e": 18198, "s": 18190, "text": "Syntax:" }, { "code": null, "e": 18268, "s": 18198, "text": "public void log(Level level, Throwable thrown, Supplier msgSupplier)\n" }, { "code": null, "e": 18532, "s": 18268, "text": "Parameters: This method accepts three parameters level which is one of the message level identifiers, e.g., SEVERE, thrown which is the Throwable associated with log message and msgSupplier which is a function, which when called, produces the desired log message." }, { "code": null, "e": 18574, "s": 18532, "text": "Return value: This method returns nothing" }, { "code": null, "e": 18649, "s": 18574, "text": "Program 5: Method log(Level level, Throwable thrown, Supplier msgSupplier)" }, { "code": "// Java program to demonstrate// Logger.log(Level level, Throwable thrown, Supplier<String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger logs\"); // log messages using // log(Level level, Throwable thrown, Supplier<String> msgSupplier) logger.log(Level.SEVERE, new RuntimeException(\"Error\"), StrSupplier); }}", "e": 19392, "s": 18649, "text": null }, { "code": null, "e": 19400, "s": 19392, "text": "Output:" }, { "code": null, "e": 20598, "s": 19400, "text": "log(Level level, Supplier msgSupplier): This method is used to Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.Syntax:public void log(Level level, Supplier msgSupplier)\nParameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msgSupplier which is a function, which when called, produces the desired log message.Return value: This method returns nothingProgram 6: Method log(Level level, Supplier msgSupplier)// Java program to demonstrate// Logger.log(Level level, <String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger messages\"); // log messages using // log(Level level, Supplier<String> msgSupplier) logger.log(Level.SEVERE, StrSupplier); }}Output:" }, { "code": null, "e": 20606, "s": 20598, "text": "Syntax:" }, { "code": null, "e": 20658, "s": 20606, "text": "public void log(Level level, Supplier msgSupplier)\n" }, { "code": null, "e": 20861, "s": 20658, "text": "Parameters: This method accepts two parameters level which is one of the message level identifiers, e.g., SEVERE and msgSupplier which is a function, which when called, produces the desired log message." }, { "code": null, "e": 20903, "s": 20861, "text": "Return value: This method returns nothing" }, { "code": null, "e": 20960, "s": 20903, "text": "Program 6: Method log(Level level, Supplier msgSupplier)" }, { "code": "// Java program to demonstrate// Logger.log(Level level, <String> msgSupplier) import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a supplier<String> method Supplier<String> StrSupplier = () -> new String(\"Logger messages\"); // log messages using // log(Level level, Supplier<String> msgSupplier) logger.log(Level.SEVERE, StrSupplier); }}", "e": 21614, "s": 20960, "text": null }, { "code": null, "e": 21622, "s": 21614, "text": "Output:" }, { "code": null, "e": 22670, "s": 21622, "text": "log(LogRecord record): This method is used to Log a LogRecord.Using logRecord we will log the info to logger Outputs.Syntax:public void log(LogRecord record)\nParameters: This method accepts one parameter record which is the LogRecord to be published.Return value: This method returns nothingProgram 7: Method log(LogRecord record)// Java program to demonstrate// Logger.log(LogRecord record) import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // create logRecords LogRecord record1 = new LogRecord(Level.INFO, \"Msg 1\"); LogRecord record2 = new LogRecord(Level.INFO, \"Msg 2\"); // log messages using // log(LogRecord record) logger.log(record1); logger.log(record2); }}Output:" }, { "code": null, "e": 22678, "s": 22670, "text": "Syntax:" }, { "code": null, "e": 22713, "s": 22678, "text": "public void log(LogRecord record)\n" }, { "code": null, "e": 22806, "s": 22713, "text": "Parameters: This method accepts one parameter record which is the LogRecord to be published." }, { "code": null, "e": 22848, "s": 22806, "text": "Return value: This method returns nothing" }, { "code": null, "e": 22888, "s": 22848, "text": "Program 7: Method log(LogRecord record)" }, { "code": "// Java program to demonstrate// Logger.log(LogRecord record) import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger; public class GFG { public static void main(String[] args) { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // create logRecords LogRecord record1 = new LogRecord(Level.INFO, \"Msg 1\"); LogRecord record2 = new LogRecord(Level.INFO, \"Msg 2\"); // log messages using // log(LogRecord record) logger.log(record1); logger.log(record2); }}", "e": 23599, "s": 22888, "text": null }, { "code": null, "e": 23607, "s": 23599, "text": "Output:" }, { "code": null, "e": 23685, "s": 23607, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Logger.html#" }, { "code": null, "e": 23705, "s": 23685, "text": "Java - util package" }, { "code": null, "e": 23720, "s": 23705, "text": "Java-Functions" }, { "code": null, "e": 23732, "s": 23720, "text": "Java-Logger" }, { "code": null, "e": 23737, "s": 23732, "text": "Java" }, { "code": null, "e": 23742, "s": 23737, "text": "Java" }, { "code": null, "e": 23840, "s": 23742, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23891, "s": 23840, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 23922, "s": 23891, "text": "How to iterate any Map in Java" }, { "code": null, "e": 23941, "s": 23922, "text": "Interfaces in Java" }, { "code": null, "e": 23971, "s": 23941, "text": "HashMap in Java with Examples" }, { "code": null, "e": 23989, "s": 23971, "text": "ArrayList in Java" }, { "code": null, "e": 24004, "s": 23989, "text": "Stream In Java" }, { "code": null, "e": 24024, "s": 24004, "text": "Collections in Java" }, { "code": null, "e": 24056, "s": 24024, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 24080, "s": 24056, "text": "Singleton Class in Java" } ]
Node.js Readable Stream close Event
12 Oct, 2021 The ‘close’ Event in a Readable Stream is emitted when the stream and any of its hidden resources are being closed This event implies that no further events can be emitted, and no further computations can take place. Moreover, if a Readable stream is created with the emitClose option then it can always emit ‘close’ event. Syntax: Event: 'close ' Below examples illustrate the use of close event in Node.js: Example 1: // Node.js program to demonstrate the // readable close event // Including fs moduleconst fs = require('fs'); // Constructing readable streamconst readable = fs.createReadStream("input.txt"); // Calling close methodreadable.close(); // Handling close eventreadable.on("close", () => { console.log("Stream ended");}); console.log("Done..."); Output: Done... Stream ended Example 2: // Node.js program to demonstrate the // readable close event // Including fs moduleconst fs = require('fs'); // Constructing readable streamconst readable = fs.createReadStream("input.txt"); // Handling close eventreadable.on("close", () => { console.log("Stream ended");}); console.log("Done..."); Output: Done... Here, close method is not called so close event is not emitted. Reference: https://nodejs.org/api/stream.html#stream_event_close_1. Node.js-Stream-module 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": "\n12 Oct, 2021" }, { "code": null, "e": 352, "s": 28, "text": "The ‘close’ Event in a Readable Stream is emitted when the stream and any of its hidden resources are being closed This event implies that no further events can be emitted, and no further computations can take place. Moreover, if a Readable stream is created with the emitClose option then it can always emit ‘close’ event." }, { "code": null, "e": 360, "s": 352, "text": "Syntax:" }, { "code": null, "e": 376, "s": 360, "text": "Event: 'close '" }, { "code": null, "e": 437, "s": 376, "text": "Below examples illustrate the use of close event in Node.js:" }, { "code": null, "e": 448, "s": 437, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // readable close event // Including fs moduleconst fs = require('fs'); // Constructing readable streamconst readable = fs.createReadStream(\"input.txt\"); // Calling close methodreadable.close(); // Handling close eventreadable.on(\"close\", () => { console.log(\"Stream ended\");}); console.log(\"Done...\");", "e": 801, "s": 448, "text": null }, { "code": null, "e": 809, "s": 801, "text": "Output:" }, { "code": null, "e": 831, "s": 809, "text": "Done...\nStream ended\n" }, { "code": null, "e": 842, "s": 831, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // readable close event // Including fs moduleconst fs = require('fs'); // Constructing readable streamconst readable = fs.createReadStream(\"input.txt\"); // Handling close eventreadable.on(\"close\", () => { console.log(\"Stream ended\");}); console.log(\"Done...\");", "e": 1153, "s": 842, "text": null }, { "code": null, "e": 1161, "s": 1153, "text": "Output:" }, { "code": null, "e": 1170, "s": 1161, "text": "Done...\n" }, { "code": null, "e": 1234, "s": 1170, "text": "Here, close method is not called so close event is not emitted." }, { "code": null, "e": 1302, "s": 1234, "text": "Reference: https://nodejs.org/api/stream.html#stream_event_close_1." }, { "code": null, "e": 1324, "s": 1302, "text": "Node.js-Stream-module" }, { "code": null, "e": 1332, "s": 1324, "text": "Node.js" }, { "code": null, "e": 1349, "s": 1332, "text": "Web Technologies" } ]
Python | Pandas Series.str.lower(), upper() and title()
17 Sep, 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. Python has some inbuilt methods to convert a string into lower, upper or Camel case. But these methods don’t work on list and other multi string objects. Pandas is a library for Data analysis which provides separate methods to convert all values in a series to respective text cases. Since, lower, upper and title are Python keywords too, .str has to be prefixed before calling these function on a Pandas series.Syntax: Series.str.lower() Series.str.upper() Series.str.title() Parameters: Doesn’t take any parameter Return Type: Series with new values To download the CSV file used, Click Here. In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below.Example #1: Using .lower() on a Series In this example, .lower() function is being called by the First Name column and hence, all the values in the First name column will be converted in to lower case. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # converting and overwriting values in columndata["First Name"]= data["First Name"].str.lower() # displaydata Output:As shown in the output image of data frame, all values in the First name column have been converted into lower case. Example #2: Using .upper() on a Series In this example, .upper() function is being called by the Team column and hence all the values in the Team column will be converted into upper case. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # converting and overwriting values in columndata["Team"]= data["Team"].str.upper() # displaydata Output:As shown in the output image of data frame, all values in the Team column have been converted into upper case. Example #3: Using .title() on a Series In this example, .title() function is being called by the Team column and hence, all the values in the into column will be converted in to Camel case. Since the values in the Team column were already in camel case, it has been converted to Upper case before and then again to camel case in order to verify the functionality of .title() method. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # converting and overwriting values in columndata["Team"]= data["Team"].str.upper().str.title() # displaydata Output:As shown in the output image of data frame, all values in the Team column have been converted into Camel case. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 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": 662, "s": 242, "text": "Python has some inbuilt methods to convert a string into lower, upper or Camel case. But these methods don’t work on list and other multi string objects. Pandas is a library for Data analysis which provides separate methods to convert all values in a series to respective text cases. Since, lower, upper and title are Python keywords too, .str has to be prefixed before calling these function on a Pandas series.Syntax:" }, { "code": null, "e": 719, "s": 662, "text": "Series.str.lower()\nSeries.str.upper()\nSeries.str.title()" }, { "code": null, "e": 758, "s": 719, "text": "Parameters: Doesn’t take any parameter" }, { "code": null, "e": 794, "s": 758, "text": "Return Type: Series with new values" }, { "code": null, "e": 837, "s": 794, "text": "To download the CSV file used, Click Here." }, { "code": null, "e": 1020, "s": 837, "text": "In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below.Example #1: Using .lower() on a Series" }, { "code": null, "e": 1183, "s": 1020, "text": "In this example, .lower() function is being called by the First Name column and hence, all the values in the First name column will be converted in to lower case." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # converting and overwriting values in columndata[\"First Name\"]= data[\"First Name\"].str.lower() # displaydata", "e": 1411, "s": 1183, "text": null }, { "code": null, "e": 1535, "s": 1411, "text": "Output:As shown in the output image of data frame, all values in the First name column have been converted into lower case." }, { "code": null, "e": 1576, "s": 1537, "text": "Example #2: Using .upper() on a Series" }, { "code": null, "e": 1725, "s": 1576, "text": "In this example, .upper() function is being called by the Team column and hence all the values in the Team column will be converted into upper case." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # converting and overwriting values in columndata[\"Team\"]= data[\"Team\"].str.upper() # displaydata", "e": 1941, "s": 1725, "text": null }, { "code": null, "e": 2059, "s": 1941, "text": "Output:As shown in the output image of data frame, all values in the Team column have been converted into upper case." }, { "code": null, "e": 2100, "s": 2061, "text": "Example #3: Using .title() on a Series" }, { "code": null, "e": 2444, "s": 2100, "text": "In this example, .title() function is being called by the Team column and hence, all the values in the into column will be converted in to Camel case. Since the values in the Team column were already in camel case, it has been converted to Upper case before and then again to camel case in order to verify the functionality of .title() method." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # converting and overwriting values in columndata[\"Team\"]= data[\"Team\"].str.upper().str.title() # displaydata", "e": 2672, "s": 2444, "text": null }, { "code": null, "e": 2790, "s": 2672, "text": "Output:As shown in the output image of data frame, all values in the Team column have been converted into Camel case." }, { "code": null, "e": 2811, "s": 2790, "text": "Python pandas-series" }, { "code": null, "e": 2840, "s": 2811, "text": "Python pandas-series-methods" }, { "code": null, "e": 2854, "s": 2840, "text": "Python-pandas" }, { "code": null, "e": 2861, "s": 2854, "text": "Python" } ]
PHP Tutorials - GeeksforGeeks
23 Dec, 2021 The term PHP is an acronym for Hypertext Preprocessor. It is a server-side scripting language that is used for web development. It can be easily embedded with HTML files. HTML codes can also be written in a PHP file. The PHP codes are executed on the server-side whereas HTML codes are directly executed on the browser. Example: Simple program to print “Hello world!” message on the screen. PHP Output: Hello world! It is one of the widely used open-source general-purpose scripting language that is used for backend Development. Apart from this, let’s see why we should learn it. Easy to Learn: It is easier to learn for anyone who has come across to any programming language for the first time. Free of Cost: Since it is an open-source language, therefore developers are allowed to use its components and all methods for free. Flexible: Since It is a dynamically typed language, therefore there are no hard rules on how to build features using it. Supports nearly all databases: It supports all the widely used databases, including MySQL, ODBC, SQLite etc. Secured: It has multiple security levels provides us a secure platform for developing websites as it has multiple security levels. Huge Community Support: It is loved and used by a huge number of developers. The developers share their knowledge with other people of the community that want to know about it. Introduction Advantages and Disadvantages Connect PHP to MySQL Form Processing Build a Grocery Store Web App using PHP with MySQL How to Insert Form Data into Database ? How to Upload Image into Database and Display it ? Create a Signup form using PHP and MySQL Database Generating a QR code Dynamically Array Functions Complete Reference String Functions Complete Reference Math Functions Complete Reference GMP Functions Complete Reference Calendar Functions Complete Reference IntlChar Functions Complete Reference Imagick Functions Complete Reference Gmagick Functions Complete Reference ImagickDraw Functions Complete Reference Image Processing and GD Functions Complete Reference SPL Data structures Complete Reference DS\Sequence Functions Complete Reference DS\Vector Functions Complete Reference Ds\Deque Functions Complete Reference Ds\Map Functions Complete Reference Ds\Set Functions Complete Reference Ds\Stack Functions Complete Reference Ds\Queue Functions Complete Reference Ds\PriorityQueue Functions Complete Reference Filesystem Functions Complete Reference Set-1 Set-2 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Learn C++ Programming Step by Step - A 20 Day Curriculum! Must Do Coding Questions for Product Based Companies GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Floyd’s Cycle Finding Algorithm Samsung R&D Interview Experience Split given String into substrings of size K by filling elements Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now! Spring Boot - Annotations Deutsche Bank Interview Experience (2021-22 )
[ { "code": null, "e": 24903, "s": 24875, "text": "\n23 Dec, 2021" }, { "code": null, "e": 25223, "s": 24903, "text": "The term PHP is an acronym for Hypertext Preprocessor. It is a server-side scripting language that is used for web development. It can be easily embedded with HTML files. HTML codes can also be written in a PHP file. The PHP codes are executed on the server-side whereas HTML codes are directly executed on the browser." }, { "code": null, "e": 25294, "s": 25223, "text": "Example: Simple program to print “Hello world!” message on the screen." }, { "code": null, "e": 25298, "s": 25294, "text": "PHP" }, { "code": null, "e": 25306, "s": 25298, "text": "Output:" }, { "code": null, "e": 25319, "s": 25306, "text": "Hello world!" }, { "code": null, "e": 25486, "s": 25321, "text": "It is one of the widely used open-source general-purpose scripting language that is used for backend Development. Apart from this, let’s see why we should learn it." }, { "code": null, "e": 25602, "s": 25486, "text": "Easy to Learn: It is easier to learn for anyone who has come across to any programming language for the first time." }, { "code": null, "e": 25734, "s": 25602, "text": "Free of Cost: Since it is an open-source language, therefore developers are allowed to use its components and all methods for free." }, { "code": null, "e": 25855, "s": 25734, "text": "Flexible: Since It is a dynamically typed language, therefore there are no hard rules on how to build features using it." }, { "code": null, "e": 25964, "s": 25855, "text": "Supports nearly all databases: It supports all the widely used databases, including MySQL, ODBC, SQLite etc." }, { "code": null, "e": 26095, "s": 25964, "text": "Secured: It has multiple security levels provides us a secure platform for developing websites as it has multiple security levels." }, { "code": null, "e": 26272, "s": 26095, "text": "Huge Community Support: It is loved and used by a huge number of developers. The developers share their knowledge with other people of the community that want to know about it." }, { "code": null, "e": 26285, "s": 26272, "text": "Introduction" }, { "code": null, "e": 26314, "s": 26285, "text": "Advantages and Disadvantages" }, { "code": null, "e": 26335, "s": 26314, "text": "Connect PHP to MySQL" }, { "code": null, "e": 26351, "s": 26335, "text": "Form Processing" }, { "code": null, "e": 26402, "s": 26351, "text": "Build a Grocery Store Web App using PHP with MySQL" }, { "code": null, "e": 26442, "s": 26402, "text": "How to Insert Form Data into Database ?" }, { "code": null, "e": 26493, "s": 26442, "text": "How to Upload Image into Database and Display it ?" }, { "code": null, "e": 26543, "s": 26493, "text": "Create a Signup form using PHP and MySQL Database" }, { "code": null, "e": 26576, "s": 26543, "text": "Generating a QR code Dynamically" }, { "code": null, "e": 26611, "s": 26576, "text": "Array Functions Complete Reference" }, { "code": null, "e": 26647, "s": 26611, "text": "String Functions Complete Reference" }, { "code": null, "e": 26681, "s": 26647, "text": "Math Functions Complete Reference" }, { "code": null, "e": 26714, "s": 26681, "text": "GMP Functions Complete Reference" }, { "code": null, "e": 26752, "s": 26714, "text": "Calendar Functions Complete Reference" }, { "code": null, "e": 26790, "s": 26752, "text": "IntlChar Functions Complete Reference" }, { "code": null, "e": 26827, "s": 26790, "text": "Imagick Functions Complete Reference" }, { "code": null, "e": 26864, "s": 26827, "text": "Gmagick Functions Complete Reference" }, { "code": null, "e": 26905, "s": 26864, "text": "ImagickDraw Functions Complete Reference" }, { "code": null, "e": 26958, "s": 26905, "text": "Image Processing and GD Functions Complete Reference" }, { "code": null, "e": 26997, "s": 26958, "text": "SPL Data structures Complete Reference" }, { "code": null, "e": 27038, "s": 26997, "text": "DS\\Sequence Functions Complete Reference" }, { "code": null, "e": 27077, "s": 27038, "text": "DS\\Vector Functions Complete Reference" }, { "code": null, "e": 27115, "s": 27077, "text": "Ds\\Deque Functions Complete Reference" }, { "code": null, "e": 27151, "s": 27115, "text": "Ds\\Map Functions Complete Reference" }, { "code": null, "e": 27187, "s": 27151, "text": "Ds\\Set Functions Complete Reference" }, { "code": null, "e": 27225, "s": 27187, "text": "Ds\\Stack Functions Complete Reference" }, { "code": null, "e": 27263, "s": 27225, "text": "Ds\\Queue Functions Complete Reference" }, { "code": null, "e": 27309, "s": 27263, "text": "Ds\\PriorityQueue Functions Complete Reference" }, { "code": null, "e": 27349, "s": 27309, "text": "Filesystem Functions Complete Reference" }, { "code": null, "e": 27355, "s": 27349, "text": "Set-1" }, { "code": null, "e": 27361, "s": 27355, "text": "Set-2" }, { "code": null, "e": 27486, "s": 27361, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27584, "s": 27486, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 27658, "s": 27584, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 27716, "s": 27658, "text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!" }, { "code": null, "e": 27769, "s": 27716, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 27835, "s": 27769, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 27867, "s": 27835, "text": "Floyd’s Cycle Finding Algorithm" }, { "code": null, "e": 27900, "s": 27867, "text": "Samsung R&D Interview Experience" }, { "code": null, "e": 27965, "s": 27900, "text": "Split given String into substrings of size K by filling elements" }, { "code": null, "e": 28035, "s": 27965, "text": "Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!" }, { "code": null, "e": 28061, "s": 28035, "text": "Spring Boot - Annotations" } ]
How to make a Python auto clicker?
19 Jan, 2021 In this article, we will see how to create an auto-clicker using Python. The code will take input from the keyboard when the user clicks on the start key and terminates auto clicker when the user clicks on exit key, the auto clicker starts clicking wherever the pointer is placed on the screen. We are going to use the pynput module here. Auto-Clicker is a script where you can auto control mouse and keyboard as many numbers of times as you want. It is controlled using user-defined keys. It works on various platforms like Windows, Mac and Linux. Auto clicker is present in pywin32 module. In this project, we will use a cross-platform module pynput to control the mouse and monitor the keyboard at the same time to create simple auto-clicker. To check for mouse events we will install pynput module (used to control the mouse) for this execute, pip install pynput in cmd. Note: If you’re stuck on how to set up python-pip package on your system then click here Installation of pynput module Verify whether the pynput module has been successfully installed into your working environment for this, open IDLE on the system that is cmd or Python Shell. Execute the command import pynput, after executing this the output should give zero errors which means your module is successfully installed. Verifying module installation Let’s now proceed with the code that is required to build an Auto-clicker using Python. Follow the below steps to create an auto-clicker: Step 1: Import time and threading then import Button and Controller from pynput.mouse module. Import Listener and KeyCode from pynput.keyboard. Python3 # importing time and threadingimport timeimport threadingfrom pynput.mouse import Button, Controller # pynput.keyboard is used to watch events of# keyboard for start and stop of auto-clickerfrom pynput.keyboard import Listener, KeyCode Step 2: Create four variables as mentioned below, delay: Delay between each click (in seconds) button: Button is used to click in whatever direction you want to. Button.left | Button.middle | Button.right start_stop_key: The key used for start and stop of the click while you run the program for executing the auto clicker. It should be from a key class or set using KeyCode. exit_key: The key used to terminate the auto clicker that is being executed. This should be from the key class or set using KeyCode. Python3 # four variables are created to# control the auto-clickerdelay = 0.001button = Button.rightstart_stop_key = KeyCode(char='a')stop_key = KeyCode(char='b') Step 3: Create a class extending threading.Thread. Pass delay and button to the class that have two flags to check if the program is executed or not. Python3 # threading.Thread is used # to control clicksclass ClickMouse(threading.Thread): # delay and button is passed in class # to check execution of auto-clicker def __init__(self, delay, button): super(ClickMouse, self).__init__() self.delay = delay self.button = button self.running = False self.program_running = True Step 4: Add methods to control the threads externally. Python3 def start_clicking(self): self.running = True def stop_clicking(self): self.running = False def exit(self): self.stop_clicking() self.program_running = False Step 5: A method is created when the thread starts, the program_running runs on loop until the value comes out to be true and also create another loop inside the existing loop where it checks if running is set to true or not. In case, we are inside both loops, it will click on the set button and sleep for the set delay. Python3 # method to check and run loop until # it is true another loop will check # if it is set to true or not, # for mouse click it set to button # and delay.def run(self): while self.program_running: while self.running: mouse.click(self.button) time.sleep(self.delay) time.sleep(0.1) Step 6: Creating an instance for the mouse controller, then create ClickMouse thread. Start the instance to move into the loop inside the run method. Python3 # instance of mouse controller is createdmouse = Controller()click_thread = ClickMouse(delay, button)click_thread.start() Step 7: Create a method on_press which takes a key as an argument and sets up a keyboard listener. The start_stop_key matches with a start key (a) when it is executed. Then the click is to be terminated when running flag is set to True in the thread. Exit method is called in the method if the exit key (b) is executed and stop the listener. Python3 # on_press method takes# key as argument def on_press(key): # start_stop_key will stop clicking # if running flag is set to true if key == start_stop_key: if click_thread.running: click_thread.stop_clicking() else: click_thread.start_clicking() # here exit method is called and when # key is pressed it terminates auto clicker elif key == stop_key: click_thread.exit() listener.stop() with Listener(on_press=on_press) as listener: listener.join() After the code is run we can see in the output as shown below, it shows the number of clicks the auto-clicker has made after the code is implemented. It is compatible with Windows, Mac and Linux. Auto-Clicker is helpful software for the systems as it let’s save a reasonable amount of time that is spent on repeated amount of clicks. Below is the complete program: Python3 # importing time and threadingimport timeimport threadingfrom pynput.mouse import Button, Controller # pynput.keyboard is used to watch events of # keyboard for start and stop of auto-clickerfrom pynput.keyboard import Listener, KeyCode # four variables are created to # control the auto-clickerdelay = 0.001button = Button.rightstart_stop_key = KeyCode(char='a')stop_key = KeyCode(char='b') # threading.Thread is used # to control clicksclass ClickMouse(threading.Thread): # delay and button is passed in class # to check execution of auto-clicker def __init__(self, delay, button): super(ClickMouse, self).__init__() self.delay = delay self.button = button self.running = False self.program_running = True def start_clicking(self): self.running = True def stop_clicking(self): self.running = False def exit(self): self.stop_clicking() self.program_running = False # method to check and run loop until # it is true another loop will check # if it is set to true or not, # for mouse click it set to button # and delay. def run(self): while self.program_running: while self.running: mouse.click(self.button) time.sleep(self.delay) time.sleep(0.1) # instance of mouse controller is createdmouse = Controller()click_thread = ClickMouse(delay, button)click_thread.start() # on_press method takes # key as argumentdef on_press(key): # start_stop_key will stop clicking # if running flag is set to true if key == start_stop_key: if click_thread.running: click_thread.stop_clicking() else: click_thread.start_clicking() # here exit method is called and when # key is pressed it terminates auto clicker elif key == stop_key: click_thread.exit() listener.stop() with Listener(on_press=on_press) as listener: listener.join() Now let’s execute the python program we’ve written and then press the start (a) and stop (a) keys in order to initiate the auto clicker. Output: Picked Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON 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": 52, "s": 24, "text": "\n19 Jan, 2021" }, { "code": null, "e": 392, "s": 52, "text": "In this article, we will see how to create an auto-clicker using Python. The code will take input from the keyboard when the user clicks on the start key and terminates auto clicker when the user clicks on exit key, the auto clicker starts clicking wherever the pointer is placed on the screen. We are going to use the pynput module here. " }, { "code": null, "e": 645, "s": 392, "text": "Auto-Clicker is a script where you can auto control mouse and keyboard as many numbers of times as you want. It is controlled using user-defined keys. It works on various platforms like Windows, Mac and Linux. Auto clicker is present in pywin32 module." }, { "code": null, "e": 929, "s": 645, "text": "In this project, we will use a cross-platform module pynput to control the mouse and monitor the keyboard at the same time to create simple auto-clicker. To check for mouse events we will install pynput module (used to control the mouse) for this execute, pip install pynput in cmd. " }, { "code": null, "e": 1018, "s": 929, "text": "Note: If you’re stuck on how to set up python-pip package on your system then click here" }, { "code": null, "e": 1048, "s": 1018, "text": "Installation of pynput module" }, { "code": null, "e": 1349, "s": 1048, "text": "Verify whether the pynput module has been successfully installed into your working environment for this, open IDLE on the system that is cmd or Python Shell. Execute the command import pynput, after executing this the output should give zero errors which means your module is successfully installed. " }, { "code": null, "e": 1379, "s": 1349, "text": "Verifying module installation" }, { "code": null, "e": 1517, "s": 1379, "text": "Let’s now proceed with the code that is required to build an Auto-clicker using Python. Follow the below steps to create an auto-clicker:" }, { "code": null, "e": 1661, "s": 1517, "text": "Step 1: Import time and threading then import Button and Controller from pynput.mouse module. Import Listener and KeyCode from pynput.keyboard." }, { "code": null, "e": 1669, "s": 1661, "text": "Python3" }, { "code": "# importing time and threadingimport timeimport threadingfrom pynput.mouse import Button, Controller # pynput.keyboard is used to watch events of# keyboard for start and stop of auto-clickerfrom pynput.keyboard import Listener, KeyCode", "e": 1906, "s": 1669, "text": null }, { "code": null, "e": 1957, "s": 1906, "text": "Step 2: Create four variables as mentioned below," }, { "code": null, "e": 2002, "s": 1957, "text": "delay: Delay between each click (in seconds)" }, { "code": null, "e": 2113, "s": 2002, "text": "button: Button is used to click in whatever direction you want to. Button.left | Button.middle | Button.right" }, { "code": null, "e": 2284, "s": 2113, "text": "start_stop_key: The key used for start and stop of the click while you run the program for executing the auto clicker. It should be from a key class or set using KeyCode." }, { "code": null, "e": 2417, "s": 2284, "text": "exit_key: The key used to terminate the auto clicker that is being executed. This should be from the key class or set using KeyCode." }, { "code": null, "e": 2425, "s": 2417, "text": "Python3" }, { "code": "# four variables are created to# control the auto-clickerdelay = 0.001button = Button.rightstart_stop_key = KeyCode(char='a')stop_key = KeyCode(char='b')", "e": 2579, "s": 2425, "text": null }, { "code": null, "e": 2729, "s": 2579, "text": "Step 3: Create a class extending threading.Thread. Pass delay and button to the class that have two flags to check if the program is executed or not." }, { "code": null, "e": 2737, "s": 2729, "text": "Python3" }, { "code": "# threading.Thread is used # to control clicksclass ClickMouse(threading.Thread): # delay and button is passed in class # to check execution of auto-clicker def __init__(self, delay, button): super(ClickMouse, self).__init__() self.delay = delay self.button = button self.running = False self.program_running = True", "e": 3098, "s": 2737, "text": null }, { "code": null, "e": 3153, "s": 3098, "text": "Step 4: Add methods to control the threads externally." }, { "code": null, "e": 3161, "s": 3153, "text": "Python3" }, { "code": "def start_clicking(self): self.running = True def stop_clicking(self): self.running = False def exit(self): self.stop_clicking() self.program_running = False", "e": 3349, "s": 3161, "text": null }, { "code": null, "e": 3673, "s": 3351, "text": "Step 5: A method is created when the thread starts, the program_running runs on loop until the value comes out to be true and also create another loop inside the existing loop where it checks if running is set to true or not. In case, we are inside both loops, it will click on the set button and sleep for the set delay." }, { "code": null, "e": 3681, "s": 3673, "text": "Python3" }, { "code": "# method to check and run loop until # it is true another loop will check # if it is set to true or not, # for mouse click it set to button # and delay.def run(self): while self.program_running: while self.running: mouse.click(self.button) time.sleep(self.delay) time.sleep(0.1)", "e": 3999, "s": 3681, "text": null }, { "code": null, "e": 4149, "s": 3999, "text": "Step 6: Creating an instance for the mouse controller, then create ClickMouse thread. Start the instance to move into the loop inside the run method." }, { "code": null, "e": 4157, "s": 4149, "text": "Python3" }, { "code": "# instance of mouse controller is createdmouse = Controller()click_thread = ClickMouse(delay, button)click_thread.start()", "e": 4279, "s": 4157, "text": null }, { "code": null, "e": 4623, "s": 4281, "text": "Step 7: Create a method on_press which takes a key as an argument and sets up a keyboard listener. The start_stop_key matches with a start key (a) when it is executed. Then the click is to be terminated when running flag is set to True in the thread. Exit method is called in the method if the exit key (b) is executed and stop the listener." }, { "code": null, "e": 4631, "s": 4623, "text": "Python3" }, { "code": "# on_press method takes# key as argument def on_press(key): # start_stop_key will stop clicking # if running flag is set to true if key == start_stop_key: if click_thread.running: click_thread.stop_clicking() else: click_thread.start_clicking() # here exit method is called and when # key is pressed it terminates auto clicker elif key == stop_key: click_thread.exit() listener.stop() with Listener(on_press=on_press) as listener: listener.join()", "e": 5155, "s": 4631, "text": null }, { "code": null, "e": 5490, "s": 5155, "text": "After the code is run we can see in the output as shown below, it shows the number of clicks the auto-clicker has made after the code is implemented. It is compatible with Windows, Mac and Linux. Auto-Clicker is helpful software for the systems as it let’s save a reasonable amount of time that is spent on repeated amount of clicks. " }, { "code": null, "e": 5521, "s": 5490, "text": "Below is the complete program:" }, { "code": null, "e": 5529, "s": 5521, "text": "Python3" }, { "code": "# importing time and threadingimport timeimport threadingfrom pynput.mouse import Button, Controller # pynput.keyboard is used to watch events of # keyboard for start and stop of auto-clickerfrom pynput.keyboard import Listener, KeyCode # four variables are created to # control the auto-clickerdelay = 0.001button = Button.rightstart_stop_key = KeyCode(char='a')stop_key = KeyCode(char='b') # threading.Thread is used # to control clicksclass ClickMouse(threading.Thread): # delay and button is passed in class # to check execution of auto-clicker def __init__(self, delay, button): super(ClickMouse, self).__init__() self.delay = delay self.button = button self.running = False self.program_running = True def start_clicking(self): self.running = True def stop_clicking(self): self.running = False def exit(self): self.stop_clicking() self.program_running = False # method to check and run loop until # it is true another loop will check # if it is set to true or not, # for mouse click it set to button # and delay. def run(self): while self.program_running: while self.running: mouse.click(self.button) time.sleep(self.delay) time.sleep(0.1) # instance of mouse controller is createdmouse = Controller()click_thread = ClickMouse(delay, button)click_thread.start() # on_press method takes # key as argumentdef on_press(key): # start_stop_key will stop clicking # if running flag is set to true if key == start_stop_key: if click_thread.running: click_thread.stop_clicking() else: click_thread.start_clicking() # here exit method is called and when # key is pressed it terminates auto clicker elif key == stop_key: click_thread.exit() listener.stop() with Listener(on_press=on_press) as listener: listener.join()", "e": 7516, "s": 5529, "text": null }, { "code": null, "e": 7654, "s": 7516, "text": "Now let’s execute the python program we’ve written and then press the start (a) and stop (a) keys in order to initiate the auto clicker. " }, { "code": null, "e": 7662, "s": 7654, "text": "Output:" }, { "code": null, "e": 7669, "s": 7662, "text": "Picked" }, { "code": null, "e": 7685, "s": 7669, "text": "Python-projects" }, { "code": null, "e": 7700, "s": 7685, "text": "python-utility" }, { "code": null, "e": 7707, "s": 7700, "text": "Python" }, { "code": null, "e": 7805, "s": 7707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7837, "s": 7805, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7864, "s": 7837, "text": "Python Classes and Objects" }, { "code": null, "e": 7885, "s": 7864, "text": "Python OOPs Concepts" }, { "code": null, "e": 7908, "s": 7885, "text": "Introduction To PYTHON" }, { "code": null, "e": 7939, "s": 7908, "text": "Python | os.path.join() method" }, { "code": null, "e": 7995, "s": 7939, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 8037, "s": 7995, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 8079, "s": 8037, "text": "Check if element exists in list in Python" }, { "code": null, "e": 8118, "s": 8079, "text": "Python | Get unique values from a list" } ]
How to match date with MongoDB $match?
To match date, use $match along with aggregate(). Let us create a collection with documents − > db.demo491.insertOne({"ShippingDate":new ISODate("2020-01-10")});{ "acknowledged" : true, "insertedId" : ObjectId("5e849a09b0f3fa88e22790be") } > db.demo491.insertOne({"ShippingDate":new ISODate("2020-02-21")});{ "acknowledged" : true, "insertedId" : ObjectId("5e849a0eb0f3fa88e22790bf") } > db.demo491.insertOne({"ShippingDate":new ISODate("2020-03-23")});{ "acknowledged" : true, "insertedId" : ObjectId("5e849a1db0f3fa88e22790c0") } > db.demo491.insertOne({"ShippingDate":new ISODate()});{ "acknowledged" : true, "insertedId" : ObjectId("5e849a28b0f3fa88e22790c1") } Display all documents from a collection with the help of find() method − > db.demo491.find(); This will produce the following output − { "_id" : ObjectId("5e849a09b0f3fa88e22790be"), "ShippingDate" : ISODate("2020-01- 10T00:00:00Z") } { "_id" : ObjectId("5e849a0eb0f3fa88e22790bf"), "ShippingDate" : ISODate("2020-02- 21T00:00:00Z") } { "_id" : ObjectId("5e849a1db0f3fa88e22790c0"), "ShippingDate" : ISODate("2020-03- 23T00:00:00Z") } { "_id" : ObjectId("5e849a28b0f3fa88e22790c1"), "ShippingDate" : ISODate("2020-04- 01T13:42:00.090Z") } Following is the query to match date with $match using MongoDB − > db.demo491.aggregate([ ... { ... '$match' : { 'ShippingDate' : { '$gte' : ISODate('2020-02-24T18:10:11.000Z') } } ... } ... ]); This will produce the following output − { "_id" : ObjectId("5e849a1db0f3fa88e22790c0"), "ShippingDate" : ISODate("2020-03- 23T00:00:00Z") } { "_id" : ObjectId("5e849a28b0f3fa88e22790c1"), "ShippingDate" : ISODate("2020-04- 01T13:42:00.090Z") }
[ { "code": null, "e": 1281, "s": 1187, "text": "To match date, use $match along with aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 1877, "s": 1281, "text": "> db.demo491.insertOne({\"ShippingDate\":new ISODate(\"2020-01-10\")});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e849a09b0f3fa88e22790be\")\n}\n> db.demo491.insertOne({\"ShippingDate\":new ISODate(\"2020-02-21\")});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e849a0eb0f3fa88e22790bf\")\n}\n> db.demo491.insertOne({\"ShippingDate\":new ISODate(\"2020-03-23\")});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e849a1db0f3fa88e22790c0\")\n}\n> db.demo491.insertOne({\"ShippingDate\":new ISODate()});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e849a28b0f3fa88e22790c1\")\n}" }, { "code": null, "e": 1950, "s": 1877, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1971, "s": 1950, "text": "> db.demo491.find();" }, { "code": null, "e": 2012, "s": 1971, "text": "This will produce the following output −" }, { "code": null, "e": 2416, "s": 2012, "text": "{ \"_id\" : ObjectId(\"5e849a09b0f3fa88e22790be\"), \"ShippingDate\" : ISODate(\"2020-01-\n10T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e849a0eb0f3fa88e22790bf\"), \"ShippingDate\" : ISODate(\"2020-02-\n21T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e849a1db0f3fa88e22790c0\"), \"ShippingDate\" : ISODate(\"2020-03-\n23T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e849a28b0f3fa88e22790c1\"), \"ShippingDate\" : ISODate(\"2020-04-\n01T13:42:00.090Z\") }" }, { "code": null, "e": 2481, "s": 2416, "text": "Following is the query to match date with $match using MongoDB −" }, { "code": null, "e": 2614, "s": 2481, "text": "> db.demo491.aggregate([\n... {\n... '$match' : { 'ShippingDate' : { '$gte' : ISODate('2020-02-24T18:10:11.000Z') } }\n... }\n... ]);" }, { "code": null, "e": 2655, "s": 2614, "text": "This will produce the following output −" }, { "code": null, "e": 2859, "s": 2655, "text": "{ \"_id\" : ObjectId(\"5e849a1db0f3fa88e22790c0\"), \"ShippingDate\" : ISODate(\"2020-03-\n23T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e849a28b0f3fa88e22790c1\"), \"ShippingDate\" : ISODate(\"2020-04-\n01T13:42:00.090Z\") }" } ]
Number of cards needed build a House of Cards of a given level N
21 Dec, 2021 Given a number N, the task is to find the number of cards needed to make a House of Cards of N levels. Examples: Input: N = 3 Output: 15 From the above image, it is clear that for the House of Cards for 3 levels 15 cards are neededInput: N = 2 Output: 7 Approach: If we observe carefully, then a series will be formed as shown below in which i-th item denotes the number of triangular cards needed to make a pyramid of i levels: If we observe carefully, then a series will be formed as shown below in which i-th item denotes the number of triangular cards needed to make a pyramid of i levels: 2, 7, 15, 26, 40, 57, 77, 100, 126, 155.........and so on. The above series is a method of difference series where differences are in AP as 5, 8, 11, 14....... and so on. Therefore nth term of the series will be: The above series is a method of difference series where differences are in AP as 5, 8, 11, 14....... and so on. Therefore nth term of the series will be: nth term = 2 + {5 + 8 + 11 +14 +.....(n-1) terms} = 2 + (n-1)*(2*5+(n-1-1)*3)/2 = 2 + (n-1)*(10+(n-2)*3)/2 = 2 + (n-1)*(10+3n-6)/2 = 2 + (n-1)*(3n+4)/2 = n*(3*n+1)/2; Therefore the number of cards needed for building a House of Cards of N levels will be: Therefore the number of cards needed for building a House of Cards of N levels will be: Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to find number of cards neededint noOfCards(int n){ return n * (3 * n + 1) / 2;} // Driver Codeint main(){ int n = 3; cout << noOfCards(n) << ", "; return 0;} // Java implementation of the above approachimport java.lang.*; class GFG{ // Function to find number of cards needed public static int noOfCards(int n) { return n * (3 * n + 1) / 2; } // Driver Code public static void main(String args[]) { int n = 3; System.out.print(noOfCards(n)); }} // This code is contributed by shubhamsingh10 # Python3 implementation of the above approach # Function to find number of cards neededdef noOfCards(n): return n * (3 * n + 1) // 2 # Driver Coden = 3print(noOfCards(n)) # This code is contributed by mohit kumar 29 // C# implementation of the above approachusing System; class GFG{ // Function to find number of cards needed public static int noOfCards(int n) { return n * (3 * n + 1) / 2; } // Driver Code public static void Main(String []args) { int n = 3; Console.Write(noOfCards(n)); }} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the above approach // Function to find number of cards neededfunction noOfCards(n){ return parseInt(n * (3 * n + 1) / 2);} // Driver Codevar n = 3;document.write(noOfCards(n)); </script> 15 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 SHUBHAMSINGH10 29AjayKumar rrrtnx rajeev0719singh vansikasharma1329 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Product of Array except itself
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Dec, 2021" }, { "code": null, "e": 156, "s": 52, "text": "Given a number N, the task is to find the number of cards needed to make a House of Cards of N levels. " }, { "code": null, "e": 168, "s": 156, "text": "Examples: " }, { "code": null, "e": 311, "s": 168, "text": "Input: N = 3 Output: 15 From the above image, it is clear that for the House of Cards for 3 levels 15 cards are neededInput: N = 2 Output: 7 " }, { "code": null, "e": 325, "s": 313, "text": "Approach: " }, { "code": null, "e": 492, "s": 325, "text": "If we observe carefully, then a series will be formed as shown below in which i-th item denotes the number of triangular cards needed to make a pyramid of i levels: " }, { "code": null, "e": 659, "s": 492, "text": "If we observe carefully, then a series will be formed as shown below in which i-th item denotes the number of triangular cards needed to make a pyramid of i levels: " }, { "code": null, "e": 718, "s": 659, "text": "2, 7, 15, 26, 40, 57, 77, 100, 126, 155.........and so on." }, { "code": null, "e": 876, "s": 718, "text": " The above series is a method of difference series where differences are in AP as 5, 8, 11, 14....... and so on. Therefore nth term of the series will be: " }, { "code": null, "e": 992, "s": 878, "text": "The above series is a method of difference series where differences are in AP as 5, 8, 11, 14....... and so on. " }, { "code": null, "e": 1036, "s": 992, "text": "Therefore nth term of the series will be: " }, { "code": null, "e": 1248, "s": 1036, "text": "nth term = 2 + {5 + 8 + 11 +14 +.....(n-1) terms}\n = 2 + (n-1)*(2*5+(n-1-1)*3)/2\n = 2 + (n-1)*(10+(n-2)*3)/2\n = 2 + (n-1)*(10+3n-6)/2\n = 2 + (n-1)*(3n+4)/2\n = n*(3*n+1)/2;" }, { "code": null, "e": 1339, "s": 1248, "text": " Therefore the number of cards needed for building a House of Cards of N levels will be: " }, { "code": null, "e": 1431, "s": 1341, "text": "Therefore the number of cards needed for building a House of Cards of N levels will be: " }, { "code": null, "e": 1487, "s": 1435, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1491, "s": 1487, "text": "CPP" }, { "code": null, "e": 1496, "s": 1491, "text": "Java" }, { "code": null, "e": 1504, "s": 1496, "text": "Python3" }, { "code": null, "e": 1507, "s": 1504, "text": "C#" }, { "code": null, "e": 1518, "s": 1507, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to find number of cards neededint noOfCards(int n){ return n * (3 * n + 1) / 2;} // Driver Codeint main(){ int n = 3; cout << noOfCards(n) << \", \"; return 0;}", "e": 1790, "s": 1518, "text": null }, { "code": "// Java implementation of the above approachimport java.lang.*; class GFG{ // Function to find number of cards needed public static int noOfCards(int n) { return n * (3 * n + 1) / 2; } // Driver Code public static void main(String args[]) { int n = 3; System.out.print(noOfCards(n)); }} // This code is contributed by shubhamsingh10", "e": 2173, "s": 1790, "text": null }, { "code": "# Python3 implementation of the above approach # Function to find number of cards neededdef noOfCards(n): return n * (3 * n + 1) // 2 # Driver Coden = 3print(noOfCards(n)) # This code is contributed by mohit kumar 29", "e": 2393, "s": 2173, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to find number of cards needed public static int noOfCards(int n) { return n * (3 * n + 1) / 2; } // Driver Code public static void Main(String []args) { int n = 3; Console.Write(noOfCards(n)); }} // This code is contributed by 29AjayKumar", "e": 2763, "s": 2393, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to find number of cards neededfunction noOfCards(n){ return parseInt(n * (3 * n + 1) / 2);} // Driver Codevar n = 3;document.write(noOfCards(n)); </script>", "e": 2994, "s": 2763, "text": null }, { "code": null, "e": 2997, "s": 2994, "text": "15" }, { "code": null, "e": 3021, "s": 2999, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3044, "s": 3021, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 3059, "s": 3044, "text": "mohit kumar 29" }, { "code": null, "e": 3074, "s": 3059, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 3086, "s": 3074, "text": "29AjayKumar" }, { "code": null, "e": 3093, "s": 3086, "text": "rrrtnx" }, { "code": null, "e": 3109, "s": 3093, "text": "rajeev0719singh" }, { "code": null, "e": 3127, "s": 3109, "text": "vansikasharma1329" }, { "code": null, "e": 3134, "s": 3127, "text": "series" }, { "code": null, "e": 3147, "s": 3134, "text": "Mathematical" }, { "code": null, "e": 3160, "s": 3147, "text": "Mathematical" }, { "code": null, "e": 3167, "s": 3160, "text": "series" }, { "code": null, "e": 3265, "s": 3167, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3297, "s": 3265, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3343, "s": 3297, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 3387, "s": 3343, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 3436, "s": 3387, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 3478, "s": 3436, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 3510, "s": 3478, "text": "Check if a number is Palindrome" }, { "code": null, "e": 3545, "s": 3510, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 3616, "s": 3545, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 3641, "s": 3616, "text": "Fizz Buzz Implementation" } ]
numpy.nonzero() in Python
28 Nov, 2018 numpy.nonzero()function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] . To group the indices by element, rather than dimension we can use transpose(nonzero(arr)). Syntax : numpy.nonzero(arr) Parameters :arr : [array_like] Input array. Return : [tuple_of_arrays] Indices of elements that are non-zero. Code #1 : Working # Python program explaining# nonzero() function import numpy as geekarr = geek.array([[0, 8, 0], [7, 0, 0], [-5, 0, 1]]) print ("Input array : \n", arr) out_tpl = geek.nonzero(arr)print ("Indices of non zero elements : ", out_tpl) Output : Input array :[[ 0 8 0][ 7 0 0][-5 0 1]]Indices of non zero elements : (array([0, 1, 2, 2], dtype=int64), array([1, 0, 0, 2], dtype=int64)) Code #2 : # Python program for getting# The corresponding non-zero values:out_arr = arr[geek.nonzero(arr)] print ("Output array of non-zero number: ", out_arr) Output : Output array of non-zero number: [ 8 7 -5 1] Code #3 : # Python program for grouping the indices# by element, rather than dimension out_ind = geek.transpose(geek.nonzero(arr)) print ("indices of non-zero number: \n", out_ind) Output : indices of non-zero number: [[0 1] [1 0] [2 0] [2 2]] Python numpy-Indexing Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Nov, 2018" }, { "code": null, "e": 143, "s": 53, "text": "numpy.nonzero()function is used to Compute the indices of the elements that are non-zero." }, { "code": null, "e": 449, "s": 143, "text": "It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] . To group the indices by element, rather than dimension we can use transpose(nonzero(arr))." }, { "code": null, "e": 477, "s": 449, "text": "Syntax : numpy.nonzero(arr)" }, { "code": null, "e": 521, "s": 477, "text": "Parameters :arr : [array_like] Input array." }, { "code": null, "e": 587, "s": 521, "text": "Return : [tuple_of_arrays] Indices of elements that are non-zero." }, { "code": null, "e": 605, "s": 587, "text": "Code #1 : Working" }, { "code": "# Python program explaining# nonzero() function import numpy as geekarr = geek.array([[0, 8, 0], [7, 0, 0], [-5, 0, 1]]) print (\"Input array : \\n\", arr) out_tpl = geek.nonzero(arr)print (\"Indices of non zero elements : \", out_tpl) ", "e": 843, "s": 605, "text": null }, { "code": null, "e": 852, "s": 843, "text": "Output :" }, { "code": null, "e": 991, "s": 852, "text": "Input array :[[ 0 8 0][ 7 0 0][-5 0 1]]Indices of non zero elements : (array([0, 1, 2, 2], dtype=int64), array([1, 0, 0, 2], dtype=int64))" }, { "code": null, "e": 1002, "s": 991, "text": " Code #2 :" }, { "code": "# Python program for getting# The corresponding non-zero values:out_arr = arr[geek.nonzero(arr)] print (\"Output array of non-zero number: \", out_arr) ", "e": 1154, "s": 1002, "text": null }, { "code": null, "e": 1163, "s": 1154, "text": "Output :" }, { "code": null, "e": 1212, "s": 1163, "text": "Output array of non-zero number: [ 8 7 -5 1]\n" }, { "code": null, "e": 1223, "s": 1212, "text": " Code #3 :" }, { "code": "# Python program for grouping the indices# by element, rather than dimension out_ind = geek.transpose(geek.nonzero(arr)) print (\"indices of non-zero number: \\n\", out_ind) ", "e": 1397, "s": 1223, "text": null }, { "code": null, "e": 1406, "s": 1397, "text": "Output :" }, { "code": null, "e": 1466, "s": 1406, "text": "indices of non-zero number: \n [[0 1]\n [1 0]\n [2 0]\n [2 2]]\n" }, { "code": null, "e": 1488, "s": 1466, "text": "Python numpy-Indexing" }, { "code": null, "e": 1501, "s": 1488, "text": "Python-numpy" }, { "code": null, "e": 1508, "s": 1501, "text": "Python" }, { "code": null, "e": 1606, "s": 1508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1624, "s": 1606, "text": "Python Dictionary" }, { "code": null, "e": 1666, "s": 1624, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1688, "s": 1666, "text": "Enumerate() in Python" }, { "code": null, "e": 1723, "s": 1688, "text": "Read a file line by line in Python" }, { "code": null, "e": 1755, "s": 1723, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1784, "s": 1755, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1814, "s": 1784, "text": "Iterate over a list in Python" }, { "code": null, "e": 1841, "s": 1814, "text": "Python Classes and Objects" }, { "code": null, "e": 1877, "s": 1841, "text": "Convert integer to string in Python" } ]
JP Morgan Code for Good Internship Interview Experience 2021
05 Aug, 2021 Application Process + Resume Pre-Requisite: The Code For Good event is the only means by which the students can apply for the Software Engineer Program (SEP) at JP Morgan Chase & Co. First Step was to Apply for JP Morgan [On Campus] for Software Engineer Program, 2022. CGPA Cutoff: 7 CGPA & No Backlog [For Application Process] The Students who were in their Second Year of College [4th Semester] were Eligible for this Internship Offer. Round 1(Online Test): The test was conducted on 20 February 2021. [Fourth Semester of College] Platform: Hacker Rank Time: 75 minutes Marks: 100 marks having 2 programming questions, each of 50 marks. [There is no negative marking.] Note: It was mandatory to attempt both the questions. The difficulty level of these questions was fairly easy. 1. Given an Array of String containing names of Tools (can have duplicates), the Starting index and A Target Tool, find the Minimum Number of Steps required to reach the target tool from the starting index. The Array is Circular, that is, If you reach the End of the array, you can go to its start and vice versa. Sample Testcase: Tools : ['saw', 'hammer', 'mallet', 'file', 'saw', 'ladder', 'scissor'] Starting Index : 6 {i.e. 'scissor'} To Find : 'saw' Answer: 1 Minimum Steps = min(2 Steps to Left, 1 Step to Right [Circular]) = 1 Step 2. Given a Linked List having either 0 or 1 as its elements, find the decimal representation of the binary number formed by the nodes of the list. Sample Testcase: Linked List = [1→ 0 → 1 → 1 → 0] Answer: 22 Decimal of 10110 = (2^4 + 2^2 + 2^1) = 16 + 4 + 2 = 22 Tip: The Faster you do [with Accuracy], the better are your Chances of Selection. I completed the test in 14 mins & was Selected for the Next Round. Round 2(Video Interview): The Video Interview took place on 10th March 2021 on the Hirevue Platform. There were 2 behavioral-based questions, flashed on screen one after the other. And it’s a recorded video interview, and the best part was that you can Retake your video but only once for each video. You will be given 30 secs to prepare for each question, and then you can start recording your answer. Online Video Interview Questions: Tell about your experience when you have been Assigned to Some Task in-School Project, or at Work, and you have done beyond that.Tell Something that you have to Learn from your Recent Mistake. Tell about your experience when you have been Assigned to Some Task in-School Project, or at Work, and you have done beyond that. Tell Something that you have to Learn from your Recent Mistake. Pro Tip: Dress in Formal [Shows you are Serious towards this Internship] during the Interview and Be Natural and Honest [Don’t Bluff] While Answering the Behavioral Question. Shortlisting was Based on all three Parameter Resume + CGPA Online Coding Test Performance HireVue Interview Round JP Morgan Chase announces the final participant shortlist for the Code For Good event on 1 May,2021. I got selected for Round 3 [Code For Good Event]. Round 3(Code for Good Hackathon): The Hackathon was conducted Virtually all over the country (India). All the selected candidates are divided into a team of 6-7 members by the company (Different students from Different Colleges). There are some Workshop Sessions [2 Day Prior to the Actual Hackathon] on Topics like Hackathon Survival Guide, Hackathon Tool Preparation [Trello], FLARE Workshop, Power of Empathy in Coding. Tip: Please do attend the Workshop, since it would definitely save your time during the real hackathon. Final Hackathon [2 Day] On the day of the hackathon, there were be 5 problem statements given by different NGOs connected to the company. Around 10 mins are given to all the teams to order their interesting statements (It is like Fastest Finger First). Once the time is over they will let you know the problem statement you are Allotted with. Tip: Be Ready to Submit your Preference within 30 seconds to 1 Minute, So that you get the Problem Statement that You Find it resonating with Teams Strengths. CFG is 24-hour Hackathon where you are given time till the next day morning and 2-3 Mentors are also allotted to each team and SME’s also be available in case if you need any Technical help. Make sure you commit your changes to GitHub from time to time so that you won’t miss any code. After the hackathon time, We have to upload the project to the portal [BeMyApp], and reviews are done by the Technical team and the Respective NGO. After all, the Reviews at the end of the event Winners would be announced! Tip: Make a Good Video Covering all the Key Functionalities of the Project. To clear this round, You need to have knowledge in Full Stack Development and be more Interactive during the hackathon. Your Team might/might not have Won the Hackathon for the Code For Good Event, But Still, If You Worked Really Well & Mentors Do Acknowledge this Fact then You Chances of Getting Selected Increase. You are Judged Based on What you Do in those 24 Hours of Hackathon. How you Divide your Work [Team Work] Considering Others Opinions and Not Dominating Solving Issues with Patience Respecting Everyone in the Group and their Contributions By End of the Month [31 July 2021] Results were announced and I was Selected for an Internship. JP Morgan Marketing Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Aug, 2021" }, { "code": null, "e": 84, "s": 54, "text": "Application Process + Resume " }, { "code": null, "e": 99, "s": 84, "text": "Pre-Requisite:" }, { "code": null, "e": 238, "s": 99, "text": "The Code For Good event is the only means by which the students can apply for the Software Engineer Program (SEP) at JP Morgan Chase & Co." }, { "code": null, "e": 327, "s": 238, "text": "First Step was to Apply for JP Morgan [On Campus] for Software Engineer Program, 2022. " }, { "code": null, "e": 386, "s": 327, "text": "CGPA Cutoff: 7 CGPA & No Backlog [For Application Process]" }, { "code": null, "e": 496, "s": 386, "text": "The Students who were in their Second Year of College [4th Semester] were Eligible for this Internship Offer." }, { "code": null, "e": 518, "s": 496, "text": "Round 1(Online Test):" }, { "code": null, "e": 591, "s": 518, "text": "The test was conducted on 20 February 2021. [Fourth Semester of College]" }, { "code": null, "e": 613, "s": 591, "text": "Platform: Hacker Rank" }, { "code": null, "e": 632, "s": 613, "text": "Time: 75 minutes " }, { "code": null, "e": 732, "s": 632, "text": "Marks: 100 marks having 2 programming questions, each of 50 marks. [There is no negative marking.]" }, { "code": null, "e": 788, "s": 732, "text": "Note: It was mandatory to attempt both the questions. " }, { "code": null, "e": 845, "s": 788, "text": "The difficulty level of these questions was fairly easy." }, { "code": null, "e": 1159, "s": 845, "text": "1. Given an Array of String containing names of Tools (can have duplicates), the Starting index and A Target Tool, find the Minimum Number of Steps required to reach the target tool from the starting index. The Array is Circular, that is, If you reach the End of the array, you can go to its start and vice versa." }, { "code": null, "e": 1176, "s": 1159, "text": "Sample Testcase:" }, { "code": null, "e": 1301, "s": 1176, "text": "Tools : ['saw', 'hammer', 'mallet', \n'file', 'saw', 'ladder', 'scissor']\nStarting Index : 6 {i.e. 'scissor'}\nTo Find : 'saw'" }, { "code": null, "e": 1311, "s": 1301, "text": "Answer: " }, { "code": null, "e": 1314, "s": 1311, "text": "1 " }, { "code": null, "e": 1388, "s": 1314, "text": "Minimum Steps = min(2 Steps to Left, 1 Step to Right [Circular]) = 1 Step" }, { "code": null, "e": 1535, "s": 1388, "text": "2. Given a Linked List having either 0 or 1 as its elements, find the decimal representation of the binary number formed by the nodes of the list." }, { "code": null, "e": 1554, "s": 1535, "text": "Sample Testcase: " }, { "code": null, "e": 1587, "s": 1554, "text": "Linked List = [1→ 0 → 1 → 1 → 0]" }, { "code": null, "e": 1596, "s": 1587, "text": "Answer: " }, { "code": null, "e": 1599, "s": 1596, "text": "22" }, { "code": null, "e": 1654, "s": 1599, "text": "Decimal of 10110 = (2^4 + 2^2 + 2^1) = 16 + 4 + 2 = 22" }, { "code": null, "e": 1736, "s": 1654, "text": "Tip: The Faster you do [with Accuracy], the better are your Chances of Selection." }, { "code": null, "e": 1803, "s": 1736, "text": "I completed the test in 14 mins & was Selected for the Next Round." }, { "code": null, "e": 1829, "s": 1803, "text": "Round 2(Video Interview):" }, { "code": null, "e": 2206, "s": 1829, "text": "The Video Interview took place on 10th March 2021 on the Hirevue Platform. There were 2 behavioral-based questions, flashed on screen one after the other. And it’s a recorded video interview, and the best part was that you can Retake your video but only once for each video. You will be given 30 secs to prepare for each question, and then you can start recording your answer." }, { "code": null, "e": 2240, "s": 2206, "text": "Online Video Interview Questions:" }, { "code": null, "e": 2433, "s": 2240, "text": "Tell about your experience when you have been Assigned to Some Task in-School Project, or at Work, and you have done beyond that.Tell Something that you have to Learn from your Recent Mistake." }, { "code": null, "e": 2563, "s": 2433, "text": "Tell about your experience when you have been Assigned to Some Task in-School Project, or at Work, and you have done beyond that." }, { "code": null, "e": 2627, "s": 2563, "text": "Tell Something that you have to Learn from your Recent Mistake." }, { "code": null, "e": 2804, "s": 2627, "text": "Pro Tip: Dress in Formal [Shows you are Serious towards this Internship] during the Interview and Be Natural and Honest [Don’t Bluff] While Answering the Behavioral Question. " }, { "code": null, "e": 2850, "s": 2804, "text": "Shortlisting was Based on all three Parameter" }, { "code": null, "e": 2864, "s": 2850, "text": "Resume + CGPA" }, { "code": null, "e": 2895, "s": 2864, "text": "Online Coding Test Performance" }, { "code": null, "e": 2919, "s": 2895, "text": "HireVue Interview Round" }, { "code": null, "e": 3072, "s": 2919, "text": "JP Morgan Chase announces the final participant shortlist for the Code For Good event on 1 May,2021. I got selected for Round 3 [Code For Good Event]. " }, { "code": null, "e": 3106, "s": 3072, "text": "Round 3(Code for Good Hackathon):" }, { "code": null, "e": 3175, "s": 3106, "text": "The Hackathon was conducted Virtually all over the country (India). " }, { "code": null, "e": 3304, "s": 3175, "text": "All the selected candidates are divided into a team of 6-7 members by the company (Different students from Different Colleges). " }, { "code": null, "e": 3497, "s": 3304, "text": "There are some Workshop Sessions [2 Day Prior to the Actual Hackathon] on Topics like Hackathon Survival Guide, Hackathon Tool Preparation [Trello], FLARE Workshop, Power of Empathy in Coding." }, { "code": null, "e": 3601, "s": 3497, "text": "Tip: Please do attend the Workshop, since it would definitely save your time during the real hackathon." }, { "code": null, "e": 3626, "s": 3601, "text": "Final Hackathon [2 Day] " }, { "code": null, "e": 3742, "s": 3626, "text": "On the day of the hackathon, there were be 5 problem statements given by different NGOs connected to the company. " }, { "code": null, "e": 3947, "s": 3742, "text": "Around 10 mins are given to all the teams to order their interesting statements (It is like Fastest Finger First). Once the time is over they will let you know the problem statement you are Allotted with." }, { "code": null, "e": 4108, "s": 3947, "text": "Tip: Be Ready to Submit your Preference within 30 seconds to 1 Minute, So that you get the Problem Statement that You Find it resonating with Teams Strengths. " }, { "code": null, "e": 4394, "s": 4108, "text": "CFG is 24-hour Hackathon where you are given time till the next day morning and 2-3 Mentors are also allotted to each team and SME’s also be available in case if you need any Technical help. Make sure you commit your changes to GitHub from time to time so that you won’t miss any code." }, { "code": null, "e": 4617, "s": 4394, "text": "After the hackathon time, We have to upload the project to the portal [BeMyApp], and reviews are done by the Technical team and the Respective NGO. After all, the Reviews at the end of the event Winners would be announced!" }, { "code": null, "e": 4693, "s": 4617, "text": "Tip: Make a Good Video Covering all the Key Functionalities of the Project." }, { "code": null, "e": 4813, "s": 4693, "text": "To clear this round, You need to have knowledge in Full Stack Development and be more Interactive during the hackathon." }, { "code": null, "e": 5012, "s": 4813, "text": "Your Team might/might not have Won the Hackathon for the Code For Good Event, But Still, If You Worked Really Well & Mentors Do Acknowledge this Fact then You Chances of Getting Selected Increase. " }, { "code": null, "e": 5080, "s": 5012, "text": "You are Judged Based on What you Do in those 24 Hours of Hackathon." }, { "code": null, "e": 5117, "s": 5080, "text": "How you Divide your Work [Team Work]" }, { "code": null, "e": 5164, "s": 5117, "text": "Considering Others Opinions and Not Dominating" }, { "code": null, "e": 5193, "s": 5164, "text": "Solving Issues with Patience" }, { "code": null, "e": 5250, "s": 5193, "text": "Respecting Everyone in the Group and their Contributions" }, { "code": null, "e": 5347, "s": 5250, "text": "By End of the Month [31 July 2021] Results were announced and I was Selected for an Internship. " }, { "code": null, "e": 5357, "s": 5347, "text": "JP Morgan" }, { "code": null, "e": 5367, "s": 5357, "text": "Marketing" }, { "code": null, "e": 5389, "s": 5367, "text": "Interview Experiences" } ]
HTML DOM getElementsByClassName() Method
12 Nov, 2021 The getElementsByClassName() method in Javascript returns an object containing all the elements with the specified class names in the document as objects. Each element in the returned object can be accessed by its index. The index value will start with 0. This method can be called upon any individual element to search for its descendant elements with the specified class names. Syntax: document.getElementsByClassName(classnames); Parameters: This is a required method that takes only one parameter, which is a string containing space-separated class names of the elements that are to be searched for. For searching with multiple class names, it must be separated with space. Note: We can use the length property that returns the collection of all HTML elements in a document for the specified class name & then by looping through the HTML elements, we can take information that wants. Example 1: This example describes the getElementsByClassName() method for getting access to HTML element by its class name. HTML <!DOCTYPE html><html> <head> <title>DOM getElementByClassName() Method</title> <style> h1 { color: green; } body { text-align: center; } .example { padding: 10px; margin: auto; margin-top: 10px; border: 1px solid black; width: 300px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementByClassName() Method</h2> <div> <h4 class="example">div1</h4> <h4 class="yellowBorder example">div2</h4> <h4 class="greenBorder example">div3</h4> <h4 class="example">div4</h4> </div> <script> document.getElementsByClassName('greenBorder example')[0].style.border = "10px solid green"; document.getElementsByClassName('yellowBorder example')[0].style.border = "10px solid yellow"; </script></body> </html> Output: document.getElementsByClassName() Method Example 2: This example describes the use of the document.getElementsByClassName() method that accesses all the 3 button classes with the specific color & alters the color of the button on clicked & the last button resets all the above 3 buttons to their initial state. HTML <!DOCTYPE html><html> <head> <title>DOM getElementByClassName() Method</title> <style> h1 { color: green; } body { text-align: center; } button { background-color: black; color: white; width: 300px; padding: 10px; margin: 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementByClassName() Method</h2> <div> <button onclick="red()" class="black red"> Click to change to red button </button> <br> <button onclick="blue()" class="black blue"> Click to change to blue button </button> <br> <button onclick="yellow()" class="black yellow"> Click to change to yellow button </button> <br> <button onclick="black()"> Click to change to all buttons to initial state </button> </div> <script> function red() { document.getElementsByClassName('red')[0] .style.backgroundColor = 'red'; } function blue() { document.getElementsByClassName('blue')[0] .style.backgroundColor = 'blue'; } function yellow() { document.getElementsByClassName('yellow')[0] .style.backgroundColor = 'yellow'; } function black() { var elements = document.getElementsByClassName('black'); for(var i = 0; i < elements.length; i++) { elements[i].style.backgroundColor = 'black'; } } </script></body> </html> Output: document.getElementsByClassName() Method Supported Browser: The browsers supported by DOM getElementsByClassName() are listed below: Google Chrome 4.0 Internet Explorer 9.0 Microsoft Edge 12.0 Firefox 3.0 Opera 9.5 Safari 3.1 Akanksha_Rai aktmishra143 bhaskargeeksforgeeks HTML-DOM HTML-Methods Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Roadmap to Learn JavaScript For Beginners Node.js fs.readFileSync() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2021" }, { "code": null, "e": 408, "s": 28, "text": "The getElementsByClassName() method in Javascript returns an object containing all the elements with the specified class names in the document as objects. Each element in the returned object can be accessed by its index. The index value will start with 0. This method can be called upon any individual element to search for its descendant elements with the specified class names." }, { "code": null, "e": 416, "s": 408, "text": "Syntax:" }, { "code": null, "e": 461, "s": 416, "text": "document.getElementsByClassName(classnames);" }, { "code": null, "e": 706, "s": 461, "text": "Parameters: This is a required method that takes only one parameter, which is a string containing space-separated class names of the elements that are to be searched for. For searching with multiple class names, it must be separated with space." }, { "code": null, "e": 916, "s": 706, "text": "Note: We can use the length property that returns the collection of all HTML elements in a document for the specified class name & then by looping through the HTML elements, we can take information that wants." }, { "code": null, "e": 1040, "s": 916, "text": "Example 1: This example describes the getElementsByClassName() method for getting access to HTML element by its class name." }, { "code": null, "e": 1045, "s": 1040, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM getElementByClassName() Method</title> <style> h1 { color: green; } body { text-align: center; } .example { padding: 10px; margin: auto; margin-top: 10px; border: 1px solid black; width: 300px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementByClassName() Method</h2> <div> <h4 class=\"example\">div1</h4> <h4 class=\"yellowBorder example\">div2</h4> <h4 class=\"greenBorder example\">div3</h4> <h4 class=\"example\">div4</h4> </div> <script> document.getElementsByClassName('greenBorder example')[0].style.border = \"10px solid green\"; document.getElementsByClassName('yellowBorder example')[0].style.border = \"10px solid yellow\"; </script></body> </html>", "e": 1892, "s": 1045, "text": null }, { "code": null, "e": 1900, "s": 1892, "text": "Output:" }, { "code": null, "e": 1941, "s": 1900, "text": "document.getElementsByClassName() Method" }, { "code": null, "e": 2212, "s": 1941, "text": "Example 2: This example describes the use of the document.getElementsByClassName() method that accesses all the 3 button classes with the specific color & alters the color of the button on clicked & the last button resets all the above 3 buttons to their initial state." }, { "code": null, "e": 2217, "s": 2212, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM getElementByClassName() Method</title> <style> h1 { color: green; } body { text-align: center; } button { background-color: black; color: white; width: 300px; padding: 10px; margin: 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM getElementByClassName() Method</h2> <div> <button onclick=\"red()\" class=\"black red\"> Click to change to red button </button> <br> <button onclick=\"blue()\" class=\"black blue\"> Click to change to blue button </button> <br> <button onclick=\"yellow()\" class=\"black yellow\"> Click to change to yellow button </button> <br> <button onclick=\"black()\"> Click to change to all buttons to initial state </button> </div> <script> function red() { document.getElementsByClassName('red')[0] .style.backgroundColor = 'red'; } function blue() { document.getElementsByClassName('blue')[0] .style.backgroundColor = 'blue'; } function yellow() { document.getElementsByClassName('yellow')[0] .style.backgroundColor = 'yellow'; } function black() { var elements = document.getElementsByClassName('black'); for(var i = 0; i < elements.length; i++) { elements[i].style.backgroundColor = 'black'; } } </script></body> </html>", "e": 3758, "s": 2217, "text": null }, { "code": null, "e": 3766, "s": 3758, "text": "Output:" }, { "code": null, "e": 3807, "s": 3766, "text": "document.getElementsByClassName() Method" }, { "code": null, "e": 3900, "s": 3807, "text": "Supported Browser: The browsers supported by DOM getElementsByClassName() are listed below: " }, { "code": null, "e": 3918, "s": 3900, "text": "Google Chrome 4.0" }, { "code": null, "e": 3940, "s": 3918, "text": "Internet Explorer 9.0" }, { "code": null, "e": 3960, "s": 3940, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 3972, "s": 3960, "text": "Firefox 3.0" }, { "code": null, "e": 3982, "s": 3972, "text": "Opera 9.5" }, { "code": null, "e": 3993, "s": 3982, "text": "Safari 3.1" }, { "code": null, "e": 4006, "s": 3993, "text": "Akanksha_Rai" }, { "code": null, "e": 4019, "s": 4006, "text": "aktmishra143" }, { "code": null, "e": 4040, "s": 4019, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 4049, "s": 4040, "text": "HTML-DOM" }, { "code": null, "e": 4062, "s": 4049, "text": "HTML-Methods" }, { "code": null, "e": 4069, "s": 4062, "text": "Picked" }, { "code": null, "e": 4086, "s": 4069, "text": "Web Technologies" }, { "code": null, "e": 4184, "s": 4086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4217, "s": 4184, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4279, "s": 4217, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4340, "s": 4279, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4390, "s": 4340, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4433, "s": 4390, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4505, "s": 4433, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4545, "s": 4505, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4569, "s": 4545, "text": "REST API (Introduction)" }, { "code": null, "e": 4611, "s": 4569, "text": "Roadmap to Learn JavaScript For Beginners" } ]
java.time.ZonedDateTime Class in Java
28 Mar, 2021 ZonedDateTime is an immutable object representing a date-time along with the time zone. This class stores all date and time fields.This class stores time to a precision of nanoseconds and a time-zone, with a zone Offset used to handle local date-times. For example, the value “2nd October 2011 at 14:45.30.123456789 +05:30 in the Asia/Kolkata time-zone” can be stored in a ZonedDateTime.This class is also used to convert the local time-line of LocalDateTime to the instant time-line of Instant. Class Declaration: public final class ZonedDateTime extends Object implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable Methods: Method Description equals(Object obj) This method checks if this date-time is equal to another date-time. format(DateTimeFormatter formatter) This method formats this date-time using the specified formatter. from(TemporalAccessor temporal) This method obtains an instance of ZonedDateTime from a temporal object. get(TemporalField field) This method gets the value of the specified field from this date-time as an int. getDayOfMonth() This method gets the day-of-month field. getDayOfWeek() This method gets the day-of-week field, which is an enum DayOfWeek. getDayOfYear() This method gets the day-of-year field. getHour() This method gets the hour-of-day field. getLong(TemporalField field) This method gets the value of the specified field from this date-time as a long. getMinute() This method gets the minute-of-hour field. getMonth() This method gets the month-of-year field using the Month enum. getMonthValue() This method gets the month-of-year field from 1 to 12. getNano() This method gets the nano-of-second field. getOffset() This method gets the zone offset, such as ‘+01:00’. getSecond() This method gets the second-of-minute field. getYear() This method gets the year field. getZone() This method gets the time-zone, such as ‘Europe/Paris’. hashCode() A hash code for this date-time. isSupported(TemporalField field) This method checks if the specified field is supported. isSupported(TemporalUnit unit) This method checks if the specified unit is supported. minus(long amountToSubtract, TemporalUnit unit) This method returns a copy of this date-time with the specified amount subtracted. minus(TemporalAmount amountToSubtract) This method returns a copy of this date-time with the specified amount subtracted. minusDays(long days) This method returns a copy of this ZonedDateTime with the specified number of days subtracted. minusHours(long hours) This method returns a copy of this ZonedDateTime with the specified number of hours subtracted. minusMinutes(long minutes) This method returns a copy of this ZonedDateTime with the specified number of minutes subtracted. minusMonths(long months) This method returns a copy of this ZonedDateTime with the specified number of months subtracted. minusNanos(long nanos) This method returns a copy of this ZonedDateTime with the specified number of nanoseconds subtracted. minusSeconds(long seconds) This method returns a copy of this ZonedDateTime with the specified number of seconds subtracted. minusWeeks(long weeks) This method returns a copy of this ZonedDateTime with the specified number of weeks subtracted. minusYears(long years) This method returns a copy of this ZonedDateTime with the specified number of years subtracted. now() This method obtains the current date-time from the system clock in the default time-zone. now(Clock clock) This method obtains the current date-time from the specified clock. now(ZoneId zone) This method obtains the current date-time from the system clock in the specified time-zone. of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone) This method obtains an instance of ZonedDateTime from a year, month, day, hour, minute, second, nanosecond and time-zone. of(LocalDate date, LocalTime time, ZoneId zone) This method obtains an instance of ZonedDateTime from a local date and time. of(LocalDateTime localDateTime, ZoneId zone) This method obtains an instance of ZonedDateTime from a local date-time. ofInstant(Instant instant, ZoneId zone) This method obtains an instance of ZonedDateTime from an Instant. ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) This method obtains an instance of ZonedDateTime from the instant formed by combining the local date-time and offset. ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) This method obtains an instance of ZonedDateTime from a local date-time using the preferred offset if possible. ofStrict(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) This method obtains an instance of ZonedDateTime strictly validating the combination of local date-time, offset and zone ID. parse(CharSequence text) This method obtains an instance of ZonedDateTime from a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris] parse(CharSequence text, DateTimeFormatter formatter) This method obtains an instance of ZonedDateTime from a text string using a specific formatter. plus(long amountToAdd, TemporalUnit unit) This method returns a copy of this date-time with the specified amount added. plus(TemporalAmount amountToAdd) This method returns a copy of this date-time with the specified amount added. plusDays(long days) This method returns a copy of this ZonedDateTime with the specified number of days added. plusHours(long hours) This method returns a copy of this ZonedDateTime with the specified number of hours added. plusMinutes(long minutes) This method returns a copy of this ZonedDateTime with the specified number of minutes added. plusMonths(long months) This method returns a copy of this ZonedDateTime with the specified number of months added. plusNanos(long nanos) This method returns a copy of this ZonedDateTime with the specified number of nanoseconds added. plusSeconds(long seconds) This method returns a copy of this ZonedDateTime with the specified number of seconds added. plusWeeks(long weeks) This method returns a copy of this ZonedDateTime with the specified number of weeks added. plusYears(long years) This method returns a copy of this ZonedDateTime with the specified number of years added. query(TemporalQuery<R> query) This method queries this date-time using the specified query. range(TemporalField field) This method gets the range of valid values for the specified field. toLocalDate() This method gets the LocalDate part of this date-time. toLocalDateTime() This method gets the LocalDateTime part of this date-time. toLocalTime() This method gets the LocalTime part of this date-time. toOffsetDateTime() This method converts this date-time to an OffsetDateTime. toString() This method outputs this date-time as a String, such as 2007-12-03T10:15:30+01:00[Europe/Paris]. truncatedTo(TemporalUnit unit) This method returns a copy of this ZonedDateTime with the time truncated. until(Temporal endExclusive, TemporalUnit unit) This method calculates the amount of time until another date-time in terms of the specified unit. with(TemporalAdjuster adjuster) This method returns an adjusted copy of this date-time. with(TemporalField field, long newValue) This method returns a copy of this date-time with the specified field set to a new value. withDayOfMonth(int dayOfMonth) This method returns a copy of this ZonedDateTime with the day-of-month altered. withDayOfYear(int dayOfYear) This method returns a copy of this ZonedDateTime with the day-of-year altered. withEarlierOffsetAtOverlap() This method returns a copy of this date-time changing the zone offset to the earlier of the two valid offsets at a local time-line overlap. withFixedOffsetZone() This method returns a copy of this date-time with the zone ID set to the offset. withHour(int hour) This method returns a copy of this ZonedDateTime with the hour-of-day altered. withLaterOffsetAtOverlap() This method returns a copy of this date-time changing the zone offset to the later of the two valid offsets at a local time-line overlap. withMinute(int minute) This method returns a copy of this ZonedDateTime with the minute-of-hour altered. withMonth(int month) This method returns a copy of this ZonedDateTime with the month-of-year altered. withNano(int nanoOfSecond) This method returns a copy of this ZonedDateTime with the nano-of-second altered. withSecond(int second) This method returns a copy of this ZonedDateTime with the second-of-minute altered. withYear(int year) This method returns a copy of this ZonedDateTime with the year altered. withZoneSameInstant(ZoneId zone) This method returns a copy of this date-time with a different time-zone, retaining the instant. withZoneSameLocal(ZoneId zone) This method returns a copy of this date-time with a different time-zone, retaining the local date-time if possible. Implementation of parse() method: Java // java program to create a new// ZonedDateTime using parse() methodimport java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { String text = "2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]"; // creating a new ZonedDateTime object ZonedDateTime zone = ZonedDateTime.parse(text); System.out.println(zone); }} 2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata] Implementation of getZone() method: Java // java program to illustrate working of getZone() methodimport java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { String text = "2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]"; // Creating a new ZonedDateTime object ZonedDateTime zone = ZonedDateTime.parse(text); // printing the zone of this zonedDateTime object System.out.println(zone.getZone()); }} Asia/Kolkata Implementation of plus() and minus() method: Java // java program to illustrate working// of plus() and minus() methodimport java.time.Period;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { String text = "2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]"; // Creating a new ZonedDateTime object ZonedDateTime zone = ZonedDateTime.parse(text); // printing original value of // this ZonedDateTime object System.out.println(zone); // printing value of this ZonedDateTime // object after substracing two months System.out.println(zone.minus(Period.ofMonths(2))); // printing value of this ZonedDateTime // object after adding two months System.out.println(zone.plus(Period.ofMonths(2))); }} 2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata] 2011-08-02T14:45:30.123456789+05:30[Asia/Kolkata] 2011-12-02T14:45:30.123456789+05:30[Asia/Kolkata] Implementation of of() method: Java // Java program to illustrate working of of() methodimport java.time.LocalDate;import java.time.LocalTime;import java.time.ZoneId;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // getting current date LocalDate date = LocalDate.now(); // getting current time LocalTime time = LocalTime.now(); // getting system default zone id ZoneId zoneId = ZoneId.systemDefault(); // creating a new ZonedDateTime object ZonedDateTime zonedatetime = ZonedDateTime.of(date, time, zoneId); System.out.println(zonedatetime); }} 2021-03-20T17:09:56.241560Z[Etc/UTC] Java-time package Java-ZonedDateTime Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Strings in Java Java Programming Examples Abstraction in Java HashSet in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2021" }, { "code": null, "e": 524, "s": 28, "text": "ZonedDateTime is an immutable object representing a date-time along with the time zone. This class stores all date and time fields.This class stores time to a precision of nanoseconds and a time-zone, with a zone Offset used to handle local date-times. For example, the value “2nd October 2011 at 14:45.30.123456789 +05:30 in the Asia/Kolkata time-zone” can be stored in a ZonedDateTime.This class is also used to convert the local time-line of LocalDateTime to the instant time-line of Instant." }, { "code": null, "e": 543, "s": 524, "text": "Class Declaration:" }, { "code": null, "e": 657, "s": 543, "text": "public final class ZonedDateTime\nextends Object\nimplements Temporal, ChronoZonedDateTime<LocalDate>, Serializable" }, { "code": null, "e": 666, "s": 657, "text": "Methods:" }, { "code": null, "e": 673, "s": 666, "text": "Method" }, { "code": null, "e": 685, "s": 673, "text": "Description" }, { "code": null, "e": 704, "s": 685, "text": "equals(Object obj)" }, { "code": null, "e": 772, "s": 704, "text": "This method checks if this date-time is equal to another date-time." }, { "code": null, "e": 808, "s": 772, "text": "format(DateTimeFormatter formatter)" }, { "code": null, "e": 874, "s": 808, "text": "This method formats this date-time using the specified formatter." }, { "code": null, "e": 906, "s": 874, "text": "from(TemporalAccessor temporal)" }, { "code": null, "e": 979, "s": 906, "text": "This method obtains an instance of ZonedDateTime from a temporal object." }, { "code": null, "e": 1004, "s": 979, "text": "get(TemporalField field)" }, { "code": null, "e": 1085, "s": 1004, "text": "This method gets the value of the specified field from this date-time as an int." }, { "code": null, "e": 1101, "s": 1085, "text": "getDayOfMonth()" }, { "code": null, "e": 1142, "s": 1101, "text": "This method gets the day-of-month field." }, { "code": null, "e": 1157, "s": 1142, "text": "getDayOfWeek()" }, { "code": null, "e": 1225, "s": 1157, "text": "This method gets the day-of-week field, which is an enum DayOfWeek." }, { "code": null, "e": 1240, "s": 1225, "text": "getDayOfYear()" }, { "code": null, "e": 1280, "s": 1240, "text": "This method gets the day-of-year field." }, { "code": null, "e": 1290, "s": 1280, "text": "getHour()" }, { "code": null, "e": 1330, "s": 1290, "text": "This method gets the hour-of-day field." }, { "code": null, "e": 1359, "s": 1330, "text": "getLong(TemporalField field)" }, { "code": null, "e": 1440, "s": 1359, "text": "This method gets the value of the specified field from this date-time as a long." }, { "code": null, "e": 1452, "s": 1440, "text": "getMinute()" }, { "code": null, "e": 1495, "s": 1452, "text": "This method gets the minute-of-hour field." }, { "code": null, "e": 1506, "s": 1495, "text": "getMonth()" }, { "code": null, "e": 1569, "s": 1506, "text": "This method gets the month-of-year field using the Month enum." }, { "code": null, "e": 1585, "s": 1569, "text": "getMonthValue()" }, { "code": null, "e": 1640, "s": 1585, "text": "This method gets the month-of-year field from 1 to 12." }, { "code": null, "e": 1650, "s": 1640, "text": "getNano()" }, { "code": null, "e": 1693, "s": 1650, "text": "This method gets the nano-of-second field." }, { "code": null, "e": 1705, "s": 1693, "text": "getOffset()" }, { "code": null, "e": 1757, "s": 1705, "text": "This method gets the zone offset, such as ‘+01:00’." }, { "code": null, "e": 1769, "s": 1757, "text": "getSecond()" }, { "code": null, "e": 1814, "s": 1769, "text": "This method gets the second-of-minute field." }, { "code": null, "e": 1824, "s": 1814, "text": "getYear()" }, { "code": null, "e": 1857, "s": 1824, "text": "This method gets the year field." }, { "code": null, "e": 1867, "s": 1857, "text": "getZone()" }, { "code": null, "e": 1923, "s": 1867, "text": "This method gets the time-zone, such as ‘Europe/Paris’." }, { "code": null, "e": 1934, "s": 1923, "text": "hashCode()" }, { "code": null, "e": 1966, "s": 1934, "text": "A hash code for this date-time." }, { "code": null, "e": 1999, "s": 1966, "text": "isSupported(TemporalField field)" }, { "code": null, "e": 2055, "s": 1999, "text": "This method checks if the specified field is supported." }, { "code": null, "e": 2086, "s": 2055, "text": "isSupported(TemporalUnit unit)" }, { "code": null, "e": 2141, "s": 2086, "text": "This method checks if the specified unit is supported." }, { "code": null, "e": 2189, "s": 2141, "text": "minus(long amountToSubtract, TemporalUnit unit)" }, { "code": null, "e": 2272, "s": 2189, "text": "This method returns a copy of this date-time with the specified amount subtracted." }, { "code": null, "e": 2311, "s": 2272, "text": "minus(TemporalAmount amountToSubtract)" }, { "code": null, "e": 2394, "s": 2311, "text": "This method returns a copy of this date-time with the specified amount subtracted." }, { "code": null, "e": 2415, "s": 2394, "text": "minusDays(long days)" }, { "code": null, "e": 2510, "s": 2415, "text": "This method returns a copy of this ZonedDateTime with the specified number of days subtracted." }, { "code": null, "e": 2533, "s": 2510, "text": "minusHours(long hours)" }, { "code": null, "e": 2629, "s": 2533, "text": "This method returns a copy of this ZonedDateTime with the specified number of hours subtracted." }, { "code": null, "e": 2656, "s": 2629, "text": "minusMinutes(long minutes)" }, { "code": null, "e": 2754, "s": 2656, "text": "This method returns a copy of this ZonedDateTime with the specified number of minutes subtracted." }, { "code": null, "e": 2779, "s": 2754, "text": "minusMonths(long months)" }, { "code": null, "e": 2876, "s": 2779, "text": "This method returns a copy of this ZonedDateTime with the specified number of months subtracted." }, { "code": null, "e": 2899, "s": 2876, "text": "minusNanos(long nanos)" }, { "code": null, "e": 3001, "s": 2899, "text": "This method returns a copy of this ZonedDateTime with the specified number of nanoseconds subtracted." }, { "code": null, "e": 3028, "s": 3001, "text": "minusSeconds(long seconds)" }, { "code": null, "e": 3126, "s": 3028, "text": "This method returns a copy of this ZonedDateTime with the specified number of seconds subtracted." }, { "code": null, "e": 3149, "s": 3126, "text": "minusWeeks(long weeks)" }, { "code": null, "e": 3245, "s": 3149, "text": "This method returns a copy of this ZonedDateTime with the specified number of weeks subtracted." }, { "code": null, "e": 3268, "s": 3245, "text": "minusYears(long years)" }, { "code": null, "e": 3364, "s": 3268, "text": "This method returns a copy of this ZonedDateTime with the specified number of years subtracted." }, { "code": null, "e": 3370, "s": 3364, "text": "now()" }, { "code": null, "e": 3460, "s": 3370, "text": "This method obtains the current date-time from the system clock in the default time-zone." }, { "code": null, "e": 3477, "s": 3460, "text": "now(Clock clock)" }, { "code": null, "e": 3545, "s": 3477, "text": "This method obtains the current date-time from the specified clock." }, { "code": null, "e": 3562, "s": 3545, "text": "now(ZoneId zone)" }, { "code": null, "e": 3654, "s": 3562, "text": "This method obtains the current date-time from the system clock in the specified time-zone." }, { "code": null, "e": 3759, "s": 3654, "text": "of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone)" }, { "code": null, "e": 3881, "s": 3759, "text": "This method obtains an instance of ZonedDateTime from a year, month, day, hour, minute, second, nanosecond and time-zone." }, { "code": null, "e": 3929, "s": 3881, "text": "of(LocalDate date, LocalTime time, ZoneId zone)" }, { "code": null, "e": 4006, "s": 3929, "text": "This method obtains an instance of ZonedDateTime from a local date and time." }, { "code": null, "e": 4051, "s": 4006, "text": "of(LocalDateTime localDateTime, ZoneId zone)" }, { "code": null, "e": 4124, "s": 4051, "text": "This method obtains an instance of ZonedDateTime from a local date-time." }, { "code": null, "e": 4164, "s": 4124, "text": "ofInstant(Instant instant, ZoneId zone)" }, { "code": null, "e": 4230, "s": 4164, "text": "This method obtains an instance of ZonedDateTime from an Instant." }, { "code": null, "e": 4301, "s": 4230, "text": "ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)" }, { "code": null, "e": 4419, "s": 4301, "text": "This method obtains an instance of ZonedDateTime from the instant formed by combining the local date-time and offset." }, { "code": null, "e": 4497, "s": 4419, "text": "ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset)" }, { "code": null, "e": 4609, "s": 4497, "text": "This method obtains an instance of ZonedDateTime from a local date-time using the preferred offset if possible." }, { "code": null, "e": 4679, "s": 4609, "text": "ofStrict(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)" }, { "code": null, "e": 4804, "s": 4679, "text": "This method obtains an instance of ZonedDateTime strictly validating the combination of local date-time, offset and zone ID." }, { "code": null, "e": 4829, "s": 4804, "text": "parse(CharSequence text)" }, { "code": null, "e": 4945, "s": 4829, "text": "This method obtains an instance of ZonedDateTime from a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris]" }, { "code": null, "e": 4999, "s": 4945, "text": "parse(CharSequence text, DateTimeFormatter formatter)" }, { "code": null, "e": 5095, "s": 4999, "text": "This method obtains an instance of ZonedDateTime from a text string using a specific formatter." }, { "code": null, "e": 5137, "s": 5095, "text": "plus(long amountToAdd, TemporalUnit unit)" }, { "code": null, "e": 5215, "s": 5137, "text": "This method returns a copy of this date-time with the specified amount added." }, { "code": null, "e": 5248, "s": 5215, "text": "plus(TemporalAmount amountToAdd)" }, { "code": null, "e": 5326, "s": 5248, "text": "This method returns a copy of this date-time with the specified amount added." }, { "code": null, "e": 5346, "s": 5326, "text": "plusDays(long days)" }, { "code": null, "e": 5436, "s": 5346, "text": "This method returns a copy of this ZonedDateTime with the specified number of days added." }, { "code": null, "e": 5458, "s": 5436, "text": "plusHours(long hours)" }, { "code": null, "e": 5549, "s": 5458, "text": "This method returns a copy of this ZonedDateTime with the specified number of hours added." }, { "code": null, "e": 5575, "s": 5549, "text": "plusMinutes(long minutes)" }, { "code": null, "e": 5668, "s": 5575, "text": "This method returns a copy of this ZonedDateTime with the specified number of minutes added." }, { "code": null, "e": 5692, "s": 5668, "text": "plusMonths(long months)" }, { "code": null, "e": 5784, "s": 5692, "text": "This method returns a copy of this ZonedDateTime with the specified number of months added." }, { "code": null, "e": 5806, "s": 5784, "text": "plusNanos(long nanos)" }, { "code": null, "e": 5903, "s": 5806, "text": "This method returns a copy of this ZonedDateTime with the specified number of nanoseconds added." }, { "code": null, "e": 5929, "s": 5903, "text": "plusSeconds(long seconds)" }, { "code": null, "e": 6022, "s": 5929, "text": "This method returns a copy of this ZonedDateTime with the specified number of seconds added." }, { "code": null, "e": 6044, "s": 6022, "text": "plusWeeks(long weeks)" }, { "code": null, "e": 6135, "s": 6044, "text": "This method returns a copy of this ZonedDateTime with the specified number of weeks added." }, { "code": null, "e": 6157, "s": 6135, "text": "plusYears(long years)" }, { "code": null, "e": 6248, "s": 6157, "text": "This method returns a copy of this ZonedDateTime with the specified number of years added." }, { "code": null, "e": 6278, "s": 6248, "text": "query(TemporalQuery<R> query)" }, { "code": null, "e": 6340, "s": 6278, "text": "This method queries this date-time using the specified query." }, { "code": null, "e": 6367, "s": 6340, "text": "range(TemporalField field)" }, { "code": null, "e": 6435, "s": 6367, "text": "This method gets the range of valid values for the specified field." }, { "code": null, "e": 6449, "s": 6435, "text": "toLocalDate()" }, { "code": null, "e": 6504, "s": 6449, "text": "This method gets the LocalDate part of this date-time." }, { "code": null, "e": 6522, "s": 6504, "text": "toLocalDateTime()" }, { "code": null, "e": 6581, "s": 6522, "text": "This method gets the LocalDateTime part of this date-time." }, { "code": null, "e": 6595, "s": 6581, "text": "toLocalTime()" }, { "code": null, "e": 6650, "s": 6595, "text": "This method gets the LocalTime part of this date-time." }, { "code": null, "e": 6669, "s": 6650, "text": "toOffsetDateTime()" }, { "code": null, "e": 6727, "s": 6669, "text": "This method converts this date-time to an OffsetDateTime." }, { "code": null, "e": 6738, "s": 6727, "text": "toString()" }, { "code": null, "e": 6835, "s": 6738, "text": "This method outputs this date-time as a String, such as 2007-12-03T10:15:30+01:00[Europe/Paris]." }, { "code": null, "e": 6866, "s": 6835, "text": "truncatedTo(TemporalUnit unit)" }, { "code": null, "e": 6940, "s": 6866, "text": "This method returns a copy of this ZonedDateTime with the time truncated." }, { "code": null, "e": 6988, "s": 6940, "text": "until(Temporal endExclusive, TemporalUnit unit)" }, { "code": null, "e": 7086, "s": 6988, "text": "This method calculates the amount of time until another date-time in terms of the specified unit." }, { "code": null, "e": 7118, "s": 7086, "text": "with(TemporalAdjuster adjuster)" }, { "code": null, "e": 7174, "s": 7118, "text": "This method returns an adjusted copy of this date-time." }, { "code": null, "e": 7215, "s": 7174, "text": "with(TemporalField field, long newValue)" }, { "code": null, "e": 7305, "s": 7215, "text": "This method returns a copy of this date-time with the specified field set to a new value." }, { "code": null, "e": 7336, "s": 7305, "text": "withDayOfMonth(int dayOfMonth)" }, { "code": null, "e": 7416, "s": 7336, "text": "This method returns a copy of this ZonedDateTime with the day-of-month altered." }, { "code": null, "e": 7445, "s": 7416, "text": "withDayOfYear(int dayOfYear)" }, { "code": null, "e": 7524, "s": 7445, "text": "This method returns a copy of this ZonedDateTime with the day-of-year altered." }, { "code": null, "e": 7553, "s": 7524, "text": "withEarlierOffsetAtOverlap()" }, { "code": null, "e": 7693, "s": 7553, "text": "This method returns a copy of this date-time changing the zone offset to the earlier of the two valid offsets at a local time-line overlap." }, { "code": null, "e": 7715, "s": 7693, "text": "withFixedOffsetZone()" }, { "code": null, "e": 7796, "s": 7715, "text": "This method returns a copy of this date-time with the zone ID set to the offset." }, { "code": null, "e": 7815, "s": 7796, "text": "withHour(int hour)" }, { "code": null, "e": 7894, "s": 7815, "text": "This method returns a copy of this ZonedDateTime with the hour-of-day altered." }, { "code": null, "e": 7921, "s": 7894, "text": "withLaterOffsetAtOverlap()" }, { "code": null, "e": 8059, "s": 7921, "text": "This method returns a copy of this date-time changing the zone offset to the later of the two valid offsets at a local time-line overlap." }, { "code": null, "e": 8082, "s": 8059, "text": "withMinute(int minute)" }, { "code": null, "e": 8164, "s": 8082, "text": "This method returns a copy of this ZonedDateTime with the minute-of-hour altered." }, { "code": null, "e": 8185, "s": 8164, "text": "withMonth(int month)" }, { "code": null, "e": 8266, "s": 8185, "text": "This method returns a copy of this ZonedDateTime with the month-of-year altered." }, { "code": null, "e": 8293, "s": 8266, "text": "withNano(int nanoOfSecond)" }, { "code": null, "e": 8375, "s": 8293, "text": "This method returns a copy of this ZonedDateTime with the nano-of-second altered." }, { "code": null, "e": 8398, "s": 8375, "text": "withSecond(int second)" }, { "code": null, "e": 8482, "s": 8398, "text": "This method returns a copy of this ZonedDateTime with the second-of-minute altered." }, { "code": null, "e": 8501, "s": 8482, "text": "withYear(int year)" }, { "code": null, "e": 8573, "s": 8501, "text": "This method returns a copy of this ZonedDateTime with the year altered." }, { "code": null, "e": 8606, "s": 8573, "text": "withZoneSameInstant(ZoneId zone)" }, { "code": null, "e": 8702, "s": 8606, "text": "This method returns a copy of this date-time with a different time-zone, retaining the instant." }, { "code": null, "e": 8733, "s": 8702, "text": "withZoneSameLocal(ZoneId zone)" }, { "code": null, "e": 8849, "s": 8733, "text": "This method returns a copy of this date-time with a different time-zone, retaining the local date-time if possible." }, { "code": null, "e": 8883, "s": 8849, "text": "Implementation of parse() method:" }, { "code": null, "e": 8888, "s": 8883, "text": "Java" }, { "code": "// java program to create a new// ZonedDateTime using parse() methodimport java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { String text = \"2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]\"; // creating a new ZonedDateTime object ZonedDateTime zone = ZonedDateTime.parse(text); System.out.println(zone); }}", "e": 9282, "s": 8888, "text": null }, { "code": null, "e": 9333, "s": 9282, "text": "2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]\n" }, { "code": null, "e": 9369, "s": 9333, "text": "Implementation of getZone() method:" }, { "code": null, "e": 9374, "s": 9369, "text": "Java" }, { "code": "// java program to illustrate working of getZone() methodimport java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { String text = \"2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]\"; // Creating a new ZonedDateTime object ZonedDateTime zone = ZonedDateTime.parse(text); // printing the zone of this zonedDateTime object System.out.println(zone.getZone()); }}", "e": 9828, "s": 9374, "text": null }, { "code": null, "e": 9842, "s": 9828, "text": "Asia/Kolkata\n" }, { "code": null, "e": 9887, "s": 9842, "text": "Implementation of plus() and minus() method:" }, { "code": null, "e": 9892, "s": 9887, "text": "Java" }, { "code": "// java program to illustrate working// of plus() and minus() methodimport java.time.Period;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { String text = \"2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]\"; // Creating a new ZonedDateTime object ZonedDateTime zone = ZonedDateTime.parse(text); // printing original value of // this ZonedDateTime object System.out.println(zone); // printing value of this ZonedDateTime // object after substracing two months System.out.println(zone.minus(Period.ofMonths(2))); // printing value of this ZonedDateTime // object after adding two months System.out.println(zone.plus(Period.ofMonths(2))); }}", "e": 10685, "s": 9892, "text": null }, { "code": null, "e": 10836, "s": 10685, "text": "2011-10-02T14:45:30.123456789+05:30[Asia/Kolkata]\n2011-08-02T14:45:30.123456789+05:30[Asia/Kolkata]\n2011-12-02T14:45:30.123456789+05:30[Asia/Kolkata]\n" }, { "code": null, "e": 10867, "s": 10836, "text": "Implementation of of() method:" }, { "code": null, "e": 10872, "s": 10867, "text": "Java" }, { "code": "// Java program to illustrate working of of() methodimport java.time.LocalDate;import java.time.LocalTime;import java.time.ZoneId;import java.time.ZonedDateTime; public class GFG { public static void main(String[] args) { // getting current date LocalDate date = LocalDate.now(); // getting current time LocalTime time = LocalTime.now(); // getting system default zone id ZoneId zoneId = ZoneId.systemDefault(); // creating a new ZonedDateTime object ZonedDateTime zonedatetime = ZonedDateTime.of(date, time, zoneId); System.out.println(zonedatetime); }}", "e": 11519, "s": 10872, "text": null }, { "code": null, "e": 11557, "s": 11519, "text": "2021-03-20T17:09:56.241560Z[Etc/UTC]\n" }, { "code": null, "e": 11575, "s": 11557, "text": "Java-time package" }, { "code": null, "e": 11594, "s": 11575, "text": "Java-ZonedDateTime" }, { "code": null, "e": 11601, "s": 11594, "text": "Picked" }, { "code": null, "e": 11606, "s": 11601, "text": "Java" }, { "code": null, "e": 11611, "s": 11606, "text": "Java" }, { "code": null, "e": 11709, "s": 11611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11724, "s": 11709, "text": "Stream In Java" }, { "code": null, "e": 11745, "s": 11724, "text": "Introduction to Java" }, { "code": null, "e": 11766, "s": 11745, "text": "Constructors in Java" }, { "code": null, "e": 11785, "s": 11766, "text": "Exceptions in Java" }, { "code": null, "e": 11802, "s": 11785, "text": "Generics in Java" }, { "code": null, "e": 11832, "s": 11802, "text": "Functional Interfaces in Java" }, { "code": null, "e": 11848, "s": 11832, "text": "Strings in Java" }, { "code": null, "e": 11874, "s": 11848, "text": "Java Programming Examples" }, { "code": null, "e": 11894, "s": 11874, "text": "Abstraction in Java" } ]
How to convert an enum type variable to a string in C++?
Here we will see how to convert some enum type data to a string in C++. There is no such direct function to do so. But we can create our own function to convert enum to string. We shall create a function that takes an enum value as an argument, and we manually return the enum names as a string from that function. Live Demo #include <iostream> using namespace std; enum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse}; string enum_to_string(Animal type) { switch(type) { case Tiger: return "Tiger"; case Elephant: return "Elephant"; case Bat: return "Bat"; case Dog: return "Dog"; case Cat: return "Cat"; case Mouse: return "Mouse"; default: return "Invalid animal"; } } int main() { cout << "The Animal is : " << enum_to_string(Dog) << " Its number: " << Dog <<endl; cout << "The Animal is : " << enum_to_string(Mouse) << " Its number: " << Mouse << endl; cout << "The Animal is : " << enum_to_string(Elephant) << " Its number: " << Elephant; } The Animal is : Dog Its number: 3 The Animal is : Mouse Its number: 5 The Animal is : Elephant Its number: 1
[ { "code": null, "e": 1239, "s": 1062, "text": "Here we will see how to convert some enum type data to a string in C++. There is no such direct function to do so. But we can create our own function to convert enum to string." }, { "code": null, "e": 1377, "s": 1239, "text": "We shall create a function that takes an enum value as an argument, and we manually return the enum names as a string from that function." }, { "code": null, "e": 1388, "s": 1377, "text": " Live Demo" }, { "code": null, "e": 2132, "s": 1388, "text": "#include <iostream>\nusing namespace std;\n\nenum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse};\n\nstring enum_to_string(Animal type) {\n switch(type) {\n case Tiger:\n return \"Tiger\";\n case Elephant:\n return \"Elephant\";\n case Bat:\n return \"Bat\";\n case Dog:\n return \"Dog\";\n case Cat:\n return \"Cat\";\n case Mouse:\n return \"Mouse\";\n default:\n return \"Invalid animal\";\n }\n}\n\nint main() {\n cout << \"The Animal is : \" << enum_to_string(Dog) << \" Its number: \" << Dog <<endl;\n cout << \"The Animal is : \" << enum_to_string(Mouse) << \" Its number: \" << Mouse << endl;\n cout << \"The Animal is : \" << enum_to_string(Elephant) << \" Its number: \" << Elephant;\n}" }, { "code": null, "e": 2241, "s": 2132, "text": "The Animal is : Dog Its number: 3\nThe Animal is : Mouse Its number: 5\nThe Animal is : Elephant Its number: 1" } ]
Lightning Fast XGBoost on Multiple GPUs | by Rahul Agarwal | Towards Data Science
XGBoost is one of the most used libraries fora data science. At the time XGBoost came into existence, it was lightning fast compared to its nearest rival Python’s Scikit-learn GBM. But as the times have progressed, it has been rivaled by some awesome libraries like LightGBM and Catboost, both on speed as well as accuracy. I, for one, use LightGBM for most of the use cases where I have just got CPU for training. But when I have a GPU or multiple GPUs at my disposal, I still love to train with XGBoost. Why? So I could make use of the excellent GPU Capabilities provided by XGBoost in conjunction with Dask to use XGBoost in both single and multi-GPU mode. How? This post is about running XGBoost on Multi-GPU machines. We are going to be using the UCI Higgs dataset. This is a binary classification problem with 11M rows and 29 columns and can take a considerable time to solve. From the UCI Site: The data has been produced using Monte Carlo simulations. The first 21 features (columns 2–22) are kinematic properties measured by the particle detectors in the accelerator. The last seven features are functions of the first 21 features; these are high-level features derived by physicists to help discriminate between the two classes. There is an interest in using deep learning methods to obviate the need for physicists to manually develop such features. Benchmark results using Bayesian Decision Trees from a standard physics package and 5-layer neural networks are presented in the original paper. The last 500,000 examples are used as a test set. We can load this dataset into memory by using the nifty function that I borrow from this NVidia post. This function downloads the Higgs dataset and creates Dmatrix objects for later XGBoost use. As we have the data loaded, we can train the XGBoost model with CPU for benchmarking purposes. print("Training with CPU ...")param = {}param['objective'] = 'binary:logitraw'param['eval_metric'] = 'error'param['silent'] = 1param['tree_method'] = 'hist'tmp = time.time()cpu_res = {}xgb.train(param, dtrain, num_round, evals=[(dtest, "test")], evals_result=cpu_res)cpu_time = time.time() - tmpprint("CPU Training Time: %s seconds" % (str(cpu_time)))---------------------------------------------------------------CPU Training Time: 717.6483490467072 seconds This code takes 717 seconds, which is around 12 minutes to finish. That is great and commendable, but can we do better? What is great is that we don’t have to change a lot in the above code to be able to use a single GPU for our model building. Why use CPU when we can use GPU? We change the tree_method to gpu_hist print("Training with Single GPU ...")param = {}param['objective'] = 'binary:logitraw'param['eval_metric'] = 'error'param['silent'] = 1param['tree_method'] = 'gpu_hist'tmp = time.time()gpu_res = {}xgb.train(param, dtrain, num_round, evals=[(dtest, "test")], evals_result=gpu_res)gpu_time = time.time() - tmpprint("GPU Training Time: %s seconds" % (str(gpu_time)))----------------------------------------------------------------GPU Training Time: 78.2187008857727 seconds And we achieve a 10x speedup with our model now finishing in 1.3 minutes. That is great, but can we do even better if we have multiple GPUs? I have, for example, 2 GPUs in my machine while the above code utilizes only 1 GPU. With GPU’s getting a lot cheaper now, it is not unusual for clusters to have more than 4 GPUs. So can we use multiple GPUs simultaneously? Two GPUs are always better than one To use MultiGPUs, the process is not so simple as to add a little argument as above, and there are a few steps involved. The first is the difference in Data loading: There are multiple steps in data load as we need dask DMatrix objects to train XGBoost with multiple GPUs. Read the CSV File using Pandas.Create a Dask Dataframe from Pandas Dataframe, andCreate Dask DMatrix Object using dask data frames. Read the CSV File using Pandas. Create a Dask Dataframe from Pandas Dataframe, and Create Dask DMatrix Object using dask data frames. To use Multi-GPU for training XGBoost, we need to use Dask to create a GPU Cluster. This command creates a cluster of our GPUs that could be used by dask by using the client object later. cluster = LocalCUDACluster()client = Client(cluster) We can now load our Dask Dmatrix Objects and define the training parameters. Note nthread beings set to one and tree_method set to gpu_hist ddtrain, ddtest = load_higgs_for_dask(client)param = {}param['objective'] = 'binary:logitraw'param['eval_metric'] = 'error'param['silence'] = 1param['tree_method'] = 'gpu_hist'param['nthread'] = 1 We can now train on Multiple GPUs using: print("Training with Multiple GPUs ...")tmp = time.time()output = xgb.dask.train(client, param, ddtrain, num_boost_round=1000, evals=[(ddtest, 'test')])multigpu_time = time.time() - tmpbst = output['booster']multigpu_res = output['history']print("Multi GPU Training Time: %s seconds" % (str(multigpu_time)))---------------------------------------------------------------Multi GPU Training Time: 50.08211898803711 seconds Please note how the call to xgb.train changes to xgb.dask.train and how it also needs the dask client to work. This took around 0.8 Minutes that is a 1.5x Speedup from Single GPU. I only had 2 GPUs at my disposal, so I can’t test it, but I believe that it increases linearly, i.e. more GPU and more reduction in time. Here are the results of all three setups: Although the difference between Multi and Single CPU looks redundant right now, it will be pretty considerable while running multiple hyperparameter tuning tasks at hand where one might need to run multiple GBM Models with different Hyperparams. Also, this result can change when we scale it to many GPUs. So keep scaling. You can find the complete code for this post on Github. If you are interested in Deep Learning and want to use your GPU for that, I would like to recommend this excellent course on Deep Learning in Computer Vision in the Advanced machine learning specialization. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 233, "s": 172, "text": "XGBoost is one of the most used libraries fora data science." }, { "code": null, "e": 496, "s": 233, "text": "At the time XGBoost came into existence, it was lightning fast compared to its nearest rival Python’s Scikit-learn GBM. But as the times have progressed, it has been rivaled by some awesome libraries like LightGBM and Catboost, both on speed as well as accuracy." }, { "code": null, "e": 678, "s": 496, "text": "I, for one, use LightGBM for most of the use cases where I have just got CPU for training. But when I have a GPU or multiple GPUs at my disposal, I still love to train with XGBoost." }, { "code": null, "e": 683, "s": 678, "text": "Why?" }, { "code": null, "e": 832, "s": 683, "text": "So I could make use of the excellent GPU Capabilities provided by XGBoost in conjunction with Dask to use XGBoost in both single and multi-GPU mode." }, { "code": null, "e": 837, "s": 832, "text": "How?" }, { "code": null, "e": 895, "s": 837, "text": "This post is about running XGBoost on Multi-GPU machines." }, { "code": null, "e": 1055, "s": 895, "text": "We are going to be using the UCI Higgs dataset. This is a binary classification problem with 11M rows and 29 columns and can take a considerable time to solve." }, { "code": null, "e": 1074, "s": 1055, "text": "From the UCI Site:" }, { "code": null, "e": 1728, "s": 1074, "text": "The data has been produced using Monte Carlo simulations. The first 21 features (columns 2–22) are kinematic properties measured by the particle detectors in the accelerator. The last seven features are functions of the first 21 features; these are high-level features derived by physicists to help discriminate between the two classes. There is an interest in using deep learning methods to obviate the need for physicists to manually develop such features. Benchmark results using Bayesian Decision Trees from a standard physics package and 5-layer neural networks are presented in the original paper. The last 500,000 examples are used as a test set." }, { "code": null, "e": 1830, "s": 1728, "text": "We can load this dataset into memory by using the nifty function that I borrow from this NVidia post." }, { "code": null, "e": 1923, "s": 1830, "text": "This function downloads the Higgs dataset and creates Dmatrix objects for later XGBoost use." }, { "code": null, "e": 2018, "s": 1923, "text": "As we have the data loaded, we can train the XGBoost model with CPU for benchmarking purposes." }, { "code": null, "e": 2487, "s": 2018, "text": "print(\"Training with CPU ...\")param = {}param['objective'] = 'binary:logitraw'param['eval_metric'] = 'error'param['silent'] = 1param['tree_method'] = 'hist'tmp = time.time()cpu_res = {}xgb.train(param, dtrain, num_round, evals=[(dtest, \"test\")], evals_result=cpu_res)cpu_time = time.time() - tmpprint(\"CPU Training Time: %s seconds\" % (str(cpu_time)))---------------------------------------------------------------CPU Training Time: 717.6483490467072 seconds" }, { "code": null, "e": 2607, "s": 2487, "text": "This code takes 717 seconds, which is around 12 minutes to finish. That is great and commendable, but can we do better?" }, { "code": null, "e": 2732, "s": 2607, "text": "What is great is that we don’t have to change a lot in the above code to be able to use a single GPU for our model building." }, { "code": null, "e": 2765, "s": 2732, "text": "Why use CPU when we can use GPU?" }, { "code": null, "e": 2803, "s": 2765, "text": "We change the tree_method to gpu_hist" }, { "code": null, "e": 3283, "s": 2803, "text": "print(\"Training with Single GPU ...\")param = {}param['objective'] = 'binary:logitraw'param['eval_metric'] = 'error'param['silent'] = 1param['tree_method'] = 'gpu_hist'tmp = time.time()gpu_res = {}xgb.train(param, dtrain, num_round, evals=[(dtest, \"test\")], evals_result=gpu_res)gpu_time = time.time() - tmpprint(\"GPU Training Time: %s seconds\" % (str(gpu_time)))----------------------------------------------------------------GPU Training Time: 78.2187008857727 seconds" }, { "code": null, "e": 3424, "s": 3283, "text": "And we achieve a 10x speedup with our model now finishing in 1.3 minutes. That is great, but can we do even better if we have multiple GPUs?" }, { "code": null, "e": 3647, "s": 3424, "text": "I have, for example, 2 GPUs in my machine while the above code utilizes only 1 GPU. With GPU’s getting a lot cheaper now, it is not unusual for clusters to have more than 4 GPUs. So can we use multiple GPUs simultaneously?" }, { "code": null, "e": 3683, "s": 3647, "text": "Two GPUs are always better than one" }, { "code": null, "e": 3804, "s": 3683, "text": "To use MultiGPUs, the process is not so simple as to add a little argument as above, and there are a few steps involved." }, { "code": null, "e": 3849, "s": 3804, "text": "The first is the difference in Data loading:" }, { "code": null, "e": 3956, "s": 3849, "text": "There are multiple steps in data load as we need dask DMatrix objects to train XGBoost with multiple GPUs." }, { "code": null, "e": 4088, "s": 3956, "text": "Read the CSV File using Pandas.Create a Dask Dataframe from Pandas Dataframe, andCreate Dask DMatrix Object using dask data frames." }, { "code": null, "e": 4120, "s": 4088, "text": "Read the CSV File using Pandas." }, { "code": null, "e": 4171, "s": 4120, "text": "Create a Dask Dataframe from Pandas Dataframe, and" }, { "code": null, "e": 4222, "s": 4171, "text": "Create Dask DMatrix Object using dask data frames." }, { "code": null, "e": 4410, "s": 4222, "text": "To use Multi-GPU for training XGBoost, we need to use Dask to create a GPU Cluster. This command creates a cluster of our GPUs that could be used by dask by using the client object later." }, { "code": null, "e": 4463, "s": 4410, "text": "cluster = LocalCUDACluster()client = Client(cluster)" }, { "code": null, "e": 4603, "s": 4463, "text": "We can now load our Dask Dmatrix Objects and define the training parameters. Note nthread beings set to one and tree_method set to gpu_hist" }, { "code": null, "e": 4800, "s": 4603, "text": "ddtrain, ddtest = load_higgs_for_dask(client)param = {}param['objective'] = 'binary:logitraw'param['eval_metric'] = 'error'param['silence'] = 1param['tree_method'] = 'gpu_hist'param['nthread'] = 1" }, { "code": null, "e": 4841, "s": 4800, "text": "We can now train on Multiple GPUs using:" }, { "code": null, "e": 5262, "s": 4841, "text": "print(\"Training with Multiple GPUs ...\")tmp = time.time()output = xgb.dask.train(client, param, ddtrain, num_boost_round=1000, evals=[(ddtest, 'test')])multigpu_time = time.time() - tmpbst = output['booster']multigpu_res = output['history']print(\"Multi GPU Training Time: %s seconds\" % (str(multigpu_time)))---------------------------------------------------------------Multi GPU Training Time: 50.08211898803711 seconds" }, { "code": null, "e": 5373, "s": 5262, "text": "Please note how the call to xgb.train changes to xgb.dask.train and how it also needs the dask client to work." }, { "code": null, "e": 5580, "s": 5373, "text": "This took around 0.8 Minutes that is a 1.5x Speedup from Single GPU. I only had 2 GPUs at my disposal, so I can’t test it, but I believe that it increases linearly, i.e. more GPU and more reduction in time." }, { "code": null, "e": 5622, "s": 5580, "text": "Here are the results of all three setups:" }, { "code": null, "e": 5868, "s": 5622, "text": "Although the difference between Multi and Single CPU looks redundant right now, it will be pretty considerable while running multiple hyperparameter tuning tasks at hand where one might need to run multiple GBM Models with different Hyperparams." }, { "code": null, "e": 5928, "s": 5868, "text": "Also, this result can change when we scale it to many GPUs." }, { "code": null, "e": 5945, "s": 5928, "text": "So keep scaling." }, { "code": null, "e": 6001, "s": 5945, "text": "You can find the complete code for this post on Github." }, { "code": null, "e": 6208, "s": 6001, "text": "If you are interested in Deep Learning and want to use your GPU for that, I would like to recommend this excellent course on Deep Learning in Computer Vision in the Advanced machine learning specialization." }, { "code": null, "e": 6471, "s": 6208, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz" } ]
Iterative Segment Tree (Range Minimum Query) - GeeksforGeeks
23 Jun, 2021 We have discussed recursive segment tree implementation. In this post, iterative implementation is discussed.Let us consider the following problem understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the minimum of elements from index l to r where 0 <= l <= r <= n-1 2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1.Examples: Input : 2, 6, 7, 5, 18, 86, 54, 2 minimum(2, 7) update(3, 4) minimum(2, 6) Output : Minimum in range 2 to 7 is 2. Minimum in range 2 to 6 is 4. The iterative version of the segment tree basically uses the fact, that for an index i, left child = 2 * i and right child = 2 * i + 1 in the tree. The parent for an index i in the segment tree array can be found by parent = i / 2. Thus we can easily travel up and down through the levels of the tree one by one. At first we compute the minimum in the ranges while constructing the tree starting from the leaf nodes and climbing up through the levels one by one. We use the same concept while processing the queries for finding the minimum in a range. Since there are (log n) levels in the worst case, so querying takes log n time. For update of a particular index to a given value we start updating the segment tree starting from the leaf nodes and update all those nodes which are affected by the updation of the current node by gradually moving up through the levels at every iteration. Updation also takes log n time because there we have to update all the levels starting from the leaf node where we update the exact value at the exact index given by the user. C++ Java Python3 C# Javascript // CPP Program to implement iterative segment// tree.#include <bits/stdc++.h>#define ll long long using namespace std; void construct_segment_tree(vector<int>& segtree, vector<int> &a, int n){ // assign values to leaves of the segment tree for (int i = 0; i < n; i++) segtree[n + i] = a[i]; /* assign values to internal nodes to compute minimum in a given range */ for (int i = n - 1; i >= 1; i--) segtree[i] = min(segtree[2 * i], segtree[2 * i + 1]);} void update(vector<int>& segtree, int pos, int value, int n){ // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = min(segtree[2 * pos], segtree[2 * pos + 1]); }} int range_query(vector<int>& segtree, int left, int right, int n){ /* Basically the left and right indices will move towards right and left respectively and with every each next higher level and compute the minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value int mi = (int)1e9; while (left < right) { // if left index in odd if (left & 1) { mi = min(mi, segtree[left]); // make left index even left++; } // if right index in odd if (right & 1) { // make right index even right--; mi = min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi;} // Driver codeint main(){ vector<int> a = { 2, 6, 10, 4, 7, 28, 9, 11, 6, 33 }; int n = a.size(); /* Construct the segment tree by assigning the values to the internal nodes*/ vector<int> segtree(2 * n); construct_segment_tree(segtree, a, n); // compute minimum in the range left to right int left = 0, right = 5; cout << "Minimum in range " << left << " to " << right << " is "<< range_query(segtree, left, right + 1, n) << "\n"; // update the value of index 3 to 1 int index = 3, value = 1; // a[3] = 1; // Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33} update(segtree, index, value, n); // point update // compute minimum in the range left to right left = 2, right = 6; cout << "Minimum in range " << left << " to " << right << " is " << range_query(segtree, left, right + 1, n) << "\n"; return 0;} // Java Program to implement iterative segment// tree.import java.io.*;import java.util.*; class GFG{ static void construct_segment_tree(int[] segtree, int[] a, int n) { // assign values to leaves of the segment tree for (int i = 0; i < n; i++) segtree[n + i] = a[i]; /* * assign values to internal nodes * to compute minimum in a given range */ for (int i = n - 1; i >= 1; i--) segtree[i] = Math.min(segtree[2 * i], segtree[2 * i + 1]); } static void update(int[] segtree, int pos, int value, int n) { // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = Math.min(segtree[2 * pos], segtree[2 * pos + 1]); } } static int range_query(int[] segtree, int left, int right, int n) { /* * Basically the left and right indices will move * towards right and left respectively and with * every each next higher level and compute the * minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value int mi = (int) 1e9; while (left < right) { // if left index in odd if ((left & 1) == 1) { mi = Math.min(mi, segtree[left]); // make left index even left++; } // if right index in odd if ((right & 1) == 1) { // make right index even right--; mi = Math.min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi; } // Driver Code public static void main(String[] args) { int[] a = {2, 6, 10, 4, 7, 28, 9, 11, 6, 33}; int n = a.length; /* * Construct the segment tree by assigning * the values to the internal nodes */ int[] segtree = new int[2 * n]; construct_segment_tree(segtree, a, n); // compute minimum in the range left to right int left = 0, right = 5; System.out.printf("Minimum in range %d to %d is %d\n", left, right, range_query(segtree, left, right + 1, n)); // update the value of index 3 to 1 int index = 3, value = 1; // a[3] = 1; // Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33} update(segtree, index, value, n); // point update // compute minimum in the range left to right left = 2; right = 6; System.out.printf("Minimum in range %d to %d is %d\n", left, right, range_query(segtree, left, right + 1, n)); }} // This code is contributed by// sanjeev2552 # Python3 program to implement# iterative segment tree.def construct_segment_tree(segtree, a, n): # assign values to leaves of # the segment tree for i in range(n): segtree[n + i] = a[i]; # assign values to remaining nodes # to compute minimum in a given range for i in range(n - 1, 0, -1): segtree[i] = min(segtree[2 * i], segtree[2 * i + 1]) def range_query(segtree, left, right, n): left += n right += n """ Basically the left and right indices will move towards right and left respectively and with every each next higher level and compute the minimum at each height change the index to leaf node first """ mi = 1e9 # initialize minimum to a very high value while (left < right): if (left & 1): # if left index in odd mi = min(mi, segtree[left]) left = left + 1 if (right & 1): # if right index in odd right -= 1 mi = min(mi, segtree[right]) # move to the next higher level left = left // 2 right = right // 2 return mi def update(segtree, pos, value, n): # change the index to leaf node first pos += n # update the value at the leaf node # at the exact index segtree[pos] = value while (pos > 1): # move up one level at a time in the tree pos >>= 1; # update the values in the nodes # in the next higher level segtree[pos] = min(segtree[2 * pos], segtree[2 * pos + 1]) # Driver Code # Elements in lista = [2, 6, 10, 4, 7, 28, 9, 11, 6, 33]n = len(a) # Construct the segment tree by assigning# the values to the internal nodessegtree = [0 for i in range(2 * n)]construct_segment_tree(segtree, a, n);left = 0right = 5 #compute minimum in the range left to rightprint ("Minimum in range", left, "to", right, "is", range_query(segtree, left, right + 1, n)) # update the value of index 3 to 1index = 3value = 1 # a[3] = 1;# Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33}update(segtree, index, value, n); # point updateleft = 2right = 6 # compute minimum in the range left to rightprint("Minimum in range", left, "to", right, "is", range_query(segtree, left, right + 1, n)) # This code is contributed by sarthak Raghuwanshi // C# Program to implement iterative segment// tree.using System; class GFG{ static void construct_segment_tree(int[] segtree, int[] a, int n) { // assign values to leaves of the segment tree for (int i = 0; i < n; i++) segtree[n + i] = a[i]; /* * assign values to internal nodes * to compute minimum in a given range */ for (int i = n - 1; i >= 1; i--) segtree[i] = Math.Min(segtree[2 * i], segtree[2 * i + 1]); } static void update(int[] segtree, int pos, int value, int n) { // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = Math.Min(segtree[2 * pos], segtree[2 * pos + 1]); } } static int range_query(int[] segtree, int left, int right, int n) { /* * Basically the left and right indices will move * towards right and left respectively and with * every each next higher level and compute the * minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value int mi = (int) 1e9; while (left < right) { // if left index in odd if ((left & 1) == 1) { mi = Math.Min(mi, segtree[left]); // make left index even left++; } // if right index in odd if ((right & 1) == 1) { // make right index even right--; mi = Math.Min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi; } // Driver Code public static void Main(String[] args) { int[] a = {2, 6, 10, 4, 7, 28, 9, 11, 6, 33}; int n = a.Length; /* * Construct the segment tree by assigning * the values to the internal nodes */ int[] segtree = new int[2 * n]; construct_segment_tree(segtree, a, n); // compute minimum in the range left to right int left = 0, right = 5; Console.Write("Minimum in range {0} to {1} is {2}\n", left, right, range_query(segtree, left, right + 1, n)); // update the value of index 3 to 1 int index = 3, value = 1; // a[3] = 1; // Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33} update(segtree, index, value, n); // point update // compute minimum in the range left to right left = 2; right = 6; Console.Write("Minimum in range {0} to {1} is {2}\n", left, right, range_query(segtree, left, right + 1, n)); }} // This code is contributed by Rajput-Ji <script> // Javascript Program to implement iterative segment// tree.function construct_segment_tree(segtree, a, n){ // assign values to leaves of the segment tree for (var i = 0; i < n; i++) segtree[n + i] = a[i]; /* * assign values to internal nodes * to compute minimum in a given range */ for (var i = n - 1; i >= 1; i--) segtree[i] = Math.min(segtree[2 * i], segtree[2 * i + 1]);}function update(segtree, pos, value, n){ // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = Math.min(segtree[2 * pos], segtree[2 * pos + 1]); }}function range_query(segtree, left, right, n){ /* * Basically the left and right indices will move * towards right and left respectively and with * every each next higher level and compute the * minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value var mi = 1000000000; while (left < right) { // if left index in odd if ((left & 1) == 1) { mi = Math.min(mi, segtree[left]); // make left index even left++; } // if right index in odd if ((right & 1) == 1) { // make right index even right--; mi = Math.min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi;} // Driver Codevar a = [2, 6, 10, 4, 7, 28, 9, 11, 6, 33];var n = a.length;/** Construct the segment tree by assigning* the values to the internal nodes*/var segtree = Array(2*n).fill(0);construct_segment_tree(segtree, a, n); // compute minimum in the range left to rightvar left = 0, right = 5;document.write(`Minimum in range ${left} to ${right} is ${range_query(segtree,left, right + 1, n)}<br>`) // update the value of index 3 to 1var index = 3, value = 1; // a[3] = 1;// Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33}update(segtree, index, value, n); // point update // compute minimum in the range left to rightleft = 2;right = 6;document.write(`Minimum in range ${left} to ${right} is ${range_query(segtree, left, right + 1, n)}<br>`); // This code is contributed by rutvik_56.</script> Minimum in range 0 to 5 is 2 Minimum in range 2 to 6 is 1 Time Complexity :(n log n) Auxiliary Space : (n) Sarthak Raghuwanshi sanjeev2552 Rajput-Ji rutvik_56 array-range-queries Segment-Tree Advanced Data Structure Tree Tree Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extendible Hashing (Dynamic approach to DBMS) Ternary Search Tree Proof that Dominant Set of a Graph is NP-Complete 2-3 Trees | (Search, Insert and Deletion) Advantages of Trie Data Structure Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 24097, "s": 24069, "text": "\n23 Jun, 2021" }, { "code": null, "e": 24525, "s": 24097, "text": "We have discussed recursive segment tree implementation. In this post, iterative implementation is discussed.Let us consider the following problem understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the minimum of elements from index l to r where 0 <= l <= r <= n-1 2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1.Examples: " }, { "code": null, "e": 24705, "s": 24525, "text": "Input : 2, 6, 7, 5, 18, 86, 54, 2\n minimum(2, 7) \n update(3, 4)\n minimum(2, 6) \nOutput : Minimum in range 2 to 7 is 2.\n Minimum in range 2 to 6 is 4." }, { "code": null, "e": 25775, "s": 24707, "text": "The iterative version of the segment tree basically uses the fact, that for an index i, left child = 2 * i and right child = 2 * i + 1 in the tree. The parent for an index i in the segment tree array can be found by parent = i / 2. Thus we can easily travel up and down through the levels of the tree one by one. At first we compute the minimum in the ranges while constructing the tree starting from the leaf nodes and climbing up through the levels one by one. We use the same concept while processing the queries for finding the minimum in a range. Since there are (log n) levels in the worst case, so querying takes log n time. For update of a particular index to a given value we start updating the segment tree starting from the leaf nodes and update all those nodes which are affected by the updation of the current node by gradually moving up through the levels at every iteration. Updation also takes log n time because there we have to update all the levels starting from the leaf node where we update the exact value at the exact index given by the user. " }, { "code": null, "e": 25779, "s": 25775, "text": "C++" }, { "code": null, "e": 25784, "s": 25779, "text": "Java" }, { "code": null, "e": 25792, "s": 25784, "text": "Python3" }, { "code": null, "e": 25795, "s": 25792, "text": "C#" }, { "code": null, "e": 25806, "s": 25795, "text": "Javascript" }, { "code": "// CPP Program to implement iterative segment// tree.#include <bits/stdc++.h>#define ll long long using namespace std; void construct_segment_tree(vector<int>& segtree, vector<int> &a, int n){ // assign values to leaves of the segment tree for (int i = 0; i < n; i++) segtree[n + i] = a[i]; /* assign values to internal nodes to compute minimum in a given range */ for (int i = n - 1; i >= 1; i--) segtree[i] = min(segtree[2 * i], segtree[2 * i + 1]);} void update(vector<int>& segtree, int pos, int value, int n){ // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = min(segtree[2 * pos], segtree[2 * pos + 1]); }} int range_query(vector<int>& segtree, int left, int right, int n){ /* Basically the left and right indices will move towards right and left respectively and with every each next higher level and compute the minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value int mi = (int)1e9; while (left < right) { // if left index in odd if (left & 1) { mi = min(mi, segtree[left]); // make left index even left++; } // if right index in odd if (right & 1) { // make right index even right--; mi = min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi;} // Driver codeint main(){ vector<int> a = { 2, 6, 10, 4, 7, 28, 9, 11, 6, 33 }; int n = a.size(); /* Construct the segment tree by assigning the values to the internal nodes*/ vector<int> segtree(2 * n); construct_segment_tree(segtree, a, n); // compute minimum in the range left to right int left = 0, right = 5; cout << \"Minimum in range \" << left << \" to \" << right << \" is \"<< range_query(segtree, left, right + 1, n) << \"\\n\"; // update the value of index 3 to 1 int index = 3, value = 1; // a[3] = 1; // Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33} update(segtree, index, value, n); // point update // compute minimum in the range left to right left = 2, right = 6; cout << \"Minimum in range \" << left << \" to \" << right << \" is \" << range_query(segtree, left, right + 1, n) << \"\\n\"; return 0;}", "e": 28694, "s": 25806, "text": null }, { "code": "// Java Program to implement iterative segment// tree.import java.io.*;import java.util.*; class GFG{ static void construct_segment_tree(int[] segtree, int[] a, int n) { // assign values to leaves of the segment tree for (int i = 0; i < n; i++) segtree[n + i] = a[i]; /* * assign values to internal nodes * to compute minimum in a given range */ for (int i = n - 1; i >= 1; i--) segtree[i] = Math.min(segtree[2 * i], segtree[2 * i + 1]); } static void update(int[] segtree, int pos, int value, int n) { // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = Math.min(segtree[2 * pos], segtree[2 * pos + 1]); } } static int range_query(int[] segtree, int left, int right, int n) { /* * Basically the left and right indices will move * towards right and left respectively and with * every each next higher level and compute the * minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value int mi = (int) 1e9; while (left < right) { // if left index in odd if ((left & 1) == 1) { mi = Math.min(mi, segtree[left]); // make left index even left++; } // if right index in odd if ((right & 1) == 1) { // make right index even right--; mi = Math.min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi; } // Driver Code public static void main(String[] args) { int[] a = {2, 6, 10, 4, 7, 28, 9, 11, 6, 33}; int n = a.length; /* * Construct the segment tree by assigning * the values to the internal nodes */ int[] segtree = new int[2 * n]; construct_segment_tree(segtree, a, n); // compute minimum in the range left to right int left = 0, right = 5; System.out.printf(\"Minimum in range %d to %d is %d\\n\", left, right, range_query(segtree, left, right + 1, n)); // update the value of index 3 to 1 int index = 3, value = 1; // a[3] = 1; // Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33} update(segtree, index, value, n); // point update // compute minimum in the range left to right left = 2; right = 6; System.out.printf(\"Minimum in range %d to %d is %d\\n\", left, right, range_query(segtree, left, right + 1, n)); }} // This code is contributed by// sanjeev2552", "e": 32011, "s": 28694, "text": null }, { "code": "# Python3 program to implement# iterative segment tree.def construct_segment_tree(segtree, a, n): # assign values to leaves of # the segment tree for i in range(n): segtree[n + i] = a[i]; # assign values to remaining nodes # to compute minimum in a given range for i in range(n - 1, 0, -1): segtree[i] = min(segtree[2 * i], segtree[2 * i + 1]) def range_query(segtree, left, right, n): left += n right += n \"\"\" Basically the left and right indices will move towards right and left respectively and with every each next higher level and compute the minimum at each height change the index to leaf node first \"\"\" mi = 1e9 # initialize minimum to a very high value while (left < right): if (left & 1): # if left index in odd mi = min(mi, segtree[left]) left = left + 1 if (right & 1): # if right index in odd right -= 1 mi = min(mi, segtree[right]) # move to the next higher level left = left // 2 right = right // 2 return mi def update(segtree, pos, value, n): # change the index to leaf node first pos += n # update the value at the leaf node # at the exact index segtree[pos] = value while (pos > 1): # move up one level at a time in the tree pos >>= 1; # update the values in the nodes # in the next higher level segtree[pos] = min(segtree[2 * pos], segtree[2 * pos + 1]) # Driver Code # Elements in lista = [2, 6, 10, 4, 7, 28, 9, 11, 6, 33]n = len(a) # Construct the segment tree by assigning# the values to the internal nodessegtree = [0 for i in range(2 * n)]construct_segment_tree(segtree, a, n);left = 0right = 5 #compute minimum in the range left to rightprint (\"Minimum in range\", left, \"to\", right, \"is\", range_query(segtree, left, right + 1, n)) # update the value of index 3 to 1index = 3value = 1 # a[3] = 1;# Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33}update(segtree, index, value, n); # point updateleft = 2right = 6 # compute minimum in the range left to rightprint(\"Minimum in range\", left, \"to\", right, \"is\", range_query(segtree, left, right + 1, n)) # This code is contributed by sarthak Raghuwanshi", "e": 34426, "s": 32011, "text": null }, { "code": "// C# Program to implement iterative segment// tree.using System; class GFG{ static void construct_segment_tree(int[] segtree, int[] a, int n) { // assign values to leaves of the segment tree for (int i = 0; i < n; i++) segtree[n + i] = a[i]; /* * assign values to internal nodes * to compute minimum in a given range */ for (int i = n - 1; i >= 1; i--) segtree[i] = Math.Min(segtree[2 * i], segtree[2 * i + 1]); } static void update(int[] segtree, int pos, int value, int n) { // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = Math.Min(segtree[2 * pos], segtree[2 * pos + 1]); } } static int range_query(int[] segtree, int left, int right, int n) { /* * Basically the left and right indices will move * towards right and left respectively and with * every each next higher level and compute the * minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value int mi = (int) 1e9; while (left < right) { // if left index in odd if ((left & 1) == 1) { mi = Math.Min(mi, segtree[left]); // make left index even left++; } // if right index in odd if ((right & 1) == 1) { // make right index even right--; mi = Math.Min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi; } // Driver Code public static void Main(String[] args) { int[] a = {2, 6, 10, 4, 7, 28, 9, 11, 6, 33}; int n = a.Length; /* * Construct the segment tree by assigning * the values to the internal nodes */ int[] segtree = new int[2 * n]; construct_segment_tree(segtree, a, n); // compute minimum in the range left to right int left = 0, right = 5; Console.Write(\"Minimum in range {0} to {1} is {2}\\n\", left, right, range_query(segtree, left, right + 1, n)); // update the value of index 3 to 1 int index = 3, value = 1; // a[3] = 1; // Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33} update(segtree, index, value, n); // point update // compute minimum in the range left to right left = 2; right = 6; Console.Write(\"Minimum in range {0} to {1} is {2}\\n\", left, right, range_query(segtree, left, right + 1, n)); }} // This code is contributed by Rajput-Ji", "e": 37747, "s": 34426, "text": null }, { "code": "<script> // Javascript Program to implement iterative segment// tree.function construct_segment_tree(segtree, a, n){ // assign values to leaves of the segment tree for (var i = 0; i < n; i++) segtree[n + i] = a[i]; /* * assign values to internal nodes * to compute minimum in a given range */ for (var i = n - 1; i >= 1; i--) segtree[i] = Math.min(segtree[2 * i], segtree[2 * i + 1]);}function update(segtree, pos, value, n){ // change the index to leaf node first pos += n; // update the value at the leaf node // at the exact index segtree[pos] = value; while (pos > 1) { // move up one level at a time in the tree pos >>= 1; // update the values in the nodes in // the next higher level segtree[pos] = Math.min(segtree[2 * pos], segtree[2 * pos + 1]); }}function range_query(segtree, left, right, n){ /* * Basically the left and right indices will move * towards right and left respectively and with * every each next higher level and compute the * minimum at each height. */ // change the index to leaf node first left += n; right += n; // initialize minimum to a very high value var mi = 1000000000; while (left < right) { // if left index in odd if ((left & 1) == 1) { mi = Math.min(mi, segtree[left]); // make left index even left++; } // if right index in odd if ((right & 1) == 1) { // make right index even right--; mi = Math.min(mi, segtree[right]); } // move to the next higher level left /= 2; right /= 2; } return mi;} // Driver Codevar a = [2, 6, 10, 4, 7, 28, 9, 11, 6, 33];var n = a.length;/** Construct the segment tree by assigning* the values to the internal nodes*/var segtree = Array(2*n).fill(0);construct_segment_tree(segtree, a, n); // compute minimum in the range left to rightvar left = 0, right = 5;document.write(`Minimum in range ${left} to ${right} is ${range_query(segtree,left, right + 1, n)}<br>`) // update the value of index 3 to 1var index = 3, value = 1; // a[3] = 1;// Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33}update(segtree, index, value, n); // point update // compute minimum in the range left to rightleft = 2;right = 6;document.write(`Minimum in range ${left} to ${right} is ${range_query(segtree, left, right + 1, n)}<br>`); // This code is contributed by rutvik_56.</script>", "e": 40339, "s": 37747, "text": null }, { "code": null, "e": 40397, "s": 40339, "text": "Minimum in range 0 to 5 is 2\nMinimum in range 2 to 6 is 1" }, { "code": null, "e": 40449, "s": 40399, "text": "Time Complexity :(n log n) Auxiliary Space : (n) " }, { "code": null, "e": 40469, "s": 40449, "text": "Sarthak Raghuwanshi" }, { "code": null, "e": 40481, "s": 40469, "text": "sanjeev2552" }, { "code": null, "e": 40491, "s": 40481, "text": "Rajput-Ji" }, { "code": null, "e": 40501, "s": 40491, "text": "rutvik_56" }, { "code": null, "e": 40521, "s": 40501, "text": "array-range-queries" }, { "code": null, "e": 40534, "s": 40521, "text": "Segment-Tree" }, { "code": null, "e": 40558, "s": 40534, "text": "Advanced Data Structure" }, { "code": null, "e": 40563, "s": 40558, "text": "Tree" }, { "code": null, "e": 40568, "s": 40563, "text": "Tree" }, { "code": null, "e": 40581, "s": 40568, "text": "Segment-Tree" }, { "code": null, "e": 40679, "s": 40581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40688, "s": 40679, "text": "Comments" }, { "code": null, "e": 40701, "s": 40688, "text": "Old Comments" }, { "code": null, "e": 40747, "s": 40701, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 40767, "s": 40747, "text": "Ternary Search Tree" }, { "code": null, "e": 40817, "s": 40767, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 40859, "s": 40817, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 40893, "s": 40859, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 40943, "s": 40893, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 40978, "s": 40943, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 41012, "s": 40978, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 41053, "s": 41012, "text": "Inorder Tree Traversal without Recursion" } ]
Designing Non-Deterministic Finite Automata (Set 5) - GeeksforGeeks
20 Nov, 2019 Prerequisite: Finite Automata IntroductionIn this article, we will see some designing of Non-Deterministic Finite Automata (NFA). Problem-1: Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language contain ‘ab’ as the substring.Explanation: The desired language will be like: L1 = {ab, abba, abaa, ...........} Here as we can see that each string of the above language contains ‘ab’ as the substring but the below language is not accepted by this NFA because some of the string of below language does not contain ‘ab’ as the substring. L2 = {bb, b, bbbb, .............} The state transition diagram of the desired language will be like below:In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it either remains in the state of itself or transit to a state ‘Y’ and on getting ‘b’ as the input it remains in the state of itself. The state ‘Y’ on getting ‘b’ as the input it transmits to a final state ‘Z’. The final state ‘Z’ on getting either ‘a’ or ‘b’ as the input it remains in the state of itself. Problem-2: Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language is not containing ‘ab’ as the substring.Explanation: The desired language will be like: L1 = {b, bb, bbbb, ...........} Here as we can see that each string of the above language is not containing ‘ab’ as the substring But the below language is not accepted by this NFA because some of the string of below language is containing ‘ab’ as the substring. L2 = {ab, aba, ababaab..............} The state transition diagram of the desired language will be like below:In the above NFA, the initial and final state ‘X’ on getting ‘b’ as the input it remains in the state of itself and on getting ‘a’ as the input it transits to another final state ‘Y’. Another final state ‘Y’ on getting ‘a’ as the input it remains in the state of itself. GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Page Replacement Algorithms in Operating Systems Normal Forms in DBMS LRU Cache Implementation Differences between TCP and UDP Data encryption standard (DES) | Set 1 Difference between DFA and NFA Conversion from NFA to DFA Turing Machine in TOC Introduction of Pushdown Automata Minimization of DFA
[ { "code": null, "e": 24270, "s": 24242, "text": "\n20 Nov, 2019" }, { "code": null, "e": 24400, "s": 24270, "text": "Prerequisite: Finite Automata IntroductionIn this article, we will see some designing of Non-Deterministic Finite Automata (NFA)." }, { "code": null, "e": 24595, "s": 24400, "text": "Problem-1: Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language contain ‘ab’ as the substring.Explanation: The desired language will be like:" }, { "code": null, "e": 24630, "s": 24595, "text": "L1 = {ab, abba, abaa, ...........}" }, { "code": null, "e": 24855, "s": 24630, "text": "Here as we can see that each string of the above language contains ‘ab’ as the substring but the below language is not accepted by this NFA because some of the string of below language does not contain ‘ab’ as the substring." }, { "code": null, "e": 24889, "s": 24855, "text": "L2 = {bb, b, bbbb, .............}" }, { "code": null, "e": 25163, "s": 24889, "text": "The state transition diagram of the desired language will be like below:In the above NFA, the initial state ‘X’ on getting ‘a’ as the input it either remains in the state of itself or transit to a state ‘Y’ and on getting ‘b’ as the input it remains in the state of itself." }, { "code": null, "e": 25337, "s": 25163, "text": "The state ‘Y’ on getting ‘b’ as the input it transmits to a final state ‘Z’. The final state ‘Z’ on getting either ‘a’ or ‘b’ as the input it remains in the state of itself." }, { "code": null, "e": 25542, "s": 25337, "text": "Problem-2: Construction of a minimal NFA accepting a set of strings over {a, b} in which each string of the language is not containing ‘ab’ as the substring.Explanation: The desired language will be like:" }, { "code": null, "e": 25574, "s": 25542, "text": "L1 = {b, bb, bbbb, ...........}" }, { "code": null, "e": 25805, "s": 25574, "text": "Here as we can see that each string of the above language is not containing ‘ab’ as the substring But the below language is not accepted by this NFA because some of the string of below language is containing ‘ab’ as the substring." }, { "code": null, "e": 25843, "s": 25805, "text": "L2 = {ab, aba, ababaab..............}" }, { "code": null, "e": 26099, "s": 25843, "text": "The state transition diagram of the desired language will be like below:In the above NFA, the initial and final state ‘X’ on getting ‘b’ as the input it remains in the state of itself and on getting ‘a’ as the input it transits to another final state ‘Y’." }, { "code": null, "e": 26186, "s": 26099, "text": "Another final state ‘Y’ on getting ‘a’ as the input it remains in the state of itself." }, { "code": null, "e": 26194, "s": 26186, "text": "GATE CS" }, { "code": null, "e": 26227, "s": 26194, "text": "Theory of Computation & Automata" }, { "code": null, "e": 26325, "s": 26227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26334, "s": 26325, "text": "Comments" }, { "code": null, "e": 26347, "s": 26334, "text": "Old Comments" }, { "code": null, "e": 26396, "s": 26347, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26417, "s": 26396, "text": "Normal Forms in DBMS" }, { "code": null, "e": 26442, "s": 26417, "text": "LRU Cache Implementation" }, { "code": null, "e": 26474, "s": 26442, "text": "Differences between TCP and UDP" }, { "code": null, "e": 26513, "s": 26474, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 26544, "s": 26513, "text": "Difference between DFA and NFA" }, { "code": null, "e": 26571, "s": 26544, "text": "Conversion from NFA to DFA" }, { "code": null, "e": 26593, "s": 26571, "text": "Turing Machine in TOC" }, { "code": null, "e": 26627, "s": 26593, "text": "Introduction of Pushdown Automata" } ]
Reshape NumPy Array
20 Jan, 2022 NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Numpy is basically used for creating array of n dimensions.Reshaping numpy array simply means changing the shape of the given array, shape basically tells the number of elements and dimension of array, by reshaping an array we can add or remove dimensions or change number of elements in each dimension.In order to reshape a numpy array we use reshape method with the given array. Syntax : array.reshape(shape)Argument : It take tuple as argument, tuple is the new shape to be formedReturn : It returns numpy.ndarray Note : We can also use np.reshape(array, shape) command to reshape the arrayReshaping : 1-D to 2D In this example we will reshape the 1-D array of shape (1, n) to 2-D array of shape (N, M) here M should be equal to the n/N there for N should be factor of n. Python3 # importing numpyimport numpy as np # creating a numpy arrayarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) # printing arrayprint("Array : " + str(array)) # length of arrayn = array.size # N-D array N dimensionN = 4 # calculating MM = n//N # reshaping numpy array# converting it to 2-D from 1-D arrayreshaped1 = array.reshape((N, M)) # printing reshaped arrayprint("First Reshaped Array : ")print(reshaped1) # creating another reshaped arrayreshaped2 = np.reshape(array, (2, 8)) # printing reshaped arrayprint("Second Reshaped Array : ")print(reshaped2) Output : Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] First Reshaped Array : [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] Second Reshaped Array : [[ 1 2 3 4 5 6 7 8] [ 9 10 11 12 13 14 15 16]] Reshaping : 1-D to 3-D In this we will see how we can reshape a 1-D array to 3-D dimension array. A 3-D array is the 1-D array of 2-D arrays. Python3 # importing numpyimport numpy as np # creating a numpy arrayarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) # printing arrayprint("Array : " + str(array)) # reshaping numpy array# converting it to 3-D from 1-D arrayreshaped = array.reshape((2, 2, 4)) # printing reshaped arrayprint("Reshaped 3-D Array : ")print(reshaped) Output : Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] Reshaped 3-D Array : [[[ 1 2 3 4] [ 5 6 7 8]] [[ 9 10 11 12] [13 14 15 16]]] Reshaping N-D to 1-D array In this example we will see how we can reshape a 2-D or 3-D array to form a 1-D array. We can also use reshape(-1) to do this, here -1 is the unknown dimension. Python3 # importing numpyimport numpy as np # creating a numpy arrayarray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # printing arrayprint(" 2-D Array : ")print(array) # reshaping numpy array# converting it to 1-D from 2-D arrayreshaped = array.reshape((9)) # or we can use unknown dimension# reshaped = array.reshape((-1)) # printing reshaped arrayprint("Reshaped 1-D Array : ")print(reshaped) Output : 2-D Array : [[1 2 3] [4 5 6] [7 8 9]] Reshaped 1-D Array : [[1 2 3 4 5 6 7 8 9]] Reshaping using unknown dimension We can reshape a array although we don’t know all the new dimensions by using -1 as one of the dimension, but we should know all the other dimension to use unknown dimension Python3 # importing numpyimport numpy as np # creating a numpy arrayarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) # printing arrayprint("Array : " + str(array)) # reshaping numpy array# converting it to 3-D from 1-D arrayreshaped1 = array.reshape((2, 2, -1)) # printing reshaped arrayprint("First Reshaped Array : ")print(reshaped1) # converting it to 2-D arrayreshaped2 = array.reshape((4, -1)) # printing reshaped arrayprint("Second Reshaped Array : ")print(reshaped2) Output : Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] First Reshaped Array : [[[ 1 2 3 4] [ 5 6 7 8]] [[ 9 10 11 12] [13 14 15 16]]] Second Reshaped Array : [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] Errors Occur during reshaping When we try to reshape a array to a shape which is not mathematically possible then value error is generated saying can not reshape the array. For example when we try to reshape 1-D array with 4 elements into a 2-D array of dimension(3, 3) is not possible as new array requires 9 elements Python3 # importing numpyimport numpy as np # creating a numpy arrayarray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # printing arrayprint(" 2-D Array : ")print(array) # reshaping numpy array# converting it to 1-D from 2-D array# reshaping it into 1, 5reshaped = array.reshape((1, 5)) # or we can use # printing reshaped arrayprint("Reshaped 1-D Array : ")print(reshaped) ValueError: cannot reshape array of size 9 into shape (1, 5) adnanirshad158 sweetyty rkbhola5 Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python 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": "\n20 Jan, 2022" }, { "code": null, "e": 635, "s": 28, "text": "NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Numpy is basically used for creating array of n dimensions.Reshaping numpy array simply means changing the shape of the given array, shape basically tells the number of elements and dimension of array, by reshaping an array we can add or remove dimensions or change number of elements in each dimension.In order to reshape a numpy array we use reshape method with the given array. " }, { "code": null, "e": 772, "s": 635, "text": "Syntax : array.reshape(shape)Argument : It take tuple as argument, tuple is the new shape to be formedReturn : It returns numpy.ndarray " }, { "code": null, "e": 1032, "s": 772, "text": "Note : We can also use np.reshape(array, shape) command to reshape the arrayReshaping : 1-D to 2D In this example we will reshape the 1-D array of shape (1, n) to 2-D array of shape (N, M) here M should be equal to the n/N there for N should be factor of n. " }, { "code": null, "e": 1040, "s": 1032, "text": "Python3" }, { "code": "# importing numpyimport numpy as np # creating a numpy arrayarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) # printing arrayprint(\"Array : \" + str(array)) # length of arrayn = array.size # N-D array N dimensionN = 4 # calculating MM = n//N # reshaping numpy array# converting it to 2-D from 1-D arrayreshaped1 = array.reshape((N, M)) # printing reshaped arrayprint(\"First Reshaped Array : \")print(reshaped1) # creating another reshaped arrayreshaped2 = np.reshape(array, (2, 8)) # printing reshaped arrayprint(\"Second Reshaped Array : \")print(reshaped2)", "e": 1620, "s": 1040, "text": null }, { "code": null, "e": 1631, "s": 1620, "text": "Output : " }, { "code": null, "e": 1854, "s": 1631, "text": "Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]\nFirst Reshaped Array : \n[[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11 12]\n [13 14 15 16]]\nSecond Reshaped Array : \n[[ 1 2 3 4 5 6 7 8]\n [ 9 10 11 12 13 14 15 16]]" }, { "code": null, "e": 1998, "s": 1854, "text": "Reshaping : 1-D to 3-D In this we will see how we can reshape a 1-D array to 3-D dimension array. A 3-D array is the 1-D array of 2-D arrays. " }, { "code": null, "e": 2006, "s": 1998, "text": "Python3" }, { "code": "# importing numpyimport numpy as np # creating a numpy arrayarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) # printing arrayprint(\"Array : \" + str(array)) # reshaping numpy array# converting it to 3-D from 1-D arrayreshaped = array.reshape((2, 2, 4)) # printing reshaped arrayprint(\"Reshaped 3-D Array : \")print(reshaped)", "e": 2355, "s": 2006, "text": null }, { "code": null, "e": 2366, "s": 2355, "text": "Output : " }, { "code": null, "e": 2514, "s": 2366, "text": "Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]\nReshaped 3-D Array : \n[[[ 1 2 3 4]\n [ 5 6 7 8]]\n\n [[ 9 10 11 12]\n [13 14 15 16]]]" }, { "code": null, "e": 2704, "s": 2514, "text": "Reshaping N-D to 1-D array In this example we will see how we can reshape a 2-D or 3-D array to form a 1-D array. We can also use reshape(-1) to do this, here -1 is the unknown dimension. " }, { "code": null, "e": 2712, "s": 2704, "text": "Python3" }, { "code": "# importing numpyimport numpy as np # creating a numpy arrayarray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # printing arrayprint(\" 2-D Array : \")print(array) # reshaping numpy array# converting it to 1-D from 2-D arrayreshaped = array.reshape((9)) # or we can use unknown dimension# reshaped = array.reshape((-1)) # printing reshaped arrayprint(\"Reshaped 1-D Array : \")print(reshaped)", "e": 3135, "s": 2712, "text": null }, { "code": null, "e": 3146, "s": 3135, "text": "Output : " }, { "code": null, "e": 3232, "s": 3146, "text": " 2-D Array : \n[[1 2 3]\n [4 5 6]\n [7 8 9]]\nReshaped 1-D Array : \n[[1 2 3 4 5 6 7 8 9]]" }, { "code": null, "e": 3442, "s": 3232, "text": "Reshaping using unknown dimension We can reshape a array although we don’t know all the new dimensions by using -1 as one of the dimension, but we should know all the other dimension to use unknown dimension " }, { "code": null, "e": 3450, "s": 3442, "text": "Python3" }, { "code": "# importing numpyimport numpy as np # creating a numpy arrayarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) # printing arrayprint(\"Array : \" + str(array)) # reshaping numpy array# converting it to 3-D from 1-D arrayreshaped1 = array.reshape((2, 2, -1)) # printing reshaped arrayprint(\"First Reshaped Array : \")print(reshaped1) # converting it to 2-D arrayreshaped2 = array.reshape((4, -1)) # printing reshaped arrayprint(\"Second Reshaped Array : \")print(reshaped2)", "e": 3943, "s": 3450, "text": null }, { "code": null, "e": 3954, "s": 3943, "text": "Output : " }, { "code": null, "e": 4190, "s": 3954, "text": "Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]\nFirst Reshaped Array : \n[[[ 1 2 3 4]\n [ 5 6 7 8]]\n\n [[ 9 10 11 12]\n [13 14 15 16]]]\nSecond Reshaped Array : \n[[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11 12]\n [13 14 15 16]]" }, { "code": null, "e": 4511, "s": 4190, "text": "Errors Occur during reshaping When we try to reshape a array to a shape which is not mathematically possible then value error is generated saying can not reshape the array. For example when we try to reshape 1-D array with 4 elements into a 2-D array of dimension(3, 3) is not possible as new array requires 9 elements " }, { "code": null, "e": 4519, "s": 4511, "text": "Python3" }, { "code": "# importing numpyimport numpy as np # creating a numpy arrayarray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # printing arrayprint(\" 2-D Array : \")print(array) # reshaping numpy array# converting it to 1-D from 2-D array# reshaping it into 1, 5reshaped = array.reshape((1, 5)) # or we can use # printing reshaped arrayprint(\"Reshaped 1-D Array : \")print(reshaped)", "e": 4919, "s": 4519, "text": null }, { "code": null, "e": 4980, "s": 4919, "text": "ValueError: cannot reshape array of size 9 into shape (1, 5)" }, { "code": null, "e": 4995, "s": 4980, "text": "adnanirshad158" }, { "code": null, "e": 5004, "s": 4995, "text": "sweetyty" }, { "code": null, "e": 5013, "s": 5004, "text": "rkbhola5" }, { "code": null, "e": 5044, "s": 5013, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 5057, "s": 5044, "text": "Python-numpy" }, { "code": null, "e": 5064, "s": 5057, "text": "Python" }, { "code": null, "e": 5162, "s": 5064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5194, "s": 5162, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5221, "s": 5194, "text": "Python Classes and Objects" }, { "code": null, "e": 5242, "s": 5221, "text": "Python OOPs Concepts" }, { "code": null, "e": 5265, "s": 5242, "text": "Introduction To PYTHON" }, { "code": null, "e": 5296, "s": 5265, "text": "Python | os.path.join() method" }, { "code": null, "e": 5352, "s": 5296, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5394, "s": 5352, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5436, "s": 5394, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5475, "s": 5436, "text": "Python | Get unique values from a list" } ]
Calculator Program with Batch Scripting in Windows
07 Sep, 2020 By using the Batch Scripting of command prompt one could even design a normal basic calculator that takes expressions and returns the result. Type the following script in notepad or any other text editor software: @echo off :a echo ________Calculator________ echo. set /p expression= Enter expression to calculate: set /a ans=%expression% echo. echo = %ans% echo pause cls goto a After writing the above text in a text editor, save the file with the extension “ .bat “. To run the program, simply double-click on the saved file, the program will open and the code will get executed in Command Prompt. It should look something like: Welcome screen! @echo off — signals Command Prompt to not display the commands (code). : a — the signals starting point of a loop. echo — same as print/println/printf/etc. Displays the specified message as output to the screen. echo. — will output a blank line. set — used to set value against a variable. set /p expression — /p signals that this is prompt. “Expression” is just a variable name. set /a ans – /a signal that variable has a numerical value. “ans” is the variable name. %ans% — calls the variable “ans” pause — will pause/ stop the program flow until the user will press a key (any key) and continue the program flow only when the users press a key (any). cls – clears the screen goto a- signals to go to the start point of the loop, effectively looping our calculator program so it can take in and calculate new expression. Program Test Cases: The program can handle simple expression calculations like: Calculating Simple Expression And it can also handle complex expressions, such as: Calculating Complex Expression Note:- The above program is calculating expressions by utilizing the calculator (that can perform simple arithmetic on 32-bit signed integers) that comes with Command Prompt. Since we are utilizing built-in calculator of Command Prompt, we can only perform following expression: + (addition), – (subtraction), * (multiplication), / (divide), % (modulo). Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Basic Operators in Shell Scripting Array Basics in Shell Scripting | Set 1
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Sep, 2020" }, { "code": null, "e": 267, "s": 53, "text": "By using the Batch Scripting of command prompt one could even design a normal basic calculator that takes expressions and returns the result. Type the following script in notepad or any other text editor software:" }, { "code": null, "e": 434, "s": 267, "text": "@echo off\n:a\necho ________Calculator________\necho.\nset /p expression= Enter expression to calculate:\nset /a ans=%expression%\necho.\necho = %ans%\necho\npause\ncls\ngoto a\n" }, { "code": null, "e": 686, "s": 434, "text": "After writing the above text in a text editor, save the file with the extension “ .bat “. To run the program, simply double-click on the saved file, the program will open and the code will get executed in Command Prompt. It should look something like:" }, { "code": null, "e": 702, "s": 686, "text": "Welcome screen!" }, { "code": null, "e": 773, "s": 702, "text": "@echo off — signals Command Prompt to not display the commands (code)." }, { "code": null, "e": 817, "s": 773, "text": ": a — the signals starting point of a loop." }, { "code": null, "e": 914, "s": 817, "text": "echo — same as print/println/printf/etc. Displays the specified message as output to the screen." }, { "code": null, "e": 948, "s": 914, "text": "echo. — will output a blank line." }, { "code": null, "e": 992, "s": 948, "text": "set — used to set value against a variable." }, { "code": null, "e": 1082, "s": 992, "text": "set /p expression — /p signals that this is prompt. “Expression” is just a variable name." }, { "code": null, "e": 1170, "s": 1082, "text": "set /a ans – /a signal that variable has a numerical value. “ans” is the variable name." }, { "code": null, "e": 1203, "s": 1170, "text": "%ans% — calls the variable “ans”" }, { "code": null, "e": 1356, "s": 1203, "text": "pause — will pause/ stop the program flow until the user will press a key (any key) and continue the program flow only when the users press a key (any)." }, { "code": null, "e": 1380, "s": 1356, "text": "cls – clears the screen" }, { "code": null, "e": 1525, "s": 1380, "text": "goto a- signals to go to the start point of the loop, effectively looping our calculator program so it can take in and calculate new expression." }, { "code": null, "e": 1545, "s": 1525, "text": "Program Test Cases:" }, { "code": null, "e": 1605, "s": 1545, "text": "The program can handle simple expression calculations like:" }, { "code": null, "e": 1635, "s": 1605, "text": "Calculating Simple Expression" }, { "code": null, "e": 1688, "s": 1635, "text": "And it can also handle complex expressions, such as:" }, { "code": null, "e": 1719, "s": 1688, "text": "Calculating Complex Expression" }, { "code": null, "e": 1726, "s": 1719, "text": "Note:-" }, { "code": null, "e": 1894, "s": 1726, "text": "The above program is calculating expressions by utilizing the calculator (that can perform simple arithmetic on 32-bit signed integers) that comes with Command Prompt." }, { "code": null, "e": 2074, "s": 1894, "text": "Since we are utilizing built-in calculator of Command Prompt, we can only perform following expression: + (addition), – (subtraction), * (multiplication), / (divide), % (modulo)." }, { "code": null, "e": 2085, "s": 2074, "text": "Linux-Unix" }, { "code": null, "e": 2183, "s": 2085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2209, "s": 2183, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2244, "s": 2209, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2281, "s": 2244, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2310, "s": 2281, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2344, "s": 2310, "text": "mv command in Linux with examples" }, { "code": null, "e": 2381, "s": 2344, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2418, "s": 2381, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2457, "s": 2418, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2492, "s": 2457, "text": "Basic Operators in Shell Scripting" } ]
Examples of Data Link Layer Protocols
05 Aug, 2020 Data Link Layer protocols are generally responsible to simply ensure and confirm that the bits and bytes that are received are identical to the bits and bytes being transferred. It is basically a set of specifications that are used for implementation of data link layer just above the physical layer of the Open System Interconnections (OSI) Model. Some Common Data Link Protocols :There are various data link protocols that are required for Wide Area Network (WAN) and modem connections. Logical Link Control (LLC) is a data link protocol of Local Area Network (LAN). Some of data link protocols are given below : Synchronous Data Link Protocol (SDLC) –SDLC is basically a communication protocol of computer. It usually supports multipoint links even error recovery or error correction also. It is usually used to carry SNA (Systems Network Architecture) traffic and is present precursor to HDLC. It is also designed and developed by IBM in 1975. It is also used to connect all of the remote devices to mainframe computers at central locations may be in point-to-point (one-to-one) or point-to-multipoint (one-to-many) connections. It is also used to make sure that the data units should arrive correctly and with right flow from one network point to next network point.High-Level Data Link Protocol (HDLC) –HDLC is basically a protocol that is now assumed to be an umbrella under which many Wide Area protocols sit. It is also adopted as a part of X.25 network. It was originally created and developed by ISO in 1979. This protocol is generally based on SDLC. It also provides best-effort unreliable service and also reliable service. HDLC is a bit-oriented protocol that is applicable for point-to-point and multipoint communications both.Serial Line Interface Protocol (SLIP) –SLIP is generally an older protocol that is just used to add a framing byte at end of IP packet. It is basically a data link control facility that is required for transferring IP packets usually among Internet Service Providers (ISP) and a home user over a dial-up link. It is an encapsulation of the TCP/IP especially designed to work with over serial ports and several router connections simply for communication. It is some limitations like it does not provide mechanisms such as error correction or error detection.Point to Point Protocol (PPP) –PPP is a protocol that is basically used to provide same functionality as SLIP. It is most robust protocol that is used to transport other types of packets also along with IP Packets. It can also be required for dial-up and leased router-router lines. It basically provides framing method to describe frames. It is a character-oriented protocol that is also used for error detection. It is also used to provides two protocols i.e. NCP and LCP. LCP is used for bringing lines up, negotiation of options, bringing them down whereas NCP is used for negotiating network-layer protocols. It is required for same serial interfaces like that of HDLC.Link Control Protocol (LCP) –It was originally developed and created by IEEE 802.2. It is also used to provide HDLC style services on LAN (Local Area Network). LCP is basically a PPP protocol that is used for establishing, configuring, testing, maintenance, and ending or terminating links for transmission of data frames.Link Access Procedure (LAP) –LAP protocols are basically a data link layer protocols that are required for framing and transferring data across point-to-point links. It also includes some reliability service features. There are basically three types of LAP i.e. LAPB (Link Access Procedure Balanced), LAPD (Link Access Procedure D-Channel), and LAPF (Link Access Procedure Frame-Mode Bearer Services). It is actually originated from IBM SDLC, which is being submitted by IBM to the ISP simply for standardization.Network Control Protocol (NCP) –NCP was also an older protocol that was implemented by ARPANET. It basically allows users to have access to use computers and some of the devices at remote locations and also to transfer files among two or more computers. It is generally a set of protocols that is forming a part of PPP. NCP is always available for each and every higher-layer protocol that is supported by PPP. NCP was replaced by TCP/IP in the 1980s. Synchronous Data Link Protocol (SDLC) –SDLC is basically a communication protocol of computer. It usually supports multipoint links even error recovery or error correction also. It is usually used to carry SNA (Systems Network Architecture) traffic and is present precursor to HDLC. It is also designed and developed by IBM in 1975. It is also used to connect all of the remote devices to mainframe computers at central locations may be in point-to-point (one-to-one) or point-to-multipoint (one-to-many) connections. It is also used to make sure that the data units should arrive correctly and with right flow from one network point to next network point. High-Level Data Link Protocol (HDLC) –HDLC is basically a protocol that is now assumed to be an umbrella under which many Wide Area protocols sit. It is also adopted as a part of X.25 network. It was originally created and developed by ISO in 1979. This protocol is generally based on SDLC. It also provides best-effort unreliable service and also reliable service. HDLC is a bit-oriented protocol that is applicable for point-to-point and multipoint communications both. Serial Line Interface Protocol (SLIP) –SLIP is generally an older protocol that is just used to add a framing byte at end of IP packet. It is basically a data link control facility that is required for transferring IP packets usually among Internet Service Providers (ISP) and a home user over a dial-up link. It is an encapsulation of the TCP/IP especially designed to work with over serial ports and several router connections simply for communication. It is some limitations like it does not provide mechanisms such as error correction or error detection. Point to Point Protocol (PPP) –PPP is a protocol that is basically used to provide same functionality as SLIP. It is most robust protocol that is used to transport other types of packets also along with IP Packets. It can also be required for dial-up and leased router-router lines. It basically provides framing method to describe frames. It is a character-oriented protocol that is also used for error detection. It is also used to provides two protocols i.e. NCP and LCP. LCP is used for bringing lines up, negotiation of options, bringing them down whereas NCP is used for negotiating network-layer protocols. It is required for same serial interfaces like that of HDLC. Link Control Protocol (LCP) –It was originally developed and created by IEEE 802.2. It is also used to provide HDLC style services on LAN (Local Area Network). LCP is basically a PPP protocol that is used for establishing, configuring, testing, maintenance, and ending or terminating links for transmission of data frames. Link Access Procedure (LAP) –LAP protocols are basically a data link layer protocols that are required for framing and transferring data across point-to-point links. It also includes some reliability service features. There are basically three types of LAP i.e. LAPB (Link Access Procedure Balanced), LAPD (Link Access Procedure D-Channel), and LAPF (Link Access Procedure Frame-Mode Bearer Services). It is actually originated from IBM SDLC, which is being submitted by IBM to the ISP simply for standardization. Network Control Protocol (NCP) –NCP was also an older protocol that was implemented by ARPANET. It basically allows users to have access to use computers and some of the devices at remote locations and also to transfer files among two or more computers. It is generally a set of protocols that is forming a part of PPP. NCP is always available for each and every higher-layer protocol that is supported by PPP. NCP was replaced by TCP/IP in the 1980s. Data Link Layer Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Network Topology GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Aug, 2020" }, { "code": null, "e": 401, "s": 52, "text": "Data Link Layer protocols are generally responsible to simply ensure and confirm that the bits and bytes that are received are identical to the bits and bytes being transferred. It is basically a set of specifications that are used for implementation of data link layer just above the physical layer of the Open System Interconnections (OSI) Model." }, { "code": null, "e": 667, "s": 401, "text": "Some Common Data Link Protocols :There are various data link protocols that are required for Wide Area Network (WAN) and modem connections. Logical Link Control (LLC) is a data link protocol of Local Area Network (LAN). Some of data link protocols are given below :" }, { "code": null, "e": 4313, "s": 667, "text": "Synchronous Data Link Protocol (SDLC) –SDLC is basically a communication protocol of computer. It usually supports multipoint links even error recovery or error correction also. It is usually used to carry SNA (Systems Network Architecture) traffic and is present precursor to HDLC. It is also designed and developed by IBM in 1975. It is also used to connect all of the remote devices to mainframe computers at central locations may be in point-to-point (one-to-one) or point-to-multipoint (one-to-many) connections. It is also used to make sure that the data units should arrive correctly and with right flow from one network point to next network point.High-Level Data Link Protocol (HDLC) –HDLC is basically a protocol that is now assumed to be an umbrella under which many Wide Area protocols sit. It is also adopted as a part of X.25 network. It was originally created and developed by ISO in 1979. This protocol is generally based on SDLC. It also provides best-effort unreliable service and also reliable service. HDLC is a bit-oriented protocol that is applicable for point-to-point and multipoint communications both.Serial Line Interface Protocol (SLIP) –SLIP is generally an older protocol that is just used to add a framing byte at end of IP packet. It is basically a data link control facility that is required for transferring IP packets usually among Internet Service Providers (ISP) and a home user over a dial-up link. It is an encapsulation of the TCP/IP especially designed to work with over serial ports and several router connections simply for communication. It is some limitations like it does not provide mechanisms such as error correction or error detection.Point to Point Protocol (PPP) –PPP is a protocol that is basically used to provide same functionality as SLIP. It is most robust protocol that is used to transport other types of packets also along with IP Packets. It can also be required for dial-up and leased router-router lines. It basically provides framing method to describe frames. It is a character-oriented protocol that is also used for error detection. It is also used to provides two protocols i.e. NCP and LCP. LCP is used for bringing lines up, negotiation of options, bringing them down whereas NCP is used for negotiating network-layer protocols. It is required for same serial interfaces like that of HDLC.Link Control Protocol (LCP) –It was originally developed and created by IEEE 802.2. It is also used to provide HDLC style services on LAN (Local Area Network). LCP is basically a PPP protocol that is used for establishing, configuring, testing, maintenance, and ending or terminating links for transmission of data frames.Link Access Procedure (LAP) –LAP protocols are basically a data link layer protocols that are required for framing and transferring data across point-to-point links. It also includes some reliability service features. There are basically three types of LAP i.e. LAPB (Link Access Procedure Balanced), LAPD (Link Access Procedure D-Channel), and LAPF (Link Access Procedure Frame-Mode Bearer Services). It is actually originated from IBM SDLC, which is being submitted by IBM to the ISP simply for standardization.Network Control Protocol (NCP) –NCP was also an older protocol that was implemented by ARPANET. It basically allows users to have access to use computers and some of the devices at remote locations and also to transfer files among two or more computers. It is generally a set of protocols that is forming a part of PPP. NCP is always available for each and every higher-layer protocol that is supported by PPP. NCP was replaced by TCP/IP in the 1980s." }, { "code": null, "e": 4970, "s": 4313, "text": "Synchronous Data Link Protocol (SDLC) –SDLC is basically a communication protocol of computer. It usually supports multipoint links even error recovery or error correction also. It is usually used to carry SNA (Systems Network Architecture) traffic and is present precursor to HDLC. It is also designed and developed by IBM in 1975. It is also used to connect all of the remote devices to mainframe computers at central locations may be in point-to-point (one-to-one) or point-to-multipoint (one-to-many) connections. It is also used to make sure that the data units should arrive correctly and with right flow from one network point to next network point." }, { "code": null, "e": 5442, "s": 4970, "text": "High-Level Data Link Protocol (HDLC) –HDLC is basically a protocol that is now assumed to be an umbrella under which many Wide Area protocols sit. It is also adopted as a part of X.25 network. It was originally created and developed by ISO in 1979. This protocol is generally based on SDLC. It also provides best-effort unreliable service and also reliable service. HDLC is a bit-oriented protocol that is applicable for point-to-point and multipoint communications both." }, { "code": null, "e": 6001, "s": 5442, "text": "Serial Line Interface Protocol (SLIP) –SLIP is generally an older protocol that is just used to add a framing byte at end of IP packet. It is basically a data link control facility that is required for transferring IP packets usually among Internet Service Providers (ISP) and a home user over a dial-up link. It is an encapsulation of the TCP/IP especially designed to work with over serial ports and several router connections simply for communication. It is some limitations like it does not provide mechanisms such as error correction or error detection." }, { "code": null, "e": 6676, "s": 6001, "text": "Point to Point Protocol (PPP) –PPP is a protocol that is basically used to provide same functionality as SLIP. It is most robust protocol that is used to transport other types of packets also along with IP Packets. It can also be required for dial-up and leased router-router lines. It basically provides framing method to describe frames. It is a character-oriented protocol that is also used for error detection. It is also used to provides two protocols i.e. NCP and LCP. LCP is used for bringing lines up, negotiation of options, bringing them down whereas NCP is used for negotiating network-layer protocols. It is required for same serial interfaces like that of HDLC." }, { "code": null, "e": 6999, "s": 6676, "text": "Link Control Protocol (LCP) –It was originally developed and created by IEEE 802.2. It is also used to provide HDLC style services on LAN (Local Area Network). LCP is basically a PPP protocol that is used for establishing, configuring, testing, maintenance, and ending or terminating links for transmission of data frames." }, { "code": null, "e": 7513, "s": 6999, "text": "Link Access Procedure (LAP) –LAP protocols are basically a data link layer protocols that are required for framing and transferring data across point-to-point links. It also includes some reliability service features. There are basically three types of LAP i.e. LAPB (Link Access Procedure Balanced), LAPD (Link Access Procedure D-Channel), and LAPF (Link Access Procedure Frame-Mode Bearer Services). It is actually originated from IBM SDLC, which is being submitted by IBM to the ISP simply for standardization." }, { "code": null, "e": 7965, "s": 7513, "text": "Network Control Protocol (NCP) –NCP was also an older protocol that was implemented by ARPANET. It basically allows users to have access to use computers and some of the devices at remote locations and also to transfer files among two or more computers. It is generally a set of protocols that is forming a part of PPP. NCP is always available for each and every higher-layer protocol that is supported by PPP. NCP was replaced by TCP/IP in the 1980s." }, { "code": null, "e": 7981, "s": 7965, "text": "Data Link Layer" }, { "code": null, "e": 7999, "s": 7981, "text": "Computer Networks" }, { "code": null, "e": 8007, "s": 7999, "text": "GATE CS" }, { "code": null, "e": 8025, "s": 8007, "text": "Computer Networks" }, { "code": null, "e": 8123, "s": 8025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8149, "s": 8123, "text": "Types of Network Topology" }, { "code": null, "e": 8179, "s": 8149, "text": "GSM in Wireless Communication" }, { "code": null, "e": 8208, "s": 8179, "text": "Socket Programming in Python" }, { "code": null, "e": 8242, "s": 8208, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 8268, "s": 8242, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 8292, "s": 8268, "text": "ACID Properties in DBMS" }, { "code": null, "e": 8319, "s": 8292, "text": "Types of Operating Systems" }, { "code": null, "e": 8340, "s": 8319, "text": "Normal Forms in DBMS" }, { "code": null, "e": 8389, "s": 8340, "text": "Page Replacement Algorithms in Operating Systems" } ]
p5.js | blendMode() Function
20 Feb, 2020 The blendMode() function is used to blend two pixels according to the given blending mode. The different types of blending modes have different methods of mixing the source pixels with the ones present in the display window, to produce the resulting pixel. Syntax: blendMode( mode ) Parameters: This function accepts single parameter mode that is used to blend the pixels. It can have the following values: BLEND: It blends the pixels using linear interpolation of the colors. It is the default blending mode. ADD: It produces the new color by adding the colors of both the pixels. DARKEST: It uses only the darker color of the two pixels. LIGHTEST: It uses only the lighter color of the two pixels. DIFFERENCE: It subtracts colors from the underlying image. EXCLUSION: It has a similar effect to the “difference” property with less intensity. MULTIPLY: It multiplies both the colors resulting in a darker image. SCREEN: It has the opposite effect to the “multiply” effect and uses inverse values of the colors. REPLACE: It entirely replaces the pixels of the first with the pixels of the other while ignoring the alpha values. REMOVE: It removes the pixels from the second color using its alpha strength. OVERLAY: It is a mix of the “multiply” and “screen” modes. It multiplies the light values and screens the dark values. It works only in the 2D renderer. HARD_LIGHT: It applies the “screen” effect when the gray value is above 50% and “multiply” when it is lower. It works only in the 2D renderer. SOFT_LIGHT: It is a mix of “darkest” and “lightest”. It works like the “overlay” mode with less intensity. It works only in the 2D renderer. DODGE: It lightens the light tones and increases the contrast, while ignoring the dark tones. It works only in the 2D renderer. BURN: It lightens the dark tones and increases the contrast, while ignoring the light tones. It works only in the 2D renderer. SUBTRACT: It applies the final color based on the remainder of the two pixels. It works only in the WEBGL renderer. The example below illustrates the blendMode() function in p5.js: Example: function setup() { blendModes = [ BLEND, ADD, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN ] index = 0; currBlendMode = blendModes[index]; createCanvas(600, 300); textSize(20);} function draw() { clear(); text('Click on the button to change the blend mode', 20, 20); text("Current blendMode: " + currBlendMode, 20, 50); btn = createButton("Change blendMode"); btn.position(30, 80); btn.mousePressed(changeBlendMode); // Set the blend mode blendMode(currBlendMode); // Draw the first circle fill("red"); circle(180, 200, 150); // Draw the second circle fill("green"); circle(260, 200, 150);} function changeBlendMode() { if (index < blendModes.length - 1) index++; else index = 0; currBlendMode = blendModes[index];} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/blendMode JavaScript-p5.js JavaScript 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": "\n20 Feb, 2020" }, { "code": null, "e": 285, "s": 28, "text": "The blendMode() function is used to blend two pixels according to the given blending mode. The different types of blending modes have different methods of mixing the source pixels with the ones present in the display window, to produce the resulting pixel." }, { "code": null, "e": 293, "s": 285, "text": "Syntax:" }, { "code": null, "e": 311, "s": 293, "text": "blendMode( mode )" }, { "code": null, "e": 435, "s": 311, "text": "Parameters: This function accepts single parameter mode that is used to blend the pixels. It can have the following values:" }, { "code": null, "e": 538, "s": 435, "text": "BLEND: It blends the pixels using linear interpolation of the colors. It is the default blending mode." }, { "code": null, "e": 610, "s": 538, "text": "ADD: It produces the new color by adding the colors of both the pixels." }, { "code": null, "e": 668, "s": 610, "text": "DARKEST: It uses only the darker color of the two pixels." }, { "code": null, "e": 728, "s": 668, "text": "LIGHTEST: It uses only the lighter color of the two pixels." }, { "code": null, "e": 787, "s": 728, "text": "DIFFERENCE: It subtracts colors from the underlying image." }, { "code": null, "e": 872, "s": 787, "text": "EXCLUSION: It has a similar effect to the “difference” property with less intensity." }, { "code": null, "e": 941, "s": 872, "text": "MULTIPLY: It multiplies both the colors resulting in a darker image." }, { "code": null, "e": 1040, "s": 941, "text": "SCREEN: It has the opposite effect to the “multiply” effect and uses inverse values of the colors." }, { "code": null, "e": 1156, "s": 1040, "text": "REPLACE: It entirely replaces the pixels of the first with the pixels of the other while ignoring the alpha values." }, { "code": null, "e": 1234, "s": 1156, "text": "REMOVE: It removes the pixels from the second color using its alpha strength." }, { "code": null, "e": 1387, "s": 1234, "text": "OVERLAY: It is a mix of the “multiply” and “screen” modes. It multiplies the light values and screens the dark values. It works only in the 2D renderer." }, { "code": null, "e": 1530, "s": 1387, "text": "HARD_LIGHT: It applies the “screen” effect when the gray value is above 50% and “multiply” when it is lower. It works only in the 2D renderer." }, { "code": null, "e": 1671, "s": 1530, "text": "SOFT_LIGHT: It is a mix of “darkest” and “lightest”. It works like the “overlay” mode with less intensity. It works only in the 2D renderer." }, { "code": null, "e": 1799, "s": 1671, "text": "DODGE: It lightens the light tones and increases the contrast, while ignoring the dark tones. It works only in the 2D renderer." }, { "code": null, "e": 1926, "s": 1799, "text": "BURN: It lightens the dark tones and increases the contrast, while ignoring the light tones. It works only in the 2D renderer." }, { "code": null, "e": 2042, "s": 1926, "text": "SUBTRACT: It applies the final color based on the remainder of the two pixels. It works only in the WEBGL renderer." }, { "code": null, "e": 2107, "s": 2042, "text": "The example below illustrates the blendMode() function in p5.js:" }, { "code": null, "e": 2116, "s": 2107, "text": "Example:" }, { "code": "function setup() { blendModes = [ BLEND, ADD, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN ] index = 0; currBlendMode = blendModes[index]; createCanvas(600, 300); textSize(20);} function draw() { clear(); text('Click on the button to change the blend mode', 20, 20); text(\"Current blendMode: \" + currBlendMode, 20, 50); btn = createButton(\"Change blendMode\"); btn.position(30, 80); btn.mousePressed(changeBlendMode); // Set the blend mode blendMode(currBlendMode); // Draw the first circle fill(\"red\"); circle(180, 200, 150); // Draw the second circle fill(\"green\"); circle(260, 200, 150);} function changeBlendMode() { if (index < blendModes.length - 1) index++; else index = 0; currBlendMode = blendModes[index];}", "e": 2963, "s": 2116, "text": null }, { "code": null, "e": 2971, "s": 2963, "text": "Output:" }, { "code": null, "e": 3011, "s": 2971, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 3109, "s": 3011, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 3162, "s": 3109, "text": "Reference: https://p5js.org/reference/#/p5/blendMode" }, { "code": null, "e": 3179, "s": 3162, "text": "JavaScript-p5.js" }, { "code": null, "e": 3190, "s": 3179, "text": "JavaScript" }, { "code": null, "e": 3207, "s": 3190, "text": "Web Technologies" } ]
numpy.isscalar() in Python
29 Nov, 2018 numpy.isscalar(num) : This is a logical function that returns true if the type of input num is scalar. Parameters : num : Input argument of any type and shape. Return : True, if input is scalar; else False Code 1 : Working # Python program explaining# isscalar() functionimport numpy as np in_array = [1, 3, 5, 4]print ("Input array : ", in_array) isscalar_values = np.isscalar(in_array)print ("\nIs scalar : ", isscalar_values) # inputprint ("\nisscalar(7) : ", np.isscalar(7)) # list input print ("\nisscalar([7]) : ", np.isscalar([7])) Output : Input array : [1, 3, 5, 4] Is scalar : False isscalar(7) : True isscalar([7]) : False References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isscalar.html. Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 131, "s": 28, "text": "numpy.isscalar(num) : This is a logical function that returns true if the type of input num is scalar." }, { "code": null, "e": 144, "s": 131, "text": "Parameters :" }, { "code": null, "e": 188, "s": 144, "text": "num : Input argument of any type and shape." }, { "code": null, "e": 197, "s": 188, "text": "Return :" }, { "code": null, "e": 235, "s": 197, "text": "True, if input is scalar; else False\n" }, { "code": null, "e": 252, "s": 235, "text": "Code 1 : Working" }, { "code": "# Python program explaining# isscalar() functionimport numpy as np in_array = [1, 3, 5, 4]print (\"Input array : \", in_array) isscalar_values = np.isscalar(in_array)print (\"\\nIs scalar : \", isscalar_values) # inputprint (\"\\nisscalar(7) : \", np.isscalar(7)) # list input print (\"\\nisscalar([7]) : \", np.isscalar([7]))", "e": 572, "s": 252, "text": null }, { "code": null, "e": 581, "s": 572, "text": "Output :" }, { "code": null, "e": 675, "s": 581, "text": "Input array : [1, 3, 5, 4]\n\nIs scalar : False\n\nisscalar(7) : True\n\nisscalar([7]) : False\n" }, { "code": null, "e": 768, "s": 675, "text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isscalar.html." }, { "code": null, "e": 797, "s": 768, "text": "Python numpy-Logic Functions" }, { "code": null, "e": 810, "s": 797, "text": "Python-numpy" }, { "code": null, "e": 817, "s": 810, "text": "Python" } ]
JavaScript | Array find() function
14 Mar, 2018 arr.find() function is used to find the first element from the array that satisfies the condition implemented by a function. If more than one element satisfies the condition then the first element satisfying the condition is returned. Suppose that you want to find the first odd number in the array. The argument function checks whether the argument passed to it is odd number or not . The find() function calls the argument function for every element of the array. The first odd number for which argument function returns true is reported by find() function as the answer. The syntax of the function is as follows: Syntax: arr.find(function(element, index, array), thisValue) ArgumentsThe argument to this function is another function that defines the condition to be checked for each element of the array. This function itself takes three arguments: array:This is the array on which the .filter() function was called. index:This is the index of the current element being processed by the function. element:This is the current element being processed by the function. Another argument thisValue is used to tell the function to use this value when executing argument function. Return valueThis function returns the first value from the array that satisfies the given condition. If no value satisfies the given condition, then it returns undefined as its answer. Examples for the above function are provided below: Example 1: function isOdd(element, index, array) { return (element%2 == 1); } print([4, 6, 8, 12].find(isOdd)); Output: undefined In this example the function find() finds all the odd numbers in the array. Since no odd numbers are present, therefore it returns undefined . Example 2: function isOdd(element, index, array) { return (element%2 == 1); } print([4, 5, 8, 11].find(isOdd)); Output: 5 In this example the function find() finds the first occurrence of odd number in the array. Since first odd number is 5, therefore it returns it. Codes for the above function are provided below: Program 1: // JavaScript to illustrate find() function <script>function isOdd(element, index, array) { return (element % 2 == 1); } function func() { var array = [ 4, 6, 8, 12 ]; // Checking for odd numbers and // reporting the first odd number document.write(array.find(isOdd));} func();</script> Output: undefined Program 2: <script>// JavaScript to illustrate find() function function isOdd(element, index, array){ return (element % 2 == 1); } function func() { var array = [ 4, 5, 8, 11 ]; // Checking for odd numbers and // reporting the first odd number document.write(array.find(isOdd));} func();</script> Output: 5 Application:Whenever we need to get the value of the first element in the array that satisfies the provided testing function that time we use Array.find() method in JavaScript.Let\’s see JavaScript program: // input array contain some elements.var array = [2, 7, 8, 9]; // Here find function returns the value of // the first element in the array that satisfies // the provided testing function (return element > 4).var found = array.find(function(element) { return element > 4;}); // Printing desired values.console.log(found); Output: > 7 javascript-array JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Mar, 2018" }, { "code": null, "e": 670, "s": 54, "text": "arr.find() function is used to find the first element from the array that satisfies the condition implemented by a function. If more than one element satisfies the condition then the first element satisfying the condition is returned. Suppose that you want to find the first odd number in the array. The argument function checks whether the argument passed to it is odd number or not . The find() function calls the argument function for every element of the array. The first odd number for which argument function returns true is reported by find() function as the answer. The syntax of the function is as follows:" }, { "code": null, "e": 678, "s": 670, "text": "Syntax:" }, { "code": null, "e": 732, "s": 678, "text": "arr.find(function(element, index, array), thisValue)\n" }, { "code": null, "e": 907, "s": 732, "text": "ArgumentsThe argument to this function is another function that defines the condition to be checked for each element of the array. This function itself takes three arguments:" }, { "code": null, "e": 975, "s": 907, "text": "array:This is the array on which the .filter() function was called." }, { "code": null, "e": 1055, "s": 975, "text": "index:This is the index of the current element being processed by the function." }, { "code": null, "e": 1124, "s": 1055, "text": "element:This is the current element being processed by the function." }, { "code": null, "e": 1232, "s": 1124, "text": "Another argument thisValue is used to tell the function to use this value when executing argument function." }, { "code": null, "e": 1417, "s": 1232, "text": "Return valueThis function returns the first value from the array that satisfies the given condition. If no value satisfies the given condition, then it returns undefined as its answer." }, { "code": null, "e": 1469, "s": 1417, "text": "Examples for the above function are provided below:" }, { "code": null, "e": 1480, "s": 1469, "text": "Example 1:" }, { "code": null, "e": 1586, "s": 1480, "text": "function isOdd(element, index, array) {\n return (element%2 == 1);\n}\n\nprint([4, 6, 8, 12].find(isOdd));\n\n" }, { "code": null, "e": 1594, "s": 1586, "text": "Output:" }, { "code": null, "e": 1605, "s": 1594, "text": "undefined\n" }, { "code": null, "e": 1748, "s": 1605, "text": "In this example the function find() finds all the odd numbers in the array. Since no odd numbers are present, therefore it returns undefined ." }, { "code": null, "e": 1759, "s": 1748, "text": "Example 2:" }, { "code": null, "e": 1864, "s": 1759, "text": "function isOdd(element, index, array) {\n return (element%2 == 1);\n}\n\nprint([4, 5, 8, 11].find(isOdd));\n" }, { "code": null, "e": 1872, "s": 1864, "text": "Output:" }, { "code": null, "e": 1875, "s": 1872, "text": "5\n" }, { "code": null, "e": 2020, "s": 1875, "text": "In this example the function find() finds the first occurrence of odd number in the array. Since first odd number is 5, therefore it returns it." }, { "code": null, "e": 2069, "s": 2020, "text": "Codes for the above function are provided below:" }, { "code": null, "e": 2080, "s": 2069, "text": "Program 1:" }, { "code": "// JavaScript to illustrate find() function <script>function isOdd(element, index, array) { return (element % 2 == 1); } function func() { var array = [ 4, 6, 8, 12 ]; // Checking for odd numbers and // reporting the first odd number document.write(array.find(isOdd));} func();</script>", "e": 2378, "s": 2080, "text": null }, { "code": null, "e": 2386, "s": 2378, "text": "Output:" }, { "code": null, "e": 2397, "s": 2386, "text": "undefined\n" }, { "code": null, "e": 2408, "s": 2397, "text": "Program 2:" }, { "code": "<script>// JavaScript to illustrate find() function function isOdd(element, index, array){ return (element % 2 == 1); } function func() { var array = [ 4, 5, 8, 11 ]; // Checking for odd numbers and // reporting the first odd number document.write(array.find(isOdd));} func();</script>", "e": 2706, "s": 2408, "text": null }, { "code": null, "e": 2714, "s": 2706, "text": "Output:" }, { "code": null, "e": 2717, "s": 2714, "text": "5\n" }, { "code": null, "e": 2924, "s": 2717, "text": "Application:Whenever we need to get the value of the first element in the array that satisfies the provided testing function that time we use Array.find() method in JavaScript.Let\\’s see JavaScript program:" }, { "code": "// input array contain some elements.var array = [2, 7, 8, 9]; // Here find function returns the value of // the first element in the array that satisfies // the provided testing function (return element > 4).var found = array.find(function(element) { return element > 4;}); // Printing desired values.console.log(found);", "e": 3249, "s": 2924, "text": null }, { "code": null, "e": 3257, "s": 3249, "text": "Output:" }, { "code": null, "e": 3262, "s": 3257, "text": "> 7\n" }, { "code": null, "e": 3279, "s": 3262, "text": "javascript-array" }, { "code": null, "e": 3290, "s": 3279, "text": "JavaScript" } ]
log() function in C++
10 Dec, 2019 Log() function in C++ : The log() function in C++ returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. Syntax for returning natural logarithm:result = log(x) Syntax for returning logarithm (base-10 logarithm) of the argument.result = log10(x) The parameters can be of any data-type like int, double or float or long double. Log() function returns value according to the following conditions: ..a) if x>1 then positive..b) if 0<x<1 returns a negative value..c) if x=1 then it returns 0..d) if x=0 then it returns -inf..e) if x<0 then it returns NaN(not a number) // CPP program to implement log() function#include <bits/stdc++.h>using namespace std; // function to evaluate natural logarithm base-edouble valueE(double d){ return log(d);} // function to evaluate logarithm base-10double value10(double d){ return log10(d);} // driver program to test the above functionint main(){ double d = 10; cout << "The logarithm value(base-e) of " << d << " is " << valueE(d) << endl; cout << "The logarithm value(base-10) of " << d << " is " << value10(d) << endl; return 0;} Output: The logarithm value(base-e) of 10 is 2.30259 The logarithm value(base-10) of 10 is 1 Application:One of the applications of log() function is to calculated values related to log, for e.g., while finding polite number we need the formula to be written in code, for that we can use log() function. Given below is an implementation of log() function. // CPP program to find Nth polite number#include <bits/stdc++.h>using namespace std; // function to evaluate n-th polite numberdouble polite(double n){ n += 1; double base = 2; return n + (log((n + (log(n) / log(base))))) / log(base);} // driver codeint main(){ double n = 7; cout << (int)polite(n); return 0;} Output: 11 mathemagic a7medsaber CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Dec, 2019" }, { "code": null, "e": 193, "s": 53, "text": "Log() function in C++ : The log() function in C++ returns the natural logarithm (base-e logarithm) of the argument passed in the parameter." }, { "code": null, "e": 248, "s": 193, "text": "Syntax for returning natural logarithm:result = log(x)" }, { "code": null, "e": 333, "s": 248, "text": "Syntax for returning logarithm (base-10 logarithm) of the argument.result = log10(x)" }, { "code": null, "e": 414, "s": 333, "text": "The parameters can be of any data-type like int, double or float or long double." }, { "code": null, "e": 482, "s": 414, "text": "Log() function returns value according to the following conditions:" }, { "code": null, "e": 652, "s": 482, "text": "..a) if x>1 then positive..b) if 0<x<1 returns a negative value..c) if x=1 then it returns 0..d) if x=0 then it returns -inf..e) if x<0 then it returns NaN(not a number)" }, { "code": "// CPP program to implement log() function#include <bits/stdc++.h>using namespace std; // function to evaluate natural logarithm base-edouble valueE(double d){ return log(d);} // function to evaluate logarithm base-10double value10(double d){ return log10(d);} // driver program to test the above functionint main(){ double d = 10; cout << \"The logarithm value(base-e) of \" << d << \" is \" << valueE(d) << endl; cout << \"The logarithm value(base-10) of \" << d << \" is \" << value10(d) << endl; return 0;}", "e": 1194, "s": 652, "text": null }, { "code": null, "e": 1202, "s": 1194, "text": "Output:" }, { "code": null, "e": 1288, "s": 1202, "text": "The logarithm value(base-e) of 10 is 2.30259\nThe logarithm value(base-10) of 10 is 1\n" }, { "code": null, "e": 1551, "s": 1288, "text": "Application:One of the applications of log() function is to calculated values related to log, for e.g., while finding polite number we need the formula to be written in code, for that we can use log() function. Given below is an implementation of log() function." }, { "code": "// CPP program to find Nth polite number#include <bits/stdc++.h>using namespace std; // function to evaluate n-th polite numberdouble polite(double n){ n += 1; double base = 2; return n + (log((n + (log(n) / log(base))))) / log(base);} // driver codeint main(){ double n = 7; cout << (int)polite(n); return 0;}", "e": 1898, "s": 1551, "text": null }, { "code": null, "e": 1906, "s": 1898, "text": "Output:" }, { "code": null, "e": 1911, "s": 1906, "text": "11 \n" }, { "code": null, "e": 1922, "s": 1911, "text": "mathemagic" }, { "code": null, "e": 1933, "s": 1922, "text": "a7medsaber" }, { "code": null, "e": 1945, "s": 1933, "text": "CPP-Library" }, { "code": null, "e": 1949, "s": 1945, "text": "STL" }, { "code": null, "e": 1953, "s": 1949, "text": "C++" }, { "code": null, "e": 1957, "s": 1953, "text": "STL" }, { "code": null, "e": 1961, "s": 1957, "text": "CPP" } ]
List FindLastIndex() Method in C# | Set -2
05 Dec, 2019 This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method: FindLastIndex(Predicate<T>) Method FindLastIndex(Int32, Predicate<T>) Method FindLastIndex(Int32, Int32, Predicate<T>) Method Here, we will discuss only the last two methods. This method searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the range of elements in the List<T> that extends from the first element to the specified index. Syntax: public int FindLastIndex (int start, Predicate<T> match); Parameters:start: It is the starting index from the searching will starts.match: It is the Predicate delegate that defines the conditions of the searched element. Return Value: If the element is found then it returns the zero-based index of type Int32 of the last occurrence of an element that matches a specified condition by the parameter “match”. And if not found then it returns “-1”. Exceptions: ArgumentNullException: If the match is null. ArgumentOutOfRangeException: If the startis outside the range of valid indexes for the List<T>. Below programs illustrate the use of above-discussed method: Example 1: // C# program to illustrate the // List<T>.FindLastIndex(Int32,// Predicate <T>) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation // List name is "PC" List<string> PC = new List<string>(); // elements in the List PC.Add("Computer"); PC.Add("keyboard"); PC.Add("laptop"); PC.Add("mouse"); // the search will starts from index 2 int indx = PC.FindLastIndex(2, FindIndex); Console.WriteLine(indx); } // Conditional method private static bool FindIndex(string g) { if (g == "Computer") { return true; } else { return false; } }} Output: 0 Example 2: // C# program to illustrate the // List<T>.FindLastIndex(Int32,// Predicate <T>) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation // List name is "PC" List<int> PC = new List<int>(); // elements in the List PC.Add(3); PC.Add(4); PC.Add(5); PC.Add(6); // condition is "FindIndex" int indx = PC.FindLastIndex(2, FindIndex); Console.WriteLine(indx); } // Conditional method private static bool FindIndex(int g) { // search for "5" if (g == 5) { return true; } else { return false; } }} Output: 2 Example 3: In this example we use an XML file and search an item from a starting index and prints the index of that item, if the item is not found then prints “-1” and if found then prints the index. The item is “GeeksForGeeks”. But here we don’t have the XML file, and here the compiler gives an exception. // C# program to illustrate the // List<T>.FindLastIndex(Int32,// Predicate <T>) Methodusing System;using System.Collections.Generic;using System.Linq; class GFG { // here List<T> contains the object "gfg" using // data from a sample XML file // List initialize private static List<gfg> geeks = new List<gfg>(); public static void Main() { // if the item is found then // it prints the index // if not found prints "-1" int x = geeks.FindLastIndex(3, FindGFG); Console.WriteLine(x); } // conditional method private static bool FindGFG(gfg g) { // item is "GeeksForGeeks" if (g.G == "GeeksForGeeks") { return true; } else { return false; } }} public class gfg { public string G { get; set; }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: ArgumentOutOfRange_IndexParameter name: startIndex This method searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the entire List and the list contains the specified number of elements and ends at the specified index. Syntax: public int FindLastIndex (int startIndex, int count, Predicate<T> match); Parameters:startIndex: It is the zero-based starting index of the backward search.count: It is the number of elements in the section to search.match: It is the Predicate<T> delegate that defines the conditions of the element to search for. Return Value: If the element is found then it returns the zero-based index of type Int32 of the last element that matches a specified condition by the parameter “match”. And if not found then it returns “-1”. Exceptions: ArgumentNullException: if the “match” is null. ArgumentOutOfRangeException: if “startIndex” is outside the range or “count” is less than 0(Zero) or “startIndex” and “count” do not specify a valid section in the List Example: // C# Program to illustrate the // FindLastIndex(Int32, Int32, // Predicate<T>) Methodusing System;using System.Collections.Generic; class GFG{ public static void Main() { // List name is "mylist" List<string> mylist = new List<string>(); // Elements in the List mylist.Add("C"); mylist.Add("C++"); mylist.Add("Java"); mylist.Add("Python"); mylist.Add("C#"); mylist.Add("HTML"); mylist.Add("Java"); mylist.Add("PHP"); // the search will starts from index 2 // the number of element is 3 int indx = mylist.FindLastIndex(2, 3, FindIndex); Console.WriteLine("The index of Java is: "+indx); } // Conditional method private static bool FindIndex(string g) { if (g == "Java") { return true; } else { return false; } }} Output: The index of Java is: 2 Note: The List<T> is searched backward starting at startIndex and ending at the first element. The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List<T> are individually passed to the Predicate<T> delegate. This method performs a linear search; therefore, this method is an O(n) operation, where n is the number of elements from the beginning of the List<T> to start. nidhi_biet CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types C# | Constructors C# | Class and Object Extension Method in C# C# | Replace() Method Difference between Ref and Out keywords in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2019" }, { "code": null, "e": 287, "s": 28, "text": "This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method:" }, { "code": null, "e": 322, "s": 287, "text": "FindLastIndex(Predicate<T>) Method" }, { "code": null, "e": 364, "s": 322, "text": "FindLastIndex(Int32, Predicate<T>) Method" }, { "code": null, "e": 413, "s": 364, "text": "FindLastIndex(Int32, Int32, Predicate<T>) Method" }, { "code": null, "e": 462, "s": 413, "text": "Here, we will discuss only the last two methods." }, { "code": null, "e": 721, "s": 462, "text": "This method searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the range of elements in the List<T> that extends from the first element to the specified index." }, { "code": null, "e": 787, "s": 721, "text": "Syntax: public int FindLastIndex (int start, Predicate<T> match);" }, { "code": null, "e": 950, "s": 787, "text": "Parameters:start: It is the starting index from the searching will starts.match: It is the Predicate delegate that defines the conditions of the searched element." }, { "code": null, "e": 1176, "s": 950, "text": "Return Value: If the element is found then it returns the zero-based index of type Int32 of the last occurrence of an element that matches a specified condition by the parameter “match”. And if not found then it returns “-1”." }, { "code": null, "e": 1188, "s": 1176, "text": "Exceptions:" }, { "code": null, "e": 1233, "s": 1188, "text": "ArgumentNullException: If the match is null." }, { "code": null, "e": 1329, "s": 1233, "text": "ArgumentOutOfRangeException: If the startis outside the range of valid indexes for the List<T>." }, { "code": null, "e": 1390, "s": 1329, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 1401, "s": 1390, "text": "Example 1:" }, { "code": "// C# program to illustrate the // List<T>.FindLastIndex(Int32,// Predicate <T>) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation // List name is \"PC\" List<string> PC = new List<string>(); // elements in the List PC.Add(\"Computer\"); PC.Add(\"keyboard\"); PC.Add(\"laptop\"); PC.Add(\"mouse\"); // the search will starts from index 2 int indx = PC.FindLastIndex(2, FindIndex); Console.WriteLine(indx); } // Conditional method private static bool FindIndex(string g) { if (g == \"Computer\") { return true; } else { return false; } }}", "e": 2204, "s": 1401, "text": null }, { "code": null, "e": 2212, "s": 2204, "text": "Output:" }, { "code": null, "e": 2215, "s": 2212, "text": "0\n" }, { "code": null, "e": 2226, "s": 2215, "text": "Example 2:" }, { "code": "// C# program to illustrate the // List<T>.FindLastIndex(Int32,// Predicate <T>) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation // List name is \"PC\" List<int> PC = new List<int>(); // elements in the List PC.Add(3); PC.Add(4); PC.Add(5); PC.Add(6); // condition is \"FindIndex\" int indx = PC.FindLastIndex(2, FindIndex); Console.WriteLine(indx); } // Conditional method private static bool FindIndex(int g) { // search for \"5\" if (g == 5) { return true; } else { return false; } }}", "e": 3013, "s": 2226, "text": null }, { "code": null, "e": 3021, "s": 3013, "text": "Output:" }, { "code": null, "e": 3024, "s": 3021, "text": "2\n" }, { "code": null, "e": 3332, "s": 3024, "text": "Example 3: In this example we use an XML file and search an item from a starting index and prints the index of that item, if the item is not found then prints “-1” and if found then prints the index. The item is “GeeksForGeeks”. But here we don’t have the XML file, and here the compiler gives an exception." }, { "code": "// C# program to illustrate the // List<T>.FindLastIndex(Int32,// Predicate <T>) Methodusing System;using System.Collections.Generic;using System.Linq; class GFG { // here List<T> contains the object \"gfg\" using // data from a sample XML file // List initialize private static List<gfg> geeks = new List<gfg>(); public static void Main() { // if the item is found then // it prints the index // if not found prints \"-1\" int x = geeks.FindLastIndex(3, FindGFG); Console.WriteLine(x); } // conditional method private static bool FindGFG(gfg g) { // item is \"GeeksForGeeks\" if (g.G == \"GeeksForGeeks\") { return true; } else { return false; } }} public class gfg { public string G { get; set; }}", "e": 4217, "s": 3332, "text": null }, { "code": null, "e": 4232, "s": 4217, "text": "Runtime Error:" }, { "code": null, "e": 4339, "s": 4232, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: ArgumentOutOfRange_IndexParameter name: startIndex" }, { "code": null, "e": 4605, "s": 4339, "text": "This method searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the entire List and the list contains the specified number of elements and ends at the specified index." }, { "code": null, "e": 4687, "s": 4605, "text": "Syntax: public int FindLastIndex (int startIndex, int count, Predicate<T> match);" }, { "code": null, "e": 4927, "s": 4687, "text": "Parameters:startIndex: It is the zero-based starting index of the backward search.count: It is the number of elements in the section to search.match: It is the Predicate<T> delegate that defines the conditions of the element to search for." }, { "code": null, "e": 5136, "s": 4927, "text": "Return Value: If the element is found then it returns the zero-based index of type Int32 of the last element that matches a specified condition by the parameter “match”. And if not found then it returns “-1”." }, { "code": null, "e": 5148, "s": 5136, "text": "Exceptions:" }, { "code": null, "e": 5195, "s": 5148, "text": "ArgumentNullException: if the “match” is null." }, { "code": null, "e": 5364, "s": 5195, "text": "ArgumentOutOfRangeException: if “startIndex” is outside the range or “count” is less than 0(Zero) or “startIndex” and “count” do not specify a valid section in the List" }, { "code": null, "e": 5373, "s": 5364, "text": "Example:" }, { "code": "// C# Program to illustrate the // FindLastIndex(Int32, Int32, // Predicate<T>) Methodusing System;using System.Collections.Generic; class GFG{ public static void Main() { // List name is \"mylist\" List<string> mylist = new List<string>(); // Elements in the List mylist.Add(\"C\"); mylist.Add(\"C++\"); mylist.Add(\"Java\"); mylist.Add(\"Python\"); mylist.Add(\"C#\"); mylist.Add(\"HTML\"); mylist.Add(\"Java\"); mylist.Add(\"PHP\"); // the search will starts from index 2 // the number of element is 3 int indx = mylist.FindLastIndex(2, 3, FindIndex); Console.WriteLine(\"The index of Java is: \"+indx); } // Conditional method private static bool FindIndex(string g) { if (g == \"Java\") { return true; } else { return false; } }}", "e": 6325, "s": 5373, "text": null }, { "code": null, "e": 6333, "s": 6325, "text": "Output:" }, { "code": null, "e": 6358, "s": 6333, "text": "The index of Java is: 2\n" }, { "code": null, "e": 6364, "s": 6358, "text": "Note:" }, { "code": null, "e": 6453, "s": 6364, "text": "The List<T> is searched backward starting at startIndex and ending at the first element." }, { "code": null, "e": 6679, "s": 6453, "text": "The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List<T> are individually passed to the Predicate<T> delegate." }, { "code": null, "e": 6840, "s": 6679, "text": "This method performs a linear search; therefore, this method is an O(n) operation, where n is the number of elements from the beginning of the List<T> to start." }, { "code": null, "e": 6851, "s": 6840, "text": "nidhi_biet" }, { "code": null, "e": 6871, "s": 6851, "text": "CSharp-Generic-List" }, { "code": null, "e": 6896, "s": 6871, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 6910, "s": 6896, "text": "CSharp-method" }, { "code": null, "e": 6913, "s": 6910, "text": "C#" }, { "code": null, "e": 6932, "s": 6913, "text": "Technical Scripter" }, { "code": null, "e": 7030, "s": 6932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7061, "s": 7030, "text": "Introduction to .NET Framework" }, { "code": null, "e": 7076, "s": 7061, "text": "C# | Delegates" }, { "code": null, "e": 7119, "s": 7076, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 7168, "s": 7119, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 7184, "s": 7168, "text": "C# | Data Types" }, { "code": null, "e": 7202, "s": 7184, "text": "C# | Constructors" }, { "code": null, "e": 7224, "s": 7202, "text": "C# | Class and Object" }, { "code": null, "e": 7247, "s": 7224, "text": "Extension Method in C#" }, { "code": null, "e": 7269, "s": 7247, "text": "C# | Replace() Method" } ]
Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
07 Jul, 2022 Given a N X N matrix Mat[N][N] of positive integers. There are only three possible moves from a cell (i, j) (i+1, j)(i+1, j-1)(i+1, j+1) (i+1, j) (i+1, j-1) (i+1, j+1) Starting from any column in row 0, return the largest sum of any of the paths up to row N-1. Examples: Input : mat[4][4] = { {4, 2, 3, 4}, {2, 9, 1, 10}, {15, 1, 3, 0}, {16, 92, 41, 44} }; Output :120 path : 4 + 9 + 15 + 92 = 120 Asked in: Amazon interview The above problem can be recursively defined.Let initial position be MaximumPathSum(N-1, j), where j varies from 0 to N-1. We return maximum value between all path that we start traversing (N-1, j) [ where j varies from 0 to N-1] i = N-1, j = 0 to N -1 int MaximumPath(Mat[][N], I, j) // IF we reached to first row of // matrix then return value of that // element IF ( i == 0 && j = 0 ) return Mat[i][j] // out of matrix bound IF( i = N || j < 0 ) return 0; // call all rest position that we reached // from current position and find maximum // between them and add current value in // that path return max(MaximumPath(Mat, i-1, j), MaximumPath(Mat, i-1, j-1), MaximumPath(Mat, i-1, j+1))) + Mat[i][j]; If we draw recursion tree of above recursive solution, we can observe overlapping subproblems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'#include<bits/stdc++.h>using namespace std;#define N 4 // function find maximum sum pathint MaximumPath(int Mat[][N]){ int result = 0 ; // create 2D matrix to store the sum // of the path int dp[N][N+2]; // initialize all dp matrix as '0' memset(dp, 0, sizeof(dp)); // copy all element of first row into // 'dp' first row for (int i = 0 ; i < N ; i++) dp[0][i+1] = Mat[0][i]; for (int i = 1 ; i < N ; i++) for (int j = 1 ; j <= N ; j++) dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + Mat[i][j-1] ; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i=0; i<=N; i++) result = max(result, dp[N-1][i]); // return maximum sum path return result ;} // driver program to test above functionint main(){ int Mat[4][4] = { { 4, 2 , 3 , 4 }, { 2 , 9 , 1 , 10}, { 15, 1 , 3 , 0 }, { 16 ,92, 41, 44 } }; cout << MaximumPath ( Mat ) <<endl ; return 0;} // Java program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'import java.util.*; public class GFG { private static int N = 4; // function find maximum sum path private static int maximumPath(int Mat[][]){ int result = 0; // create 2D matrix to store the sum // of the path int dp[][] = new int[N][N + 2]; // copy all element of first row into // 'dp' first row for (int i = 0; i < N; i++) dp[0][i + 1] = Mat[0][i]; for (int i = 1; i < N; i++) for (int j = 1; j <= N; j++) dp[i][j] = Math.max(dp[i - 1][j - 1], Math.max(dp[i - 1][j], dp[i - 1][j + 1])) + Mat[i][j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i = 0; i <= N; i++) result = Math.max(result, dp[N - 1][i]); // return maximum sum path return result; } // driver code public static void main(String arg[]){ int Mat[][] = { { 4, 2, 3, 4 }, { 2, 9, 1, 10 }, { 15, 1, 3, 0 }, { 16, 92, 41, 44 } }; System.out.println(maximumPath(Mat)); }} // This code is contributed by Anant Agarwal. # Python3 program to find# Maximum path sum# start any column in# row '0' and ends# up to any column in row 'n-1' N = 4 # function find maximum sum pathdef MaximumPath(Mat): result = 0 # create 2D matrix to store the sum # of the path # initialize all dp matrix as '0' dp = [[0 for i in range(N+2)] for j in range(N)] # copy all element of first row into # dp first row for i in range(N): for j in range(1, N+1): dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + \ Mat[i][j-1] # Find maximum path sum that end ups # at any column of last row 'N-1' for i in range(N+1): result = max(result, dp[N-1][i]) # return maximum sum path return result # driver program to test above functionMat = [[4, 2, 3, 4], [2, 9, 1, 10], [15, 1, 3, 0], [16, 92, 41, 44]] print(MaximumPath(Mat)) # This code is contributed by Soumen Ghosh. // C# program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'using System; class GFG { static int N = 4; // function find maximum sum path static int MaximumPath(int [,] Mat) { int result = 0; // create 2D matrix to store the sum // of the path int [,]dp = new int[N,N + 2]; // initialize all dp matrix as '0' //for (int[] rows : dp) // Arrays.fill(rows, 0); // copy all element of first row into // 'dp' first row for (int i = 0; i < N; i++) dp[0,i + 1] = Mat[0,i]; for (int i = 1; i < N; i++) for (int j = 1; j <= N; j++) dp[i,j] = Math.Max(dp[i - 1,j - 1], Math.Max(dp[i - 1,j], dp[i - 1,j + 1])) + Mat[i,j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i = 0; i <= N; i++) result = Math.Max(result, dp[N - 1,i]); // return maximum sum path return result; } // driver code public static void Main() { int [,]Mat = { { 4, 2, 3, 4 }, { 2, 9, 1, 10 }, { 15, 1, 3, 0 }, { 16, 92, 41, 44 } }; Console.WriteLine(MaximumPath(Mat)); }} // This code is contributed by Ryuga. <?php// PHP program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'$N = 4; // function find maximum sum pathfunction MaximumPath(&$Mat){ global $N; $result = 0; // create 2D matrix to store the sum // of the path $dp = array_fill(0, $N, array_fill(0, $N + 2, NULL)); // copy all element of first row // into 'dp' first row for ($i = 0 ; $i < $N ; $i++) $dp[0][$i + 1] = $Mat[0][$i]; for ($i = 1 ; $i < $N ; $i++) for ($j = 1 ; $j <= $N ; $j++) $dp[$i][$j] = max($dp[$i - 1][$j - 1], max($dp[$i - 1][$j], $dp[$i - 1][$j + 1])) + $Mat[$i][$j - 1] ; // Find maximum path sum that end ups // at any column of last row 'N-1' for ($i = 0; $i <= $N; $i++) $result = max($result, $dp[$N - 1][$i]); // return maximum sum path return $result ;} // Driver Code$Mat = array(array(4, 2 , 3 , 4), array(2 , 9 , 1 , 10), array(15, 1 , 3 , 0), array(16 ,92, 41, 44)); echo MaximumPath ($Mat) . "\n" ; // This code is contributed by ita_c?> <script> // Javascript program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1' let N = 4; // function find maximum sum path function MaximumPath(Mat) { let result = 0; // create 2D matrix to store the sum // of the path let dp = new Array(N); // initialize all dp matrix as '0' for(let i=0;i<N;i++) { dp[i]=new Array(N+2); for(let j=0;j<N+2;j++) { dp[i][j]=0; } } // copy all element of first row into // 'dp' first row for (let i = 0; i < N; i++) dp[0][i + 1] = Mat[0][i]; for (let i = 1; i < N; i++) for (let j = 1; j <= N; j++) dp[i][j] = Math.max(dp[i - 1][j - 1], Math.max(dp[i - 1][j], dp[i - 1][j + 1])) + Mat[i][j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (let i = 0; i <= N; i++) result = Math.max(result, dp[N - 1][i]); // return maximum sum path return result; } // driver code let Mat = [[4, 2, 3, 4], [2, 9, 1, 10], [15, 1, 3, 0], [16, 92, 41, 44]] document.write(MaximumPath(Mat)) // This code is contributed by rag2127 </script> 120 Time complexity : O(N2) This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. ankthon ukasp rag2127 saurabh1990aror abhishekagashe ashutosh dubey 2 hardikkoriintern Dynamic Programming Matrix Dynamic Programming 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 Matrix Chain Multiplication | DP-8 Sieve of Eratosthenes Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 163, "s": 54, "text": "Given a N X N matrix Mat[N][N] of positive integers. There are only three possible moves from a cell (i, j) " }, { "code": null, "e": 192, "s": 163, "text": "(i+1, j)(i+1, j-1)(i+1, j+1)" }, { "code": null, "e": 201, "s": 192, "text": "(i+1, j)" }, { "code": null, "e": 212, "s": 201, "text": "(i+1, j-1)" }, { "code": null, "e": 223, "s": 212, "text": "(i+1, j+1)" }, { "code": null, "e": 316, "s": 223, "text": "Starting from any column in row 0, return the largest sum of any of the paths up to row N-1." }, { "code": null, "e": 327, "s": 316, "text": "Examples: " }, { "code": null, "e": 521, "s": 327, "text": "Input : mat[4][4] = { {4, 2, 3, 4},\n {2, 9, 1, 10},\n {15, 1, 3, 0},\n {16, 92, 41, 44} };\nOutput :120\npath : 4 + 9 + 15 + 92 = 120 " }, { "code": null, "e": 549, "s": 521, "text": "Asked in: Amazon interview " }, { "code": null, "e": 780, "s": 549, "text": "The above problem can be recursively defined.Let initial position be MaximumPathSum(N-1, j), where j varies from 0 to N-1. We return maximum value between all path that we start traversing (N-1, j) [ where j varies from 0 to N-1] " }, { "code": null, "e": 1337, "s": 780, "text": "i = N-1, j = 0 to N -1\nint MaximumPath(Mat[][N], I, j)\n \n // IF we reached to first row of \n // matrix then return value of that \n // element \n IF ( i == 0 && j = 0 )\n return Mat[i][j]\n\n // out of matrix bound \n IF( i = N || j < 0 )\n return 0;\n\n // call all rest position that we reached\n // from current position and find maximum \n // between them and add current value in \n // that path \n return max(MaximumPath(Mat, i-1, j), \n MaximumPath(Mat, i-1, j-1), \n MaximumPath(Mat, i-1, j+1)))\n + Mat[i][j];" }, { "code": null, "e": 1580, "s": 1337, "text": "If we draw recursion tree of above recursive solution, we can observe overlapping subproblems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution. " }, { "code": null, "e": 1596, "s": 1580, "text": "Implementation:" }, { "code": null, "e": 1600, "s": 1596, "text": "C++" }, { "code": null, "e": 1605, "s": 1600, "text": "Java" }, { "code": null, "e": 1613, "s": 1605, "text": "Python3" }, { "code": null, "e": 1616, "s": 1613, "text": "C#" }, { "code": null, "e": 1620, "s": 1616, "text": "PHP" }, { "code": null, "e": 1631, "s": 1620, "text": "Javascript" }, { "code": "// C++ program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'#include<bits/stdc++.h>using namespace std;#define N 4 // function find maximum sum pathint MaximumPath(int Mat[][N]){ int result = 0 ; // create 2D matrix to store the sum // of the path int dp[N][N+2]; // initialize all dp matrix as '0' memset(dp, 0, sizeof(dp)); // copy all element of first row into // 'dp' first row for (int i = 0 ; i < N ; i++) dp[0][i+1] = Mat[0][i]; for (int i = 1 ; i < N ; i++) for (int j = 1 ; j <= N ; j++) dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + Mat[i][j-1] ; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i=0; i<=N; i++) result = max(result, dp[N-1][i]); // return maximum sum path return result ;} // driver program to test above functionint main(){ int Mat[4][4] = { { 4, 2 , 3 , 4 }, { 2 , 9 , 1 , 10}, { 15, 1 , 3 , 0 }, { 16 ,92, 41, 44 } }; cout << MaximumPath ( Mat ) <<endl ; return 0;}", "e": 2822, "s": 1631, "text": null }, { "code": "// Java program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'import java.util.*; public class GFG { private static int N = 4; // function find maximum sum path private static int maximumPath(int Mat[][]){ int result = 0; // create 2D matrix to store the sum // of the path int dp[][] = new int[N][N + 2]; // copy all element of first row into // 'dp' first row for (int i = 0; i < N; i++) dp[0][i + 1] = Mat[0][i]; for (int i = 1; i < N; i++) for (int j = 1; j <= N; j++) dp[i][j] = Math.max(dp[i - 1][j - 1], Math.max(dp[i - 1][j], dp[i - 1][j + 1])) + Mat[i][j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i = 0; i <= N; i++) result = Math.max(result, dp[N - 1][i]); // return maximum sum path return result; } // driver code public static void main(String arg[]){ int Mat[][] = { { 4, 2, 3, 4 }, { 2, 9, 1, 10 }, { 15, 1, 3, 0 }, { 16, 92, 41, 44 } }; System.out.println(maximumPath(Mat)); }} // This code is contributed by Anant Agarwal.", "e": 4222, "s": 2822, "text": null }, { "code": "# Python3 program to find# Maximum path sum# start any column in# row '0' and ends# up to any column in row 'n-1' N = 4 # function find maximum sum pathdef MaximumPath(Mat): result = 0 # create 2D matrix to store the sum # of the path # initialize all dp matrix as '0' dp = [[0 for i in range(N+2)] for j in range(N)] # copy all element of first row into # dp first row for i in range(N): for j in range(1, N+1): dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + \\ Mat[i][j-1] # Find maximum path sum that end ups # at any column of last row 'N-1' for i in range(N+1): result = max(result, dp[N-1][i]) # return maximum sum path return result # driver program to test above functionMat = [[4, 2, 3, 4], [2, 9, 1, 10], [15, 1, 3, 0], [16, 92, 41, 44]] print(MaximumPath(Mat)) # This code is contributed by Soumen Ghosh.", "e": 5217, "s": 4222, "text": null }, { "code": "// C# program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'using System; class GFG { static int N = 4; // function find maximum sum path static int MaximumPath(int [,] Mat) { int result = 0; // create 2D matrix to store the sum // of the path int [,]dp = new int[N,N + 2]; // initialize all dp matrix as '0' //for (int[] rows : dp) // Arrays.fill(rows, 0); // copy all element of first row into // 'dp' first row for (int i = 0; i < N; i++) dp[0,i + 1] = Mat[0,i]; for (int i = 1; i < N; i++) for (int j = 1; j <= N; j++) dp[i,j] = Math.Max(dp[i - 1,j - 1], Math.Max(dp[i - 1,j], dp[i - 1,j + 1])) + Mat[i,j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i = 0; i <= N; i++) result = Math.Max(result, dp[N - 1,i]); // return maximum sum path return result; } // driver code public static void Main() { int [,]Mat = { { 4, 2, 3, 4 }, { 2, 9, 1, 10 }, { 15, 1, 3, 0 }, { 16, 92, 41, 44 } }; Console.WriteLine(MaximumPath(Mat)); }} // This code is contributed by Ryuga.", "e": 6671, "s": 5217, "text": null }, { "code": "<?php// PHP program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'$N = 4; // function find maximum sum pathfunction MaximumPath(&$Mat){ global $N; $result = 0; // create 2D matrix to store the sum // of the path $dp = array_fill(0, $N, array_fill(0, $N + 2, NULL)); // copy all element of first row // into 'dp' first row for ($i = 0 ; $i < $N ; $i++) $dp[0][$i + 1] = $Mat[0][$i]; for ($i = 1 ; $i < $N ; $i++) for ($j = 1 ; $j <= $N ; $j++) $dp[$i][$j] = max($dp[$i - 1][$j - 1], max($dp[$i - 1][$j], $dp[$i - 1][$j + 1])) + $Mat[$i][$j - 1] ; // Find maximum path sum that end ups // at any column of last row 'N-1' for ($i = 0; $i <= $N; $i++) $result = max($result, $dp[$N - 1][$i]); // return maximum sum path return $result ;} // Driver Code$Mat = array(array(4, 2 , 3 , 4), array(2 , 9 , 1 , 10), array(15, 1 , 3 , 0), array(16 ,92, 41, 44)); echo MaximumPath ($Mat) . \"\\n\" ; // This code is contributed by ita_c?>", "e": 7850, "s": 6671, "text": null }, { "code": "<script> // Javascript program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1' let N = 4; // function find maximum sum path function MaximumPath(Mat) { let result = 0; // create 2D matrix to store the sum // of the path let dp = new Array(N); // initialize all dp matrix as '0' for(let i=0;i<N;i++) { dp[i]=new Array(N+2); for(let j=0;j<N+2;j++) { dp[i][j]=0; } } // copy all element of first row into // 'dp' first row for (let i = 0; i < N; i++) dp[0][i + 1] = Mat[0][i]; for (let i = 1; i < N; i++) for (let j = 1; j <= N; j++) dp[i][j] = Math.max(dp[i - 1][j - 1], Math.max(dp[i - 1][j], dp[i - 1][j + 1])) + Mat[i][j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (let i = 0; i <= N; i++) result = Math.max(result, dp[N - 1][i]); // return maximum sum path return result; } // driver code let Mat = [[4, 2, 3, 4], [2, 9, 1, 10], [15, 1, 3, 0], [16, 92, 41, 44]] document.write(MaximumPath(Mat)) // This code is contributed by rag2127 </script>", "e": 9317, "s": 7850, "text": null }, { "code": null, "e": 9321, "s": 9317, "text": "120" }, { "code": null, "e": 9346, "s": 9321, "text": "Time complexity : O(N2) " }, { "code": null, "e": 9645, "s": 9346, "text": "This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 9653, "s": 9645, "text": "ankthon" }, { "code": null, "e": 9659, "s": 9653, "text": "ukasp" }, { "code": null, "e": 9667, "s": 9659, "text": "rag2127" }, { "code": null, "e": 9683, "s": 9667, "text": "saurabh1990aror" }, { "code": null, "e": 9698, "s": 9683, "text": "abhishekagashe" }, { "code": null, "e": 9715, "s": 9698, "text": "ashutosh dubey 2" }, { "code": null, "e": 9732, "s": 9715, "text": "hardikkoriintern" }, { "code": null, "e": 9752, "s": 9732, "text": "Dynamic Programming" }, { "code": null, "e": 9759, "s": 9752, "text": "Matrix" }, { "code": null, "e": 9779, "s": 9759, "text": "Dynamic Programming" }, { "code": null, "e": 9786, "s": 9779, "text": "Matrix" }, { "code": null, "e": 9884, "s": 9786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9911, "s": 9884, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 9949, "s": 9911, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 9982, "s": 9949, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 10017, "s": 9982, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 10039, "s": 10017, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 10074, "s": 10039, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 10110, "s": 10074, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 10154, "s": 10110, "text": "Program to find largest element in an array" }, { "code": null, "e": 10185, "s": 10154, "text": "Rat in a Maze | Backtracking-2" } ]
What is the difference between the dot (.) operator and -> in C++?
The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as class, struct, or union are considered "of class type". So the following refers to all three of them. a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class. a→b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that a points to. Note that . is not overloadable. → is overloadable operator, so we can define our own function(operator→()) that should be called when this operator is used. so if a is an object of a class that overloads operator→ (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented. [1] References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the #3 as well. However, I thought this would be more confusing than helpful, since references to pointers (T*&) are rarely ever used. #include<iostream> class A { public: int b; A() { b = 5; } }; int main() { A a = A(); A* x = &a; std::cout << "a.b = " << a.b << "\n"; std::cout << "x->b = " << x->b << "\n"; return 0; } This will give the output − 5 5
[ { "code": null, "e": 1440, "s": 1187, "text": "The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as class, struct, or union are considered \"of class type\". So the following refers to all three of them." }, { "code": null, "e": 1610, "s": 1440, "text": "a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class." }, { "code": null, "e": 1767, "s": 1610, "text": "a→b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a→b is accessing the property b of the object that a points to." }, { "code": null, "e": 2097, "s": 1767, "text": "Note that . is not overloadable. → is overloadable operator, so we can define our own function(operator→()) that should be called when this operator is used. so if a is an object of a class that overloads operator→ (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented." }, { "code": null, "e": 2340, "s": 2097, "text": "[1] References are, semantically, aliases to objects, so I should have added \"or reference to a pointer\" to the #3 as well. However, I thought this would be more confusing than helpful, since references to pointers (T*&) are rarely ever used." }, { "code": null, "e": 2549, "s": 2340, "text": "#include<iostream>\nclass A {\n public: int b;\n A() { b = 5; }\n};\n\nint main() {\n A a = A();\n A* x = &a;\n std::cout << \"a.b = \" << a.b << \"\\n\";\n std::cout << \"x->b = \" << x->b << \"\\n\";\n return 0;\n}" }, { "code": null, "e": 2577, "s": 2549, "text": "This will give the output −" }, { "code": null, "e": 2581, "s": 2577, "text": "5\n5" } ]
Python | Dividing two lists
11 Feb, 2019 Sometimes we come across the situations in which we require to apply a particular function to each elements of two lists at similar index. Most popular of them are 4 of the elementary mathematics operations. These are quite similar and come up as application for certain utilities. Let’s discuss certain ways in which the division of two lists can be performed. Method #1 : Using zip() + list comprehensionThe zip operation can be used to link one list with the other and the computation part can be handled by the list comprehension and hence providing a shorthand to this particular problem. # Python3 code to demonstrate # division of lists# using zip() + list comprehension # initializing lists test_list1 = [3, 5, 2, 6, 4]test_list2 = [7, 3, 4, 1, 5] # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # division of lists# using zip() + list comprehensionres = [i / j for i, j in zip(test_list1, test_list2)] # printing resultprint ("The division list is : " + str(res)) The original list 1 is : [3, 5, 2, 6, 4] The original list 2 is : [7, 3, 4, 1, 5] The division list is : [0.42857142857142855, 1.6666666666666667, 0.5, 6.0, 0.8] Method #2 : Using map()Using map function is most elegant way in which we can possibly perform the twining of a function with both the lists. Different operations other than division can also be applied over it. # Python3 code to demonstrate # division of lists# using map()from operator import truediv # initializing lists test_list1 = [3, 5, 2, 6, 4]test_list2 = [7, 3, 4, 1, 5] # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # division of lists# using map()res = list(map(truediv, test_list1, test_list2)) # printing resultprint ("The division list is : " + str(res)) The original list 1 is : [3, 5, 2, 6, 4] The original list 2 is : [7, 3, 4, 1, 5] The division list is : [0.42857142857142855, 1.6666666666666667, 0.5, 6.0, 0.8] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Feb, 2019" }, { "code": null, "e": 390, "s": 28, "text": "Sometimes we come across the situations in which we require to apply a particular function to each elements of two lists at similar index. Most popular of them are 4 of the elementary mathematics operations. These are quite similar and come up as application for certain utilities. Let’s discuss certain ways in which the division of two lists can be performed." }, { "code": null, "e": 622, "s": 390, "text": "Method #1 : Using zip() + list comprehensionThe zip operation can be used to link one list with the other and the computation part can be handled by the list comprehension and hence providing a shorthand to this particular problem." }, { "code": "# Python3 code to demonstrate # division of lists# using zip() + list comprehension # initializing lists test_list1 = [3, 5, 2, 6, 4]test_list2 = [7, 3, 4, 1, 5] # printing original lists print (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # division of lists# using zip() + list comprehensionres = [i / j for i, j in zip(test_list1, test_list2)] # printing resultprint (\"The division list is : \" + str(res))", "e": 1090, "s": 622, "text": null }, { "code": null, "e": 1253, "s": 1090, "text": "The original list 1 is : [3, 5, 2, 6, 4]\nThe original list 2 is : [7, 3, 4, 1, 5]\nThe division list is : [0.42857142857142855, 1.6666666666666667, 0.5, 6.0, 0.8]\n" }, { "code": null, "e": 1466, "s": 1253, "text": " Method #2 : Using map()Using map function is most elegant way in which we can possibly perform the twining of a function with both the lists. Different operations other than division can also be applied over it." }, { "code": "# Python3 code to demonstrate # division of lists# using map()from operator import truediv # initializing lists test_list1 = [3, 5, 2, 6, 4]test_list2 = [7, 3, 4, 1, 5] # printing original lists print (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # division of lists# using map()res = list(map(truediv, test_list1, test_list2)) # printing resultprint (\"The division list is : \" + str(res))", "e": 1915, "s": 1466, "text": null }, { "code": null, "e": 2078, "s": 1915, "text": "The original list 1 is : [3, 5, 2, 6, 4]\nThe original list 2 is : [7, 3, 4, 1, 5]\nThe division list is : [0.42857142857142855, 1.6666666666666667, 0.5, 6.0, 0.8]\n" }, { "code": null, "e": 2099, "s": 2078, "text": "Python list-programs" }, { "code": null, "e": 2111, "s": 2099, "text": "python-list" }, { "code": null, "e": 2118, "s": 2111, "text": "Python" }, { "code": null, "e": 2134, "s": 2118, "text": "Python Programs" }, { "code": null, "e": 2146, "s": 2134, "text": "python-list" }, { "code": null, "e": 2244, "s": 2146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2262, "s": 2244, "text": "Python Dictionary" }, { "code": null, "e": 2304, "s": 2262, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2326, "s": 2304, "text": "Enumerate() in Python" }, { "code": null, "e": 2361, "s": 2326, "text": "Read a file line by line in Python" }, { "code": null, "e": 2387, "s": 2361, "text": "Python String | replace()" }, { "code": null, "e": 2430, "s": 2387, "text": "Python program to convert a list to string" }, { "code": null, "e": 2469, "s": 2430, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2507, "s": 2469, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2556, "s": 2507, "text": "Python | Convert string dictionary to dictionary" } ]
Walmart Interview Experience for SDE | On- Campus 2021 (Virtual)
26 Aug, 2021 Walmart Global Tech visited our campus in the month of August, to hire students for the Software Development Engineer role.Initially, there was a CGPA based shortlisting, after which around 250 students were selected to attend the Online Assessment. Online Assessment: The platform was HackerEarth, time duration was 1 hour 10 technical MCQs, belonging to OOPS, OS, DBMS, Networks, and SQL 2 coding questions of medium-hard level Coding Questions were: You are given two strings A and B that are made of lowercase English alphabets. Find the number of different pairs ((i,j), (k,l)) such that the substrings A[i...j] and B[k...l] are equal and the value of j-i+1 is minimum.C++C++// Solution to Q1int smallest_common_substrings(string A, string B) { char freq[256] = {0}; for (char c : A) { freq++; } int sum = 0; for (char c : B) { sum += freq; } return sum;}Given an array of N items a1,a2.....anGiven two integers K and X. Where K denotes the maximum number of jumps you can take in either direction that is from the position i, you can jump to position j in one step only if abs(j-i) <= K and 1<=j<=n.Jumping from i to j and will cost X amount if a[i] = a[j].Find minimum cost to reach position N from position 1.C++C++//Solution to Q2#include <bits/stdc++.h>using namespace std; int solve(vector<int> &arr, int n, int k, int x){ vector<int> dptable(n, INT_MAX); dptable[0] = 0; for (int i = 0; i < n; i++) { for (int j = max(0, i - k); j <= min(n - 1, i + k); j++) { if (dptable[j] > dptable[i] + (arr[j] == arr[i] ? 0 : x)) { dptable[j] = dptable[i] + (arr[j] == arr[i] ? 0 : x); } } } return dptable[n - 1];} int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> arr(n); for (auto &x : arr) cin >> x; int k, x; cin >> k >> x; cout << solve(arr, n, k, x); return 0;} You are given two strings A and B that are made of lowercase English alphabets. Find the number of different pairs ((i,j), (k,l)) such that the substrings A[i...j] and B[k...l] are equal and the value of j-i+1 is minimum.C++C++// Solution to Q1int smallest_common_substrings(string A, string B) { char freq[256] = {0}; for (char c : A) { freq++; } int sum = 0; for (char c : B) { sum += freq; } return sum;} C++ // Solution to Q1int smallest_common_substrings(string A, string B) { char freq[256] = {0}; for (char c : A) { freq++; } int sum = 0; for (char c : B) { sum += freq; } return sum;} Given an array of N items a1,a2.....anGiven two integers K and X. Where K denotes the maximum number of jumps you can take in either direction that is from the position i, you can jump to position j in one step only if abs(j-i) <= K and 1<=j<=n.Jumping from i to j and will cost X amount if a[i] = a[j].Find minimum cost to reach position N from position 1.C++C++//Solution to Q2#include <bits/stdc++.h>using namespace std; int solve(vector<int> &arr, int n, int k, int x){ vector<int> dptable(n, INT_MAX); dptable[0] = 0; for (int i = 0; i < n; i++) { for (int j = max(0, i - k); j <= min(n - 1, i + k); j++) { if (dptable[j] > dptable[i] + (arr[j] == arr[i] ? 0 : x)) { dptable[j] = dptable[i] + (arr[j] == arr[i] ? 0 : x); } } } return dptable[n - 1];} int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> arr(n); for (auto &x : arr) cin >> x; int k, x; cin >> k >> x; cout << solve(arr, n, k, x); return 0;} C++ //Solution to Q2#include <bits/stdc++.h>using namespace std; int solve(vector<int> &arr, int n, int k, int x){ vector<int> dptable(n, INT_MAX); dptable[0] = 0; for (int i = 0; i < n; i++) { for (int j = max(0, i - k); j <= min(n - 1, i + k); j++) { if (dptable[j] > dptable[i] + (arr[j] == arr[i] ? 0 : x)) { dptable[j] = dptable[i] + (arr[j] == arr[i] ? 0 : x); } } } return dptable[n - 1];} int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> arr(n); for (auto &x : arr) cin >> x; int k, x; cin >> k >> x; cout << solve(arr, n, k, x); return 0;} Was able to pass all test cases of both the problems, students with 1 total and 1 partial solution also made it to the next round. 33 were selected for the next round. Round 1(Techincal Interview 1): 45- 50 min This round was a technical interview conducted over Zoom. The interviewer first introduced himself, he was an SDE 3(backend) and had 10 years of experience in the IT field and was working with Walmart for quite some time. I was not asked to code any problem in this round, it focused more on core CSE subjects. I was asked to introduce myself and then we went straight to the technical questions. He gave me a google docs link which I could use to explain answers to him. There are 2 machines and the first machine wants to send a message to the other. Explain in detail how the communication takes place. I explained everything about the OSI and TCP/IP model, the working of each layer in transmitting data, 3-way handshaking protocol to establish connections. He was satisfied with my answer.Was about the implementation of STL, he asked me if I am given an unordered set of n numbers, how will I change it to an ordered set without using a sorting algorithm. I told him that we can make a BST of the given unordered set and then do inorder traversal of the tree to get an ordered set of the elements. I explained my approach on the google doc.He was satisfied and didn’t ask me to code it.Given a sorted array, with 1 repeating number find the number. I gave him the simple o(n) solution, after which he asked me to make my solution more complex(yes, more complex) it was very odd and interesting at the same time for an interviewer to ask me to make my solution more complex, the interviewer was very polite and we had a good discussion on it.Various questions on Threading, Paging and Segmentation were asked. The interview went for about 50 minutes, at the end he asked whether I had any questions for him, I asked about his day-to-day responsibilities at Walmart, which he answered in a very informative and polite manner. There are 2 machines and the first machine wants to send a message to the other. Explain in detail how the communication takes place. I explained everything about the OSI and TCP/IP model, the working of each layer in transmitting data, 3-way handshaking protocol to establish connections. He was satisfied with my answer. Was about the implementation of STL, he asked me if I am given an unordered set of n numbers, how will I change it to an ordered set without using a sorting algorithm. I told him that we can make a BST of the given unordered set and then do inorder traversal of the tree to get an ordered set of the elements. I explained my approach on the google doc.He was satisfied and didn’t ask me to code it. Given a sorted array, with 1 repeating number find the number. I gave him the simple o(n) solution, after which he asked me to make my solution more complex(yes, more complex) it was very odd and interesting at the same time for an interviewer to ask me to make my solution more complex, the interviewer was very polite and we had a good discussion on it. Various questions on Threading, Paging and Segmentation were asked. The interview went for about 50 minutes, at the end he asked whether I had any questions for him, I asked about his day-to-day responsibilities at Walmart, which he answered in a very informative and polite manner. 25 were selected for the next round. Tips: Prepare the core subjects very well since they are equally as important as DSA and ask good and meaningful questions to the interviewer at the end of the interview. Round 2(Technical Interview 2): 1 hour Conducted over zoom. The interviewer was a Senior Data Scientist at Walmart and he told me initially that this would be a coding round. Before moving on to the coding questions, we had a good discussion about my projects since my resume was primarily data science-based. Few questions I was asked How is LSTM better than simple RNN? Explained about the vanishing gradient problem, explained the mathematics behind it, was satisfied.Why did you use Random Forest Algorithm in one of your projects? Explained the pros of Random Forest, its working, how is it different from a decision tree.What is relative feature importance and partial dependent plots? Had used it in one of my projects so explained it to him, was satisfied.What is the bias-variance trade-off and how can Random Forest be used to solve personalization problems? Then he moved onto the coding questions, he asked me to open my favorite IDE and code.Pattern printing question: https://practice.geeksforgeeks.org/problems/pascal-triangle0652/1. Identified that it was a pascal’s triangle, explained the logic to him, then he asked me to code it while sharing my screen.The code ran successfully, he was satisfied.Finding a loop in the linked list: https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1. Wasn’t asked to code this, only needed to explain the approach to him, gave him the brute force approach, then used maps to reduce the complexity, he was satisfied with O(n) time and O(n) space complexity (PS: it can be solved in O(1) space as well)Write a function that has an equal probability of printing YES and NO. Gave him the idea of rand() in C++, he then followed up by making the probability of printing YES as 25% and then 10%. Suggested some tweaks in the rand() function, he was satisfied. How is LSTM better than simple RNN? Explained about the vanishing gradient problem, explained the mathematics behind it, was satisfied. Why did you use Random Forest Algorithm in one of your projects? Explained the pros of Random Forest, its working, how is it different from a decision tree. What is relative feature importance and partial dependent plots? Had used it in one of my projects so explained it to him, was satisfied. What is the bias-variance trade-off and how can Random Forest be used to solve personalization problems? Then he moved onto the coding questions, he asked me to open my favorite IDE and code. Pattern printing question: https://practice.geeksforgeeks.org/problems/pascal-triangle0652/1. Identified that it was a pascal’s triangle, explained the logic to him, then he asked me to code it while sharing my screen.The code ran successfully, he was satisfied. Finding a loop in the linked list: https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1. Wasn’t asked to code this, only needed to explain the approach to him, gave him the brute force approach, then used maps to reduce the complexity, he was satisfied with O(n) time and O(n) space complexity (PS: it can be solved in O(1) space as well) Write a function that has an equal probability of printing YES and NO. Gave him the idea of rand() in C++, he then followed up by making the probability of printing YES as 25% and then 10%. Suggested some tweaks in the rand() function, he was satisfied. The interview went for about 1 hour, at the end he asked whether I had any questions for him, I asked about his day-to-day responsibilities at Walmart as a Data Scientist, which he answered in a very informative and polite manner. Tips: Make sure you can stand up for everything you have written on your resume because the interviewer will go deep into your projects and internships. Round 3(Hiring Manager/HR Round): 1 hr I was asked to stay after my technical round and about 10 minutes later I had this round, I was informed it was my final round. The interviewer first asked me to introduce myself, he then asked some questions based on my resume, my experience about my first hackathon win, why did I do the ML certification which I stated in my resume.He asked me what according to me what is the most important quality in a leader. Then we had a good and long discussion about Walmart, innovations at Walmart, any recent technology which Walmart was working on. He also asked some technical questions like what is Cloud, what is the difference between Public and Private Clouds? I asked him about the various teams working at Walmart. All in all, we had a very good discussion, the interview went for about an hour, he then wished me luck and asked me to look out for any updates from my placement cell. Results were announced the next day, 16 students were selected as FTEs, and 7 were selected as interns which could be converted to FTE based on performance. I was selected as one of the FTEs Tips: Make sure you research everything about the company which you have applied for, use GFG for regular practice for DSA and also for the Core Subjects. Marketing On-Campus Walmart Interview Experiences Walmart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Aug, 2021" }, { "code": null, "e": 304, "s": 54, "text": "Walmart Global Tech visited our campus in the month of August, to hire students for the Software Development Engineer role.Initially, there was a CGPA based shortlisting, after which around 250 students were selected to attend the Online Assessment." }, { "code": null, "e": 378, "s": 304, "text": "Online Assessment: The platform was HackerEarth, time duration was 1 hour" }, { "code": null, "e": 444, "s": 378, "text": "10 technical MCQs, belonging to OOPS, OS, DBMS, Networks, and SQL" }, { "code": null, "e": 484, "s": 444, "text": "2 coding questions of medium-hard level" }, { "code": null, "e": 507, "s": 484, "text": "Coding Questions were:" }, { "code": null, "e": 2044, "s": 507, "text": "You are given two strings A and B that are made of lowercase English alphabets. Find the number of different pairs ((i,j), (k,l)) such that the substrings A[i...j] and B[k...l] are equal and the value of j-i+1 is minimum.C++C++// Solution to Q1int smallest_common_substrings(string A, string B) { char freq[256] = {0}; for (char c : A) { freq++; } int sum = 0; for (char c : B) { sum += freq; } return sum;}Given an array of N items a1,a2.....anGiven two integers K and X. Where K denotes the maximum number of jumps you can take in either direction that is from the position i, you can jump to position j in one step only if abs(j-i) <= K and 1<=j<=n.Jumping from i to j and will cost X amount if a[i] = a[j].Find minimum cost to reach position N from position 1.C++C++//Solution to Q2#include <bits/stdc++.h>using namespace std; int solve(vector<int> &arr, int n, int k, int x){ vector<int> dptable(n, INT_MAX); dptable[0] = 0; for (int i = 0; i < n; i++) { for (int j = max(0, i - k); j <= min(n - 1, i + k); j++) { if (dptable[j] > dptable[i] + (arr[j] == arr[i] ? 0 : x)) { dptable[j] = dptable[i] + (arr[j] == arr[i] ? 0 : x); } } } return dptable[n - 1];} int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> arr(n); for (auto &x : arr) cin >> x; int k, x; cin >> k >> x; cout << solve(arr, n, k, x); return 0;}" }, { "code": null, "e": 2495, "s": 2044, "text": "You are given two strings A and B that are made of lowercase English alphabets. Find the number of different pairs ((i,j), (k,l)) such that the substrings A[i...j] and B[k...l] are equal and the value of j-i+1 is minimum.C++C++// Solution to Q1int smallest_common_substrings(string A, string B) { char freq[256] = {0}; for (char c : A) { freq++; } int sum = 0; for (char c : B) { sum += freq; } return sum;}" }, { "code": null, "e": 2499, "s": 2495, "text": "C++" }, { "code": "// Solution to Q1int smallest_common_substrings(string A, string B) { char freq[256] = {0}; for (char c : A) { freq++; } int sum = 0; for (char c : B) { sum += freq; } return sum;}", "e": 2723, "s": 2499, "text": null }, { "code": null, "e": 3810, "s": 2723, "text": "Given an array of N items a1,a2.....anGiven two integers K and X. Where K denotes the maximum number of jumps you can take in either direction that is from the position i, you can jump to position j in one step only if abs(j-i) <= K and 1<=j<=n.Jumping from i to j and will cost X amount if a[i] = a[j].Find minimum cost to reach position N from position 1.C++C++//Solution to Q2#include <bits/stdc++.h>using namespace std; int solve(vector<int> &arr, int n, int k, int x){ vector<int> dptable(n, INT_MAX); dptable[0] = 0; for (int i = 0; i < n; i++) { for (int j = max(0, i - k); j <= min(n - 1, i + k); j++) { if (dptable[j] > dptable[i] + (arr[j] == arr[i] ? 0 : x)) { dptable[j] = dptable[i] + (arr[j] == arr[i] ? 0 : x); } } } return dptable[n - 1];} int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> arr(n); for (auto &x : arr) cin >> x; int k, x; cin >> k >> x; cout << solve(arr, n, k, x); return 0;}" }, { "code": null, "e": 3814, "s": 3810, "text": "C++" }, { "code": "//Solution to Q2#include <bits/stdc++.h>using namespace std; int solve(vector<int> &arr, int n, int k, int x){ vector<int> dptable(n, INT_MAX); dptable[0] = 0; for (int i = 0; i < n; i++) { for (int j = max(0, i - k); j <= min(n - 1, i + k); j++) { if (dptable[j] > dptable[i] + (arr[j] == arr[i] ? 0 : x)) { dptable[j] = dptable[i] + (arr[j] == arr[i] ? 0 : x); } } } return dptable[n - 1];} int main(){ ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> arr(n); for (auto &x : arr) cin >> x; int k, x; cin >> k >> x; cout << solve(arr, n, k, x); return 0;}", "e": 4538, "s": 3814, "text": null }, { "code": null, "e": 4669, "s": 4538, "text": "Was able to pass all test cases of both the problems, students with 1 total and 1 partial solution also made it to the next round." }, { "code": null, "e": 4706, "s": 4669, "text": "33 were selected for the next round." }, { "code": null, "e": 4749, "s": 4706, "text": "Round 1(Techincal Interview 1): 45- 50 min" }, { "code": null, "e": 4807, "s": 4749, "text": "This round was a technical interview conducted over Zoom." }, { "code": null, "e": 5060, "s": 4807, "text": "The interviewer first introduced himself, he was an SDE 3(backend) and had 10 years of experience in the IT field and was working with Walmart for quite some time. I was not asked to code any problem in this round, it focused more on core CSE subjects." }, { "code": null, "e": 5146, "s": 5060, "text": "I was asked to introduce myself and then we went straight to the technical questions." }, { "code": null, "e": 5221, "s": 5146, "text": "He gave me a google docs link which I could use to explain answers to him." }, { "code": null, "e": 6579, "s": 5221, "text": "There are 2 machines and the first machine wants to send a message to the other. Explain in detail how the communication takes place. I explained everything about the OSI and TCP/IP model, the working of each layer in transmitting data, 3-way handshaking protocol to establish connections. He was satisfied with my answer.Was about the implementation of STL, he asked me if I am given an unordered set of n numbers, how will I change it to an ordered set without using a sorting algorithm. I told him that we can make a BST of the given unordered set and then do inorder traversal of the tree to get an ordered set of the elements. I explained my approach on the google doc.He was satisfied and didn’t ask me to code it.Given a sorted array, with 1 repeating number find the number. I gave him the simple o(n) solution, after which he asked me to make my solution more complex(yes, more complex) it was very odd and interesting at the same time for an interviewer to ask me to make my solution more complex, the interviewer was very polite and we had a good discussion on it.Various questions on Threading, Paging and Segmentation were asked. The interview went for about 50 minutes, at the end he asked whether I had any questions for him, I asked about his day-to-day responsibilities at Walmart, which he answered in a very informative and polite manner." }, { "code": null, "e": 6902, "s": 6579, "text": "There are 2 machines and the first machine wants to send a message to the other. Explain in detail how the communication takes place. I explained everything about the OSI and TCP/IP model, the working of each layer in transmitting data, 3-way handshaking protocol to establish connections. He was satisfied with my answer." }, { "code": null, "e": 7301, "s": 6902, "text": "Was about the implementation of STL, he asked me if I am given an unordered set of n numbers, how will I change it to an ordered set without using a sorting algorithm. I told him that we can make a BST of the given unordered set and then do inorder traversal of the tree to get an ordered set of the elements. I explained my approach on the google doc.He was satisfied and didn’t ask me to code it." }, { "code": null, "e": 7657, "s": 7301, "text": "Given a sorted array, with 1 repeating number find the number. I gave him the simple o(n) solution, after which he asked me to make my solution more complex(yes, more complex) it was very odd and interesting at the same time for an interviewer to ask me to make my solution more complex, the interviewer was very polite and we had a good discussion on it." }, { "code": null, "e": 7940, "s": 7657, "text": "Various questions on Threading, Paging and Segmentation were asked. The interview went for about 50 minutes, at the end he asked whether I had any questions for him, I asked about his day-to-day responsibilities at Walmart, which he answered in a very informative and polite manner." }, { "code": null, "e": 7977, "s": 7940, "text": "25 were selected for the next round." }, { "code": null, "e": 8148, "s": 7977, "text": "Tips: Prepare the core subjects very well since they are equally as important as DSA and ask good and meaningful questions to the interviewer at the end of the interview." }, { "code": null, "e": 8187, "s": 8148, "text": "Round 2(Technical Interview 2): 1 hour" }, { "code": null, "e": 8458, "s": 8187, "text": "Conducted over zoom. The interviewer was a Senior Data Scientist at Walmart and he told me initially that this would be a coding round. Before moving on to the coding questions, we had a good discussion about my projects since my resume was primarily data science-based." }, { "code": null, "e": 8484, "s": 8458, "text": "Few questions I was asked" }, { "code": null, "e": 9977, "s": 8484, "text": "How is LSTM better than simple RNN? Explained about the vanishing gradient problem, explained the mathematics behind it, was satisfied.Why did you use Random Forest Algorithm in one of your projects? Explained the pros of Random Forest, its working, how is it different from a decision tree.What is relative feature importance and partial dependent plots? Had used it in one of my projects so explained it to him, was satisfied.What is the bias-variance trade-off and how can Random Forest be used to solve personalization problems? Then he moved onto the coding questions, he asked me to open my favorite IDE and code.Pattern printing question: https://practice.geeksforgeeks.org/problems/pascal-triangle0652/1. Identified that it was a pascal’s triangle, explained the logic to him, then he asked me to code it while sharing my screen.The code ran successfully, he was satisfied.Finding a loop in the linked list: https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1. Wasn’t asked to code this, only needed to explain the approach to him, gave him the brute force approach, then used maps to reduce the complexity, he was satisfied with O(n) time and O(n) space complexity (PS: it can be solved in O(1) space as well)Write a function that has an equal probability of printing YES and NO. Gave him the idea of rand() in C++, he then followed up by making the probability of printing YES as 25% and then 10%. Suggested some tweaks in the rand() function, he was satisfied." }, { "code": null, "e": 10113, "s": 9977, "text": "How is LSTM better than simple RNN? Explained about the vanishing gradient problem, explained the mathematics behind it, was satisfied." }, { "code": null, "e": 10270, "s": 10113, "text": "Why did you use Random Forest Algorithm in one of your projects? Explained the pros of Random Forest, its working, how is it different from a decision tree." }, { "code": null, "e": 10408, "s": 10270, "text": "What is relative feature importance and partial dependent plots? Had used it in one of my projects so explained it to him, was satisfied." }, { "code": null, "e": 10600, "s": 10408, "text": "What is the bias-variance trade-off and how can Random Forest be used to solve personalization problems? Then he moved onto the coding questions, he asked me to open my favorite IDE and code." }, { "code": null, "e": 10863, "s": 10600, "text": "Pattern printing question: https://practice.geeksforgeeks.org/problems/pascal-triangle0652/1. Identified that it was a pascal’s triangle, explained the logic to him, then he asked me to code it while sharing my screen.The code ran successfully, he was satisfied." }, { "code": null, "e": 11222, "s": 10863, "text": "Finding a loop in the linked list: https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1. Wasn’t asked to code this, only needed to explain the approach to him, gave him the brute force approach, then used maps to reduce the complexity, he was satisfied with O(n) time and O(n) space complexity (PS: it can be solved in O(1) space as well)" }, { "code": null, "e": 11476, "s": 11222, "text": "Write a function that has an equal probability of printing YES and NO. Gave him the idea of rand() in C++, he then followed up by making the probability of printing YES as 25% and then 10%. Suggested some tweaks in the rand() function, he was satisfied." }, { "code": null, "e": 11707, "s": 11476, "text": "The interview went for about 1 hour, at the end he asked whether I had any questions for him, I asked about his day-to-day responsibilities at Walmart as a Data Scientist, which he answered in a very informative and polite manner." }, { "code": null, "e": 11860, "s": 11707, "text": "Tips: Make sure you can stand up for everything you have written on your resume because the interviewer will go deep into your projects and internships." }, { "code": null, "e": 11899, "s": 11860, "text": "Round 3(Hiring Manager/HR Round): 1 hr" }, { "code": null, "e": 12027, "s": 11899, "text": "I was asked to stay after my technical round and about 10 minutes later I had this round, I was informed it was my final round." }, { "code": null, "e": 12315, "s": 12027, "text": "The interviewer first asked me to introduce myself, he then asked some questions based on my resume, my experience about my first hackathon win, why did I do the ML certification which I stated in my resume.He asked me what according to me what is the most important quality in a leader." }, { "code": null, "e": 12445, "s": 12315, "text": "Then we had a good and long discussion about Walmart, innovations at Walmart, any recent technology which Walmart was working on." }, { "code": null, "e": 12562, "s": 12445, "text": "He also asked some technical questions like what is Cloud, what is the difference between Public and Private Clouds?" }, { "code": null, "e": 12618, "s": 12562, "text": "I asked him about the various teams working at Walmart." }, { "code": null, "e": 12787, "s": 12618, "text": "All in all, we had a very good discussion, the interview went for about an hour, he then wished me luck and asked me to look out for any updates from my placement cell." }, { "code": null, "e": 12945, "s": 12787, "text": "Results were announced the next day, 16 students were selected as FTEs, and 7 were selected as interns which could be converted to FTE based on performance. " }, { "code": null, "e": 12980, "s": 12945, "text": "I was selected as one of the FTEs " }, { "code": null, "e": 13135, "s": 12980, "text": "Tips: Make sure you research everything about the company which you have applied for, use GFG for regular practice for DSA and also for the Core Subjects." }, { "code": null, "e": 13145, "s": 13135, "text": "Marketing" }, { "code": null, "e": 13155, "s": 13145, "text": "On-Campus" }, { "code": null, "e": 13163, "s": 13155, "text": "Walmart" }, { "code": null, "e": 13185, "s": 13163, "text": "Interview Experiences" }, { "code": null, "e": 13193, "s": 13185, "text": "Walmart" } ]
Excel VBA Logical Operators
24 Aug, 2021 Logical operators are used for performing logical and asthmatic operations on a set of values or variables. The table depicts all the different types of logical operators supported by Excel: AND (LOGICAL AND) If both the conditions are True, then the Expression is true. Example: Assume variable A holds 10 and variable B holds 0, then a<>0 AND b<>0 is False OR ( Logical OR Operator) If any of the two conditions are True, then the condition is true. Example: Assume variable A holds 10 and variable B holds 0, then a<>0 OR b<>0 is true. NOT ( Logical NOT Operator) Reverse the result. If a condition is true, then the Logical NOT operator will make false. Example: Assume variable A holds 10 and variable B holds 0, then NOT(a<>0 OR b<>0) is false. XOR ( Logical XOR Operator) It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True. Example: Assume variable A holds 10 and variable B holds 0, then (a<>0 XOR b<>0) is true If both the conditions are True, then the Expression is true. Example: Assume variable A holds 20 and variable B holds 0, then a<>0 AND b<>0 is False Program: Private Sub Demo_Loop() Dim a As Integer //Declaring variable a = 20 Dim b As Integer //Declaring variable b = 0 If a <> 0 And b <> 0 Then MsgBox ("AND LOGICAL Operator Result is : True") Else MsgBox ("AND LOGICAL Operator Result is : False") End If End Sub Output: AND LOGICAL Operator Result is : False If any of the two conditions are True, then the condition is true. Example: Assume variable A holds 20 and variable B holds 0, then a<>0 OR b<>0 is true. Program: Private Sub Demo_Loop() Dim a As Integer //Declaring variable a = 20 Dim b As Integer //Declaring variable b = 0 If a <> 0 Or b <> 0 Then MsgBox ("OR LOGICAL Operator Result is : True") Else MsgBox ("OR LOGICAL Operator Result is : False") End If End Sub Output: OR LOGICAL Operator Result is : True Reverse the result. If a condition is true, then the Logical NOT operator will make false. Example: Assume variable A holds 20 and variable B holds 0, then NOT(a<>0 OR b<>0) is false. Program: Private Sub Demo_Loop() Dim a As Integer //Declaring variable a = 20 Dim b As Integer //Declaring variable b = 0 If a <> 0 Not b <> 0 Then MsgBox ("NOT LOGICAL Operator Result is : True") Else MsgBox ("NOT LOGICAL Operator Result is : False") End If End Sub Output: NOT LOGICAL Operator Result is : False It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True. Example: Assume variable A holds 20 and variable B holds 0, then (a<>0 XOR b<>0) is true. Program: Private Sub Demo_Loop() Dim a As Integer //Declaring variable a = 20 Dim b As Integer //Declaring variable b = 0 If a <> 0 Xor b <> 0 Then MsgBox ("XOR LOGICAL Operator Result is : True") Else MsgBox ("XOR LOGICAL Operator Result is : False") End If End Sub Output: XOR LOGICAL Operator Result is : True A Sample Program showing all the Operators is included below along with the outputs: Program: Private Sub Demo_Loop() Dim a As Integer //Declaring variable a = 20 Dim b As Integer //Declaring variable b = 0 If a <> 0 And b <> 0 Then MsgBox ("AND LOGICAL Operator Result is : True") Else MsgBox ("AND LOGICAL Operator Result is : False") End If If a <> 0 Or b <> 0 Then MsgBox ("OR LOGICAL Operator Result is : True") Else MsgBox ("OR LOGICAL Operator Result is : False") End If If Not (a <> 0 Or b <> 0) Then MsgBox ("NOT LOGICAL Operator Result is : True") Else MsgBox ("NOT LOGICAL Operator Result is : False") End If If (a <> 0 Xor b <> 0) Then MsgBox ("XOR LOGICAL Operator Result is : True") Else MsgBox ("XOR LOGICAL Operator Result is : False") End If End Sub Output: AND LOGICAL Operator Result is : False OR LOGICAL Operator Result is : True NOT LOGICAL Operator Result is : False XOR LOGICAL Operator Result is : True akshitsaxenaa09 Excel-VBA Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? How to make a 3 Axis Graph using Excel? Macros in Excel Introduction to Excel Spreadsheet How to Show Percentages in Stacked Column Chart in Excel? How to Create a Macro in Excel?
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Aug, 2021" }, { "code": null, "e": 245, "s": 54, "text": "Logical operators are used for performing logical and asthmatic operations on a set of values or variables. The table depicts all the different types of logical operators supported by Excel:" }, { "code": null, "e": 251, "s": 245, "text": "AND " }, { "code": null, "e": 265, "s": 251, "text": "(LOGICAL AND)" }, { "code": null, "e": 327, "s": 265, "text": "If both the conditions are True, then the Expression is true." }, { "code": null, "e": 336, "s": 327, "text": "Example:" }, { "code": null, "e": 393, "s": 336, "text": "Assume variable A holds 10 and variable B holds 0, then " }, { "code": null, "e": 416, "s": 393, "text": "a<>0 AND b<>0 is False" }, { "code": null, "e": 419, "s": 416, "text": "OR" }, { "code": null, "e": 442, "s": 419, "text": "( Logical OR Operator)" }, { "code": null, "e": 509, "s": 442, "text": "If any of the two conditions are True, then the condition is true." }, { "code": null, "e": 518, "s": 509, "text": "Example:" }, { "code": null, "e": 575, "s": 518, "text": "Assume variable A holds 10 and variable B holds 0, then " }, { "code": null, "e": 597, "s": 575, "text": "a<>0 OR b<>0 is true." }, { "code": null, "e": 601, "s": 597, "text": "NOT" }, { "code": null, "e": 625, "s": 601, "text": "( Logical NOT Operator)" }, { "code": null, "e": 716, "s": 625, "text": "Reverse the result. If a condition is true, then the Logical NOT operator will make false." }, { "code": null, "e": 725, "s": 716, "text": "Example:" }, { "code": null, "e": 782, "s": 725, "text": "Assume variable A holds 10 and variable B holds 0, then " }, { "code": null, "e": 810, "s": 782, "text": "NOT(a<>0 OR b<>0) is false." }, { "code": null, "e": 814, "s": 810, "text": "XOR" }, { "code": null, "e": 838, "s": 814, "text": "( Logical XOR Operator)" }, { "code": null, "e": 967, "s": 838, "text": "It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True." }, { "code": null, "e": 976, "s": 967, "text": "Example:" }, { "code": null, "e": 1033, "s": 976, "text": "Assume variable A holds 10 and variable B holds 0, then " }, { "code": null, "e": 1057, "s": 1033, "text": "(a<>0 XOR b<>0) is true" }, { "code": null, "e": 1119, "s": 1057, "text": "If both the conditions are True, then the Expression is true." }, { "code": null, "e": 1128, "s": 1119, "text": "Example:" }, { "code": null, "e": 1207, "s": 1128, "text": "Assume variable A holds 20 and variable B holds 0, then a<>0 AND b<>0 is False" }, { "code": null, "e": 1216, "s": 1207, "text": "Program:" }, { "code": null, "e": 1491, "s": 1216, "text": "Private Sub Demo_Loop()\n\nDim a As Integer //Declaring variable\n\n a = 20\n\n Dim b As Integer //Declaring variable\n\n b = 0\n\nIf a <> 0 And b <> 0 Then\n\nMsgBox (\"AND LOGICAL Operator Result is : True\")\n\n Else\n\n MsgBox (\"AND LOGICAL Operator Result is : False\")\n\n End If\n\nEnd Sub" }, { "code": null, "e": 1499, "s": 1491, "text": "Output:" }, { "code": null, "e": 1538, "s": 1499, "text": "AND LOGICAL Operator Result is : False" }, { "code": null, "e": 1605, "s": 1538, "text": "If any of the two conditions are True, then the condition is true." }, { "code": null, "e": 1614, "s": 1605, "text": "Example:" }, { "code": null, "e": 1692, "s": 1614, "text": "Assume variable A holds 20 and variable B holds 0, then a<>0 OR b<>0 is true." }, { "code": null, "e": 1701, "s": 1692, "text": "Program:" }, { "code": null, "e": 1957, "s": 1701, "text": "Private Sub Demo_Loop()\nDim a As Integer //Declaring variable\na = 20\nDim b As Integer //Declaring variable\nb = 0\nIf a <> 0 Or b <> 0 Then\nMsgBox (\"OR LOGICAL Operator Result is : True\")\nElse\nMsgBox (\"OR LOGICAL Operator Result is : False\")\nEnd If\nEnd Sub" }, { "code": null, "e": 1965, "s": 1957, "text": "Output:" }, { "code": null, "e": 2002, "s": 1965, "text": "OR LOGICAL Operator Result is : True" }, { "code": null, "e": 2093, "s": 2002, "text": "Reverse the result. If a condition is true, then the Logical NOT operator will make false." }, { "code": null, "e": 2102, "s": 2093, "text": "Example:" }, { "code": null, "e": 2186, "s": 2102, "text": "Assume variable A holds 20 and variable B holds 0, then NOT(a<>0 OR b<>0) is false." }, { "code": null, "e": 2195, "s": 2186, "text": "Program:" }, { "code": null, "e": 2454, "s": 2195, "text": "Private Sub Demo_Loop()\nDim a As Integer //Declaring variable\na = 20\nDim b As Integer //Declaring variable\nb = 0\nIf a <> 0 Not b <> 0 Then\nMsgBox (\"NOT LOGICAL Operator Result is : True\")\nElse\nMsgBox (\"NOT LOGICAL Operator Result is : False\")\nEnd If\nEnd Sub" }, { "code": null, "e": 2462, "s": 2454, "text": "Output:" }, { "code": null, "e": 2501, "s": 2462, "text": "NOT LOGICAL Operator Result is : False" }, { "code": null, "e": 2630, "s": 2501, "text": "It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True." }, { "code": null, "e": 2639, "s": 2630, "text": "Example:" }, { "code": null, "e": 2720, "s": 2639, "text": "Assume variable A holds 20 and variable B holds 0, then (a<>0 XOR b<>0) is true." }, { "code": null, "e": 2729, "s": 2720, "text": "Program:" }, { "code": null, "e": 2988, "s": 2729, "text": "Private Sub Demo_Loop()\nDim a As Integer //Declaring variable\na = 20\nDim b As Integer //Declaring variable\nb = 0\nIf a <> 0 Xor b <> 0 Then\nMsgBox (\"XOR LOGICAL Operator Result is : True\")\nElse\nMsgBox (\"XOR LOGICAL Operator Result is : False\")\nEnd If\nEnd Sub" }, { "code": null, "e": 2996, "s": 2988, "text": "Output:" }, { "code": null, "e": 3034, "s": 2996, "text": "XOR LOGICAL Operator Result is : True" }, { "code": null, "e": 3119, "s": 3034, "text": "A Sample Program showing all the Operators is included below along with the outputs:" }, { "code": null, "e": 3128, "s": 3119, "text": "Program:" }, { "code": null, "e": 3880, "s": 3128, "text": " Private Sub Demo_Loop()\nDim a As Integer //Declaring variable\n a = 20\n Dim b As Integer //Declaring variable\n b = 0\n \n If a <> 0 And b <> 0 Then\n MsgBox (\"AND LOGICAL Operator Result is : True\")\n Else\n MsgBox (\"AND LOGICAL Operator Result is : False\")\n End If\n If a <> 0 Or b <> 0 Then\n MsgBox (\"OR LOGICAL Operator Result is : True\")\n Else\n MsgBox (\"OR LOGICAL Operator Result is : False\")\n End If\n If Not (a <> 0 Or b <> 0) Then\n MsgBox (\"NOT LOGICAL Operator Result is : True\")\n Else\n MsgBox (\"NOT LOGICAL Operator Result is : False\")\n End If\n If (a <> 0 Xor b <> 0) Then\n MsgBox (\"XOR LOGICAL Operator Result is : True\")\n Else\n MsgBox (\"XOR LOGICAL Operator Result is : False\")\n End If\nEnd Sub" }, { "code": null, "e": 3888, "s": 3880, "text": "Output:" }, { "code": null, "e": 4041, "s": 3888, "text": "AND LOGICAL Operator Result is : False\nOR LOGICAL Operator Result is : True\nNOT LOGICAL Operator Result is : False\nXOR LOGICAL Operator Result is : True" }, { "code": null, "e": 4057, "s": 4041, "text": "akshitsaxenaa09" }, { "code": null, "e": 4067, "s": 4057, "text": "Excel-VBA" }, { "code": null, "e": 4074, "s": 4067, "text": "Picked" }, { "code": null, "e": 4080, "s": 4074, "text": "Excel" }, { "code": null, "e": 4178, "s": 4080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4216, "s": 4178, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 4248, "s": 4216, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 4289, "s": 4248, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 4344, "s": 4289, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 4372, "s": 4344, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 4412, "s": 4372, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 4428, "s": 4412, "text": "Macros in Excel" }, { "code": null, "e": 4462, "s": 4428, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 4520, "s": 4462, "text": "How to Show Percentages in Stacked Column Chart in Excel?" } ]
Python – Assign Alphabet to each element
11 Sep, 2021 Given a list of elements, assign similar alphabet to same element. Input : test_list = [4, 5, 2, 4, 2, 6] Output : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’, ‘d’] Explanation : Alphabets assigned to elements as occurring. Input : test_list = [4, 5, 2, 4, 2, 6] Output : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’] Explanation : Alphabets assigned to elements as occurring. Method #1 : Using ascii_lowercase() + loop + list comprehension In this, we extract all lowercase alphabets using lowercase(), and create dictionary mapping same element to similar character, post that we flatten that to appropriate index using list comprehension. Python3 # Python3 code to demonstrate working of# Assign Alphabet to each element# Using ascii_lowercase() + loop + list comprehensionimport string # initializing listtest_list = [4, 5, 2, 4, 2, 6, 5, 2, 5] # printing listprint("The original list : " + str(test_list)) temp = {}cntr = 0for ele in test_list: if ele in temp: continue # assigning same Alphabet to same element temp[ele] = string.ascii_lowercase[cntr] cntr += 1 # flatteningres = [temp.get(ele) for ele in test_list] # printing resultsprint("The mapped List : " + str(res)) The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5] The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b'] Method #2 : Using defaultdict() + ascii_lowercase() + iter() In this we use defaultdict() to assign values to similar elements, ascii_lowercase() is used to get all lowercase all lowercased alphabets. Python3 # Python3 code to demonstrate working of# Assign Alphabet to each element# Using defaultdict() + ascii_lowercase() + iter()from collections import defaultdictimport string # initializing listtest_list = [4, 5, 2, 4, 2, 6, 5, 2, 5] # printing listprint("The original list : " + str(test_list)) # assigning lowercases as iteratortemp = iter(string.ascii_lowercase) # lambda functions fits to similar elementsres = defaultdict(lambda: next(temp)) # flatten in listres = [res[key] for key in test_list] # printing resultsprint("The mapped List : " + str(list(res))) The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5] The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b'] sagartomar9927 akshaysingh98088 Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Defaultdict in Python Python program to add two numbers Python | Get dictionary keys as a list Python Program for Fibonacci numbers Python Program for factorial of a number
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Sep, 2021" }, { "code": null, "e": 95, "s": 28, "text": "Given a list of elements, assign similar alphabet to same element." }, { "code": null, "e": 233, "s": 95, "text": "Input : test_list = [4, 5, 2, 4, 2, 6] Output : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’, ‘d’] Explanation : Alphabets assigned to elements as occurring." }, { "code": null, "e": 368, "s": 233, "text": "Input : test_list = [4, 5, 2, 4, 2, 6] Output : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’] Explanation : Alphabets assigned to elements as occurring. " }, { "code": null, "e": 433, "s": 368, "text": "Method #1 : Using ascii_lowercase() + loop + list comprehension " }, { "code": null, "e": 634, "s": 433, "text": "In this, we extract all lowercase alphabets using lowercase(), and create dictionary mapping same element to similar character, post that we flatten that to appropriate index using list comprehension." }, { "code": null, "e": 642, "s": 634, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Assign Alphabet to each element# Using ascii_lowercase() + loop + list comprehensionimport string # initializing listtest_list = [4, 5, 2, 4, 2, 6, 5, 2, 5] # printing listprint(\"The original list : \" + str(test_list)) temp = {}cntr = 0for ele in test_list: if ele in temp: continue # assigning same Alphabet to same element temp[ele] = string.ascii_lowercase[cntr] cntr += 1 # flatteningres = [temp.get(ele) for ele in test_list] # printing resultsprint(\"The mapped List : \" + str(res))", "e": 1200, "s": 642, "text": null }, { "code": null, "e": 1312, "s": 1200, "text": "The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]\nThe mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']" }, { "code": null, "e": 1373, "s": 1312, "text": "Method #2 : Using defaultdict() + ascii_lowercase() + iter()" }, { "code": null, "e": 1513, "s": 1373, "text": "In this we use defaultdict() to assign values to similar elements, ascii_lowercase() is used to get all lowercase all lowercased alphabets." }, { "code": null, "e": 1521, "s": 1513, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Assign Alphabet to each element# Using defaultdict() + ascii_lowercase() + iter()from collections import defaultdictimport string # initializing listtest_list = [4, 5, 2, 4, 2, 6, 5, 2, 5] # printing listprint(\"The original list : \" + str(test_list)) # assigning lowercases as iteratortemp = iter(string.ascii_lowercase) # lambda functions fits to similar elementsres = defaultdict(lambda: next(temp)) # flatten in listres = [res[key] for key in test_list] # printing resultsprint(\"The mapped List : \" + str(list(res)))", "e": 2083, "s": 1521, "text": null }, { "code": null, "e": 2195, "s": 2083, "text": "The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]\nThe mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']" }, { "code": null, "e": 2210, "s": 2195, "text": "sagartomar9927" }, { "code": null, "e": 2227, "s": 2210, "text": "akshaysingh98088" }, { "code": null, "e": 2248, "s": 2227, "text": "Python list-programs" }, { "code": null, "e": 2271, "s": 2248, "text": "Python string-programs" }, { "code": null, "e": 2278, "s": 2271, "text": "Python" }, { "code": null, "e": 2294, "s": 2278, "text": "Python Programs" }, { "code": null, "e": 2392, "s": 2294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2437, "s": 2392, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2487, "s": 2437, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2503, "s": 2487, "text": "Deque in Python" }, { "code": null, "e": 2519, "s": 2503, "text": "Queue in Python" }, { "code": null, "e": 2541, "s": 2519, "text": "Defaultdict in Python" }, { "code": null, "e": 2563, "s": 2541, "text": "Defaultdict in Python" }, { "code": null, "e": 2597, "s": 2563, "text": "Python program to add two numbers" }, { "code": null, "e": 2636, "s": 2597, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2673, "s": 2636, "text": "Python Program for Fibonacci numbers" } ]
Python Script to create random jokes using pyjokes
02 Dec, 2020 Python supports creation of random jokes using one of its libraries. Let us explore it a little more, Pyjokes is a python library that is used to create one-line jokes for programmers. Informally, it can also be referred as a fun python library which is pretty simple to use. Let us see how you can actually use it to perform the required task, You can simply install it using pip with the following command: pip install pyjokes Now to use it, we need to import the installed library in our python Script using the following command: import pyjokes Before, moving further towards our python script, it is necessary to get familiar with the two functions of Pyjokes library, namely get_joke() and get_jokes(). get_joke() Syntax: get_joke(language,category) As the name suggests, this function is used to actually return a single joke from a certain category and in a particular language, (Categories and languages will be introduced later in this article). get_jokes() Syntax: get_jokes(language,category) It is similar to the get_joke() function, the only difference lies in the fact that instead of returning a single joke, it returns a list of random jokes from a certain category and in a particular language. Language and category are the two parameters of get_joke() and get_jokes() functions. Language specifies in which language you want the joke(s) to be displayed. By default, it is set to “en” that returns jokes in English. All other possible values for language parameter are described below: Similarly, the category parameter specifies the category in which you want joke(s) to be displayed. By default, it is set to “neutral”. All other possible values for the category parameter are described below: Below are some examples to understand better: Example 1: Using get_joke() to generate a single joke Python3 # importing installed libraryimport pyjokes # using get_joke() to generate a single joke#language is english#category is neutralMy_joke = pyjokes.get_joke(language="en", category="neutral") print(My_joke) Output: Example 2: Using get_jokes() to generate a list of jokes Python3 import pyjokes # using get_jokes() to generate a whole list of jokes# language is german# category is twisterlist_of_jokes = pyjokes.get_jokes(language="de", category="twister") # traversing through the generated list of jokes# Range of i may change, depending on the number of jokes# you want to displayfor i in range(0, 4): print(list_of_jokes[i], sep='\n') Output: python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Dec, 2020" }, { "code": null, "e": 398, "s": 53, "text": "Python supports creation of random jokes using one of its libraries. Let us explore it a little more, Pyjokes is a python library that is used to create one-line jokes for programmers. Informally, it can also be referred as a fun python library which is pretty simple to use. Let us see how you can actually use it to perform the required task," }, { "code": null, "e": 462, "s": 398, "text": "You can simply install it using pip with the following command:" }, { "code": null, "e": 482, "s": 462, "text": "pip install pyjokes" }, { "code": null, "e": 587, "s": 482, "text": "Now to use it, we need to import the installed library in our python Script using the following command:" }, { "code": null, "e": 602, "s": 587, "text": "import pyjokes" }, { "code": null, "e": 763, "s": 602, "text": "Before, moving further towards our python script, it is necessary to get familiar with the two functions of Pyjokes library, namely get_joke() and get_jokes(). " }, { "code": null, "e": 775, "s": 763, "text": "get_joke() " }, { "code": null, "e": 783, "s": 775, "text": "Syntax:" }, { "code": null, "e": 811, "s": 783, "text": "get_joke(language,category)" }, { "code": null, "e": 1012, "s": 811, "text": "As the name suggests, this function is used to actually return a single joke from a certain category and in a particular language, (Categories and languages will be introduced later in this article). " }, { "code": null, "e": 1024, "s": 1012, "text": "get_jokes()" }, { "code": null, "e": 1032, "s": 1024, "text": "Syntax:" }, { "code": null, "e": 1061, "s": 1032, "text": "get_jokes(language,category)" }, { "code": null, "e": 1269, "s": 1061, "text": "It is similar to the get_joke() function, the only difference lies in the fact that instead of returning a single joke, it returns a list of random jokes from a certain category and in a particular language." }, { "code": null, "e": 1356, "s": 1269, "text": "Language and category are the two parameters of get_joke() and get_jokes() functions. " }, { "code": null, "e": 1562, "s": 1356, "text": "Language specifies in which language you want the joke(s) to be displayed. By default, it is set to “en” that returns jokes in English. All other possible values for language parameter are described below:" }, { "code": null, "e": 1772, "s": 1562, "text": "Similarly, the category parameter specifies the category in which you want joke(s) to be displayed. By default, it is set to “neutral”. All other possible values for the category parameter are described below:" }, { "code": null, "e": 1818, "s": 1772, "text": "Below are some examples to understand better:" }, { "code": null, "e": 1872, "s": 1818, "text": "Example 1: Using get_joke() to generate a single joke" }, { "code": null, "e": 1880, "s": 1872, "text": "Python3" }, { "code": "# importing installed libraryimport pyjokes # using get_joke() to generate a single joke#language is english#category is neutralMy_joke = pyjokes.get_joke(language=\"en\", category=\"neutral\") print(My_joke)", "e": 2087, "s": 1880, "text": null }, { "code": null, "e": 2095, "s": 2087, "text": "Output:" }, { "code": null, "e": 2152, "s": 2095, "text": "Example 2: Using get_jokes() to generate a list of jokes" }, { "code": null, "e": 2160, "s": 2152, "text": "Python3" }, { "code": "import pyjokes # using get_jokes() to generate a whole list of jokes# language is german# category is twisterlist_of_jokes = pyjokes.get_jokes(language=\"de\", category=\"twister\") # traversing through the generated list of jokes# Range of i may change, depending on the number of jokes# you want to displayfor i in range(0, 4): print(list_of_jokes[i], sep='\\n')", "e": 2525, "s": 2160, "text": null }, { "code": null, "e": 2533, "s": 2525, "text": "Output:" }, { "code": null, "e": 2548, "s": 2533, "text": "python-modules" }, { "code": null, "e": 2563, "s": 2548, "text": "python-utility" }, { "code": null, "e": 2570, "s": 2563, "text": "Python" }, { "code": null, "e": 2668, "s": 2570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2700, "s": 2668, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2727, "s": 2700, "text": "Python Classes and Objects" }, { "code": null, "e": 2748, "s": 2727, "text": "Python OOPs Concepts" }, { "code": null, "e": 2771, "s": 2748, "text": "Introduction To PYTHON" }, { "code": null, "e": 2827, "s": 2771, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2858, "s": 2827, "text": "Python | os.path.join() method" }, { "code": null, "e": 2900, "s": 2858, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2942, "s": 2900, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2981, "s": 2942, "text": "Python | datetime.timedelta() function" } ]
Looping through buttons in Tkinter
26 Mar, 2021 In this article, let’s see how we can loop through the buttons in Tkinter. Stepwise implementation: Step 1: Import the Tkinter package and all of its modules and create a root window (root = Tk()). Python3 # Import package and it's modulesfrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("GeekForGeeks") # Set geometry (widthxheight)root.geometry('400x400') # Execute Tkinterroot.mainloop() Output Step 2: Now let’s add a Entry() class and will display the button name as soon as one of the buttons is clicked. Python3 # Import package and it's modulesfrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("GeekForGeeks") # Set geometry (widthxheight)root.geometry('400x400') # Entry Boxtext = Entry(root, width = 30, bg = 'White')text.pack(pady = 10) # Execute Tkinterroot.mainloop() Output Step 3: Now let’s create an empty dictionary (button_dict) to save all the button objects and a list consisting of names of all the buttons. Now loop over each item of the list to create an button object of it and store it in the dictionary. For the button command, create a function named ‘action’ and for each button call the text_update() function to update the changes in the entry in Entry() object created earlier. Python3 # Import package and it's modulesfrom tkinter import * # text_update functiondef text_updation(language): text.delete(0, END) text.insert(0, language) # create root windowroot = Tk() # root window title and dimensionroot.title("GeekForGeeks") # Set geometry (widthxheight)root.geometry('400x400') # Entry Boxtext = Entry(root, width=30, bg='White')text.pack(pady=10) # create buttonsbutton_dict = {}words = ["Python", "Java", "R", "JavaScript"]for lang in words: # pass each button's text to a function def action(x = lang): return text_updation(x) # create the buttons button_dict[lang] = Button(root, text = lang, command = action) button_dict[lang].pack(pady=10) # Execute Tkinterroot.mainloop() Output Picked Python Tkinter-exercises Python-tkinter 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": 54, "s": 26, "text": "\n26 Mar, 2021" }, { "code": null, "e": 129, "s": 54, "text": "In this article, let’s see how we can loop through the buttons in Tkinter." }, { "code": null, "e": 154, "s": 129, "text": "Stepwise implementation:" }, { "code": null, "e": 252, "s": 154, "text": "Step 1: Import the Tkinter package and all of its modules and create a root window (root = Tk())." }, { "code": null, "e": 260, "s": 252, "text": "Python3" }, { "code": "# Import package and it's modulesfrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"GeekForGeeks\") # Set geometry (widthxheight)root.geometry('400x400') # Execute Tkinterroot.mainloop()", "e": 498, "s": 260, "text": null }, { "code": null, "e": 505, "s": 498, "text": "Output" }, { "code": null, "e": 618, "s": 505, "text": "Step 2: Now let’s add a Entry() class and will display the button name as soon as one of the buttons is clicked." }, { "code": null, "e": 626, "s": 618, "text": "Python3" }, { "code": "# Import package and it's modulesfrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"GeekForGeeks\") # Set geometry (widthxheight)root.geometry('400x400') # Entry Boxtext = Entry(root, width = 30, bg = 'White')text.pack(pady = 10) # Execute Tkinterroot.mainloop()", "e": 941, "s": 626, "text": null }, { "code": null, "e": 950, "s": 941, "text": "Output " }, { "code": null, "e": 1371, "s": 950, "text": "Step 3: Now let’s create an empty dictionary (button_dict) to save all the button objects and a list consisting of names of all the buttons. Now loop over each item of the list to create an button object of it and store it in the dictionary. For the button command, create a function named ‘action’ and for each button call the text_update() function to update the changes in the entry in Entry() object created earlier." }, { "code": null, "e": 1379, "s": 1371, "text": "Python3" }, { "code": "# Import package and it's modulesfrom tkinter import * # text_update functiondef text_updation(language): text.delete(0, END) text.insert(0, language) # create root windowroot = Tk() # root window title and dimensionroot.title(\"GeekForGeeks\") # Set geometry (widthxheight)root.geometry('400x400') # Entry Boxtext = Entry(root, width=30, bg='White')text.pack(pady=10) # create buttonsbutton_dict = {}words = [\"Python\", \"Java\", \"R\", \"JavaScript\"]for lang in words: # pass each button's text to a function def action(x = lang): return text_updation(x) # create the buttons button_dict[lang] = Button(root, text = lang, command = action) button_dict[lang].pack(pady=10) # Execute Tkinterroot.mainloop()", "e": 2159, "s": 1379, "text": null }, { "code": null, "e": 2166, "s": 2159, "text": "Output" }, { "code": null, "e": 2173, "s": 2166, "text": "Picked" }, { "code": null, "e": 2198, "s": 2173, "text": "Python Tkinter-exercises" }, { "code": null, "e": 2213, "s": 2198, "text": "Python-tkinter" }, { "code": null, "e": 2220, "s": 2213, "text": "Python" }, { "code": null, "e": 2318, "s": 2220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2350, "s": 2318, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2377, "s": 2350, "text": "Python Classes and Objects" }, { "code": null, "e": 2398, "s": 2377, "text": "Python OOPs Concepts" }, { "code": null, "e": 2421, "s": 2398, "text": "Introduction To PYTHON" }, { "code": null, "e": 2452, "s": 2421, "text": "Python | os.path.join() method" }, { "code": null, "e": 2508, "s": 2452, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2550, "s": 2508, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2592, "s": 2550, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2631, "s": 2592, "text": "Python | Get unique values from a list" } ]
Python OpenCV | cv2.copyMakeBorder() method
08 Aug, 2021 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.copyMakeBorder() method is used to create a border around the image like a photo frame. Syntax: cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value) Parameters: src: It is the source image. top: It is the border width in number of pixels in top direction. bottom: It is the border width in number of pixels in bottom direction. left: It is the border width in number of pixels in left direction. right: It is the border width in number of pixels in right direction. borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc dest: It is the destination imagevalue: It is an optional parameter which depicts color of border if border type is cv2.BORDER_CONSTANT. Return Value: It returns an image. The borderType flags are described below: cv2.BORDER_CONSTANT: It adds a constant colored border. The value should be given as a keyword argumentcv2.BORDER_REFLECT: The border will be mirror reflection of the border elements. Suppose, if image contains letters “abcdefg” then output will be “gfedcba|abcdefg|gfedcba“. cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT: It does the same works as cv2.BORDER_REFLECT but with slight change. Suppose, if image contains letters “abcdefgh” then output will be “gfedcb|abcdefgh|gfedcba“. cv2.BORDER_REPLICATE: It replicates the last element. Suppose, if image contains letters “abcdefgh” then output will be “aaaaa|abcdefgh|hhhhh“. Image used for all the below examples: Example #1: Python3 # Python program to explain cv2.copyMakeBorder() method # importing cv2import cv2 # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.copyMakeBorder() methodimage = cv2.copyMakeBorder(image, 10, 10, 10, 10, cv2.BORDER_CONSTANT, None, value = 0) # Displaying the imagecv2.imshow(window_name, image) Output: Example #2: Python3 # Python program to explain cv2.copyMakeBorder() method # importing cv2import cv2 # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.copyMakeBorder() methodimage = cv2.copyMakeBorder(image, 100, 100, 50, 50, cv2.BORDER_REFLECT) # Displaying the imagecv2.imshow(window_name, image) Output: smyafe7o9x6r1d65ted6ubs9hacynx7ltfue26rl Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Aug, 2021" }, { "code": null, "e": 212, "s": 28, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.copyMakeBorder() method is used to create a border around the image like a photo frame. " }, { "code": null, "e": 289, "s": 212, "text": "Syntax: cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value)" }, { "code": null, "e": 872, "s": 289, "text": "Parameters: src: It is the source image. top: It is the border width in number of pixels in top direction. bottom: It is the border width in number of pixels in bottom direction. left: It is the border width in number of pixels in left direction. right: It is the border width in number of pixels in right direction. borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc dest: It is the destination imagevalue: It is an optional parameter which depicts color of border if border type is cv2.BORDER_CONSTANT." }, { "code": null, "e": 909, "s": 872, "text": "Return Value: It returns an image. " }, { "code": null, "e": 953, "s": 909, "text": "The borderType flags are described below: " }, { "code": null, "e": 1583, "s": 953, "text": "cv2.BORDER_CONSTANT: It adds a constant colored border. The value should be given as a keyword argumentcv2.BORDER_REFLECT: The border will be mirror reflection of the border elements. Suppose, if image contains letters “abcdefg” then output will be “gfedcba|abcdefg|gfedcba“. cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT: It does the same works as cv2.BORDER_REFLECT but with slight change. Suppose, if image contains letters “abcdefgh” then output will be “gfedcb|abcdefgh|gfedcba“. cv2.BORDER_REPLICATE: It replicates the last element. Suppose, if image contains letters “abcdefgh” then output will be “aaaaa|abcdefgh|hhhhh“. " }, { "code": null, "e": 1624, "s": 1583, "text": "Image used for all the below examples: " }, { "code": null, "e": 1638, "s": 1624, "text": "Example #1: " }, { "code": null, "e": 1646, "s": 1638, "text": "Python3" }, { "code": "# Python program to explain cv2.copyMakeBorder() method # importing cv2import cv2 # pathpath = r'C:\\Users\\Rajnish\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.copyMakeBorder() methodimage = cv2.copyMakeBorder(image, 10, 10, 10, 10, cv2.BORDER_CONSTANT, None, value = 0) # Displaying the imagecv2.imshow(window_name, image)", "e": 2095, "s": 1646, "text": null }, { "code": null, "e": 2105, "s": 2095, "text": "Output: " }, { "code": null, "e": 2119, "s": 2105, "text": "Example #2: " }, { "code": null, "e": 2127, "s": 2119, "text": "Python3" }, { "code": "# Python program to explain cv2.copyMakeBorder() method # importing cv2import cv2 # pathpath = r'C:\\Users\\Rajnish\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.copyMakeBorder() methodimage = cv2.copyMakeBorder(image, 100, 100, 50, 50, cv2.BORDER_REFLECT) # Displaying the imagecv2.imshow(window_name, image)", "e": 2560, "s": 2127, "text": null }, { "code": null, "e": 2570, "s": 2560, "text": "Output: " }, { "code": null, "e": 2613, "s": 2572, "text": "smyafe7o9x6r1d65ted6ubs9hacynx7ltfue26rl" }, { "code": null, "e": 2630, "s": 2613, "text": "Image-Processing" }, { "code": null, "e": 2637, "s": 2630, "text": "OpenCV" }, { "code": null, "e": 2644, "s": 2637, "text": "Python" }, { "code": null, "e": 2742, "s": 2644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2784, "s": 2742, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2806, "s": 2784, "text": "Enumerate() in Python" }, { "code": null, "e": 2832, "s": 2806, "text": "Python String | replace()" }, { "code": null, "e": 2864, "s": 2832, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2893, "s": 2864, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2920, "s": 2893, "text": "Python Classes and Objects" }, { "code": null, "e": 2956, "s": 2920, "text": "Convert integer to string in Python" }, { "code": null, "e": 2977, "s": 2956, "text": "Python OOPs Concepts" }, { "code": null, "e": 3008, "s": 2977, "text": "Python | os.path.join() method" } ]
Gensim - Documents & LDA Model
This chapter discusses the documents and LDA model in Gensim. We can find the optimal number of topics for LDA by creating many LDA models with various values of topics. Among those LDAs we can pick one having highest coherence value. Following function named coherence_values_computation() will train multiple LDA models. It will also provide the models as well as their corresponding coherence score − def coherence_values_computation(dictionary, corpus, texts, limit, start=2, step=3): coherence_values = [] model_list = [] for num_topics in range(start, limit, step): model = gensim.models.wrappers.LdaMallet( mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word ) model_list.append(model) coherencemodel = CoherenceModel( model=model, texts=texts, dictionary=dictionary, coherence='c_v' ) coherence_values.append(coherencemodel.get_coherence()) return model_list, coherence_values Now with the help of following code, we can get the optimal number of topics which we can show with the help of a graph as well − model_list, coherence_values = coherence_values_computation ( dictionary=id2word, corpus=corpus, texts=data_lemmatized, start=1, limit=50, step=8 ) limit=50; start=1; step=8; x = range(start, limit, step) plt.plot(x, coherence_values) plt.xlabel("Num Topics") plt.ylabel("Coherence score") plt.legend(("coherence_values"), loc='best') plt.show() Next, we can also print the coherence values for various topics as follows − for m, cv in zip(x, coherence_values): print("Num Topics =", m, " is having Coherence Value of", round(cv, 4)) Num Topics = 1 is having Coherence Value of 0.4866 Num Topics = 9 is having Coherence Value of 0.5083 Num Topics = 17 is having Coherence Value of 0.5584 Num Topics = 25 is having Coherence Value of 0.5793 Num Topics = 33 is having Coherence Value of 0.587 Num Topics = 41 is having Coherence Value of 0.5842 Num Topics = 49 is having Coherence Value of 0.5735 Now, the question arises which model should we pick now? One of the good practices is to pick the model, that is giving highest coherence value before flattering out. So that’s why, we will be choosing the model with 25 topics which is at number 4 in the above list. optimal_model = model_list[3] model_topics = optimal_model.show_topics(formatted=False) pprint(optimal_model.print_topics(num_words=10)) [ (0, '0.018*"power" + 0.011*"high" + 0.010*"ground" + 0.009*"current" + ' '0.008*"low" + 0.008*"wire" + 0.007*"water" + 0.007*"work" + 0.007*"design" ' '+ 0.007*"light"'), (1, '0.036*"game" + 0.029*"team" + 0.029*"year" + 0.028*"play" + 0.020*"player" ' '+ 0.019*"win" + 0.018*"good" + 0.013*"season" + 0.012*"run" + 0.011*"hit"'), (2, '0.020*"image" + 0.019*"information" + 0.017*"include" + 0.017*"mail" + ' '0.016*"send" + 0.015*"list" + 0.013*"post" + 0.012*"address" + ' '0.012*"internet" + 0.012*"system"'), (3, '0.986*"ax" + 0.002*"_" + 0.001*"tm" + 0.000*"part" + 0.000*"biz" + ' '0.000*"mb" + 0.000*"mbs" + 0.000*"pne" + 0.000*"end" + 0.000*"di"'), (4, '0.020*"make" + 0.014*"work" + 0.013*"money" + 0.013*"year" + 0.012*"people" ' '+ 0.011*"job" + 0.010*"group" + 0.009*"government" + 0.008*"support" + ' '0.008*"question"'), (5, '0.011*"study" + 0.011*"drug" + 0.009*"science" + 0.008*"food" + ' '0.008*"problem" + 0.008*"result" + 0.008*"effect" + 0.007*"doctor" + ' '0.007*"research" + 0.007*"patient"'), (6, '0.024*"gun" + 0.024*"law" + 0.019*"state" + 0.015*"case" + 0.013*"people" + ' '0.010*"crime" + 0.010*"weapon" + 0.010*"person" + 0.008*"firearm" + ' '0.008*"police"'), (7, '0.012*"word" + 0.011*"question" + 0.011*"exist" + 0.011*"true" + ' '0.010*"religion" + 0.010*"claim" + 0.008*"argument" + 0.008*"truth" + ' '0.008*"life" + 0.008*"faith"'), (8, '0.077*"time" + 0.029*"day" + 0.029*"call" + 0.025*"back" + 0.021*"work" + ' '0.019*"long" + 0.015*"end" + 0.015*"give" + 0.014*"year" + 0.014*"week"'), (9, '0.048*"thing" + 0.041*"make" + 0.038*"good" + 0.037*"people" + ' '0.028*"write" + 0.019*"bad" + 0.019*"point" + 0.018*"read" + 0.018*"post" + ' '0.016*"idea"'), (10, '0.022*"book" + 0.020*"_" + 0.013*"man" + 0.012*"people" + 0.011*"write" + ' '0.011*"find" + 0.010*"history" + 0.010*"armenian" + 0.009*"turkish" + ' '0.009*"number"'), (11, '0.064*"line" + 0.030*"buy" + 0.028*"organization" + 0.025*"price" + ' '0.025*"sell" + 0.023*"good" + 0.021*"host" + 0.018*"sale" + 0.017*"mail" + ' '0.016*"cost"'), (12, '0.041*"car" + 0.015*"bike" + 0.011*"ride" + 0.010*"engine" + 0.009*"drive" ' '+ 0.008*"side" + 0.008*"article" + 0.007*"turn" + 0.007*"front" + ' '0.007*"speed"'), (13, '0.018*"people" + 0.011*"attack" + 0.011*"state" + 0.011*"israeli" + ' '0.010*"war" + 0.010*"country" + 0.010*"government" + 0.009*"live" + ' '0.009*"give" + 0.009*"land"'), (14, '0.037*"file" + 0.026*"line" + 0.021*"read" + 0.019*"follow" + ' '0.018*"number" + 0.015*"program" + 0.014*"write" + 0.012*"entry" + ' '0.012*"give" + 0.011*"check"'), (15, '0.196*"write" + 0.172*"line" + 0.165*"article" + 0.117*"organization" + ' '0.086*"host" + 0.030*"reply" + 0.010*"university" + 0.008*"hear" + ' '0.007*"post" + 0.007*"news"'), (16, '0.021*"people" + 0.014*"happen" + 0.014*"child" + 0.012*"kill" + ' '0.011*"start" + 0.011*"live" + 0.010*"fire" + 0.010*"leave" + 0.009*"hear" ' '+ 0.009*"home"'), (17, '0.038*"key" + 0.018*"system" + 0.015*"space" + 0.015*"technology" + ' '0.014*"encryption" + 0.010*"chip" + 0.010*"bit" + 0.009*"launch" + ' '0.009*"public" + 0.009*"government"'), (18, '0.035*"drive" + 0.031*"system" + 0.027*"problem" + 0.027*"card" + ' '0.020*"driver" + 0.017*"bit" + 0.017*"work" + 0.016*"disk" + ' '0.014*"monitor" + 0.014*"machine"'), (19, '0.031*"window" + 0.020*"run" + 0.018*"color" + 0.018*"program" + ' '0.017*"application" + 0.016*"display" + 0.015*"set" + 0.015*"version" + ' '0.012*"screen" + 0.012*"problem"') ] Finding dominant topics in sentences is one of the most useful practical applications of topic modeling. It determines what topic a given document is about. Here, we will find that topic number which has the highest percentage contribution in that particular document. In order to aggregate the information in a table, we will be creating a function named dominant_topics() − def dominant_topics(ldamodel=lda_model, corpus=corpus, texts=data): sent_topics_df = pd.DataFrame() Next, we will get the main topics in every document − for i, row in enumerate(ldamodel[corpus]): row = sorted(row, key=lambda x: (x[1]), reverse=True) Next, we will get the Dominant topic, Perc Contribution and Keywords for every document − for j, (topic_num, prop_topic) in enumerate(row): if j == 0: # => dominant topic wp = ldamodel.show_topic(topic_num) topic_keywords = ", ".join([word for word, prop in wp]) sent_topics_df = sent_topics_df.append( pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True ) else: break sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords'] With the help of following code, we will add the original text to the end of the output − contents = pd.Series(texts) sent_topics_df = pd.concat([sent_topics_df, contents], axis=1) return(sent_topics_df) df_topic_sents_keywords = dominant_topics( ldamodel=optimal_model, corpus=corpus, texts=data ) Now, do the formatting of topics in the sentences as follows − df_dominant_topic = df_topic_sents_keywords.reset_index() df_dominant_topic.columns = [ 'Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text' ] Finally, we can show the dominant topics as follows − df_dominant_topic.head(15) In order to understand more about the topic, we can also find the documents, a given topic has contributed to the most. We can infer that topic by reading that particular document(s). sent_topics_sorteddf_mallet = pd.DataFrame() sent_topics_outdf_grpd = df_topic_sents_keywords.groupby('Dominant_Topic') for i, grp in sent_topics_outdf_grpd: sent_topics_sorteddf_mallet = pd.concat([sent_topics_sorteddf_mallet, grp.sort_values(['Perc_Contribution'], ascending=[0]).head(1)], axis=0) sent_topics_sorteddf_mallet.reset_index(drop=True, inplace=True) sent_topics_sorteddf_mallet.columns = [ 'Topic_Number', "Contribution_Perc", "Keywords", "Text" ] sent_topics_sorteddf_mallet.head() Sometimes we also want to judge how widely the topic is discussed in documents. For this we need to understand the volume and distribution of topics across the documents. First calculate the number of documents for every Topic as follows − topic_counts = df_topic_sents_keywords['Dominant_Topic'].value_counts() Next, calculate the percentage of Documents for every Topic as follows −; topic_contribution = round(topic_counts/topic_counts.sum(), 4) Now find the topic Number and Keywords as follows − topic_num_keywords = df_topic_sents_keywords[['Dominant_Topic', 'Topic_Keywords']] Now, concatenate then Column wise as follows − df_dominant_topics = pd.concat( [topic_num_keywords, topic_counts, topic_contribution], axis=1 ) Next, we will change the Column names as follows − df_dominant_topics.columns = [ 'Dominant-Topic', 'Topic-Keywords', 'Num_Documents', 'Perc_Documents' ] df_dominant_topics Print Add Notes Bookmark this page
[ { "code": null, "e": 2114, "s": 2052, "text": "This chapter discusses the documents and LDA model in Gensim." }, { "code": null, "e": 2287, "s": 2114, "text": "We can find the optimal number of topics for LDA by creating many LDA models with various values of topics. Among those LDAs we can pick one having highest coherence value." }, { "code": null, "e": 2456, "s": 2287, "text": "Following function named coherence_values_computation() will train multiple LDA models. It will also provide the models as well as their corresponding coherence score −" }, { "code": null, "e": 3003, "s": 2456, "text": "def coherence_values_computation(dictionary, corpus, texts, limit, start=2, step=3):\n coherence_values = []\n model_list = []\n for num_topics in range(start, limit, step):\n model = gensim.models.wrappers.LdaMallet(\n mallet_path, corpus=corpus, num_topics=num_topics, id2word=id2word\n )\n model_list.append(model)\n coherencemodel = CoherenceModel(\n model=model, texts=texts, dictionary=dictionary, coherence='c_v'\n )\n coherence_values.append(coherencemodel.get_coherence())\nreturn model_list, coherence_values" }, { "code": null, "e": 3133, "s": 3003, "text": "Now with the help of following code, we can get the optimal number of topics which we can show with the help of a graph as well −" }, { "code": null, "e": 3486, "s": 3133, "text": "model_list, coherence_values = coherence_values_computation (\n dictionary=id2word, corpus=corpus, texts=data_lemmatized, \n start=1, limit=50, step=8\n)\nlimit=50; start=1; step=8;\nx = range(start, limit, step)\nplt.plot(x, coherence_values)\nplt.xlabel(\"Num Topics\")\nplt.ylabel(\"Coherence score\")\nplt.legend((\"coherence_values\"), loc='best')\nplt.show()" }, { "code": null, "e": 3563, "s": 3486, "text": "Next, we can also print the coherence values for various topics as follows −" }, { "code": null, "e": 3677, "s": 3563, "text": "for m, cv in zip(x, coherence_values):\n print(\"Num Topics =\", m, \" is having Coherence Value of\", round(cv, 4))" }, { "code": null, "e": 4039, "s": 3677, "text": "Num Topics = 1 is having Coherence Value of 0.4866\nNum Topics = 9 is having Coherence Value of 0.5083\nNum Topics = 17 is having Coherence Value of 0.5584\nNum Topics = 25 is having Coherence Value of 0.5793\nNum Topics = 33 is having Coherence Value of 0.587\nNum Topics = 41 is having Coherence Value of 0.5842\nNum Topics = 49 is having Coherence Value of 0.5735\n" }, { "code": null, "e": 4306, "s": 4039, "text": "Now, the question arises which model should we pick now? One of the good practices is to pick the model, that is giving highest coherence value before flattering out. So that’s why, we will be choosing the model with 25 topics which is at number 4 in the above list." }, { "code": null, "e": 8135, "s": 4306, "text": "optimal_model = model_list[3]\nmodel_topics = optimal_model.show_topics(formatted=False)\npprint(optimal_model.print_topics(num_words=10))\n\n[\n (0,\n '0.018*\"power\" + 0.011*\"high\" + 0.010*\"ground\" + 0.009*\"current\" + '\n '0.008*\"low\" + 0.008*\"wire\" + 0.007*\"water\" + 0.007*\"work\" + 0.007*\"design\" '\n '+ 0.007*\"light\"'),\n (1,\n '0.036*\"game\" + 0.029*\"team\" + 0.029*\"year\" + 0.028*\"play\" + 0.020*\"player\" '\n '+ 0.019*\"win\" + 0.018*\"good\" + 0.013*\"season\" + 0.012*\"run\" + 0.011*\"hit\"'),\n (2,\n '0.020*\"image\" + 0.019*\"information\" + 0.017*\"include\" + 0.017*\"mail\" + '\n '0.016*\"send\" + 0.015*\"list\" + 0.013*\"post\" + 0.012*\"address\" + '\n '0.012*\"internet\" + 0.012*\"system\"'),\n (3,\n '0.986*\"ax\" + 0.002*\"_\" + 0.001*\"tm\" + 0.000*\"part\" + 0.000*\"biz\" + '\n '0.000*\"mb\" + 0.000*\"mbs\" + 0.000*\"pne\" + 0.000*\"end\" + 0.000*\"di\"'),\n (4,\n '0.020*\"make\" + 0.014*\"work\" + 0.013*\"money\" + 0.013*\"year\" + 0.012*\"people\" '\n '+ 0.011*\"job\" + 0.010*\"group\" + 0.009*\"government\" + 0.008*\"support\" + '\n '0.008*\"question\"'),\n (5,\n '0.011*\"study\" + 0.011*\"drug\" + 0.009*\"science\" + 0.008*\"food\" + '\n '0.008*\"problem\" + 0.008*\"result\" + 0.008*\"effect\" + 0.007*\"doctor\" + '\n '0.007*\"research\" + 0.007*\"patient\"'),\n (6,\n '0.024*\"gun\" + 0.024*\"law\" + 0.019*\"state\" + 0.015*\"case\" + 0.013*\"people\" + '\n '0.010*\"crime\" + 0.010*\"weapon\" + 0.010*\"person\" + 0.008*\"firearm\" + '\n '0.008*\"police\"'),\n (7,\n '0.012*\"word\" + 0.011*\"question\" + 0.011*\"exist\" + 0.011*\"true\" + '\n '0.010*\"religion\" + 0.010*\"claim\" + 0.008*\"argument\" + 0.008*\"truth\" + '\n '0.008*\"life\" + 0.008*\"faith\"'),\n (8,\n '0.077*\"time\" + 0.029*\"day\" + 0.029*\"call\" + 0.025*\"back\" + 0.021*\"work\" + '\n '0.019*\"long\" + 0.015*\"end\" + 0.015*\"give\" + 0.014*\"year\" + 0.014*\"week\"'),\n (9,\n '0.048*\"thing\" + 0.041*\"make\" + 0.038*\"good\" + 0.037*\"people\" + '\n '0.028*\"write\" + 0.019*\"bad\" + 0.019*\"point\" + 0.018*\"read\" + 0.018*\"post\" + '\n '0.016*\"idea\"'),\n (10,\n '0.022*\"book\" + 0.020*\"_\" + 0.013*\"man\" + 0.012*\"people\" + 0.011*\"write\" + '\n '0.011*\"find\" + 0.010*\"history\" + 0.010*\"armenian\" + 0.009*\"turkish\" + '\n '0.009*\"number\"'),\n (11,\n '0.064*\"line\" + 0.030*\"buy\" + 0.028*\"organization\" + 0.025*\"price\" + '\n '0.025*\"sell\" + 0.023*\"good\" + 0.021*\"host\" + 0.018*\"sale\" + 0.017*\"mail\" + '\n '0.016*\"cost\"'),\n (12,\n '0.041*\"car\" + 0.015*\"bike\" + 0.011*\"ride\" + 0.010*\"engine\" + 0.009*\"drive\" '\n '+ 0.008*\"side\" + 0.008*\"article\" + 0.007*\"turn\" + 0.007*\"front\" + '\n '0.007*\"speed\"'),\n (13,\n '0.018*\"people\" + 0.011*\"attack\" + 0.011*\"state\" + 0.011*\"israeli\" + '\n '0.010*\"war\" + 0.010*\"country\" + 0.010*\"government\" + 0.009*\"live\" + '\n '0.009*\"give\" + 0.009*\"land\"'),\n (14,\n '0.037*\"file\" + 0.026*\"line\" + 0.021*\"read\" + 0.019*\"follow\" + '\n '0.018*\"number\" + 0.015*\"program\" + 0.014*\"write\" + 0.012*\"entry\" + '\n '0.012*\"give\" + 0.011*\"check\"'),\n (15,\n '0.196*\"write\" + 0.172*\"line\" + 0.165*\"article\" + 0.117*\"organization\" + '\n '0.086*\"host\" + 0.030*\"reply\" + 0.010*\"university\" + 0.008*\"hear\" + '\n '0.007*\"post\" + 0.007*\"news\"'),\n (16,\n '0.021*\"people\" + 0.014*\"happen\" + 0.014*\"child\" + 0.012*\"kill\" + '\n '0.011*\"start\" + 0.011*\"live\" + 0.010*\"fire\" + 0.010*\"leave\" + 0.009*\"hear\" '\n '+ 0.009*\"home\"'),\n (17,\n '0.038*\"key\" + 0.018*\"system\" + 0.015*\"space\" + 0.015*\"technology\" + '\n '0.014*\"encryption\" + 0.010*\"chip\" + 0.010*\"bit\" + 0.009*\"launch\" + '\n '0.009*\"public\" + 0.009*\"government\"'),\n (18,\n '0.035*\"drive\" + 0.031*\"system\" + 0.027*\"problem\" + 0.027*\"card\" + '\n '0.020*\"driver\" + 0.017*\"bit\" + 0.017*\"work\" + 0.016*\"disk\" + '\n '0.014*\"monitor\" + 0.014*\"machine\"'),\n (19,\n '0.031*\"window\" + 0.020*\"run\" + 0.018*\"color\" + 0.018*\"program\" + '\n '0.017*\"application\" + 0.016*\"display\" + 0.015*\"set\" + 0.015*\"version\" + '\n '0.012*\"screen\" + 0.012*\"problem\"')\n]" }, { "code": null, "e": 8511, "s": 8135, "text": "Finding dominant topics in sentences is one of the most useful practical applications of topic modeling. It determines what topic a given document is about. Here, we will find that topic number which has the highest percentage contribution in that particular document. In order to aggregate the information in a table, we will be creating a function named dominant_topics() −" }, { "code": null, "e": 8615, "s": 8511, "text": "def dominant_topics(ldamodel=lda_model, corpus=corpus, texts=data):\n sent_topics_df = pd.DataFrame()\n" }, { "code": null, "e": 8669, "s": 8615, "text": "Next, we will get the main topics in every document −" }, { "code": null, "e": 8770, "s": 8669, "text": "for i, row in enumerate(ldamodel[corpus]):\n row = sorted(row, key=lambda x: (x[1]), reverse=True)\n" }, { "code": null, "e": 8860, "s": 8770, "text": "Next, we will get the Dominant topic, Perc Contribution and Keywords for every document −" }, { "code": null, "e": 9281, "s": 8860, "text": "for j, (topic_num, prop_topic) in enumerate(row):\n if j == 0: # => dominant topic\n wp = ldamodel.show_topic(topic_num)\n topic_keywords = \", \".join([word for word, prop in wp])\nsent_topics_df = sent_topics_df.append(\n pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True\n)\n else:\n break\nsent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']" }, { "code": null, "e": 9371, "s": 9281, "text": "With the help of following code, we will add the original text to the end of the output −" }, { "code": null, "e": 9589, "s": 9371, "text": "contents = pd.Series(texts)\n sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)\n return(sent_topics_df)\ndf_topic_sents_keywords = dominant_topics(\n ldamodel=optimal_model, corpus=corpus, texts=data\n)" }, { "code": null, "e": 9652, "s": 9589, "text": "Now, do the formatting of topics in the sentences as follows −" }, { "code": null, "e": 9820, "s": 9652, "text": "df_dominant_topic = df_topic_sents_keywords.reset_index()\ndf_dominant_topic.columns = [\n 'Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text'\n]\n" }, { "code": null, "e": 9874, "s": 9820, "text": "Finally, we can show the dominant topics as follows −" }, { "code": null, "e": 9902, "s": 9874, "text": "df_dominant_topic.head(15)\n" }, { "code": null, "e": 10086, "s": 9902, "text": "In order to understand more about the topic, we can also find the documents, a given topic has contributed to the most. We can infer that topic by reading that particular document(s)." }, { "code": null, "e": 10590, "s": 10086, "text": "sent_topics_sorteddf_mallet = pd.DataFrame()\nsent_topics_outdf_grpd = df_topic_sents_keywords.groupby('Dominant_Topic')\nfor i, grp in sent_topics_outdf_grpd:\n sent_topics_sorteddf_mallet = pd.concat([sent_topics_sorteddf_mallet,\ngrp.sort_values(['Perc_Contribution'], ascending=[0]).head(1)], axis=0)\nsent_topics_sorteddf_mallet.reset_index(drop=True, inplace=True)\nsent_topics_sorteddf_mallet.columns = [\n 'Topic_Number', \"Contribution_Perc\", \"Keywords\", \"Text\"\n]\nsent_topics_sorteddf_mallet.head()" }, { "code": null, "e": 10761, "s": 10590, "text": "Sometimes we also want to judge how widely the topic is discussed in documents. For this we need to understand the volume and distribution of topics across the documents." }, { "code": null, "e": 10830, "s": 10761, "text": "First calculate the number of documents for every Topic as follows −" }, { "code": null, "e": 10903, "s": 10830, "text": "topic_counts = df_topic_sents_keywords['Dominant_Topic'].value_counts()\n" }, { "code": null, "e": 10977, "s": 10903, "text": "Next, calculate the percentage of Documents for every Topic as follows −;" }, { "code": null, "e": 11041, "s": 10977, "text": "topic_contribution = round(topic_counts/topic_counts.sum(), 4)\n" }, { "code": null, "e": 11093, "s": 11041, "text": "Now find the topic Number and Keywords as follows −" }, { "code": null, "e": 11177, "s": 11093, "text": "topic_num_keywords = df_topic_sents_keywords[['Dominant_Topic', 'Topic_Keywords']]\n" }, { "code": null, "e": 11224, "s": 11177, "text": "Now, concatenate then Column wise as follows −" }, { "code": null, "e": 11325, "s": 11224, "text": "df_dominant_topics = pd.concat(\n [topic_num_keywords, topic_counts, topic_contribution], axis=1\n)\n" }, { "code": null, "e": 11376, "s": 11325, "text": "Next, we will change the Column names as follows −" }, { "code": null, "e": 11501, "s": 11376, "text": "df_dominant_topics.columns = [\n 'Dominant-Topic', 'Topic-Keywords', 'Num_Documents', 'Perc_Documents'\n]\ndf_dominant_topics" }, { "code": null, "e": 11508, "s": 11501, "text": " Print" }, { "code": null, "e": 11519, "s": 11508, "text": " Add Notes" } ]
MVC Framework - Ajax Support
As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your application, you can ignore this step. <add key = "UnobtrusiveJavaScriptEnabled" value = "true" /> After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery libraries here using the following code − <script src = "~/Scripts/jquery-ui-1.8.24.min.js" type = "text/javascript"> </script> <script src = "~/Scripts/jquery.unobtrusive-ajax.min.js" type = "text/javascript"> </script> In the example that follows, we will create a form which will display the list of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the list of users belonging to this category using unobtrusive AJAX setup. Step 1 − Create a Model file Model.cs and copy the following code. using System; namespace MVCAjaxSupportExample.Models { public class User { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public Role Role { get; set; } } public enum Role { Admin, Normal, Guest } } Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MVCAjaxSupportExample.Models; namespace MVCAjaxSupportExample.Controllers { public class UserController : Controller { private readonly User[] userData = { new User {FirstName = "Edy", LastName = "Clooney", Role = Role.Admin}, new User {FirstName = "David", LastName = "Sanderson", Role = Role.Admin}, new User {FirstName = "Pandy", LastName = "Griffyth", Role = Role.Normal}, new User {FirstName = "Joe", LastName = "Gubbins", Role = Role.Normal}, new User {FirstName = "Mike", LastName = "Smith", Role = Role.Guest} }; public ActionResult Index() { return View(userData); } public PartialViewResult GetUserData(string selectedRole = "All") { IEnumerable data = userData; if (selectedRole != "All") { var selected = (Role) Enum.Parse(typeof (Role), selectedRole); data = userData.Where(p => p.Role == selected); } return PartialView(data); } public ActionResult GetUser(string selectedRole = "All") { return View((object) selectedRole); } } } Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render list of users based on the selected role from the dropdown. @model IEnumerable<MVCAjaxSupportExample.Models.User> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th> @Html.DisplayNameFor(model => model.BirthDate) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.BirthDate) </td> <td> </td> </tr> } </table> Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller's GetUserData Action. @using MVCAjaxSupportExample.Models @model string @{ ViewBag.Title = "GetUser"; AjaxOptions ajaxOpts = new AjaxOptions { UpdateTargetId = "tableBody" }; } <h2>Get User</h2> <table> <thead> <tr> <th>First</th> <th>Last</th> <th>Role</th> </tr> </thead> <tbody id="tableBody"> @Html.Action("GetUserData", new {selectedRole = Model }) </tbody> </table> @using (Ajax.BeginForm("GetUser", ajaxOpts)) { <div> @Html.DropDownList("selectedRole", new SelectList( new [] {"All"}.Concat(Enum.GetNames(typeof(Role))))) <button type="submit">Submit</button> </div> } Step 5 − Finally, change the Route.config entries to launch the User Controller. defaults: new { controller = "User", action = "GetUser", id = UrlParameter.Optional } Step 6 − Run the application which will look like the following screenshot. If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page. 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 55 Lectures 4.5 hours University Code 40 Lectures 2.5 hours University Code 140 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2334, "s": 2025, "text": "As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features." }, { "code": null, "e": 2606, "s": 2334, "text": "To enable the unobtrusive AJAX support in the MVC application, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your application, you can ignore this step." }, { "code": null, "e": 2667, "s": 2606, "text": "<add key = \"UnobtrusiveJavaScriptEnabled\" value = \"true\" />\n" }, { "code": null, "e": 2841, "s": 2667, "text": "After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery libraries here using the following code −" }, { "code": null, "e": 3022, "s": 2841, "text": "<script src = \"~/Scripts/jquery-ui-1.8.24.min.js\" type = \"text/javascript\">\n</script> \n\n<script src = \"~/Scripts/jquery.unobtrusive-ajax.min.js\" type = \"text/javascript\">\n</script>" }, { "code": null, "e": 3331, "s": 3022, "text": "In the example that follows, we will create a form which will display the list of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the list of users belonging to this category using unobtrusive AJAX setup." }, { "code": null, "e": 3398, "s": 3331, "text": "Step 1 − Create a Model file Model.cs and copy the following code." }, { "code": null, "e": 3784, "s": 3398, "text": "using System; \n\nnamespace MVCAjaxSupportExample.Models { \n \n public class User { \n public int UserId { get; set; } \n public string FirstName { get; set; } \n public string LastName { get; set; } \n public DateTime BirthDate { get; set; } \n public Role Role { get; set; } \n } \n \n public enum Role { \n Admin, \n Normal, \n Guest \n } \n} " }, { "code": null, "e": 3910, "s": 3784, "text": "Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code." }, { "code": null, "e": 5216, "s": 3910, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Web.Mvc; \nusing MVCAjaxSupportExample.Models; \n\nnamespace MVCAjaxSupportExample.Controllers {\n \n public class UserController : Controller { \n \n private readonly User[] userData = \n { \n new User {FirstName = \"Edy\", LastName = \"Clooney\", Role = Role.Admin}, \n new User {FirstName = \"David\", LastName = \"Sanderson\", Role = Role.Admin}, \n new User {FirstName = \"Pandy\", LastName = \"Griffyth\", Role = Role.Normal}, \n new User {FirstName = \"Joe\", LastName = \"Gubbins\", Role = Role.Normal}, \n new User {FirstName = \"Mike\", LastName = \"Smith\", Role = Role.Guest} \n }; \n \n public ActionResult Index() { \n return View(userData); \n } \n \n public PartialViewResult GetUserData(string selectedRole = \"All\") { \n IEnumerable data = userData; \n \n if (selectedRole != \"All\") { \n var selected = (Role) Enum.Parse(typeof (Role), selectedRole); \n data = userData.Where(p => p.Role == selected); \n } \n \n return PartialView(data); \n } \n \n public ActionResult GetUser(string selectedRole = \"All\") { \n return View((object) selectedRole); \n } \n } \n}" }, { "code": null, "e": 5387, "s": 5216, "text": "Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render list of users based on the selected role from the dropdown." }, { "code": null, "e": 6114, "s": 5387, "text": "@model IEnumerable<MVCAjaxSupportExample.Models.User> \n\n<table> \n <tr> \n <th> \n @Html.DisplayNameFor(model => model.FirstName) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.LastName) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.BirthDate) \n </th> \n <th></th> \n </tr> \n\n @foreach (var item in Model) { \n <tr> \n <td> \n @Html.DisplayFor(modelItem => item.FirstName) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.LastName) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.BirthDate) \n </td> \n \n <td> \n \n </td> \n </tr> \n} \n</table>" }, { "code": null, "e": 6278, "s": 6114, "text": "Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller's GetUserData Action." }, { "code": null, "e": 6943, "s": 6278, "text": "@using MVCAjaxSupportExample.Models \n@model string \n\n@{ \nViewBag.Title = \"GetUser\"; \n\nAjaxOptions ajaxOpts = new AjaxOptions { \nUpdateTargetId = \"tableBody\" \n}; \n} \n\n<h2>Get User</h2> \n<table> \n <thead>\n <tr>\n <th>First</th>\n <th>Last</th>\n <th>Role</th>\n </tr>\n </thead> \n \n <tbody id=\"tableBody\"> \n @Html.Action(\"GetUserData\", new {selectedRole = Model }) \n </tbody> \n</table> \n\n@using (Ajax.BeginForm(\"GetUser\", ajaxOpts)) { \n <div> \n @Html.DropDownList(\"selectedRole\", new SelectList( \n new [] {\"All\"}.Concat(Enum.GetNames(typeof(Role))))) \n <button type=\"submit\">Submit</button> \n </div> \n}" }, { "code": null, "e": 7024, "s": 6943, "text": "Step 5 − Finally, change the Route.config entries to launch the User Controller." }, { "code": null, "e": 7111, "s": 7024, "text": "defaults: new { controller = \"User\", action = \"GetUser\", id = UrlParameter.Optional }\n" }, { "code": null, "e": 7187, "s": 7111, "text": "Step 6 − Run the application which will look like the following screenshot." }, { "code": null, "e": 7342, "s": 7187, "text": "If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page." }, { "code": null, "e": 7377, "s": 7342, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7400, "s": 7377, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7434, "s": 7400, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 7454, "s": 7434, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7489, "s": 7454, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7506, "s": 7489, "text": " University Code" }, { "code": null, "e": 7541, "s": 7506, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7558, "s": 7541, "text": " University Code" }, { "code": null, "e": 7593, "s": 7558, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7610, "s": 7593, "text": " University Code" }, { "code": null, "e": 7644, "s": 7610, "text": "\n 140 Lectures \n 9 hours \n" }, { "code": null, "e": 7659, "s": 7644, "text": " Bhrugen Patel" }, { "code": null, "e": 7666, "s": 7659, "text": " Print" }, { "code": null, "e": 7677, "s": 7666, "text": " Add Notes" } ]
How to change navigation bar color in Bootstrap ? - GeeksforGeeks
03 Aug, 2021 The navigation bar color can be changed in Bootstrap using 2 methods:Method 1: Using the inbuilt color classesChanging the text colorThe text color of the navigation bar can be changed using two inbuilt classes: navbar-light: This class will set the color of the text to dark. This is used when using a light background color. navbar-dark: This class will set the color of the text to light. This is used when using a dark background color. Changing the background color:Bootstrap 4 has a few inbuilt classes for the colors of any background. These can be used to set the color of the background of the navigation bar. The various background classes available are: .bg-primary: This sets the color to the primary color. .bg-secondary: This sets the color to the secondary color. .bg-success: This sets the color to the success color. .bg-danger: This sets the color to the danger color. .bg-warning: This sets the color to the warning color. .bg-info: This sets the color to the info color. .bg-light: This sets the color to the light color. .bg-dark: This sets the color to the dark color. .bg-white: This sets the color to the white color. .bg-transparent: This sets the navbar to be transparent. Example: html <!DOCTYPE html><html> <head> <title> How to change navigation bar color in Bootstrap ? </title> <!-- Include Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></head> <body> <!-- Navbar text is dark and background is light --> <nav class="navbar navbar-light bg-light"> <a class="navbar-brand" href="#"> Light color background </a> </nav> <nav class="navbar navbar-light bg-warning"> <a class="navbar-brand" href="#"> Warning color background </a> </nav> <!-- Navbar text is light and background is dark --> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href="#"> Dark color background </a> </nav> <nav class="navbar navbar-dark bg-primary"> <a class="navbar-brand" href="#"> Primary color background </a> </nav> <nav class="navbar navbar-dark bg-secondary"> <a class="navbar-brand" href="#"> Secondary color background </a> </nav> <nav class="navbar navbar-dark bg-success"> <a class="navbar-brand" href="#"> Success color background </a> </nav> <div class="container"> <h1 style="color: green">GeeksforGeeks</h1> <b> How to change navigation bar color in Bootstrap ? </b> <p>The above navigation bars use some of the default color classes available in Bootstrap4.</p> </div></body> </html> Output: Method 2: Creating a custom class for the navigation barA custom class can be created to specify the background color and the text color of the navbar. This class is styled using CSS according to the required values. The names of the classes are kept in a manner to override the inbuilt navigation bar classes.The background color is set by directly specifying the background-color property with the color needed. html /* Modify the background color */.navbar-custom { background-color: lightgreen;} The navbar text and the brand text color can be set using the .navbar-text and .navbar-brand classes. These are the inbuilt navigation bar classes that are be overridden by using the same class name. The text color is specified using the color property. html /* Modify brand and text color */.navbar-custom .navbar-brand,.navbar-custom .navbar-text { color: green;} Example: html <!DOCTYPE html><html> <head> <title> How to change navigation bar color in Bootstrap ? </title> <!-- Include Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> /* Modify the background color */ .navbar-custom { background-color: lightgreen; } /* Modify brand and text color */ .navbar-custom .navbar-brand, .navbar-custom .navbar-text { color: green; } </style></head> <body> <!-- Navbar text is dark and background is light --> <nav class="navbar navbar-custom"> <a class="navbar-brand" href="#"> Custom color background navbar </a> </nav> <div class="container"> <h1 style="color: green">GeeksforGeeks</h1> <b>How to change navigation bar color in Bootstrap ?</b> <p>The above navigation bar uses a custom class for changing the colors.</p> </div></body> </html> Output: sumitgumber28 Bootstrap-4 Bootstrap-Misc Picked Bootstrap Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? 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": 24601, "s": 24573, "text": "\n03 Aug, 2021" }, { "code": null, "e": 24815, "s": 24601, "text": "The navigation bar color can be changed in Bootstrap using 2 methods:Method 1: Using the inbuilt color classesChanging the text colorThe text color of the navigation bar can be changed using two inbuilt classes: " }, { "code": null, "e": 24930, "s": 24815, "text": "navbar-light: This class will set the color of the text to dark. This is used when using a light background color." }, { "code": null, "e": 25044, "s": 24930, "text": "navbar-dark: This class will set the color of the text to light. This is used when using a dark background color." }, { "code": null, "e": 25269, "s": 25044, "text": "Changing the background color:Bootstrap 4 has a few inbuilt classes for the colors of any background. These can be used to set the color of the background of the navigation bar. The various background classes available are: " }, { "code": null, "e": 25324, "s": 25269, "text": ".bg-primary: This sets the color to the primary color." }, { "code": null, "e": 25383, "s": 25324, "text": ".bg-secondary: This sets the color to the secondary color." }, { "code": null, "e": 25438, "s": 25383, "text": ".bg-success: This sets the color to the success color." }, { "code": null, "e": 25491, "s": 25438, "text": ".bg-danger: This sets the color to the danger color." }, { "code": null, "e": 25546, "s": 25491, "text": ".bg-warning: This sets the color to the warning color." }, { "code": null, "e": 25595, "s": 25546, "text": ".bg-info: This sets the color to the info color." }, { "code": null, "e": 25646, "s": 25595, "text": ".bg-light: This sets the color to the light color." }, { "code": null, "e": 25695, "s": 25646, "text": ".bg-dark: This sets the color to the dark color." }, { "code": null, "e": 25746, "s": 25695, "text": ".bg-white: This sets the color to the white color." }, { "code": null, "e": 25803, "s": 25746, "text": ".bg-transparent: This sets the navbar to be transparent." }, { "code": null, "e": 25814, "s": 25803, "text": "Example: " }, { "code": null, "e": 25819, "s": 25814, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to change navigation bar color in Bootstrap ? </title> <!-- Include Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"></head> <body> <!-- Navbar text is dark and background is light --> <nav class=\"navbar navbar-light bg-light\"> <a class=\"navbar-brand\" href=\"#\"> Light color background </a> </nav> <nav class=\"navbar navbar-light bg-warning\"> <a class=\"navbar-brand\" href=\"#\"> Warning color background </a> </nav> <!-- Navbar text is light and background is dark --> <nav class=\"navbar navbar-dark bg-dark\"> <a class=\"navbar-brand\" href=\"#\"> Dark color background </a> </nav> <nav class=\"navbar navbar-dark bg-primary\"> <a class=\"navbar-brand\" href=\"#\"> Primary color background </a> </nav> <nav class=\"navbar navbar-dark bg-secondary\"> <a class=\"navbar-brand\" href=\"#\"> Secondary color background </a> </nav> <nav class=\"navbar navbar-dark bg-success\"> <a class=\"navbar-brand\" href=\"#\"> Success color background </a> </nav> <div class=\"container\"> <h1 style=\"color: green\">GeeksforGeeks</h1> <b> How to change navigation bar color in Bootstrap ? </b> <p>The above navigation bars use some of the default color classes available in Bootstrap4.</p> </div></body> </html>", "e": 27343, "s": 25819, "text": null }, { "code": null, "e": 27353, "s": 27343, "text": "Output: " }, { "code": null, "e": 27769, "s": 27353, "text": "Method 2: Creating a custom class for the navigation barA custom class can be created to specify the background color and the text color of the navbar. This class is styled using CSS according to the required values. The names of the classes are kept in a manner to override the inbuilt navigation bar classes.The background color is set by directly specifying the background-color property with the color needed. " }, { "code": null, "e": 27774, "s": 27769, "text": "html" }, { "code": "/* Modify the background color */.navbar-custom { background-color: lightgreen;}", "e": 27858, "s": 27774, "text": null }, { "code": null, "e": 28113, "s": 27858, "text": "The navbar text and the brand text color can be set using the .navbar-text and .navbar-brand classes. These are the inbuilt navigation bar classes that are be overridden by using the same class name. The text color is specified using the color property. " }, { "code": null, "e": 28118, "s": 28113, "text": "html" }, { "code": "/* Modify brand and text color */.navbar-custom .navbar-brand,.navbar-custom .navbar-text { color: green;}", "e": 28228, "s": 28118, "text": null }, { "code": null, "e": 28239, "s": 28228, "text": "Example: " }, { "code": null, "e": 28244, "s": 28239, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to change navigation bar color in Bootstrap ? </title> <!-- Include Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <style> /* Modify the background color */ .navbar-custom { background-color: lightgreen; } /* Modify brand and text color */ .navbar-custom .navbar-brand, .navbar-custom .navbar-text { color: green; } </style></head> <body> <!-- Navbar text is dark and background is light --> <nav class=\"navbar navbar-custom\"> <a class=\"navbar-brand\" href=\"#\"> Custom color background navbar </a> </nav> <div class=\"container\"> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to change navigation bar color in Bootstrap ?</b> <p>The above navigation bar uses a custom class for changing the colors.</p> </div></body> </html>", "e": 29294, "s": 28244, "text": null }, { "code": null, "e": 29304, "s": 29294, "text": "Output: " }, { "code": null, "e": 29320, "s": 29306, "text": "sumitgumber28" }, { "code": null, "e": 29332, "s": 29320, "text": "Bootstrap-4" }, { "code": null, "e": 29347, "s": 29332, "text": "Bootstrap-Misc" }, { "code": null, "e": 29354, "s": 29347, "text": "Picked" }, { "code": null, "e": 29364, "s": 29354, "text": "Bootstrap" }, { "code": null, "e": 29381, "s": 29364, "text": "Web Technologies" }, { "code": null, "e": 29408, "s": 29381, "text": "Web technologies Questions" }, { "code": null, "e": 29506, "s": 29408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29515, "s": 29506, "text": "Comments" }, { "code": null, "e": 29528, "s": 29515, "text": "Old Comments" }, { "code": null, "e": 29569, "s": 29528, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 29632, "s": 29569, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 29665, "s": 29632, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 29691, "s": 29665, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 29740, "s": 29691, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 29796, "s": 29740, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29829, "s": 29796, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29891, "s": 29829, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29934, "s": 29891, "text": "How to fetch data from an API in ReactJS ?" } ]
A little DISTINCT challenge with DAX optimisation | by Salvatore Cagliari | Towards Data Science
One of my clients asked me about the best way to perform a count of all his orders. This looks like an easy task in DAX, but it holds a few minor hurdles to answer the question in the best way. I used the Contoso dataset from Microsoft for this article. You can find it here: Microsoft Contoso BI Demo Dataset for Retail Industry. Take care that you need a SQL Server instance for this dataset, as the downloaded file is a SQL Server database backup file. Because the original file contains “only” 12 million rows in the Online Sales table, and I wanted to have as much test data as possible, I generated a further 51 million rows in this table, for a total of 63 million rows. The Retail sales table contains 15.5 million rows now, instead of 3.4 million rows. I loaded this data in a Power BI file, which has now 1.45 GB instead of 210 MB from the original dataset. I used DAX Studio to measure the performance of the different variants. When we look at the Online Sales table, we will notice that The table contains a column SaleOrderNumber Each SaleOrderNumber exists multiple times Each row has a SalesOrderLineNumber, which start from 1 for each Order Number. My client’s question was, “How can I count my orders most efficiently?”. The most straightforward approach to fulfil the requirement is a DISTINCTCOUNT(‘Online Sales’[Sales Order Number]). But I already experienced some performance issues for DISTINCTCOUNT() and wanted to try something different and compare the performance. You can read about possible problems with DISTINCTCOUNT() in the SQLBI Article Analyzing the performance of DISTINCTCOUNT in DAX. So I tried the following approach: I added a calculated column to the Online Sales table with the following expression: [First Order Line Counter] = IF(‘Online Sales’[Sales Order Line Number] = 1, 1, 0) To test the result, I executed the following query: DEFINE MEASURE ‘All Measures’[Distinct Order Count] = DISTINCTCOUNT(‘Online Sales’[Sales Order Number]) MEASURE ‘All Measures’[Sum First Line Counter] = SUM(‘Online Sales’[First Order Line Counter]) EVALUATE SUMMARIZECOLUMNS( ‘Date’[Year] ,”Distinct Order Count”, ‘All Measures’[Distinct Order Count] ,”First Order Line Count”, ‘All Measures’[Sum First Line Counter] ) The result is identical for both Measures. But as soon as you start slicing the result by other attributes, for example, by Brand Name, the situation changes: DEFINE MEASURE ‘All Measures’[Distinct Order Count] = DISTINCTCOUNT(‘Online Sales’[Sales Order Number]) MEASURE ‘All Measures’[Sum First Line Counter] = SUM(‘Online Sales’[First Order Line Counter]) EVALUATE SUMMARIZECOLUMNS( ‘Date’[Year] ,’Product’[BrandName] ,”Distinct Order Count”, ‘All Measures’[Distinct Order Count] ,”First Order Line Count”, ‘All Measures’[Sum First Line Counter] ) The result is no longer the same: Most of the rows have a [Sales Order Line Number], which is different from 1. As a consequence, all these rows have 0 as [First Order Line Counter]). The approach with the calculated column is not usable in this scenario. Even that I usually add a counter column with 1 in each row to simplify calculations (SUM() instead of COUNTROWS() ). The second approach is to use the following Measure: ‘All Measures’[Order Count] = COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[Sales Order Number] ) ) You can use VALUES(‘Online Sales’[SalesOrderNumber]) or DISTINCT(‘Online Sales’[SalesOrderNumber]) instead of SUMMARIZE(). But there is almost no difference in performance between these three solutions. Still, it would help if you made attention to the different behaviour between VALUES() and DISTINCT() related to possible blank values (See here for details: Blank row in DAX (SQLBI) ). I tested both variants against my test model, and I get almost the same performance: Both are quick, and the query is fulfilled almost entirely from the Storage Engine. And all three variants return the same result. I will explain why it is important that the Storage Engine fulfils the query instead of the Formula Engine later. At this point, I would have been able to go to my client and tell him what I found out: “It doesn’t matter. You can use whatever method you want”. But I knew that he has some complex calculation that relies on the DISTINCTCOUNT() pattern. So I needed to test these pattern as well. One of them is to count stock items using the LASTNONBLANK() function with a DISTINCTCOUNT() over specific columns. To use the same amount of data, I created a measure to count the last day’s orders in a specific period. I started with the DISTINCTCOUNT() function to get a baseline: ‘All Measures’[Count Last Day Sales] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) )RETURN CALCULATE( DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) ,LastSaleDate ) I queried the data with this measure and got this result: After this test, I applied the second approach described above to this measure: ‘All Measures’[Count Last Day Sales 2] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,COUNT(‘Online Sales’[SalesOrderNumber]) )RETURN CALCULATE( COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[SalesOrderNumber] ) ) ,LastSaleDate ) The performance was noticeably different: As you can see, the Total time is almost one second less. More importantly, the Storage Engine is used ~5% more as with DISTINCTCOUNT(). Why this is so important: Two factors make the usage of Storage Engine preferably instead of the Formula Engine: The Storage Engine is multi-threaded, while the Formula Engine is single-threaded only.The Storage Engine has a cache, while the Formula Engine doesn’t have any cache. The Storage Engine is multi-threaded, while the Formula Engine is single-threaded only. The Storage Engine has a cache, while the Formula Engine doesn’t have any cache. This first factor makes the Storage Engine fast and more efficient. The second factor makes measures, which uses more of the Storage Engine, more scalable. This means that when several users are using a report with this measure, the Storage Engine will use his cache, and the performance will be better. This topic is explained here in detail: Formula engine and storage engine in DAX (SQLBI) As the guys at SQLBI always point out, it is essential to understand the theory, but it is more important to test this knowledge against the specific situation. So I executed a benchmark test in DAX Studio. The results are surprising: Now compare the benchmark result with the measure which uses SUMMARIZE(): This result is surprising when you look at the results with a warm cache. With a cold cache, the Measure with SUMMARIZE() is consistently quicker. But as soon as we use the cache, the measure with DISTINCT() becomes quicker. The measure which uses less from the Storage Engine performs better when the query is executed several times. This result is unexpected and needs more analysis. You can find the reason for this result when you look at the execution plans side by side: You see the significant difference when you compare the first two lines. The Measure with DISTINCTCOUNT() generates 4'290 and 6'575 intermediary rows, while the Measure with SUMMARIZE() generates 8'536 and 6'575 intermediary rows. The following steps are using fewer rows as well with the DISTINCTCOUNT() measure. This is the reason why the measure with DISTINCTCOUNT() is faster when using the cache. There are fewer data to store in the cache, and therefore, it has fewer data to retrieve. My main message to you is: Don’t take any advice for granted. Your situation is always unique, and it can change the outcome of any optimisation applied to your code. You need a good understanding of how the two Engines works and how to use the available tools to gain as much knowledge as possible. When you test your code, execute the query with and without cache. You can use the “Clear Cache then run” feature in DAX Studio for this: Apply your know-how to your specific situation and don’t take anything for granted because you have read something written on the Internet. Think about the existing use-cases and how your users will query the data. Use this knowledge to perform meaningful benchmarks and take valuable measurements. Document all steps, changes to your code and measurements after each change. For my tests, I used the following DAX Query with the definition of all different Measures to perform the tests: DEFINE MEASURE ‘All Measures’[Distinct Count] = DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) MEASURE ‘All Measures’[Order Count] = COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[SalesOrderNumber] ) ) MEASURE ‘All Measures’[Order Count D] = COUNTROWS( DISTINCT( ‘Online Sales’[SalesOrderNumber] ) ) MEASURE ‘All Measures’[Order Count V] = COUNTROWS( VALUES( ‘Online Sales’[SalesOrderNumber] ) ) MEASURE ‘All Measures’[Sum Main Row] = SUM(‘Online Sales’[First Order Line Count]) MEASURE ‘All Measures’[Sum Sales Line] = SUM(‘Online Sales’[Sale Line Counter]) MEASURE ‘All Measures’[Sales Last Date] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,COUNT(‘Online Sales’[SalesOrderNumber]) ) RETURN LastSaleDate MEASURE ‘All Measures’[Count Last Day Sales] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) ) RETURN CALCULATE( DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) ,LastSaleDate ) MEASURE ‘All Measures’[Count Last Day Sales 2] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,COUNT(‘Online Sales’[SalesOrderNumber]) ) RETURN CALCULATE( COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[SalesOrderNumber] ) ) // Alternative to SUMMARIZE is: // VALUES(‘Online Sales’[SalesOrderNumber] // ) // ) ,LastSaleDate ) //EVALUATE // SUMMARIZECOLUMNS( // ‘Date’[Year] // ,’Customer’[CompanyName] // ,”Distinct Count”, ‘All Measures’[Distinct Count] // ,”Sum First order Line”, ‘All Measures’[Sum Main Row] // ,”Sum Line Counter”, ‘All Measures’[Sum Sales Line] // ,”Order Count Adv.”, ‘All Measures’[Order Count] // ,”Distinct Count”, ‘All Measures’[Distinct Count] // ,”Distinct Count D”, ‘All Measures’[Order Count D] // ,”Distinct Count V”, ‘All Measures’[Order Count V] // ) EVALUATE SUMMARIZECOLUMNS( ‘Date’[Year] ,’Customer’[CompanyName] // ,”Distinct Count”, ‘All Measures’[Distinct Count] // ,”Sum First order Line”, ‘All Measures’[Sum Main Row] // ,”Sum Line Counter”, ‘All Measures’[Sum Sales Line] // ,”Order Count Adv.”, ‘All Measures’[Order Count] // ,”Sales Last Date”, ‘All Measures’[Sales Last Date] ,”Count Last Sales”, ‘All Measures’[Count Last Day Sales] // ,”Count Last Sales 2", ‘All Measures’[Count Last Day Sales 2] ) I uncommented the parts I wanted to test or compare and changed the Measures directly in the Script. In the end: Use your common sense to choose the right approach when you try to find the best solution. BTW: You can apply everything in this article to Power BI and Analysis Services.
[ { "code": null, "e": 365, "s": 171, "text": "One of my clients asked me about the best way to perform a count of all his orders. This looks like an easy task in DAX, but it holds a few minor hurdles to answer the question in the best way." }, { "code": null, "e": 627, "s": 365, "text": "I used the Contoso dataset from Microsoft for this article. You can find it here: Microsoft Contoso BI Demo Dataset for Retail Industry. Take care that you need a SQL Server instance for this dataset, as the downloaded file is a SQL Server database backup file." }, { "code": null, "e": 933, "s": 627, "text": "Because the original file contains “only” 12 million rows in the Online Sales table, and I wanted to have as much test data as possible, I generated a further 51 million rows in this table, for a total of 63 million rows. The Retail sales table contains 15.5 million rows now, instead of 3.4 million rows." }, { "code": null, "e": 1039, "s": 933, "text": "I loaded this data in a Power BI file, which has now 1.45 GB instead of 210 MB from the original dataset." }, { "code": null, "e": 1111, "s": 1039, "text": "I used DAX Studio to measure the performance of the different variants." }, { "code": null, "e": 1171, "s": 1111, "text": "When we look at the Online Sales table, we will notice that" }, { "code": null, "e": 1215, "s": 1171, "text": "The table contains a column SaleOrderNumber" }, { "code": null, "e": 1258, "s": 1215, "text": "Each SaleOrderNumber exists multiple times" }, { "code": null, "e": 1337, "s": 1258, "text": "Each row has a SalesOrderLineNumber, which start from 1 for each Order Number." }, { "code": null, "e": 1410, "s": 1337, "text": "My client’s question was, “How can I count my orders most efficiently?”." }, { "code": null, "e": 1526, "s": 1410, "text": "The most straightforward approach to fulfil the requirement is a DISTINCTCOUNT(‘Online Sales’[Sales Order Number])." }, { "code": null, "e": 1793, "s": 1526, "text": "But I already experienced some performance issues for DISTINCTCOUNT() and wanted to try something different and compare the performance. You can read about possible problems with DISTINCTCOUNT() in the SQLBI Article Analyzing the performance of DISTINCTCOUNT in DAX." }, { "code": null, "e": 1828, "s": 1793, "text": "So I tried the following approach:" }, { "code": null, "e": 1913, "s": 1828, "text": "I added a calculated column to the Online Sales table with the following expression:" }, { "code": null, "e": 1996, "s": 1913, "text": "[First Order Line Counter] = IF(‘Online Sales’[Sales Order Line Number] = 1, 1, 0)" }, { "code": null, "e": 2048, "s": 1996, "text": "To test the result, I executed the following query:" }, { "code": null, "e": 2466, "s": 2048, "text": "DEFINE MEASURE ‘All Measures’[Distinct Order Count] = DISTINCTCOUNT(‘Online Sales’[Sales Order Number]) MEASURE ‘All Measures’[Sum First Line Counter] = SUM(‘Online Sales’[First Order Line Counter]) EVALUATE SUMMARIZECOLUMNS( ‘Date’[Year] ,”Distinct Order Count”, ‘All Measures’[Distinct Order Count] ,”First Order Line Count”, ‘All Measures’[Sum First Line Counter] )" }, { "code": null, "e": 2509, "s": 2466, "text": "The result is identical for both Measures." }, { "code": null, "e": 2625, "s": 2509, "text": "But as soon as you start slicing the result by other attributes, for example, by Brand Name, the situation changes:" }, { "code": null, "e": 3059, "s": 2625, "text": "DEFINE MEASURE ‘All Measures’[Distinct Order Count] = DISTINCTCOUNT(‘Online Sales’[Sales Order Number]) MEASURE ‘All Measures’[Sum First Line Counter] = SUM(‘Online Sales’[First Order Line Counter]) EVALUATE SUMMARIZECOLUMNS( ‘Date’[Year] ,’Product’[BrandName] ,”Distinct Order Count”, ‘All Measures’[Distinct Order Count] ,”First Order Line Count”, ‘All Measures’[Sum First Line Counter] )" }, { "code": null, "e": 3093, "s": 3059, "text": "The result is no longer the same:" }, { "code": null, "e": 3243, "s": 3093, "text": "Most of the rows have a [Sales Order Line Number], which is different from 1. As a consequence, all these rows have 0 as [First Order Line Counter])." }, { "code": null, "e": 3433, "s": 3243, "text": "The approach with the calculated column is not usable in this scenario. Even that I usually add a counter column with 1 in each row to simplify calculations (SUM() instead of COUNTROWS() )." }, { "code": null, "e": 3486, "s": 3433, "text": "The second approach is to use the following Measure:" }, { "code": null, "e": 3632, "s": 3486, "text": "‘All Measures’[Order Count] = COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[Sales Order Number] ) )" }, { "code": null, "e": 4021, "s": 3632, "text": "You can use VALUES(‘Online Sales’[SalesOrderNumber]) or DISTINCT(‘Online Sales’[SalesOrderNumber]) instead of SUMMARIZE(). But there is almost no difference in performance between these three solutions. Still, it would help if you made attention to the different behaviour between VALUES() and DISTINCT() related to possible blank values (See here for details: Blank row in DAX (SQLBI) )." }, { "code": null, "e": 4106, "s": 4021, "text": "I tested both variants against my test model, and I get almost the same performance:" }, { "code": null, "e": 4237, "s": 4106, "text": "Both are quick, and the query is fulfilled almost entirely from the Storage Engine. And all three variants return the same result." }, { "code": null, "e": 4351, "s": 4237, "text": "I will explain why it is important that the Storage Engine fulfils the query instead of the Formula Engine later." }, { "code": null, "e": 4498, "s": 4351, "text": "At this point, I would have been able to go to my client and tell him what I found out: “It doesn’t matter. You can use whatever method you want”." }, { "code": null, "e": 4633, "s": 4498, "text": "But I knew that he has some complex calculation that relies on the DISTINCTCOUNT() pattern. So I needed to test these pattern as well." }, { "code": null, "e": 4749, "s": 4633, "text": "One of them is to count stock items using the LASTNONBLANK() function with a DISTINCTCOUNT() over specific columns." }, { "code": null, "e": 4854, "s": 4749, "text": "To use the same amount of data, I created a measure to count the last day’s orders in a specific period." }, { "code": null, "e": 4917, "s": 4854, "text": "I started with the DISTINCTCOUNT() function to get a baseline:" }, { "code": null, "e": 5177, "s": 4917, "text": "‘All Measures’[Count Last Day Sales] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) )RETURN CALCULATE( DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) ,LastSaleDate )" }, { "code": null, "e": 5235, "s": 5177, "text": "I queried the data with this measure and got this result:" }, { "code": null, "e": 5315, "s": 5235, "text": "After this test, I applied the second approach described above to this measure:" }, { "code": null, "e": 5627, "s": 5315, "text": "‘All Measures’[Count Last Day Sales 2] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,COUNT(‘Online Sales’[SalesOrderNumber]) )RETURN CALCULATE( COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[SalesOrderNumber] ) ) ,LastSaleDate )" }, { "code": null, "e": 5669, "s": 5627, "text": "The performance was noticeably different:" }, { "code": null, "e": 5727, "s": 5669, "text": "As you can see, the Total time is almost one second less." }, { "code": null, "e": 5806, "s": 5727, "text": "More importantly, the Storage Engine is used ~5% more as with DISTINCTCOUNT()." }, { "code": null, "e": 5832, "s": 5806, "text": "Why this is so important:" }, { "code": null, "e": 5919, "s": 5832, "text": "Two factors make the usage of Storage Engine preferably instead of the Formula Engine:" }, { "code": null, "e": 6087, "s": 5919, "text": "The Storage Engine is multi-threaded, while the Formula Engine is single-threaded only.The Storage Engine has a cache, while the Formula Engine doesn’t have any cache." }, { "code": null, "e": 6175, "s": 6087, "text": "The Storage Engine is multi-threaded, while the Formula Engine is single-threaded only." }, { "code": null, "e": 6256, "s": 6175, "text": "The Storage Engine has a cache, while the Formula Engine doesn’t have any cache." }, { "code": null, "e": 6560, "s": 6256, "text": "This first factor makes the Storage Engine fast and more efficient. The second factor makes measures, which uses more of the Storage Engine, more scalable. This means that when several users are using a report with this measure, the Storage Engine will use his cache, and the performance will be better." }, { "code": null, "e": 6649, "s": 6560, "text": "This topic is explained here in detail: Formula engine and storage engine in DAX (SQLBI)" }, { "code": null, "e": 6810, "s": 6649, "text": "As the guys at SQLBI always point out, it is essential to understand the theory, but it is more important to test this knowledge against the specific situation." }, { "code": null, "e": 6884, "s": 6810, "text": "So I executed a benchmark test in DAX Studio. The results are surprising:" }, { "code": null, "e": 6958, "s": 6884, "text": "Now compare the benchmark result with the measure which uses SUMMARIZE():" }, { "code": null, "e": 7032, "s": 6958, "text": "This result is surprising when you look at the results with a warm cache." }, { "code": null, "e": 7183, "s": 7032, "text": "With a cold cache, the Measure with SUMMARIZE() is consistently quicker. But as soon as we use the cache, the measure with DISTINCT() becomes quicker." }, { "code": null, "e": 7344, "s": 7183, "text": "The measure which uses less from the Storage Engine performs better when the query is executed several times. This result is unexpected and needs more analysis." }, { "code": null, "e": 7435, "s": 7344, "text": "You can find the reason for this result when you look at the execution plans side by side:" }, { "code": null, "e": 7508, "s": 7435, "text": "You see the significant difference when you compare the first two lines." }, { "code": null, "e": 7666, "s": 7508, "text": "The Measure with DISTINCTCOUNT() generates 4'290 and 6'575 intermediary rows, while the Measure with SUMMARIZE() generates 8'536 and 6'575 intermediary rows." }, { "code": null, "e": 7927, "s": 7666, "text": "The following steps are using fewer rows as well with the DISTINCTCOUNT() measure. This is the reason why the measure with DISTINCTCOUNT() is faster when using the cache. There are fewer data to store in the cache, and therefore, it has fewer data to retrieve." }, { "code": null, "e": 8094, "s": 7927, "text": "My main message to you is: Don’t take any advice for granted. Your situation is always unique, and it can change the outcome of any optimisation applied to your code." }, { "code": null, "e": 8227, "s": 8094, "text": "You need a good understanding of how the two Engines works and how to use the available tools to gain as much knowledge as possible." }, { "code": null, "e": 8365, "s": 8227, "text": "When you test your code, execute the query with and without cache. You can use the “Clear Cache then run” feature in DAX Studio for this:" }, { "code": null, "e": 8505, "s": 8365, "text": "Apply your know-how to your specific situation and don’t take anything for granted because you have read something written on the Internet." }, { "code": null, "e": 8664, "s": 8505, "text": "Think about the existing use-cases and how your users will query the data. Use this knowledge to perform meaningful benchmarks and take valuable measurements." }, { "code": null, "e": 8741, "s": 8664, "text": "Document all steps, changes to your code and measurements after each change." }, { "code": null, "e": 8854, "s": 8741, "text": "For my tests, I used the following DAX Query with the definition of all different Measures to perform the tests:" }, { "code": null, "e": 11523, "s": 8854, "text": "DEFINE MEASURE ‘All Measures’[Distinct Count] = DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) MEASURE ‘All Measures’[Order Count] = COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[SalesOrderNumber] ) ) MEASURE ‘All Measures’[Order Count D] = COUNTROWS( DISTINCT( ‘Online Sales’[SalesOrderNumber] ) ) MEASURE ‘All Measures’[Order Count V] = COUNTROWS( VALUES( ‘Online Sales’[SalesOrderNumber] ) ) MEASURE ‘All Measures’[Sum Main Row] = SUM(‘Online Sales’[First Order Line Count]) MEASURE ‘All Measures’[Sum Sales Line] = SUM(‘Online Sales’[Sale Line Counter]) MEASURE ‘All Measures’[Sales Last Date] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,COUNT(‘Online Sales’[SalesOrderNumber]) ) RETURN LastSaleDate MEASURE ‘All Measures’[Count Last Day Sales] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) ) RETURN CALCULATE( DISTINCTCOUNT(‘Online Sales’[SalesOrderNumber]) ,LastSaleDate ) MEASURE ‘All Measures’[Count Last Day Sales 2] = VAR LastSaleDate = LASTNONBLANK(‘Date’[Date] ,COUNT(‘Online Sales’[SalesOrderNumber]) ) RETURN CALCULATE( COUNTROWS( SUMMARIZE( ‘Online Sales’ ,’Online Sales’[SalesOrderNumber] ) ) // Alternative to SUMMARIZE is: // VALUES(‘Online Sales’[SalesOrderNumber] // ) // ) ,LastSaleDate ) //EVALUATE // SUMMARIZECOLUMNS( // ‘Date’[Year] // ,’Customer’[CompanyName] // ,”Distinct Count”, ‘All Measures’[Distinct Count] // ,”Sum First order Line”, ‘All Measures’[Sum Main Row] // ,”Sum Line Counter”, ‘All Measures’[Sum Sales Line] // ,”Order Count Adv.”, ‘All Measures’[Order Count] // ,”Distinct Count”, ‘All Measures’[Distinct Count] // ,”Distinct Count D”, ‘All Measures’[Order Count D] // ,”Distinct Count V”, ‘All Measures’[Order Count V] // ) EVALUATE SUMMARIZECOLUMNS( ‘Date’[Year] ,’Customer’[CompanyName] // ,”Distinct Count”, ‘All Measures’[Distinct Count] // ,”Sum First order Line”, ‘All Measures’[Sum Main Row] // ,”Sum Line Counter”, ‘All Measures’[Sum Sales Line] // ,”Order Count Adv.”, ‘All Measures’[Order Count] // ,”Sales Last Date”, ‘All Measures’[Sales Last Date] ,”Count Last Sales”, ‘All Measures’[Count Last Day Sales] // ,”Count Last Sales 2\", ‘All Measures’[Count Last Day Sales 2] )" }, { "code": null, "e": 11624, "s": 11523, "text": "I uncommented the parts I wanted to test or compare and changed the Measures directly in the Script." }, { "code": null, "e": 11727, "s": 11624, "text": "In the end: Use your common sense to choose the right approach when you try to find the best solution." } ]