title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Import and Merge Multiple CSV Files in R - GeeksforGeeks
17 Jun, 2021 In this article, we will be looking at the approach to merge multiple CSV files in the R programming language. dplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles. plyr: plyr is an R package that makes it simple to split data apart, do stuff to it, and mash it back together. readr: This provides a fast and friendly way to read rectangular data (like ‘csv’, ‘tsv’, and ‘fwf’). list.files() function: This function produces a character vector of the names of files or directories in the named directory. Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE) lapply() function: This function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X. Syntax: lapply(X, FUN, ...) bind_rows() function: This function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one. Syntax: bind_rows(..., .id = NULL) Parameter: ...: Data frames to combine. .id: Data frame identifier. To merge multiple CSV files, the user needs to install and import dplyr,plyr, and readr packages in the R console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language. Data in Use: Example: R library("dplyr") library("plyr") library("readr") gfg_data <- list.files(path = "C:/Users/Geetansh Sahni/Documents/R/Data", pattern = "*.csv", full.names = TRUE) %>% lapply(read_csv) %>% bind_rows gfg_data Output: Picked R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Control Statements in R Programming Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Logistic Regression in R Programming How to change Colors in ggplot2 Line Plot in R ? How to filter R DataFrame by values in a column? Linear Discriminant Analysis in R Programming R - Operators
[ { "code": null, "e": 24923, "s": 24892, "text": " \n17 Jun, 2021\n" }, { "code": null, "e": 25034, "s": 24923, "text": "In this article, we will be looking at the approach to merge multiple CSV files in the R programming language." }, { "code": null, "e": 25184, "s": 25034, "text": "dplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles." }, { "code": null, "e": 25296, "s": 25184, "text": "plyr: plyr is an R package that makes it simple to split data apart, do stuff to it, and mash it back together." }, { "code": null, "e": 25398, "s": 25296, "text": "readr: This provides a fast and friendly way to read rectangular data (like ‘csv’, ‘tsv’, and ‘fwf’)." }, { "code": null, "e": 25524, "s": 25398, "text": "list.files() function: This function produces a character vector of the names of files or directories in the named directory." }, { "code": null, "e": 25685, "s": 25524, "text": "Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)" }, { "code": null, "e": 25845, "s": 25685, "text": "lapply() function: This function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X." }, { "code": null, "e": 25873, "s": 25845, "text": "Syntax: lapply(X, FUN, ...)" }, { "code": null, "e": 26047, "s": 25873, "text": "bind_rows() function: This function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one." }, { "code": null, "e": 26055, "s": 26047, "text": "Syntax:" }, { "code": null, "e": 26082, "s": 26055, "text": "bind_rows(..., .id = NULL)" }, { "code": null, "e": 26093, "s": 26082, "text": "Parameter:" }, { "code": null, "e": 26122, "s": 26093, "text": "...: Data frames to combine." }, { "code": null, "e": 26150, "s": 26122, "text": ".id: Data frame identifier." }, { "code": null, "e": 26500, "s": 26150, "text": "To merge multiple CSV files, the user needs to install and import dplyr,plyr, and readr packages in the R console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language." }, { "code": null, "e": 26513, "s": 26500, "text": "Data in Use:" }, { "code": null, "e": 26522, "s": 26513, "text": "Example:" }, { "code": null, "e": 26524, "s": 26522, "text": "R" }, { "code": "\n\n\n\n\n\n\nlibrary(\"dplyr\") \nlibrary(\"plyr\") \nlibrary(\"readr\") \n \ngfg_data <- list.files(path = \"C:/Users/Geetansh Sahni/Documents/R/Data\", \n pattern = \"*.csv\", full.names = TRUE) %>% \n lapply(read_csv) %>% \n bind_rows \n \ngfg_data\n\n\n\n\n\n", "e": 26984, "s": 26534, "text": null }, { "code": null, "e": 26993, "s": 26984, "text": " Output:" }, { "code": null, "e": 27002, "s": 26993, "text": "\nPicked\n" }, { "code": null, "e": 27010, "s": 27002, "text": "\nR-CSV\n" }, { "code": null, "e": 27023, "s": 27010, "text": "\nR Language\n" }, { "code": null, "e": 27228, "s": 27023, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27264, "s": 27228, "text": "Control Statements in R Programming" }, { "code": null, "e": 27316, "s": 27264, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27340, "s": 27316, "text": "Data Visualization in R" }, { "code": null, "e": 27375, "s": 27340, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27413, "s": 27375, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27450, "s": 27413, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27499, "s": 27450, "text": "How to change Colors in ggplot2 Line Plot in R ?" }, { "code": null, "e": 27548, "s": 27499, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27594, "s": 27548, "text": "Linear Discriminant Analysis in R Programming" } ]
Factor Analysis 101. Can we reduce the number of variables... | by Jeppe Andersen | Towards Data Science
Even though this is an introductory look at Factor Analysis, I assume that the reader has some knowledge in math and statistics and want to learn about multivariate statistical analysis. This article will focus on the theoretical understanding of Factor Analysis and I will thus leave out the coding related to this subject — except for a simple R illustration. Make sure to follow my profile if you enjoy this article and want to see more! In real life, data tends to follow some patterns but the reasons are not apparent right from the start of the data analysis. The essential purpose of Factor Analysis is to describe the covariance relationships between several variables in terms of a few underlying and unobservable random components that we will call factors. We will assume that the variables can be grouped by looking at their correlations. That is, assume that all variables in a specific group have high correlation among themselves, but low correlation with variables in other groups. In that case we can think of each group of variables as a representation of a single underlying construction, or a factor, which is responsible for the observed correlation. As an example, correlation from a group consisting of the variables english, math and biology scores could come from an underlying “intelligence factor” and another group of variables representing fitness scores could correspond to another underlying factor.Factor Analysis is an extension of Principal Component Analysis (PCA). Both models tries to approximate the covariance matrix Σ, but Factor Analysis questions whether the data are consistent with some prescribed structure. If you haven’t heard about PCA, I recommend this article that illustrates it with R: towardsdatascience.com The Factor Analysis Model in matrix form is: X is an observable stochastic vector with p components, mean vector μ and covariance matrix Σ. The factor model says that X is linear dependent on a few m unobservable stochastic variables, called common factors and p sources of variation, called errors or specific factors. The coefficients l_ij is called the loadings of the variable i on the factor j, so that the matrix L is the matrix of factor loadings (I will use “_” to denote lowercase letters).The i specific factors ε_i are only connected with the i variables X_i. The p deviations, are expressed in terms of the p+m stochastic variables, which are all unobservable. This is what seperates the factor model from the multivariate regression model, where the independent variables can be observed. All of these unobservable components provides some complications. We cannot directly verify the factor model if we have unobservable components, but with some assumptions on F and ε, the model implements covariance relationships and we can try to interpret them. We will then assume that the mean and covariance for F and ε are: and that F and ε are independent, so that Cov(ε, F) = E(εF’) = 0.Here, Cov(ε) includes Ψ which is the uniqueness for each variable, i.e. the amount of variance that cannot be explained by any factor. If the unobservable random vectors F and ε satisfy these conditions, we have a factor model with m common factors: The covariance structure of this model is then: The factor model is linear in the common factors. If the relationship between X and the underlying factors are not linear, the covariance structure above is not sufficient. The proportion of variance of the ith variable contributed by the m common factors is called the ith communality, h2_i. The proportion of Var(X_i) = σ_ii that is due to the specific factor is the uniqueness or specific variance. We will see that: (I.e. Var(X_i) = communality + specific variance)Or that The ith communality is then the sum of squares of loadings of the ith variable on the m common factors. If the common and specific factors can be assumed normal distributed, we can use MLE for the factor loadings and specific variances. The likelihood function is not pretty, so I won’t include it here, but understand that it depends on L and Ψ through Σ = LL^T + Ψ. This model is not defined because of the many choices for L and this is where the uniqueness condition comes to use: It’s a diagonal matrix and it secures one maximum so that estimates for ^L and ^Ψ can be found (I will use ^ in front of a letter to denote a “hat” operator). From here, the proportion of total variance included in the jth factor can be explained by the estimated loadings. The trouble here is that the maximum likelihood solution for factor loadings is limited by the uniqueness condition and clear patterns in the factors can be difficult to see until they are rotated. Our structure is orthogonal (e.g. two vectors are considered orthogonal if they form a 90-degree angle). An orthogonal transformation of factor loadings (and hence as implied orthogonal rotation of the factors) is called factor rotation. If ^L is the matrix of estimated factor loadings, then is a matrix of “rotated” loadings. The estimated covariance matrix stays the same and this rotation can give a simpler structure and make the factors easier to interpret, just like a microscope. An analytical solution is the Varimax Criterion (Google it) that chooses the orthogonal transformation for maximizing. Factor rotation is especially good for estimates found by MLE because of the uniqueness condition used there. Alright, so what did we just spend 10 minutes reading about?Dealing with multidimensional data can be tough, so if we can “cut” down the number of dimensions, we can make the data way easier to look at and we can subjectively try to intepret the underlying factors. We will look at the Olympic decathlon data (Johnson and Wichern p.499) that you can get with od.data <- read.table("http://static.lib.virginia.edu/statlab/materials/data/decathlon.dat") Edit: If you are trying this out for the first time, you will get an error if you are not adding a matrix translation. This is done by: od.data <- as.matrix(od.data)rownames(od.data) <- colnames(od.data) <- c("100m","LJ","SP","HJ","400m","100mH","DS","PV","JV","1500m") First let’s try 3 factors. The output is: By default, factanalprovides ML estimates and Varimax rotation. First is the uniqueness. It represents ^Ψ from earlier. If the uniqueness is high, the variance cannot be described by any of the factors, thus the name uniqueness or specific variance. It cannot be explained by some underlying factor. This is the case for the 1500m run and vica versa for SP (Shot put). If we subtract the uniqueness from 1, we get the communality and it will then tell how much variance is explained by the 3 factors. The loadings represent ^L from earlier. I have sorted the data and we can easily see that shot put (SP) and discus (DS) have high loadings relative to the other variables in factor 1, implying thename “arm strength” for this factor. Specifically it means that e.g. shot put has correlation of 0.915 with factor 1 and a smaller correlation with the other two factors. We are also interested in “Cumulative var”, the cumulative proportion of variance explained, and it should be a “high” number, where high is subjective. We should probably try fitting 4 factors, as I don’t think that 0.554 is that high and we might be able to do better. The low p-value in the end also rejects the hypothesis that 3 factors are sufficient.The output is now: This looks more promising. 4 factors are sufficient (according to the p-value) and we have succesfully reduced the number of variables from 10 to 4. The interpretation of the factors is subjective, we cannot explicitly name them, but a good guess could be “arm strength”, “leg strength”, “speed/acceleration” and “running endurance” by looking at where the correlation is high for the variables. Javelin and 100m hurdles have high uniqueness and does not fit well into any of the factors. Maybe a little bit in factor 1 and 2, respectively. The most important part is finding the number of factors. From here you can play around with estimation and rotation methods and sharpen the focus of the microscope, but it’s not that crucial. Johnson and Wichern state that “the vast majority of attempted factor analyses do not yield clearcut results.” (p. 526) There is no guarantee that a factor analysis will lead to a satisfying description of meaningful factors. If you find yourself confused over the results of a factor analysis because it didn’t seem to “work”, there’s a good chance you did nothing wrong and that the factor analysis simply didn’t find anything interesting. Also, factor analysis can lead to controversy if you’re trying to measure quantities such as “intelligence”, “compassion” or “potential”. Those quantities are difficult to measure and can they be responsible for events that we know we can measure, such as high SAT scores? Factor analysis cannot answer this. The quality of a factor analysis depends more on a “Wow” criterion, as the quality has not been quantified and if you can say “wow, I understand these factors” the application has probably been a success. As I said before, the cumulative variance is a subjective measure and it is hard to know whether 0.621 is good or bad and intuitively, 60% is probably not that good. Either way, if you are able to reduce the dimensions from, say, 50 to 8 (or 10 to 4 in our case), it could help you explore your data better and make it more managable by understanding the covariance between the variables. Please keep in mind that this is purely introductory and isn’t supposed to be a conclusion or an exhaustive analysis. Feel free to correct me if I missed something or did something wrong (I probably did). There are a lot of different methods for dealing with multivariate data and there is even more to Factor Analysis than in the scope of this article. Make sure to follow my profile if you enjoy this article and want to see more!
[ { "code": null, "e": 534, "s": 172, "text": "Even though this is an introductory look at Factor Analysis, I assume that the reader has some knowledge in math and statistics and want to learn about multivariate statistical analysis. This article will focus on the theoretical understanding of Factor Analysis and I will thus leave out the coding related to this subject — except for a simple R illustration." }, { "code": null, "e": 613, "s": 534, "text": "Make sure to follow my profile if you enjoy this article and want to see more!" }, { "code": null, "e": 940, "s": 613, "text": "In real life, data tends to follow some patterns but the reasons are not apparent right from the start of the data analysis. The essential purpose of Factor Analysis is to describe the covariance relationships between several variables in terms of a few underlying and unobservable random components that we will call factors." }, { "code": null, "e": 1344, "s": 940, "text": "We will assume that the variables can be grouped by looking at their correlations. That is, assume that all variables in a specific group have high correlation among themselves, but low correlation with variables in other groups. In that case we can think of each group of variables as a representation of a single underlying construction, or a factor, which is responsible for the observed correlation." }, { "code": null, "e": 1910, "s": 1344, "text": "As an example, correlation from a group consisting of the variables english, math and biology scores could come from an underlying “intelligence factor” and another group of variables representing fitness scores could correspond to another underlying factor.Factor Analysis is an extension of Principal Component Analysis (PCA). Both models tries to approximate the covariance matrix Σ, but Factor Analysis questions whether the data are consistent with some prescribed structure. If you haven’t heard about PCA, I recommend this article that illustrates it with R:" }, { "code": null, "e": 1933, "s": 1910, "text": "towardsdatascience.com" }, { "code": null, "e": 1978, "s": 1933, "text": "The Factor Analysis Model in matrix form is:" }, { "code": null, "e": 2168, "s": 1978, "text": "X is an observable stochastic vector with p components, mean vector μ and covariance matrix Σ. The factor model says that X is linear dependent on a few m unobservable stochastic variables," }, { "code": null, "e": 2218, "s": 2168, "text": "called common factors and p sources of variation," }, { "code": null, "e": 2522, "s": 2218, "text": "called errors or specific factors. The coefficients l_ij is called the loadings of the variable i on the factor j, so that the matrix L is the matrix of factor loadings (I will use “_” to denote lowercase letters).The i specific factors ε_i are only connected with the i variables X_i. The p deviations," }, { "code": null, "e": 2578, "s": 2522, "text": "are expressed in terms of the p+m stochastic variables," }, { "code": null, "e": 2998, "s": 2578, "text": "which are all unobservable. This is what seperates the factor model from the multivariate regression model, where the independent variables can be observed. All of these unobservable components provides some complications. We cannot directly verify the factor model if we have unobservable components, but with some assumptions on F and ε, the model implements covariance relationships and we can try to interpret them." }, { "code": null, "e": 3064, "s": 2998, "text": "We will then assume that the mean and covariance for F and ε are:" }, { "code": null, "e": 3264, "s": 3064, "text": "and that F and ε are independent, so that Cov(ε, F) = E(εF’) = 0.Here, Cov(ε) includes Ψ which is the uniqueness for each variable, i.e. the amount of variance that cannot be explained by any factor." }, { "code": null, "e": 3379, "s": 3264, "text": "If the unobservable random vectors F and ε satisfy these conditions, we have a factor model with m common factors:" }, { "code": null, "e": 3427, "s": 3379, "text": "The covariance structure of this model is then:" }, { "code": null, "e": 3600, "s": 3427, "text": "The factor model is linear in the common factors. If the relationship between X and the underlying factors are not linear, the covariance structure above is not sufficient." }, { "code": null, "e": 3847, "s": 3600, "text": "The proportion of variance of the ith variable contributed by the m common factors is called the ith communality, h2_i. The proportion of Var(X_i) = σ_ii that is due to the specific factor is the uniqueness or specific variance. We will see that:" }, { "code": null, "e": 3904, "s": 3847, "text": "(I.e. Var(X_i) = communality + specific variance)Or that" }, { "code": null, "e": 4008, "s": 3904, "text": "The ith communality is then the sum of squares of loadings of the ith variable on the m common factors." }, { "code": null, "e": 4389, "s": 4008, "text": "If the common and specific factors can be assumed normal distributed, we can use MLE for the factor loadings and specific variances. The likelihood function is not pretty, so I won’t include it here, but understand that it depends on L and Ψ through Σ = LL^T + Ψ. This model is not defined because of the many choices for L and this is where the uniqueness condition comes to use:" }, { "code": null, "e": 4861, "s": 4389, "text": "It’s a diagonal matrix and it secures one maximum so that estimates for ^L and ^Ψ can be found (I will use ^ in front of a letter to denote a “hat” operator). From here, the proportion of total variance included in the jth factor can be explained by the estimated loadings. The trouble here is that the maximum likelihood solution for factor loadings is limited by the uniqueness condition and clear patterns in the factors can be difficult to see until they are rotated." }, { "code": null, "e": 5154, "s": 4861, "text": "Our structure is orthogonal (e.g. two vectors are considered orthogonal if they form a 90-degree angle). An orthogonal transformation of factor loadings (and hence as implied orthogonal rotation of the factors) is called factor rotation. If ^L is the matrix of estimated factor loadings, then" }, { "code": null, "e": 5578, "s": 5154, "text": "is a matrix of “rotated” loadings. The estimated covariance matrix stays the same and this rotation can give a simpler structure and make the factors easier to interpret, just like a microscope. An analytical solution is the Varimax Criterion (Google it) that chooses the orthogonal transformation for maximizing. Factor rotation is especially good for estimates found by MLE because of the uniqueness condition used there." }, { "code": null, "e": 5844, "s": 5578, "text": "Alright, so what did we just spend 10 minutes reading about?Dealing with multidimensional data can be tough, so if we can “cut” down the number of dimensions, we can make the data way easier to look at and we can subjectively try to intepret the underlying factors." }, { "code": null, "e": 5937, "s": 5844, "text": "We will look at the Olympic decathlon data (Johnson and Wichern p.499) that you can get with" }, { "code": null, "e": 6030, "s": 5937, "text": "od.data <- read.table(\"http://static.lib.virginia.edu/statlab/materials/data/decathlon.dat\")" }, { "code": null, "e": 6166, "s": 6030, "text": "Edit: If you are trying this out for the first time, you will get an error if you are not adding a matrix translation. This is done by:" }, { "code": null, "e": 6300, "s": 6166, "text": "od.data <- as.matrix(od.data)rownames(od.data) <- colnames(od.data) <- c(\"100m\",\"LJ\",\"SP\",\"HJ\",\"400m\",\"100mH\",\"DS\",\"PV\",\"JV\",\"1500m\")" }, { "code": null, "e": 6342, "s": 6300, "text": "First let’s try 3 factors. The output is:" }, { "code": null, "e": 6843, "s": 6342, "text": "By default, factanalprovides ML estimates and Varimax rotation. First is the uniqueness. It represents ^Ψ from earlier. If the uniqueness is high, the variance cannot be described by any of the factors, thus the name uniqueness or specific variance. It cannot be explained by some underlying factor. This is the case for the 1500m run and vica versa for SP (Shot put). If we subtract the uniqueness from 1, we get the communality and it will then tell how much variance is explained by the 3 factors." }, { "code": null, "e": 7210, "s": 6843, "text": "The loadings represent ^L from earlier. I have sorted the data and we can easily see that shot put (SP) and discus (DS) have high loadings relative to the other variables in factor 1, implying thename “arm strength” for this factor. Specifically it means that e.g. shot put has correlation of 0.915 with factor 1 and a smaller correlation with the other two factors." }, { "code": null, "e": 7585, "s": 7210, "text": "We are also interested in “Cumulative var”, the cumulative proportion of variance explained, and it should be a “high” number, where high is subjective. We should probably try fitting 4 factors, as I don’t think that 0.554 is that high and we might be able to do better. The low p-value in the end also rejects the hypothesis that 3 factors are sufficient.The output is now:" }, { "code": null, "e": 8126, "s": 7585, "text": "This looks more promising. 4 factors are sufficient (according to the p-value) and we have succesfully reduced the number of variables from 10 to 4. The interpretation of the factors is subjective, we cannot explicitly name them, but a good guess could be “arm strength”, “leg strength”, “speed/acceleration” and “running endurance” by looking at where the correlation is high for the variables. Javelin and 100m hurdles have high uniqueness and does not fit well into any of the factors. Maybe a little bit in factor 1 and 2, respectively." }, { "code": null, "e": 8319, "s": 8126, "text": "The most important part is finding the number of factors. From here you can play around with estimation and rotation methods and sharpen the focus of the microscope, but it’s not that crucial." }, { "code": null, "e": 8761, "s": 8319, "text": "Johnson and Wichern state that “the vast majority of attempted factor analyses do not yield clearcut results.” (p. 526) There is no guarantee that a factor analysis will lead to a satisfying description of meaningful factors. If you find yourself confused over the results of a factor analysis because it didn’t seem to “work”, there’s a good chance you did nothing wrong and that the factor analysis simply didn’t find anything interesting." }, { "code": null, "e": 9275, "s": 8761, "text": "Also, factor analysis can lead to controversy if you’re trying to measure quantities such as “intelligence”, “compassion” or “potential”. Those quantities are difficult to measure and can they be responsible for events that we know we can measure, such as high SAT scores? Factor analysis cannot answer this. The quality of a factor analysis depends more on a “Wow” criterion, as the quality has not been quantified and if you can say “wow, I understand these factors” the application has probably been a success." }, { "code": null, "e": 9664, "s": 9275, "text": "As I said before, the cumulative variance is a subjective measure and it is hard to know whether 0.621 is good or bad and intuitively, 60% is probably not that good. Either way, if you are able to reduce the dimensions from, say, 50 to 8 (or 10 to 4 in our case), it could help you explore your data better and make it more managable by understanding the covariance between the variables." }, { "code": null, "e": 10018, "s": 9664, "text": "Please keep in mind that this is purely introductory and isn’t supposed to be a conclusion or an exhaustive analysis. Feel free to correct me if I missed something or did something wrong (I probably did). There are a lot of different methods for dealing with multivariate data and there is even more to Factor Analysis than in the scope of this article." } ]
Convert a JSON object to XML format in Java?
A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert a JSONObject into an XML format using org.json.XML class, this provides static methods to convert an XML text into a JSONObject and to convert a JSONObject into an XML text. The XML.toString() method convert a JSON object into a well-formed, element-normal XML string. public static java.lang.String toString(java.lang.Object object) throws JSONException import java.io.*; import org.json.*; public class JSONtoXMLTest { public static void main(String[] args) throws JSONException { String json = "{employee : { age:30, name : Raja, technology:Java}}"; //Convert JSON to XML String xml = convert(json, "root"); // This method converts json object to xml string System.out.println(xml); } public static String convert(String json, String root) throws JSONException { JSONObject jsonObject = new JSONObject(json); String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<"+root+">" + XML.toString(jsonFileObject) + "</"+root+">"; return xml; } } <?xml version="1.0" encoding="ISO-8859-15"?> <root> <employee> <name>Raja</name> <technology>Java</technology> <age>30</age> </employee> </root>
[ { "code": null, "e": 1443, "s": 1062, "text": "A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert a JSONObject into an XML format using org.json.XML class, this provides static methods to convert an XML text into a JSONObject and to convert a JSONObject into an XML text. The XML.toString() method convert a JSON object into a well-formed, element-normal XML string." }, { "code": null, "e": 1529, "s": 1443, "text": "public static java.lang.String toString(java.lang.Object object) throws JSONException" }, { "code": null, "e": 2180, "s": 1529, "text": "import java.io.*;\nimport org.json.*;\npublic class JSONtoXMLTest {\n public static void main(String[] args) throws JSONException {\n String json = \"{employee : { age:30, name : Raja, technology:Java}}\";\n //Convert JSON to XML\n String xml = convert(json, \"root\"); // This method converts json object to xml string\n System.out.println(xml);\n }\n public static String convert(String json, String root) throws JSONException {\n JSONObject jsonObject = new JSONObject(json);\n String xml = \"<?xml version=\\\"1.0\\\" encoding=\\\"ISO-8859-15\\\"?>\\n<\"+root+\">\" + XML.toString(jsonFileObject) + \"</\"+root+\">\";\n return xml;\n }\n}" }, { "code": null, "e": 2349, "s": 2180, "text": "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n<root>\n <employee>\n <name>Raja</name>\n <technology>Java</technology>\n <age>30</age>\n </employee>\n</root>" } ]
Product of maximum in first array and minimum in second | Practice | GeeksforGeeks
Given two arrays of A and B respectively of sizes N1 and N2, the task is to calculate the product of the maximum element of the first array and minimum element of the second array. Example 1: Input : A[] = {5, 7, 9, 3, 6, 2}, B[] = {1, 2, 6, -1, 0, 9} Output : -9 Explanation: The first array is 5 7 9 3 6 2. The max element among these elements is 9. The second array is 1 2 6 -1 0 9. The min element among these elements is -1. The product of 9 and -1 is 9*-1=-9. Example 2: Input : A[] = {0, 0, 0, 0}, B[] = {1, -1, 2} Output : 0 Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function find_multiplication() that takes an array of integer (A), another array of integer (B), size of array A(n), size of array B(m) and return the product of the max element of the first array and the minimum element of the second array. The driver code takes care of the printing. Expected Time Complexity: O(N + M). Expected Auxiliary Space: O(1). Output: For each test case, output the product of the max element of the first array and the minimum element of the second array. Constraints: 1 ≤ N, M ≤ 106 -108 ≤ Ai, Bi ≤ 108 0 visionsameer393 days ago class Solution: def find_multiplication (self, arr, brr, n, m) : arr.sort() brr.sort() a1=arr[-1] b1=brr[0] return a1*b1 +1 harshscode1 week ago long long int ma=INT_MIN,mi=INT_MAX; for(int i=0;i<n;i++) if(a[i]>ma) ma=a[i]; for(int i=0;i<m;i++) if(b[i]<mi) mi=b[i]; return (mi*ma); 0 vinayreddy222vr2 weeks ago a=max(arr) b=min(brr) return a*b 0 mayank180919993 weeks ago long long find_multiplication(int a[], int b[], int n, int m) { // Complete the function sort(a,a+n); sort(b,b+m); return a[n-1]*b[0]; } 0 somawatpravin021 month ago class Solution: def find_multiplication (self, arr, brr, n, m) : #Complete the function arr.sort() brr.sort() return (arr[n-1]*brr[0]) 0 sakesai301 month ago class Solution{ // Function for finding maximum and value pair public static long find_multiplication (int arr[], int brr[], int n, int m) { sort(arr,0,n-1,n-1); sort(brr,0,m-1,0); return arr[n-1]*brr[0]; } static void sort(int[] arr,int lo,int hi,int key){ int pivot = arr[lo]; int lt = lo; int gt = hi; int i = lo; while(i<=gt){ if(arr[i]<pivot){ swap(arr,i,lt); lt++; i++; }else if(arr[i]>pivot){ swap(arr,i,gt); gt--; }else{ i++; } } if(lt>key){ sort(arr,lo,lt-1,key); }else if(gt<key){ sort(arr,gt+1,hi,key); }else{ return; } } static void swap(int[] arr,int lo,int hi){ int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp; } } 0 rahulp00rtx1 month ago Simple JavaScipt, 0.6 class Solution{ find_multiplication(a,n,b,m){ //code here let mx = a[0],mn = b[0]; for(let i = 0; i<n; i++){ if(a[i] > mx) mx = a[i]; } for(let i =0; i<m; i++){ if(b[i] < mn) mn = b[i]; } return mn * mx; }} 0 hasnainraza1998hr1 month ago C++, 0.4 long long find_multiplication(int a[], int b[], int n, int m) { int maxNum = *max_element(a,a+n); int minNum = *min_element(b,b+m); return maxNum*minNum; } 0 kanchanikirankumarreddyPremium2 months ago c++: class Solution{ public: long long find_multiplication(int a[], int b[], int n, int m) { int max=*max_element(a,a+n); int min=*min_element(b,b+m); return min*max; }}; 0 aakasshuit2 months ago //Java Solution Arrays.sort(arr); Arrays.sort(brr); return (arr[n-1]*brr[0]); 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": 419, "s": 238, "text": "Given two arrays of A and B respectively of sizes N1 and N2, the task is to calculate the product of the maximum element of the first array and minimum element of the second array." }, { "code": null, "e": 430, "s": 419, "text": "Example 1:" }, { "code": null, "e": 716, "s": 430, "text": "Input : A[] = {5, 7, 9, 3, 6, 2}, \n B[] = {1, 2, 6, -1, 0, 9}\nOutput : -9\nExplanation:\nThe first array is 5 7 9 3 6 2. \nThe max element among these elements is 9.\nThe second array is 1 2 6 -1 0 9.\nThe min element among these elements is -1.\nThe product of 9 and -1 is 9*-1=-9.\n\n" }, { "code": null, "e": 727, "s": 716, "text": "Example 2:" }, { "code": null, "e": 797, "s": 727, "text": "Input : A[] = {0, 0, 0, 0}, \n B[] = {1, -1, 2}\nOutput : 0\n\n" }, { "code": null, "e": 1207, "s": 797, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function find_multiplication() that takes an array of integer (A), another array of integer (B), size of array A(n), size of array B(m) and return the product of the max element of the first array and the minimum element of the second array. The driver code takes care of the printing." }, { "code": null, "e": 1277, "s": 1207, "text": "Expected Time Complexity: O(N + M).\nExpected Auxiliary Space: O(1).\n " }, { "code": null, "e": 1407, "s": 1277, "text": "Output:\nFor each test case, output the product of the max element of the first array and the minimum element of the second array." }, { "code": null, "e": 1455, "s": 1407, "text": "Constraints:\n1 ≤ N, M ≤ 106\n-108 ≤ Ai, Bi ≤ 108" }, { "code": null, "e": 1457, "s": 1455, "text": "0" }, { "code": null, "e": 1482, "s": 1457, "text": "visionsameer393 days ago" }, { "code": null, "e": 1636, "s": 1482, "text": "class Solution: def find_multiplication (self, arr, brr, n, m) : arr.sort() brr.sort() a1=arr[-1] b1=brr[0] return a1*b1" }, { "code": null, "e": 1639, "s": 1636, "text": "+1" }, { "code": null, "e": 1660, "s": 1639, "text": "harshscode1 week ago" }, { "code": null, "e": 1861, "s": 1660, "text": " long long int ma=INT_MIN,mi=INT_MAX;\n for(int i=0;i<n;i++)\n if(a[i]>ma)\n ma=a[i];\n for(int i=0;i<m;i++)\n if(b[i]<mi)\n mi=b[i];\n return (mi*ma);" }, { "code": null, "e": 1863, "s": 1861, "text": "0" }, { "code": null, "e": 1890, "s": 1863, "text": "vinayreddy222vr2 weeks ago" }, { "code": null, "e": 1936, "s": 1890, "text": "a=max(arr) b=min(brr) return a*b " }, { "code": null, "e": 1938, "s": 1936, "text": "0" }, { "code": null, "e": 1964, "s": 1938, "text": "mayank180919993 weeks ago" }, { "code": null, "e": 2147, "s": 1964, "text": " long long find_multiplication(int a[], int b[], int n, int m)\n {\n // Complete the function\n sort(a,a+n);\n sort(b,b+m);\n return a[n-1]*b[0];\n }" }, { "code": null, "e": 2149, "s": 2147, "text": "0" }, { "code": null, "e": 2176, "s": 2149, "text": "somawatpravin021 month ago" }, { "code": null, "e": 2338, "s": 2176, "text": "class Solution: def find_multiplication (self, arr, brr, n, m) : #Complete the function arr.sort() brr.sort() return (arr[n-1]*brr[0])" }, { "code": null, "e": 2340, "s": 2338, "text": "0" }, { "code": null, "e": 2361, "s": 2340, "text": "sakesai301 month ago" }, { "code": null, "e": 3274, "s": 2361, "text": "class Solution{ // Function for finding maximum and value pair public static long find_multiplication (int arr[], int brr[], int n, int m) { sort(arr,0,n-1,n-1); sort(brr,0,m-1,0); return arr[n-1]*brr[0]; } static void sort(int[] arr,int lo,int hi,int key){ int pivot = arr[lo]; int lt = lo; int gt = hi; int i = lo; while(i<=gt){ if(arr[i]<pivot){ swap(arr,i,lt); lt++; i++; }else if(arr[i]>pivot){ swap(arr,i,gt); gt--; }else{ i++; } } if(lt>key){ sort(arr,lo,lt-1,key); }else if(gt<key){ sort(arr,gt+1,hi,key); }else{ return; } } static void swap(int[] arr,int lo,int hi){ int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp; } }" }, { "code": null, "e": 3276, "s": 3274, "text": "0" }, { "code": null, "e": 3299, "s": 3276, "text": "rahulp00rtx1 month ago" }, { "code": null, "e": 3321, "s": 3299, "text": "Simple JavaScipt, 0.6" }, { "code": null, "e": 3616, "s": 3321, "text": "class Solution{ find_multiplication(a,n,b,m){ //code here let mx = a[0],mn = b[0]; for(let i = 0; i<n; i++){ if(a[i] > mx) mx = a[i]; } for(let i =0; i<m; i++){ if(b[i] < mn) mn = b[i]; } return mn * mx; }} " }, { "code": null, "e": 3618, "s": 3616, "text": "0" }, { "code": null, "e": 3647, "s": 3618, "text": "hasnainraza1998hr1 month ago" }, { "code": null, "e": 3656, "s": 3647, "text": "C++, 0.4" }, { "code": null, "e": 3834, "s": 3656, "text": "long long find_multiplication(int a[], int b[], int n, int m) { int maxNum = *max_element(a,a+n); int minNum = *min_element(b,b+m); return maxNum*minNum; }" }, { "code": null, "e": 3836, "s": 3834, "text": "0" }, { "code": null, "e": 3879, "s": 3836, "text": "kanchanikirankumarreddyPremium2 months ago" }, { "code": null, "e": 3884, "s": 3879, "text": "c++:" }, { "code": null, "e": 4080, "s": 3884, "text": "class Solution{ public: long long find_multiplication(int a[], int b[], int n, int m) { int max=*max_element(a,a+n); int min=*min_element(b,b+m); return min*max; }};" }, { "code": null, "e": 4082, "s": 4080, "text": "0" }, { "code": null, "e": 4105, "s": 4082, "text": "aakasshuit2 months ago" }, { "code": null, "e": 4208, "s": 4105, "text": "//Java Solution\n\n Arrays.sort(arr);\n Arrays.sort(brr);\n return (arr[n-1]*brr[0]);" }, { "code": null, "e": 4354, "s": 4208, "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": 4390, "s": 4354, "text": " Login to access your submissions. " }, { "code": null, "e": 4400, "s": 4390, "text": "\nProblem\n" }, { "code": null, "e": 4410, "s": 4400, "text": "\nContest\n" }, { "code": null, "e": 4473, "s": 4410, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4621, "s": 4473, "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": 4829, "s": 4621, "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": 4935, "s": 4829, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
MFC - Controls Management
In MFC applications, after visually adding a control to your application, if you want to refer to it in your code, you can declare a variable based on, or associated with that control. The MFC library allows you to declare two types of variables for some of the controls used in an application a value or a control variable. One variable is used for the information stored in the control, which is also known as Control Variable/Instance. One variable is used for the information stored in the control, which is also known as Control Variable/Instance. The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable. The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable. A control variable is a variable based on the class that manages the control. For example, a button control is based on the CButton class. To see these concepts in real programming, let us create an MFC dialog based project MFCControlManagement. Once the project is created, you will see the following dialog box in designer window. Step 1 − Delete the TODO line and drag one checkbox and one Edit control as shown in the following snapshot. Change the caption of checkbox to Enable Control. Step 2 − Right-click on the checkbox. Step 3 − Select Add Variable. Step 4 − You can now see the Add Member Variable Wizard. You can select different options on this dialog box. For checkbox, the variable type is CButton. It is selected by default in this dialog box. Similarly, the control ID is also selected by default now we need to select Control in the Category combo box, and type m_enableDisableCheck in the Variable Name edit box and click finish. Step 5 − Similarly, add Control Variable of Edit control with the settings as shown in the following snapshot. Observe the header file of the dialog class. You can see that the new variables have been added now. CButton m_enableDisableCheck; CEdit m_myEditControl; Another type of variable you can declare for a control is the value variable. Not all controls provide a value variable. The value variable must be able to handle the type of value stored in the control it is intended to refer to. The value variable must be able to handle the type of value stored in the control it is intended to refer to. For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable. For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable. Let us look into this type of variable for checkbox and edit control. Step 1 − Right-click on the checkbox and select Add Variable. Step 2 − The Variable type is BOOL. Select Value from the Category dropdown list. Step 3 − Click Finish to continue. Step 4 − Similarly, add value Variable for Edit control with the settings as shown in the following snapshot. Step 5 − Type CString in variable type and m_editControlVal in the variable name field. Step 6 − You can now see these variables added in the Header file. bool m_enableDisableVal; CString m_editControlVal; After adding a control to your application, whether you visually added it or created it dynamically, you will also decide how to handle the possible actions that the user can perform on the control. For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers. For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers. You can quickly create a handler either for the default control notification event or for any applicable Windows message. You can quickly create a handler either for the default control notification event or for any applicable Windows message. Let us look into the same example in which we added event handler for checkbox. Step 1 − Right-click the control for which you want to handle the notification event. Step 2 − On the shortcut menu, click Add Event Handler to display the Event Handler Wizard. Step 3 − Select the event in the Message type box to add to the class selected in the Class list box. Step 4 − Accept the default name in the Function handler name box, or provide the name of your choice. Step 5 − Click Add and edit to add the event handler. Step 6 − You can now see the following event added at the end of CMFCControlManagementDlg.cpp file. void CMFCControlManagementDlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here } So far, we have seen how to add controls to an application. We will now see how to manage these controls as per user requirement. We can use the control variable/instance in a particular event handler. Step 1 − Let us look into the following example. Here, we will enable/disable the edit control when the checkbox is checked/unchecked. Step 2 − We have now added the checkbox click event handler. Here is the implementation − void CMFCControlManagementDlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); } Step 3 − When the dialog is created, we need to add the following code to CMFCControlManagementDlg::OnInitDialog(). This will manage these controls. UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); Step 4 − Here is the complete implementation of CMFCControlManagementDlg.cpp file. // MFCControlManagementDlg.cpp : implementation file // #include "stdafx.h" #include "MFCControlManagement.h" #include "MFCControlManagementDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCControlManagementDlg dialog CMFCControlManagementDlg::CMFCControlManagementDlg(CWnd* pParent /* = NULL*/) :CDialogEx(IDD_MFCCONTROLMANAGEMENT_DIALOG, pParent) , m_enableDisableVal(FALSE) , m_editControlVal(_T("")) { m_hIcon = AfxGetApp()&rarr LoadIcon(IDR_MAINFRAME); } void CMFCControlManagementDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_CHECK1, m_enableDisableCheck); DDX_Control(pDX, IDC_EDIT1, m_myEditControl); DDX_Check(pDX, IDC_CHECK1, m_enableDisableVal); DDX_Text(pDX, IDC_EDIT1, m_editControlVal); } BEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1) END_MESSAGE_MAP() // CMFCControlManagementDlg message handlers BOOL CMFCControlManagementDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu → AppendMenu(MF_SEPARATOR); pSysMenu → AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); return TRUE; // return TRUE unless you set the focus to a control } void CMFCControlManagementDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); }else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCControlManagementDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); }else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCControlManagementDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCControlManagementDlg::OnBnClickedCheck1() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_enableDisableVal) m_myEditControl.EnableWindow(TRUE); else m_myEditControl.EnableWindow(FALSE); } Step 5 − When the above code is compiled and executed, you will see the following output. The checkbox is unchecked by default. This disables the edit control too. Step 6 − Check the Enable Control checkbox. This will automatically enable the edit control. Print Add Notes Bookmark this page
[ { "code": null, "e": 2392, "s": 2067, "text": "In MFC applications, after visually adding a control to your application, if you want to refer to it in your code, you can declare a variable based on, or associated with that control. The MFC library allows you to declare two types of variables for some of the controls used in an application a value or a control variable." }, { "code": null, "e": 2506, "s": 2392, "text": "One variable is used for the information stored in the control, which is also known as Control Variable/Instance." }, { "code": null, "e": 2620, "s": 2506, "text": "One variable is used for the information stored in the control, which is also known as Control Variable/Instance." }, { "code": null, "e": 2751, "s": 2620, "text": "The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable." }, { "code": null, "e": 2882, "s": 2751, "text": "The other variable is known as Control Value Variable. A user can perform some sort of actions on that control with this variable." }, { "code": null, "e": 3021, "s": 2882, "text": "A control variable is a variable based on the class that manages the control. For example, a button control is based on the CButton class." }, { "code": null, "e": 3128, "s": 3021, "text": "To see these concepts in real programming, let us create an MFC dialog based project MFCControlManagement." }, { "code": null, "e": 3215, "s": 3128, "text": "Once the project is created, you will see the following dialog box in designer window." }, { "code": null, "e": 3374, "s": 3215, "text": "Step 1 − Delete the TODO line and drag one checkbox and one Edit control as shown in the following snapshot. Change the caption of checkbox to Enable Control." }, { "code": null, "e": 3412, "s": 3374, "text": "Step 2 − Right-click on the checkbox." }, { "code": null, "e": 3442, "s": 3412, "text": "Step 3 − Select Add Variable." }, { "code": null, "e": 3499, "s": 3442, "text": "Step 4 − You can now see the Add Member Variable Wizard." }, { "code": null, "e": 3642, "s": 3499, "text": "You can select different options on this dialog box. For checkbox, the variable type is CButton. It is selected by default in this dialog box." }, { "code": null, "e": 3831, "s": 3642, "text": "Similarly, the control ID is also selected by default now we need to select Control in the Category combo box, and type m_enableDisableCheck in the Variable Name edit box and click finish." }, { "code": null, "e": 3942, "s": 3831, "text": "Step 5 − Similarly, add Control Variable of Edit control with the settings as shown in the following snapshot." }, { "code": null, "e": 4043, "s": 3942, "text": "Observe the header file of the dialog class. You can see that the new variables have been added now." }, { "code": null, "e": 4096, "s": 4043, "text": "CButton m_enableDisableCheck;\nCEdit m_myEditControl;" }, { "code": null, "e": 4217, "s": 4096, "text": "Another type of variable you can declare for a control is the value variable. Not all controls provide a value variable." }, { "code": null, "e": 4327, "s": 4217, "text": "The value variable must be able to handle the type of value stored in the control it is intended to refer to." }, { "code": null, "e": 4437, "s": 4327, "text": "The value variable must be able to handle the type of value stored in the control it is intended to refer to." }, { "code": null, "e": 4592, "s": 4437, "text": "For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable." }, { "code": null, "e": 4747, "s": 4592, "text": "For example, because a text based control is used to handle text, you can declare a text-based data type for it. This would usually be a CString variable." }, { "code": null, "e": 4817, "s": 4747, "text": "Let us look into this type of variable for checkbox and edit control." }, { "code": null, "e": 4879, "s": 4817, "text": "Step 1 − Right-click on the checkbox and select Add Variable." }, { "code": null, "e": 4961, "s": 4879, "text": "Step 2 − The Variable type is BOOL. Select Value from the Category dropdown list." }, { "code": null, "e": 4996, "s": 4961, "text": "Step 3 − Click Finish to continue." }, { "code": null, "e": 5106, "s": 4996, "text": "Step 4 − Similarly, add value Variable for Edit control with the settings as shown in the following snapshot." }, { "code": null, "e": 5194, "s": 5106, "text": "Step 5 − Type CString in variable type and m_editControlVal in the variable name field." }, { "code": null, "e": 5261, "s": 5194, "text": "Step 6 − You can now see these variables added in the Header file." }, { "code": null, "e": 5312, "s": 5261, "text": "bool m_enableDisableVal;\nCString m_editControlVal;" }, { "code": null, "e": 5511, "s": 5312, "text": "After adding a control to your application, whether you visually added it or created it dynamically, you will also decide how to handle the possible actions that the user can perform on the control." }, { "code": null, "e": 5651, "s": 5511, "text": "For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers." }, { "code": null, "e": 5791, "s": 5651, "text": "For project dialog boxes that are already associated with a class, you can take advantage of some shortcuts when you create event handlers." }, { "code": null, "e": 5913, "s": 5791, "text": "You can quickly create a handler either for the default control notification event or for any applicable Windows message." }, { "code": null, "e": 6035, "s": 5913, "text": "You can quickly create a handler either for the default control notification event or for any applicable Windows message." }, { "code": null, "e": 6115, "s": 6035, "text": "Let us look into the same example in which we added event handler for checkbox." }, { "code": null, "e": 6201, "s": 6115, "text": "Step 1 − Right-click the control for which you want to handle the notification event." }, { "code": null, "e": 6293, "s": 6201, "text": "Step 2 − On the shortcut menu, click Add Event Handler to display the Event Handler Wizard." }, { "code": null, "e": 6395, "s": 6293, "text": "Step 3 − Select the event in the Message type box to add to the class selected in the Class list box." }, { "code": null, "e": 6498, "s": 6395, "text": "Step 4 − Accept the default name in the Function handler name box, or provide the name of your choice." }, { "code": null, "e": 6552, "s": 6498, "text": "Step 5 − Click Add and edit to add the event handler." }, { "code": null, "e": 6652, "s": 6552, "text": "Step 6 − You can now see the following event added at the end of CMFCControlManagementDlg.cpp file." }, { "code": null, "e": 6767, "s": 6652, "text": "void CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n}" }, { "code": null, "e": 6969, "s": 6767, "text": "So far, we have seen how to add controls to an application. We will now see how to manage these controls as per user requirement. We can use the control variable/instance in a particular event handler." }, { "code": null, "e": 7104, "s": 6969, "text": "Step 1 − Let us look into the following example. Here, we will enable/disable the edit control when the checkbox is checked/unchecked." }, { "code": null, "e": 7194, "s": 7104, "text": "Step 2 − We have now added the checkbox click event handler. Here is the implementation −" }, { "code": null, "e": 7450, "s": 7194, "text": "void CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n}" }, { "code": null, "e": 7599, "s": 7450, "text": "Step 3 − When the dialog is created, we need to add the following code to CMFCControlManagementDlg::OnInitDialog(). This will manage these controls." }, { "code": null, "e": 7725, "s": 7599, "text": "UpdateData(TRUE);\nif (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\nelse\n m_myEditControl.EnableWindow(FALSE);" }, { "code": null, "e": 7808, "s": 7725, "text": "Step 4 − Here is the complete implementation of CMFCControlManagementDlg.cpp file." }, { "code": null, "e": 12100, "s": 7808, "text": "// MFCControlManagementDlg.cpp : implementation file\n//\n\n#include \"stdafx.h\"\n#include \"MFCControlManagement.h\"\n#include \"MFCControlManagementDlg.h\"\n#include \"afxdialogex.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\n// CAboutDlg dialog used for App About\n\nclass CAboutDlg : public CDialogEx {\n public:\n CAboutDlg();\n\t\n // Dialog Data\n #ifdef AFX_DESIGN_TIME\n enum { IDD = IDD_ABOUTBOX };\n #endif\n\n protected:\n virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support\n \n // Implementation\n protected:\n DECLARE_MESSAGE_MAP()\n};\n\nCAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {\n\n}\nvoid CAboutDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n}\n\nBEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)\nEND_MESSAGE_MAP()\n\n// CMFCControlManagementDlg dialog\n\n\nCMFCControlManagementDlg::CMFCControlManagementDlg(CWnd* pParent /* = NULL*/)\n :CDialogEx(IDD_MFCCONTROLMANAGEMENT_DIALOG, pParent) , \n m_enableDisableVal(FALSE) , m_editControlVal(_T(\"\")) {\n m_hIcon = AfxGetApp()&rarr LoadIcon(IDR_MAINFRAME);\n}\n\nvoid CMFCControlManagementDlg::DoDataExchange(CDataExchange* pDX) {\n CDialogEx::DoDataExchange(pDX);\n DDX_Control(pDX, IDC_CHECK1, m_enableDisableCheck);\n DDX_Control(pDX, IDC_EDIT1, m_myEditControl);\n DDX_Check(pDX, IDC_CHECK1, m_enableDisableVal);\n DDX_Text(pDX, IDC_EDIT1, m_editControlVal);\n}\nBEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx)\n ON_WM_SYSCOMMAND()\n ON_WM_PAINT()\n ON_WM_QUERYDRAGICON()\n ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1)\nEND_MESSAGE_MAP()\n\n// CMFCControlManagementDlg message handlers\n\nBOOL CMFCControlManagementDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Add \"About...\" menu item to system menu.\n // IDM_ABOUTBOX must be in the system command range.\n ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n ASSERT(IDM_ABOUTBOX < 0xF000);\n \n CMenu* pSysMenu = GetSystemMenu(FALSE);\n if (pSysMenu != NULL) {\n BOOL bNameValid;\n CString strAboutMenu;\n bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n ASSERT(bNameValid);\n if (!strAboutMenu.IsEmpty()) {\n pSysMenu → AppendMenu(MF_SEPARATOR);\n pSysMenu → AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n }\n }\n\t\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}\nvoid CMFCControlManagementDlg::OnSysCommand(UINT nID, LPARAM lParam) {\n if ((nID & 0xFFF0) == IDM_ABOUTBOX) {\n CAboutDlg dlgAbout;\n dlgAbout.DoModal();\n }else {\n CDialogEx::OnSysCommand(nID, lParam);\n }\n}\n\n// If you add a minimize button to your dialog, you will need the code below\n// to draw the icon. For MFC applications using the document/view model,\n// this is automatically done for you by the framework.\n\nvoid CMFCControlManagementDlg::OnPaint() {\n if (IsIconic()) {\n CPaintDC dc(this); // device context for painting\n \n SendMessage(WM_ICONERASEBKGND,\n reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);\n\t\t\t\n // Center icon in client rectangle\n int cxIcon = GetSystemMetrics(SM_CXICON);\n int cyIcon = GetSystemMetrics(SM_CYICON);\n CRect rect;\n GetClientRect(&rect);\n int x = (rect.Width() - cxIcon + 1) / 2;\n int y = (rect.Height() - cyIcon + 1) / 2;\n\t\t\n // Draw the icon\n dc.DrawIcon(x, y, m_hIcon);\n }else {\n CDialogEx::OnPaint();\n }\n}\n\n// The system calls this function to obtain the cursor to display while the user drags\n// the minimized window.\nHCURSOR CMFCControlManagementDlg::OnQueryDragIcon() {\n return static_cast<HCURSOR>(m_hIcon);\n}\n\nvoid CMFCControlManagementDlg::OnBnClickedCheck1() {\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_enableDisableVal)\n m_myEditControl.EnableWindow(TRUE);\n else\n m_myEditControl.EnableWindow(FALSE);\n}" }, { "code": null, "e": 12264, "s": 12100, "text": "Step 5 − When the above code is compiled and executed, you will see the following output. The checkbox is unchecked by default. This disables the edit control too." }, { "code": null, "e": 12357, "s": 12264, "text": "Step 6 − Check the Enable Control checkbox. This will automatically enable the edit control." }, { "code": null, "e": 12364, "s": 12357, "text": " Print" }, { "code": null, "e": 12375, "s": 12364, "text": " Add Notes" } ]
Magic Number | Practice | GeeksforGeeks
A magic number is defined as a number that can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), .... Given the value of n, find the n'th Magic number modulo 109+7. Example 1: Input: n = 1 Output: 5 Explanation: 1'st Magic number is 5. ​Example 2: Input: n = 2 Output: 25 Explanation: 2'nd Magic number is 25. Your Task: You don't need to read input or print anything. Your task is to complete the function nthMagicNo() which takes n input and returns the answer. Expected Time Complexity: O(log n) Expected Auxiliary Space: O(1) Constraints: 1 ≤ n ≤ 105 +1 prasadkandekar5553 months ago Ohhh....! 110037 test cases 0 Panasa Teja10 months ago Panasa Teja Executed in 0.43sec https://uploads.disquscdn.c... 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": 478, "s": 238, "text": "A magic number is defined as a number that can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), ....\nGiven the value of n, find the n'th Magic number modulo 109+7." }, { "code": null, "e": 489, "s": 478, "text": "Example 1:" }, { "code": null, "e": 549, "s": 489, "text": "Input: n = 1\nOutput: 5\nExplanation: 1'st Magic number is 5." }, { "code": null, "e": 564, "s": 549, "text": "​Example 2:" }, { "code": null, "e": 627, "s": 564, "text": "Input: n = 2\nOutput: 25\nExplanation: 2'nd Magic number is 25. " }, { "code": null, "e": 876, "s": 627, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function nthMagicNo() which takes n input and returns the answer.\n\nExpected Time Complexity: O(log n)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ n ≤ 105" }, { "code": null, "e": 879, "s": 876, "text": "+1" }, { "code": null, "e": 909, "s": 879, "text": "prasadkandekar5553 months ago" }, { "code": null, "e": 938, "s": 909, "text": "Ohhh....! 110037 test cases " }, { "code": null, "e": 940, "s": 938, "text": "0" }, { "code": null, "e": 965, "s": 940, "text": "Panasa Teja10 months ago" }, { "code": null, "e": 977, "s": 965, "text": "Panasa Teja" }, { "code": null, "e": 1028, "s": 977, "text": "Executed in 0.43sec https://uploads.disquscdn.c..." }, { "code": null, "e": 1174, "s": 1028, "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": 1210, "s": 1174, "text": " Login to access your submissions. " }, { "code": null, "e": 1220, "s": 1210, "text": "\nProblem\n" }, { "code": null, "e": 1230, "s": 1220, "text": "\nContest\n" }, { "code": null, "e": 1293, "s": 1230, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 1441, "s": 1293, "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": 1649, "s": 1441, "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": 1755, "s": 1649, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to implement Linear Regression with PyTorch | by Dorian Lazar | Towards Data Science
Probably, implementing linear regression with PyTorch is an overkill. This library was made for more complicated stuff like neural networks, complex deep learning architectures, etc. Nevertheless, I think that using it for implementing a simpler machine learning method, like linear regression, is a good exercise for those who want to start learning PyTorch. At its core, PyTorch is just a math library similar to NumPy, but with 2 important improvements: It can use GPU to make its operations a lot faster. If you have a compatible GPU properly configured, you can make the code run on GPU with just a few changes. It is capable of automatic differentiation; this means that for gradient-based methods you don’t need to manually compute the gradient, PyTorch will do it for you. You can think of PyTorch as NumPy on steroids. While these 2 features may not seem like big improvements for what we want to do here (linear regression), since this is not very computationally-expensive and the gradient is quite simple to compute manually, they make a big difference in deep learning where we need a lot of computing power and the gradient is quite nasty to calculate by hand. Before working on the implementation, let’s first briefly recall what linear regression is: Linear regression is estimating an unknown variable in a linear fashion by some other known variables. Visually, we fit a line (or a hyperplane in higher dimensions) through our data points. If you’re not comfortable with this concept or want to understand better the math behind it, you can read my previous article about linear regression: towardsdatascience.com Now, let’s jump to the coding part. Firstly, we need to, obviously, import some libraries. We import torch as it is the main thing we use for the implementation, matplotlib for visualizing our results, make_regression function, from sklearn, which we will be using to generate a regression dataset for using as an example, and the python’s built-in math module. import torchimport matplotlib.pyplot as pltfrom sklearn.datasets import make_regressionimport math Then we will create a LinearRegression class with the following methods: .fit() — this method will do the actual learning of our linear regression model; here we will find the optimal weights .predict() — this one will be used for prediction; it will return the output of our linear model .rmse() — computes the root mean squared error of our model with the given data; this metric is kind of “the average distance from our model’s estimate to the true y value” The first thing we do inside .fit() is to concatenate an extra column of 1’s to our input matrix X. This is to simplify our math and treat the bias as the weight of an extra variable that’s always 1. The .fit() method will be able to learn the parameters by using either closed-form formula or stochastic gradient descent. And to choose which to use, we will have a parameter called method that will expect a string of either ‘solve’ or ‘sgd’. When method is set to ‘solve’ we will get the weights of our model by the following formula: which requires the matrix X to have full column rank; so, we will check for this and otherwise we show an error message. The first part of our .fit() method is: Note that the other parameters after method are optional and are used only in the case we use SGD. The second part of this method handles the case of method = ‘sgd’, which doesn’t require that X has full column rank. The SGD algorithm for our least squares linear regression is sketched below: We will start this algorithm by initializing the weights class attribute to a tensor which is a column vector with values drawn from a normal distribution with mean 0 and standard deviation 1/(number of columns). We divide the standard deviation by the number of columns to make sure we don’t get too big values as output in the initial stages of the algorithm. This is to help us converge faster. At the beginning of each iteration, we randomly shuffle our rows of data. Then, for each batch, we compute the gradient and subtract it (multiplied by the learning rate) from the current weights vector to obtain the new weights. In the SGD algorithm sketched above, we had shown the manually computed gradient; it’s that expression multiplied by alpha (the learning rate). But in the code below we won’t compute that expression explicitly; instead, we compute the loss value: then we let PyTorch compute the gradient for us. Below is the second half of our .fit() method: To compute the gradient of the loss with respect to the weights, we need to call the .requires_grad_(True) method on the self.weights tensor, then we compute the loss according to the formula given above. After the loss is computed, we call .backward() method on the loss tensor which will compute the gradient and store it in the .grad attribute of self.weights. After we do the update, we call .detach() to get a new tensor without any operations recorded on it, so that the next time we compute the gradient we will do so based only on operations in that single iteration. We return self from this method to be able to concatenate the calls of the constructor and .fit() like this: lr = LinearRegression().fit(X, y, ‘solve’). The .predict() method is quite straight-forward. We first check if .fit() was called before, then concatenate a column of 1’s to X and verify that the shape of X allows multiplication with the weights vector. If everything is OK, we simply return the result of the multiplication between X and the weights vector as the predictions. In .rmse() we first get the outputs of the model using .predict(), then if there were no errors during predict, we compute and return the root mean squared error which can be thought of as “the average distance from our model’s estimate to the true y value”. Below is the full code of the LinearRegression class: To show our implementation of linear regression in action, we will generate a regression dataset with the make_regression() function from sklearn. X, y = make_regression(n_features=1, n_informative=1, bias=1, noise=35) Let’s plot this dataset to see how it looks like: plt.scatter(X, y) The y returned by make_regression() is a flat vector. We will reshape it to a column vector to use with our LinearRegression class. y = y.reshape((-1, 1)) Firstly, we will use method = ‘solve’ to fit the regression line: lr_solve = LinearRegression().fit(X, y, method='solve')plt.scatter(X, y)plt.plot(X, lr_solve.predict(X), color='orange') The root mean squared error of the above regression model is: lr_solve.rmse(X, y)# tensor(31.8709, dtype=torch.float64) Then, we also use method = ‘sgd’ and we will let the other parameters have their default values: lr_sgd = LinearRegression().fit(X, y, method='sgd')plt.scatter(X, y)plt.plot(X, lr_sgd.predict(X), color='orange') As you can see, the regression lines in the 2 images above for methods ‘solve’ and ‘sgd’ are almost identical. The root mean squared error we got when using ‘sgd’ is: lr_sgd.rmse(X, y)# tensor(31.9000, dtype=torch.float64) Here is the Jupyter Notebook with all the code: I hope you found this information useful and thanks for reading! This article is also posted on my own website here. Feel free to have a look!
[ { "code": null, "e": 532, "s": 172, "text": "Probably, implementing linear regression with PyTorch is an overkill. This library was made for more complicated stuff like neural networks, complex deep learning architectures, etc. Nevertheless, I think that using it for implementing a simpler machine learning method, like linear regression, is a good exercise for those who want to start learning PyTorch." }, { "code": null, "e": 629, "s": 532, "text": "At its core, PyTorch is just a math library similar to NumPy, but with 2 important improvements:" }, { "code": null, "e": 789, "s": 629, "text": "It can use GPU to make its operations a lot faster. If you have a compatible GPU properly configured, you can make the code run on GPU with just a few changes." }, { "code": null, "e": 953, "s": 789, "text": "It is capable of automatic differentiation; this means that for gradient-based methods you don’t need to manually compute the gradient, PyTorch will do it for you." }, { "code": null, "e": 1000, "s": 953, "text": "You can think of PyTorch as NumPy on steroids." }, { "code": null, "e": 1347, "s": 1000, "text": "While these 2 features may not seem like big improvements for what we want to do here (linear regression), since this is not very computationally-expensive and the gradient is quite simple to compute manually, they make a big difference in deep learning where we need a lot of computing power and the gradient is quite nasty to calculate by hand." }, { "code": null, "e": 1439, "s": 1347, "text": "Before working on the implementation, let’s first briefly recall what linear regression is:" }, { "code": null, "e": 1630, "s": 1439, "text": "Linear regression is estimating an unknown variable in a linear fashion by some other known variables. Visually, we fit a line (or a hyperplane in higher dimensions) through our data points." }, { "code": null, "e": 1781, "s": 1630, "text": "If you’re not comfortable with this concept or want to understand better the math behind it, you can read my previous article about linear regression:" }, { "code": null, "e": 1804, "s": 1781, "text": "towardsdatascience.com" }, { "code": null, "e": 1840, "s": 1804, "text": "Now, let’s jump to the coding part." }, { "code": null, "e": 2166, "s": 1840, "text": "Firstly, we need to, obviously, import some libraries. We import torch as it is the main thing we use for the implementation, matplotlib for visualizing our results, make_regression function, from sklearn, which we will be using to generate a regression dataset for using as an example, and the python’s built-in math module." }, { "code": null, "e": 2265, "s": 2166, "text": "import torchimport matplotlib.pyplot as pltfrom sklearn.datasets import make_regressionimport math" }, { "code": null, "e": 2338, "s": 2265, "text": "Then we will create a LinearRegression class with the following methods:" }, { "code": null, "e": 2457, "s": 2338, "text": ".fit() — this method will do the actual learning of our linear regression model; here we will find the optimal weights" }, { "code": null, "e": 2554, "s": 2457, "text": ".predict() — this one will be used for prediction; it will return the output of our linear model" }, { "code": null, "e": 2727, "s": 2554, "text": ".rmse() — computes the root mean squared error of our model with the given data; this metric is kind of “the average distance from our model’s estimate to the true y value”" }, { "code": null, "e": 2927, "s": 2727, "text": "The first thing we do inside .fit() is to concatenate an extra column of 1’s to our input matrix X. This is to simplify our math and treat the bias as the weight of an extra variable that’s always 1." }, { "code": null, "e": 3171, "s": 2927, "text": "The .fit() method will be able to learn the parameters by using either closed-form formula or stochastic gradient descent. And to choose which to use, we will have a parameter called method that will expect a string of either ‘solve’ or ‘sgd’." }, { "code": null, "e": 3264, "s": 3171, "text": "When method is set to ‘solve’ we will get the weights of our model by the following formula:" }, { "code": null, "e": 3385, "s": 3264, "text": "which requires the matrix X to have full column rank; so, we will check for this and otherwise we show an error message." }, { "code": null, "e": 3425, "s": 3385, "text": "The first part of our .fit() method is:" }, { "code": null, "e": 3524, "s": 3425, "text": "Note that the other parameters after method are optional and are used only in the case we use SGD." }, { "code": null, "e": 3642, "s": 3524, "text": "The second part of this method handles the case of method = ‘sgd’, which doesn’t require that X has full column rank." }, { "code": null, "e": 3719, "s": 3642, "text": "The SGD algorithm for our least squares linear regression is sketched below:" }, { "code": null, "e": 4117, "s": 3719, "text": "We will start this algorithm by initializing the weights class attribute to a tensor which is a column vector with values drawn from a normal distribution with mean 0 and standard deviation 1/(number of columns). We divide the standard deviation by the number of columns to make sure we don’t get too big values as output in the initial stages of the algorithm. This is to help us converge faster." }, { "code": null, "e": 4346, "s": 4117, "text": "At the beginning of each iteration, we randomly shuffle our rows of data. Then, for each batch, we compute the gradient and subtract it (multiplied by the learning rate) from the current weights vector to obtain the new weights." }, { "code": null, "e": 4593, "s": 4346, "text": "In the SGD algorithm sketched above, we had shown the manually computed gradient; it’s that expression multiplied by alpha (the learning rate). But in the code below we won’t compute that expression explicitly; instead, we compute the loss value:" }, { "code": null, "e": 4642, "s": 4593, "text": "then we let PyTorch compute the gradient for us." }, { "code": null, "e": 4689, "s": 4642, "text": "Below is the second half of our .fit() method:" }, { "code": null, "e": 5265, "s": 4689, "text": "To compute the gradient of the loss with respect to the weights, we need to call the .requires_grad_(True) method on the self.weights tensor, then we compute the loss according to the formula given above. After the loss is computed, we call .backward() method on the loss tensor which will compute the gradient and store it in the .grad attribute of self.weights. After we do the update, we call .detach() to get a new tensor without any operations recorded on it, so that the next time we compute the gradient we will do so based only on operations in that single iteration." }, { "code": null, "e": 5418, "s": 5265, "text": "We return self from this method to be able to concatenate the calls of the constructor and .fit() like this: lr = LinearRegression().fit(X, y, ‘solve’)." }, { "code": null, "e": 5751, "s": 5418, "text": "The .predict() method is quite straight-forward. We first check if .fit() was called before, then concatenate a column of 1’s to X and verify that the shape of X allows multiplication with the weights vector. If everything is OK, we simply return the result of the multiplication between X and the weights vector as the predictions." }, { "code": null, "e": 6010, "s": 5751, "text": "In .rmse() we first get the outputs of the model using .predict(), then if there were no errors during predict, we compute and return the root mean squared error which can be thought of as “the average distance from our model’s estimate to the true y value”." }, { "code": null, "e": 6064, "s": 6010, "text": "Below is the full code of the LinearRegression class:" }, { "code": null, "e": 6211, "s": 6064, "text": "To show our implementation of linear regression in action, we will generate a regression dataset with the make_regression() function from sklearn." }, { "code": null, "e": 6305, "s": 6211, "text": "X, y = make_regression(n_features=1, n_informative=1, bias=1, noise=35)" }, { "code": null, "e": 6355, "s": 6305, "text": "Let’s plot this dataset to see how it looks like:" }, { "code": null, "e": 6373, "s": 6355, "text": "plt.scatter(X, y)" }, { "code": null, "e": 6505, "s": 6373, "text": "The y returned by make_regression() is a flat vector. We will reshape it to a column vector to use with our LinearRegression class." }, { "code": null, "e": 6528, "s": 6505, "text": "y = y.reshape((-1, 1))" }, { "code": null, "e": 6594, "s": 6528, "text": "Firstly, we will use method = ‘solve’ to fit the regression line:" }, { "code": null, "e": 6715, "s": 6594, "text": "lr_solve = LinearRegression().fit(X, y, method='solve')plt.scatter(X, y)plt.plot(X, lr_solve.predict(X), color='orange')" }, { "code": null, "e": 6777, "s": 6715, "text": "The root mean squared error of the above regression model is:" }, { "code": null, "e": 6835, "s": 6777, "text": "lr_solve.rmse(X, y)# tensor(31.8709, dtype=torch.float64)" }, { "code": null, "e": 6932, "s": 6835, "text": "Then, we also use method = ‘sgd’ and we will let the other parameters have their default values:" }, { "code": null, "e": 7047, "s": 6932, "text": "lr_sgd = LinearRegression().fit(X, y, method='sgd')plt.scatter(X, y)plt.plot(X, lr_sgd.predict(X), color='orange')" }, { "code": null, "e": 7158, "s": 7047, "text": "As you can see, the regression lines in the 2 images above for methods ‘solve’ and ‘sgd’ are almost identical." }, { "code": null, "e": 7214, "s": 7158, "text": "The root mean squared error we got when using ‘sgd’ is:" }, { "code": null, "e": 7270, "s": 7214, "text": "lr_sgd.rmse(X, y)# tensor(31.9000, dtype=torch.float64)" }, { "code": null, "e": 7318, "s": 7270, "text": "Here is the Jupyter Notebook with all the code:" }, { "code": null, "e": 7383, "s": 7318, "text": "I hope you found this information useful and thanks for reading!" } ]
How to change the width of whisker lines in a boxplot using ggplot2 in R?
In R, by default the whisker lines are as wide as the box of the boxplot but it would be great if we reduce that width or increase it because it will get attention of the viewer in that way. This can be done by using the width argument inside the stat_boxplot function of ggplot2 package. Check out the below example to understand how it works. Consider the below data frame − Live Demo > x<-sample(LETTERS[1:2],20,replace=TRUE) > y<-rpois(20,5) > df<-data.frame(x,y) > df x y 1 B 5 2 B 4 3 A 6 4 A 9 5 B 2 6 B 4 7 B 6 8 B 2 9 B 4 10 B 8 11 B 3 12 A 7 13 B 5 14 A 7 15 A 2 16 B 7 17 B 7 18 A 2 19 B 5 20 B 5 Loading ggplot2 package and creating boxplot − > library(ggplot2) > ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom="errorbar") Creating the boxplot with different whisker lines width − > ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom="errorbar",width=0.05) > ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom="errorbar",width=0.40)
[ { "code": null, "e": 1407, "s": 1062, "text": "In R, by default the whisker lines are as wide as the box of the boxplot but it would be great if we reduce that width or increase it because it will get attention of the viewer in that way. This can be done by using the width argument inside the stat_boxplot function of ggplot2 package. Check out the below example to understand how it works." }, { "code": null, "e": 1439, "s": 1407, "text": "Consider the below data frame −" }, { "code": null, "e": 1449, "s": 1439, "text": "Live Demo" }, { "code": null, "e": 1535, "s": 1449, "text": "> x<-sample(LETTERS[1:2],20,replace=TRUE)\n> y<-rpois(20,5)\n> df<-data.frame(x,y)\n> df" }, { "code": null, "e": 1670, "s": 1535, "text": "x y\n1 B 5\n2 B 4\n3 A 6\n4 A 9\n5 B 2\n6 B 4\n7 B 6\n8 B 2\n9 B 4\n10 B 8\n11 B 3\n12 A 7\n13 B 5\n14 A 7\n15 A 2\n16 B 7\n17 B 7\n18 A 2\n19 B 5\n20 B 5" }, { "code": null, "e": 1717, "s": 1670, "text": "Loading ggplot2 package and creating boxplot −" }, { "code": null, "e": 1803, "s": 1717, "text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom=\"errorbar\")" }, { "code": null, "e": 1861, "s": 1803, "text": "Creating the boxplot with different whisker lines width −" }, { "code": null, "e": 1939, "s": 1861, "text": "> ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom=\"errorbar\",width=0.05)" }, { "code": null, "e": 2017, "s": 1939, "text": "> ggplot(df,aes(x,y))+geom_boxplot()+stat_boxplot(geom=\"errorbar\",width=0.40)" } ]
Difference between stopPropagation vs stopImmediatePropagation in JavaScript - GeeksforGeeks
23 Jan, 2022 An event propagates or bubbles till the window object-level every time a registered event is called. For example, Let us consider a parent div element (“Div Parent”) that contains another child div element (“Div child”), and for both, a click event is registered. If child div is clicked, the event will be fired at all places i.e, at both parent and child objects.StopPropagation() event method: Prevents propagation of any handlers at top-level DOM hierarchy to execute. It stops the click event from bubbling to the parent elements.Example: In this method, after clicking the <div> element 1st event handler will occur after that nothing will happen. If you click the <p> element then the 2nd and 1st event handler will occur because <p> element is inside of <div> element but if you click <span> element only the 3rd event handler will occur, cause StopPropagation() event method stops the event from bubbling to the parent elements. HTML <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("span").click(function(event) { event.stopPropagation(); alert("The span element was clicked."); }); $("p").click(function(event) { alert("The p element was clicked."); }); $("div").click(function() { alert("The div element was clicked."); }); }); </script> <style> div { height: 120px; width: 300px; padding: 10px; margin: 50px; border: 2px solid black; background-color: purple; } p { background-color: orange; } span { background-color: cyan; } </style></head> <body> <center> <div> <h1 style="color:lightgreen;"> GeeskforGeeks </h1> <p> Acomputer Science Portal for Geeks<br> <span>Click on this span element.</span> </p> </div> <p> event.stopPropagation() stops the click event from bubbling to the parent elements. </p> </center></body> </html> Output: Before Clicking the element: After Clicking the <div> element: After Clicking the <p> element: After Clicking the <span> element: StopImmediatePropagation() event method: Prevents both propagation of any other handlers and those at top level DOM hierarchy. It stops the other events which were assigned after this event.Example: The StopImmediatePropagation() event stops the next event. HTML <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("div").click(function(event) { alert("'Event handler 1' executed"); event.stopImmediatePropagation(); }); $("div").click(function(event) { alert("'Event handler 2' executed"); }); $("div").click(function(event) { alert("'Event handler 3' executed"); }); }); </script> <style> div { height: 100px; width: 300px; padding: 10px; margin: 50px; border: 2px solid black; background-color: purple; } </style></head> <body> <center> <div> <h1 style="color:lightgreen;"> GeeskforGeeks </h1> Click on this div element. </div> <p> event.stopImmediatePropagation() stop the second and third event. </p> </center></body> </html> Output: Before Clicking the div element: After clicking the div element: stopPropagation vs stopImmediatePropagation anikaseth98 adnanirshad158 Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n23 Jan, 2022" }, { "code": null, "e": 25849, "s": 24909, "text": "An event propagates or bubbles till the window object-level every time a registered event is called. For example, Let us consider a parent div element (“Div Parent”) that contains another child div element (“Div child”), and for both, a click event is registered. If child div is clicked, the event will be fired at all places i.e, at both parent and child objects.StopPropagation() event method: Prevents propagation of any handlers at top-level DOM hierarchy to execute. It stops the click event from bubbling to the parent elements.Example: In this method, after clicking the <div> element 1st event handler will occur after that nothing will happen. If you click the <p> element then the 2nd and 1st event handler will occur because <p> element is inside of <div> element but if you click <span> element only the 3rd event handler will occur, cause StopPropagation() event method stops the event from bubbling to the parent elements. " }, { "code": null, "e": 25854, "s": 25849, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"span\").click(function(event) { event.stopPropagation(); alert(\"The span element was clicked.\"); }); $(\"p\").click(function(event) { alert(\"The p element was clicked.\"); }); $(\"div\").click(function() { alert(\"The div element was clicked.\"); }); }); </script> <style> div { height: 120px; width: 300px; padding: 10px; margin: 50px; border: 2px solid black; background-color: purple; } p { background-color: orange; } span { background-color: cyan; } </style></head> <body> <center> <div> <h1 style=\"color:lightgreen;\"> GeeskforGeeks </h1> <p> Acomputer Science Portal for Geeks<br> <span>Click on this span element.</span> </p> </div> <p> event.stopPropagation() stops the click event from bubbling to the parent elements. </p> </center></body> </html>", "e": 27221, "s": 25854, "text": null }, { "code": null, "e": 27231, "s": 27221, "text": "Output: " }, { "code": null, "e": 27262, "s": 27231, "text": "Before Clicking the element: " }, { "code": null, "e": 27298, "s": 27262, "text": "After Clicking the <div> element: " }, { "code": null, "e": 27332, "s": 27298, "text": "After Clicking the <p> element: " }, { "code": null, "e": 27371, "s": 27334, "text": "After Clicking the <span> element: " }, { "code": null, "e": 27631, "s": 27371, "text": "StopImmediatePropagation() event method: Prevents both propagation of any other handlers and those at top level DOM hierarchy. It stops the other events which were assigned after this event.Example: The StopImmediatePropagation() event stops the next event. " }, { "code": null, "e": 27636, "s": 27631, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"div\").click(function(event) { alert(\"'Event handler 1' executed\"); event.stopImmediatePropagation(); }); $(\"div\").click(function(event) { alert(\"'Event handler 2' executed\"); }); $(\"div\").click(function(event) { alert(\"'Event handler 3' executed\"); }); }); </script> <style> div { height: 100px; width: 300px; padding: 10px; margin: 50px; border: 2px solid black; background-color: purple; } </style></head> <body> <center> <div> <h1 style=\"color:lightgreen;\"> GeeskforGeeks </h1> Click on this div element. </div> <p> event.stopImmediatePropagation() stop the second and third event. </p> </center></body> </html>", "e": 28794, "s": 27636, "text": null }, { "code": null, "e": 28804, "s": 28794, "text": "Output: " }, { "code": null, "e": 28839, "s": 28804, "text": "Before Clicking the div element: " }, { "code": null, "e": 28873, "s": 28839, "text": "After clicking the div element: " }, { "code": null, "e": 28919, "s": 28873, "text": "stopPropagation vs stopImmediatePropagation " }, { "code": null, "e": 28933, "s": 28921, "text": "anikaseth98" }, { "code": null, "e": 28948, "s": 28933, "text": "adnanirshad158" }, { "code": null, "e": 28955, "s": 28948, "text": "Picked" }, { "code": null, "e": 28966, "s": 28955, "text": "JavaScript" }, { "code": null, "e": 28983, "s": 28966, "text": "Web Technologies" }, { "code": null, "e": 29010, "s": 28983, "text": "Web technologies Questions" }, { "code": null, "e": 29108, "s": 29010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29153, "s": 29108, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29214, "s": 29153, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29286, "s": 29214, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29338, "s": 29286, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29384, "s": 29338, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29426, "s": 29384, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29459, "s": 29426, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29502, "s": 29459, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29547, "s": 29502, "text": "Convert a string to an integer in JavaScript" } ]
How to Count the Number of Vowels in a string using Python?
Declare a string object containing all vowels. >>> vowels='aeiou' Set up a count variable initialize to 0 >>> count=0 Check if each character of input string belong to vowel string. If yes increment the count >>> string='Hello How are you?' >>> for s in string: if s in vowels: count=count+1 In the end display value of count >>> count 7
[ { "code": null, "e": 1109, "s": 1062, "text": "Declare a string object containing all vowels." }, { "code": null, "e": 1128, "s": 1109, "text": ">>> vowels='aeiou'" }, { "code": null, "e": 1168, "s": 1128, "text": "Set up a count variable initialize to 0" }, { "code": null, "e": 1180, "s": 1168, "text": ">>> count=0" }, { "code": null, "e": 1271, "s": 1180, "text": "Check if each character of input string belong to vowel string. If yes increment the count" }, { "code": null, "e": 1366, "s": 1271, "text": ">>> string='Hello How are you?'\n>>> for s in string:\n if s in vowels: count=count+1" }, { "code": null, "e": 1400, "s": 1366, "text": "In the end display value of count" }, { "code": null, "e": 1412, "s": 1400, "text": ">>> count\n7" } ]
Write a Regular Expression to remove all special characters from a JavaScript String?
To remove all special characters from a JavaScript string, you can try to run the following code − <html> <head> <script> var str = "@!Welcome to our website$$"; document.write(str); // Removing Special Characters document.write("<br>"+str.replace(/[^\w\s]/gi, '')); </script> </head> <body> </body> </html>
[ { "code": null, "e": 1161, "s": 1062, "text": "To remove all special characters from a JavaScript string, you can try to run the following code −" }, { "code": null, "e": 1444, "s": 1161, "text": "<html>\n <head>\n <script>\n var str = \"@!Welcome to our website$$\";\n document.write(str);\n \n // Removing Special Characters\n document.write(\"<br>\"+str.replace(/[^\\w\\s]/gi, ''));\n </script>\n </head>\n \n <body>\n </body>\n</html>" } ]
Maximum area of a Rectangle that can be circumscribed about a given Rectangle of size LxW - GeeksforGeeks
27 Apr, 2021 Given a rectangle of dimensions L and W. The task is to find the maximum area of a rectangle that can be circumscribed about a given rectangle with dimensions L and W. Examples: Input: L = 10, W = 10Output: 200 Input: L = 18, W = 12Output: 450 Approach: Let below is the given rectangle EFGH of dimensions L and W. We have to find the area of rectangle ABCD which is circumscribing rectangle EFGH. In the above figure: If then as GCF is right angled triangle. Therefore, => => Similarly, Now, The area of rectangle ABCD is given by: Area = AB * AD Area = (AE + EB)*(AH + HD) .....(1) According to the projection rule: AE = L*sin(X) EB = W*cos(X) AH = L*cos(X) HD = W*sin(X) Substituting the value of the above projections in equation (1) we have: Now to maximize the area, the value of sin(2X) must be maximum i.e., 1. Therefore after substituting sin(2X) as 1 we have, Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find area of rectangle// inscribed another rectangle of// length L and width Wdouble AreaofRectangle(int L, int W){ // Area of rectangle double area = (W + L) * (W + L) / 2; // Return the area return area;} // Driver Codeint main(){ // Given dimensions int L = 18; int W = 12; // Function call cout << AreaofRectangle(L, W); return 0;} // This code is contributed by Princi Singh // Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to find area of rectangle// inscribed another rectangle of// length L and width Wstatic double AreaofRectangle(int L, int W){ // Area of rectangle double area = (W + L) * (W + L) / 2; // Return the area return area;} // Driver Codepublic static void main(String args[]){ // Given dimensions int L = 18; int W = 12; // Function call System.out.println(AreaofRectangle(L, W));}} // This code is contributed by offbeat # Python3 program for the above approach # Function to find area of rectangle# inscribed another rectangle of# length L and width Wdef AreaofRectangle(L, W): # Area of rectangle area =(W + L)*(W + L)/2 # Return the area return area # Driver Codeif __name__ == "__main__": # Given Dimensions L = 18 W = 12 # Function Call print(AreaofRectangle(L, W)) // C# program for the above approachusing System; class GFG{ // Function to find area of rectangle// inscribed another rectangle of// length L and width Wstatic double AreaofRectangle(int L, int W){ // Area of rectangle double area = (W + L) * (W + L) / 2; // Return the area return area;} // Driver Codepublic static void Main(String []args){ // Given dimensions int L = 18; int W = 12; // Function call Console.Write(AreaofRectangle(L, W));}} // This code is contributed by shivanisinghss2110 <script> // JavaScript program for the above approach // Function to find area of rectangle // inscribed another rectangle of // length L and width W function AreaofRectangle(L, W) { // Area of rectangle var area = parseFloat(((W + L) * (W + L)) / 2).toFixed(1); // Return the area return area; } // Driver Code // Given dimensions var L = 18; var W = 12; // Function call document.write(AreaofRectangle(L, W)); </script> 450.0 Time Complexity: O(1) Auxiliary Space: O(1) offbeat shivanisinghss2110 princi singh rdtank area-volume-programs square-rectangle Geometric Greedy Mathematical Strings Strings Greedy Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Equation of circle when three points on the circle are given Program to find slope of a line Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26671, "s": 26643, "text": "\n27 Apr, 2021" }, { "code": null, "e": 26840, "s": 26671, "text": "Given a rectangle of dimensions L and W. The task is to find the maximum area of a rectangle that can be circumscribed about a given rectangle with dimensions L and W. " }, { "code": null, "e": 26850, "s": 26840, "text": "Examples:" }, { "code": null, "e": 26885, "s": 26852, "text": "Input: L = 10, W = 10Output: 200" }, { "code": null, "e": 26918, "s": 26885, "text": "Input: L = 18, W = 12Output: 450" }, { "code": null, "e": 27076, "s": 26920, "text": "Approach: Let below is the given rectangle EFGH of dimensions L and W. We have to find the area of rectangle ABCD which is circumscribing rectangle EFGH. " }, { "code": null, "e": 27213, "s": 27076, "text": "In the above figure: If then as GCF is right angled triangle. Therefore, => => Similarly, Now, The area of rectangle ABCD is given by: " }, { "code": null, "e": 27266, "s": 27213, "text": "Area = AB * AD Area = (AE + EB)*(AH + HD) .....(1) " }, { "code": null, "e": 27360, "s": 27268, "text": "According to the projection rule: AE = L*sin(X) EB = W*cos(X) AH = L*cos(X) HD = W*sin(X) " }, { "code": null, "e": 27435, "s": 27360, "text": "Substituting the value of the above projections in equation (1) we have: " }, { "code": null, "e": 27560, "s": 27435, "text": "Now to maximize the area, the value of sin(2X) must be maximum i.e., 1. Therefore after substituting sin(2X) as 1 we have, " }, { "code": null, "e": 27613, "s": 27560, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27617, "s": 27613, "text": "C++" }, { "code": null, "e": 27622, "s": 27617, "text": "Java" }, { "code": null, "e": 27630, "s": 27622, "text": "Python3" }, { "code": null, "e": 27633, "s": 27630, "text": "C#" }, { "code": null, "e": 27644, "s": 27633, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find area of rectangle// inscribed another rectangle of// length L and width Wdouble AreaofRectangle(int L, int W){ // Area of rectangle double area = (W + L) * (W + L) / 2; // Return the area return area;} // Driver Codeint main(){ // Given dimensions int L = 18; int W = 12; // Function call cout << AreaofRectangle(L, W); return 0;} // This code is contributed by Princi Singh", "e": 28171, "s": 27644, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to find area of rectangle// inscribed another rectangle of// length L and width Wstatic double AreaofRectangle(int L, int W){ // Area of rectangle double area = (W + L) * (W + L) / 2; // Return the area return area;} // Driver Codepublic static void main(String args[]){ // Given dimensions int L = 18; int W = 12; // Function call System.out.println(AreaofRectangle(L, W));}} // This code is contributed by offbeat", "e": 28740, "s": 28171, "text": null }, { "code": "# Python3 program for the above approach # Function to find area of rectangle# inscribed another rectangle of# length L and width Wdef AreaofRectangle(L, W): # Area of rectangle area =(W + L)*(W + L)/2 # Return the area return area # Driver Codeif __name__ == \"__main__\": # Given Dimensions L = 18 W = 12 # Function Call print(AreaofRectangle(L, W))", "e": 29103, "s": 28740, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find area of rectangle// inscribed another rectangle of// length L and width Wstatic double AreaofRectangle(int L, int W){ // Area of rectangle double area = (W + L) * (W + L) / 2; // Return the area return area;} // Driver Codepublic static void Main(String []args){ // Given dimensions int L = 18; int W = 12; // Function call Console.Write(AreaofRectangle(L, W));}} // This code is contributed by shivanisinghss2110", "e": 29653, "s": 29103, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find area of rectangle // inscribed another rectangle of // length L and width W function AreaofRectangle(L, W) { // Area of rectangle var area = parseFloat(((W + L) * (W + L)) / 2).toFixed(1); // Return the area return area; } // Driver Code // Given dimensions var L = 18; var W = 12; // Function call document.write(AreaofRectangle(L, W)); </script>", "e": 30170, "s": 29653, "text": null }, { "code": null, "e": 30176, "s": 30170, "text": "450.0" }, { "code": null, "e": 30223, "s": 30178, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 30231, "s": 30223, "text": "offbeat" }, { "code": null, "e": 30250, "s": 30231, "text": "shivanisinghss2110" }, { "code": null, "e": 30263, "s": 30250, "text": "princi singh" }, { "code": null, "e": 30270, "s": 30263, "text": "rdtank" }, { "code": null, "e": 30291, "s": 30270, "text": "area-volume-programs" }, { "code": null, "e": 30308, "s": 30291, "text": "square-rectangle" }, { "code": null, "e": 30318, "s": 30308, "text": "Geometric" }, { "code": null, "e": 30325, "s": 30318, "text": "Greedy" }, { "code": null, "e": 30338, "s": 30325, "text": "Mathematical" }, { "code": null, "e": 30346, "s": 30338, "text": "Strings" }, { "code": null, "e": 30354, "s": 30346, "text": "Strings" }, { "code": null, "e": 30361, "s": 30354, "text": "Greedy" }, { "code": null, "e": 30374, "s": 30361, "text": "Mathematical" }, { "code": null, "e": 30384, "s": 30374, "text": "Geometric" }, { "code": null, "e": 30482, "s": 30384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30548, "s": 30482, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 30609, "s": 30548, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 30641, "s": 30609, "text": "Program to find slope of a line" }, { "code": null, "e": 30687, "s": 30641, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 30757, "s": 30687, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 30808, "s": 30757, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 30866, "s": 30808, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 30917, "s": 30866, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 30944, "s": 30917, "text": "Program for array rotation" } ]
How to use .data files from UCI. Don’t be frightened by the .data... | by Jacob Toftgaard Rasmussen | Towards Data Science
You will learn how to use the data sets from UCI that come with the .data file type in this quick article. Kaggle.com is a great choice for finding data to use in your data science projects. The site is filled with interesting data sets, notebooks from other scientists and tutorials. All the data sets I have encountered on Kaggle have been .csv files, this is very convenient when working with pandas. You might wonder (at least I did) if Kaggle is the only place where data can be found. Hint: It is not! You will also find awesome data sets on UCI Machine Learning Repository. An example of an interesting data set is the Breast Cancer Wisconsin (Original) Data Set. I recently wanted to use this exact data set to practice my classification skills. However, I quickly ran into some trouble (or so I thought). The data I had downloaded was contained in a .data file... How do you work with that?I certainly didn’t know. As I have only ever worked with .csv files (I am a relatively new data scientist) all I know how to do is use the pandas read_csv() function to import my data sets into a DataFrame. To download the data first click on the Data Folder which well take you to a second page (lower half of the following picture), here you click on the file you want to download. The .data file can be opened with Microsoft Excel or Notepad. I tried doing the latter: You can see that all the data points are separated with a comma! Naturally I tried to implement the data in Google Colab. I was very curious as to whether it would work or not. As you can see there is no problem with using read_csv() to read the data into a DataFrame. This really shows how powerful Pandas are I think! There is just one small thing missing I think. The column names. So lets add those. Scroll down a bit on the page of a data set on UCI, and you will find the Attribute information. This provides the names for the features in the corresponding data set. Now we can add those to our DataFrame. You add column names to your DataFrame with the .columns property on the DataFrame. Take a look: Here is all the code from Google Colab if you want to try it yourself (you will have to download the data from UCI and upload it to the Colab document): import pandas as pddataset = pd.read_csv('breast-cancer-wisconsin.data')dataset.columns = ['Id', 'Clump_thickness', 'Uniformity_cell_size', 'Uniformity_cell_shape', 'Marginal_adhesion', 'Single_e_cell_size', 'Bare_nuclei', 'Bland_chromatin', 'Normal_nucleoli', 'Mitoses', 'Class']dataset.head() Did you know?The .data file type is actually a text file. It is used by a data mining software called analysis studio, however, the program is no longer being developed (source: Fileinfo, visited 15–08–2020). I hope this short article was useful to you. I am happy that I now know that I can use .data files from UCI without a problem! Keep learning! — Jacob Toftgaard Rasmussen
[ { "code": null, "e": 279, "s": 172, "text": "You will learn how to use the data sets from UCI that come with the .data file type in this quick article." }, { "code": null, "e": 576, "s": 279, "text": "Kaggle.com is a great choice for finding data to use in your data science projects. The site is filled with interesting data sets, notebooks from other scientists and tutorials. All the data sets I have encountered on Kaggle have been .csv files, this is very convenient when working with pandas." }, { "code": null, "e": 663, "s": 576, "text": "You might wonder (at least I did) if Kaggle is the only place where data can be found." }, { "code": null, "e": 680, "s": 663, "text": "Hint: It is not!" }, { "code": null, "e": 843, "s": 680, "text": "You will also find awesome data sets on UCI Machine Learning Repository. An example of an interesting data set is the Breast Cancer Wisconsin (Original) Data Set." }, { "code": null, "e": 1045, "s": 843, "text": "I recently wanted to use this exact data set to practice my classification skills. However, I quickly ran into some trouble (or so I thought). The data I had downloaded was contained in a .data file..." }, { "code": null, "e": 1096, "s": 1045, "text": "How do you work with that?I certainly didn’t know." }, { "code": null, "e": 1278, "s": 1096, "text": "As I have only ever worked with .csv files (I am a relatively new data scientist) all I know how to do is use the pandas read_csv() function to import my data sets into a DataFrame." }, { "code": null, "e": 1455, "s": 1278, "text": "To download the data first click on the Data Folder which well take you to a second page (lower half of the following picture), here you click on the file you want to download." }, { "code": null, "e": 1543, "s": 1455, "text": "The .data file can be opened with Microsoft Excel or Notepad. I tried doing the latter:" }, { "code": null, "e": 1608, "s": 1543, "text": "You can see that all the data points are separated with a comma!" }, { "code": null, "e": 1720, "s": 1608, "text": "Naturally I tried to implement the data in Google Colab. I was very curious as to whether it would work or not." }, { "code": null, "e": 1812, "s": 1720, "text": "As you can see there is no problem with using read_csv() to read the data into a DataFrame." }, { "code": null, "e": 1863, "s": 1812, "text": "This really shows how powerful Pandas are I think!" }, { "code": null, "e": 1947, "s": 1863, "text": "There is just one small thing missing I think. The column names. So lets add those." }, { "code": null, "e": 2155, "s": 1947, "text": "Scroll down a bit on the page of a data set on UCI, and you will find the Attribute information. This provides the names for the features in the corresponding data set. Now we can add those to our DataFrame." }, { "code": null, "e": 2252, "s": 2155, "text": "You add column names to your DataFrame with the .columns property on the DataFrame. Take a look:" }, { "code": null, "e": 2405, "s": 2252, "text": "Here is all the code from Google Colab if you want to try it yourself (you will have to download the data from UCI and upload it to the Colab document):" }, { "code": null, "e": 2700, "s": 2405, "text": "import pandas as pddataset = pd.read_csv('breast-cancer-wisconsin.data')dataset.columns = ['Id', 'Clump_thickness', 'Uniformity_cell_size', 'Uniformity_cell_shape', 'Marginal_adhesion', 'Single_e_cell_size', 'Bare_nuclei', 'Bland_chromatin', 'Normal_nucleoli', 'Mitoses', 'Class']dataset.head()" }, { "code": null, "e": 2909, "s": 2700, "text": "Did you know?The .data file type is actually a text file. It is used by a data mining software called analysis studio, however, the program is no longer being developed (source: Fileinfo, visited 15–08–2020)." }, { "code": null, "e": 3036, "s": 2909, "text": "I hope this short article was useful to you. I am happy that I now know that I can use .data files from UCI without a problem!" } ]
What are the modes a file can be opened using Python?
Files in python can be opened in the following modes. These modes can be used in combinations and need to be passed as the second argument when opening a file. If you don't specify a mode, files are opened in readonly text mode. f = open("test.txt") # Equivalent to rt or race f = open("test.txt", 'w') # Write in text mode f = open("test.bmp", 'r+b') # Read/write in binary mode f = open("test.txt", 'a') # Append mode
[ { "code": null, "e": 1116, "s": 1062, "text": "Files in python can be opened in the following modes." }, { "code": null, "e": 1293, "s": 1118, "text": "These modes can be used in combinations and need to be passed as the second argument when opening a file. If you don't specify a mode, files are opened in readonly text mode." }, { "code": null, "e": 1484, "s": 1293, "text": "f = open(\"test.txt\") # Equivalent to rt or race\nf = open(\"test.txt\", 'w') # Write in text mode\nf = open(\"test.bmp\", 'r+b') # Read/write in binary mode\nf = open(\"test.txt\", 'a') # Append mode" } ]
JavaScript TypeError - Setting getter-only property "x" - GeeksforGeeks
18 Aug, 2020 This JavaScript exception setting getter-only property works in strict-mode only and occurs if the user tries to set a new value to a property for which only a getter is specified. Message: TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: setting getter-only property "x" (Firefox) TypeError: Cannot set property "prop" of #<Object> which has only a getter (Chrome) Error Type: TypeError Cause of the Error: The user is trying to set a new value to a property for which only a getter is defined. Example 1: In this example, the getter method is defined for the object. Property can not be accessed directly. HTML <script>"use strict";function GFG_Fun() { var temp = null; Object.defineProperty(this, 'temp', { get: function() { return temp; } });}var obj = new GFG_Fun(); obj.temp;obj.temp = 100; // Error here</script> Output: TypeError: Cannot set property temp of #<GFG_Fun> which has only a getter Example 2: In this example, the getter method is defined for the object ‘Person’. Property ‘Age’can not be accessed directly. HTML <script>"use strict";function Person(ageP) { var age = ageP; Object.defineProperty(this, 'age', { get: function() { return age; } });}var p = new Person(22);p.age = 30; // TypeError</script> Output: TypeError: Cannot set property age of #<Person> which has only a getter JavaScript-Errors JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? 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": 24909, "s": 24881, "text": "\n18 Aug, 2020" }, { "code": null, "e": 25090, "s": 24909, "text": "This JavaScript exception setting getter-only property works in strict-mode only and occurs if the user tries to set a new value to a property for which only a getter is specified." }, { "code": null, "e": 25099, "s": 25090, "text": "Message:" }, { "code": null, "e": 25346, "s": 25099, "text": "TypeError: Assignment to read-only properties is \n not allowed in strict mode (Edge)\nTypeError: setting getter-only property \"x\" (Firefox)\nTypeError: Cannot set property \"prop\" of #<Object> \n which has only a getter (Chrome)\n\n" }, { "code": null, "e": 25358, "s": 25346, "text": "Error Type:" }, { "code": null, "e": 25369, "s": 25358, "text": "TypeError\n" }, { "code": null, "e": 25477, "s": 25369, "text": "Cause of the Error: The user is trying to set a new value to a property for which only a getter is defined." }, { "code": null, "e": 25589, "s": 25477, "text": "Example 1: In this example, the getter method is defined for the object. Property can not be accessed directly." }, { "code": null, "e": 25594, "s": 25589, "text": "HTML" }, { "code": "<script>\"use strict\";function GFG_Fun() { var temp = null; Object.defineProperty(this, 'temp', { get: function() { return temp; } });}var obj = new GFG_Fun(); obj.temp;obj.temp = 100; // Error here</script>", "e": 25819, "s": 25594, "text": null }, { "code": null, "e": 25827, "s": 25819, "text": "Output:" }, { "code": null, "e": 25903, "s": 25827, "text": "TypeError: Cannot set property temp of \n#<GFG_Fun> which has only a getter\n" }, { "code": null, "e": 26029, "s": 25903, "text": "Example 2: In this example, the getter method is defined for the object ‘Person’. Property ‘Age’can not be accessed directly." }, { "code": null, "e": 26034, "s": 26029, "text": "HTML" }, { "code": "<script>\"use strict\";function Person(ageP) { var age = ageP; Object.defineProperty(this, 'age', { get: function() { return age; } });}var p = new Person(22);p.age = 30; // TypeError</script>", "e": 26244, "s": 26034, "text": null }, { "code": null, "e": 26252, "s": 26244, "text": "Output:" }, { "code": null, "e": 26326, "s": 26252, "text": "TypeError: Cannot set property age of \n#<Person> which has only a getter\n" }, { "code": null, "e": 26344, "s": 26326, "text": "JavaScript-Errors" }, { "code": null, "e": 26355, "s": 26344, "text": "JavaScript" }, { "code": null, "e": 26372, "s": 26355, "text": "Web Technologies" }, { "code": null, "e": 26470, "s": 26372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26479, "s": 26470, "text": "Comments" }, { "code": null, "e": 26492, "s": 26479, "text": "Old Comments" }, { "code": null, "e": 26553, "s": 26492, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26594, "s": 26553, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26648, "s": 26594, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26688, "s": 26648, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26750, "s": 26688, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 26806, "s": 26750, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26839, "s": 26806, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26901, "s": 26839, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26944, "s": 26901, "text": "How to fetch data from an API in ReactJS ?" } ]
DateTime.IsDaylightSavingTime() Method in C# - GeeksforGeeks
06 Feb, 2019 This method is used to indicate whether this instance of DateTime is within the daylight saving time range for the current time zone. Syntax: public bool IsDaylightSavingTime (); Return Value: This method returns true if the value of the Kind property is Local or Unspecified and the value of this instance of DateTime is within the daylight saving time range for the local time zone and false if Kind is Utc. Below programs illustrate the use of DateTime.IsDaylightSavingTime() Method: Example 1: // C# program to demonstrate the// DateTime.IsDaylightSavingTime()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting Typecode of date // using IsDaylightSavingTime() method; bool value = date.IsDaylightSavingTime(); // checking the condition if (value) Console.WriteLine("Instance of DateTime is within the" + " daylight saving time range for"+ " the current time zone."); else Console.WriteLine("Instance of DateTime is not within the" + " daylight saving time range for the "+ "current time zone."); }} Instance of DateTime is not within the daylight saving time range for the current time zone. Example 2: // C# program to demonstrate the// DateTime.IsDaylightSavingTime()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(1970, 1, 1, 4, 0, 15); // getting Typecode of date // using IsDaylightSavingTime() method; bool value = date.IsDaylightSavingTime(); // checking the condition if (value) Console.WriteLine("Instance of DateTime is within the" + " daylight saving time range for "+ "the current time zone."); else Console.WriteLine("Instance of DateTime is not within the" + " daylight saving time range for the "+ "current time zone."); }} Instance of DateTime is not within the daylight saving time range for the current time zone. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.isdaylightsavingtime?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n06 Feb, 2019" }, { "code": null, "e": 24045, "s": 23911, "text": "This method is used to indicate whether this instance of DateTime is within the daylight saving time range for the current time zone." }, { "code": null, "e": 24090, "s": 24045, "text": "Syntax: public bool IsDaylightSavingTime ();" }, { "code": null, "e": 24321, "s": 24090, "text": "Return Value: This method returns true if the value of the Kind property is Local or Unspecified and the value of this instance of DateTime is within the daylight saving time range for the local time zone and false if Kind is Utc." }, { "code": null, "e": 24398, "s": 24321, "text": "Below programs illustrate the use of DateTime.IsDaylightSavingTime() Method:" }, { "code": null, "e": 24409, "s": 24398, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.IsDaylightSavingTime()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting Typecode of date // using IsDaylightSavingTime() method; bool value = date.IsDaylightSavingTime(); // checking the condition if (value) Console.WriteLine(\"Instance of DateTime is within the\" + \" daylight saving time range for\"+ \" the current time zone.\"); else Console.WriteLine(\"Instance of DateTime is not within the\" + \" daylight saving time range for the \"+ \"current time zone.\"); }}", "e": 25341, "s": 24409, "text": null }, { "code": null, "e": 25434, "s": 25341, "text": "Instance of DateTime is not within the daylight saving time range for the current time zone." }, { "code": null, "e": 25445, "s": 25434, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// DateTime.IsDaylightSavingTime()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(1970, 1, 1, 4, 0, 15); // getting Typecode of date // using IsDaylightSavingTime() method; bool value = date.IsDaylightSavingTime(); // checking the condition if (value) Console.WriteLine(\"Instance of DateTime is within the\" + \" daylight saving time range for \"+ \"the current time zone.\"); else Console.WriteLine(\"Instance of DateTime is not within the\" + \" daylight saving time range for the \"+ \"current time zone.\"); }}", "e": 26377, "s": 25445, "text": null }, { "code": null, "e": 26470, "s": 26377, "text": "Instance of DateTime is not within the daylight saving time range for the current time zone." }, { "code": null, "e": 26481, "s": 26470, "text": "Reference:" }, { "code": null, "e": 26586, "s": 26481, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.isdaylightsavingtime?view=netframework-4.7.2" }, { "code": null, "e": 26609, "s": 26586, "text": "CSharp DateTime Struct" }, { "code": null, "e": 26623, "s": 26609, "text": "CSharp-method" }, { "code": null, "e": 26626, "s": 26623, "text": "C#" }, { "code": null, "e": 26724, "s": 26626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26733, "s": 26724, "text": "Comments" }, { "code": null, "e": 26746, "s": 26733, "text": "Old Comments" }, { "code": null, "e": 26786, "s": 26746, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26809, "s": 26786, "text": "Extension Method in C#" }, { "code": null, "e": 26837, "s": 26809, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26859, "s": 26837, "text": "Partial Classes in C#" }, { "code": null, "e": 26876, "s": 26859, "text": "C# | Inheritance" }, { "code": null, "e": 26916, "s": 26876, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26949, "s": 26916, "text": "Linked List Implementation in C#" }, { "code": null, "e": 26992, "s": 26949, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27008, "s": 26992, "text": "C# | List Class" } ]
How to quickly swap two arrays of same size in C++? - GeeksforGeeks
28 May, 2017 Given two arrays a[] and b[] of same size, we need to swap their contents. Example : Input : a[] = {1, 2, 3, 4} b[] = {5, 6, 7, 8} Output : a[] = {5, 6, 7, 8} b[] = {1, 2, 3, 4} A simple solution is to iterate over elements of both arrays and swap them one by one. A quick solution is to use std::swap(). It can directly swap arrays if they are of same size. // Illustrating the use of swap function// to swap two arrays#include <iostream>#include <utility>using namespace std; // Driver Programint main (){ int a[] = {1, 2, 3, 4}; int b[] = {5, 6, 7, 8}; int n = sizeof(a)/sizeof(a[0]); swap(a, b); cout << "a[] = "; for (int i=0; i<n; i++) cout << a[i] << ", "; cout << "\nb[] = "; for (int i=0; i<n; i++) cout << b[i] << ", "; return 0;} Output : a[] = 5, 6, 7, 8, b[] = 1, 2, 3, 4, This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Inline Functions in C++ Exception Handling in C++ Destructors in C++ new and delete operators in C++ for dynamic memory std::string class in C++ Sorting a vector in C++
[ { "code": null, "e": 24043, "s": 24015, "text": "\n28 May, 2017" }, { "code": null, "e": 24118, "s": 24043, "text": "Given two arrays a[] and b[] of same size, we need to swap their contents." }, { "code": null, "e": 24128, "s": 24118, "text": "Example :" }, { "code": null, "e": 24239, "s": 24128, "text": "Input : a[] = {1, 2, 3, 4}\n b[] = {5, 6, 7, 8}\nOutput : a[] = {5, 6, 7, 8}\n b[] = {1, 2, 3, 4}\n" }, { "code": null, "e": 24326, "s": 24239, "text": "A simple solution is to iterate over elements of both arrays and swap them one by one." }, { "code": null, "e": 24420, "s": 24326, "text": "A quick solution is to use std::swap(). It can directly swap arrays if they are of same size." }, { "code": "// Illustrating the use of swap function// to swap two arrays#include <iostream>#include <utility>using namespace std; // Driver Programint main (){ int a[] = {1, 2, 3, 4}; int b[] = {5, 6, 7, 8}; int n = sizeof(a)/sizeof(a[0]); swap(a, b); cout << \"a[] = \"; for (int i=0; i<n; i++) cout << a[i] << \", \"; cout << \"\\nb[] = \"; for (int i=0; i<n; i++) cout << b[i] << \", \"; return 0;}", "e": 24852, "s": 24420, "text": null }, { "code": null, "e": 24861, "s": 24852, "text": "Output :" }, { "code": null, "e": 24898, "s": 24861, "text": "a[] = 5, 6, 7, 8, \nb[] = 1, 2, 3, 4," }, { "code": null, "e": 25201, "s": 24898, "text": "This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 25326, "s": 25201, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25330, "s": 25326, "text": "C++" }, { "code": null, "e": 25334, "s": 25330, "text": "CPP" }, { "code": null, "e": 25432, "s": 25334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25441, "s": 25432, "text": "Comments" }, { "code": null, "e": 25454, "s": 25441, "text": "Old Comments" }, { "code": null, "e": 25475, "s": 25454, "text": "Iterators in C++ STL" }, { "code": null, "e": 25503, "s": 25475, "text": "Operator Overloading in C++" }, { "code": null, "e": 25523, "s": 25503, "text": "Polymorphism in C++" }, { "code": null, "e": 25556, "s": 25523, "text": "Friend class and function in C++" }, { "code": null, "e": 25580, "s": 25556, "text": "Inline Functions in C++" }, { "code": null, "e": 25606, "s": 25580, "text": "Exception Handling in C++" }, { "code": null, "e": 25625, "s": 25606, "text": "Destructors in C++" }, { "code": null, "e": 25676, "s": 25625, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 25701, "s": 25676, "text": "std::string class in C++" } ]
Python eval() built-in-function. Let us understand the eval()... | by Tanu N Prabhu | Towards Data Science
Let us understand the eval() built-in-function in python. This would be a short article about eval function in python, wherein I would be explaining to you about eval function, its syntax, and few questions that are often asked in interviews so that you clearly understand it and answer those questions in ease. To get the full code, click on my GitHub repository down below: github.com Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer. The syntax of the eval function is as shown below: eval(expression, [globals[, locals]]) The arguments or parameters of eval function are strings, also optionally global and locals can be used as an argument inside eval function, but the globals must be represented as a dictionary and the locals as a mapped object. The return value would be the result of the evaluated expression. Often the return type would be an integer. Eval function is mostly used in situations or applications which need to evaluate mathematical expressions. Also if the user wants to evaluate the string into code then can use eval function, because eval function evaluates the string expression and returns the integer as a result. Now you all know the input() takes the user input, but when the user enters an integer as an input the input function returns a string, but in the case of eval it will evaluate the returned value from a string to an integer. I know most of you are confused, let me clear your confusion by giving an example: input = input("Enter any number of your choice:")print(input)print(type(input))--------------------------------------------------------------------Enter any number of your choice: 10 + 10 10 + 10 <class 'str'> See like I said I entered an integer 10+ 10 where I was expecting a result of 20 (10 + 10) but the input method returned a string of the same input entered. eval = eval(input("Enter any number of your choice"))print(eval)print(type(eval))--------------------------------------------------------------------Enter any number of your choice: 10 + 10 20 <class 'int'> In the case of eval, it returned the evaluated expression 20 in the form of an integer given the string as input. 10 + 10 is an expression that returns 20 as a result. Yes, we can perform mathematical operations using eval function as seen below: evaluate = input(“Enter what operation x has to perform: “)print(evaluate)print(type(evaluate))--------------------------------------------------------------------Enter what operation x has to perform: x + x + 100 - 35 + 5 * 80 x + x + 100 - 35 + 5 * 80 <class 'str'>x = 10print(type(x))--------------------------------------------------------------------<class 'int'>expression = eval(evaluate)print(expression)print(type(expression))--------------------------------------------------------------------485 <class 'int'> See like I said if you give the input as a string and eval function evaluates the expression and returns the result as an integer. This is all you need to know to get you started with eval function in python, now you know all the answers for the above questions. The same questions might not be asked all the time, the point is to know the concepts better, then you can answer any questions. If you want to spend some time reading through some material regarding the eval function, I recommend you guys to read the documentation of eval function shown below: docs.python.org Thank you guys, this is the end of the article like I said this is a small article. If you guys have some doubts or if you are stuck with something, please let me know in the comment sections below, I will definitely answer all your questions. Alright time to say goodbye, have a wonderful day.
[ { "code": null, "e": 230, "s": 172, "text": "Let us understand the eval() built-in-function in python." }, { "code": null, "e": 548, "s": 230, "text": "This would be a short article about eval function in python, wherein I would be explaining to you about eval function, its syntax, and few questions that are often asked in interviews so that you clearly understand it and answer those questions in ease. To get the full code, click on my GitHub repository down below:" }, { "code": null, "e": 559, "s": 548, "text": "github.com" }, { "code": null, "e": 819, "s": 559, "text": "Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer." }, { "code": null, "e": 870, "s": 819, "text": "The syntax of the eval function is as shown below:" }, { "code": null, "e": 908, "s": 870, "text": "eval(expression, [globals[, locals]])" }, { "code": null, "e": 1136, "s": 908, "text": "The arguments or parameters of eval function are strings, also optionally global and locals can be used as an argument inside eval function, but the globals must be represented as a dictionary and the locals as a mapped object." }, { "code": null, "e": 1245, "s": 1136, "text": "The return value would be the result of the evaluated expression. Often the return type would be an integer." }, { "code": null, "e": 1528, "s": 1245, "text": "Eval function is mostly used in situations or applications which need to evaluate mathematical expressions. Also if the user wants to evaluate the string into code then can use eval function, because eval function evaluates the string expression and returns the integer as a result." }, { "code": null, "e": 1836, "s": 1528, "text": "Now you all know the input() takes the user input, but when the user enters an integer as an input the input function returns a string, but in the case of eval it will evaluate the returned value from a string to an integer. I know most of you are confused, let me clear your confusion by giving an example:" }, { "code": null, "e": 2046, "s": 1836, "text": "input = input(\"Enter any number of your choice:\")print(input)print(type(input))--------------------------------------------------------------------Enter any number of your choice: 10 + 10 10 + 10 <class 'str'>" }, { "code": null, "e": 2203, "s": 2046, "text": "See like I said I entered an integer 10+ 10 where I was expecting a result of 20 (10 + 10) but the input method returned a string of the same input entered." }, { "code": null, "e": 2410, "s": 2203, "text": "eval = eval(input(\"Enter any number of your choice\"))print(eval)print(type(eval))--------------------------------------------------------------------Enter any number of your choice: 10 + 10 20 <class 'int'>" }, { "code": null, "e": 2578, "s": 2410, "text": "In the case of eval, it returned the evaluated expression 20 in the form of an integer given the string as input. 10 + 10 is an expression that returns 20 as a result." }, { "code": null, "e": 2657, "s": 2578, "text": "Yes, we can perform mathematical operations using eval function as seen below:" }, { "code": null, "e": 3178, "s": 2657, "text": "evaluate = input(“Enter what operation x has to perform: “)print(evaluate)print(type(evaluate))--------------------------------------------------------------------Enter what operation x has to perform: x + x + 100 - 35 + 5 * 80 x + x + 100 - 35 + 5 * 80 <class 'str'>x = 10print(type(x))--------------------------------------------------------------------<class 'int'>expression = eval(evaluate)print(expression)print(type(expression))--------------------------------------------------------------------485 <class 'int'>" }, { "code": null, "e": 3309, "s": 3178, "text": "See like I said if you give the input as a string and eval function evaluates the expression and returns the result as an integer." }, { "code": null, "e": 3737, "s": 3309, "text": "This is all you need to know to get you started with eval function in python, now you know all the answers for the above questions. The same questions might not be asked all the time, the point is to know the concepts better, then you can answer any questions. If you want to spend some time reading through some material regarding the eval function, I recommend you guys to read the documentation of eval function shown below:" }, { "code": null, "e": 3753, "s": 3737, "text": "docs.python.org" } ]
DateField - Django Models - GeeksforGeeks
24 Aug, 2021 DateField is a field that stores date, represented in Python by a datetime.date instance. As the name suggests, this field is used to store an object of date created in python. The default form widget for this field is a TextInput. The admin can add a JavaScript calendar and a shortcut for “Today” explicitly. Syntax: field_name = models.DateField(**options) DateField has the following extra optional arguments – Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override. The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that. Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today – from datetime.date.today()For DateTimeField: default=timezone.now – from django.utils.timezone.now() For DateField: default=date.today – from datetime.date.today() For DateTimeField: default=timezone.now – from django.utils.timezone.now() Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error. Illustration of DateField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into the models.py file of geeks app. Python3 from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DateField() Add the geeks app to INSTALLED_APPS Python3 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py Python3 # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DateField()), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field DateField is created when you run migrations on the project. It is a field to store datetime.date python object. DateField is used for storing python datetime.date instance in the database. One can store any type of date using the same in the database. Let’s try storing a date in model created above. Python3 # importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport datetime # creating an instance of# datetime.dated = datetime.date(1997, 10, 19) # creating an instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DateField will enable it to store empty values for that table in a relational database. Here are the field options and attributes that a DateField can use. NaveenArora annianni Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23859, "s": 23831, "text": "\n24 Aug, 2021" }, { "code": null, "e": 24170, "s": 23859, "text": "DateField is a field that stores date, represented in Python by a datetime.date instance. As the name suggests, this field is used to store an object of date created in python. The default form widget for this field is a TextInput. The admin can add a JavaScript calendar and a shortcut for “Today” explicitly." }, { "code": null, "e": 24178, "s": 24170, "text": "Syntax:" }, { "code": null, "e": 24219, "s": 24178, "text": "field_name = models.DateField(**options)" }, { "code": null, "e": 24274, "s": 24219, "text": "DateField has the following extra optional arguments –" }, { "code": null, "e": 24720, "s": 24274, "text": "Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override. The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that." }, { "code": null, "e": 25239, "s": 24720, "text": "Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today – from datetime.date.today()For DateTimeField: default=timezone.now – from django.utils.timezone.now() " }, { "code": null, "e": 25302, "s": 25239, "text": "For DateField: default=date.today – from datetime.date.today()" }, { "code": null, "e": 25378, "s": 25302, "text": "For DateTimeField: default=timezone.now – from django.utils.timezone.now() " }, { "code": null, "e": 25516, "s": 25380, "text": "Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error." }, { "code": null, "e": 25627, "s": 25516, "text": "Illustration of DateField using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 25715, "s": 25627, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 25766, "s": 25715, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25799, "s": 25766, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25863, "s": 25799, "text": "Enter the following code into the models.py file of geeks app. " }, { "code": null, "e": 25871, "s": 25863, "text": "Python3" }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DateField()", "e": 26021, "s": 25871, "text": null }, { "code": null, "e": 26058, "s": 26021, "text": "Add the geeks app to INSTALLED_APPS " }, { "code": null, "e": 26066, "s": 26058, "text": "Python3" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 26303, "s": 26066, "text": null }, { "code": null, "e": 26361, "s": 26303, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 26393, "s": 26361, "text": "Python manage.py makemigrations" }, { "code": null, "e": 26494, "s": 26393, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py " }, { "code": null, "e": 26502, "s": 26494, "text": "Python3" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DateField()), ], ), ]", "e": 27081, "s": 26502, "text": null }, { "code": null, "e": 27091, "s": 27081, "text": "Now run, " }, { "code": null, "e": 27116, "s": 27091, "text": "Python manage.py migrate" }, { "code": null, "e": 27250, "s": 27116, "text": "Thus, an geeks_field DateField is created when you run migrations on the project. It is a field to store datetime.date python object." }, { "code": null, "e": 27440, "s": 27250, "text": "DateField is used for storing python datetime.date instance in the database. One can store any type of date using the same in the database. Let’s try storing a date in model created above. " }, { "code": null, "e": 27448, "s": 27440, "text": "Python3" }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport datetime # creating an instance of# datetime.dated = datetime.date(1997, 10, 19) # creating an instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()", "e": 27748, "s": 27448, "text": null }, { "code": null, "e": 27828, "s": 27748, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel. " }, { "code": null, "e": 28177, "s": 27828, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DateField will enable it to store empty values for that table in a relational database. Here are the field options and attributes that a DateField can use. " }, { "code": null, "e": 28189, "s": 28177, "text": "NaveenArora" }, { "code": null, "e": 28198, "s": 28189, "text": "annianni" }, { "code": null, "e": 28212, "s": 28198, "text": "Django-models" }, { "code": null, "e": 28226, "s": 28212, "text": "Python Django" }, { "code": null, "e": 28233, "s": 28226, "text": "Python" }, { "code": null, "e": 28331, "s": 28233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28340, "s": 28331, "text": "Comments" }, { "code": null, "e": 28353, "s": 28340, "text": "Old Comments" }, { "code": null, "e": 28371, "s": 28353, "text": "Python Dictionary" }, { "code": null, "e": 28406, "s": 28371, "text": "Read a file line by line in Python" }, { "code": null, "e": 28428, "s": 28406, "text": "Enumerate() in Python" }, { "code": null, "e": 28460, "s": 28428, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28490, "s": 28460, "text": "Iterate over a list in Python" }, { "code": null, "e": 28532, "s": 28490, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28575, "s": 28532, "text": "Python program to convert a list to string" }, { "code": null, "e": 28601, "s": 28575, "text": "Python String | replace()" }, { "code": null, "e": 28645, "s": 28601, "text": "Reading and Writing to text files in Python" } ]
Display hello world using React.js
create-react-app is a command to create a React.js project with default configuration. Create-react-app will help in running react applications. Command will be executed on npm or yarn If npm and node.js is installed on computer, install create-react-app globally with command − npm install –g create-react-app Creation of project − to create a project once above commands are executed, run below command − npx create-react-app hello-world-example npx comes with npm version 5.2+ , npm version can be checked on terminal using npm –version If npm version is 5.2+, then react.js project can be directly created with command − npx create-react-app hello-world-example If npm version is 6+, npm init react-app hello-world is also an option to create React.js project. With yarn, we have command − yarn create react-app hello-world-example Once above commands are done , change directory to hello-world-example With create-react-app, webpack or babel required for using advanced JavaScript features are preconfigured and we can only concentrate on writing code. cd hello-world-example To execute the application, run the below command on terminal − npm start npm start runs a live development server and the code changes will automatically refresh the browser and reflect the changes. A browser window will be opened, if not opened automatically open a browser manually and type url − localhost:3000 in the address bar. 3000 is the default port used in React application. Port number can be changed if any issue with port number. The default text on application run is shown below − To update open the project using any code editor tools e.g. visual studio code Open the file App.js import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p>Edit <code>src/App.js</code> and save to reload.</p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer"> Learn React </a> </header> </div> ); } export default App; Change the content of return statement to just hello World text − import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> Hello World ! </div> ); } export default App; The text on the browser will be changed immediately
[ { "code": null, "e": 1247, "s": 1062, "text": "create-react-app is a command to create a React.js project with default configuration. Create-react-app will help in running react applications. Command will be executed on npm or yarn" }, { "code": null, "e": 1341, "s": 1247, "text": "If npm and node.js is installed on computer, install create-react-app globally with command −" }, { "code": null, "e": 1373, "s": 1341, "text": "npm install –g create-react-app" }, { "code": null, "e": 1469, "s": 1373, "text": "Creation of project − to create a project once above commands are executed, run below command −" }, { "code": null, "e": 1510, "s": 1469, "text": "npx create-react-app hello-world-example" }, { "code": null, "e": 1602, "s": 1510, "text": "npx comes with npm version 5.2+ , npm version can be checked on terminal using npm –version" }, { "code": null, "e": 1687, "s": 1602, "text": "If npm version is 5.2+, then react.js project can be directly created with command −" }, { "code": null, "e": 1728, "s": 1687, "text": "npx create-react-app hello-world-example" }, { "code": null, "e": 1827, "s": 1728, "text": "If npm version is 6+, npm init react-app hello-world is also an option to create React.js project." }, { "code": null, "e": 1898, "s": 1827, "text": "With yarn, we have command − yarn create react-app hello-world-example" }, { "code": null, "e": 1969, "s": 1898, "text": "Once above commands are done , change directory to hello-world-example" }, { "code": null, "e": 2120, "s": 1969, "text": "With create-react-app, webpack or babel required for using advanced JavaScript features are preconfigured and we can only concentrate on writing code." }, { "code": null, "e": 2143, "s": 2120, "text": "cd hello-world-example" }, { "code": null, "e": 2207, "s": 2143, "text": "To execute the application, run the below command on terminal −" }, { "code": null, "e": 2217, "s": 2207, "text": "npm start" }, { "code": null, "e": 2343, "s": 2217, "text": "npm start runs a live development server and the code changes will automatically refresh the browser and reflect the changes." }, { "code": null, "e": 2588, "s": 2343, "text": "A browser window will be opened, if not opened automatically open a browser manually and type url − localhost:3000 in the address bar. 3000 is the default port used in React application. Port number can be changed if any issue with port number." }, { "code": null, "e": 2641, "s": 2588, "text": "The default text on application run is shown below −" }, { "code": null, "e": 2720, "s": 2641, "text": "To update open the project using any code editor tools e.g. visual studio code" }, { "code": null, "e": 2741, "s": 2720, "text": "Open the file App.js" }, { "code": null, "e": 3318, "s": 2741, "text": "import React from 'react';\nimport logo from './logo.svg';\nimport './App.css';\nfunction App() {\n return (\n <div className=\"App\">\n <header className=\"App-header\">\n <img src={logo} className=\"App-logo\" alt=\"logo\" />\n <p>Edit <code>src/App.js</code> and save to reload.</p>\n <a\n className=\"App-link\"\n href=\"https://reactjs.org\"\n target=\"_blank\"\n rel=\"noopener noreferrer\">\n Learn React\n </a>\n </header>\n </div>\n );\n}\nexport default App;" }, { "code": null, "e": 3384, "s": 3318, "text": "Change the content of return statement to just hello World text −" }, { "code": null, "e": 3583, "s": 3384, "text": "import React from 'react';\nimport logo from './logo.svg';\nimport './App.css';\nfunction App() {\n return (\n <div className=\"App\">\n Hello World !\n </div>\n );\n}\nexport default App;" }, { "code": null, "e": 3635, "s": 3583, "text": "The text on the browser will be changed immediately" } ]
Create index on create table in MySQL?
Let us first create a table and index − mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentAge int, StudentCountryName varchar(100), INDEX first_Name_index(StudentFirstName) ); Query OK, 0 rows affected (1.01 sec) Check the description of the table − mysql> desc DemoTable; This will produce the following output − +--------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentFirstName | varchar(20) | YES | MUL | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentCountryName | varchar(100) | YES | | NULL | | +--------------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1102, "s": 1062, "text": "Let us first create a table and index −" }, { "code": null, "e": 1366, "s": 1102, "text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentFirstName varchar(20),\n StudentAge int,\n StudentCountryName varchar(100),\n INDEX first_Name_index(StudentFirstName)\n );\nQuery OK, 0 rows affected (1.01 sec)" }, { "code": null, "e": 1403, "s": 1366, "text": "Check the description of the table −" }, { "code": null, "e": 1426, "s": 1403, "text": "mysql> desc DemoTable;" }, { "code": null, "e": 1467, "s": 1426, "text": "This will produce the following output −" }, { "code": null, "e": 2116, "s": 1467, "text": "+--------------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentFirstName | varchar(20) | YES | MUL | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n| StudentCountryName | varchar(100) | YES | | NULL | |\n+--------------------+--------------+------+-----+---------+----------------+\n4 rows in set (0.00 sec)" } ]
Minimum number of insertions in given String to remove adjacent duplicates - GeeksforGeeks
21 Jan, 2022 Given a string str of size N, the task is to find the minimum number of additions in the string such that no two consecutive elements are the same. Examples: Input: str=”rrg” Output: 1Explanation: Add an element between two r’s Input: str=”rrrrr”Output: 4 Approach: The above problem can be solved using the below given steps: Declare variable min_steps and initialise it by 0.Traverse the string using a for-loop from i=0 to i<N.Check if the current character is the same as the character before it.If yes, then increment min_steps by 1.Else, continue the loop.Print min_steps as the answer. Declare variable min_steps and initialise it by 0. Traverse the string using a for-loop from i=0 to i<N. Check if the current character is the same as the character before it. If yes, then increment min_steps by 1. Else, continue the loop. Print min_steps as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <iostream>using namespace std; // Function to find the minimum// number of additions such that// no two elements are the sameint minAdditions(string str){ // Storing length of the string int len = str.size(); // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps;} // Driver Codeint main(){ string str = "RRG"; cout << minAdditions(str); return 0;} // Java program for above approachimport java.util.*;public class GFG { // Function to find the minimum // number of additions such that // no two elements are the same static int minAdditions(String str) { // Storing length of the string int len = str.length(); // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str.charAt(i) == str.charAt(i - 1)) min_steps++; } // Returning the number of additions return min_steps; } // Driver Code public static void main(String args[]) { String str = "RRG"; System.out.println(minAdditions(str)); }} // This code is contributed by Samim Hossain Mondal. # python3 program for the above approach # Function to find the minimum# number of additions such that# no two elements are the samedef minAdditions(str): # Storing length of the string le = len(str) # Variable to store # the number of steps needed min_steps = 0 # For loop to check # all colours in the string for i in range(1, le): if (str[i] == str[i - 1]): min_steps += 1 # Returning the number of additions return min_steps # Driver Codeif __name__ == "__main__": str = "RRG" print(minAdditions(str)) # This code is contributed by rakeshsahni // C# program for the above approachusing System;class GFG { // Function to find the minimum // number of additions such that // no two elements are the same static int minAdditions(string str) { // Storing length of the string int len = str.Length; // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps; } // Driver Code public static void Main() { string str = "RRG"; Console.Write(minAdditions(str)); }} // This code is contributed by ukasp. <script>// Javascript program for the above approach // Function to find the minimum// number of additions such that// no two elements are the samefunction minAdditions(str){ // Storing length of the string let len = str.length; // Variable to store // the number of steps needed let min_steps = 0; let i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps;} // Driver Code let str = "RRG";document.write(minAdditions(str)) // This code is contributed by gfgking.</script> 1 Time Complexity: O(N)Auxiliary Space: O(1) rakeshsahni ukasp samim2000 gfgking kaurareen Algo-Geek 2021 Algo Geek Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Encode given String by inserting in Matrix column-wise and printing it row-wise Lexicographically smallest string formed by concatenating any prefix and its mirrored form Count of adjacent pairs in given Array with even sum Check if the given string is valid English word or not Abbreviate given string by replacing all characters with length except the first and last Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25859, "s": 25831, "text": "\n21 Jan, 2022" }, { "code": null, "e": 26007, "s": 25859, "text": "Given a string str of size N, the task is to find the minimum number of additions in the string such that no two consecutive elements are the same." }, { "code": null, "e": 26017, "s": 26007, "text": "Examples:" }, { "code": null, "e": 26087, "s": 26017, "text": "Input: str=”rrg” Output: 1Explanation: Add an element between two r’s" }, { "code": null, "e": 26115, "s": 26087, "text": "Input: str=”rrrrr”Output: 4" }, { "code": null, "e": 26186, "s": 26115, "text": "Approach: The above problem can be solved using the below given steps:" }, { "code": null, "e": 26452, "s": 26186, "text": "Declare variable min_steps and initialise it by 0.Traverse the string using a for-loop from i=0 to i<N.Check if the current character is the same as the character before it.If yes, then increment min_steps by 1.Else, continue the loop.Print min_steps as the answer." }, { "code": null, "e": 26503, "s": 26452, "text": "Declare variable min_steps and initialise it by 0." }, { "code": null, "e": 26557, "s": 26503, "text": "Traverse the string using a for-loop from i=0 to i<N." }, { "code": null, "e": 26628, "s": 26557, "text": "Check if the current character is the same as the character before it." }, { "code": null, "e": 26667, "s": 26628, "text": "If yes, then increment min_steps by 1." }, { "code": null, "e": 26692, "s": 26667, "text": "Else, continue the loop." }, { "code": null, "e": 26723, "s": 26692, "text": "Print min_steps as the answer." }, { "code": null, "e": 26774, "s": 26723, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26778, "s": 26774, "text": "C++" }, { "code": null, "e": 26783, "s": 26778, "text": "Java" }, { "code": null, "e": 26791, "s": 26783, "text": "Python3" }, { "code": null, "e": 26794, "s": 26791, "text": "C#" }, { "code": null, "e": 26805, "s": 26794, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to find the minimum// number of additions such that// no two elements are the sameint minAdditions(string str){ // Storing length of the string int len = str.size(); // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps;} // Driver Codeint main(){ string str = \"RRG\"; cout << minAdditions(str); return 0;}", "e": 27464, "s": 26805, "text": null }, { "code": "// Java program for above approachimport java.util.*;public class GFG { // Function to find the minimum // number of additions such that // no two elements are the same static int minAdditions(String str) { // Storing length of the string int len = str.length(); // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str.charAt(i) == str.charAt(i - 1)) min_steps++; } // Returning the number of additions return min_steps; } // Driver Code public static void main(String args[]) { String str = \"RRG\"; System.out.println(minAdditions(str)); }} // This code is contributed by Samim Hossain Mondal.", "e": 28237, "s": 27464, "text": null }, { "code": "# python3 program for the above approach # Function to find the minimum# number of additions such that# no two elements are the samedef minAdditions(str): # Storing length of the string le = len(str) # Variable to store # the number of steps needed min_steps = 0 # For loop to check # all colours in the string for i in range(1, le): if (str[i] == str[i - 1]): min_steps += 1 # Returning the number of additions return min_steps # Driver Codeif __name__ == \"__main__\": str = \"RRG\" print(minAdditions(str)) # This code is contributed by rakeshsahni", "e": 28845, "s": 28237, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Function to find the minimum // number of additions such that // no two elements are the same static int minAdditions(string str) { // Storing length of the string int len = str.Length; // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps; } // Driver Code public static void Main() { string str = \"RRG\"; Console.Write(minAdditions(str)); }} // This code is contributed by ukasp.", "e": 29557, "s": 28845, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the minimum// number of additions such that// no two elements are the samefunction minAdditions(str){ // Storing length of the string let len = str.length; // Variable to store // the number of steps needed let min_steps = 0; let i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps;} // Driver Code let str = \"RRG\";document.write(minAdditions(str)) // This code is contributed by gfgking.</script>", "e": 30211, "s": 29557, "text": null }, { "code": null, "e": 30216, "s": 30214, "text": "1" }, { "code": null, "e": 30261, "s": 30218, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 30275, "s": 30263, "text": "rakeshsahni" }, { "code": null, "e": 30281, "s": 30275, "text": "ukasp" }, { "code": null, "e": 30291, "s": 30281, "text": "samim2000" }, { "code": null, "e": 30299, "s": 30291, "text": "gfgking" }, { "code": null, "e": 30309, "s": 30299, "text": "kaurareen" }, { "code": null, "e": 30324, "s": 30309, "text": "Algo-Geek 2021" }, { "code": null, "e": 30334, "s": 30324, "text": "Algo Geek" }, { "code": null, "e": 30342, "s": 30334, "text": "Strings" }, { "code": null, "e": 30350, "s": 30342, "text": "Strings" }, { "code": null, "e": 30448, "s": 30350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30457, "s": 30448, "text": "Comments" }, { "code": null, "e": 30470, "s": 30457, "text": "Old Comments" }, { "code": null, "e": 30550, "s": 30470, "text": "Encode given String by inserting in Matrix column-wise and printing it row-wise" }, { "code": null, "e": 30641, "s": 30550, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 30694, "s": 30641, "text": "Count of adjacent pairs in given Array with even sum" }, { "code": null, "e": 30749, "s": 30694, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 30839, "s": 30749, "text": "Abbreviate given string by replacing all characters with length except the first and last" }, { "code": null, "e": 30864, "s": 30839, "text": "Reverse a string in Java" }, { "code": null, "e": 30898, "s": 30864, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 30944, "s": 30898, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31004, "s": 30944, "text": "Write a program to print all permutations of a given string" } ]
DATESINPERIOD function
Returns a table that contains a column of dates that begins with the start_date and continues for the specified number_of_intervals. DATESINPERIOD (<dates>, <start_date>, <number_of_intervals>, <interval>) dates A column that contains dates. start_date A date expression. number_of_intervals An integer that specifies the number of intervals to add to or subtract from the dates. interval The interval by which to shift the dates. The value for interval can be one of the following − year quarter month day A table containing a single column of date values. The dates parameter can be any of the following − A reference to a date/time column. A reference to a date/time column. A table expression that returns a single column of date/time values. A table expression that returns a single column of date/time values. A Boolean expression that defines a single-column table of date/time values. A Boolean expression that defines a single-column table of date/time values. Constraints on Boolean expressions − The expression cannot reference a calculated field. The expression cannot reference a calculated field. The expression cannot use CALCULATE function. The expression cannot use CALCULATE function. The expression cannot use any function that scans a table or returns a table, including aggregation functions. The expression cannot use any function that scans a table or returns a table, including aggregation functions. However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value. If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time. The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them. The result table includes only dates that are specified in the dates parameter. = CALCULATE ( SUM (Sales [Sales Amount]), DATESINPERIOD (Sales[Date], DATE (2015,1,1),3, MONTH) ) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2134, "s": 2001, "text": "Returns a table that contains a column of dates that begins with the start_date and continues for the specified number_of_intervals." }, { "code": null, "e": 2209, "s": 2134, "text": "DATESINPERIOD (<dates>, <start_date>, <number_of_intervals>, <interval>) \n" }, { "code": null, "e": 2215, "s": 2209, "text": "dates" }, { "code": null, "e": 2245, "s": 2215, "text": "A column that contains dates." }, { "code": null, "e": 2256, "s": 2245, "text": "start_date" }, { "code": null, "e": 2275, "s": 2256, "text": "A date expression." }, { "code": null, "e": 2295, "s": 2275, "text": "number_of_intervals" }, { "code": null, "e": 2383, "s": 2295, "text": "An integer that specifies the number of intervals to add to or subtract from the dates." }, { "code": null, "e": 2392, "s": 2383, "text": "interval" }, { "code": null, "e": 2434, "s": 2392, "text": "The interval by which to shift the dates." }, { "code": null, "e": 2487, "s": 2434, "text": "The value for interval can be one of the following −" }, { "code": null, "e": 2492, "s": 2487, "text": "year" }, { "code": null, "e": 2500, "s": 2492, "text": "quarter" }, { "code": null, "e": 2506, "s": 2500, "text": "month" }, { "code": null, "e": 2510, "s": 2506, "text": "day" }, { "code": null, "e": 2561, "s": 2510, "text": "A table containing a single column of date values." }, { "code": null, "e": 2611, "s": 2561, "text": "The dates parameter can be any of the following −" }, { "code": null, "e": 2646, "s": 2611, "text": "A reference to a date/time column." }, { "code": null, "e": 2681, "s": 2646, "text": "A reference to a date/time column." }, { "code": null, "e": 2750, "s": 2681, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2819, "s": 2750, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2896, "s": 2819, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2973, "s": 2896, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 3010, "s": 2973, "text": "Constraints on Boolean expressions −" }, { "code": null, "e": 3062, "s": 3010, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3114, "s": 3062, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3160, "s": 3114, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3206, "s": 3160, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3317, "s": 3206, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3428, "s": 3317, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3544, "s": 3428, "text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value." }, { "code": null, "e": 3715, "s": 3544, "text": "If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time." }, { "code": null, "e": 3940, "s": 3715, "text": "The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them." }, { "code": null, "e": 4020, "s": 3940, "text": "The result table includes only dates that are specified in the dates parameter." }, { "code": null, "e": 4127, "s": 4020, "text": "= CALCULATE ( \n SUM (Sales [Sales Amount]), \n DATESINPERIOD (Sales[Date], DATE (2015,1,1),3, MONTH)\n) " }, { "code": null, "e": 4162, "s": 4127, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4176, "s": 4162, "text": " Abhay Gadiya" }, { "code": null, "e": 4209, "s": 4176, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4223, "s": 4209, "text": " Randy Minder" }, { "code": null, "e": 4258, "s": 4223, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4272, "s": 4258, "text": " Randy Minder" }, { "code": null, "e": 4279, "s": 4272, "text": " Print" }, { "code": null, "e": 4290, "s": 4279, "text": " Add Notes" } ]
Comments in C# - GeeksforGeeks
07 May, 2019 Comments are used for explaining the code and are used in a similar manner as in Java, C or C++. Compilers ignore the comment entries and do not execute them. Generally, programming languages contain two types of comments but in C#, there are 3 Types of comments : Single Line Comments : It is used to comment a single line. These comment can be written in a separate line or along with the codes in the same line. But for better understanding always use the comment in a separate line.Syntax :// Single Line CommentsMultiline Comments : It is used to comment more than one line. Generally this is used to comment out an entire block of code statements.Syntax :/* Multiline Comment */ Example :// C# program to demonstrate the single // line and multiline commentsusing System; namespace HelloGeeksApp { class HelloGeeks { // Single Line Comment -- Function to print Message public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Multiline Comment -- Define a variable of string type and assign value to it*/ string msg = "GeeksforGeeks"; // Calling function Message(msg); }}}Output:GeeksforGeeks XML Documentation Comments : It is a special type of comment in C# and used to create the documentation of C# code by adding XML elements in the source code. XML elements are added in XML Documentation Comments of C#. For more details refer to XML Documentation Comments in C#Syntax :/// <summary> /// This class does something of program Summary. /// </summary> Example :// C# program to demonstrate XML// Documentation Comments using System; namespace HelloGeeksApp { class HelloGeeks { /// <summary> /// Method to Display Geeksforgeeks Message /// </summary> /// <param name="Geeksforgeeks"></param> public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Define a variable of string type and assign value to it*/ string msg = "GeeksforGeeks"; // Calling function Message(msg); }}}Output:GeeksforGeeks Single Line Comments : It is used to comment a single line. These comment can be written in a separate line or along with the codes in the same line. But for better understanding always use the comment in a separate line.Syntax :// Single Line Comments // Single Line Comments Multiline Comments : It is used to comment more than one line. Generally this is used to comment out an entire block of code statements.Syntax :/* Multiline Comment */ Example :// C# program to demonstrate the single // line and multiline commentsusing System; namespace HelloGeeksApp { class HelloGeeks { // Single Line Comment -- Function to print Message public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Multiline Comment -- Define a variable of string type and assign value to it*/ string msg = "GeeksforGeeks"; // Calling function Message(msg); }}}Output:GeeksforGeeks /* Multiline Comment */ Example : // C# program to demonstrate the single // line and multiline commentsusing System; namespace HelloGeeksApp { class HelloGeeks { // Single Line Comment -- Function to print Message public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Multiline Comment -- Define a variable of string type and assign value to it*/ string msg = "GeeksforGeeks"; // Calling function Message(msg); }}} GeeksforGeeks XML Documentation Comments : It is a special type of comment in C# and used to create the documentation of C# code by adding XML elements in the source code. XML elements are added in XML Documentation Comments of C#. For more details refer to XML Documentation Comments in C#Syntax :/// <summary> /// This class does something of program Summary. /// </summary> Example :// C# program to demonstrate XML// Documentation Comments using System; namespace HelloGeeksApp { class HelloGeeks { /// <summary> /// Method to Display Geeksforgeeks Message /// </summary> /// <param name="Geeksforgeeks"></param> public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Define a variable of string type and assign value to it*/ string msg = "GeeksforGeeks"; // Calling function Message(msg); }}}Output:GeeksforGeeks /// <summary> /// This class does something of program Summary. /// </summary> Example : // C# program to demonstrate XML// Documentation Comments using System; namespace HelloGeeksApp { class HelloGeeks { /// <summary> /// Method to Display Geeksforgeeks Message /// </summary> /// <param name="Geeksforgeeks"></param> public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Define a variable of string type and assign value to it*/ string msg = "GeeksforGeeks"; // Calling function Message(msg); }}} GeeksforGeeks Note : The <summary> tag provides the information about the defined a type or member and <param> tag is method parameters. Related Articles: Comments in Java Comments in SQL Comments in HTML Akanksha_Rai CSharp-Basics C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Extension Method in C# Introduction to .NET Framework C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Different ways to sort an array in descending order in C#
[ { "code": null, "e": 23435, "s": 23407, "text": "\n07 May, 2019" }, { "code": null, "e": 23700, "s": 23435, "text": "Comments are used for explaining the code and are used in a similar manner as in Java, C or C++. Compilers ignore the comment entries and do not execute them. Generally, programming languages contain two types of comments but in C#, there are 3 Types of comments :" }, { "code": null, "e": 25737, "s": 23700, "text": "Single Line Comments : It is used to comment a single line. These comment can be written in a separate line or along with the codes in the same line. But for better understanding always use the comment in a separate line.Syntax :// Single Line CommentsMultiline Comments : It is used to comment more than one line. Generally this is used to comment out an entire block of code statements.Syntax :/* Multiline\nComment */\nExample :// C# program to demonstrate the single // line and multiline commentsusing System; namespace HelloGeeksApp { class HelloGeeks { // Single Line Comment -- Function to print Message public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Multiline Comment -- Define a variable of string type and assign value to it*/ string msg = \"GeeksforGeeks\"; // Calling function Message(msg); }}}Output:GeeksforGeeks\nXML Documentation Comments : It is a special type of comment in C# and used to create the documentation of C# code by adding XML elements in the source code. XML elements are added in XML Documentation Comments of C#. For more details refer to XML Documentation Comments in C#Syntax :/// <summary>\n/// This class does something of program Summary.\n/// </summary>\nExample :// C# program to demonstrate XML// Documentation Comments using System; namespace HelloGeeksApp { class HelloGeeks { /// <summary> /// Method to Display Geeksforgeeks Message /// </summary> /// <param name=\"Geeksforgeeks\"></param> public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Define a variable of string type and assign value to it*/ string msg = \"GeeksforGeeks\"; // Calling function Message(msg); }}}Output:GeeksforGeeks\n" }, { "code": null, "e": 25990, "s": 25737, "text": "Single Line Comments : It is used to comment a single line. These comment can be written in a separate line or along with the codes in the same line. But for better understanding always use the comment in a separate line.Syntax :// Single Line Comments" }, { "code": null, "e": 26014, "s": 25990, "text": "// Single Line Comments" }, { "code": null, "e": 26793, "s": 26014, "text": "Multiline Comments : It is used to comment more than one line. Generally this is used to comment out an entire block of code statements.Syntax :/* Multiline\nComment */\nExample :// C# program to demonstrate the single // line and multiline commentsusing System; namespace HelloGeeksApp { class HelloGeeks { // Single Line Comment -- Function to print Message public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Multiline Comment -- Define a variable of string type and assign value to it*/ string msg = \"GeeksforGeeks\"; // Calling function Message(msg); }}}Output:GeeksforGeeks\n" }, { "code": null, "e": 26818, "s": 26793, "text": "/* Multiline\nComment */\n" }, { "code": null, "e": 26828, "s": 26818, "text": "Example :" }, { "code": "// C# program to demonstrate the single // line and multiline commentsusing System; namespace HelloGeeksApp { class HelloGeeks { // Single Line Comment -- Function to print Message public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Multiline Comment -- Define a variable of string type and assign value to it*/ string msg = \"GeeksforGeeks\"; // Calling function Message(msg); }}}", "e": 27409, "s": 26828, "text": null }, { "code": null, "e": 27424, "s": 27409, "text": "GeeksforGeeks\n" }, { "code": null, "e": 28431, "s": 27424, "text": "XML Documentation Comments : It is a special type of comment in C# and used to create the documentation of C# code by adding XML elements in the source code. XML elements are added in XML Documentation Comments of C#. For more details refer to XML Documentation Comments in C#Syntax :/// <summary>\n/// This class does something of program Summary.\n/// </summary>\nExample :// C# program to demonstrate XML// Documentation Comments using System; namespace HelloGeeksApp { class HelloGeeks { /// <summary> /// Method to Display Geeksforgeeks Message /// </summary> /// <param name=\"Geeksforgeeks\"></param> public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Define a variable of string type and assign value to it*/ string msg = \"GeeksforGeeks\"; // Calling function Message(msg); }}}Output:GeeksforGeeks\n" }, { "code": null, "e": 28511, "s": 28431, "text": "/// <summary>\n/// This class does something of program Summary.\n/// </summary>\n" }, { "code": null, "e": 28521, "s": 28511, "text": "Example :" }, { "code": "// C# program to demonstrate XML// Documentation Comments using System; namespace HelloGeeksApp { class HelloGeeks { /// <summary> /// Method to Display Geeksforgeeks Message /// </summary> /// <param name=\"Geeksforgeeks\"></param> public static void Message(string message) { Console.WriteLine(message); } // Main function static void Main(string[] args) { /* Define a variable of string type and assign value to it*/ string msg = \"GeeksforGeeks\"; // Calling function Message(msg); }}}", "e": 29135, "s": 28521, "text": null }, { "code": null, "e": 29150, "s": 29135, "text": "GeeksforGeeks\n" }, { "code": null, "e": 29273, "s": 29150, "text": "Note : The <summary> tag provides the information about the defined a type or member and <param> tag is method parameters." }, { "code": null, "e": 29291, "s": 29273, "text": "Related Articles:" }, { "code": null, "e": 29308, "s": 29291, "text": "Comments in Java" }, { "code": null, "e": 29324, "s": 29308, "text": "Comments in SQL" }, { "code": null, "e": 29341, "s": 29324, "text": "Comments in HTML" }, { "code": null, "e": 29354, "s": 29341, "text": "Akanksha_Rai" }, { "code": null, "e": 29368, "s": 29354, "text": "CSharp-Basics" }, { "code": null, "e": 29371, "s": 29368, "text": "C#" }, { "code": null, "e": 29469, "s": 29371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29478, "s": 29469, "text": "Comments" }, { "code": null, "e": 29491, "s": 29478, "text": "Old Comments" }, { "code": null, "e": 29514, "s": 29491, "text": "C# | Method Overriding" }, { "code": null, "e": 29542, "s": 29514, "text": "C# Dictionary with examples" }, { "code": null, "e": 29588, "s": 29542, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29603, "s": 29588, "text": "C# | Delegates" }, { "code": null, "e": 29643, "s": 29603, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29666, "s": 29643, "text": "Extension Method in C#" }, { "code": null, "e": 29697, "s": 29666, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29719, "s": 29697, "text": "C# | Abstract Classes" }, { "code": null, "e": 29759, "s": 29719, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Bootstrap - Tables
Bootstrap provides a clean layout for building tables. Some of the table elements supported by Bootstrap are − <table> Wrapping element for displaying data in a tabular format <thead> Container element for table header rows (<tr>) to label table columns. <tbody> Container element for table rows (<tr>) in the body of the table. <tr> Container element for a set of table cells (<td> or <th>) that appears on a single row. <td> Default table cell. <th> Special table cell for column (or row, depending on scope and placement) labels. Must be used within a <thead> <caption> Description or summary of what the table holds. If you want a nice, basic table style with just some light padding and horizontal dividers, add the base class of .table to any table as shown in the following example − <table class = "table"> <caption>Basic Table Layout</caption> <thead> <tr> <th>Name</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Tanmay</td> <td>Bangalore</td> </tr> <tr> <td>Sachin</td> <td>Mumbai</td> </tr> </tbody> </table> Along with the base table markup and the .table class, there are a few additional classes that you can use to style the markup. Following sections will give you a glimpse of all these classes. By adding the .table-striped class, you will get stripes on rows within the <tbody> as seen in the following example − <table class = "table table-striped"> <caption>Striped Table Layout</caption> <thead> <tr> <th>Name</th> <th>City</th> <th>Pincode</th> </tr> </thead> <tbody> <tr> <td>Tanmay</td> <td>Bangalore</td> <td>560001</td> </tr> <tr> <td>Sachin</td> <td>Mumbai</td> <td>400003</td> </tr> <tr> <td>Uma</td> <td>Pune</td> <td>411027</td> </tr> </tbody> </table> By adding the .table-bordered class, you will get borders surrounding every element and rounded corners around the entire table as seen in the following example − <table class = "table table-bordered"> <caption>Bordered Table Layout</caption> <thead> <tr> <th>Name</th> <th>City</th> <th>Pincode</th> </tr> </thead> <tbody> <tr> <td>Tanmay</td> <td>Bangalore</td> <td>560001</td> </tr> <tr> <td>Sachin</td> <td>Mumbai</td> <td>400003</td> </tr> <tr> <td>Uma</td> <td>Pune</td> <td>411027</td> </tr> </tbody> </table> By adding the .table-hover class, a light gray background will be added to rows while the cursor hovers over them, as seen in the following example − <table class = "table table-hover"> <caption>Hover Table Layout</caption> <thead> <tr> <th>Name</th> <th>City</th> <th>Pincode</th> </tr> </thead> <tbody> <tr> <td>Tanmay</td> <td>Bangalore</td> <td>560001</td> </tr> <tr> <td>Sachin</td> <td>Mumbai</td> <td>400003</td> </tr> <tr> <td>Uma</td> <td>Pune</td> <td>411027</td> </tr> </tbody> </table> By adding the .table-condensed class, row padding is cut in half to condense the table. as seen in the following example. This is useful if you want any denser information. <table class = "table table-condensed"> <caption>Condensed Table Layout</caption> <thead> <tr> <th>Name</th> <th>City</th> <th>Pincode</th> </tr> </thead> <tbody> <tr> <td>Tanmay</td> <td>Bangalore</td> <td>560001</td> </tr> <tr> <td>Sachin</td> <td>Mumbai</td> <td>400003</td> </tr> <tr> <td>Uma</td> <td>Pune</td> <td>411027</td> </tr> </tbody> </table> The Contextual classes shown in following table will allow you to change the background color of your table rows or individual cells. .active Applies the hover color to a particular row or cell .success Indicates a successful or positive action .warning Indicates a warning that might need attention .danger Indicates a dangerous or potentially negative action These classes can be applied to <tr>, <td> or <th>. <table class = "table"> <caption>Contextual Table Layout</caption> <thead> <tr> <th>Product</th> <th>Payment Date</th> <th>Status</th> </tr> </thead> <tbody> <tr class = "active"> <td>Product1</td> <td>23/11/2013</td> <td>Pending</td> </tr> <tr class = "success"> <td>Product2</td> <td>10/11/2013</td> <td>Delivered</td> </tr> <tr class = "warning"> <td>Product3</td> <td>20/10/2013</td> <td>In Call to confirm</td> </tr> <tr class = "danger"> <td>Product4</td> <td>20/10/2013</td> <td>Declined</td> </tr> </tbody> </table> By wrapping any .table in .table-responsive class, you will make the table scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables. <div class = "table-responsive"> <table class = "table"> <caption>Responsive Table Layout</caption> <thead> <tr> <th>Product</th> <th>Payment Date</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Product1</td> <td>23/11/2013</td> <td>Pending</td> </tr> <tr> <td>Product2</td> <td>10/11/2013</td> <td>Delivered</td> </tr> <tr> <td>Product3</td> <td>20/10/2013</td> <td>In Call to confirm</td> </tr> <tr> <td>Product4</td> <td>20/10/2013</td> <td>Declined</td> </tr> </tbody> </table> </div> 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3442, "s": 3331, "text": "Bootstrap provides a clean layout for building tables. Some of the table elements supported by Bootstrap are −" }, { "code": null, "e": 3450, "s": 3442, "text": "<table>" }, { "code": null, "e": 3507, "s": 3450, "text": "Wrapping element for displaying data in a tabular format" }, { "code": null, "e": 3515, "s": 3507, "text": "<thead>" }, { "code": null, "e": 3586, "s": 3515, "text": "Container element for table header rows (<tr>) to label table columns." }, { "code": null, "e": 3594, "s": 3586, "text": "<tbody>" }, { "code": null, "e": 3660, "s": 3594, "text": "Container element for table rows (<tr>) in the body of the table." }, { "code": null, "e": 3665, "s": 3660, "text": "<tr>" }, { "code": null, "e": 3753, "s": 3665, "text": "Container element for a set of table cells (<td> or <th>) that appears on a single row." }, { "code": null, "e": 3758, "s": 3753, "text": "<td>" }, { "code": null, "e": 3778, "s": 3758, "text": "Default table cell." }, { "code": null, "e": 3783, "s": 3778, "text": "<th>" }, { "code": null, "e": 3894, "s": 3783, "text": "Special table cell for column (or row, depending on scope and placement) labels. Must be used within a <thead>" }, { "code": null, "e": 3904, "s": 3894, "text": "<caption>" }, { "code": null, "e": 3952, "s": 3904, "text": "Description or summary of what the table holds." }, { "code": null, "e": 4122, "s": 3952, "text": "If you want a nice, basic table style with just some light padding and horizontal dividers, add the base class of .table to any table as shown in the following example −" }, { "code": null, "e": 4475, "s": 4122, "text": "<table class = \"table\">\n <caption>Basic Table Layout</caption>\n \n <thead>\n <tr>\n <th>Name</th>\n <th>City</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Tanmay</td>\n <td>Bangalore</td>\n </tr>\n \n <tr>\n <td>Sachin</td>\n <td>Mumbai</td>\n </tr>\n </tbody>\n</table>" }, { "code": null, "e": 4668, "s": 4475, "text": "Along with the base table markup and the .table class, there are a few additional classes that you can use to style the markup. Following sections will give you a glimpse of all these classes." }, { "code": null, "e": 4787, "s": 4668, "text": "By adding the .table-striped class, you will get stripes on rows within the <tbody> as seen in the following example −" }, { "code": null, "e": 5332, "s": 4787, "text": "<table class = \"table table-striped\">\n <caption>Striped Table Layout</caption>\n \n <thead>\n <tr>\n <th>Name</th>\n <th>City</th>\n <th>Pincode</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Tanmay</td>\n <td>Bangalore</td>\n <td>560001</td>\n </tr>\n \n <tr>\n <td>Sachin</td>\n <td>Mumbai</td>\n <td>400003</td>\n </tr>\n \n <tr>\n <td>Uma</td>\n <td>Pune</td>\n <td>411027</td>\n </tr>\n </tbody>\n</table>" }, { "code": null, "e": 5495, "s": 5332, "text": "By adding the .table-bordered class, you will get borders surrounding every element and rounded corners around the entire table as seen in the following example −" }, { "code": null, "e": 6044, "s": 5495, "text": "<table class = \"table table-bordered\">\n <caption>Bordered Table Layout</caption>\n \n <thead>\n <tr>\n <th>Name</th>\n <th>City</th>\n <th>Pincode</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Tanmay</td>\n <td>Bangalore</td>\n <td>560001</td>\n </tr>\n \n <tr>\n <td>Sachin</td>\n <td>Mumbai</td>\n <td>400003</td>\n </tr>\n \n <tr>\n <td>Uma</td>\n <td>Pune</td>\n <td>411027</td>\n </tr>\n </tbody>\n\t\n</table>" }, { "code": null, "e": 6194, "s": 6044, "text": "By adding the .table-hover class, a light gray background will be added to rows while the cursor hovers over them, as seen in the following example −" }, { "code": null, "e": 6735, "s": 6194, "text": "<table class = \"table table-hover\">\n <caption>Hover Table Layout</caption>\n \n <thead>\n <tr>\n <th>Name</th>\n <th>City</th>\n <th>Pincode</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Tanmay</td>\n <td>Bangalore</td>\n <td>560001</td>\n </tr>\n \n <tr>\n <td>Sachin</td>\n <td>Mumbai</td>\n <td>400003</td>\n </tr>\n \n <tr>\n <td>Uma</td>\n <td>Pune</td>\n <td>411027</td>\n </tr>\n </tbody>\n</table>" }, { "code": null, "e": 6909, "s": 6735, "text": "By adding the .table-condensed class, row padding is cut in half to condense the table. as seen in the following example. This is useful if you want any denser information." }, { "code": null, "e": 7458, "s": 6909, "text": "<table class = \"table table-condensed\">\n <caption>Condensed Table Layout</caption>\n \n <thead>\n <tr>\n <th>Name</th>\n <th>City</th>\n <th>Pincode</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Tanmay</td>\n <td>Bangalore</td>\n <td>560001</td>\n </tr>\n \n <tr>\n <td>Sachin</td>\n <td>Mumbai</td>\n <td>400003</td>\n </tr>\n \n <tr>\n <td>Uma</td>\n <td>Pune</td>\n <td>411027</td>\n </tr>\n </tbody>\n</table>" }, { "code": null, "e": 7592, "s": 7458, "text": "The Contextual classes shown in following table will allow you to change the background color of your table rows or individual cells." }, { "code": null, "e": 7600, "s": 7592, "text": ".active" }, { "code": null, "e": 7652, "s": 7600, "text": "Applies the hover color to a particular row or cell" }, { "code": null, "e": 7661, "s": 7652, "text": ".success" }, { "code": null, "e": 7703, "s": 7661, "text": "Indicates a successful or positive action" }, { "code": null, "e": 7712, "s": 7703, "text": ".warning" }, { "code": null, "e": 7758, "s": 7712, "text": "Indicates a warning that might need attention" }, { "code": null, "e": 7766, "s": 7758, "text": ".danger" }, { "code": null, "e": 7819, "s": 7766, "text": "Indicates a dangerous or potentially negative action" }, { "code": null, "e": 7871, "s": 7819, "text": "These classes can be applied to <tr>, <td> or <th>." }, { "code": null, "e": 8634, "s": 7871, "text": "<table class = \"table\">\n <caption>Contextual Table Layout</caption>\n \n <thead>\n <tr>\n <th>Product</th>\n <th>Payment Date</th>\n <th>Status</th>\n </tr>\n </thead>\n \n <tbody>\n <tr class = \"active\">\n <td>Product1</td>\n <td>23/11/2013</td>\n <td>Pending</td>\n </tr>\n \n <tr class = \"success\">\n <td>Product2</td>\n <td>10/11/2013</td>\n <td>Delivered</td>\n </tr>\n \n <tr class = \"warning\">\n <td>Product3</td>\n <td>20/10/2013</td>\n <td>In Call to confirm</td>\n </tr>\n \n <tr class = \"danger\">\n <td>Product4</td>\n <td>20/10/2013</td>\n <td>Declined</td>\n </tr>\n </tbody>\n</table>" }, { "code": null, "e": 8862, "s": 8634, "text": "By wrapping any .table in .table-responsive class, you will make the table scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables." }, { "code": null, "e": 9709, "s": 8862, "text": "<div class = \"table-responsive\">\n <table class = \"table\">\n <caption>Responsive Table Layout</caption>\n \n <thead>\n <tr>\n <th>Product</th>\n <th>Payment Date</th>\n <th>Status</th>\n </tr>\n </thead>\n \n <tbody>\n <tr>\n <td>Product1</td>\n <td>23/11/2013</td>\n <td>Pending</td>\n </tr>\n \n <tr>\n <td>Product2</td>\n <td>10/11/2013</td>\n <td>Delivered</td>\n </tr>\n \n <tr>\n <td>Product3</td>\n <td>20/10/2013</td>\n <td>In Call to confirm</td>\n </tr>\n \n <tr>\n <td>Product4</td>\n <td>20/10/2013</td>\n <td>Declined</td>\n </tr>\n </tbody>\n </table>\n</div> \t" }, { "code": null, "e": 9742, "s": 9709, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 9756, "s": 9742, "text": " Anadi Sharma" }, { "code": null, "e": 9791, "s": 9756, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9808, "s": 9791, "text": " Frahaan Hussain" }, { "code": null, "e": 9845, "s": 9808, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 9873, "s": 9845, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9906, "s": 9873, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 9918, "s": 9906, "text": " Azaz Patel" }, { "code": null, "e": 9953, "s": 9918, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9970, "s": 9953, "text": " Muhammad Ismail" }, { "code": null, "e": 10003, "s": 9970, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 10023, "s": 10003, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 10030, "s": 10023, "text": " Print" }, { "code": null, "e": 10041, "s": 10030, "text": " Add Notes" } ]
ArrayList forEach() method in Java - GeeksforGeeks
26 Nov, 2018 The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptions thrown by the Operation are passed to the caller. Until and unless an overriding class has specified a concurrent modification policy, the operation cannot modify the underlying source of elements so we can say that behavior of this method is unspecified. Retrieving Elements from Collection in Java. Syntax: public void forEach(Consumer<? super E> action) Parameter: This method takes a parameter action which represents the action to be performed for each element. Returns: This method does not returns anything. Exception: This method throws NullPointerException if the specified action is null. Below programs illustrate forEach() method of ArrayList: Program 1: Program to demonstrate forEach() method on ArrayList which contains a list of Numbers. // Java Program Demonstrate forEach()// method of ArrayList import java.util.*;public class GFG { public static void main(String[] args) { // create an ArrayList which going to // contains a list of Numbers ArrayList<Integer> Numbers = new ArrayList<Integer>(); // Add Number to list Numbers.add(23); Numbers.add(32); Numbers.add(45); Numbers.add(63); // forEach method of ArrayList and // print numbers Numbers.forEach((n) -> System.out.println(n)); }} 23 32 45 63 Program 2: Program to demonstrate forEach() method on ArrayList which contains list of Students Names. // Java Program Demonstrate forEach()// method of ArrayList import java.util.*;public class GFG { public static void main(String[] args) { // create an ArrayList which going to // contains a list of Student names which is actually // string values ArrayList<String> students = new ArrayList<String>(); // Add Strings to list // each string represents student name students.add("Ram"); students.add("Mohan"); students.add("Sohan"); students.add("Rabi"); // print result System.out.println("list of Students:"); // forEach method of ArrayList and // print student names students.forEach((n) -> print(n)); } // printing student name public static void print(String n) { System.out.println("Student Name is " + n); }} list of Students: Student Name is Ram Student Name is Mohan Student Name is Sohan Student Name is Rabi Reference: https://docs.oracle.com/javase/10/docs/api/java/util/ArrayList.html#forEach(java.util.function.Consumer) Java - util package Java-ArrayList Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java Singleton Class in Java Set in Java Overriding in Java LinkedList in Java Collections in Java Initializing a List in Java Queue Interface In Java Multithreading in Java
[ { "code": null, "e": 24063, "s": 24035, "text": "\n26 Nov, 2018" }, { "code": null, "e": 24466, "s": 24063, "text": "The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptions thrown by the Operation are passed to the caller." }, { "code": null, "e": 24672, "s": 24466, "text": "Until and unless an overriding class has specified a concurrent modification policy, the operation cannot modify the underlying source of elements so we can say that behavior of this method is unspecified." }, { "code": null, "e": 24717, "s": 24672, "text": "Retrieving Elements from Collection in Java." }, { "code": null, "e": 24725, "s": 24717, "text": "Syntax:" }, { "code": null, "e": 24773, "s": 24725, "text": "public void forEach(Consumer<? super E> action)" }, { "code": null, "e": 24883, "s": 24773, "text": "Parameter: This method takes a parameter action which represents the action to be performed for each element." }, { "code": null, "e": 24931, "s": 24883, "text": "Returns: This method does not returns anything." }, { "code": null, "e": 25015, "s": 24931, "text": "Exception: This method throws NullPointerException if the specified action is null." }, { "code": null, "e": 25072, "s": 25015, "text": "Below programs illustrate forEach() method of ArrayList:" }, { "code": null, "e": 25170, "s": 25072, "text": "Program 1: Program to demonstrate forEach() method on ArrayList which contains a list of Numbers." }, { "code": "// Java Program Demonstrate forEach()// method of ArrayList import java.util.*;public class GFG { public static void main(String[] args) { // create an ArrayList which going to // contains a list of Numbers ArrayList<Integer> Numbers = new ArrayList<Integer>(); // Add Number to list Numbers.add(23); Numbers.add(32); Numbers.add(45); Numbers.add(63); // forEach method of ArrayList and // print numbers Numbers.forEach((n) -> System.out.println(n)); }}", "e": 25717, "s": 25170, "text": null }, { "code": null, "e": 25730, "s": 25717, "text": "23\n32\n45\n63\n" }, { "code": null, "e": 25833, "s": 25730, "text": "Program 2: Program to demonstrate forEach() method on ArrayList which contains list of Students Names." }, { "code": "// Java Program Demonstrate forEach()// method of ArrayList import java.util.*;public class GFG { public static void main(String[] args) { // create an ArrayList which going to // contains a list of Student names which is actually // string values ArrayList<String> students = new ArrayList<String>(); // Add Strings to list // each string represents student name students.add(\"Ram\"); students.add(\"Mohan\"); students.add(\"Sohan\"); students.add(\"Rabi\"); // print result System.out.println(\"list of Students:\"); // forEach method of ArrayList and // print student names students.forEach((n) -> print(n)); } // printing student name public static void print(String n) { System.out.println(\"Student Name is \" + n); }}", "e": 26691, "s": 25833, "text": null }, { "code": null, "e": 26795, "s": 26691, "text": "list of Students:\nStudent Name is Ram\nStudent Name is Mohan\nStudent Name is Sohan\nStudent Name is Rabi\n" }, { "code": null, "e": 26911, "s": 26795, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/ArrayList.html#forEach(java.util.function.Consumer)" }, { "code": null, "e": 26931, "s": 26911, "text": "Java - util package" }, { "code": null, "e": 26946, "s": 26931, "text": "Java-ArrayList" }, { "code": null, "e": 26963, "s": 26946, "text": "Java-Collections" }, { "code": null, "e": 26978, "s": 26963, "text": "Java-Functions" }, { "code": null, "e": 26983, "s": 26978, "text": "Java" }, { "code": null, "e": 26988, "s": 26983, "text": "Java" }, { "code": null, "e": 27005, "s": 26988, "text": "Java-Collections" }, { "code": null, "e": 27103, "s": 27005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27122, "s": 27103, "text": "Interfaces in Java" }, { "code": null, "e": 27137, "s": 27122, "text": "Stream In Java" }, { "code": null, "e": 27161, "s": 27137, "text": "Singleton Class in Java" }, { "code": null, "e": 27173, "s": 27161, "text": "Set in Java" }, { "code": null, "e": 27192, "s": 27173, "text": "Overriding in Java" }, { "code": null, "e": 27211, "s": 27192, "text": "LinkedList in Java" }, { "code": null, "e": 27231, "s": 27211, "text": "Collections in Java" }, { "code": null, "e": 27259, "s": 27231, "text": "Initializing a List in Java" }, { "code": null, "e": 27283, "s": 27259, "text": "Queue Interface In Java" } ]
Python | Pandas dataframe.clip()
16 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.clip() is used to trim values at specified input threshold. We can use this function to put a lower limit and upper limit on the values that any cell can have in the dataframe. Syntax: DataFrame.clip(lower=None, upper=None, axis=None, inplace=False, *args, **kwargs) Parameters:lower : Minimum threshold value. All values below this threshold will be set to it.upper : Maximum threshold value. All values above this threshold will be set to it.axis : Align object with lower and upper along the given axis.inplace : Whether to perform the operation in place on the data.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy. Example #1: Use clip() function to trim values of a data frame below and above a given threshold value. # importing pandas as pdimport pandas as pd # Creating a dataframe using dictionarydf = pd.DataFrame({"A":[-5, 8, 12, -9, 5, 3], "B":[-1, -4, 6, 4, 11, 3], "C":[11, 4, -8, 7, 3, -2]}) # Printing the data frame for visualizationdf Now trim all the values below -4 to -4 and all the values above 9 to 9. Values in-between -4 and 9 remaining the same. # Clip in range (-4, 9)df.clip(-4, 9) Output : Notice, there is not any value in the data frame greater than 9 and smaller than -4 Example #2: Use clip() function to clips using specific lower and upper thresholds per column element in the dataframe. # importing pandas as pdimport pandas as pd # Creating a dataframe using dictionary df = pd.DataFrame({"A":[-5, 8, 12, -9, 5, 3], "B":[-1, -4, 6, 4, 11, 3], "C":[11, 4, -8, 7, 3, -2]}) # Printing the dataframedf when axis=0, then the value will be clipped across the rows. We are going to provide upper and lower threshold for all the column element (i.e. equivalent to the no. of rows) Creating a Series to store the lower and upper threshold value for each column element. # lower limit for each individual column element.lower_limit = pd.Series([1, -3, 2, 3, -2, -1]) # upper limit for each individual column element.upper_limit = lower_limit + 5 # Print lower_limitlower_limit # Print upper_limitupper_limit Output : Now we want to apply these limits on the dataframe. # applying different limit value for each column elementdf.clip(lower_limit, upper_limit, axis = 0) Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python 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 Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 436, "s": 242, "text": "Pandas dataframe.clip() is used to trim values at specified input threshold. We can use this function to put a lower limit and upper limit on the values that any cell can have in the dataframe." }, { "code": null, "e": 526, "s": 436, "text": "Syntax: DataFrame.clip(lower=None, upper=None, axis=None, inplace=False, *args, **kwargs)" }, { "code": null, "e": 934, "s": 526, "text": "Parameters:lower : Minimum threshold value. All values below this threshold will be set to it.upper : Maximum threshold value. All values above this threshold will be set to it.axis : Align object with lower and upper along the given axis.inplace : Whether to perform the operation in place on the data.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with numpy." }, { "code": null, "e": 1038, "s": 934, "text": "Example #1: Use clip() function to trim values of a data frame below and above a given threshold value." }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dataframe using dictionarydf = pd.DataFrame({\"A\":[-5, 8, 12, -9, 5, 3], \"B\":[-1, -4, 6, 4, 11, 3], \"C\":[11, 4, -8, 7, 3, -2]}) # Printing the data frame for visualizationdf", "e": 1306, "s": 1038, "text": null }, { "code": null, "e": 1425, "s": 1306, "text": "Now trim all the values below -4 to -4 and all the values above 9 to 9. Values in-between -4 and 9 remaining the same." }, { "code": "# Clip in range (-4, 9)df.clip(-4, 9)", "e": 1463, "s": 1425, "text": null }, { "code": null, "e": 1472, "s": 1463, "text": "Output :" }, { "code": null, "e": 1676, "s": 1472, "text": "Notice, there is not any value in the data frame greater than 9 and smaller than -4 Example #2: Use clip() function to clips using specific lower and upper thresholds per column element in the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dataframe using dictionary df = pd.DataFrame({\"A\":[-5, 8, 12, -9, 5, 3], \"B\":[-1, -4, 6, 4, 11, 3], \"C\":[11, 4, -8, 7, 3, -2]}) # Printing the dataframedf", "e": 1927, "s": 1676, "text": null }, { "code": null, "e": 2102, "s": 1927, "text": "when axis=0, then the value will be clipped across the rows. We are going to provide upper and lower threshold for all the column element (i.e. equivalent to the no. of rows)" }, { "code": null, "e": 2190, "s": 2102, "text": "Creating a Series to store the lower and upper threshold value for each column element." }, { "code": "# lower limit for each individual column element.lower_limit = pd.Series([1, -3, 2, 3, -2, -1]) # upper limit for each individual column element.upper_limit = lower_limit + 5 # Print lower_limitlower_limit # Print upper_limitupper_limit", "e": 2430, "s": 2190, "text": null }, { "code": null, "e": 2439, "s": 2430, "text": "Output :" }, { "code": null, "e": 2491, "s": 2439, "text": "Now we want to apply these limits on the dataframe." }, { "code": "# applying different limit value for each column elementdf.clip(lower_limit, upper_limit, axis = 0)", "e": 2591, "s": 2491, "text": null }, { "code": null, "e": 2600, "s": 2591, "text": "Output :" }, { "code": null, "e": 2624, "s": 2600, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2656, "s": 2624, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2670, "s": 2656, "text": "Python-pandas" }, { "code": null, "e": 2677, "s": 2670, "text": "Python" }, { "code": null, "e": 2775, "s": 2677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2793, "s": 2775, "text": "Python Dictionary" }, { "code": null, "e": 2835, "s": 2793, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2857, "s": 2835, "text": "Enumerate() in Python" }, { "code": null, "e": 2892, "s": 2857, "text": "Read a file line by line in Python" }, { "code": null, "e": 2918, "s": 2892, "text": "Python String | replace()" }, { "code": null, "e": 2950, "s": 2918, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2979, "s": 2950, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3006, "s": 2979, "text": "Python Classes and Objects" }, { "code": null, "e": 3036, "s": 3006, "text": "Iterate over a list in Python" } ]
Incremental Compiler in Compiler Design
26 Aug, 2020 Incremental Compiler is a compiler that generates code for a statement, or group of statements, which is independent of the code generated for other statements. Examples :C/C++ GNU Compiler, Java eclipse platform, etc. The Incremental Compiler is such a compilation scheme in which only modified source text gets recompiled and merged with previously compiled code to form a new target code. Thus incremental compiler avoid recompilation of the whole source code on some modification. Rather only modified portion of source program gets compiled. Code --> Compilation New code --> New Compilation (Previous (Previous Compilation + Code + Changes) compilation of modified part) Need of Incremental Compiler :Much of a programmer’s time is spent in an edit-compile-debug workflow as following. you make a small change (often in a single module or even function). you let the compiler translate the code into a binary, and finally. you run the program or a bunch of unit tests in order to see results of the change. This will increase the time of compilation at every step of change. But this can be overcome with the concept of incremental compiler (save the previous compilation and compile the modified part of the code). How can this concept (concept of incremented compilation) be implemented :We have already heard that computing something incrementally means updating only those parts of the computation’s output that need to be adapted in response to a given change in the computation’s inputs. One basic strategy we can employ to achieve this is to view one big computation (like compiling a program) as a composite of many smaller, interrelated computations that build upon each other. Each of those smaller computations will yield an intermediate result that can be cached and hopefully re-used in a later iteration, sparing us the need to re-compute that particular intermediate result again. Features of incremental compiler : During program development process modifications to Source program can cause recompilation of whole source text. This overhead is reduced in incremental compiler. Run time errors can be patched up just like compile time errors by keeping program modification as it is. The compilation process is faster. The memory used is less. Handling batch programs become very flexible using Incremental compiler. In incremental compiler program structure table is maintained for memory allocation of target code. When a new statement is compiled the new entry for it is created in program structure table. Thus memory allocation required for incremental compiler need not be contiguous. Helps in tracking the dependencies on source program. Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design Compiler construction tools Basic Blocks in Compiler Design Token, Patterns, and Lexems Compiler Design - Variants of Syntax Tree Loop Optimization in Compiler Design
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2020" }, { "code": null, "e": 189, "s": 28, "text": "Incremental Compiler is a compiler that generates code for a statement, or group of statements, which is independent of the code generated for other statements." }, { "code": null, "e": 247, "s": 189, "text": "Examples :C/C++ GNU Compiler, Java eclipse platform, etc." }, { "code": null, "e": 575, "s": 247, "text": "The Incremental Compiler is such a compilation scheme in which only modified source text gets recompiled and merged with previously compiled code to form a new target code. Thus incremental compiler avoid recompilation of the whole source code on some modification. Rather only modified portion of source program gets compiled." }, { "code": null, "e": 795, "s": 575, "text": "Code --> Compilation\nNew code --> New Compilation \n\n(Previous (Previous Compilation + \nCode + Changes) compilation of modified part) \n" }, { "code": null, "e": 910, "s": 795, "text": "Need of Incremental Compiler :Much of a programmer’s time is spent in an edit-compile-debug workflow as following." }, { "code": null, "e": 979, "s": 910, "text": "you make a small change (often in a single module or even function)." }, { "code": null, "e": 1047, "s": 979, "text": "you let the compiler translate the code into a binary, and finally." }, { "code": null, "e": 1131, "s": 1047, "text": "you run the program or a bunch of unit tests in order to see results of the change." }, { "code": null, "e": 1340, "s": 1131, "text": "This will increase the time of compilation at every step of change. But this can be overcome with the concept of incremental compiler (save the previous compilation and compile the modified part of the code)." }, { "code": null, "e": 2020, "s": 1340, "text": "How can this concept (concept of incremented compilation) be implemented :We have already heard that computing something incrementally means updating only those parts of the computation’s output that need to be adapted in response to a given change in the computation’s inputs. One basic strategy we can employ to achieve this is to view one big computation (like compiling a program) as a composite of many smaller, interrelated computations that build upon each other. Each of those smaller computations will yield an intermediate result that can be cached and hopefully re-used in a later iteration, sparing us the need to re-compute that particular intermediate result again." }, { "code": null, "e": 2055, "s": 2020, "text": "Features of incremental compiler :" }, { "code": null, "e": 2218, "s": 2055, "text": "During program development process modifications to Source program can cause recompilation of whole source text. This overhead is reduced in incremental compiler." }, { "code": null, "e": 2324, "s": 2218, "text": "Run time errors can be patched up just like compile time errors by keeping program modification as it is." }, { "code": null, "e": 2359, "s": 2324, "text": "The compilation process is faster." }, { "code": null, "e": 2384, "s": 2359, "text": "The memory used is less." }, { "code": null, "e": 2457, "s": 2384, "text": "Handling batch programs become very flexible using Incremental compiler." }, { "code": null, "e": 2731, "s": 2457, "text": "In incremental compiler program structure table is maintained for memory allocation of target code. When a new statement is compiled the new entry for it is created in program structure table. Thus memory allocation required for incremental compiler need not be contiguous." }, { "code": null, "e": 2785, "s": 2731, "text": "Helps in tracking the dependencies on source program." }, { "code": null, "e": 2801, "s": 2785, "text": "Compiler Design" }, { "code": null, "e": 2899, "s": 2801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2957, "s": 2899, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 2990, "s": 2957, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 3021, "s": 2990, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 3091, "s": 3021, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 3131, "s": 3091, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 3159, "s": 3131, "text": "Compiler construction tools" }, { "code": null, "e": 3191, "s": 3159, "text": "Basic Blocks in Compiler Design" }, { "code": null, "e": 3219, "s": 3191, "text": "Token, Patterns, and Lexems" }, { "code": null, "e": 3261, "s": 3219, "text": "Compiler Design - Variants of Syntax Tree" } ]
How to create an empty DataFrame and append rows & columns to it in Pandas?
02 Jul, 2020 Let’s discuss how to create an empty DataFrame and append rows & columns to it in Pandas. There are multiple ways in which we can do this task. Method #1: Create a complete empty DataFrame without any column name or indices and then appending columns one by one to it. # import pandas library as pdimport pandas as pd # create an Empty DataFrame objectdf = pd.DataFrame() print(df) # append columns to an empty DataFramedf['Name'] = ['Ankit', 'Ankita', 'Yashvardhan']df['Articles'] = [97, 600, 200]df['Improved'] = [2200, 75, 100] df Output: Method #2: Create an empty DataFrame with columns name only then appending rows one by one to it using append() method. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. # import pandas library as pdimport pandas as pd # create an Empty DataFrame# object With column names onlydf = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'])print(df) # append rows to an empty DataFramedf = df.append({'Name' : 'Ankit', 'Articles' : 97, 'Improved' : 2200}, ignore_index = True)df = df.append({'Name' : 'Aishwary', 'Articles' : 30, 'Improved' : 50}, ignore_index = True)df = df.append({'Name' : 'yash', 'Articles' : 17, 'Improved' : 220}, ignore_index = True) df Output: Method #3: Create an empty DataFrame with a column name and indices and then appending rows one by one to it using loc[] method. # import pandas library as pdimport pandas as pd # create an Empty DataFrame object With# column names and indices df = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'], index = ['a', 'b', 'c']) print("Empty DataFrame With NaN values : \n\n", df) # adding rows to an empty # dataframe at existing indexdf.loc['a'] = ['Ankita', 50, 100]df.loc['b'] = ['Ankit', 60, 120]df.loc['c'] = ['Harsh', 30, 60] df Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jul, 2020" }, { "code": null, "e": 172, "s": 28, "text": "Let’s discuss how to create an empty DataFrame and append rows & columns to it in Pandas. There are multiple ways in which we can do this task." }, { "code": null, "e": 297, "s": 172, "text": "Method #1: Create a complete empty DataFrame without any column name or indices and then appending columns one by one to it." }, { "code": "# import pandas library as pdimport pandas as pd # create an Empty DataFrame objectdf = pd.DataFrame() print(df) # append columns to an empty DataFramedf['Name'] = ['Ankit', 'Ankita', 'Yashvardhan']df['Articles'] = [97, 600, 200]df['Improved'] = [2200, 75, 100] df", "e": 566, "s": 297, "text": null }, { "code": null, "e": 574, "s": 566, "text": "Output:" }, { "code": null, "e": 694, "s": 574, "text": "Method #2: Create an empty DataFrame with columns name only then appending rows one by one to it using append() method." }, { "code": null, "e": 703, "s": 694, "text": "Chapters" }, { "code": null, "e": 730, "s": 703, "text": "descriptions off, selected" }, { "code": null, "e": 780, "s": 730, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 803, "s": 780, "text": "captions off, selected" }, { "code": null, "e": 811, "s": 803, "text": "English" }, { "code": null, "e": 835, "s": 811, "text": "This is a modal window." }, { "code": null, "e": 904, "s": 835, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 926, "s": 904, "text": "End of dialog window." }, { "code": "# import pandas library as pdimport pandas as pd # create an Empty DataFrame# object With column names onlydf = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'])print(df) # append rows to an empty DataFramedf = df.append({'Name' : 'Ankit', 'Articles' : 97, 'Improved' : 2200}, ignore_index = True)df = df.append({'Name' : 'Aishwary', 'Articles' : 30, 'Improved' : 50}, ignore_index = True)df = df.append({'Name' : 'yash', 'Articles' : 17, 'Improved' : 220}, ignore_index = True) df", "e": 1463, "s": 926, "text": null }, { "code": null, "e": 1471, "s": 1463, "text": "Output:" }, { "code": null, "e": 1600, "s": 1471, "text": "Method #3: Create an empty DataFrame with a column name and indices and then appending rows one by one to it using loc[] method." }, { "code": "# import pandas library as pdimport pandas as pd # create an Empty DataFrame object With# column names and indices df = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'], index = ['a', 'b', 'c']) print(\"Empty DataFrame With NaN values : \\n\\n\", df) # adding rows to an empty # dataframe at existing indexdf.loc['a'] = ['Ankita', 50, 100]df.loc['b'] = ['Ankit', 60, 120]df.loc['c'] = ['Harsh', 30, 60] df", "e": 2032, "s": 1600, "text": null }, { "code": null, "e": 2040, "s": 2032, "text": "Output:" }, { "code": null, "e": 2064, "s": 2040, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2078, "s": 2064, "text": "Python-pandas" }, { "code": null, "e": 2085, "s": 2078, "text": "Python" }, { "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": 2201, "s": 2183, "text": "Python Dictionary" }, { "code": null, "e": 2243, "s": 2201, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2265, "s": 2243, "text": "Enumerate() in Python" }, { "code": null, "e": 2297, "s": 2265, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2326, "s": 2297, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2353, "s": 2326, "text": "Python Classes and Objects" }, { "code": null, "e": 2389, "s": 2353, "text": "Convert integer to string in Python" }, { "code": null, "e": 2410, "s": 2389, "text": "Python OOPs Concepts" }, { "code": null, "e": 2433, "s": 2410, "text": "Introduction To PYTHON" } ]
Create And Deploy A Stock Price Web Application using Python and Streamlit
12 Nov, 2021 In this article, we are going to see how to create and deploy a stock price web application. To create an amazing Web Application that deals with Data Science, we have a perfect platform to carry out this task. Streamlit and Python package builds and shares the data application in the fastest way possible. Streamlit is open source anyone can contribute to it but first install Streamlit locally. pip install streamlit Streamlit ensures the fastest way to build and share data apps. Stock is always going to be the trending matter for years to speak. Everyone with a good income likes to invest in the Stock market. A Stock Market is a place where shares of pubic listed companies are traded. Since we are dealing with Stock Price details, we might require Web Scrap the details. But to our recuse, there is one such Python library that deals with the stock price. Yahoo Finance in short finance works with online advertising companies to provide you with advertising that is as relevant and useful as possible. pip install yfinance First import the necessary modules required for the Web Application. import streamlit as st import yfinance as finance You need to know the basic syntax of Markdown to display text on Web App. You can check this Introduction to Markdown and get started. Once you get familiar with Markdown language displaying messages using Streamlit becomes an easy task. Set the title name, sidebar header, and Subheading: st.title("Build and Deploy Stock Market App Using Streamlit") st.header("A Basic Data Science Web Application") st.sidebar.header("Geeksforgeeks \n TrueGeeks") The actual part of the code begins now. Since we will be analyzing the Google and Microsoft stock prices, initialize the ticker attribute, and get the history of GOOGL and MSFT for the past one month. yfinance allows you to check the updates over a certain period of time. yfinance returns pandas.DataFrame with multi-level column names, with a level for the ticker and a level for the stock price data. You can check the below code that displays the heading, data, summary information about the company, and plot an amazing graph. yfinace.download displays tabular data that includes Open, High, Low, Closing, and Volume data at different time intervals. Once you have initialized the ticker you check the detailed information about the ticker that includes the long summary, the total number of employees, the state and country name, the revenue growth, and much more information. We have used the most important commands for this web application you can check the below code. Python import streamlit as stimport yfinance as finance def get_ticker(name): company = finance.Ticker(name) # google return company # Project Detailsst.title("Build and Deploy Stock Market App Using Streamlit")st.header("A Basic Data Science Web Application")st.sidebar.header("Geeksforgeeks \n TrueGeeks") company1 = get_ticker("GOOGL")company2 = get_ticker("MSFT") # fetches the data: Open, Close, High, Low and Volumegoogle = finance.download("GOOGL", start="2021-10-01", end="2021-10-01")microsoft = finance.download("MSFT", start="2021-10-01", end="2021-10-01") # Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,maxdata1 = company1.history(period="3mo")data2 = company2.history(period="3mo") # markdown syntaxst.write("""### Google""") # detailed summary on Googlest.write(company1.info['longBusinessSummary']) st.write(google) # plots the graphst.line_chart(data1.values) st.write("""### Microsoft""")st.write(company2.info['longBusinessSummary'], "\n", microsoft)st.line_chart(data2.values) streamlit run myapp.py Streamlit web applications can be deployed for direct use through various options available on the internet. There are different platforms on how you could deploy the Streamlit application. You can deploy your app using Heroku as well. Check the complete guide to deploy apps on Heroku. We will be looking into a direct method provided by Streamlit itself. The free Community tier is the perfect solution if your app is hosted in a public GitHub repo and you’d like anyone in the world to be able to access it. Before proceeding further you will require your own GitHub account where you will save your Web app. Once you have put your app on GitHub make sure you have added a requirement.txt file. This file will contain the necessary Python library which is required. You need to follow just three-step to deploy your app: Step 1: Create a Github Repository for your Streamlit app and then Sign-up (https://forms.streamlit.io/community-sign-up)to Streamlit Community. Step 2: You need to wait for 2 business days and then you can finally deploy your app. Open the mail which you will receive from the https://share.streamlit.io/ community and create a new app. Step 3: Next select the repo which you created at the first step. After selecting repo_name, Choose the branch name and main python file where you have saved your code. Once your app is deployed, you can find it with this URL: https://share.streamlit.io/[username]/[repo_name]/[default_branch_name]/[your_py_code_file_name] singghakshay Python-streamlit python-utility TrueGeek-2021 Python TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? How to Convert Char to String in Java? Basics of API Testing Using Postman Types of Internet Protocols
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2021" }, { "code": null, "e": 121, "s": 28, "text": "In this article, we are going to see how to create and deploy a stock price web application." }, { "code": null, "e": 337, "s": 121, "text": "To create an amazing Web Application that deals with Data Science, we have a perfect platform to carry out this task. Streamlit and Python package builds and shares the data application in the fastest way possible. " }, { "code": null, "e": 427, "s": 337, "text": "Streamlit is open source anyone can contribute to it but first install Streamlit locally." }, { "code": null, "e": 449, "s": 427, "text": "pip install streamlit" }, { "code": null, "e": 1042, "s": 449, "text": "Streamlit ensures the fastest way to build and share data apps. Stock is always going to be the trending matter for years to speak. Everyone with a good income likes to invest in the Stock market. A Stock Market is a place where shares of pubic listed companies are traded. Since we are dealing with Stock Price details, we might require Web Scrap the details. But to our recuse, there is one such Python library that deals with the stock price. Yahoo Finance in short finance works with online advertising companies to provide you with advertising that is as relevant and useful as possible." }, { "code": null, "e": 1063, "s": 1042, "text": "pip install yfinance" }, { "code": null, "e": 1132, "s": 1063, "text": "First import the necessary modules required for the Web Application." }, { "code": null, "e": 1182, "s": 1132, "text": "import streamlit as st\nimport yfinance as finance" }, { "code": null, "e": 1420, "s": 1182, "text": "You need to know the basic syntax of Markdown to display text on Web App. You can check this Introduction to Markdown and get started. Once you get familiar with Markdown language displaying messages using Streamlit becomes an easy task." }, { "code": null, "e": 1472, "s": 1420, "text": "Set the title name, sidebar header, and Subheading:" }, { "code": null, "e": 1632, "s": 1472, "text": "st.title(\"Build and Deploy Stock Market App Using Streamlit\")\nst.header(\"A Basic Data Science Web Application\")\nst.sidebar.header(\"Geeksforgeeks \\n TrueGeeks\")" }, { "code": null, "e": 1835, "s": 1632, "text": "The actual part of the code begins now. Since we will be analyzing the Google and Microsoft stock prices, initialize the ticker attribute, and get the history of GOOGL and MSFT for the past one month. " }, { "code": null, "e": 2166, "s": 1835, "text": "yfinance allows you to check the updates over a certain period of time. yfinance returns pandas.DataFrame with multi-level column names, with a level for the ticker and a level for the stock price data. You can check the below code that displays the heading, data, summary information about the company, and plot an amazing graph." }, { "code": null, "e": 2518, "s": 2166, "text": "yfinace.download displays tabular data that includes Open, High, Low, Closing, and Volume data at different time intervals. Once you have initialized the ticker you check the detailed information about the ticker that includes the long summary, the total number of employees, the state and country name, the revenue growth, and much more information. " }, { "code": null, "e": 2614, "s": 2518, "text": "We have used the most important commands for this web application you can check the below code." }, { "code": null, "e": 2621, "s": 2614, "text": "Python" }, { "code": "import streamlit as stimport yfinance as finance def get_ticker(name): company = finance.Ticker(name) # google return company # Project Detailsst.title(\"Build and Deploy Stock Market App Using Streamlit\")st.header(\"A Basic Data Science Web Application\")st.sidebar.header(\"Geeksforgeeks \\n TrueGeeks\") company1 = get_ticker(\"GOOGL\")company2 = get_ticker(\"MSFT\") # fetches the data: Open, Close, High, Low and Volumegoogle = finance.download(\"GOOGL\", start=\"2021-10-01\", end=\"2021-10-01\")microsoft = finance.download(\"MSFT\", start=\"2021-10-01\", end=\"2021-10-01\") # Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,maxdata1 = company1.history(period=\"3mo\")data2 = company2.history(period=\"3mo\") # markdown syntaxst.write(\"\"\"### Google\"\"\") # detailed summary on Googlest.write(company1.info['longBusinessSummary']) st.write(google) # plots the graphst.line_chart(data1.values) st.write(\"\"\"### Microsoft\"\"\")st.write(company2.info['longBusinessSummary'], \"\\n\", microsoft)st.line_chart(data2.values)", "e": 3625, "s": 2621, "text": null }, { "code": null, "e": 3649, "s": 3625, "text": " streamlit run myapp.py" }, { "code": null, "e": 3936, "s": 3649, "text": "Streamlit web applications can be deployed for direct use through various options available on the internet. There are different platforms on how you could deploy the Streamlit application. You can deploy your app using Heroku as well. Check the complete guide to deploy apps on Heroku." }, { "code": null, "e": 4419, "s": 3936, "text": "We will be looking into a direct method provided by Streamlit itself. The free Community tier is the perfect solution if your app is hosted in a public GitHub repo and you’d like anyone in the world to be able to access it. Before proceeding further you will require your own GitHub account where you will save your Web app. Once you have put your app on GitHub make sure you have added a requirement.txt file. This file will contain the necessary Python library which is required. " }, { "code": null, "e": 4474, "s": 4419, "text": "You need to follow just three-step to deploy your app:" }, { "code": null, "e": 4620, "s": 4474, "text": "Step 1: Create a Github Repository for your Streamlit app and then Sign-up (https://forms.streamlit.io/community-sign-up)to Streamlit Community. " }, { "code": null, "e": 4813, "s": 4620, "text": "Step 2: You need to wait for 2 business days and then you can finally deploy your app. Open the mail which you will receive from the https://share.streamlit.io/ community and create a new app." }, { "code": null, "e": 4982, "s": 4813, "text": "Step 3: Next select the repo which you created at the first step. After selecting repo_name, Choose the branch name and main python file where you have saved your code." }, { "code": null, "e": 5040, "s": 4982, "text": "Once your app is deployed, you can find it with this URL:" }, { "code": null, "e": 5137, "s": 5040, "text": "https://share.streamlit.io/[username]/[repo_name]/[default_branch_name]/[your_py_code_file_name]" }, { "code": null, "e": 5150, "s": 5137, "text": "singghakshay" }, { "code": null, "e": 5167, "s": 5150, "text": "Python-streamlit" }, { "code": null, "e": 5182, "s": 5167, "text": "python-utility" }, { "code": null, "e": 5196, "s": 5182, "text": "TrueGeek-2021" }, { "code": null, "e": 5203, "s": 5196, "text": "Python" }, { "code": null, "e": 5212, "s": 5203, "text": "TrueGeek" }, { "code": null, "e": 5310, "s": 5212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5342, "s": 5310, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5369, "s": 5342, "text": "Python Classes and Objects" }, { "code": null, "e": 5390, "s": 5369, "text": "Python OOPs Concepts" }, { "code": null, "e": 5413, "s": 5390, "text": "Introduction To PYTHON" }, { "code": null, "e": 5469, "s": 5413, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5514, "s": 5469, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 5571, "s": 5514, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 5610, "s": 5571, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 5646, "s": 5610, "text": "Basics of API Testing Using Postman" } ]
How to create a menu using navbar-inverse in Bootstrap ?
10 Oct, 2021 In this article, we will learn how to create a menu using the navbar-inverse in Bootstrap & will also understand its implementation through the example. The menu bar is a very important part while making a navigation bar for the website. We can create a menu bar along with inverse the color of the menu bar using the Bootstrap navbar-inverse class. The navbar in Bootstrap contains many classes such as: .navbar-brand class: This class is used for your company, product, or project name, or any brand name. .navbar-nav class: This class is used for full-height and lightweight navigation (including support for dropdowns). .navbar-toggler class: This class is used for the collapse plugin and other navigation toggling behaviors. .navbar-text class: This class is used for adding vertically centered strings of text. .collapse.navbar-collapse class: This class is used for grouping and hiding navbar contents by a parent breakpoint. The flex and spacing utility classes are used for any form controls and actions. We will understand the above classes & their usage through the example. Let’s see how to implement navbar using Bootstrap. Step 1: Import the Bootstrap CDN links inside our HTML file. <!– Bootstrap compiled and minified CSS –><link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css” integrity=”sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu” crossorigin=”anonymous”/> <!– Bootstrap compiled and minified JavaScript –><script src=”https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js” integrity=”sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd” crossorigin=”anonymous”></script> Step 2: Add the <nav> tag inside your <body> with the navbar and navbar-default classes inside in it. <nav class="navbar navbar-default "> <!-- content --> </nav> Step 3: Create a <nav> tag with a class name as navbar navbar-default, & inside of <nav> tag, we will create a <div> with class name as “container-fluid”. Now, in order to use the brand logo or name, we will add a class as navbar-brand, and inside it, create a <ul> tag with a class name as “nav navbar-nav”, followed by the list of the item using the<li> tag. <nav class="navbar navbar-default"> <div class="container-fluid"> <a class="navbar-brand" href="#">GeekforGeeks</a> <ul class="nav navbar-nav"> <li class="active"><a href="#">Web Technology </a></li> <li><a href="#">Data Structure</a></li> <li><a href="#">Algorithm</a></li> <li><a href="#">Competitive Programming</a></li> <li><a href="#">Programming Languages</a></li> </ul> </div> </nav> At this stage, we have created a basic navigation bar using Bootstrap. The below code example illustrates the basic navbar in Bootstrap. Complete Code: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous" /> <title>GeeksforGeeks Bootstrap Tutorial</title> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <a class="navbar-brand" href="#">GeekforGeeks</a> <ul class="nav navbar-nav"> <li class="active"><a href="#">Web Technology </a></li> <li><a href="#">Data Structure</a></li> <li><a href="#">Algorithm</a></li> <li><a href="#">Competitive Programming</a></li> <li><a href="#">Programming Languages</a></li> </ul> </div> </nav> </body></html> Output: Simple Navigation Bar in Bootstrap From the above output, we can see that the menu-bar is having a white background and if we need to change the background to black and other text content to white, we can simply add the ‘.navbar-inverse’ class in the <nav> tag as shown below. <nav class="navbar navbar-default navbar-inverse"> <!-- Content --> </nav> Example: This example illustrates the use of the .navbar-inverse class for changing the background to black in Bootstrap. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous" /> <title>GeeksforGeeks Bootstrap Tutorial</title> </head> <body> <nav class="navbar navbar-default navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href="#">GeekforGeeks</a> <ul class="nav navbar-nav"> <li class="active"><a href="#">Web Technology </a></li> <li><a href="#">Data Structure</a></li> <li><a href="#">Algorithm</a></li> <li><a href="#">Competitive Programming</a></li> <li><a href="#">Programming Languages</a></li> </ul> </div> </nav> </body></html> Output: After adding navbar-inverse, the navbar turns black As you can clearly see from the above output, the color is changed to black and fonts become white. Thus, we have successfully created a basic navigation bar using Bootstrap using the “navbar-inverse” class. Now, we can also add several features like dropdowns and search options inside our navigation bar. In order to make a drop-down menu, we will be using the below code: <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Link1</a></li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> </ul> </div> For placing the search option to the right in the navbar, we will use the below code snippet: <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" /> </div> <button type="submit" class="btn btn-default">Submit </button> </form> At this point, we have made the updated navbar code after adding more features like drop-down and search bar. Complete Code: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous" /> <title>GeeksforGeeks Bootstrap Navbar Tutorial</title> </head> <body> <nav class="navbar navbar-default navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href="#">GeeksforGeeks</a> <ul class="nav navbar-nav"> <li class="active"><a href="#">Data Structure</a></li> <li><a href="#">Algorithm</a></li> <li><a href="#">Competitive Programming</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Web Technology<span class="caret"></span> </a> <ul class="dropdown-menu"> <li> <a href="#">HTML</a> </li> <li> <a href="#">CSS</a> </li> <li> <a href="#">JavaScript</a> </li> </ul> </li> </ul> <form class="navbar-form navbar-right"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" /> </div> <button type="submit" class="btn btn-default">Submit </button> </form> </div> </nav> </body></html> Output: Navbar after adding features like dropdown and search option NOTE: The class “.navbar-inverse” is now outdated. It is used in bootstrap to make the navbar dark till version 3.3.7. Now, the class “.bg-dark” is used to darken the components in the current version 5.0.0 & the previous version 4.6.1. Bootstrap-Questions HTML-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Oct, 2021" }, { "code": null, "e": 378, "s": 28, "text": "In this article, we will learn how to create a menu using the navbar-inverse in Bootstrap & will also understand its implementation through the example. The menu bar is a very important part while making a navigation bar for the website. We can create a menu bar along with inverse the color of the menu bar using the Bootstrap navbar-inverse class." }, { "code": null, "e": 433, "s": 378, "text": "The navbar in Bootstrap contains many classes such as:" }, { "code": null, "e": 536, "s": 433, "text": ".navbar-brand class: This class is used for your company, product, or project name, or any brand name." }, { "code": null, "e": 652, "s": 536, "text": ".navbar-nav class: This class is used for full-height and lightweight navigation (including support for dropdowns)." }, { "code": null, "e": 759, "s": 652, "text": ".navbar-toggler class: This class is used for the collapse plugin and other navigation toggling behaviors." }, { "code": null, "e": 846, "s": 759, "text": ".navbar-text class: This class is used for adding vertically centered strings of text." }, { "code": null, "e": 962, "s": 846, "text": ".collapse.navbar-collapse class: This class is used for grouping and hiding navbar contents by a parent breakpoint." }, { "code": null, "e": 1043, "s": 962, "text": "The flex and spacing utility classes are used for any form controls and actions." }, { "code": null, "e": 1166, "s": 1043, "text": "We will understand the above classes & their usage through the example. Let’s see how to implement navbar using Bootstrap." }, { "code": null, "e": 1227, "s": 1166, "text": "Step 1: Import the Bootstrap CDN links inside our HTML file." }, { "code": null, "e": 1482, "s": 1227, "text": "<!– Bootstrap compiled and minified CSS –><link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css” integrity=”sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu” crossorigin=”anonymous”/>" }, { "code": null, "e": 1734, "s": 1482, "text": "<!– Bootstrap compiled and minified JavaScript –><script src=”https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js” integrity=”sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd” crossorigin=”anonymous”></script>" }, { "code": null, "e": 1836, "s": 1734, "text": "Step 2: Add the <nav> tag inside your <body> with the navbar and navbar-default classes inside in it." }, { "code": null, "e": 1902, "s": 1836, "text": "<nav class=\"navbar navbar-default \">\n <!-- content -->\n</nav>" }, { "code": null, "e": 2263, "s": 1902, "text": "Step 3: Create a <nav> tag with a class name as navbar navbar-default, & inside of <nav> tag, we will create a <div> with class name as “container-fluid”. Now, in order to use the brand logo or name, we will add a class as navbar-brand, and inside it, create a <ul> tag with a class name as “nav navbar-nav”, followed by the list of the item using the<li> tag." }, { "code": null, "e": 2700, "s": 2263, "text": "<nav class=\"navbar navbar-default\">\n <div class=\"container-fluid\">\n <a class=\"navbar-brand\" href=\"#\">GeekforGeeks</a>\n <ul class=\"nav navbar-nav\">\n <li class=\"active\"><a href=\"#\">Web Technology </a></li>\n <li><a href=\"#\">Data Structure</a></li>\n <li><a href=\"#\">Algorithm</a></li>\n <li><a href=\"#\">Competitive Programming</a></li>\n <li><a href=\"#\">Programming Languages</a></li>\n </ul>\n </div>\n</nav>" }, { "code": null, "e": 2837, "s": 2700, "text": "At this stage, we have created a basic navigation bar using Bootstrap. The below code example illustrates the basic navbar in Bootstrap." }, { "code": null, "e": 2852, "s": 2837, "text": "Complete Code:" }, { "code": null, "e": 2857, "s": 2852, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu\" crossorigin=\"anonymous\" /> <title>GeeksforGeeks Bootstrap Tutorial</title> </head> <body> <nav class=\"navbar navbar-default\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"#\">GeekforGeeks</a> <ul class=\"nav navbar-nav\"> <li class=\"active\"><a href=\"#\">Web Technology </a></li> <li><a href=\"#\">Data Structure</a></li> <li><a href=\"#\">Algorithm</a></li> <li><a href=\"#\">Competitive Programming</a></li> <li><a href=\"#\">Programming Languages</a></li> </ul> </div> </nav> </body></html>", "e": 3900, "s": 2857, "text": null }, { "code": null, "e": 3908, "s": 3900, "text": "Output:" }, { "code": null, "e": 3943, "s": 3908, "text": "Simple Navigation Bar in Bootstrap" }, { "code": null, "e": 4185, "s": 3943, "text": "From the above output, we can see that the menu-bar is having a white background and if we need to change the background to black and other text content to white, we can simply add the ‘.navbar-inverse’ class in the <nav> tag as shown below." }, { "code": null, "e": 4264, "s": 4185, "text": "<nav class=\"navbar navbar-default navbar-inverse\">\n <!-- Content -->\n</nav>" }, { "code": null, "e": 4386, "s": 4264, "text": "Example: This example illustrates the use of the .navbar-inverse class for changing the background to black in Bootstrap." }, { "code": null, "e": 4391, "s": 4386, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu\" crossorigin=\"anonymous\" /> <title>GeeksforGeeks Bootstrap Tutorial</title> </head> <body> <nav class=\"navbar navbar-default navbar-inverse\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"#\">GeekforGeeks</a> <ul class=\"nav navbar-nav\"> <li class=\"active\"><a href=\"#\">Web Technology </a></li> <li><a href=\"#\">Data Structure</a></li> <li><a href=\"#\">Algorithm</a></li> <li><a href=\"#\">Competitive Programming</a></li> <li><a href=\"#\">Programming Languages</a></li> </ul> </div> </nav> </body></html>", "e": 5453, "s": 4391, "text": null }, { "code": null, "e": 5461, "s": 5453, "text": "Output:" }, { "code": null, "e": 5514, "s": 5461, "text": " After adding navbar-inverse, the navbar turns black" }, { "code": null, "e": 5821, "s": 5514, "text": "As you can clearly see from the above output, the color is changed to black and fonts become white. Thus, we have successfully created a basic navigation bar using Bootstrap using the “navbar-inverse” class. Now, we can also add several features like dropdowns and search options inside our navigation bar." }, { "code": null, "e": 5889, "s": 5821, "text": "In order to make a drop-down menu, we will be using the below code:" }, { "code": null, "e": 6310, "s": 5889, "text": "<div class=\"dropdown\">\n <button\n class=\"btn btn-default dropdown-toggle\"\n type=\"button\"\n id=\"dropdownMenu1\"\n data-toggle=\"dropdown\"\n aria-haspopup=\"true\"\n aria-expanded=\"true\">\n Dropdown\n <span class=\"caret\"></span>\n </button>\n \n <ul class=\"dropdown-menu\" aria-labelledby=\"dropdownMenu1\">\n <li><a href=\"#\">Link1</a></li>\n <li><a href=\"#\">Link2</a></li>\n <li><a href=\"#\">Link3</a></li>\n </ul>\n</div>" }, { "code": null, "e": 6404, "s": 6310, "text": "For placing the search option to the right in the navbar, we will use the below code snippet:" }, { "code": null, "e": 6662, "s": 6404, "text": "<form class=\"navbar-form navbar-right\" role=\"search\">\n <div class=\"form-group\">\n <input type=\"text\" class=\"form-control\" \n placeholder=\"Search\" />\n </div>\n <button type=\"submit\" \n class=\"btn btn-default\">Submit\n </button>\n</form>" }, { "code": null, "e": 6772, "s": 6662, "text": "At this point, we have made the updated navbar code after adding more features like drop-down and search bar." }, { "code": null, "e": 6787, "s": 6772, "text": "Complete Code:" }, { "code": null, "e": 6792, "s": 6787, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu\" crossorigin=\"anonymous\" /> <title>GeeksforGeeks Bootstrap Navbar Tutorial</title> </head> <body> <nav class=\"navbar navbar-default navbar-inverse\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"#\">GeeksforGeeks</a> <ul class=\"nav navbar-nav\"> <li class=\"active\"><a href=\"#\">Data Structure</a></li> <li><a href=\"#\">Algorithm</a></li> <li><a href=\"#\">Competitive Programming</a></li> <li class=\"dropdown\"> <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\"> Web Technology<span class=\"caret\"></span> </a> <ul class=\"dropdown-menu\"> <li> <a href=\"#\">HTML</a> </li> <li> <a href=\"#\">CSS</a> </li> <li> <a href=\"#\">JavaScript</a> </li> </ul> </li> </ul> <form class=\"navbar-form navbar-right\"> <div class=\"form-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Search\" /> </div> <button type=\"submit\" class=\"btn btn-default\">Submit </button> </form> </div> </nav> </body></html>", "e": 8682, "s": 6792, "text": null }, { "code": null, "e": 8690, "s": 8682, "text": "Output:" }, { "code": null, "e": 8751, "s": 8690, "text": "Navbar after adding features like dropdown and search option" }, { "code": null, "e": 8990, "s": 8751, "text": "NOTE: The class “.navbar-inverse” is now outdated. It is used in bootstrap to make the navbar dark till version 3.3.7. Now, the class “.bg-dark” is used to darken the components in the current version 5.0.0 & the previous version 4.6.1. " }, { "code": null, "e": 9010, "s": 8990, "text": "Bootstrap-Questions" }, { "code": null, "e": 9025, "s": 9010, "text": "HTML-Questions" }, { "code": null, "e": 9032, "s": 9025, "text": "Picked" }, { "code": null, "e": 9042, "s": 9032, "text": "Bootstrap" }, { "code": null, "e": 9059, "s": 9042, "text": "Web Technologies" }, { "code": null, "e": 9157, "s": 9059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9198, "s": 9157, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 9231, "s": 9198, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 9276, "s": 9231, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 9302, "s": 9276, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 9369, "s": 9302, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 9402, "s": 9369, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 9464, "s": 9402, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 9525, "s": 9464, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 9575, "s": 9525, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
numpy.repeat() in Python
28 Mar, 2022 The numpy.repeat() function repeats elements of the array – arr. Syntax : numpy.repeat(arr, repetitions, axis = None) Parameters : array : [array_like]Input array. repetitions : No. of repetitions of each array elements along the given axis. axis : Axis along which we want to repeat values. By default, it returns a flat output array. Return : An array with repetitions of array - arr elements as per repetitions, number of times we want to repeat arr Code 1 : Python # Python Program illustrating# numpy.repeat() import numpy as geek #Working on 1Darr = geek.arange(5)print("arr : \n", arr) repetitions = 2a = geek.repeat(arr, repetitions)print("\nRepeating arr 2 times : \n", a)print("Shape : ", a.shape) repetitions = 3a = geek.repeat(arr, repetitions)print("\nRepeating arr 3 times : \n", a)# [0 0 0 ..., 4 4 4] means [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]# since it was long output, so it uses [ ... ]print("Shape : ", a.shape) Output : arr : [0 1 2 3 4] Repeating arr 2 times : [0 0 1 1 2 2 3 3 4 4] Shape : (10,) Repeating arr 3 times : [0 0 0 ..., 4 4 4] Shape : (15,) Code 2 : Python # Python Program illustrating# numpy.repeat() import numpy as geek arr = geek.arange(6).reshape(2, 3)print("arr : \n", arr) repetitions = 2print("\nRepeating arr : \n", geek.repeat(arr, repetitions, 1))print("arr Shape : \n", geek.repeat(arr, repetitions).shape) repetitions = 2print("\nRepeating arr : \n", geek.repeat(arr, repetitions, 0))print("arr Shape : \n", geek.repeat(arr, repetitions).shape) repetitions = 3print("\nRepeating arr : \n", geek.repeat(arr, repetitions, 1))print("arr Shape : \n", geek.repeat(arr, repetitions).shape) Output : arr : [[0 1 2] [3 4 5]] Repeating arr : [[0 0 1 1 2 2] [3 3 4 4 5 5]] arr Shape : (12,) Repeating arr : [[0 1 2] [0 1 2] [3 4 5] [3 4 5]] arr Shape : (12,) Repeating arr : [[0 0 0 ..., 2 2 2] [3 3 3 ..., 5 5 5]] arr Shape : (18,) References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kothavvsaakash 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 | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON 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": 28, "s": 0, "text": "\n28 Mar, 2022" }, { "code": null, "e": 103, "s": 28, "text": "The numpy.repeat() function repeats elements of the array – arr. Syntax : " }, { "code": null, "e": 147, "s": 103, "text": "numpy.repeat(arr, repetitions, axis = None)" }, { "code": null, "e": 161, "s": 147, "text": "Parameters : " }, { "code": null, "e": 392, "s": 161, "text": "array : [array_like]Input array. \nrepetitions : No. of repetitions of each array elements along the given axis.\naxis : Axis along which we want to repeat values. By default, it returns \n a flat output array." }, { "code": null, "e": 402, "s": 392, "text": "Return : " }, { "code": null, "e": 513, "s": 402, "text": "An array with repetitions of array - arr elements as per repetitions, number of times \nwe want to repeat arr " }, { "code": null, "e": 523, "s": 513, "text": "Code 1 : " }, { "code": null, "e": 530, "s": 523, "text": "Python" }, { "code": "# Python Program illustrating# numpy.repeat() import numpy as geek #Working on 1Darr = geek.arange(5)print(\"arr : \\n\", arr) repetitions = 2a = geek.repeat(arr, repetitions)print(\"\\nRepeating arr 2 times : \\n\", a)print(\"Shape : \", a.shape) repetitions = 3a = geek.repeat(arr, repetitions)print(\"\\nRepeating arr 3 times : \\n\", a)# [0 0 0 ..., 4 4 4] means [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]# since it was long output, so it uses [ ... ]print(\"Shape : \", a.shape)", "e": 988, "s": 530, "text": null }, { "code": null, "e": 998, "s": 988, "text": "Output : " }, { "code": null, "e": 1143, "s": 998, "text": "arr : \n [0 1 2 3 4]\n\nRepeating arr 2 times : \n [0 0 1 1 2 2 3 3 4 4]\nShape : (10,)\n\nRepeating arr 3 times : \n [0 0 0 ..., 4 4 4]\nShape : (15,)" }, { "code": null, "e": 1153, "s": 1143, "text": "Code 2 : " }, { "code": null, "e": 1160, "s": 1153, "text": "Python" }, { "code": "# Python Program illustrating# numpy.repeat() import numpy as geek arr = geek.arange(6).reshape(2, 3)print(\"arr : \\n\", arr) repetitions = 2print(\"\\nRepeating arr : \\n\", geek.repeat(arr, repetitions, 1))print(\"arr Shape : \\n\", geek.repeat(arr, repetitions).shape) repetitions = 2print(\"\\nRepeating arr : \\n\", geek.repeat(arr, repetitions, 0))print(\"arr Shape : \\n\", geek.repeat(arr, repetitions).shape) repetitions = 3print(\"\\nRepeating arr : \\n\", geek.repeat(arr, repetitions, 1))print(\"arr Shape : \\n\", geek.repeat(arr, repetitions).shape)", "e": 1705, "s": 1160, "text": null }, { "code": null, "e": 1715, "s": 1705, "text": "Output : " }, { "code": null, "e": 1968, "s": 1715, "text": "arr : \n [[0 1 2]\n [3 4 5]]\n\nRepeating arr : \n [[0 0 1 1 2 2]\n [3 3 4 4 5 5]]\narr Shape : \n (12,)\n\nRepeating arr : \n [[0 1 2]\n [0 1 2]\n [3 4 5]\n [3 4 5]]\narr Shape : \n (12,)\n\nRepeating arr : \n [[0 0 0 ..., 2 2 2]\n [3 3 3 ..., 5 5 5]]\narr Shape : \n (18,)" }, { "code": null, "e": 2580, "s": 1968, "text": "References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2595, "s": 2580, "text": "kothavvsaakash" }, { "code": null, "e": 2626, "s": 2595, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2639, "s": 2626, "text": "Python-numpy" }, { "code": null, "e": 2646, "s": 2639, "text": "Python" }, { "code": null, "e": 2744, "s": 2646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2776, "s": 2744, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2803, "s": 2776, "text": "Python Classes and Objects" }, { "code": null, "e": 2834, "s": 2803, "text": "Python | os.path.join() method" }, { "code": null, "e": 2855, "s": 2834, "text": "Python OOPs Concepts" }, { "code": null, "e": 2911, "s": 2855, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2934, "s": 2911, "text": "Introduction To PYTHON" }, { "code": null, "e": 2976, "s": 2934, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3018, "s": 2976, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3057, "s": 3018, "text": "Python | datetime.timedelta() function" } ]
Motherboard parts – North Bridge
27 Sep, 2021 Motherboard comprises of many parts embedded in it. In this article, a part named North Bridge is being discussed. A motherboard has a chip set logic architecture consisting of two chipsets: 1. North Bridge 2. South Bridge We have explained here, only North Bridge. 1. North Bridge : North bridge is also called as Host Bridge. The north bridge is directly connected to the Central Processing Unit(CPU) for processing tasks that need the highest performance. These chip sets act as a medium for communication between the CPU and parts of motherboard thereby, Memory Controller Hub, being the other name for North Bridge. History : The name North bridge was derived while designing the architecture of the chip sets. It was designed in such way that the CPU would have a easy access for connecting parts of motherboard. Features : A north bridge communicates with processor via Front Side Bus or FSB for short. It controls the interaction with motherboard parts such as Accelerated Graphics Port (AGP), Peripheral Component Interconnect (PCI), and other crucial parts. Advantages : Easy communication is being established between parts of motherboard via North Bridge. Faster data transfer due to easy communication access. Disadvantages There is no major disadvantages. sumitgumber28 sagar0719kumar Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 220, "s": 28, "text": "Motherboard comprises of many parts embedded in it. In this article, a part named North Bridge is being discussed. A motherboard has a chip set logic architecture consisting of two chipsets: " }, { "code": null, "e": 253, "s": 220, "text": "1. North Bridge\n2. South Bridge " }, { "code": null, "e": 297, "s": 253, "text": "We have explained here, only North Bridge. " }, { "code": null, "e": 653, "s": 297, "text": "1. North Bridge : North bridge is also called as Host Bridge. The north bridge is directly connected to the Central Processing Unit(CPU) for processing tasks that need the highest performance. These chip sets act as a medium for communication between the CPU and parts of motherboard thereby, Memory Controller Hub, being the other name for North Bridge. " }, { "code": null, "e": 852, "s": 653, "text": "History : The name North bridge was derived while designing the architecture of the chip sets. It was designed in such way that the CPU would have a easy access for connecting parts of motherboard. " }, { "code": null, "e": 864, "s": 852, "text": "Features : " }, { "code": null, "e": 944, "s": 864, "text": "A north bridge communicates with processor via Front Side Bus or FSB for short." }, { "code": null, "e": 1102, "s": 944, "text": "It controls the interaction with motherboard parts such as Accelerated Graphics Port (AGP), Peripheral Component Interconnect (PCI), and other crucial parts." }, { "code": null, "e": 1116, "s": 1102, "text": "Advantages : " }, { "code": null, "e": 1203, "s": 1116, "text": "Easy communication is being established between parts of motherboard via North Bridge." }, { "code": null, "e": 1258, "s": 1203, "text": "Faster data transfer due to easy communication access." }, { "code": null, "e": 1306, "s": 1258, "text": "Disadvantages There is no major disadvantages. " }, { "code": null, "e": 1320, "s": 1306, "text": "sumitgumber28" }, { "code": null, "e": 1335, "s": 1320, "text": "sagar0719kumar" }, { "code": null, "e": 1372, "s": 1335, "text": "Computer Organization & Architecture" } ]
How to Create Boxplots by Group in Matplotlib?
25 Jan, 2022 Boxplots by groups can be created using the matplotlib package, but, however, if you wish to make more customizations to your grouped box plot, then the seaborn package provides a go-to function that supports a wide variety of customizations to the grouped box plots. Matplotlib doesn’t provide an explicit function to create a grouped box plot. We have to construct the plot as per the required format. This article discusses how to create grouped boxplots in matplotlib. matplotlib.pyplot.boxplot() & matplotlib.pyplot.setp() are the two useful functions to create grouped boxplots Syntax: matplotlib.pyplot.boxplot(x, notch, positions, widths) Syntax: matplotlib.pyplot.setp(obj, *args, **kwargs) Python3 # import the matplotlib packageimport matplotlib.pyplot as plt # import the numpy packageimport numpy as np # create 2 - sample a 3-Dim array, that measures# the summer and winter rain fall amountsummer_rain = [[3, 5, 7], [15, 17, 12, 12, 15], [26, 21, 15]]winter_rain = [[16, 14, 12], [31, 20, 25, 23, 28], [29, 31, 35, 41]] # the list named ticks, summarizes or groups# the summer and winter rainfall as low, mid# and highticks = ['Low', 'Mid', 'High'] # create a boxplot for two arrays separately,# the position specifies the location of the# particular box in the graph,# this can be changed as per your wish. Use width# to specify the width of the plotsummer_rain_plot = plt.boxplot(summer_rain, positions=np.array( np.arange(len(summer_rain)))*2.0-0.35, widths=0.6)winter_rain_plot = plt.boxplot(winter_rain, positions=np.array( np.arange(len(winter_rain)))*2.0+0.35, widths=0.6) # each plot returns a dictionary, use plt.setp()# function to assign the color code# for all properties of the box plot of particular group# use the below function to set color for particular group,# by iterating over all properties of the box plotdef define_box_properties(plot_name, color_code, label): for k, v in plot_name.items(): plt.setp(plot_name.get(k), color=color_code) # use plot function to draw a small line to name the legend. plt.plot([], c=color_code, label=label) plt.legend() # setting colors for each groupsdefine_box_properties(summer_rain_plot, '#D7191C', 'Summer')define_box_properties(winter_rain_plot, '#2C7BB6', 'Winter') # set the x label valuesplt.xticks(np.arange(0, len(ticks) * 2, 2), ticks) # set the limit for x axisplt.xlim(-2, len(ticks)*2) # set the limit for y axisplt.ylim(0, 50) # set the titleplt.title('Grouped boxplot using matplotlib') Output: Explanation: Import the necessary packages numpy and matplotlib. Create 2 – sample arrays of 3 dimensions named, summer_rain and winter_rain Create another list named ticks, that summarizes or groups the summer and winter rainfall as low, mid, and high. Create a boxplot for two arrays separately as shown. Use the position argument to specify the location of every box in the group, here, the summer_rain plot has 3 boxes which are separated at a spacing of [-0.35, 1.65, 3.65] and the winter_rain plot has 3 boxes which are separated at a spacing of [0.35, 2.35, 4.35]. The width of each box is kept at 0.6. Now, each individual plot summer_rain_plot and winter_rain_plot returns a dictionary, This dictionary has a list of properties of the box plot like whiskers, median, fliers etc. Now, iterate through the dictionary items and use plt.setp() function to assign a unique color code for each group as shown. Use plt.plot() function to draw a default line to represent the legends of the box plot. The define_box_properties function, takes the plot, color and the legend name as arguments and set the properties of the plot appropriately. Finally, to improve the aesthetic value, use xlim, ylim function to define the limits of the x and y axis and use xticks function to label the x-axis. Set the title of the plot using plt.title() function. You can also plot grouped box plots using long-form and wide form data using yet another library called seaborn which is built on top matplotlib library. Syntax: sns.boxplot(data, x, y) Parameters: data – specifies the dataframe to be used for the box plots x – specifies the column to be used in the x-axis y – specifies the column to be used in y-axis Python3 # import the necessary python packagesimport pandas as pdimport numpy as npimport seaborn as sns # create long-form datadata = pd.DataFrame({'season': np.repeat(['Summer', 'Winter', 'Spring'], 5), 'rainfall_amount': [17, 18, 19, 21, 27, 33, 37, 33, 36, 12, 14, 15, 16, 21, 22], })# print the dataprint(data) # use seaborn plot and specify the x and y# columns and specify the dataframesns.boxplot(x='season', y='rainfall_amount', data=data) Output: Python3 # import the necessary python packagesimport pandas as pdimport numpy as npimport seaborn as sns # create wide-form datadata = pd.DataFrame({'Summer': [17, 18, 19, 21, 27], 'Winter': [33, 37, 33, 36, 12], 'Spring': [14, 15, 16, 21, 22]})# print the dataprint(data)# use melt to convert wide form to long form data# use seaborn plot and specify the x and y columns# and specify the dataframesns.boxplot(x='variable', y='value', data=pd.melt(data)).set( xlabel='Season', ylabel='Rainfall amount') Output: Code Explanation: Import the necessary packages Create a sample dataframe that lists seasonal rainfall amounts in wide form format as shown. To plot the grouped box plot, the data has to be in a long format, so use pandas.melt() function to melt the data from the wide form to long-form. When the wide form data is converted to long-form data, the two columns will be named as ‘variable’ and ‘value’ by default. Use seaborn plot and pass the ‘variable’ as x and ‘value’ as y column of the boxplot and the corresponding dataframe. Use the set() function to set the x and y-axis labels of the boxplot. akshaysingh98088 sagartomar9927 Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python Defaultdict in Python How to iterate through Excel rows in Python?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jan, 2022" }, { "code": null, "e": 502, "s": 28, "text": "Boxplots by groups can be created using the matplotlib package, but, however, if you wish to make more customizations to your grouped box plot, then the seaborn package provides a go-to function that supports a wide variety of customizations to the grouped box plots. Matplotlib doesn’t provide an explicit function to create a grouped box plot. We have to construct the plot as per the required format. This article discusses how to create grouped boxplots in matplotlib. " }, { "code": null, "e": 613, "s": 502, "text": "matplotlib.pyplot.boxplot() & matplotlib.pyplot.setp() are the two useful functions to create grouped boxplots" }, { "code": null, "e": 676, "s": 613, "text": "Syntax: matplotlib.pyplot.boxplot(x, notch, positions, widths)" }, { "code": null, "e": 729, "s": 676, "text": "Syntax: matplotlib.pyplot.setp(obj, *args, **kwargs)" }, { "code": null, "e": 737, "s": 729, "text": "Python3" }, { "code": "# import the matplotlib packageimport matplotlib.pyplot as plt # import the numpy packageimport numpy as np # create 2 - sample a 3-Dim array, that measures# the summer and winter rain fall amountsummer_rain = [[3, 5, 7], [15, 17, 12, 12, 15], [26, 21, 15]]winter_rain = [[16, 14, 12], [31, 20, 25, 23, 28], [29, 31, 35, 41]] # the list named ticks, summarizes or groups# the summer and winter rainfall as low, mid# and highticks = ['Low', 'Mid', 'High'] # create a boxplot for two arrays separately,# the position specifies the location of the# particular box in the graph,# this can be changed as per your wish. Use width# to specify the width of the plotsummer_rain_plot = plt.boxplot(summer_rain, positions=np.array( np.arange(len(summer_rain)))*2.0-0.35, widths=0.6)winter_rain_plot = plt.boxplot(winter_rain, positions=np.array( np.arange(len(winter_rain)))*2.0+0.35, widths=0.6) # each plot returns a dictionary, use plt.setp()# function to assign the color code# for all properties of the box plot of particular group# use the below function to set color for particular group,# by iterating over all properties of the box plotdef define_box_properties(plot_name, color_code, label): for k, v in plot_name.items(): plt.setp(plot_name.get(k), color=color_code) # use plot function to draw a small line to name the legend. plt.plot([], c=color_code, label=label) plt.legend() # setting colors for each groupsdefine_box_properties(summer_rain_plot, '#D7191C', 'Summer')define_box_properties(winter_rain_plot, '#2C7BB6', 'Winter') # set the x label valuesplt.xticks(np.arange(0, len(ticks) * 2, 2), ticks) # set the limit for x axisplt.xlim(-2, len(ticks)*2) # set the limit for y axisplt.ylim(0, 50) # set the titleplt.title('Grouped boxplot using matplotlib')", "e": 2685, "s": 737, "text": null }, { "code": null, "e": 2693, "s": 2685, "text": "Output:" }, { "code": null, "e": 2706, "s": 2693, "text": "Explanation:" }, { "code": null, "e": 2758, "s": 2706, "text": "Import the necessary packages numpy and matplotlib." }, { "code": null, "e": 2834, "s": 2758, "text": "Create 2 – sample arrays of 3 dimensions named, summer_rain and winter_rain" }, { "code": null, "e": 2947, "s": 2834, "text": "Create another list named ticks, that summarizes or groups the summer and winter rainfall as low, mid, and high." }, { "code": null, "e": 3000, "s": 2947, "text": "Create a boxplot for two arrays separately as shown." }, { "code": null, "e": 3267, "s": 3000, "text": "Use the position argument to specify the location of every box in the group, here, the summer_rain plot has 3 boxes which are separated at a spacing of [-0.35, 1.65, 3.65] and the winter_rain plot has 3 boxes which are separated at a spacing of [0.35, 2.35, 4.35]." }, { "code": null, "e": 3305, "s": 3267, "text": "The width of each box is kept at 0.6." }, { "code": null, "e": 3483, "s": 3305, "text": "Now, each individual plot summer_rain_plot and winter_rain_plot returns a dictionary, This dictionary has a list of properties of the box plot like whiskers, median, fliers etc." }, { "code": null, "e": 3608, "s": 3483, "text": "Now, iterate through the dictionary items and use plt.setp() function to assign a unique color code for each group as shown." }, { "code": null, "e": 3697, "s": 3608, "text": "Use plt.plot() function to draw a default line to represent the legends of the box plot." }, { "code": null, "e": 3838, "s": 3697, "text": "The define_box_properties function, takes the plot, color and the legend name as arguments and set the properties of the plot appropriately." }, { "code": null, "e": 4043, "s": 3838, "text": "Finally, to improve the aesthetic value, use xlim, ylim function to define the limits of the x and y axis and use xticks function to label the x-axis. Set the title of the plot using plt.title() function." }, { "code": null, "e": 4197, "s": 4043, "text": "You can also plot grouped box plots using long-form and wide form data using yet another library called seaborn which is built on top matplotlib library." }, { "code": null, "e": 4229, "s": 4197, "text": "Syntax: sns.boxplot(data, x, y)" }, { "code": null, "e": 4241, "s": 4229, "text": "Parameters:" }, { "code": null, "e": 4301, "s": 4241, "text": "data – specifies the dataframe to be used for the box plots" }, { "code": null, "e": 4352, "s": 4301, "text": "x – specifies the column to be used in the x-axis" }, { "code": null, "e": 4398, "s": 4352, "text": "y – specifies the column to be used in y-axis" }, { "code": null, "e": 4406, "s": 4398, "text": "Python3" }, { "code": "# import the necessary python packagesimport pandas as pdimport numpy as npimport seaborn as sns # create long-form datadata = pd.DataFrame({'season': np.repeat(['Summer', 'Winter', 'Spring'], 5), 'rainfall_amount': [17, 18, 19, 21, 27, 33, 37, 33, 36, 12, 14, 15, 16, 21, 22], })# print the dataprint(data) # use seaborn plot and specify the x and y# columns and specify the dataframesns.boxplot(x='season', y='rainfall_amount', data=data)", "e": 5008, "s": 4406, "text": null }, { "code": null, "e": 5016, "s": 5008, "text": "Output:" }, { "code": null, "e": 5024, "s": 5016, "text": "Python3" }, { "code": "# import the necessary python packagesimport pandas as pdimport numpy as npimport seaborn as sns # create wide-form datadata = pd.DataFrame({'Summer': [17, 18, 19, 21, 27], 'Winter': [33, 37, 33, 36, 12], 'Spring': [14, 15, 16, 21, 22]})# print the dataprint(data)# use melt to convert wide form to long form data# use seaborn plot and specify the x and y columns# and specify the dataframesns.boxplot(x='variable', y='value', data=pd.melt(data)).set( xlabel='Season', ylabel='Rainfall amount')", "e": 5565, "s": 5024, "text": null }, { "code": null, "e": 5573, "s": 5565, "text": "Output:" }, { "code": null, "e": 5591, "s": 5573, "text": "Code Explanation:" }, { "code": null, "e": 5621, "s": 5591, "text": "Import the necessary packages" }, { "code": null, "e": 5714, "s": 5621, "text": "Create a sample dataframe that lists seasonal rainfall amounts in wide form format as shown." }, { "code": null, "e": 5861, "s": 5714, "text": "To plot the grouped box plot, the data has to be in a long format, so use pandas.melt() function to melt the data from the wide form to long-form." }, { "code": null, "e": 5985, "s": 5861, "text": "When the wide form data is converted to long-form data, the two columns will be named as ‘variable’ and ‘value’ by default." }, { "code": null, "e": 6104, "s": 5985, "text": "Use seaborn plot and pass the ‘variable’ as x and ‘value’ as y column of the boxplot and the corresponding dataframe." }, { "code": null, "e": 6174, "s": 6104, "text": "Use the set() function to set the x and y-axis labels of the boxplot." }, { "code": null, "e": 6191, "s": 6174, "text": "akshaysingh98088" }, { "code": null, "e": 6206, "s": 6191, "text": "sagartomar9927" }, { "code": null, "e": 6213, "s": 6206, "text": "Picked" }, { "code": null, "e": 6231, "s": 6213, "text": "Python-matplotlib" }, { "code": null, "e": 6238, "s": 6231, "text": "Python" }, { "code": null, "e": 6336, "s": 6238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6386, "s": 6336, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 6408, "s": 6386, "text": "Enumerate() in Python" }, { "code": null, "e": 6424, "s": 6408, "text": "Deque in Python" }, { "code": null, "e": 6440, "s": 6424, "text": "Stack in Python" }, { "code": null, "e": 6465, "s": 6440, "text": "sum() function in Python" }, { "code": null, "e": 6506, "s": 6465, "text": "Print lists in Python (5 Different Ways)" }, { "code": null, "e": 6548, "s": 6506, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6564, "s": 6548, "text": "Queue in Python" }, { "code": null, "e": 6586, "s": 6564, "text": "Defaultdict in Python" } ]
Lex Program to remove comments from C program
11 Jul, 2022 Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The commands for executing the lex program are: lex abc.l (abc is the file name) cc lex.yy.c -efl ./a.out Let’s see LEX program to accept string starting with vowel.Examples: Input : //testing #include int main() { /* multiline comment continue.... */ return 0; } Output : #include int main() { return 0; } Below is the implementation: /% Lex Program to remove comments from C program and save it in a file %//*Definition Section*/%{%} /*Starting character sequence for multiline comment*/start \/\*/*Ending character sequence for multiline comment*/end \*\/ /*Rule Section*/%% /*Regular expression for single line comment*/\/\/(.*) ;/*Regular expression for multi line comment*/ {start}.*{end} ; %% /*Driver function*/int main(int k,char **argcv){yyin=fopen(argcv[1],"r");yyout=fopen("out.c","w");/*call the yylex function.*/yylex();return 0;} Output: psil123 Lex program C Programs Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jul, 2022" }, { "code": null, "e": 249, "s": 53, "text": "Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language." }, { "code": null, "e": 297, "s": 249, "text": "The commands for executing the lex program are:" }, { "code": null, "e": 356, "s": 297, "text": "lex abc.l (abc is the file name)\ncc lex.yy.c -efl\n./a.out\n" }, { "code": null, "e": 425, "s": 356, "text": "Let’s see LEX program to accept string starting with vowel.Examples:" }, { "code": null, "e": 573, "s": 425, "text": "Input : \n//testing\n#include \nint main()\n{\n /* multiline comment\n continue....\n */\n return 0;\n}\n\nOutput :\n#include \nint main()\n{\n \n return 0;\n}\n\n" }, { "code": null, "e": 602, "s": 573, "text": "Below is the implementation:" }, { "code": "/% Lex Program to remove comments from C program and save it in a file %//*Definition Section*/%{%} /*Starting character sequence for multiline comment*/start \\/\\*/*Ending character sequence for multiline comment*/end \\*\\/ /*Rule Section*/%% /*Regular expression for single line comment*/\\/\\/(.*) ;/*Regular expression for multi line comment*/ {start}.*{end} ; %% /*Driver function*/int main(int k,char **argcv){yyin=fopen(argcv[1],\"r\");yyout=fopen(\"out.c\",\"w\");/*call the yylex function.*/yylex();return 0;}", "e": 1120, "s": 602, "text": null }, { "code": null, "e": 1128, "s": 1120, "text": "Output:" }, { "code": null, "e": 1136, "s": 1128, "text": "psil123" }, { "code": null, "e": 1148, "s": 1136, "text": "Lex program" }, { "code": null, "e": 1159, "s": 1148, "text": "C Programs" }, { "code": null, "e": 1175, "s": 1159, "text": "Compiler Design" } ]
Regular Expressions in Java
09 Feb, 2022 Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. This consists of 3 classes and 1 interface. The java.util.regex package primarily consists of the following three classes as depicted below in tabular format as follows: Regex in java provides us with 3 classes and 1 interface listed below as follows: Pattern ClassMatcher ClassPatternSyntaxException ClassMatchResult Interface Pattern Class Matcher Class PatternSyntaxException Class MatchResult Interface More understanding can be interpreted from the image provided below as follows: This class is a compilation of regular expressions that can be used to define various types of patterns, providing no public constructors. This can be created by invoking the compile() method which accepts a regular expression as the first argument, thus returns a pattern after execution. Example: Pattern class Java // Java Program Demonstrating Working of matches() Method// Pattern class // Importing Pattern class from java.util.regex packageimport java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Following line prints "true" because the whole // text "geeksforgeeks" matches pattern // "geeksforge*ks" System.out.println(Pattern.matches( "geeksforge*ks", "geeksforgeeks")); // Following line prints "false" because the whole // text "geeksfor" doesn't match pattern "g*geeks*" System.out.println( Pattern.matches("g*geeks*", "geeksfor")); }} true false This object is used to perform match operations for an input string in java, thus interpreting the previously explained patterns. This too defines no public constructors. This can be implemented by invoking a matcher() on any pattern object. Note: T Pattern.matches() checks if the whole text matches with a pattern or not. Other methods (demonstrated below) are mainly used to find multiple occurrences of patterns in the text. Let us do discuss a few sample programs as we did for Pattern class. Here we will be discussing a few java programs that demonstrate the workings of compile(), find(), start(), end(), and split() in order to get a better understanding of the Matcher class. Example 1: Pattern searching Java // Java program to demonstrate working of// String matching in Java // Importing Matcher and Pattern classimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Create a pattern to be searched // Custom pattern Pattern pattern = Pattern.compile("geeks"); // Search above pattern in "geeksforgeeks.org" Matcher m = pattern.matcher("geeksforgeeks.org"); // Finding string using find() method while (m.find()) // Print starting and ending indexes // of the pattern in the text // using this functionality of this class System.out.println("Pattern found from " + m.start() + " to " + (m.end() - 1)); }} Pattern found from 0 to 4 Pattern found from 8 to 12 Example 2: Simple regular expression searching Java // Java program to demonstrate working of// String matching in Java // Importing Matcher and Pattern class// from java.util packageimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating a pattern to be searched // Custom pattern to be searched Pattern pattern = Pattern.compile("ge*"); // Searching for the above pattern in // "geeksforgeeks.org" Matcher m = pattern.matcher("geeksforgeeks.org"); // Checking whether the pattern is there or not // using find() method while (m.find()) // Print starting and ending indexes of the // pattern in text using method functionality of // this class System.out.println("Pattern found from " + m.start() + " to " + (m.end() - 1)); }} Pattern found from 0 to 2 Pattern found from 8 to 10 Pattern found from 16 to 16 Example 3: Case Insensitive pattern searching Java // Java Program Demonstrating Working of String matching // Importing Matcher class and Pattern classes// from java.util.regex packageimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating a pattern to be searched Pattern pattern = Pattern.compile( "ge*", Pattern.CASE_INSENSITIVE); // Searching above pattern in "geeksforgeeks.org" Matcher m = pattern.matcher("GeeksforGeeks.org"); // Find th above string using find() method while (m.find()) // Printing the starting and ending indexes of // the pattern in text using class method // functionalities System.out.println("Pattern found from " + m.start() + " to " + (m.end() - 1)); }} Pattern found from 0 to 2 Pattern found from 8 to 10 Pattern found from 16 to 16 Example 4: split() method to split a text based on a delimiter pattern. The string split() method breaks a given string around matches of the given regular expression. There exist two variations of this method so do go through it prior to moving onto the implementation of this method. Illustration: Input --> String: 016-78967 Output --> Regex: {"016", "78967"} Java // Java program Illustrating Working of split() Method// by Splitting a text by a given pattern // Importing Matcher and Pattern classes from// java.util.regex packageimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom string String text = "geeks1for2geeks3"; // Specifies the string pattern // which is to be searched String delimiter = "\\d"; Pattern pattern = Pattern.compile( delimiter, Pattern.CASE_INSENSITIVE); // Used to perform case insensitive search of the // string String[] result = pattern.split(text); // Iterating using for each loop for (String temp : result) System.out.println(temp); }} geeks for geeks Now we are done with discussing both the classes. Now we will be introducing you to two new concepts that make absolute clear Also there is an exception class associated with This is an object of Regex which is used to indicate a syntax error in a regular expression pattern and is an unchecked exception. Following are the methods been there up in the PatternSyntaxException class as provided below in tabular format as follows. This interface is used to determine the result of a match operation for a regular expression. It must be noted that although the match boundaries, groups, and group boundaries can be seen, the modification is not allowed through a MatchResult. Following are the methods been there up here in this interface as provided below in tabular format as follows: Lastly, let us do discuss some of the important observations as retrieved from the above article We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in Pattern class.Like above, we create a Matcher object using matcher() on objects of Pattern class.Pattern.matches() is also a static method that is used to check if given text as a whole matches pattern or not.find() is used to find multiple occurrences of patterns in the text.We can split a text based on a delimiter pattern using the split() method We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in Pattern class. Like above, we create a Matcher object using matcher() on objects of Pattern class. Pattern.matches() is also a static method that is used to check if given text as a whole matches pattern or not. find() is used to find multiple occurrences of patterns in the text. We can split a text based on a delimiter pattern using the split() method This article is contributed by Akash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.orgerror-index. 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. Chinmoy Lenka Sapna2001 solankimayank arorakashish0911 nishkarshgandhi java-regular-expression Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples For-each loop in Java Queue Interface In Java Interfaces in Java How to add an element to an Array in Java? Stack Class in Java Multidimensional Arrays in Java ArrayList in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Feb, 2022" }, { "code": null, "e": 563, "s": 54, "text": "Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. This consists of 3 classes and 1 interface. The java.util.regex package primarily consists of the following three classes as depicted below in tabular format as follows:" }, { "code": null, "e": 645, "s": 563, "text": "Regex in java provides us with 3 classes and 1 interface listed below as follows:" }, { "code": null, "e": 721, "s": 645, "text": "Pattern ClassMatcher ClassPatternSyntaxException ClassMatchResult Interface" }, { "code": null, "e": 735, "s": 721, "text": "Pattern Class" }, { "code": null, "e": 749, "s": 735, "text": "Matcher Class" }, { "code": null, "e": 778, "s": 749, "text": "PatternSyntaxException Class" }, { "code": null, "e": 800, "s": 778, "text": "MatchResult Interface" }, { "code": null, "e": 880, "s": 800, "text": "More understanding can be interpreted from the image provided below as follows:" }, { "code": null, "e": 1170, "s": 880, "text": "This class is a compilation of regular expressions that can be used to define various types of patterns, providing no public constructors. This can be created by invoking the compile() method which accepts a regular expression as the first argument, thus returns a pattern after execution." }, { "code": null, "e": 1194, "s": 1170, "text": "Example: Pattern class " }, { "code": null, "e": 1199, "s": 1194, "text": "Java" }, { "code": "// Java Program Demonstrating Working of matches() Method// Pattern class // Importing Pattern class from java.util.regex packageimport java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Following line prints \"true\" because the whole // text \"geeksforgeeks\" matches pattern // \"geeksforge*ks\" System.out.println(Pattern.matches( \"geeksforge*ks\", \"geeksforgeeks\")); // Following line prints \"false\" because the whole // text \"geeksfor\" doesn't match pattern \"g*geeks*\" System.out.println( Pattern.matches(\"g*geeks*\", \"geeksfor\")); }}", "e": 1883, "s": 1199, "text": null }, { "code": null, "e": 1894, "s": 1883, "text": "true\nfalse" }, { "code": null, "e": 2136, "s": 1894, "text": "This object is used to perform match operations for an input string in java, thus interpreting the previously explained patterns. This too defines no public constructors. This can be implemented by invoking a matcher() on any pattern object." }, { "code": null, "e": 2323, "s": 2136, "text": "Note: T Pattern.matches() checks if the whole text matches with a pattern or not. Other methods (demonstrated below) are mainly used to find multiple occurrences of patterns in the text." }, { "code": null, "e": 2580, "s": 2323, "text": "Let us do discuss a few sample programs as we did for Pattern class. Here we will be discussing a few java programs that demonstrate the workings of compile(), find(), start(), end(), and split() in order to get a better understanding of the Matcher class." }, { "code": null, "e": 2610, "s": 2580, "text": "Example 1: Pattern searching " }, { "code": null, "e": 2615, "s": 2610, "text": "Java" }, { "code": "// Java program to demonstrate working of// String matching in Java // Importing Matcher and Pattern classimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Create a pattern to be searched // Custom pattern Pattern pattern = Pattern.compile(\"geeks\"); // Search above pattern in \"geeksforgeeks.org\" Matcher m = pattern.matcher(\"geeksforgeeks.org\"); // Finding string using find() method while (m.find()) // Print starting and ending indexes // of the pattern in the text // using this functionality of this class System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end() - 1)); }}", "e": 3483, "s": 2615, "text": null }, { "code": null, "e": 3536, "s": 3483, "text": "Pattern found from 0 to 4\nPattern found from 8 to 12" }, { "code": null, "e": 3584, "s": 3536, "text": "Example 2: Simple regular expression searching " }, { "code": null, "e": 3589, "s": 3584, "text": "Java" }, { "code": "// Java program to demonstrate working of// String matching in Java // Importing Matcher and Pattern class// from java.util packageimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating a pattern to be searched // Custom pattern to be searched Pattern pattern = Pattern.compile(\"ge*\"); // Searching for the above pattern in // \"geeksforgeeks.org\" Matcher m = pattern.matcher(\"geeksforgeeks.org\"); // Checking whether the pattern is there or not // using find() method while (m.find()) // Print starting and ending indexes of the // pattern in text using method functionality of // this class System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end() - 1)); }}", "e": 4556, "s": 3589, "text": null }, { "code": null, "e": 4637, "s": 4556, "text": "Pattern found from 0 to 2\nPattern found from 8 to 10\nPattern found from 16 to 16" }, { "code": null, "e": 4685, "s": 4637, "text": "Example 3: Case Insensitive pattern searching " }, { "code": null, "e": 4690, "s": 4685, "text": "Java" }, { "code": "// Java Program Demonstrating Working of String matching // Importing Matcher class and Pattern classes// from java.util.regex packageimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating a pattern to be searched Pattern pattern = Pattern.compile( \"ge*\", Pattern.CASE_INSENSITIVE); // Searching above pattern in \"geeksforgeeks.org\" Matcher m = pattern.matcher(\"GeeksforGeeks.org\"); // Find th above string using find() method while (m.find()) // Printing the starting and ending indexes of // the pattern in text using class method // functionalities System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end() - 1)); }}", "e": 5607, "s": 4690, "text": null }, { "code": null, "e": 5688, "s": 5607, "text": "Pattern found from 0 to 2\nPattern found from 8 to 10\nPattern found from 16 to 16" }, { "code": null, "e": 5760, "s": 5688, "text": "Example 4: split() method to split a text based on a delimiter pattern." }, { "code": null, "e": 5974, "s": 5760, "text": "The string split() method breaks a given string around matches of the given regular expression. There exist two variations of this method so do go through it prior to moving onto the implementation of this method." }, { "code": null, "e": 5988, "s": 5974, "text": "Illustration:" }, { "code": null, "e": 6053, "s": 5988, "text": "Input --> String: 016-78967\nOutput --> Regex: {\"016\", \"78967\"}" }, { "code": null, "e": 6058, "s": 6053, "text": "Java" }, { "code": "// Java program Illustrating Working of split() Method// by Splitting a text by a given pattern // Importing Matcher and Pattern classes from// java.util.regex packageimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom string String text = \"geeks1for2geeks3\"; // Specifies the string pattern // which is to be searched String delimiter = \"\\\\d\"; Pattern pattern = Pattern.compile( delimiter, Pattern.CASE_INSENSITIVE); // Used to perform case insensitive search of the // string String[] result = pattern.split(text); // Iterating using for each loop for (String temp : result) System.out.println(temp); }}", "e": 6889, "s": 6058, "text": null }, { "code": null, "e": 6905, "s": 6889, "text": "geeks\nfor\ngeeks" }, { "code": null, "e": 7082, "s": 6905, "text": "Now we are done with discussing both the classes. Now we will be introducing you to two new concepts that make absolute clear Also there is an exception class associated with " }, { "code": null, "e": 7337, "s": 7082, "text": "This is an object of Regex which is used to indicate a syntax error in a regular expression pattern and is an unchecked exception. Following are the methods been there up in the PatternSyntaxException class as provided below in tabular format as follows." }, { "code": null, "e": 7692, "s": 7337, "text": "This interface is used to determine the result of a match operation for a regular expression. It must be noted that although the match boundaries, groups, and group boundaries can be seen, the modification is not allowed through a MatchResult. Following are the methods been there up here in this interface as provided below in tabular format as follows:" }, { "code": null, "e": 7789, "s": 7692, "text": "Lastly, let us do discuss some of the important observations as retrieved from the above article" }, { "code": null, "e": 8254, "s": 7789, "text": "We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in Pattern class.Like above, we create a Matcher object using matcher() on objects of Pattern class.Pattern.matches() is also a static method that is used to check if given text as a whole matches pattern or not.find() is used to find multiple occurrences of patterns in the text.We can split a text based on a delimiter pattern using the split() method" }, { "code": null, "e": 8383, "s": 8254, "text": "We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in Pattern class." }, { "code": null, "e": 8467, "s": 8383, "text": "Like above, we create a Matcher object using matcher() on objects of Pattern class." }, { "code": null, "e": 8580, "s": 8467, "text": "Pattern.matches() is also a static method that is used to check if given text as a whole matches pattern or not." }, { "code": null, "e": 8649, "s": 8580, "text": "find() is used to find multiple occurrences of patterns in the text." }, { "code": null, "e": 8723, "s": 8649, "text": "We can split a text based on a delimiter pattern using the split() method" }, { "code": null, "e": 9124, "s": 8723, "text": "This article is contributed by Akash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.orgerror-index. 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": 9138, "s": 9124, "text": "Chinmoy Lenka" }, { "code": null, "e": 9148, "s": 9138, "text": "Sapna2001" }, { "code": null, "e": 9162, "s": 9148, "text": "solankimayank" }, { "code": null, "e": 9179, "s": 9162, "text": "arorakashish0911" }, { "code": null, "e": 9195, "s": 9179, "text": "nishkarshgandhi" }, { "code": null, "e": 9219, "s": 9195, "text": "java-regular-expression" }, { "code": null, "e": 9224, "s": 9219, "text": "Java" }, { "code": null, "e": 9243, "s": 9224, "text": "Technical Scripter" }, { "code": null, "e": 9248, "s": 9243, "text": "Java" }, { "code": null, "e": 9346, "s": 9248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9382, "s": 9346, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 9407, "s": 9382, "text": "Reverse a string in Java" }, { "code": null, "e": 9451, "s": 9407, "text": "Split() String method in Java with examples" }, { "code": null, "e": 9473, "s": 9451, "text": "For-each loop in Java" }, { "code": null, "e": 9497, "s": 9473, "text": "Queue Interface In Java" }, { "code": null, "e": 9516, "s": 9497, "text": "Interfaces in Java" }, { "code": null, "e": 9559, "s": 9516, "text": "How to add an element to an Array in Java?" }, { "code": null, "e": 9579, "s": 9559, "text": "Stack Class in Java" }, { "code": null, "e": 9611, "s": 9579, "text": "Multidimensional Arrays in Java" } ]
How to set the Location of the TextBox in C#?
29 Nov, 2019 In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the coordinates of the upper-left corner of the TextBox control relative to the upper-left corner of its container with the help of Location property. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the Location property of the TextBox as shown in 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 TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image: Step 3: After drag and drop you will go to the properties of the TextBox control to set the Location property of the TextBox. As shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Location property of the TextBox programmatically with the help of given syntax: public System.Drawing.Point Location { get; set; } Here, Point is used to represent the upper-left corner of the control relative to the upper-left corner of its container. Following steps are used to set the Location property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the Location property of the TextBox provided by the TextBox class.// Set Location property Mytextbox1.Location = new Point(187, 51); // Set Location property Mytextbox1.Location = new Point(187, 51); Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox1); 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 my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Area"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox1); 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 my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Area"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}} Output: CSharp-Windows-Forms-Namespace C# 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, 2019" }, { "code": null, "e": 450, "s": 28, "text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the coordinates of the upper-left corner of the TextBox control relative to the upper-left corner of its container with the help of Location property. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 566, "s": 450, "text": "1. Design-Time: It is the simplest way to set the Location property of the TextBox as shown in the following steps:" }, { "code": null, "e": 682, "s": 566, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 869, "s": 682, "text": "Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:" }, { "code": null, "e": 1031, "s": 869, "text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the Location property of the TextBox. As shown in the below image:Output:" }, { "code": null, "e": 1039, "s": 1031, "text": "Output:" }, { "code": null, "e": 1216, "s": 1039, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Location property of the TextBox programmatically with the help of given syntax:" }, { "code": null, "e": 1267, "s": 1216, "text": "public System.Drawing.Point Location { get; set; }" }, { "code": null, "e": 1459, "s": 1267, "text": "Here, Point is used to represent the upper-left corner of the control relative to the upper-left corner of its container. Following steps are used to set the Location property of the TextBox:" }, { "code": null, "e": 1603, "s": 1459, "text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1659, "s": 1603, "text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1831, "s": 1659, "text": "Step 2 : After creating TextBox, set the Location property of the TextBox provided by the TextBox class.// Set Location property\nMytextbox1.Location = new Point(187, 51);\n" }, { "code": null, "e": 1899, "s": 1831, "text": "// Set Location property\nMytextbox1.Location = new Point(187, 51);\n" }, { "code": null, "e": 3842, "s": 1899, "text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox1);\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 my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = \"Enter Name\"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = \"text_box1\"; Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = \"Enter Area\"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.Name = \"text_box2\"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output:" }, { "code": null, "e": 3902, "s": 3842, "text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox1);\n" }, { "code": null, "e": 3911, "s": 3902, "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 my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = \"Enter Name\"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = \"text_box1\"; Mytextbox1.Margin = new Padding(5, 5, 5, 5); // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = \"Enter Area\"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.Name = \"text_box2\"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}", "e": 5710, "s": 3911, "text": null }, { "code": null, "e": 5718, "s": 5710, "text": "Output:" }, { "code": null, "e": 5749, "s": 5718, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 5752, "s": 5749, "text": "C#" } ]
swap() in C++
06 Jul, 2022 The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. Syntax: swap(a, b) Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type. Return Value: The function does not return anything, it swaps the values of the two variables. Programs below illustrate the swap() function: Program 1: // C++ program for illustration of swap() function#include <bits/stdc++.h>using namespace std; int main(){ int a = 10; int b = 20; cout << "Value of a before: " << a << endl; cout << "Value of b before: " << b << endl; // swap values of the variables swap(a, b); cout << "Value of a now: " << a << endl; cout << "Value of b now: " << b << endl; return 0;} Value of a before: 10 Value of b before: 20 Value of a now: 20 Value of b now: 10 Program 2: #include <bits/stdc++.h>using namespace std; int main(){ string a = "Geeks"; string b = "function"; cout << "Value of a before: " << a << endl; cout << "Value of b before: " << b << endl; swap(a, b); cout << "Value of a now: " << a << endl; cout << "Value of b now: " << b << endl; return 0;} Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks mhgeeksforgeeks CPP-Functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 183, "s": 52, "text": "The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables." }, { "code": null, "e": 191, "s": 183, "text": "Syntax:" }, { "code": null, "e": 203, "s": 191, "text": "swap(a, b)\n" }, { "code": null, "e": 334, "s": 203, "text": "Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type." }, { "code": null, "e": 429, "s": 334, "text": "Return Value: The function does not return anything, it swaps the values of the two variables." }, { "code": null, "e": 476, "s": 429, "text": "Programs below illustrate the swap() function:" }, { "code": null, "e": 487, "s": 476, "text": "Program 1:" }, { "code": "// C++ program for illustration of swap() function#include <bits/stdc++.h>using namespace std; int main(){ int a = 10; int b = 20; cout << \"Value of a before: \" << a << endl; cout << \"Value of b before: \" << b << endl; // swap values of the variables swap(a, b); cout << \"Value of a now: \" << a << endl; cout << \"Value of b now: \" << b << endl; return 0;}", "e": 873, "s": 487, "text": null }, { "code": null, "e": 956, "s": 873, "text": "Value of a before: 10\nValue of b before: 20\nValue of a now: 20\nValue of b now: 10\n" }, { "code": null, "e": 967, "s": 956, "text": "Program 2:" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ string a = \"Geeks\"; string b = \"function\"; cout << \"Value of a before: \" << a << endl; cout << \"Value of b before: \" << b << endl; swap(a, b); cout << \"Value of a now: \" << a << endl; cout << \"Value of b now: \" << b << endl; return 0;}", "e": 1285, "s": 967, "text": null }, { "code": null, "e": 1386, "s": 1285, "text": "Value of a before: Geeks\nValue of b before: function\nValue of a now: function\nValue of b now: Geeks\n" }, { "code": null, "e": 1402, "s": 1386, "text": "mhgeeksforgeeks" }, { "code": null, "e": 1416, "s": 1402, "text": "CPP-Functions" }, { "code": null, "e": 1420, "s": 1416, "text": "STL" }, { "code": null, "e": 1424, "s": 1420, "text": "C++" }, { "code": null, "e": 1428, "s": 1424, "text": "STL" }, { "code": null, "e": 1432, "s": 1428, "text": "CPP" } ]
How to get the Daily News using Python
14 Sep, 2021 In this article, we are going to see how to get daily news using Python. Here we will use Beautiful Soup and the request module to scrape the data. 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 Step 1: First of all, make sure to import these libraries. Python3 import requestsfrom bs4 import BeautifulSoup Step 2: Then to get the HTML contents of https://www.bbc.com/news, add these 2 lines of code: Python3 url='https://www.bbc.com/news'response = requests.get(url) Step 3: Get specific HTML tag In order to find the HTML tags within which news headlines are contained, head over to https://www.bbc.com/news and inspect a news headline by right-clicking it and clicking “inspect”: You will see that all headlines are contained within “<h3>” tags. Therefore, to scrape all “<h3>” tags within this webpage, add these lines of code to your script: First, we define “soup” as the HTML content of the BBC news webpage. Next, we define “headlines” as an array of all “<h3>” tags found within the webpage. Finally, the script paddles through the “headlines” array and displays all of its contents one by one, ridding each element of its outerHTML and displaying only its text contents using the “text.strip()” method. Python3 soup = BeautifulSoup(response.text, 'html.parser')headlines = soup.find('body').find_all('h3')for x in headlines: print(x.text.strip()) Python3 import requestsfrom bs4 import BeautifulSoup url = 'https://www.bbc.com/news'response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')headlines = soup.find('body').find_all('h3')for x in headlines: print(x.text.strip()) Output: You might have noticed that your output contains duplicate news headlines and text contents that aren’t news headlines. Create a list of all the text elements you want to get rid of: unwanted = [‘BBC World News TV’, ‘BBC World Service Radio’, ‘News daily newsletter’, ‘Mobile app’, ‘Get in touch’] Then print text elements only if they are not in this list by putting: print(x.text.strip()) Python3 import requestsfrom bs4 import BeautifulSoup url = 'https://www.bbc.com/news'response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')headlines = soup.find('body').find_all('h3')unwanted = ['BBC World News TV', 'BBC World Service Radio', 'News daily newsletter', 'Mobile app', 'Get in touch'] for x in list(dict.fromkeys(headlines)): if x.text.strip() not in unwanted: print(x.text.strip()) Output: Picked Python BeautifulSoup Python bs4-Exercises Python web-scraping-exercises Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON 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": "\n14 Sep, 2021" }, { "code": null, "e": 201, "s": 53, "text": "In this article, we are going to see how to get daily news using Python. Here we will use Beautiful Soup and the request module to scrape the data." }, { "code": null, "e": 394, "s": 201, "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": 410, "s": 394, "text": "pip install bs4" }, { "code": null, "e": 592, "s": 410, "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": 613, "s": 592, "text": "pip install requests" }, { "code": null, "e": 672, "s": 613, "text": "Step 1: First of all, make sure to import these libraries." }, { "code": null, "e": 680, "s": 672, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup", "e": 725, "s": 680, "text": null }, { "code": null, "e": 819, "s": 725, "text": "Step 2: Then to get the HTML contents of https://www.bbc.com/news, add these 2 lines of code:" }, { "code": null, "e": 827, "s": 819, "text": "Python3" }, { "code": "url='https://www.bbc.com/news'response = requests.get(url)", "e": 886, "s": 827, "text": null }, { "code": null, "e": 916, "s": 886, "text": "Step 3: Get specific HTML tag" }, { "code": null, "e": 1101, "s": 916, "text": "In order to find the HTML tags within which news headlines are contained, head over to https://www.bbc.com/news and inspect a news headline by right-clicking it and clicking “inspect”:" }, { "code": null, "e": 1265, "s": 1101, "text": "You will see that all headlines are contained within “<h3>” tags. Therefore, to scrape all “<h3>” tags within this webpage, add these lines of code to your script:" }, { "code": null, "e": 1631, "s": 1265, "text": "First, we define “soup” as the HTML content of the BBC news webpage. Next, we define “headlines” as an array of all “<h3>” tags found within the webpage. Finally, the script paddles through the “headlines” array and displays all of its contents one by one, ridding each element of its outerHTML and displaying only its text contents using the “text.strip()” method." }, { "code": null, "e": 1639, "s": 1631, "text": "Python3" }, { "code": "soup = BeautifulSoup(response.text, 'html.parser')headlines = soup.find('body').find_all('h3')for x in headlines: print(x.text.strip())", "e": 1778, "s": 1639, "text": null }, { "code": null, "e": 1786, "s": 1778, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup url = 'https://www.bbc.com/news'response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')headlines = soup.find('body').find_all('h3')for x in headlines: print(x.text.strip())", "e": 2033, "s": 1786, "text": null }, { "code": null, "e": 2041, "s": 2033, "text": "Output:" }, { "code": null, "e": 2161, "s": 2041, "text": "You might have noticed that your output contains duplicate news headlines and text contents that aren’t news headlines." }, { "code": null, "e": 2224, "s": 2161, "text": "Create a list of all the text elements you want to get rid of:" }, { "code": null, "e": 2339, "s": 2224, "text": "unwanted = [‘BBC World News TV’, ‘BBC World Service Radio’, ‘News daily newsletter’, ‘Mobile app’, ‘Get in touch’]" }, { "code": null, "e": 2410, "s": 2339, "text": "Then print text elements only if they are not in this list by putting:" }, { "code": null, "e": 2432, "s": 2410, "text": "print(x.text.strip())" }, { "code": null, "e": 2440, "s": 2432, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup url = 'https://www.bbc.com/news'response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')headlines = soup.find('body').find_all('h3')unwanted = ['BBC World News TV', 'BBC World Service Radio', 'News daily newsletter', 'Mobile app', 'Get in touch'] for x in list(dict.fromkeys(headlines)): if x.text.strip() not in unwanted: print(x.text.strip())", "e": 2877, "s": 2440, "text": null }, { "code": null, "e": 2885, "s": 2877, "text": "Output:" }, { "code": null, "e": 2892, "s": 2885, "text": "Picked" }, { "code": null, "e": 2913, "s": 2892, "text": "Python BeautifulSoup" }, { "code": null, "e": 2934, "s": 2913, "text": "Python bs4-Exercises" }, { "code": null, "e": 2964, "s": 2934, "text": "Python web-scraping-exercises" }, { "code": null, "e": 2980, "s": 2964, "text": "Python-requests" }, { "code": null, "e": 2987, "s": 2980, "text": "Python" }, { "code": null, "e": 3085, "s": 2987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3117, "s": 3085, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3144, "s": 3117, "text": "Python Classes and Objects" }, { "code": null, "e": 3165, "s": 3144, "text": "Python OOPs Concepts" }, { "code": null, "e": 3196, "s": 3165, "text": "Python | os.path.join() method" }, { "code": null, "e": 3252, "s": 3196, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3275, "s": 3252, "text": "Introduction To PYTHON" }, { "code": null, "e": 3317, "s": 3275, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3359, "s": 3317, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3398, "s": 3359, "text": "Python | datetime.timedelta() function" } ]
CheckBox in C#
27 Sep, 2021 The CheckBox control is the part of windows form which is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list or it can provide us options like yes or no, true or false, etc. It can be displayed as an image or text or both. The CheckBox is a class and defined under System.Windows.Forms namespace. In Windows form, you can create CheckBox in two different ways: 1. Design-Time: It is the simplest way to create a CheckBox 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 CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the CheckBox control to modify the CheckBox design according to your requirement. Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can create your own checkbox programmatically using the CheckBox class. Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class. // Creating checkbox CheckBox Mycheckbox = new CheckBox(); Step 2: After creating CheckBox, set the properties of the CheckBox provided by the CheckBox class. // Set height of the checkbox Mycheckbox.Height = 50; // Set width of the checkbox Mycheckbox.Width = 100; // Set location of the checkbox Mycheckbox.Location = new Point(229, 136); // Set text in the checkbox Mycheckbox.Text = "Married"; // Set font of the checkbox Mycheckbox.Font = new Font("Bradley Hand ITC", 12); Step 3: And last add this checkbox control to form using Add() method. // Add this checkbox to form this.Controls.Add(Mycheckbox); Example: C# 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 WindowsFormsApp5 { 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.Text = "Select Status:"; l.AutoSize = true; l.Location = new Point(233, 111); l.Font = new Font("Bradley Hand ITC", 12); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = "Married"; Mycheckbox.Font = new Font("Bradley Hand ITC", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Location = new Point(230, 198); Mycheckbox1.Text = "UnMarried"; Mycheckbox1.AutoSize = true; Mycheckbox1.Font = new Font("Bradley Hand ITC", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}} Output: sagartomar9927 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 476, "s": 28, "text": "The CheckBox control is the part of windows form which is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list or it can provide us options like yes or no, true or false, etc. It can be displayed as an image or text or both. The CheckBox is a class and defined under System.Windows.Forms namespace. In Windows form, you can create CheckBox in two different ways:" }, { "code": null, "e": 564, "s": 476, "text": "1. Design-Time: It is the simplest way to create a CheckBox using the following steps: " }, { "code": null, "e": 682, "s": 564, "text": "Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp " }, { "code": null, "e": 843, "s": 682, "text": "Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. " }, { "code": null, "e": 987, "s": 843, "text": "Step 3: After drag and drop you will go to the properties of the CheckBox control to modify the CheckBox design according to your requirement. " }, { "code": null, "e": 996, "s": 987, "text": "Output: " }, { "code": null, "e": 1153, "s": 996, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can create your own checkbox programmatically using the CheckBox class. " }, { "code": null, "e": 1244, "s": 1153, "text": "Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class." }, { "code": null, "e": 1303, "s": 1244, "text": "// Creating checkbox\nCheckBox Mycheckbox = new CheckBox();" }, { "code": null, "e": 1404, "s": 1303, "text": "Step 2: After creating CheckBox, set the properties of the CheckBox provided by the CheckBox class. " }, { "code": null, "e": 1728, "s": 1404, "text": "// Set height of the checkbox\n Mycheckbox.Height = 50;\n\n// Set width of the checkbox\nMycheckbox.Width = 100;\n\n// Set location of the checkbox\nMycheckbox.Location = new Point(229, 136);\n\n// Set text in the checkbox\nMycheckbox.Text = \"Married\";\n\n// Set font of the checkbox\nMycheckbox.Font = new Font(\"Bradley Hand ITC\", 12);" }, { "code": null, "e": 1800, "s": 1728, "text": "Step 3: And last add this checkbox control to form using Add() method. " }, { "code": null, "e": 1860, "s": 1800, "text": "// Add this checkbox to form\nthis.Controls.Add(Mycheckbox);" }, { "code": null, "e": 1869, "s": 1860, "text": "Example:" }, { "code": null, "e": 1872, "s": 1869, "text": "C#" }, { "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 WindowsFormsApp5 { 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.Text = \"Select Status:\"; l.AutoSize = true; l.Location = new Point(233, 111); l.Font = new Font(\"Bradley Hand ITC\", 12); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = \"Married\"; Mycheckbox.Font = new Font(\"Bradley Hand ITC\", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Location = new Point(230, 198); Mycheckbox1.Text = \"UnMarried\"; Mycheckbox1.AutoSize = true; Mycheckbox1.Font = new Font(\"Bradley Hand ITC\", 12); // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}", "e": 3315, "s": 1872, "text": null }, { "code": null, "e": 3324, "s": 3315, "text": "Output: " }, { "code": null, "e": 3341, "s": 3326, "text": "sagartomar9927" }, { "code": null, "e": 3344, "s": 3341, "text": "C#" } ]
Python PIL | Image filter with ImageFilter module
25 Jun, 2019 The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the Image.filter() method. Image used: Filters –The current version of the library provides the set of predefined image enhancement filters: 1. BLUR # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the blur filterim2 = im1.filter(ImageFilter.BLUR) im2.show() Output: 2. CONTOUR # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the contour filterim2 = im1.filter(ImageFilter.CONTOUR) im2.show() Output: 3. EMBOSS # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the emboss filterim2 = im1.filter(ImageFilter.EMBOSS) im2.show() Output: 4. EDGE_ENHANCE # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the EDGE_ENHANCE filterim2 = im1.filter(ImageFilter.EDGE_ENHANCE) im2.show() Output: 5. EDGE_ENHANCE_MORE # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the EDGE_ENHANCE_MORE filterim2 = im1.filter(ImageFilter.EDGE_ENHANCE_MORE) im2.show() Output: python-utility 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 159, "s": 28, "text": "The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the Image.filter() method." }, { "code": null, "e": 171, "s": 159, "text": "Image used:" }, { "code": null, "e": 273, "s": 171, "text": "Filters –The current version of the library provides the set of predefined image enhancement filters:" }, { "code": null, "e": 281, "s": 273, "text": "1. BLUR" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the blur filterim2 = im1.filter(ImageFilter.BLUR) im2.show()", "e": 535, "s": 281, "text": null }, { "code": null, "e": 554, "s": 535, "text": "Output: 2. CONTOUR" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the contour filterim2 = im1.filter(ImageFilter.CONTOUR) im2.show()", "e": 814, "s": 554, "text": null }, { "code": null, "e": 832, "s": 814, "text": "Output: 3. EMBOSS" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the emboss filterim2 = im1.filter(ImageFilter.EMBOSS) im2.show()", "e": 1090, "s": 832, "text": null }, { "code": null, "e": 1114, "s": 1090, "text": "Output: 4. EDGE_ENHANCE" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the EDGE_ENHANCE filterim2 = im1.filter(ImageFilter.EDGE_ENHANCE) im2.show()", "e": 1384, "s": 1114, "text": null }, { "code": null, "e": 1413, "s": 1384, "text": "Output: 5. EDGE_ENHANCE_MORE" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the EDGE_ENHANCE_MORE filterim2 = im1.filter(ImageFilter.EDGE_ENHANCE_MORE) im2.show()", "e": 1693, "s": 1413, "text": null }, { "code": null, "e": 1701, "s": 1693, "text": "Output:" }, { "code": null, "e": 1716, "s": 1701, "text": "python-utility" }, { "code": null, "e": 1723, "s": 1716, "text": "Python" }, { "code": null, "e": 1821, "s": 1723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1839, "s": 1821, "text": "Python Dictionary" }, { "code": null, "e": 1881, "s": 1839, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1903, "s": 1881, "text": "Enumerate() in Python" }, { "code": null, "e": 1929, "s": 1903, "text": "Python String | replace()" }, { "code": null, "e": 1961, "s": 1929, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1990, "s": 1961, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2017, "s": 1990, "text": "Python Classes and Objects" }, { "code": null, "e": 2038, "s": 2017, "text": "Python OOPs Concepts" }, { "code": null, "e": 2061, "s": 2038, "text": "Introduction To PYTHON" } ]
Plot choropleth maps with shapefiles using Geopandas | by Xiao Wang | Towards Data Science
Choropleth maps are useful and powerful visualisations which present data by areas or regions that colored or patterned according to the values. It is a bit like heatmaps but in geographic shapes. I use it very often as it is really clear to users where the areas are and also handy for them to compare the data between areas with a quick look. If you are creating an interactive dashboard, choropleth maps will help readers slice and dice by areas as well as making the dashboard more vivid and not only limited to charts or tables. My previous experience with choropleth maps was in Power BI where a large range of shapes have defaulted and there’s no flexibility to customize your own map. For example, when working on the crime data, I would like to display the data by police districts instead of cities or regions, which is not achievable by the Power BI shape map. The good thing is with Geopandas in Python, it is easy to achieve with a few lines. Python packages: import pandas as pdimport matplotlib.pyplot as plt #if using matplotlibimport plotly.express as px #if using plotlyimport geopandas as gpd Shapefile: The file for New Zealand police district was downloaded from Koordinates. #set up the file path and read the shapefile datafp = "nz-police-district-boundaries.shx"map_df = gpd.read_file(fp)map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)#read the csv datadf = pd.read_csv('District.csv') You may want to check and see what the shapefile looks like: #see what the map looks likemap_df.plot(figsize=(20, 10)) As you may notice, there were some mismatch between the ‘District.csv’ and the ‘map_df’, for example the ‘Counties Manukau’ in the csv file and ‘Counties/Manukau’ in the map file. So we need to tidy those up before creating the maps: #rename one of the columnsmap_df = map_df.rename({'DISTRICT_N': 'District'}, axis = 'columns')#drop a columnmap_df = map_df.drop(columns = 'DISTRICT_I')#replace the values in the dataframemap_df = map_df.replace(['Counties/Manukau','Northland'],['Counties Manukau','Northen']) The last step before creating the choropleth map was to merge two dataset. This process is similar to SQL: df_merged = map_df.merge(df, #map_df merge to df left_on=[‘District’], right_on=[‘District’]) Then we get a new dataframe: fig, ax = plt.subplots(1, figsize=(10,6))df_merged.plot(column='Sum', cmap='Blues', linewidth=1, ax=ax, edgecolor='0.9', legend = True)ax.axis('off') fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color="Sum", height=500, color_continuous_scale="Viridis")fig.update_geos(fitbounds="locations", visible=True)fig.update_layout( title_text='Map')fig.update(layout = dict(title=dict(x=0.5)))fig.update_layout( margin={"r":0,"t":30,"l":10,"b":10}, coloraxis_colorbar={ 'title':'Sum'})fig.show() Choropleth maps have been used very often in dashboards nowadays. To create the maps, the first thing is to get the shapefile or geo json files you would like to apply in your personalised map and then merge your data accordingly. Have a play with it 🤪! Any questions, feel free to drop me a line here or via my LinkedIn.
[ { "code": null, "e": 369, "s": 172, "text": "Choropleth maps are useful and powerful visualisations which present data by areas or regions that colored or patterned according to the values. It is a bit like heatmaps but in geographic shapes." }, { "code": null, "e": 706, "s": 369, "text": "I use it very often as it is really clear to users where the areas are and also handy for them to compare the data between areas with a quick look. If you are creating an interactive dashboard, choropleth maps will help readers slice and dice by areas as well as making the dashboard more vivid and not only limited to charts or tables." }, { "code": null, "e": 1128, "s": 706, "text": "My previous experience with choropleth maps was in Power BI where a large range of shapes have defaulted and there’s no flexibility to customize your own map. For example, when working on the crime data, I would like to display the data by police districts instead of cities or regions, which is not achievable by the Power BI shape map. The good thing is with Geopandas in Python, it is easy to achieve with a few lines." }, { "code": null, "e": 1145, "s": 1128, "text": "Python packages:" }, { "code": null, "e": 1284, "s": 1145, "text": "import pandas as pdimport matplotlib.pyplot as plt #if using matplotlibimport plotly.express as px #if using plotlyimport geopandas as gpd" }, { "code": null, "e": 1295, "s": 1284, "text": "Shapefile:" }, { "code": null, "e": 1369, "s": 1295, "text": "The file for New Zealand police district was downloaded from Koordinates." }, { "code": null, "e": 1590, "s": 1369, "text": "#set up the file path and read the shapefile datafp = \"nz-police-district-boundaries.shx\"map_df = gpd.read_file(fp)map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)#read the csv datadf = pd.read_csv('District.csv')" }, { "code": null, "e": 1651, "s": 1590, "text": "You may want to check and see what the shapefile looks like:" }, { "code": null, "e": 1709, "s": 1651, "text": "#see what the map looks likemap_df.plot(figsize=(20, 10))" }, { "code": null, "e": 1943, "s": 1709, "text": "As you may notice, there were some mismatch between the ‘District.csv’ and the ‘map_df’, for example the ‘Counties Manukau’ in the csv file and ‘Counties/Manukau’ in the map file. So we need to tidy those up before creating the maps:" }, { "code": null, "e": 2220, "s": 1943, "text": "#rename one of the columnsmap_df = map_df.rename({'DISTRICT_N': 'District'}, axis = 'columns')#drop a columnmap_df = map_df.drop(columns = 'DISTRICT_I')#replace the values in the dataframemap_df = map_df.replace(['Counties/Manukau','Northland'],['Counties Manukau','Northen'])" }, { "code": null, "e": 2327, "s": 2220, "text": "The last step before creating the choropleth map was to merge two dataset. This process is similar to SQL:" }, { "code": null, "e": 2422, "s": 2327, "text": "df_merged = map_df.merge(df, #map_df merge to df left_on=[‘District’], right_on=[‘District’])" }, { "code": null, "e": 2451, "s": 2422, "text": "Then we get a new dataframe:" }, { "code": null, "e": 2601, "s": 2451, "text": "fig, ax = plt.subplots(1, figsize=(10,6))df_merged.plot(column='Sum', cmap='Blues', linewidth=1, ax=ax, edgecolor='0.9', legend = True)ax.axis('off')" }, { "code": null, "e": 3044, "s": 2601, "text": "fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color=\"Sum\", height=500, color_continuous_scale=\"Viridis\")fig.update_geos(fitbounds=\"locations\", visible=True)fig.update_layout( title_text='Map')fig.update(layout = dict(title=dict(x=0.5)))fig.update_layout( margin={\"r\":0,\"t\":30,\"l\":10,\"b\":10}, coloraxis_colorbar={ 'title':'Sum'})fig.show()" }, { "code": null, "e": 3275, "s": 3044, "text": "Choropleth maps have been used very often in dashboards nowadays. To create the maps, the first thing is to get the shapefile or geo json files you would like to apply in your personalised map and then merge your data accordingly." } ]
C++ Inheritance
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on. A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form − class derived-class: access-specifier base-class Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default. Consider a base class Shape and its derived class Rectangle as follows − #include <iostream> using namespace std; // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived class class Rectangle: public Shape { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; return 0; } When the above code is compiled and executed, it produces the following result − Total area: 35 A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class. We can summarize the different access types according to - who can access them in the following way − A derived class inherits all base class methods with the following exceptions − Constructors, destructors and copy constructors of the base class. Overloaded operators of the base class. The friend functions of the base class. When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above. We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied − Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class. Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class. Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class. Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class. Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class. Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class. A C++ class can inherit members from more than one class and here is the extended syntax − class derived-class: access baseA, access baseB.... Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example − #include <iostream> using namespace std; // Base class Shape class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Base class PaintCost class PaintCost { public: int getCost(int area) { return area * 70; } }; // Derived class class Rectangle: public Shape, public PaintCost { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; // Print the total cost of painting cout << "Total paint cost: $" << Rect.getCost(area) << endl; return 0; } When the above code is compiled and executed, it produces the following result − Total area: 35 Total paint cost: $2450 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2632, "s": 2318, "text": "One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time." }, { "code": null, "e": 2922, "s": 2632, "text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class." }, { "code": null, "e": 3070, "s": 2922, "text": "The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on." }, { "code": null, "e": 3358, "s": 3070, "text": "A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form −" }, { "code": null, "e": 3408, "s": 3358, "text": "class derived-class: access-specifier base-class\n" }, { "code": null, "e": 3598, "s": 3408, "text": "Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default." }, { "code": null, "e": 3671, "s": 3598, "text": "Consider a base class Shape and its derived class Rectangle as follows −" }, { "code": null, "e": 4247, "s": 3671, "text": "#include <iostream>\n \nusing namespace std;\n\n// Base class\nclass Shape {\n public:\n void setWidth(int w) {\n width = w;\n }\n void setHeight(int h) {\n height = h;\n }\n \n protected:\n int width;\n int height;\n};\n\n// Derived class\nclass Rectangle: public Shape {\n public:\n int getArea() { \n return (width * height); \n }\n};\n\nint main(void) {\n Rectangle Rect;\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n\n // Print the area of the object.\n cout << \"Total area: \" << Rect.getArea() << endl;\n\n return 0;\n}" }, { "code": null, "e": 4328, "s": 4247, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4344, "s": 4328, "text": "Total area: 35\n" }, { "code": null, "e": 4561, "s": 4344, "text": "A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class." }, { "code": null, "e": 4663, "s": 4561, "text": "We can summarize the different access types according to - who can access them in the following way −" }, { "code": null, "e": 4743, "s": 4663, "text": "A derived class inherits all base class methods with the following exceptions −" }, { "code": null, "e": 4810, "s": 4743, "text": "Constructors, destructors and copy constructors of the base class." }, { "code": null, "e": 4850, "s": 4810, "text": "Overloaded operators of the base class." }, { "code": null, "e": 4890, "s": 4850, "text": "The friend functions of the base class." }, { "code": null, "e": 5095, "s": 4890, "text": "When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above." }, { "code": null, "e": 5258, "s": 5095, "text": "We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied −" }, { "code": null, "e": 5662, "s": 5258, "text": "Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class." }, { "code": null, "e": 6066, "s": 5662, "text": "Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class." }, { "code": null, "e": 6228, "s": 6066, "text": "Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class." }, { "code": null, "e": 6390, "s": 6228, "text": "Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class." }, { "code": null, "e": 6545, "s": 6390, "text": "Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class." }, { "code": null, "e": 6700, "s": 6545, "text": "Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class." }, { "code": null, "e": 6791, "s": 6700, "text": "A C++ class can inherit members from more than one class and here is the extended syntax −" }, { "code": null, "e": 6844, "s": 6791, "text": "class derived-class: access baseA, access baseB....\n" }, { "code": null, "e": 7024, "s": 6844, "text": "Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example −" }, { "code": null, "e": 7892, "s": 7024, "text": "#include <iostream>\n \nusing namespace std;\n\n// Base class Shape\nclass Shape {\n public:\n void setWidth(int w) {\n width = w;\n }\n void setHeight(int h) {\n height = h;\n }\n \n protected:\n int width;\n int height;\n};\n\n// Base class PaintCost\nclass PaintCost {\n public:\n int getCost(int area) {\n return area * 70;\n }\n};\n\n// Derived class\nclass Rectangle: public Shape, public PaintCost {\n public:\n int getArea() {\n return (width * height); \n }\n};\n\nint main(void) {\n Rectangle Rect;\n int area;\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n\n area = Rect.getArea();\n \n // Print the area of the object.\n cout << \"Total area: \" << Rect.getArea() << endl;\n\n // Print the total cost of painting\n cout << \"Total paint cost: $\" << Rect.getCost(area) << endl;\n\n return 0;\n}" }, { "code": null, "e": 7973, "s": 7892, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 8013, "s": 7973, "text": "Total area: 35\nTotal paint cost: $2450\n" }, { "code": null, "e": 8050, "s": 8013, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 8069, "s": 8050, "text": " Arnab Chakraborty" }, { "code": null, "e": 8101, "s": 8069, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 8124, "s": 8101, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8160, "s": 8124, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 8177, "s": 8160, "text": " Frahaan Hussain" }, { "code": null, "e": 8212, "s": 8177, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8229, "s": 8212, "text": " Frahaan Hussain" }, { "code": null, "e": 8264, "s": 8229, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8281, "s": 8264, "text": " Frahaan Hussain" }, { "code": null, "e": 8316, "s": 8281, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8333, "s": 8316, "text": " Frahaan Hussain" }, { "code": null, "e": 8340, "s": 8333, "text": " Print" }, { "code": null, "e": 8351, "s": 8340, "text": " Add Notes" } ]
PHP | ereg_replace() Function - GeeksforGeeks
13 Jun, 2018 The ereg_replace() is an inbuilt function in PHP and is used to search a string pattern in an other string. If pattern is found in the original string then it will replace matching text with a replacement string. You may refer to the article on Regular Expression for basic understanding of pattern matching using regular expressions. Syntax: string ereg_replace ( $string_pattern, $replace_string, $original_string ) Parameters Used: This function accepts three mandatory parameters and all of these parameters are described below. $string_pattern: This parameter specifies the pattern to be searched in the $original_string. Its can be used with both array and string type which is parenthesized substrings. $replace_string: This parameter specifies the string by which the matching text will be replaced and it can be used with both array and string type. The replacement contain substring in the form of \digit, which replaces the text matching digit’th parenthesized substring and \0 produce entire contents string. $original_string: This parameter specifies the input string and can be of both array and string type. Return Value: This function returns a modified string or array if matches found. If matches not fount in the original string then it will return unchanged original string or array. Note: The ereg_replace() function is case sensitive in PHP. This function was deprecated in PHP 5.3.0, and removed in PHP 7.0.0. Examples: Input: $original_string = "Geeksforgeeks PHP article."; $string_pattern = "(.*)PHP(.*)"; $replace_string = " You should read \\1all\\2"; Output: You should read Geeksforgeeks all article. Explanation: Within the parenthesis "\1" and "\2" to access the part of string and replace with 'PHP' to 'all'. Input: $original_string = "Geeksforgeeks is no:one computer science portal."; $replace_string = '1'; $original_string = ereg_replace('one', $replace_string, $original_string); Output: Geeksforgeeks is no:1 computer science portal. Below programs illustrate the ereg_replace() function. Program 1: <?php // Original input string $original_string = "Write any topic ."; // Pattern to be searched$string_pattern = "(.*)any(.*)"; // Replace string$replace_string = " own yours own \\1biography\\2"; echo ereg_replace($patternstrVal, $replacesstrVal, $stringVal); ?> Output: Write own yours own biography topic. Note: While using an integer value as the replacement parameter, we do not get expected result as the function interpret the number to ordinal value of character. Program 2: <?php // Original input string $original_string = "India To Become World's Fifth Largest Economy In 2018."; // Replace string$replace_string = 5; // This function call will not show the expected output as the// function interpret the number to ordinal value of character.echo ereg_replace('Fifth',$replace_string, $original_string); $original_string = "India To Become World's Fifth Largest Economy In 2018."; // Replace String$replace_string = '5'; // This function call will show // the correct expected outputecho ereg_replace('Fifth',$replace_string, $original_string); ?> Output: India To Become World's Largest Economy In 2018. India To Become World's 5 Largest Economy In 2018. Reference: http://php.net/manual/en/function.ereg-replace.php PHP-function Pattern Searching PHP Web Technologies Pattern Searching PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to validate HTML tag using Regular Expression How to validate pin code of India using Regular Expression Build a DFA to accept Binary strings that starts or ends with "01" How to check Aadhaar number is valid or not using Regular Expression How to validate time in 24-hour format using Regular Expression How to Insert Form Data into Database using PHP ? How to pop an alert message box using PHP ? How to execute PHP code using command line ? PHP in_array() Function How to Upload Image into Database and Display it using PHP ?
[ { "code": null, "e": 25302, "s": 25274, "text": "\n13 Jun, 2018" }, { "code": null, "e": 25637, "s": 25302, "text": "The ereg_replace() is an inbuilt function in PHP and is used to search a string pattern in an other string. If pattern is found in the original string then it will replace matching text with a replacement string. You may refer to the article on Regular Expression for basic understanding of pattern matching using regular expressions." }, { "code": null, "e": 25645, "s": 25637, "text": "Syntax:" }, { "code": null, "e": 25722, "s": 25645, "text": "string ereg_replace ( $string_pattern, $replace_string, $original_string )\n" }, { "code": null, "e": 25837, "s": 25722, "text": "Parameters Used: This function accepts three mandatory parameters and all of these parameters are described below." }, { "code": null, "e": 26014, "s": 25837, "text": "$string_pattern: This parameter specifies the pattern to be searched in the $original_string. Its can be used with both array and string type which is parenthesized substrings." }, { "code": null, "e": 26325, "s": 26014, "text": "$replace_string: This parameter specifies the string by which the matching text will be replaced and it can be used with both array and string type. The replacement contain substring in the form of \\digit, which replaces the text matching digit’th parenthesized substring and \\0 produce entire contents string." }, { "code": null, "e": 26427, "s": 26325, "text": "$original_string: This parameter specifies the input string and can be of both array and string type." }, { "code": null, "e": 26608, "s": 26427, "text": "Return Value: This function returns a modified string or array if matches found. If matches not fount in the original string then it will return unchanged original string or array." }, { "code": null, "e": 26737, "s": 26608, "text": "Note: The ereg_replace() function is case sensitive in PHP. This function was deprecated in PHP 5.3.0, and removed in PHP 7.0.0." }, { "code": null, "e": 26747, "s": 26737, "text": "Examples:" }, { "code": null, "e": 27417, "s": 26747, "text": "Input: $original_string = \"Geeksforgeeks PHP article.\"; \n $string_pattern = \"(.*)PHP(.*)\"; \n $replace_string = \" You should read \\\\1all\\\\2\"; \nOutput: You should read Geeksforgeeks all article.\nExplanation: Within the parenthesis \"\\1\" and \"\\2\" to access\n the part of string and replace with 'PHP' to 'all'.\n\nInput: $original_string = \"Geeksforgeeks is no:one computer \n science portal.\";\n $replace_string = '1'; \n $original_string = ereg_replace('one', $replace_string,\n $original_string);\nOutput: Geeksforgeeks is no:1 computer science portal. \n" }, { "code": null, "e": 27472, "s": 27417, "text": "Below programs illustrate the ereg_replace() function." }, { "code": null, "e": 27483, "s": 27472, "text": "Program 1:" }, { "code": "<?php // Original input string $original_string = \"Write any topic .\"; // Pattern to be searched$string_pattern = \"(.*)any(.*)\"; // Replace string$replace_string = \" own yours own \\\\1biography\\\\2\"; echo ereg_replace($patternstrVal, $replacesstrVal, $stringVal); ?>", "e": 27757, "s": 27483, "text": null }, { "code": null, "e": 27765, "s": 27757, "text": "Output:" }, { "code": null, "e": 27803, "s": 27765, "text": "Write own yours own biography topic.\n" }, { "code": null, "e": 27966, "s": 27803, "text": "Note: While using an integer value as the replacement parameter, we do not get expected result as the function interpret the number to ordinal value of character." }, { "code": null, "e": 27977, "s": 27966, "text": "Program 2:" }, { "code": "<?php // Original input string $original_string = \"India To Become World's Fifth Largest Economy In 2018.\"; // Replace string$replace_string = 5; // This function call will not show the expected output as the// function interpret the number to ordinal value of character.echo ereg_replace('Fifth',$replace_string, $original_string); $original_string = \"India To Become World's Fifth Largest Economy In 2018.\"; // Replace String$replace_string = '5'; // This function call will show // the correct expected outputecho ereg_replace('Fifth',$replace_string, $original_string); ?> ", "e": 28614, "s": 27977, "text": null }, { "code": null, "e": 28622, "s": 28614, "text": "Output:" }, { "code": null, "e": 28724, "s": 28622, "text": "India To Become World's Largest Economy In 2018.\nIndia To Become World's 5 Largest Economy In 2018.\n" }, { "code": null, "e": 28786, "s": 28724, "text": "Reference: http://php.net/manual/en/function.ereg-replace.php" }, { "code": null, "e": 28799, "s": 28786, "text": "PHP-function" }, { "code": null, "e": 28817, "s": 28799, "text": "Pattern Searching" }, { "code": null, "e": 28821, "s": 28817, "text": "PHP" }, { "code": null, "e": 28838, "s": 28821, "text": "Web Technologies" }, { "code": null, "e": 28856, "s": 28838, "text": "Pattern Searching" }, { "code": null, "e": 28860, "s": 28856, "text": "PHP" }, { "code": null, "e": 28958, "s": 28860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28967, "s": 28958, "text": "Comments" }, { "code": null, "e": 28980, "s": 28967, "text": "Old Comments" }, { "code": null, "e": 29030, "s": 28980, "text": "How to validate HTML tag using Regular Expression" }, { "code": null, "e": 29089, "s": 29030, "text": "How to validate pin code of India using Regular Expression" }, { "code": null, "e": 29156, "s": 29089, "text": "Build a DFA to accept Binary strings that starts or ends with \"01\"" }, { "code": null, "e": 29225, "s": 29156, "text": "How to check Aadhaar number is valid or not using Regular Expression" }, { "code": null, "e": 29289, "s": 29225, "text": "How to validate time in 24-hour format using Regular Expression" }, { "code": null, "e": 29339, "s": 29289, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29383, "s": 29339, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 29428, "s": 29383, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 29452, "s": 29428, "text": "PHP in_array() Function" } ]
How to run (Model-Agnostic Meta-Learning) MAML algorithm | by Rahul Bhadani | Towards Data Science
MAML is a class of meta-learning algorithms created by Stanford Research and UC Berkeley Alum Dr. Chelsea Finn. MAML was inspired by the idea behind the question that how much data is really needed to learn about something. Can we teach algorithms to learn how to learn? In such a context, there are a few challenges with conventional machine learning algorithms: Intensive training is requiredLabeled data for some problems may be limitedThe performance of the network may be sensitive to the choice of hyperparameters Intensive training is required Labeled data for some problems may be limited The performance of the network may be sensitive to the choice of hyperparameters In such respect, meta-learning algorithms can be designed to address the following tasks: Dynamic selection of inductive biasBuilding meta-rules for multi-task learningLearning to learn with hyperparameter optimization Dynamic selection of inductive bias Building meta-rules for multi-task learning Learning to learn with hyperparameter optimization Taken from Chelsea Finn’s original research: MAML is a meta-learning algorithm that is compatible with any model trained with gradient descent algorithm and covers problems from classification, reinforcement learning (RL)and regression MAML is designed such that it trains a model on a variety of tasks such that it can learn a new learning task with only a small number of training samples. A few important points of MAML are: MAML doesn’t expand the number of learned parameters.No constraint on the architecture or network of the model.Can be combined with other deep-learning frameworks such as Recurrent Neural Network (RNN), Convolutional Neural Network (CNN), and Multi-Layer Perceptron (MLP). MAML doesn’t expand the number of learned parameters. No constraint on the architecture or network of the model. Can be combined with other deep-learning frameworks such as Recurrent Neural Network (RNN), Convolutional Neural Network (CNN), and Multi-Layer Perceptron (MLP). Problem setup for MAML is reproduced from the original paper: MAML introduces an outer loop called meta-training. Chelsea Finn’s Github repo provides the code to reproduce the MAML results. You can use the following steps to reproduce its results: I am going to create a python virtual environment and install dependencies:sudo apt install virtualenvvirtualenv — python=python3.6 maml source maml/bin/activateNext, we install dependencies:pip install tensorflow==1.11.0pip install imageI didn’t use the latest version of Tensorflow as MAML code was written a couple of years ago when TF2 was still not released for public use.Clone the MAML repo: git clone https://github.com/cbfinn/mamlDownload omniglot data, for this article, I am only going to run omniglot example besides sinusoidal example:wget https://github.com/brendenlake/omniglot/raw/master/python/images_background.zipwget https://github.com/brendenlake/omniglot/raw/master/python/images_evaluation.zipUnzip images_background and images_evaluation zip files to maml/data/omniglot folder where mamal folder is the Github repo folder. The directory structure looks as follows: I am going to create a python virtual environment and install dependencies:sudo apt install virtualenvvirtualenv — python=python3.6 maml source maml/bin/activate Next, we install dependencies: pip install tensorflow==1.11.0pip install imageI didn’t use the latest version of Tensorflow as MAML code was written a couple of years ago when TF2 was still not released for public use. Clone the MAML repo: git clone https://github.com/cbfinn/maml Download omniglot data, for this article, I am only going to run omniglot example besides sinusoidal example:wget https://github.com/brendenlake/omniglot/raw/master/python/images_background.zipwget https://github.com/brendenlake/omniglot/raw/master/python/images_evaluation.zip Unzip images_background and images_evaluation zip files to maml/data/omniglot folder where mamal folder is the Github repo folder. The directory structure looks as follows: 7. Navigate to data subfolder of maml folder and copy the content of omniglot to omniglot_resized . The run resize-image script cd maml/datacp -r omniglot/* omniglot_resized/cd omniglot_resizedpython resize_images.py 8. Now, we go back to the root directory of maml repo and run two examples: a. Sinusoid example: python main.py --datasource=sinusoid --logdir=logs/sine/ --metatrain_iterations=70000 --norm=None --update_batch_size=10 b. omniglot example: python main.py --datasource=omniglot --metatrain_iterations=60000 --meta_batch_size=32 --update_batch_size=1 --update_lr=0.4 --num_updates=1 --logdir=logs/omniglot5way/ The checkpoint of each example will be saved in log/ directory. Update: I discovered that there is a bug in the codebase. I believe the bug might have been introduced inadvertently. In main.py , line 160 saver.save(sess, FLAGS.logdir + ‘/’ + exp_string + ‘/model’ + str(itr)) , itr variable is the for loop iterator and I believe that saver.save statement should be executed inside the for loop at the end of the loop and not outside the loop. From here onwards, I believe an intermediate-level machine learning practitioner should be able to modify the pipeline to meet his/her requirements.
[ { "code": null, "e": 443, "s": 172, "text": "MAML is a class of meta-learning algorithms created by Stanford Research and UC Berkeley Alum Dr. Chelsea Finn. MAML was inspired by the idea behind the question that how much data is really needed to learn about something. Can we teach algorithms to learn how to learn?" }, { "code": null, "e": 536, "s": 443, "text": "In such a context, there are a few challenges with conventional machine learning algorithms:" }, { "code": null, "e": 692, "s": 536, "text": "Intensive training is requiredLabeled data for some problems may be limitedThe performance of the network may be sensitive to the choice of hyperparameters" }, { "code": null, "e": 723, "s": 692, "text": "Intensive training is required" }, { "code": null, "e": 769, "s": 723, "text": "Labeled data for some problems may be limited" }, { "code": null, "e": 850, "s": 769, "text": "The performance of the network may be sensitive to the choice of hyperparameters" }, { "code": null, "e": 940, "s": 850, "text": "In such respect, meta-learning algorithms can be designed to address the following tasks:" }, { "code": null, "e": 1069, "s": 940, "text": "Dynamic selection of inductive biasBuilding meta-rules for multi-task learningLearning to learn with hyperparameter optimization" }, { "code": null, "e": 1105, "s": 1069, "text": "Dynamic selection of inductive bias" }, { "code": null, "e": 1149, "s": 1105, "text": "Building meta-rules for multi-task learning" }, { "code": null, "e": 1200, "s": 1149, "text": "Learning to learn with hyperparameter optimization" }, { "code": null, "e": 1245, "s": 1200, "text": "Taken from Chelsea Finn’s original research:" }, { "code": null, "e": 1436, "s": 1245, "text": "MAML is a meta-learning algorithm that is compatible with any model trained with gradient descent algorithm and covers problems from classification, reinforcement learning (RL)and regression" }, { "code": null, "e": 1592, "s": 1436, "text": "MAML is designed such that it trains a model on a variety of tasks such that it can learn a new learning task with only a small number of training samples." }, { "code": null, "e": 1628, "s": 1592, "text": "A few important points of MAML are:" }, { "code": null, "e": 1901, "s": 1628, "text": "MAML doesn’t expand the number of learned parameters.No constraint on the architecture or network of the model.Can be combined with other deep-learning frameworks such as Recurrent Neural Network (RNN), Convolutional Neural Network (CNN), and Multi-Layer Perceptron (MLP)." }, { "code": null, "e": 1955, "s": 1901, "text": "MAML doesn’t expand the number of learned parameters." }, { "code": null, "e": 2014, "s": 1955, "text": "No constraint on the architecture or network of the model." }, { "code": null, "e": 2176, "s": 2014, "text": "Can be combined with other deep-learning frameworks such as Recurrent Neural Network (RNN), Convolutional Neural Network (CNN), and Multi-Layer Perceptron (MLP)." }, { "code": null, "e": 2238, "s": 2176, "text": "Problem setup for MAML is reproduced from the original paper:" }, { "code": null, "e": 2290, "s": 2238, "text": "MAML introduces an outer loop called meta-training." }, { "code": null, "e": 2424, "s": 2290, "text": "Chelsea Finn’s Github repo provides the code to reproduce the MAML results. You can use the following steps to reproduce its results:" }, { "code": null, "e": 3313, "s": 2424, "text": "I am going to create a python virtual environment and install dependencies:sudo apt install virtualenvvirtualenv — python=python3.6 maml source maml/bin/activateNext, we install dependencies:pip install tensorflow==1.11.0pip install imageI didn’t use the latest version of Tensorflow as MAML code was written a couple of years ago when TF2 was still not released for public use.Clone the MAML repo: git clone https://github.com/cbfinn/mamlDownload omniglot data, for this article, I am only going to run omniglot example besides sinusoidal example:wget https://github.com/brendenlake/omniglot/raw/master/python/images_background.zipwget https://github.com/brendenlake/omniglot/raw/master/python/images_evaluation.zipUnzip images_background and images_evaluation zip files to maml/data/omniglot folder where mamal folder is the Github repo folder. The directory structure looks as follows:" }, { "code": null, "e": 3475, "s": 3313, "text": "I am going to create a python virtual environment and install dependencies:sudo apt install virtualenvvirtualenv — python=python3.6 maml source maml/bin/activate" }, { "code": null, "e": 3506, "s": 3475, "text": "Next, we install dependencies:" }, { "code": null, "e": 3694, "s": 3506, "text": "pip install tensorflow==1.11.0pip install imageI didn’t use the latest version of Tensorflow as MAML code was written a couple of years ago when TF2 was still not released for public use." }, { "code": null, "e": 3756, "s": 3694, "text": "Clone the MAML repo: git clone https://github.com/cbfinn/maml" }, { "code": null, "e": 4034, "s": 3756, "text": "Download omniglot data, for this article, I am only going to run omniglot example besides sinusoidal example:wget https://github.com/brendenlake/omniglot/raw/master/python/images_background.zipwget https://github.com/brendenlake/omniglot/raw/master/python/images_evaluation.zip" }, { "code": null, "e": 4207, "s": 4034, "text": "Unzip images_background and images_evaluation zip files to maml/data/omniglot folder where mamal folder is the Github repo folder. The directory structure looks as follows:" }, { "code": null, "e": 4335, "s": 4207, "text": "7. Navigate to data subfolder of maml folder and copy the content of omniglot to omniglot_resized . The run resize-image script" }, { "code": null, "e": 4424, "s": 4335, "text": "cd maml/datacp -r omniglot/* omniglot_resized/cd omniglot_resizedpython resize_images.py" }, { "code": null, "e": 4500, "s": 4424, "text": "8. Now, we go back to the root directory of maml repo and run two examples:" }, { "code": null, "e": 4521, "s": 4500, "text": "a. Sinusoid example:" }, { "code": null, "e": 4642, "s": 4521, "text": "python main.py --datasource=sinusoid --logdir=logs/sine/ --metatrain_iterations=70000 --norm=None --update_batch_size=10" }, { "code": null, "e": 4663, "s": 4642, "text": "b. omniglot example:" }, { "code": null, "e": 4832, "s": 4663, "text": "python main.py --datasource=omniglot --metatrain_iterations=60000 --meta_batch_size=32 --update_batch_size=1 --update_lr=0.4 --num_updates=1 --logdir=logs/omniglot5way/" }, { "code": null, "e": 4896, "s": 4832, "text": "The checkpoint of each example will be saved in log/ directory." }, { "code": null, "e": 5276, "s": 4896, "text": "Update: I discovered that there is a bug in the codebase. I believe the bug might have been introduced inadvertently. In main.py , line 160 saver.save(sess, FLAGS.logdir + ‘/’ + exp_string + ‘/model’ + str(itr)) , itr variable is the for loop iterator and I believe that saver.save statement should be executed inside the for loop at the end of the loop and not outside the loop." } ]
How to find an element based on a data-attribute value using jQuery
To find an element based on a data-attribute value using jQuery is quite easy. Try to run the following code to find an element based on a data-attribute value − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $('[data-slide="0"]').addClass('demo'); }); </script> <style> .demo { font-size: 150%; color: red; } </style> </head> <body> <p data-slide="0">Rocky</p> <p data-slide="1">Amit</p> <p data-slide="2">John</p> </body> </html>
[ { "code": null, "e": 1224, "s": 1062, "text": "To find an element based on a data-attribute value using jQuery is quite easy. Try to run the following code to find an element based on a data-attribute value −" }, { "code": null, "e": 1234, "s": 1224, "text": "Live Demo" }, { "code": null, "e": 1638, "s": 1234, "text": "<!DOCTYPE html>\n<html>\n<head>\n\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function() {\n $('[data-slide=\"0\"]').addClass('demo');\n });\n</script>\n<style>\n.demo {\n font-size: 150%;\n color: red;\n}\n</style>\n</head>\n<body>\n\n<p data-slide=\"0\">Rocky</p>\n<p data-slide=\"1\">Amit</p>\n<p data-slide=\"2\">John</p>\n\n</body>\n</html>" } ]
Generating random numbers in Java - GeeksforGeeks
26 Oct, 2016 Java provides three ways to generate random numbers using some built-in methods and classes as listed below: java.util.Random class Math.random method : Can Generate Random Numbers of double type. ThreadLocalRandom class For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that instance. We can generate random numbers of types integers, float, double, long, booleans using this class. We can pass arguments to the methods for placing an upper bound on the range of the numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5 both inclusive.// A Java program to demonstrate random number generation// using java.util.Random;import java.util.Random; public class generateRandom{ public static void main(String args[]) { // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println("Random Integers: "+rand_int1); System.out.println("Random Integers: "+rand_int2); // Generate Random doubles double rand_dub1 = rand.nextDouble(); double rand_dub2 = rand.nextDouble(); // Print random doubles System.out.println("Random Doubles: "+rand_dub1); System.out.println("Random Doubles: "+rand_dub2); }}Output:Random Integers: 547 Random Integers: 126 Random Doubles: 0.8369779739988428 Random Doubles: 0.5497554388209912 2) Math.random()The class Math contains various methods for performing various numeric operations such as, calculating exponentiation, logarithms etc. One of these methods is random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. The returned values are chosen pseudorandomly. This method can only generate random numbers of type Doubles. Below program explains how to use this method:// Java program to demonstrate working of // Math.random() to generate random numbersimport java.util.*; public class generateRandom{ public static void main(String args[]) { // Generating random doubles System.out.println("Random doubles: " + Math.random()); System.out.println("Random doubles: " + Math.random()); }}Output:Random doubles: 0.13077348615666562 Random doubles: 0.09247016928442775 3) java.util.concurrent.ThreadLocalRandom classThis class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc. Below program explains how to use this class to generate random numbers:// Java program to demonstrate working of ThreadLocalRandom// to generate random numbers.import java.util.concurrent.ThreadLocalRandom; public class generateRandom{ public static void main(String args[]) { // Generate random integers in range 0 to 999 int rand_int1 = ThreadLocalRandom.current().nextInt(); int rand_int2 = ThreadLocalRandom.current().nextInt(); // Print random integers System.out.println("Random Integers: " + rand_int1); System.out.println("Random Integers: " + rand_int2); // Generate Random doubles double rand_dub1 = ThreadLocalRandom.current().nextDouble(); double rand_dub2 = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println("Random Doubles: " + rand_dub1); System.out.println("Random Doubles: " + rand_dub2); // Generate random booleans boolean rand_bool1 = ThreadLocalRandom.current().nextBoolean(); boolean rand_bool2 = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println("Random Booleans: " + rand_bool1); System.out.println("Random Booleans: " + rand_bool2); }}Output:Random Integers: 536953314 Random Integers: 25905330 Random Doubles: 0.7504989954390163 Random Doubles: 0.7658597196204409 Random Booleans: false Random Booleans: true References:https://docs.oracle.comThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave // A Java program to demonstrate random number generation// using java.util.Random;import java.util.Random; public class generateRandom{ public static void main(String args[]) { // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println("Random Integers: "+rand_int1); System.out.println("Random Integers: "+rand_int2); // Generate Random doubles double rand_dub1 = rand.nextDouble(); double rand_dub2 = rand.nextDouble(); // Print random doubles System.out.println("Random Doubles: "+rand_dub1); System.out.println("Random Doubles: "+rand_dub2); }} Output: Random Integers: 547 Random Integers: 126 Random Doubles: 0.8369779739988428 Random Doubles: 0.5497554388209912 // Java program to demonstrate working of // Math.random() to generate random numbersimport java.util.*; public class generateRandom{ public static void main(String args[]) { // Generating random doubles System.out.println("Random doubles: " + Math.random()); System.out.println("Random doubles: " + Math.random()); }} Output: Random doubles: 0.13077348615666562 Random doubles: 0.09247016928442775 // Java program to demonstrate working of ThreadLocalRandom// to generate random numbers.import java.util.concurrent.ThreadLocalRandom; public class generateRandom{ public static void main(String args[]) { // Generate random integers in range 0 to 999 int rand_int1 = ThreadLocalRandom.current().nextInt(); int rand_int2 = ThreadLocalRandom.current().nextInt(); // Print random integers System.out.println("Random Integers: " + rand_int1); System.out.println("Random Integers: " + rand_int2); // Generate Random doubles double rand_dub1 = ThreadLocalRandom.current().nextDouble(); double rand_dub2 = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println("Random Doubles: " + rand_dub1); System.out.println("Random Doubles: " + rand_dub2); // Generate random booleans boolean rand_bool1 = ThreadLocalRandom.current().nextBoolean(); boolean rand_bool2 = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println("Random Booleans: " + rand_bool1); System.out.println("Random Booleans: " + rand_bool2); }} Output: Random Integers: 536953314 Random Integers: 25905330 Random Doubles: 0.7504989954390163 Random Doubles: 0.7658597196204409 Random Booleans: false Random Booleans: true References:https://docs.oracle.com This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24633, "s": 24605, "text": "\n26 Oct, 2016" }, { "code": null, "e": 24742, "s": 24633, "text": "Java provides three ways to generate random numbers using some built-in methods and classes as listed below:" }, { "code": null, "e": 24765, "s": 24742, "text": "java.util.Random class" }, { "code": null, "e": 24830, "s": 24765, "text": "Math.random method : Can Generate Random Numbers of double type." }, { "code": null, "e": 24854, "s": 24830, "text": "ThreadLocalRandom class" }, { "code": null, "e": 25046, "s": 24854, "text": "For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that instance." }, { "code": null, "e": 25144, "s": 25046, "text": "We can generate random numbers of types integers, float, double, long, booleans using this class." }, { "code": null, "e": 29261, "s": 25144, "text": "We can pass arguments to the methods for placing an upper bound on the range of the numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5 both inclusive.// A Java program to demonstrate random number generation// using java.util.Random;import java.util.Random; public class generateRandom{ public static void main(String args[]) { // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println(\"Random Integers: \"+rand_int1); System.out.println(\"Random Integers: \"+rand_int2); // Generate Random doubles double rand_dub1 = rand.nextDouble(); double rand_dub2 = rand.nextDouble(); // Print random doubles System.out.println(\"Random Doubles: \"+rand_dub1); System.out.println(\"Random Doubles: \"+rand_dub2); }}Output:Random Integers: 547\nRandom Integers: 126\nRandom Doubles: 0.8369779739988428\nRandom Doubles: 0.5497554388209912\n 2) Math.random()The class Math contains various methods for performing various numeric operations such as, calculating exponentiation, logarithms etc. One of these methods is random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. The returned values are chosen pseudorandomly. This method can only generate random numbers of type Doubles. Below program explains how to use this method:// Java program to demonstrate working of // Math.random() to generate random numbersimport java.util.*; public class generateRandom{ public static void main(String args[]) { // Generating random doubles System.out.println(\"Random doubles: \" + Math.random()); System.out.println(\"Random doubles: \" + Math.random()); }}Output:Random doubles: 0.13077348615666562\nRandom doubles: 0.09247016928442775\n 3) java.util.concurrent.ThreadLocalRandom classThis class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc. Below program explains how to use this class to generate random numbers:// Java program to demonstrate working of ThreadLocalRandom// to generate random numbers.import java.util.concurrent.ThreadLocalRandom; public class generateRandom{ public static void main(String args[]) { // Generate random integers in range 0 to 999 int rand_int1 = ThreadLocalRandom.current().nextInt(); int rand_int2 = ThreadLocalRandom.current().nextInt(); // Print random integers System.out.println(\"Random Integers: \" + rand_int1); System.out.println(\"Random Integers: \" + rand_int2); // Generate Random doubles double rand_dub1 = ThreadLocalRandom.current().nextDouble(); double rand_dub2 = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println(\"Random Doubles: \" + rand_dub1); System.out.println(\"Random Doubles: \" + rand_dub2); // Generate random booleans boolean rand_bool1 = ThreadLocalRandom.current().nextBoolean(); boolean rand_bool2 = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println(\"Random Booleans: \" + rand_bool1); System.out.println(\"Random Booleans: \" + rand_bool2); }}Output:Random Integers: 536953314\nRandom Integers: 25905330\nRandom Doubles: 0.7504989954390163\nRandom Doubles: 0.7658597196204409\nRandom Booleans: false\nRandom Booleans: true\nReferences:https://docs.oracle.comThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": "// A Java program to demonstrate random number generation// using java.util.Random;import java.util.Random; public class generateRandom{ public static void main(String args[]) { // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println(\"Random Integers: \"+rand_int1); System.out.println(\"Random Integers: \"+rand_int2); // Generate Random doubles double rand_dub1 = rand.nextDouble(); double rand_dub2 = rand.nextDouble(); // Print random doubles System.out.println(\"Random Doubles: \"+rand_dub1); System.out.println(\"Random Doubles: \"+rand_dub2); }}", "e": 30095, "s": 29261, "text": null }, { "code": null, "e": 30103, "s": 30095, "text": "Output:" }, { "code": null, "e": 30216, "s": 30103, "text": "Random Integers: 547\nRandom Integers: 126\nRandom Doubles: 0.8369779739988428\nRandom Doubles: 0.5497554388209912\n" }, { "code": "// Java program to demonstrate working of // Math.random() to generate random numbersimport java.util.*; public class generateRandom{ public static void main(String args[]) { // Generating random doubles System.out.println(\"Random doubles: \" + Math.random()); System.out.println(\"Random doubles: \" + Math.random()); }}", "e": 30568, "s": 30218, "text": null }, { "code": null, "e": 30576, "s": 30568, "text": "Output:" }, { "code": null, "e": 30649, "s": 30576, "text": "Random doubles: 0.13077348615666562\nRandom doubles: 0.09247016928442775\n" }, { "code": "// Java program to demonstrate working of ThreadLocalRandom// to generate random numbers.import java.util.concurrent.ThreadLocalRandom; public class generateRandom{ public static void main(String args[]) { // Generate random integers in range 0 to 999 int rand_int1 = ThreadLocalRandom.current().nextInt(); int rand_int2 = ThreadLocalRandom.current().nextInt(); // Print random integers System.out.println(\"Random Integers: \" + rand_int1); System.out.println(\"Random Integers: \" + rand_int2); // Generate Random doubles double rand_dub1 = ThreadLocalRandom.current().nextDouble(); double rand_dub2 = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println(\"Random Doubles: \" + rand_dub1); System.out.println(\"Random Doubles: \" + rand_dub2); // Generate random booleans boolean rand_bool1 = ThreadLocalRandom.current().nextBoolean(); boolean rand_bool2 = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println(\"Random Booleans: \" + rand_bool1); System.out.println(\"Random Booleans: \" + rand_bool2); }}", "e": 31859, "s": 30651, "text": null }, { "code": null, "e": 31867, "s": 31859, "text": "Output:" }, { "code": null, "e": 32036, "s": 31867, "text": "Random Integers: 536953314\nRandom Integers: 25905330\nRandom Doubles: 0.7504989954390163\nRandom Doubles: 0.7658597196204409\nRandom Booleans: false\nRandom Booleans: true\n" }, { "code": null, "e": 32071, "s": 32036, "text": "References:https://docs.oracle.com" }, { "code": null, "e": 32372, "s": 32071, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 32497, "s": 32372, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32502, "s": 32497, "text": "Java" }, { "code": null, "e": 32507, "s": 32502, "text": "Java" }, { "code": null, "e": 32605, "s": 32507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32614, "s": 32605, "text": "Comments" }, { "code": null, "e": 32627, "s": 32614, "text": "Old Comments" }, { "code": null, "e": 32678, "s": 32627, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32708, "s": 32678, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32739, "s": 32708, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32758, "s": 32739, "text": "Interfaces in Java" }, { "code": null, "e": 32790, "s": 32758, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32808, "s": 32790, "text": "ArrayList in Java" }, { "code": null, "e": 32828, "s": 32808, "text": "Stack Class in Java" }, { "code": null, "e": 32860, "s": 32828, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32884, "s": 32860, "text": "Singleton Class in Java" } ]
Remove personal information from a text with Python — Part II | by Leo van der Meulen | Towards Data Science
This is a follow-up on my previous article on the removal of personal information from texts. The GDPR is the General Data Protection Regulation by the European Union. Its purpose is to protect data of all European residents. Protecting data is also an intrinsic value of a developer. Protecting data in a row/column data structure is relative easy by controlling access to columns and rows. But what about free text? In my previous article I described a solution based on the usage of regular expressions and a list of forbidden words. In this article we add an implementation based on Named Entity Recognition (NER). The full implementation can be found in the github PrivacyFilter project. According to wikipedia NER is: Named-entity recognition (NER) (also known as (named) entity identification, entity chunking, and entity extraction) is a subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pre-defined categories such as person names, organizations, locations, medical codes, time expressions, quantities, monetary values, percentages, etc. So it is all about finding and identifying entities in texts. An entity can be a single word or a series of consecutive words. An entity is classified into a pre-defined category. For example, in the sentence below, three entities are found: The entity person “Sebastian Thrun”, the entity organisation “Google” and the entity date “2007”. NER is a subset of the artificial intelligence field of Natural Language Processing (NLP). This field contains algorithms processing and analysing natural languages. When NER is capable of identifying entities in natural language, these entities can be removed from the text in case it is a privacy related entity like person, organisation, date or location. First we need a NLP processing package. NLP packages are trained per language since all languages have their own grammar. We are working with Dutch so we need one that understands this. We will be using Spacy for our privacy filter. On the Spacy website a tool can be found that helps installing Spacy. After selecting your Python environoment and language, it gives the appropriate commands to install Spacy: The selected pipeline (efficiency or accuracy) determines the accuracy of the NER model versus the size and speed. Selecting ‘efficiency’ results in a smaller and faster model but with lower accuracy compared to ‘accuracy’. It depends on your use case which model is more appropriate. For development we choose to use the efficiency model. Running a first NER analysis: After importing the Spacy package in line 2, a model is loaded using the spacy.load() method. In this case the efficient model for Dutch is loaded. A model is specified by its name, which is identical with the name used to download the model in the previous step. To switch to the accurate Dutch language model replace “nl_core_news_sm” with “nl_core_news_lg”. For the example above this results in the same output. A quick, simple performance test shows that loading the small model takes ~2.0 seconds and the large model takes ~4.5 seconds. Analysing a sentence is 5.5 milliseconds versus 6.0 milliseconds. The large model seems to take approximately 500 MB memory extra. The meaning of the Part of Speech (POS) tags can be found on this site. For our example, they are: Geert PROPN PERSON Proper noun, personwerkt VERB Verbsinds ADP Adposition, case marking2010 NUM DATE Numeral, datevoor ADB AdpositionHAL PROPN ORG Proper noun, organisation. PUNCT Punctuation For filtering PII we are interested in the POS types NUM and PROPN. We will replace the POS text elements with a tag describing their entity type . The first part of the code loads the language model and parses the input string to a list of tokens (doc). The loop in lines 8–16 build the filtered text by iterating over all tokens in the document. If a token is of type PROPN, NOUN or NUMBER it is replaced with a tag <...>, where the tag is equal to the entity type recognized by Spacy. All tokens are, with a prefix space, concatenated to the new string. The prefix is required since tokenizing the string has removed these. In case of a punctuation symbol, no prefix space is added (line 12–13). After the loop the first character of the new string is a space due to line 11 or 13 so we need to remove this space (line 17). This results in the string without privacy information. How good is it? In the previous article we have build a privacy filter based on a forbidden word list. That apprach requires more code and effort compared to NER. But how do they compare? NER requires grammatically correct sentences. In that case, replacement of privacy information works well, even if names are misspelled. NER is superior to the forbidden word list. The forbidden word filter will replace forbidden words, no matter what there context is. Especially the list of street names and city names results in a lot of unnecessary deleted words. E.g., words like plant names, animals or ojects like Castle are common as street names and will be removed from the text. This might remove a lot of unnecessary words, reducing the usability of the resulting text. NER will perform better. If the text is not grammatically correct (e.g. the answer ‘Peter’ to the question ‘What is your name?’ will not be filtered correct by NER. These sentences are common in chat messages and transcripts of conversations. The NER approach will fail in these cases since the NER algorithm cannot determine the nature of these answers with one or a few words. So it all depends on your use case and required level of filtering. This combination determines if the best approach is to use the forbidden list version, the NER version or even a combination of the two. The latter will combine the advantages of both approaches (but also part of their weaknesses). To find the best approach, take a subset of your data to filter and test different algorithms and/or combinations to find the best fitting one. Some examples to compare NER with the forbidden word list (FWL): INPUT: Geert werkt sinds 2010 voor HAL.NER : <FILTERED> werkt sinds <FILTERED> voor <FILTERED>.FWL : <FILTERED> werkt sinds <FILTERED> voor HAL.INPUT: Heert werkt sinds 2010 voor HAL.NER : <FILTERED> werkt sinds <FILTERED> voor <FILTERED>.FWL : Heert werkt sinds <FILTERED> voor HAL.INPUT: Wat is je naam? Geert.NER : Wat is je naam? Geert.FWL : Wat is je naam? FILTERED.INPUT: Geert kijkt naar de duiven op het dak.NER : <FILTERED> kijkt naar de duiven op het dak.FWL : <FILTERED> kijkt naar de <FILTERED> op het dak. (all tags like <PERSON> are replaced with the generic tag <FILTERED> for ease of comparison) The first example shows tat FWL cannot remove company names since it has no list of company names. The NER algorithm has determined on the sentence that ‘HAL’ is a noun en more specific an organisation. The second example shows that NER can handle a type error in the name since it looks at the structure of the sentence while FWL does not recognize ‘Heert’ as a name. The list of names only contain the correct spelled versions. The third example shows that NER needs grammatical correct sentences to identify ‘Geert’ as a name. This could be the transcript of a conversation or the interaction in a chat. It shows how NER works good with written language but has trouble understanding spoken (like) language. And in the last example FWL removes the word ‘duiven’ since it does not only describe the animal (duiven is Dutch for pigeons) but is also the name of a city. The privacy filter code on Github contains both approaches and during initialisation it is possible to choose the NER approach or the FWL approach. We did not touch the regular expressions in this article, but selecting the NER approach will also execute the regular expressions (NER does not recognize and replace URL’s etc). It also contains some example texts to use and filter to see the differences between both approaches in real life us cases. This article, and the previous, describe two approaches to remove personal information in text. Both approaches have their strong sides and weaknesses and it is not possible to choose one approach for all use cases. Removing more privacy information also results in removing more non-privacy information and thereby reducing the value of the filtered text. NER is more accurate in removal of identified privacy information but requires well formed sentences to operate. For maximum security it is even possible to combine both approaches. Feel free to experiment with the implementation on Github. I hope you enjoyed this article. For more inspiration check some of my other articles: Remove personal information from text with Python Side-by-side comparison of strings in Python Parallel web requests with Python All public transport leads to Utrecht, not Rome Visualization of travel times with OTP and QGIS Disclaimer: The views and opinions included in this article belong only to the author.
[ { "code": null, "e": 266, "s": 172, "text": "This is a follow-up on my previous article on the removal of personal information from texts." }, { "code": null, "e": 590, "s": 266, "text": "The GDPR is the General Data Protection Regulation by the European Union. Its purpose is to protect data of all European residents. Protecting data is also an intrinsic value of a developer. Protecting data in a row/column data structure is relative easy by controlling access to columns and rows. But what about free text?" }, { "code": null, "e": 865, "s": 590, "text": "In my previous article I described a solution based on the usage of regular expressions and a list of forbidden words. In this article we add an implementation based on Named Entity Recognition (NER). The full implementation can be found in the github PrivacyFilter project." }, { "code": null, "e": 896, "s": 865, "text": "According to wikipedia NER is:" }, { "code": null, "e": 1288, "s": 896, "text": "Named-entity recognition (NER) (also known as (named) entity identification, entity chunking, and entity extraction) is a subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pre-defined categories such as person names, organizations, locations, medical codes, time expressions, quantities, monetary values, percentages, etc." }, { "code": null, "e": 1628, "s": 1288, "text": "So it is all about finding and identifying entities in texts. An entity can be a single word or a series of consecutive words. An entity is classified into a pre-defined category. For example, in the sentence below, three entities are found: The entity person “Sebastian Thrun”, the entity organisation “Google” and the entity date “2007”." }, { "code": null, "e": 1987, "s": 1628, "text": "NER is a subset of the artificial intelligence field of Natural Language Processing (NLP). This field contains algorithms processing and analysing natural languages. When NER is capable of identifying entities in natural language, these entities can be removed from the text in case it is a privacy related entity like person, organisation, date or location." }, { "code": null, "e": 2220, "s": 1987, "text": "First we need a NLP processing package. NLP packages are trained per language since all languages have their own grammar. We are working with Dutch so we need one that understands this. We will be using Spacy for our privacy filter." }, { "code": null, "e": 2397, "s": 2220, "text": "On the Spacy website a tool can be found that helps installing Spacy. After selecting your Python environoment and language, it gives the appropriate commands to install Spacy:" }, { "code": null, "e": 2767, "s": 2397, "text": "The selected pipeline (efficiency or accuracy) determines the accuracy of the NER model versus the size and speed. Selecting ‘efficiency’ results in a smaller and faster model but with lower accuracy compared to ‘accuracy’. It depends on your use case which model is more appropriate. For development we choose to use the efficiency model. Running a first NER analysis:" }, { "code": null, "e": 3183, "s": 2767, "text": "After importing the Spacy package in line 2, a model is loaded using the spacy.load() method. In this case the efficient model for Dutch is loaded. A model is specified by its name, which is identical with the name used to download the model in the previous step. To switch to the accurate Dutch language model replace “nl_core_news_sm” with “nl_core_news_lg”. For the example above this results in the same output." }, { "code": null, "e": 3441, "s": 3183, "text": "A quick, simple performance test shows that loading the small model takes ~2.0 seconds and the large model takes ~4.5 seconds. Analysing a sentence is 5.5 milliseconds versus 6.0 milliseconds. The large model seems to take approximately 500 MB memory extra." }, { "code": null, "e": 3540, "s": 3441, "text": "The meaning of the Part of Speech (POS) tags can be found on this site. For our example, they are:" }, { "code": null, "e": 3808, "s": 3540, "text": "Geert PROPN PERSON Proper noun, personwerkt VERB Verbsinds ADP Adposition, case marking2010 NUM DATE Numeral, datevoor ADB AdpositionHAL PROPN ORG Proper noun, organisation. PUNCT Punctuation" }, { "code": null, "e": 3956, "s": 3808, "text": "For filtering PII we are interested in the POS types NUM and PROPN. We will replace the POS text elements with a tag describing their entity type ." }, { "code": null, "e": 4507, "s": 3956, "text": "The first part of the code loads the language model and parses the input string to a list of tokens (doc). The loop in lines 8–16 build the filtered text by iterating over all tokens in the document. If a token is of type PROPN, NOUN or NUMBER it is replaced with a tag <...>, where the tag is equal to the entity type recognized by Spacy. All tokens are, with a prefix space, concatenated to the new string. The prefix is required since tokenizing the string has removed these. In case of a punctuation symbol, no prefix space is added (line 12–13)." }, { "code": null, "e": 4691, "s": 4507, "text": "After the loop the first character of the new string is a space due to line 11 or 13 so we need to remove this space (line 17). This results in the string without privacy information." }, { "code": null, "e": 4707, "s": 4691, "text": "How good is it?" }, { "code": null, "e": 4879, "s": 4707, "text": "In the previous article we have build a privacy filter based on a forbidden word list. That apprach requires more code and effort compared to NER. But how do they compare?" }, { "code": null, "e": 5060, "s": 4879, "text": "NER requires grammatically correct sentences. In that case, replacement of privacy information works well, even if names are misspelled. NER is superior to the forbidden word list." }, { "code": null, "e": 5486, "s": 5060, "text": "The forbidden word filter will replace forbidden words, no matter what there context is. Especially the list of street names and city names results in a lot of unnecessary deleted words. E.g., words like plant names, animals or ojects like Castle are common as street names and will be removed from the text. This might remove a lot of unnecessary words, reducing the usability of the resulting text. NER will perform better." }, { "code": null, "e": 5840, "s": 5486, "text": "If the text is not grammatically correct (e.g. the answer ‘Peter’ to the question ‘What is your name?’ will not be filtered correct by NER. These sentences are common in chat messages and transcripts of conversations. The NER approach will fail in these cases since the NER algorithm cannot determine the nature of these answers with one or a few words." }, { "code": null, "e": 6284, "s": 5840, "text": "So it all depends on your use case and required level of filtering. This combination determines if the best approach is to use the forbidden list version, the NER version or even a combination of the two. The latter will combine the advantages of both approaches (but also part of their weaknesses). To find the best approach, take a subset of your data to filter and test different algorithms and/or combinations to find the best fitting one." }, { "code": null, "e": 6349, "s": 6284, "text": "Some examples to compare NER with the forbidden word list (FWL):" }, { "code": null, "e": 6876, "s": 6349, "text": "INPUT: Geert werkt sinds 2010 voor HAL.NER : <FILTERED> werkt sinds <FILTERED> voor <FILTERED>.FWL : <FILTERED> werkt sinds <FILTERED> voor HAL.INPUT: Heert werkt sinds 2010 voor HAL.NER : <FILTERED> werkt sinds <FILTERED> voor <FILTERED>.FWL : Heert werkt sinds <FILTERED> voor HAL.INPUT: Wat is je naam? Geert.NER : Wat is je naam? Geert.FWL : Wat is je naam? FILTERED.INPUT: Geert kijkt naar de duiven op het dak.NER : <FILTERED> kijkt naar de duiven op het dak.FWL : <FILTERED> kijkt naar de <FILTERED> op het dak." }, { "code": null, "e": 6969, "s": 6876, "text": "(all tags like <PERSON> are replaced with the generic tag <FILTERED> for ease of comparison)" }, { "code": null, "e": 7172, "s": 6969, "text": "The first example shows tat FWL cannot remove company names since it has no list of company names. The NER algorithm has determined on the sentence that ‘HAL’ is a noun en more specific an organisation." }, { "code": null, "e": 7399, "s": 7172, "text": "The second example shows that NER can handle a type error in the name since it looks at the structure of the sentence while FWL does not recognize ‘Heert’ as a name. The list of names only contain the correct spelled versions." }, { "code": null, "e": 7680, "s": 7399, "text": "The third example shows that NER needs grammatical correct sentences to identify ‘Geert’ as a name. This could be the transcript of a conversation or the interaction in a chat. It shows how NER works good with written language but has trouble understanding spoken (like) language." }, { "code": null, "e": 7839, "s": 7680, "text": "And in the last example FWL removes the word ‘duiven’ since it does not only describe the animal (duiven is Dutch for pigeons) but is also the name of a city." }, { "code": null, "e": 8290, "s": 7839, "text": "The privacy filter code on Github contains both approaches and during initialisation it is possible to choose the NER approach or the FWL approach. We did not touch the regular expressions in this article, but selecting the NER approach will also execute the regular expressions (NER does not recognize and replace URL’s etc). It also contains some example texts to use and filter to see the differences between both approaches in real life us cases." }, { "code": null, "e": 8888, "s": 8290, "text": "This article, and the previous, describe two approaches to remove personal information in text. Both approaches have their strong sides and weaknesses and it is not possible to choose one approach for all use cases. Removing more privacy information also results in removing more non-privacy information and thereby reducing the value of the filtered text. NER is more accurate in removal of identified privacy information but requires well formed sentences to operate. For maximum security it is even possible to combine both approaches. Feel free to experiment with the implementation on Github." }, { "code": null, "e": 8975, "s": 8888, "text": "I hope you enjoyed this article. For more inspiration check some of my other articles:" }, { "code": null, "e": 9025, "s": 8975, "text": "Remove personal information from text with Python" }, { "code": null, "e": 9070, "s": 9025, "text": "Side-by-side comparison of strings in Python" }, { "code": null, "e": 9104, "s": 9070, "text": "Parallel web requests with Python" }, { "code": null, "e": 9152, "s": 9104, "text": "All public transport leads to Utrecht, not Rome" }, { "code": null, "e": 9200, "s": 9152, "text": "Visualization of travel times with OTP and QGIS" } ]
How to explain neural networks using SHAP | by Gianluca Malato | Towards Data Science
Neural networks are fascinating and very efficient tools for data scientists, but they have a very huge flaw: they are unexplainable black boxes. In fact, they don’t give us any information about feature importance. Fortunately, there is a powerful approach we can use to interpret every model, even neural networks. It is the SHAP approach. Let’s see how to use it to explain and interpret a neural network in Python. SHAP stands for SHapley Additive exPlanations. It’s a way to calculate the impact of a feature to the value of the target variable. The idea is you have to consider each feature as a player and the dataset as a team. Each player gives their contribution to the result of the team. The sum of these contributions gives us the value of the target variable given some values of the features (i.e. given a particular record). The main concept is that the impact of a feature doesn’t rely only on the single feature, but on the entire set of features in the dataset. So, SHAP calculates the impact of every feature to the target variable (called shap value) using combinatorial calculus and retraining the model over all the combination of features that contains the one we are considering. The average absolute value of the impact of a feature against a target variable can be used as a measure of its importance. A very clear explanation of SHAP is given in this great article. The benefit of SHAP is that it doesn’t care about the model we use. In fact, it is a model-agnostic approach. So, it’s perfect to explain those models that don’t give us their own interpretation of feature importance, like neural networks. Let’s see how to use SHAP in Python with neural networks. In this example, we are going to calculate feature impact using SHAP for a neural network using Python and scikit-learn. In real-life cases, you’d probably use Keras to build a neural network, but the concept is exactly the same. For this example, we are going to use the diabetes dataset of scikit-learn, which is a regression dataset. Let’s first install shap library. !pip install shap Then, let’s import it and other useful libraries. import shap from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPRegressor from sklearn.pipeline import make_pipeline from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split Now we can load our dataset and the feature names, which will be useful later. X,y = load_diabetes(return_X_y=True) features = load_diabetes()['feature_names'] We can now split our dataset into training and test. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) Now we have to create our model. Since we are talking about a neural network, we must scale the features in advance. For this example, I’ll use a standard scaler. The model itself is a feedforward neural network with 5 neurons in the hidden layer, 10000 epochs and a logistic activation function with an auto-adaptive learning rate. In real life, you will optimize these hyperparameters properly before setting these values. model = make_pipeline( StandardScaler(), MLPRegressor(hidden_layer_sizes=(5,),activation='logistic', max_iter=10000,learning_rate='invscaling',random_state=0) ) We can now fit our model. model.fit(X_train,y_train) Now it comes the SHAP part. First of all, we need to create an object called explainer. It’s the object that takes, in input, the predict method of our model and the training dataset. In order to make SHAP model-agnostic, it performs a perturbation around the points of the training dataset and calculates the impact of this perturbation to the model. It’s a type of resampling technique, whose number of samples is set later. This approach is related to another famous approach called LIME, which has been proved to be a special case of the original SHAP approach. The result is a statistical estimate of the SHAP values. So, first of all, let’s define the explainer object. explainer = shap.KernelExplainer(model.predict,X_train) Now we can calculate the shap values. Remember that they are calculated resampling the training dataset and calculating the impact over these perturbations, so we have to define a proper number of samples. For this example, I’ll use 100 samples. Then, the impact is calculated on the test dataset. shap_values = explainer.shap_values(X_test,nsamples=100) A nice progress bar appears and shows the progress of the calculation, which can be quite slow. At the end, we get a (n_samples,n_features) numpy array. Each element is the shap value of that feature of that record. Remember that shap values are calculated for each feature and for each record. Now we can plot what is called a “summary plot”. Let’s first plot it and then we’ll comment the results. shap.summary_plot(shap_values,X_test,feature_names=features) Each point of every row is a record of the test dataset. The features are sorted from the most important one to the less important. We can see that s5 is the most important feature. The higher the value of this feature, the more positive the impact on the target. The lower this value, the more negative the contribution. Let’s go deeper inside a particular record, for example the first one. A very useful plot we can draw is called force plot shap.initjs() shap.force_plot(explainer.expected_value, shap_values[0,:] ,X_test[0,:],feature_names=features) 113.90 is the predicted value. The base value is the average value of the target variable across all the records. Each stripe shows the impact of its feature in pushing the value of the target variable farther or closer to the base value. Red stripes show that their features push the value towards higher values. Blue stripes show that their features push the value towards lower values. The wider a stripe, the higher (in absolute value) the contribution. The sum of these contributions pushes the value of the target variable from the vase value to the final, predicted value. As we can see, for this particular record, bmi, bp, s2, sex and s5 values have a positive contribution to the predicted value. s5 is still the most important variable of this record, because its contribution is the widest one (it has the largest stripe). The only variable that shows a negative contribution is s1, but it’s not strong enough to move the predicted value lower than the base value. So, since the total positive contribution (red stripes) is larger than the negative contribution (blue stripe), the final value is greater than the base value. That’s how SHAP works. As we can see, we are learning several things about feature importance by reading only these charts. We don’t care about the model we are using, because SHAP is a model-agnostic approach. We just care about how the features impact the predicted value. This is very helpful for explaining black-boxes models like, in this example, neural networks. We could never achieve such a knowledge of our dataset just knowing the weights of our neural network and that’s why SHAP is a very useful approach. SHAP is a very powerful approach when it comes to explaining models that are not able to give us their own interpretation of feature importance. Such models are, for example, neural networks and KNN. Although this method is quite powerful, there’s no free lunch and we have to suffer some computationally expensive calculations that we must be aware of. If you want to learn mode about neural networks and SHAP technique, you can join my 10+ hours online course about Supervised Machine Learning in Python. Originally published at https://www.yourdatateacher.com on May 17, 2021.
[ { "code": null, "e": 514, "s": 172, "text": "Neural networks are fascinating and very efficient tools for data scientists, but they have a very huge flaw: they are unexplainable black boxes. In fact, they don’t give us any information about feature importance. Fortunately, there is a powerful approach we can use to interpret every model, even neural networks. It is the SHAP approach." }, { "code": null, "e": 591, "s": 514, "text": "Let’s see how to use it to explain and interpret a neural network in Python." }, { "code": null, "e": 1013, "s": 591, "text": "SHAP stands for SHapley Additive exPlanations. It’s a way to calculate the impact of a feature to the value of the target variable. The idea is you have to consider each feature as a player and the dataset as a team. Each player gives their contribution to the result of the team. The sum of these contributions gives us the value of the target variable given some values of the features (i.e. given a particular record)." }, { "code": null, "e": 1501, "s": 1013, "text": "The main concept is that the impact of a feature doesn’t rely only on the single feature, but on the entire set of features in the dataset. So, SHAP calculates the impact of every feature to the target variable (called shap value) using combinatorial calculus and retraining the model over all the combination of features that contains the one we are considering. The average absolute value of the impact of a feature against a target variable can be used as a measure of its importance." }, { "code": null, "e": 1566, "s": 1501, "text": "A very clear explanation of SHAP is given in this great article." }, { "code": null, "e": 1806, "s": 1566, "text": "The benefit of SHAP is that it doesn’t care about the model we use. In fact, it is a model-agnostic approach. So, it’s perfect to explain those models that don’t give us their own interpretation of feature importance, like neural networks." }, { "code": null, "e": 1864, "s": 1806, "text": "Let’s see how to use SHAP in Python with neural networks." }, { "code": null, "e": 2094, "s": 1864, "text": "In this example, we are going to calculate feature impact using SHAP for a neural network using Python and scikit-learn. In real-life cases, you’d probably use Keras to build a neural network, but the concept is exactly the same." }, { "code": null, "e": 2201, "s": 2094, "text": "For this example, we are going to use the diabetes dataset of scikit-learn, which is a regression dataset." }, { "code": null, "e": 2235, "s": 2201, "text": "Let’s first install shap library." }, { "code": null, "e": 2253, "s": 2235, "text": "!pip install shap" }, { "code": null, "e": 2303, "s": 2253, "text": "Then, let’s import it and other useful libraries." }, { "code": null, "e": 2551, "s": 2303, "text": "import shap from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPRegressor from sklearn.pipeline import make_pipeline from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split" }, { "code": null, "e": 2630, "s": 2551, "text": "Now we can load our dataset and the feature names, which will be useful later." }, { "code": null, "e": 2711, "s": 2630, "text": "X,y = load_diabetes(return_X_y=True) features = load_diabetes()['feature_names']" }, { "code": null, "e": 2764, "s": 2711, "text": "We can now split our dataset into training and test." }, { "code": null, "e": 2855, "s": 2764, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)" }, { "code": null, "e": 3280, "s": 2855, "text": "Now we have to create our model. Since we are talking about a neural network, we must scale the features in advance. For this example, I’ll use a standard scaler. The model itself is a feedforward neural network with 5 neurons in the hidden layer, 10000 epochs and a logistic activation function with an auto-adaptive learning rate. In real life, you will optimize these hyperparameters properly before setting these values." }, { "code": null, "e": 3441, "s": 3280, "text": "model = make_pipeline( StandardScaler(), MLPRegressor(hidden_layer_sizes=(5,),activation='logistic', max_iter=10000,learning_rate='invscaling',random_state=0) )" }, { "code": null, "e": 3467, "s": 3441, "text": "We can now fit our model." }, { "code": null, "e": 3494, "s": 3467, "text": "model.fit(X_train,y_train)" }, { "code": null, "e": 4117, "s": 3494, "text": "Now it comes the SHAP part. First of all, we need to create an object called explainer. It’s the object that takes, in input, the predict method of our model and the training dataset. In order to make SHAP model-agnostic, it performs a perturbation around the points of the training dataset and calculates the impact of this perturbation to the model. It’s a type of resampling technique, whose number of samples is set later. This approach is related to another famous approach called LIME, which has been proved to be a special case of the original SHAP approach. The result is a statistical estimate of the SHAP values." }, { "code": null, "e": 4170, "s": 4117, "text": "So, first of all, let’s define the explainer object." }, { "code": null, "e": 4226, "s": 4170, "text": "explainer = shap.KernelExplainer(model.predict,X_train)" }, { "code": null, "e": 4472, "s": 4226, "text": "Now we can calculate the shap values. Remember that they are calculated resampling the training dataset and calculating the impact over these perturbations, so we have to define a proper number of samples. For this example, I’ll use 100 samples." }, { "code": null, "e": 4524, "s": 4472, "text": "Then, the impact is calculated on the test dataset." }, { "code": null, "e": 4581, "s": 4524, "text": "shap_values = explainer.shap_values(X_test,nsamples=100)" }, { "code": null, "e": 4677, "s": 4581, "text": "A nice progress bar appears and shows the progress of the calculation, which can be quite slow." }, { "code": null, "e": 4876, "s": 4677, "text": "At the end, we get a (n_samples,n_features) numpy array. Each element is the shap value of that feature of that record. Remember that shap values are calculated for each feature and for each record." }, { "code": null, "e": 4981, "s": 4876, "text": "Now we can plot what is called a “summary plot”. Let’s first plot it and then we’ll comment the results." }, { "code": null, "e": 5042, "s": 4981, "text": "shap.summary_plot(shap_values,X_test,feature_names=features)" }, { "code": null, "e": 5364, "s": 5042, "text": "Each point of every row is a record of the test dataset. The features are sorted from the most important one to the less important. We can see that s5 is the most important feature. The higher the value of this feature, the more positive the impact on the target. The lower this value, the more negative the contribution." }, { "code": null, "e": 5487, "s": 5364, "text": "Let’s go deeper inside a particular record, for example the first one. A very useful plot we can draw is called force plot" }, { "code": null, "e": 5597, "s": 5487, "text": "shap.initjs() shap.force_plot(explainer.expected_value, shap_values[0,:] ,X_test[0,:],feature_names=features)" }, { "code": null, "e": 6177, "s": 5597, "text": "113.90 is the predicted value. The base value is the average value of the target variable across all the records. Each stripe shows the impact of its feature in pushing the value of the target variable farther or closer to the base value. Red stripes show that their features push the value towards higher values. Blue stripes show that their features push the value towards lower values. The wider a stripe, the higher (in absolute value) the contribution. The sum of these contributions pushes the value of the target variable from the vase value to the final, predicted value." }, { "code": null, "e": 6757, "s": 6177, "text": "As we can see, for this particular record, bmi, bp, s2, sex and s5 values have a positive contribution to the predicted value. s5 is still the most important variable of this record, because its contribution is the widest one (it has the largest stripe). The only variable that shows a negative contribution is s1, but it’s not strong enough to move the predicted value lower than the base value. So, since the total positive contribution (red stripes) is larger than the negative contribution (blue stripe), the final value is greater than the base value. That’s how SHAP works." }, { "code": null, "e": 7104, "s": 6757, "text": "As we can see, we are learning several things about feature importance by reading only these charts. We don’t care about the model we are using, because SHAP is a model-agnostic approach. We just care about how the features impact the predicted value. This is very helpful for explaining black-boxes models like, in this example, neural networks." }, { "code": null, "e": 7253, "s": 7104, "text": "We could never achieve such a knowledge of our dataset just knowing the weights of our neural network and that’s why SHAP is a very useful approach." }, { "code": null, "e": 7607, "s": 7253, "text": "SHAP is a very powerful approach when it comes to explaining models that are not able to give us their own interpretation of feature importance. Such models are, for example, neural networks and KNN. Although this method is quite powerful, there’s no free lunch and we have to suffer some computationally expensive calculations that we must be aware of." }, { "code": null, "e": 7760, "s": 7607, "text": "If you want to learn mode about neural networks and SHAP technique, you can join my 10+ hours online course about Supervised Machine Learning in Python." } ]
SVG <symbol> Element - GeeksforGeeks
31 Mar, 2022 SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas. The SVG <symbol> element is used to define graphical template objects which can be instantiated by the <use> element. The use of symbol elements for graphics that are used multiple times in the same document adds structure and semantics. Syntax: <symbol attribute="" > content Here </symbol> Attribute: x: x-axis coordinates the positioning of the image. y: y-axis coordinates the positioning of the image. width: Width of the image. height: Height of the image. viewBox: Bound of the SVG element. Global Attributes: Some global attributes used like core attributes and styling attributes, etc. Example 1: <!DOCTYPE html><html> <body> <svg width="400" height="400" xmlns="http://www.w3.org/2000/svg"> <symbol id="circ" width="10" height="10" viewBox="0 0 2 2"> <circle cx="1" cy="1" r="1" /> </symbol> <use xlink:href="#circ" x="5" y="5"/> </svg></body> </html> Output: A dot symbol. Example 2: <!DOCTYPE html><html> <body> <svg viewBox="0 0 80 20" xmlns="http://www.w3.org/2000/svg"> <symbol id="circ" width="10" height="10" viewBox="0 0 2 2"> <rect height="10" width="10" /> </symbol> <use xlink:href="#circ" x="5" y="5" opacity="0.5" fill="green"/> </svg></body> </html> Output: Supported Browsers: The following browsers are supported by this SVG element: Chrome Edge Firefox Safari Internet Explorer Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-SVG SVG-Element HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container 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": 24503, "s": 24475, "text": "\n31 Mar, 2022" }, { "code": null, "e": 24611, "s": 24503, "text": "SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas." }, { "code": null, "e": 24849, "s": 24611, "text": "The SVG <symbol> element is used to define graphical template objects which can be instantiated by the <use> element. The use of symbol elements for graphics that are used multiple times in the same document adds structure and semantics." }, { "code": null, "e": 24857, "s": 24849, "text": "Syntax:" }, { "code": null, "e": 24908, "s": 24857, "text": "<symbol attribute=\"\" >\n content Here\n</symbol>\n" }, { "code": null, "e": 24919, "s": 24908, "text": "Attribute:" }, { "code": null, "e": 24971, "s": 24919, "text": "x: x-axis coordinates the positioning of the image." }, { "code": null, "e": 25023, "s": 24971, "text": "y: y-axis coordinates the positioning of the image." }, { "code": null, "e": 25050, "s": 25023, "text": "width: Width of the image." }, { "code": null, "e": 25079, "s": 25050, "text": "height: Height of the image." }, { "code": null, "e": 25114, "s": 25079, "text": "viewBox: Bound of the SVG element." }, { "code": null, "e": 25211, "s": 25114, "text": "Global Attributes: Some global attributes used like core attributes and styling attributes, etc." }, { "code": null, "e": 25222, "s": 25211, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <body> <svg width=\"400\" height=\"400\" xmlns=\"http://www.w3.org/2000/svg\"> <symbol id=\"circ\" width=\"10\" height=\"10\" viewBox=\"0 0 2 2\"> <circle cx=\"1\" cy=\"1\" r=\"1\" /> </symbol> <use xlink:href=\"#circ\" x=\"5\" y=\"5\"/> </svg></body> </html>", "e": 25591, "s": 25222, "text": null }, { "code": null, "e": 25613, "s": 25591, "text": "Output: A dot symbol." }, { "code": null, "e": 25624, "s": 25613, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <body> <svg viewBox=\"0 0 80 20\" xmlns=\"http://www.w3.org/2000/svg\"> <symbol id=\"circ\" width=\"10\" height=\"10\" viewBox=\"0 0 2 2\"> <rect height=\"10\" width=\"10\" /> </symbol> <use xlink:href=\"#circ\" x=\"5\" y=\"5\" opacity=\"0.5\" fill=\"green\"/> </svg></body> </html>", "e": 26028, "s": 25624, "text": null }, { "code": null, "e": 26036, "s": 26028, "text": "Output:" }, { "code": null, "e": 26114, "s": 26036, "text": "Supported Browsers: The following browsers are supported by this SVG element:" }, { "code": null, "e": 26121, "s": 26114, "text": "Chrome" }, { "code": null, "e": 26126, "s": 26121, "text": "Edge" }, { "code": null, "e": 26134, "s": 26126, "text": "Firefox" }, { "code": null, "e": 26141, "s": 26134, "text": "Safari" }, { "code": null, "e": 26159, "s": 26141, "text": "Internet Explorer" }, { "code": null, "e": 26165, "s": 26159, "text": "Opera" }, { "code": null, "e": 26302, "s": 26165, "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": 26311, "s": 26302, "text": "HTML-SVG" }, { "code": null, "e": 26323, "s": 26311, "text": "SVG-Element" }, { "code": null, "e": 26328, "s": 26323, "text": "HTML" }, { "code": null, "e": 26345, "s": 26328, "text": "Web Technologies" }, { "code": null, "e": 26350, "s": 26345, "text": "HTML" }, { "code": null, "e": 26448, "s": 26350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26457, "s": 26448, "text": "Comments" }, { "code": null, "e": 26470, "s": 26457, "text": "Old Comments" }, { "code": null, "e": 26494, "s": 26470, "text": "REST API (Introduction)" }, { "code": null, "e": 26531, "s": 26494, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26560, "s": 26531, "text": "Form validation using jQuery" }, { "code": null, "e": 26607, "s": 26560, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 26669, "s": 26607, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26725, "s": 26669, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26758, "s": 26725, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26801, "s": 26758, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26862, "s": 26801, "text": "Difference between var, let and const keywords in JavaScript" } ]
Python - Group each increasing and decreasing run in list - GeeksforGeeks
06 Jun, 2021 Given a list, the task is to write a Python program to group each increasing and decreasing run. This is known as a monotonous grouping. A list is monotonic if it is either monotone increasing or monotone decreasing. A list A is monotone decreasing if for all i <= j, A[i] >= A[j]. Example: Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2] Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]] Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups. Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1] Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1]] Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups. Example : Using loop + zip() In this, every two lists each starting from 0th and 1st index are zipped, and then each element from both are compared to check run and change flag accordingly. Initial flag value is evaluated on basis of which of the first 2 elements is greater, post that flag is toggled to have appropriate run grouping. Python3 # Python3 code to demonstrate working of# Monotonous grouping in List# Using loop + zip() # initializing listtest_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2] # printing original listprint("The original list is : " + str(test_list)) res = []temp = []is_up = True if test_list[0] > test_list[1]: is_up = Falsefor curr, nex in zip(test_list, test_list[1:]): temp.append(curr) # checking for increasing or decreasing to change list if (nex > curr and not is_up) or (nex < curr and is_up): res.append(temp) temp = [] # toggling is_up = not is_up temp.append(nex)res.append(temp) # printing resultprint("Monotonous grouping : " + str(res)) Output: The original list is : [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2] Monotonous grouping : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 23901, "s": 23873, "text": "\n06 Jun, 2021" }, { "code": null, "e": 24184, "s": 23901, "text": "Given a list, the task is to write a Python program to group each increasing and decreasing run. This is known as a monotonous grouping. A list is monotonic if it is either monotone increasing or monotone decreasing. A list A is monotone decreasing if for all i <= j, A[i] >= A[j]." }, { "code": null, "e": 24193, "s": 24184, "text": "Example:" }, { "code": null, "e": 24256, "s": 24193, "text": "Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]" }, { "code": null, "e": 24324, "s": 24256, "text": "Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]" }, { "code": null, "e": 24494, "s": 24324, "text": "Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups." }, { "code": null, "e": 24546, "s": 24494, "text": "Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1]" }, { "code": null, "e": 24599, "s": 24546, "text": "Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1]]" }, { "code": null, "e": 24769, "s": 24599, "text": "Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups." }, { "code": null, "e": 24799, "s": 24769, "text": "Example : Using loop + zip()" }, { "code": null, "e": 25106, "s": 24799, "text": "In this, every two lists each starting from 0th and 1st index are zipped, and then each element from both are compared to check run and change flag accordingly. Initial flag value is evaluated on basis of which of the first 2 elements is greater, post that flag is toggled to have appropriate run grouping." }, { "code": null, "e": 25114, "s": 25106, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Monotonous grouping in List# Using loop + zip() # initializing listtest_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2] # printing original listprint(\"The original list is : \" + str(test_list)) res = []temp = []is_up = True if test_list[0] > test_list[1]: is_up = Falsefor curr, nex in zip(test_list, test_list[1:]): temp.append(curr) # checking for increasing or decreasing to change list if (nex > curr and not is_up) or (nex < curr and is_up): res.append(temp) temp = [] # toggling is_up = not is_up temp.append(nex)res.append(temp) # printing resultprint(\"Monotonous grouping : \" + str(res))", "e": 25829, "s": 25114, "text": null }, { "code": null, "e": 25837, "s": 25829, "text": "Output:" }, { "code": null, "e": 25903, "s": 25837, "text": "The original list is : [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]" }, { "code": null, "e": 25984, "s": 25903, "text": "Monotonous grouping : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]" }, { "code": null, "e": 26005, "s": 25984, "text": "Python list-programs" }, { "code": null, "e": 26012, "s": 26005, "text": "Python" }, { "code": null, "e": 26028, "s": 26012, "text": "Python Programs" }, { "code": null, "e": 26126, "s": 26028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26135, "s": 26126, "text": "Comments" }, { "code": null, "e": 26148, "s": 26135, "text": "Old Comments" }, { "code": null, "e": 26180, "s": 26148, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26236, "s": 26180, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26278, "s": 26236, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26320, "s": 26278, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26356, "s": 26320, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26378, "s": 26356, "text": "Defaultdict in Python" }, { "code": null, "e": 26417, "s": 26378, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26463, "s": 26417, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26501, "s": 26463, "text": "Python | Convert a list to dictionary" } ]
How to test if a parameter is provided to a function in JavaScript?
To test if a parameter is provided by a function, use the if condition and check with “undefined”. Following is the code − function checkingParameter(parameter) { if (parameter !== undefined) { console.log("Parameter is provided."); } else { console.log("Parameter is not provided.") } } checkingParameter(); checkingParameter("JavaScript"); To run the above program, you need to use the below command − node fileName.js. Here, my file name is demo327.js. This will produce the following output − PS C:\Users\Amit\javascript-code> node demo327.js Parameter is not provided. Parameter is provided.
[ { "code": null, "e": 1161, "s": 1062, "text": "To test if a parameter is provided by a function, use the if condition and check with “undefined”." }, { "code": null, "e": 1185, "s": 1161, "text": "Following is the code −" }, { "code": null, "e": 1425, "s": 1185, "text": "function checkingParameter(parameter) {\n if (parameter !== undefined) {\n console.log(\"Parameter is provided.\");\n } else {\n console.log(\"Parameter is not provided.\")\n }\n}\ncheckingParameter();\ncheckingParameter(\"JavaScript\");" }, { "code": null, "e": 1487, "s": 1425, "text": "To run the above program, you need to use the below command −" }, { "code": null, "e": 1505, "s": 1487, "text": "node fileName.js." }, { "code": null, "e": 1539, "s": 1505, "text": "Here, my file name is demo327.js." }, { "code": null, "e": 1580, "s": 1539, "text": "This will produce the following output −" }, { "code": null, "e": 1680, "s": 1580, "text": "PS C:\\Users\\Amit\\javascript-code> node demo327.js\nParameter is not provided.\nParameter is provided." } ]
10 Ways to Create a Stream in Java - GeeksforGeeks
11 Dec, 2018 The Stream API, introduced in Java 8, it is used to process collections of objects. Stream is a sequence of objects, that supports many different methods which can be pipe lined to produce the desired result. The features of Java stream are – A stream is not a data structure alternatively it takes input from the Collections, Arrays or I/O channels. A Streams does not change the original data structure, they only provide the result as the pipelined methods. Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipe lined. Terminal operation mark the end of the stream and return the result. Different way to create Streams: Using CollectionApproach:Get the collectionConstruct a Sequential Stream from the collection using Collection.stream() methodPrint the StreamBelow is the implementation of the above approach:Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(List<T> list) { // Create stream object with the List Stream<T> stream = list.stream(); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Create ArrayList of String List<String> list = new ArrayList<>(); // Add element in list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Get the Stream from the List getStream(list); }}Output:Geeks for Geeks Create a stream from specified valuesStream.of(T...t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements.Below is the implementation of the above approach:Program:// Java program to create Stream from values import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create a stream from specified values Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9); // Displaying the sequential ordered stream stream.forEach(p -> System.out.print(p + " ")); } public static void main(String[] args) { // Get the Stream from the values getStream(); }}Output:1 2 3 4 5 6 7 8 9 Create stream from an array:The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.Integer arrayCreate stream using Arrays.stream()Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }}Output:a b c Create stream using Stream.of()A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }}Output:a b c Create an empty stream using Stream.empty()The empty() method is used upon creation to avoid returning null for streams with no element.Program:// Java program to create empty Stream import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create stream from an array using Stream.empty() Stream<String> streamOfArray = Stream.empty(); // Iterate list first to last element Iterator<String> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the empty Stream getStream(); }}Output: Create a Stream using Stream.builder()The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream() { // Create stream using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add("a") .add("b") .add("c") .build(); // Iterate list first to last element Iterator<String> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Stream using Builder getStream(); }}Output:a b c Create an infinite Stream using Stream.iterate()The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4.Program:// Java program to create infinite Stream// using Stream.iterate() method import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(int seedValue, int limitTerms) { // Create infinite stream // using Stream.iterate() method Stream.iterate(seedValue, (Integer n) -> n * n) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the seed value int seedValue = 2; // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(seedValue, limitTerms); }}Output:2 4 16 256 65536 Create an infinite Stream using Stream.generate() methodThe generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit.Program:// Java program to create infinite Stream// using Stream.generate() method import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(int limitTerms) { // Create infinite stream // using Stream.generate() method Stream.generate(Math::random) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(limitTerms); }}Output:0.2293502475696314 0.5650334795948209 0.3418138293253522 0.36831074763500116 0.4864408670097241 Create stream from a Pattern using PredicateIn java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*;import java.util.regex.Pattern; class GFG { // Function convert a List into Stream private static void getStream(List<String> list, Pattern p) { list.stream() .filter(p.asPredicate()) .forEach(System.out::println); } public static void main(String[] args) { // Create ArrayList of String // that is backed by the specified array List<String> list = Arrays .asList("Geeks", "For", "Geek", "GeeksForGeeks", "A Computer Portal"); // Get the pattern Pattern p = Pattern.compile("^G"); // Get the Stream from the List matching Pattern getStream(list, p); }}Output:Geeks Geek GeeksForGeeks Create stream from IteratorIterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterator<T> itr) { // Convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators .spliteratorUnknownSize(itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream Stream<T> stream = StreamSupport.stream(spitr, false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Iterator Iterator<String> iterator = Arrays .asList("a", "b", "c") .iterator(); // Get the Stream from the Iterator getStream(iterator); }}Output:a b c Create stream from IterableIterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream.Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterable<T> iterable) { // Convert the iterator into a Stream Stream<T> stream = StreamSupport .stream(iterable.spliterator(), false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Iterable Iterable<String> iterable = Arrays.asList("a", "b", "c"); // Get the Stream from the Iterable getStream(iterable); }}Output:a b c Using CollectionApproach:Get the collectionConstruct a Sequential Stream from the collection using Collection.stream() methodPrint the StreamBelow is the implementation of the above approach:Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(List<T> list) { // Create stream object with the List Stream<T> stream = list.stream(); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Create ArrayList of String List<String> list = new ArrayList<>(); // Add element in list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Get the Stream from the List getStream(list); }}Output:Geeks for Geeks Approach: Get the collectionConstruct a Sequential Stream from the collection using Collection.stream() methodPrint the Stream Get the collection Construct a Sequential Stream from the collection using Collection.stream() method Print the Stream Below is the implementation of the above approach: Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(List<T> list) { // Create stream object with the List Stream<T> stream = list.stream(); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Create ArrayList of String List<String> list = new ArrayList<>(); // Add element in list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Get the Stream from the List getStream(list); }} Geeks for Geeks Create a stream from specified valuesStream.of(T...t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements.Below is the implementation of the above approach:Program:// Java program to create Stream from values import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create a stream from specified values Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9); // Displaying the sequential ordered stream stream.forEach(p -> System.out.print(p + " ")); } public static void main(String[] args) { // Get the Stream from the values getStream(); }}Output:1 2 3 4 5 6 7 8 9 Stream.of(T...t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements. Below is the implementation of the above approach: Program: // Java program to create Stream from values import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create a stream from specified values Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9); // Displaying the sequential ordered stream stream.forEach(p -> System.out.print(p + " ")); } public static void main(String[] args) { // Get the Stream from the values getStream(); }} 1 2 3 4 5 6 7 8 9 Create stream from an array:The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.Integer arrayCreate stream using Arrays.stream()Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }}Output:a b c Create stream using Stream.of()A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }}Output:a b c The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.Integer array Create stream using Arrays.stream()Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }}Output:a b c Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }} a b c Create stream using Stream.of()A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }}Output:a b c Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { "a", "b", "c" }; // Get the Stream from the Array getStream(arr); }} a b c Create an empty stream using Stream.empty()The empty() method is used upon creation to avoid returning null for streams with no element.Program:// Java program to create empty Stream import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create stream from an array using Stream.empty() Stream<String> streamOfArray = Stream.empty(); // Iterate list first to last element Iterator<String> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the empty Stream getStream(); }}Output: The empty() method is used upon creation to avoid returning null for streams with no element. Program: // Java program to create empty Stream import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create stream from an array using Stream.empty() Stream<String> streamOfArray = Stream.empty(); // Iterate list first to last element Iterator<String> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the empty Stream getStream(); }} Create a Stream using Stream.builder()The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream() { // Create stream using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add("a") .add("b") .add("c") .build(); // Iterate list first to last element Iterator<String> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Stream using Builder getStream(); }}Output:a b c The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream. Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream() { // Create stream using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add("a") .add("b") .add("c") .build(); // Iterate list first to last element Iterator<String> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Stream using Builder getStream(); }} a b c Create an infinite Stream using Stream.iterate()The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4.Program:// Java program to create infinite Stream// using Stream.iterate() method import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(int seedValue, int limitTerms) { // Create infinite stream // using Stream.iterate() method Stream.iterate(seedValue, (Integer n) -> n * n) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the seed value int seedValue = 2; // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(seedValue, limitTerms); }}Output:2 4 16 256 65536 The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4. Program: // Java program to create infinite Stream// using Stream.iterate() method import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(int seedValue, int limitTerms) { // Create infinite stream // using Stream.iterate() method Stream.iterate(seedValue, (Integer n) -> n * n) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the seed value int seedValue = 2; // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(seedValue, limitTerms); }} 2 4 16 256 65536 Create an infinite Stream using Stream.generate() methodThe generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit.Program:// Java program to create infinite Stream// using Stream.generate() method import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(int limitTerms) { // Create infinite stream // using Stream.generate() method Stream.generate(Math::random) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(limitTerms); }}Output:0.2293502475696314 0.5650334795948209 0.3418138293253522 0.36831074763500116 0.4864408670097241 The generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit. Program: // Java program to create infinite Stream// using Stream.generate() method import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(int limitTerms) { // Create infinite stream // using Stream.generate() method Stream.generate(Math::random) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(limitTerms); }} 0.2293502475696314 0.5650334795948209 0.3418138293253522 0.36831074763500116 0.4864408670097241 Create stream from a Pattern using PredicateIn java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*;import java.util.regex.Pattern; class GFG { // Function convert a List into Stream private static void getStream(List<String> list, Pattern p) { list.stream() .filter(p.asPredicate()) .forEach(System.out::println); } public static void main(String[] args) { // Create ArrayList of String // that is backed by the specified array List<String> list = Arrays .asList("Geeks", "For", "Geek", "GeeksForGeeks", "A Computer Portal"); // Get the pattern Pattern p = Pattern.compile("^G"); // Get the Stream from the List matching Pattern getStream(list, p); }}Output:Geeks Geek GeeksForGeeks In java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching. Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.*;import java.util.regex.Pattern; class GFG { // Function convert a List into Stream private static void getStream(List<String> list, Pattern p) { list.stream() .filter(p.asPredicate()) .forEach(System.out::println); } public static void main(String[] args) { // Create ArrayList of String // that is backed by the specified array List<String> list = Arrays .asList("Geeks", "For", "Geek", "GeeksForGeeks", "A Computer Portal"); // Get the pattern Pattern p = Pattern.compile("^G"); // Get the Stream from the List matching Pattern getStream(list, p); }} Geeks Geek GeeksForGeeks Create stream from IteratorIterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterator<T> itr) { // Convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators .spliteratorUnknownSize(itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream Stream<T> stream = StreamSupport.stream(spitr, false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Iterator Iterator<String> iterator = Arrays .asList("a", "b", "c") .iterator(); // Get the Stream from the Iterator getStream(iterator); }}Output:a b c Iterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator(). Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterator<T> itr) { // Convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators .spliteratorUnknownSize(itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream Stream<T> stream = StreamSupport.stream(spitr, false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Iterator Iterator<String> iterator = Arrays .asList("a", "b", "c") .iterator(); // Get the Stream from the Iterator getStream(iterator); }} a b c Create stream from IterableIterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream.Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterable<T> iterable) { // Convert the iterator into a Stream Stream<T> stream = StreamSupport .stream(iterable.spliterator(), false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Iterable Iterable<String> iterable = Arrays.asList("a", "b", "c"); // Get the Stream from the Iterable getStream(iterable); }}Output:a b c Iterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream. Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method. Program: // Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterable<T> iterable) { // Convert the iterator into a Stream Stream<T> stream = StreamSupport .stream(iterable.spliterator(), false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + " "); } } public static void main(String[] args) { // Get the Iterable Iterable<String> iterable = Arrays.asList("a", "b", "c"); // Get the Stream from the Iterable getStream(iterable); }} a b c java-stream Java-Stream-programs Picked Technical Scripter 2018 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Overriding in Java
[ { "code": null, "e": 24134, "s": 24106, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24343, "s": 24134, "text": "The Stream API, introduced in Java 8, it is used to process collections of objects. Stream is a sequence of objects, that supports many different methods which can be pipe lined to produce the desired result." }, { "code": null, "e": 24377, "s": 24343, "text": "The features of Java stream are –" }, { "code": null, "e": 24485, "s": 24377, "text": "A stream is not a data structure alternatively it takes input from the Collections, Arrays or I/O channels." }, { "code": null, "e": 24595, "s": 24485, "text": "A Streams does not change the original data structure, they only provide the result as the pipelined methods." }, { "code": null, "e": 24802, "s": 24595, "text": "Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipe lined. Terminal operation mark the end of the stream and return the result." }, { "code": null, "e": 24835, "s": 24802, "text": "Different way to create Streams:" }, { "code": null, "e": 37175, "s": 24835, "text": "Using CollectionApproach:Get the collectionConstruct a Sequential Stream from the collection using Collection.stream() methodPrint the StreamBelow is the implementation of the above approach:Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(List<T> list) { // Create stream object with the List Stream<T> stream = list.stream(); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Create ArrayList of String List<String> list = new ArrayList<>(); // Add element in list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Get the Stream from the List getStream(list); }}Output:Geeks for Geeks\nCreate a stream from specified valuesStream.of(T...t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements.Below is the implementation of the above approach:Program:// Java program to create Stream from values import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create a stream from specified values Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9); // Displaying the sequential ordered stream stream.forEach(p -> System.out.print(p + \" \")); } public static void main(String[] args) { // Get the Stream from the values getStream(); }}Output:1 2 3 4 5 6 7 8 9\nCreate stream from an array:The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.Integer arrayCreate stream using Arrays.stream()Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}Output:a b c\nCreate stream using Stream.of()A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}Output:a b c\nCreate an empty stream using Stream.empty()The empty() method is used upon creation to avoid returning null for streams with no element.Program:// Java program to create empty Stream import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create stream from an array using Stream.empty() Stream<String> streamOfArray = Stream.empty(); // Iterate list first to last element Iterator<String> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the empty Stream getStream(); }}Output:\nCreate a Stream using Stream.builder()The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream() { // Create stream using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add(\"a\") .add(\"b\") .add(\"c\") .build(); // Iterate list first to last element Iterator<String> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Stream using Builder getStream(); }}Output:a b c\nCreate an infinite Stream using Stream.iterate()The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4.Program:// Java program to create infinite Stream// using Stream.iterate() method import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(int seedValue, int limitTerms) { // Create infinite stream // using Stream.iterate() method Stream.iterate(seedValue, (Integer n) -> n * n) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the seed value int seedValue = 2; // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(seedValue, limitTerms); }}Output:2\n4\n16\n256\n65536\nCreate an infinite Stream using Stream.generate() methodThe generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit.Program:// Java program to create infinite Stream// using Stream.generate() method import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(int limitTerms) { // Create infinite stream // using Stream.generate() method Stream.generate(Math::random) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(limitTerms); }}Output:0.2293502475696314\n0.5650334795948209\n0.3418138293253522\n0.36831074763500116\n0.4864408670097241\nCreate stream from a Pattern using PredicateIn java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*;import java.util.regex.Pattern; class GFG { // Function convert a List into Stream private static void getStream(List<String> list, Pattern p) { list.stream() .filter(p.asPredicate()) .forEach(System.out::println); } public static void main(String[] args) { // Create ArrayList of String // that is backed by the specified array List<String> list = Arrays .asList(\"Geeks\", \"For\", \"Geek\", \"GeeksForGeeks\", \"A Computer Portal\"); // Get the pattern Pattern p = Pattern.compile(\"^G\"); // Get the Stream from the List matching Pattern getStream(list, p); }}Output:Geeks\nGeek\nGeeksForGeeks\nCreate stream from IteratorIterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterator<T> itr) { // Convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators .spliteratorUnknownSize(itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream Stream<T> stream = StreamSupport.stream(spitr, false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Iterator Iterator<String> iterator = Arrays .asList(\"a\", \"b\", \"c\") .iterator(); // Get the Stream from the Iterator getStream(iterator); }}Output:a b c\nCreate stream from IterableIterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream.Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterable<T> iterable) { // Convert the iterator into a Stream Stream<T> stream = StreamSupport .stream(iterable.spliterator(), false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Iterable Iterable<String> iterable = Arrays.asList(\"a\", \"b\", \"c\"); // Get the Stream from the Iterable getStream(iterable); }}Output:a b c\n" }, { "code": null, "e": 38227, "s": 37175, "text": "Using CollectionApproach:Get the collectionConstruct a Sequential Stream from the collection using Collection.stream() methodPrint the StreamBelow is the implementation of the above approach:Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(List<T> list) { // Create stream object with the List Stream<T> stream = list.stream(); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Create ArrayList of String List<String> list = new ArrayList<>(); // Add element in list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Get the Stream from the List getStream(list); }}Output:Geeks for Geeks\n" }, { "code": null, "e": 38237, "s": 38227, "text": "Approach:" }, { "code": null, "e": 38354, "s": 38237, "text": "Get the collectionConstruct a Sequential Stream from the collection using Collection.stream() methodPrint the Stream" }, { "code": null, "e": 38373, "s": 38354, "text": "Get the collection" }, { "code": null, "e": 38456, "s": 38373, "text": "Construct a Sequential Stream from the collection using Collection.stream() method" }, { "code": null, "e": 38473, "s": 38456, "text": "Print the Stream" }, { "code": null, "e": 38524, "s": 38473, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 38533, "s": 38524, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(List<T> list) { // Create stream object with the List Stream<T> stream = list.stream(); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Create ArrayList of String List<String> list = new ArrayList<>(); // Add element in list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Get the Stream from the List getStream(list); }}", "e": 39363, "s": 38533, "text": null }, { "code": null, "e": 39380, "s": 39363, "text": "Geeks for Geeks\n" }, { "code": null, "e": 40324, "s": 39380, "text": "Create a stream from specified valuesStream.of(T...t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements.Below is the implementation of the above approach:Program:// Java program to create Stream from values import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create a stream from specified values Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9); // Displaying the sequential ordered stream stream.forEach(p -> System.out.print(p + \" \")); } public static void main(String[] args) { // Get the Stream from the values getStream(); }}Output:1 2 3 4 5 6 7 8 9\n" }, { "code": null, "e": 40501, "s": 40324, "text": "Stream.of(T...t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements." }, { "code": null, "e": 40552, "s": 40501, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 40561, "s": 40552, "text": "Program:" }, { "code": "// Java program to create Stream from values import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create a stream from specified values Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9); // Displaying the sequential ordered stream stream.forEach(p -> System.out.print(p + \" \")); } public static void main(String[] args) { // Get the Stream from the values getStream(); }}", "e": 41209, "s": 40561, "text": null }, { "code": null, "e": 41228, "s": 41209, "text": "1 2 3 4 5 6 7 8 9\n" }, { "code": null, "e": 43241, "s": 41228, "text": "Create stream from an array:The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.Integer arrayCreate stream using Arrays.stream()Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}Output:a b c\nCreate stream using Stream.of()A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}Output:a b c\n" }, { "code": null, "e": 43454, "s": 43241, "text": "The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.Integer array" }, { "code": null, "e": 44299, "s": 43454, "text": "Create stream using Arrays.stream()Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}Output:a b c\n" }, { "code": null, "e": 44308, "s": 44299, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Arrays.stream() Stream<T> streamOfArray = Arrays.stream(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}", "e": 45097, "s": 44308, "text": null }, { "code": null, "e": 45104, "s": 45097, "text": "a b c\n" }, { "code": null, "e": 46033, "s": 45104, "text": "Create stream using Stream.of()A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}Output:a b c\n" }, { "code": null, "e": 46042, "s": 46033, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(T[] arr) { // Create stream from an array // using Stream.of() Stream<T> streamOfArray = Stream.of(arr); // Iterate list first to last element Iterator<T> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the array String[] arr = new String[] { \"a\", \"b\", \"c\" }; // Get the Stream from the Array getStream(arr); }}", "e": 46801, "s": 46042, "text": null }, { "code": null, "e": 46808, "s": 46801, "text": "a b c\n" }, { "code": null, "e": 47619, "s": 46808, "text": "Create an empty stream using Stream.empty()The empty() method is used upon creation to avoid returning null for streams with no element.Program:// Java program to create empty Stream import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create stream from an array using Stream.empty() Stream<String> streamOfArray = Stream.empty(); // Iterate list first to last element Iterator<String> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the empty Stream getStream(); }}Output:\n" }, { "code": null, "e": 47713, "s": 47619, "text": "The empty() method is used upon creation to avoid returning null for streams with no element." }, { "code": null, "e": 47722, "s": 47713, "text": "Program:" }, { "code": "// Java program to create empty Stream import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static void getStream() { // Create stream from an array using Stream.empty() Stream<String> streamOfArray = Stream.empty(); // Iterate list first to last element Iterator<String> it = streamOfArray.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the empty Stream getStream(); }}", "e": 48381, "s": 47722, "text": null }, { "code": null, "e": 49521, "s": 48383, "text": "Create a Stream using Stream.builder()The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream() { // Create stream using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add(\"a\") .add(\"b\") .add(\"c\") .build(); // Iterate list first to last element Iterator<String> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Stream using Builder getStream(); }}Output:a b c\n" }, { "code": null, "e": 49709, "s": 49521, "text": "The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream." }, { "code": null, "e": 49718, "s": 49709, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream() { // Create stream using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add(\"a\") .add(\"b\") .add(\"c\") .build(); // Iterate list first to last element Iterator<String> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Stream using Builder getStream(); }}", "e": 50610, "s": 49718, "text": null }, { "code": null, "e": 50617, "s": 50610, "text": "a b c\n" }, { "code": null, "e": 51837, "s": 50617, "text": "Create an infinite Stream using Stream.iterate()The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4.Program:// Java program to create infinite Stream// using Stream.iterate() method import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(int seedValue, int limitTerms) { // Create infinite stream // using Stream.iterate() method Stream.iterate(seedValue, (Integer n) -> n * n) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the seed value int seedValue = 2; // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(seedValue, limitTerms); }}Output:2\n4\n16\n256\n65536\n" }, { "code": null, "e": 52219, "s": 51837, "text": "The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4." }, { "code": null, "e": 52228, "s": 52219, "text": "Program:" }, { "code": "// Java program to create infinite Stream// using Stream.iterate() method import java.util.*;import java.util.stream.Stream; class GFG { // Function convert a List into Stream private static <T> void getStream(int seedValue, int limitTerms) { // Create infinite stream // using Stream.iterate() method Stream.iterate(seedValue, (Integer n) -> n * n) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the seed value int seedValue = 2; // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(seedValue, limitTerms); }}", "e": 52987, "s": 52228, "text": null }, { "code": null, "e": 53005, "s": 52987, "text": "2\n4\n16\n256\n65536\n" }, { "code": null, "e": 54018, "s": 53005, "text": "Create an infinite Stream using Stream.generate() methodThe generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit.Program:// Java program to create infinite Stream// using Stream.generate() method import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(int limitTerms) { // Create infinite stream // using Stream.generate() method Stream.generate(Math::random) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(limitTerms); }}Output:0.2293502475696314\n0.5650334795948209\n0.3418138293253522\n0.36831074763500116\n0.4864408670097241\n" }, { "code": null, "e": 54235, "s": 54018, "text": "The generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit." }, { "code": null, "e": 54244, "s": 54235, "text": "Program:" }, { "code": "// Java program to create infinite Stream// using Stream.generate() method import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(int limitTerms) { // Create infinite stream // using Stream.generate() method Stream.generate(Math::random) .limit(limitTerms) .forEach(System.out::println); } public static void main(String[] args) { // Get the limit for number of terms int limitTerms = 5; // Get the Stream from the function getStream(limitTerms); }}", "e": 54874, "s": 54244, "text": null }, { "code": null, "e": 54971, "s": 54874, "text": "0.2293502475696314\n0.5650334795948209\n0.3418138293253522\n0.36831074763500116\n0.4864408670097241\n" }, { "code": null, "e": 56082, "s": 54971, "text": "Create stream from a Pattern using PredicateIn java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*;import java.util.regex.Pattern; class GFG { // Function convert a List into Stream private static void getStream(List<String> list, Pattern p) { list.stream() .filter(p.asPredicate()) .forEach(System.out::println); } public static void main(String[] args) { // Create ArrayList of String // that is backed by the specified array List<String> list = Arrays .asList(\"Geeks\", \"For\", \"Geek\", \"GeeksForGeeks\", \"A Computer Portal\"); // Get the pattern Pattern p = Pattern.compile(\"^G\"); // Get the Stream from the List matching Pattern getStream(list, p); }}Output:Geeks\nGeek\nGeeksForGeeks\n" }, { "code": null, "e": 56218, "s": 56082, "text": "In java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching." }, { "code": null, "e": 56227, "s": 56218, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.*;import java.util.regex.Pattern; class GFG { // Function convert a List into Stream private static void getStream(List<String> list, Pattern p) { list.stream() .filter(p.asPredicate()) .forEach(System.out::println); } public static void main(String[] args) { // Create ArrayList of String // that is backed by the specified array List<String> list = Arrays .asList(\"Geeks\", \"For\", \"Geek\", \"GeeksForGeeks\", \"A Computer Portal\"); // Get the pattern Pattern p = Pattern.compile(\"^G\"); // Get the Stream from the List matching Pattern getStream(list, p); }}", "e": 57119, "s": 56227, "text": null }, { "code": null, "e": 57145, "s": 57119, "text": "Geeks\nGeek\nGeeksForGeeks\n" }, { "code": null, "e": 58704, "s": 57145, "text": "Create stream from IteratorIterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterator<T> itr) { // Convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators .spliteratorUnknownSize(itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream Stream<T> stream = StreamSupport.stream(spitr, false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Iterator Iterator<String> iterator = Arrays .asList(\"a\", \"b\", \"c\") .iterator(); // Get the Stream from the Iterator getStream(iterator); }}Output:a b c\n" }, { "code": null, "e": 59131, "s": 58704, "text": "Iterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator()." }, { "code": null, "e": 59140, "s": 59131, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterator<T> itr) { // Convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators .spliteratorUnknownSize(itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream Stream<T> stream = StreamSupport.stream(spitr, false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Iterator Iterator<String> iterator = Arrays .asList(\"a\", \"b\", \"c\") .iterator(); // Get the Stream from the Iterator getStream(iterator); }}", "e": 60225, "s": 59140, "text": null }, { "code": null, "e": 60232, "s": 60225, "text": "a b c\n" }, { "code": null, "e": 61720, "s": 60232, "text": "Create stream from IterableIterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream.Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method.Program:// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterable<T> iterable) { // Convert the iterator into a Stream Stream<T> stream = StreamSupport .stream(iterable.spliterator(), false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Iterable Iterable<String> iterable = Arrays.asList(\"a\", \"b\", \"c\"); // Get the Stream from the Iterable getStream(iterable); }}Output:a b c\n" }, { "code": null, "e": 62120, "s": 61720, "text": "Iterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream." }, { "code": null, "e": 62317, "s": 62120, "text": "Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method." }, { "code": null, "e": 62326, "s": 62317, "text": "Program:" }, { "code": "// Java program to create Stream from Collections import java.util.*;import java.util.stream.*; class GFG { // Function convert a List into Stream private static <T> void getStream(Iterable<T> iterable) { // Convert the iterator into a Stream Stream<T> stream = StreamSupport .stream(iterable.spliterator(), false); // Iterate list first to last element Iterator<T> it = stream.iterator(); // Iterate stream object while (it.hasNext()) { System.out.print(it.next() + \" \"); } } public static void main(String[] args) { // Get the Iterable Iterable<String> iterable = Arrays.asList(\"a\", \"b\", \"c\"); // Get the Stream from the Iterable getStream(iterable); }}", "e": 63171, "s": 62326, "text": null }, { "code": null, "e": 63178, "s": 63171, "text": "a b c\n" }, { "code": null, "e": 63190, "s": 63178, "text": "java-stream" }, { "code": null, "e": 63211, "s": 63190, "text": "Java-Stream-programs" }, { "code": null, "e": 63218, "s": 63211, "text": "Picked" }, { "code": null, "e": 63242, "s": 63218, "text": "Technical Scripter 2018" }, { "code": null, "e": 63247, "s": 63242, "text": "Java" }, { "code": null, "e": 63266, "s": 63247, "text": "Technical Scripter" }, { "code": null, "e": 63271, "s": 63266, "text": "Java" }, { "code": null, "e": 63369, "s": 63271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 63378, "s": 63369, "text": "Comments" }, { "code": null, "e": 63391, "s": 63378, "text": "Old Comments" }, { "code": null, "e": 63423, "s": 63391, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 63453, "s": 63423, "text": "HashMap in Java with Examples" }, { "code": null, "e": 63472, "s": 63453, "text": "Interfaces in Java" }, { "code": null, "e": 63503, "s": 63472, "text": "How to iterate any Map in Java" }, { "code": null, "e": 63521, "s": 63503, "text": "ArrayList in Java" }, { "code": null, "e": 63572, "s": 63521, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 63604, "s": 63572, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 63624, "s": 63604, "text": "Stack Class in Java" }, { "code": null, "e": 63643, "s": 63624, "text": "LinkedList in Java" } ]
Cassandra - Cqlsh
This chapter introduces the Cassandra query language shell and explains how to use its commands. By default, Cassandra provides a prompt Cassandra query language shell (cqlsh) that allows users to communicate with it. Using this shell, you can execute Cassandra Query Language (CQL). Using cqlsh, you can define a schema, insert data, and execute a query. Start cqlsh using the command cqlsh as shown below. It gives the Cassandra cqlsh prompt as output. [hadoop@linux bin]$ cqlsh Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 2.1.2 | CQL spec 3.2.0 | Native protocol v3] Use HELP for help. cqlsh> Cqlsh − As discussed above, this command is used to start the cqlsh prompt. In addition, it supports a few more options as well. The following table explains all the options of cqlsh and their usage. cqlsh --execute cql_statement Cqlsh has a few commands that allow users to interact with it. The commands are listed below. Given below are the Cqlsh documented shell commands. These are the commands used to perform tasks such as displaying help topics, exit from cqlsh, describe,etc. HELP − Displays help topics for all cqlsh commands. HELP − Displays help topics for all cqlsh commands. CAPTURE − Captures the output of a command and adds it to a file. CAPTURE − Captures the output of a command and adds it to a file. CONSISTENCY − Shows the current consistency level, or sets a new consistency level. CONSISTENCY − Shows the current consistency level, or sets a new consistency level. COPY − Copies data to and from Cassandra. COPY − Copies data to and from Cassandra. DESCRIBE − Describes the current cluster of Cassandra and its objects. DESCRIBE − Describes the current cluster of Cassandra and its objects. EXPAND − Expands the output of a query vertically. EXPAND − Expands the output of a query vertically. EXIT − Using this command, you can terminate cqlsh. EXIT − Using this command, you can terminate cqlsh. PAGING − Enables or disables query paging. PAGING − Enables or disables query paging. SHOW − Displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions. SHOW − Displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions. SOURCE − Executes a file that contains CQL statements. SOURCE − Executes a file that contains CQL statements. TRACING − Enables or disables request tracing. TRACING − Enables or disables request tracing. CREATE KEYSPACE − Creates a KeySpace in Cassandra. CREATE KEYSPACE − Creates a KeySpace in Cassandra. USE − Connects to a created KeySpace. USE − Connects to a created KeySpace. ALTER KEYSPACE − Changes the properties of a KeySpace. ALTER KEYSPACE − Changes the properties of a KeySpace. DROP KEYSPACE − Removes a KeySpace DROP KEYSPACE − Removes a KeySpace CREATE TABLE − Creates a table in a KeySpace. CREATE TABLE − Creates a table in a KeySpace. ALTER TABLE − Modifies the column properties of a table. ALTER TABLE − Modifies the column properties of a table. DROP TABLE − Removes a table. DROP TABLE − Removes a table. TRUNCATE − Removes all the data from a table. TRUNCATE − Removes all the data from a table. CREATE INDEX − Defines a new index on a single column of a table. CREATE INDEX − Defines a new index on a single column of a table. DROP INDEX − Deletes a named index. DROP INDEX − Deletes a named index. INSERT − Adds columns for a row in a table. INSERT − Adds columns for a row in a table. UPDATE − Updates a column of a row. UPDATE − Updates a column of a row. DELETE − Deletes data from a table. DELETE − Deletes data from a table. BATCH − Executes multiple DML statements at once. BATCH − Executes multiple DML statements at once. SELECT − This clause reads data from a table SELECT − This clause reads data from a table WHERE − The where clause is used along with select to read a specific data. WHERE − The where clause is used along with select to read a specific data. ORDERBY − The orderby clause is used along with select to read a specific data in a specific order. ORDERBY − The orderby clause is used along with select to read a specific data in a specific order. 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2384, "s": 2287, "text": "This chapter introduces the Cassandra query language shell and explains how to use its commands." }, { "code": null, "e": 2571, "s": 2384, "text": "By default, Cassandra provides a prompt Cassandra query language shell (cqlsh) that allows users to communicate with it. Using this shell, you can execute Cassandra Query Language (CQL)." }, { "code": null, "e": 2592, "s": 2571, "text": "Using cqlsh, you can" }, { "code": null, "e": 2609, "s": 2592, "text": "define a schema," }, { "code": null, "e": 2626, "s": 2609, "text": "insert data, and" }, { "code": null, "e": 2643, "s": 2626, "text": "execute a query." }, { "code": null, "e": 2742, "s": 2643, "text": "Start cqlsh using the command cqlsh as shown below. It gives the Cassandra cqlsh prompt as output." }, { "code": null, "e": 2910, "s": 2742, "text": "[hadoop@linux bin]$ cqlsh\nConnected to Test Cluster at 127.0.0.1:9042.\n[cqlsh 5.0.1 | Cassandra 2.1.2 | CQL spec 3.2.0 | Native protocol v3]\nUse HELP for help.\ncqlsh>\n" }, { "code": null, "e": 3110, "s": 2910, "text": "Cqlsh − As discussed above, this command is used to start the cqlsh prompt. In addition, it supports a few more options as well. The following table explains all the options of cqlsh and their usage." }, { "code": null, "e": 3126, "s": 3110, "text": "cqlsh --execute" }, { "code": null, "e": 3140, "s": 3126, "text": "cql_statement" }, { "code": null, "e": 3234, "s": 3140, "text": "Cqlsh has a few commands that allow users to interact with it. The commands are\nlisted below." }, { "code": null, "e": 3395, "s": 3234, "text": "Given below are the Cqlsh documented shell commands. These are the commands used to perform tasks such as displaying help topics, exit from cqlsh, describe,etc." }, { "code": null, "e": 3447, "s": 3395, "text": "HELP − Displays help topics for all cqlsh commands." }, { "code": null, "e": 3499, "s": 3447, "text": "HELP − Displays help topics for all cqlsh commands." }, { "code": null, "e": 3565, "s": 3499, "text": "CAPTURE − Captures the output of a command and adds it to a file." }, { "code": null, "e": 3631, "s": 3565, "text": "CAPTURE − Captures the output of a command and adds it to a file." }, { "code": null, "e": 3715, "s": 3631, "text": "CONSISTENCY − Shows the current consistency level, or sets a new consistency level." }, { "code": null, "e": 3799, "s": 3715, "text": "CONSISTENCY − Shows the current consistency level, or sets a new consistency level." }, { "code": null, "e": 3841, "s": 3799, "text": "COPY − Copies data to and from Cassandra." }, { "code": null, "e": 3883, "s": 3841, "text": "COPY − Copies data to and from Cassandra." }, { "code": null, "e": 3954, "s": 3883, "text": "DESCRIBE − Describes the current cluster of Cassandra and its objects." }, { "code": null, "e": 4025, "s": 3954, "text": "DESCRIBE − Describes the current cluster of Cassandra and its objects." }, { "code": null, "e": 4076, "s": 4025, "text": "EXPAND − Expands the output of a query vertically." }, { "code": null, "e": 4127, "s": 4076, "text": "EXPAND − Expands the output of a query vertically." }, { "code": null, "e": 4179, "s": 4127, "text": "EXIT − Using this command, you can terminate cqlsh." }, { "code": null, "e": 4231, "s": 4179, "text": "EXIT − Using this command, you can terminate cqlsh." }, { "code": null, "e": 4274, "s": 4231, "text": "PAGING − Enables or disables query paging." }, { "code": null, "e": 4317, "s": 4274, "text": "PAGING − Enables or disables query paging." }, { "code": null, "e": 4429, "s": 4317, "text": "SHOW − Displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions." }, { "code": null, "e": 4541, "s": 4429, "text": "SHOW − Displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions." }, { "code": null, "e": 4596, "s": 4541, "text": "SOURCE − Executes a file that contains CQL statements." }, { "code": null, "e": 4651, "s": 4596, "text": "SOURCE − Executes a file that contains CQL statements." }, { "code": null, "e": 4698, "s": 4651, "text": "TRACING − Enables or disables request tracing." }, { "code": null, "e": 4745, "s": 4698, "text": "TRACING − Enables or disables request tracing." }, { "code": null, "e": 4796, "s": 4745, "text": "CREATE KEYSPACE − Creates a KeySpace in Cassandra." }, { "code": null, "e": 4847, "s": 4796, "text": "CREATE KEYSPACE − Creates a KeySpace in Cassandra." }, { "code": null, "e": 4885, "s": 4847, "text": "USE − Connects to a created KeySpace." }, { "code": null, "e": 4923, "s": 4885, "text": "USE − Connects to a created KeySpace." }, { "code": null, "e": 4978, "s": 4923, "text": "ALTER KEYSPACE − Changes the properties of a KeySpace." }, { "code": null, "e": 5033, "s": 4978, "text": "ALTER KEYSPACE − Changes the properties of a KeySpace." }, { "code": null, "e": 5068, "s": 5033, "text": "DROP KEYSPACE − Removes a KeySpace" }, { "code": null, "e": 5103, "s": 5068, "text": "DROP KEYSPACE − Removes a KeySpace" }, { "code": null, "e": 5149, "s": 5103, "text": "CREATE TABLE − Creates a table in a KeySpace." }, { "code": null, "e": 5195, "s": 5149, "text": "CREATE TABLE − Creates a table in a KeySpace." }, { "code": null, "e": 5252, "s": 5195, "text": "ALTER TABLE − Modifies the column properties of a table." }, { "code": null, "e": 5309, "s": 5252, "text": "ALTER TABLE − Modifies the column properties of a table." }, { "code": null, "e": 5339, "s": 5309, "text": "DROP TABLE − Removes a table." }, { "code": null, "e": 5369, "s": 5339, "text": "DROP TABLE − Removes a table." }, { "code": null, "e": 5415, "s": 5369, "text": "TRUNCATE − Removes all the data from a table." }, { "code": null, "e": 5461, "s": 5415, "text": "TRUNCATE − Removes all the data from a table." }, { "code": null, "e": 5527, "s": 5461, "text": "CREATE INDEX − Defines a new index on a single column of a table." }, { "code": null, "e": 5593, "s": 5527, "text": "CREATE INDEX − Defines a new index on a single column of a table." }, { "code": null, "e": 5629, "s": 5593, "text": "DROP INDEX − Deletes a named index." }, { "code": null, "e": 5665, "s": 5629, "text": "DROP INDEX − Deletes a named index." }, { "code": null, "e": 5709, "s": 5665, "text": "INSERT − Adds columns for a row in a table." }, { "code": null, "e": 5753, "s": 5709, "text": "INSERT − Adds columns for a row in a table." }, { "code": null, "e": 5789, "s": 5753, "text": "UPDATE − Updates a column of a row." }, { "code": null, "e": 5825, "s": 5789, "text": "UPDATE − Updates a column of a row." }, { "code": null, "e": 5861, "s": 5825, "text": "DELETE − Deletes data from a table." }, { "code": null, "e": 5897, "s": 5861, "text": "DELETE − Deletes data from a table." }, { "code": null, "e": 5947, "s": 5897, "text": "BATCH − Executes multiple DML statements at once." }, { "code": null, "e": 5997, "s": 5947, "text": "BATCH − Executes multiple DML statements at once." }, { "code": null, "e": 6042, "s": 5997, "text": "SELECT − This clause reads data from a table" }, { "code": null, "e": 6087, "s": 6042, "text": "SELECT − This clause reads data from a table" }, { "code": null, "e": 6163, "s": 6087, "text": "WHERE − The where clause is used along with select to read a specific data." }, { "code": null, "e": 6239, "s": 6163, "text": "WHERE − The where clause is used along with select to read a specific data." }, { "code": null, "e": 6339, "s": 6239, "text": "ORDERBY − The orderby clause is used along with select to read a specific data in a specific order." }, { "code": null, "e": 6439, "s": 6339, "text": "ORDERBY − The orderby clause is used along with select to read a specific data in a specific order." }, { "code": null, "e": 6472, "s": 6439, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 6486, "s": 6472, "text": " Navdeep Kaur" }, { "code": null, "e": 6521, "s": 6486, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6539, "s": 6521, "text": " Bigdata Engineer" }, { "code": null, "e": 6546, "s": 6539, "text": " Print" }, { "code": null, "e": 6557, "s": 6546, "text": " Add Notes" } ]
SQL | Wildcard operators - GeeksforGeeks
01 Sep, 2020 Prerequisite: SQL | WHERE ClauseIn the above mentioned article WHERE Clause is discussed in which LIKE operator is also explained, where you must have encountered the word wildcards now lets get deeper into Wildcards. Wildcard operators are used with LIKE operator, there are four basic operators: Basic syntax: SELECT column1,column2 FROM table_name WHERE column LIKE wildcard_operator; column1 , column2: fields in the table table_name: name of table column: name of field used for filtering data Queries To fetch records from Student table with NAME ending with letter ‘T’.SELECT * FROM Student WHERE NAME LIKE '%T'; Output:ROLL_NONAMEADDRESSPHONEAge3SUJITROHTAKXXXXXXXXXX203SUJITROHTAKXXXXXXXXXX20 SELECT * FROM Student WHERE NAME LIKE '%T'; Output: To fetch records from Student table with NAME ending any letter but starting from ‘RAMES’.SELECT * FROM Student WHERE NAME LIKE 'RAMES_'; Output:2RAMESHGURGAONXXXXXXXXXX18ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX18 SELECT * FROM Student WHERE NAME LIKE 'RAMES_'; Output: 2RAMESHGURGAONXXXXXXXXXX18 To fetch records from Student table with address containing letters ‘a’, ‘b’, or ‘c’.SELECT * FROM Student WHERE ADDRESS LIKE '%[A-C]%'; Output:2RAMESHGURGAONXXXXXXXXXX18ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX203SUJITROHTAKXXXXXXXXXX20 SELECT * FROM Student WHERE ADDRESS LIKE '%[A-C]%'; Output: 2RAMESHGURGAONXXXXXXXXXX18 To fetch records from Student table with ADDRESS not containing letters ‘a’, ‘b’, or ‘c’.SELECT * FROM Student WHERE ADDRESS LIKE '%[^A-C]%'; Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX184SURESHDelhiXXXXXXXXXX18 SELECT * FROM Student WHERE ADDRESS LIKE '%[^A-C]%'; Output: To fetch records from Student table with PHONE field having a ‘9’ in 1st position and a ‘5’ in 4th position.SELECT * FROM Student WHERE PHONE LIKE '9__5%'; Output:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX18 SELECT * FROM Student WHERE PHONE LIKE '9__5%'; Output: To fetch records from Student table with ADDRESS containing total of 6 characters.SELECT * FROM Student WHERE ADDRESS LIKE '______'; Output:ROLL_NONAMEADDRESSPHONEAge3SUJITROHTAKXXXXXXXXXX203SUJITROHTAKXXXXXXXXXX20 SELECT * FROM Student WHERE ADDRESS LIKE '______'; Output: To fetch records from Student table with ADDRESS containing ‘OH’ at any position, and the result set should not contain duplicate data.SELECT DISTINCT * FROM Student WHERE ADDRESS LIKE '%OH%'; Output:ROLL_NONAMEADDRESSPHONEAge3SUJITROHTAKXXXXXXXXXX20 SELECT DISTINCT * FROM Student WHERE ADDRESS LIKE '%OH%'; Output: This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. RAJAT1996 MANMEETKAUR3 lonewolf_ab shubham_singh khushboogoyal499 SQL-Clauses-Operators DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Clustered and Non-clustered index CTE in SQL SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between Primary Key and Foreign Key How to find Nth highest salary from a table SQL | ALTER (RENAME) CTE in SQL SQL | Views Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 23601, "s": 23573, "text": "\n01 Sep, 2020" }, { "code": null, "e": 23820, "s": 23601, "text": "Prerequisite: SQL | WHERE ClauseIn the above mentioned article WHERE Clause is discussed in which LIKE operator is also explained, where you must have encountered the word wildcards now lets get deeper into Wildcards." }, { "code": null, "e": 23900, "s": 23820, "text": "Wildcard operators are used with LIKE operator, there are four basic operators:" }, { "code": null, "e": 23914, "s": 23900, "text": "Basic syntax:" }, { "code": null, "e": 24102, "s": 23914, "text": "SELECT column1,column2 FROM table_name WHERE column LIKE wildcard_operator;\ncolumn1 , column2: fields in the table\ntable_name: name of table\ncolumn: name of field used for filtering data\n" }, { "code": null, "e": 24110, "s": 24102, "text": "Queries" }, { "code": null, "e": 24305, "s": 24110, "text": "To fetch records from Student table with NAME ending with letter ‘T’.SELECT * FROM Student WHERE NAME LIKE '%T';\nOutput:ROLL_NONAMEADDRESSPHONEAge3SUJITROHTAKXXXXXXXXXX203SUJITROHTAKXXXXXXXXXX20" }, { "code": null, "e": 24350, "s": 24305, "text": "SELECT * FROM Student WHERE NAME LIKE '%T';\n" }, { "code": null, "e": 24358, "s": 24350, "text": "Output:" }, { "code": null, "e": 24582, "s": 24358, "text": "To fetch records from Student table with NAME ending any letter but starting from ‘RAMES’.SELECT * FROM Student WHERE NAME LIKE 'RAMES_';\nOutput:2RAMESHGURGAONXXXXXXXXXX18ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX18" }, { "code": null, "e": 24631, "s": 24582, "text": "SELECT * FROM Student WHERE NAME LIKE 'RAMES_';\n" }, { "code": null, "e": 24639, "s": 24631, "text": "Output:" }, { "code": null, "e": 24666, "s": 24639, "text": "2RAMESHGURGAONXXXXXXXXXX18" }, { "code": null, "e": 24963, "s": 24666, "text": "To fetch records from Student table with address containing letters ‘a’, ‘b’, or ‘c’.SELECT * FROM Student WHERE ADDRESS LIKE '%[A-C]%';\nOutput:2RAMESHGURGAONXXXXXXXXXX18ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX203SUJITROHTAKXXXXXXXXXX20" }, { "code": null, "e": 25016, "s": 24963, "text": "SELECT * FROM Student WHERE ADDRESS LIKE '%[A-C]%';\n" }, { "code": null, "e": 25024, "s": 25016, "text": "Output:" }, { "code": null, "e": 25051, "s": 25024, "text": "2RAMESHGURGAONXXXXXXXXXX18" }, { "code": null, "e": 25272, "s": 25051, "text": "To fetch records from Student table with ADDRESS not containing letters ‘a’, ‘b’, or ‘c’.SELECT * FROM Student WHERE ADDRESS LIKE '%[^A-C]%';\nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX184SURESHDelhiXXXXXXXXXX18" }, { "code": null, "e": 25326, "s": 25272, "text": "SELECT * FROM Student WHERE ADDRESS LIKE '%[^A-C]%';\n" }, { "code": null, "e": 25334, "s": 25326, "text": "Output:" }, { "code": null, "e": 25545, "s": 25334, "text": "To fetch records from Student table with PHONE field having a ‘9’ in 1st position and a ‘5’ in 4th position.SELECT * FROM Student WHERE PHONE LIKE '9__5%';\nOutput:ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX18" }, { "code": null, "e": 25594, "s": 25545, "text": "SELECT * FROM Student WHERE PHONE LIKE '9__5%';\n" }, { "code": null, "e": 25602, "s": 25594, "text": "Output:" }, { "code": null, "e": 25817, "s": 25602, "text": "To fetch records from Student table with ADDRESS containing total of 6 characters.SELECT * FROM Student WHERE ADDRESS LIKE '______';\nOutput:ROLL_NONAMEADDRESSPHONEAge3SUJITROHTAKXXXXXXXXXX203SUJITROHTAKXXXXXXXXXX20" }, { "code": null, "e": 25869, "s": 25817, "text": "SELECT * FROM Student WHERE ADDRESS LIKE '______';\n" }, { "code": null, "e": 25877, "s": 25869, "text": "Output:" }, { "code": null, "e": 26128, "s": 25877, "text": "To fetch records from Student table with ADDRESS containing ‘OH’ at any position, and the result set should not contain duplicate data.SELECT DISTINCT * FROM Student WHERE ADDRESS LIKE '%OH%';\nOutput:ROLL_NONAMEADDRESSPHONEAge3SUJITROHTAKXXXXXXXXXX20" }, { "code": null, "e": 26187, "s": 26128, "text": "SELECT DISTINCT * FROM Student WHERE ADDRESS LIKE '%OH%';\n" }, { "code": null, "e": 26195, "s": 26187, "text": "Output:" }, { "code": null, "e": 26497, "s": 26195, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26622, "s": 26497, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26632, "s": 26622, "text": "RAJAT1996" }, { "code": null, "e": 26645, "s": 26632, "text": "MANMEETKAUR3" }, { "code": null, "e": 26657, "s": 26645, "text": "lonewolf_ab" }, { "code": null, "e": 26671, "s": 26657, "text": "shubham_singh" }, { "code": null, "e": 26688, "s": 26671, "text": "khushboogoyal499" }, { "code": null, "e": 26710, "s": 26688, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 26715, "s": 26710, "text": "DBMS" }, { "code": null, "e": 26719, "s": 26715, "text": "SQL" }, { "code": null, "e": 26724, "s": 26719, "text": "DBMS" }, { "code": null, "e": 26728, "s": 26724, "text": "SQL" }, { "code": null, "e": 26826, "s": 26728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26835, "s": 26826, "text": "Comments" }, { "code": null, "e": 26848, "s": 26835, "text": "Old Comments" }, { "code": null, "e": 26901, "s": 26848, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26912, "s": 26901, "text": "CTE in SQL" }, { "code": null, "e": 26924, "s": 26912, "text": "SQL | Views" }, { "code": null, "e": 26969, "s": 26924, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27016, "s": 26969, "text": "Difference between Primary Key and Foreign Key" }, { "code": null, "e": 27060, "s": 27016, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 27081, "s": 27060, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 27092, "s": 27081, "text": "CTE in SQL" }, { "code": null, "e": 27104, "s": 27092, "text": "SQL | Views" } ]
How to set maximum date in datepicker dialog in Android using Kotlin?
This example demonstrates how to set maximum date in datepicker dialog in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#f2f6f4" android:padding="10dp" tools:context=".MainActivity"> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:fontFamily="sans-serif-condensed" android:text="Date" android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.app.DatePickerDialog import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { private var year = 0 private var month = 0 private var day = 0 lateinit var textView: TextView private lateinit var calendar: Calendar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" calendar = Calendar.getInstance() year = calendar.get(Calendar.YEAR) month = calendar.get(Calendar.MONTH) day = calendar.get(Calendar.DAY_OF_MONTH) textView = findViewById(R.id.textView) val dialog = DatePickerDialog(this, { _, year, month, day_of_month -> calendar[Calendar.YEAR] = year calendar[Calendar.MONTH] = month + 1 calendar[Calendar.DAY_OF_MONTH] = day_of_month val myFormat = "dd/MM/yyyy" val sdf = SimpleDateFormat(myFormat, Locale.getDefault()) textView.text = sdf.format(calendar.time) }, calendar[Calendar.YEAR], calendar[Calendar.MONTH], calendar[Calendar.DAY_OF_MONTH]) dialog.datePicker.minDate = calendar.timeInMillis calendar.add(Calendar.YEAR, 0) dialog.datePicker.maxDate = calendar.timeInMillis dialog.show() } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
[ { "code": null, "e": 1158, "s": 1062, "text": "This example demonstrates how to set maximum date in datepicker dialog in Android using Kotlin." }, { "code": null, "e": 1287, "s": 1158, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1352, "s": 1287, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2503, "s": 1352, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"#f2f6f4\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:fontFamily=\"sans-serif-condensed\"\n android:text=\"Date\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2558, "s": 2503, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3971, "s": 2558, "text": "import android.app.DatePickerDialog\nimport android.os.Bundle\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport java.text.SimpleDateFormat\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n private var year = 0\n private var month = 0\n private var day = 0\n lateinit var textView: TextView\n private lateinit var calendar: Calendar\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n calendar = Calendar.getInstance()\n year = calendar.get(Calendar.YEAR)\n month = calendar.get(Calendar.MONTH)\n day = calendar.get(Calendar.DAY_OF_MONTH)\n textView = findViewById(R.id.textView)\n val dialog = DatePickerDialog(this, { _, year, month, day_of_month ->\n calendar[Calendar.YEAR] = year\n calendar[Calendar.MONTH] = month + 1\n calendar[Calendar.DAY_OF_MONTH] = day_of_month\n val myFormat = \"dd/MM/yyyy\"\n val sdf = SimpleDateFormat(myFormat, Locale.getDefault())\n textView.text = sdf.format(calendar.time)\n }, calendar[Calendar.YEAR], calendar[Calendar.MONTH], calendar[Calendar.DAY_OF_MONTH])\n dialog.datePicker.minDate = calendar.timeInMillis\n calendar.add(Calendar.YEAR, 0)\n dialog.datePicker.maxDate = calendar.timeInMillis\n dialog.show()\n }\n}" }, { "code": null, "e": 4026, "s": 3971, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4700, "s": 4026, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5049, "s": 4700, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
How to check if an instance of 8 puzzle is solvable?
03 Nov, 2021 What is 8 puzzle? Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space How to find if given state is solvable? Following are two examples, the first example can reach goal state by a series of slides. The second example cannot. Following is simple rule to check if a 8 puzzle is solvable. It is not possible to solve an instance of 8 puzzle if number of inversions is odd in the input state. In the examples given in above figure, the first example has 10 inversions, therefore solvable. The second example has 11 inversions, therefore unsolvable. What is inversion? A pair of tiles form an inversion if the values on tiles are in reverse order of their appearance in goal state. For example, the following instance of 8 puzzle has two inversions, (8, 6) and (8, 7). 1 2 3 4 _ 5 8 6 7 Following are the implementations to check whether a given instance of 8 puzzle is solvable or not. The idea is simple, we count inversions in the given 8 puzzle. C++ Java Python3 C# PHP Javascript // C++ program to check if a given instance of 8 puzzle is solvable or not#include <iostream>using namespace std; // A utility function to count inversions in given array 'arr[]'int getInvCount(int arr[]){ int inv_count = 0; for (int i = 0; i < 9 - 1; i++) for (int j = i+1; j < 9; j++) // Value 0 is used for empty space if (arr[j] && arr[i] && arr[i] > arr[j]) inv_count++; return inv_count;} // This function returns true if given 8 puzzle is solvable.bool isSolvable(int puzzle[3][3]){ // Count inversions in given 8 puzzle int invCount = getInvCount((int *)puzzle); // return true if inversion count is even. return (invCount%2 == 0);} /* Driver program to test above functions */int main(int argv, int** args){ int puzzle[3][3] = {{1, 8, 2}, {0, 4, 3}, // Value 0 is used for empty space {7, 6, 5}}; isSolvable(puzzle)? cout << "Solvable": cout << "Not Solvable"; return 0;} // Java program to check if a given// instance of 8 puzzle is solvable or notclass GFG{ // A utility function to count// inversions in given array 'arr[]'static int getInvCount(int[][] arr){ int inv_count = 0; for (int i = 0; i < 3 - 1; i++) for (int j = i + 1; j < 3; j++) // Value 0 is used for empty space if (arr[j][i] > 0 && arr[j][i] > arr[i][j]) inv_count++; return inv_count;} // This function returns true// if given 8 puzzle is solvable.static boolean isSolvable(int[][] puzzle){ // Count inversions in given 8 puzzle int invCount = getInvCount(puzzle); // return true if inversion count is even. return (invCount % 2 == 0);} /* Driver code */public static void main (String[] args){ int[][] puzzle = {{1, 8, 2},{0, 4, 3},{7, 6, 5}}; if(isSolvable(puzzle)) System.out.println("Solvable"); else System.out.println("Not Solvable");}} // This code is contributed by chandan_jnu # Python3 program to check if a given# instance of 8 puzzle is solvable or not # A utility function to count# inversions in given array 'arr[]'def getInvCount(arr): inv_count = 0 empty_value = -1 for i in range(0, 9): for j in range(i + 1, 9): if arr[j] != empty_value and arr[i] != empty_value and arr[i] > arr[j]: inv_count += 1 return inv_count # This function returns true# if given 8 puzzle is solvable.def isSolvable(puzzle) : # Count inversions in given 8 puzzle inv_count = getInvCount([j for sub in puzzle for j in sub]) # return true if inversion count is even. return (inv_count % 2 == 0) # Driver codepuzzle = [[8, 1, 2],[-1, 4, 3],[7, 6, 5]]if(isSolvable(puzzle)) : print("Solvable")else : print("Not Solvable") # This code is contributed by vitorhugooli # Fala meu povo desse Brasil varonil // C# program to check if a given// instance of 8 puzzle is solvable or notusing System; class GFG{ // A utility function to count// inversions in given array 'arr[]'static int getInvCount(int[,] arr){ int inv_count = 0; for (int i = 0; i < 3 - 1; i++) for (int j = i + 1; j < 3; j++) // Value 0 is used for empty space if (arr[j, i] > 0 && arr[j, i] > arr[i, j]) inv_count++; return inv_count;} // This function returns true// if given 8 puzzle is solvable.static bool isSolvable(int[,] puzzle){ // Count inversions in given 8 puzzle int invCount = getInvCount(puzzle); // return true if inversion count is even. return (invCount % 2 == 0);} /* Driver code */static void Main(){ int[,] puzzle = new int[3,3]{{1, 8, 2}, {0, 4, 3}, // Value 0 is used for empty space {7, 6, 5}}; if(isSolvable(puzzle)) Console.WriteLine("Solvable"); else Console.WriteLine("Not Solvable");}} // This code is contributed by chandan_jnu <?php// PHP program to check if// a given instance of 8// puzzle is solvable or not // A utility function to// count inversions in// given array 'arr[]'function getInvCount($arr){ $inv_count = 0; for ($i = 0; $i < 9 - 1; $i++) for ( $j = $i + 1; $j < 9; $j++) $inv_count++; return $inv_count;} // This function returns true// if given 8 puzzle is solvable.function isSolvable($puzzle){ // Count inversions in // given 8 puzzle $invCount = getInvCount($puzzle); // return true if // inversion count is even. return ($invCount % 2 == 0);} // Driver Code$puzzle = array(array(1, 8, 2), array(0, 4, 3), // Value 0 is used array(7, 6, 5));// for empty space if(isSolvable($puzzle) == true) echo "Solvable"; else echo "Not Solvable"; // This code is contributed by ajit?> <script> // JavaScript program to check if a given// instance of 8 puzzle is solvable or not // A utility function to count inversions// in given array 'arr[]'function getInvCount(arr){ let inv_count = 0 ; for(let i=0;i<2;i++){ for(let j=i+1;j<3;j++){ // Value 0 is used for empty space if (arr[j][i] > 0 && arr[j][i] > arr[i][j]) inv_count += 1; } } return inv_count;}// This function returns true// if given 8 puzzle is solvable.function isSolvable(puzzle){ // Count inversions in given 8 puzzle let invCount = getInvCount(puzzle); // return true if inversion count is even. return (invCount % 2 == 0);} // Driver code // Value 0 is used for empty spacepuzzle = [[1, 8, 2],[0, 4, 3],[7, 6, 5]] ;if(isSolvable(puzzle)) document.write("Solvable");else document.write("Not Solvable"); </script> Output : Solvable Time Complexity: O(1) Auxiliary Space: O(1) Note that the above implementation uses simple algorithm for inversion count. It is done this way for simplicity. The code can be optimized to O(nLogn) using the merge sort based algorithm for inversion count. How does this work? The idea is based on the fact the parity of inversions remains same after a set of moves, i.e., if the inversion count is odd in initial stage, then it remain odd after any sequence of moves and if the inversion count is even, then it remains even after any sequence of moves. In the goal state, there are 0 inversions. So we can reach goal state only from a state which has even inversion count.How parity of inversion count is invariant? When we slide a tile, we either make a row move (moving a left or right tile into the blank space), or make a column move (moving a up or down tile to the blank space). a) A row move doesn’t change the inversion count. See following example 1 2 3 Row Move 1 2 3 4 _ 5 ----------> _ 4 5 8 6 7 8 6 7 Inversion count remains 2 after the move 1 2 3 Row Move 1 2 3 4 _ 5 ----------> 4 5 _ 8 6 7 8 6 7 Inversion count remains 2 after the move b) A column move does one of the following three. .....(i) Increases inversion count by 2. See following example. 1 2 3 Column Move 1 _ 3 4 _ 5 -----------> 4 2 5 8 6 7 8 6 7 Inversion count increases by 2 (changes from 2 to 4) .....(ii) Decreases inversion count by 2 1 3 4 Column Move 1 3 4 5 _ 6 ------------> 5 2 6 7 2 8 7 _ 8 Inversion count decreases by 2 (changes from 5 to 3) .....(iii) Keeps the inversion count same. 1 2 3 Column Move 1 2 3 4 _ 5 ------------> 4 6 5 7 6 8 7 _ 8 Inversion count remains 1 after the move So if a move either increases/decreases inversion count by 2, or keeps the inversion count same, then it is not possible to change parity of a state by any sequence of row/column moves. Exercise: How to check if a given instance of 15 puzzle is solvable or not. In a 15 puzzle, we have 4×4 board where 15 tiles have a number and one empty space. Note that the above simple rules of inversion count don’t directly work for 15 puzzle, the rules need to be modified for 15 puzzle. Related Article: How to check if an instance of 15 puzzle is solvable?This article is contributed by Ishan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t Chandan_Kumar vibhu4agarwal Akanksha_Rai lukijosai divyeshrabadiya07 rohan07 kk9826225 vho2009 subham348 Mathematical Mathematical 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 Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Modulo Operator (%) in C/C++ with Examples Program for factorial of a number
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Nov, 2021" }, { "code": null, "e": 326, "s": 52, "text": "What is 8 puzzle? Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space" }, { "code": null, "e": 484, "s": 326, "text": "How to find if given state is solvable? Following are two examples, the first example can reach goal state by a series of slides. The second example cannot. " }, { "code": null, "e": 804, "s": 484, "text": "Following is simple rule to check if a 8 puzzle is solvable. It is not possible to solve an instance of 8 puzzle if number of inversions is odd in the input state. In the examples given in above figure, the first example has 10 inversions, therefore solvable. The second example has 11 inversions, therefore unsolvable." }, { "code": null, "e": 1024, "s": 804, "text": "What is inversion? A pair of tiles form an inversion if the values on tiles are in reverse order of their appearance in goal state. For example, the following instance of 8 puzzle has two inversions, (8, 6) and (8, 7). " }, { "code": null, "e": 1069, "s": 1024, "text": " 1 2 3\n 4 _ 5\n 8 6 7 " }, { "code": null, "e": 1233, "s": 1069, "text": "Following are the implementations to check whether a given instance of 8 puzzle is solvable or not. The idea is simple, we count inversions in the given 8 puzzle. " }, { "code": null, "e": 1237, "s": 1233, "text": "C++" }, { "code": null, "e": 1242, "s": 1237, "text": "Java" }, { "code": null, "e": 1250, "s": 1242, "text": "Python3" }, { "code": null, "e": 1253, "s": 1250, "text": "C#" }, { "code": null, "e": 1257, "s": 1253, "text": "PHP" }, { "code": null, "e": 1268, "s": 1257, "text": "Javascript" }, { "code": "// C++ program to check if a given instance of 8 puzzle is solvable or not#include <iostream>using namespace std; // A utility function to count inversions in given array 'arr[]'int getInvCount(int arr[]){ int inv_count = 0; for (int i = 0; i < 9 - 1; i++) for (int j = i+1; j < 9; j++) // Value 0 is used for empty space if (arr[j] && arr[i] && arr[i] > arr[j]) inv_count++; return inv_count;} // This function returns true if given 8 puzzle is solvable.bool isSolvable(int puzzle[3][3]){ // Count inversions in given 8 puzzle int invCount = getInvCount((int *)puzzle); // return true if inversion count is even. return (invCount%2 == 0);} /* Driver program to test above functions */int main(int argv, int** args){ int puzzle[3][3] = {{1, 8, 2}, {0, 4, 3}, // Value 0 is used for empty space {7, 6, 5}}; isSolvable(puzzle)? cout << \"Solvable\": cout << \"Not Solvable\"; return 0;}", "e": 2288, "s": 1268, "text": null }, { "code": "// Java program to check if a given// instance of 8 puzzle is solvable or notclass GFG{ // A utility function to count// inversions in given array 'arr[]'static int getInvCount(int[][] arr){ int inv_count = 0; for (int i = 0; i < 3 - 1; i++) for (int j = i + 1; j < 3; j++) // Value 0 is used for empty space if (arr[j][i] > 0 && arr[j][i] > arr[i][j]) inv_count++; return inv_count;} // This function returns true// if given 8 puzzle is solvable.static boolean isSolvable(int[][] puzzle){ // Count inversions in given 8 puzzle int invCount = getInvCount(puzzle); // return true if inversion count is even. return (invCount % 2 == 0);} /* Driver code */public static void main (String[] args){ int[][] puzzle = {{1, 8, 2},{0, 4, 3},{7, 6, 5}}; if(isSolvable(puzzle)) System.out.println(\"Solvable\"); else System.out.println(\"Not Solvable\");}} // This code is contributed by chandan_jnu", "e": 3298, "s": 2288, "text": null }, { "code": "# Python3 program to check if a given# instance of 8 puzzle is solvable or not # A utility function to count# inversions in given array 'arr[]'def getInvCount(arr): inv_count = 0 empty_value = -1 for i in range(0, 9): for j in range(i + 1, 9): if arr[j] != empty_value and arr[i] != empty_value and arr[i] > arr[j]: inv_count += 1 return inv_count # This function returns true# if given 8 puzzle is solvable.def isSolvable(puzzle) : # Count inversions in given 8 puzzle inv_count = getInvCount([j for sub in puzzle for j in sub]) # return true if inversion count is even. return (inv_count % 2 == 0) # Driver codepuzzle = [[8, 1, 2],[-1, 4, 3],[7, 6, 5]]if(isSolvable(puzzle)) : print(\"Solvable\")else : print(\"Not Solvable\") # This code is contributed by vitorhugooli # Fala meu povo desse Brasil varonil ", "e": 4193, "s": 3298, "text": null }, { "code": "// C# program to check if a given// instance of 8 puzzle is solvable or notusing System; class GFG{ // A utility function to count// inversions in given array 'arr[]'static int getInvCount(int[,] arr){ int inv_count = 0; for (int i = 0; i < 3 - 1; i++) for (int j = i + 1; j < 3; j++) // Value 0 is used for empty space if (arr[j, i] > 0 && arr[j, i] > arr[i, j]) inv_count++; return inv_count;} // This function returns true// if given 8 puzzle is solvable.static bool isSolvable(int[,] puzzle){ // Count inversions in given 8 puzzle int invCount = getInvCount(puzzle); // return true if inversion count is even. return (invCount % 2 == 0);} /* Driver code */static void Main(){ int[,] puzzle = new int[3,3]{{1, 8, 2}, {0, 4, 3}, // Value 0 is used for empty space {7, 6, 5}}; if(isSolvable(puzzle)) Console.WriteLine(\"Solvable\"); else Console.WriteLine(\"Not Solvable\");}} // This code is contributed by chandan_jnu", "e": 5265, "s": 4193, "text": null }, { "code": "<?php// PHP program to check if// a given instance of 8// puzzle is solvable or not // A utility function to// count inversions in// given array 'arr[]'function getInvCount($arr){ $inv_count = 0; for ($i = 0; $i < 9 - 1; $i++) for ( $j = $i + 1; $j < 9; $j++) $inv_count++; return $inv_count;} // This function returns true// if given 8 puzzle is solvable.function isSolvable($puzzle){ // Count inversions in // given 8 puzzle $invCount = getInvCount($puzzle); // return true if // inversion count is even. return ($invCount % 2 == 0);} // Driver Code$puzzle = array(array(1, 8, 2), array(0, 4, 3), // Value 0 is used array(7, 6, 5));// for empty space if(isSolvable($puzzle) == true) echo \"Solvable\"; else echo \"Not Solvable\"; // This code is contributed by ajit?>", "e": 6172, "s": 5265, "text": null }, { "code": "<script> // JavaScript program to check if a given// instance of 8 puzzle is solvable or not // A utility function to count inversions// in given array 'arr[]'function getInvCount(arr){ let inv_count = 0 ; for(let i=0;i<2;i++){ for(let j=i+1;j<3;j++){ // Value 0 is used for empty space if (arr[j][i] > 0 && arr[j][i] > arr[i][j]) inv_count += 1; } } return inv_count;}// This function returns true// if given 8 puzzle is solvable.function isSolvable(puzzle){ // Count inversions in given 8 puzzle let invCount = getInvCount(puzzle); // return true if inversion count is even. return (invCount % 2 == 0);} // Driver code // Value 0 is used for empty spacepuzzle = [[1, 8, 2],[0, 4, 3],[7, 6, 5]] ;if(isSolvable(puzzle)) document.write(\"Solvable\");else document.write(\"Not Solvable\"); </script>", "e": 7061, "s": 6172, "text": null }, { "code": null, "e": 7071, "s": 7061, "text": "Output : " }, { "code": null, "e": 7080, "s": 7071, "text": "Solvable" }, { "code": null, "e": 7102, "s": 7080, "text": "Time Complexity: O(1)" }, { "code": null, "e": 7124, "s": 7102, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7334, "s": 7124, "text": "Note that the above implementation uses simple algorithm for inversion count. It is done this way for simplicity. The code can be optimized to O(nLogn) using the merge sort based algorithm for inversion count." }, { "code": null, "e": 7964, "s": 7334, "text": "How does this work? The idea is based on the fact the parity of inversions remains same after a set of moves, i.e., if the inversion count is odd in initial stage, then it remain odd after any sequence of moves and if the inversion count is even, then it remains even after any sequence of moves. In the goal state, there are 0 inversions. So we can reach goal state only from a state which has even inversion count.How parity of inversion count is invariant? When we slide a tile, we either make a row move (moving a left or right tile into the blank space), or make a column move (moving a up or down tile to the blank space). " }, { "code": null, "e": 8038, "s": 7964, "text": "a) A row move doesn’t change the inversion count. See following example " }, { "code": null, "e": 8360, "s": 8038, "text": " 1 2 3 Row Move 1 2 3\n 4 _ 5 ----------> _ 4 5 \n 8 6 7 8 6 7\n Inversion count remains 2 after the move\n\n 1 2 3 Row Move 1 2 3\n 4 _ 5 ----------> 4 5 _\n 8 6 7 8 6 7\n Inversion count remains 2 after the move" }, { "code": null, "e": 8475, "s": 8360, "text": "b) A column move does one of the following three. .....(i) Increases inversion count by 2. See following example. " }, { "code": null, "e": 8685, "s": 8475, "text": " 1 2 3 Column Move 1 _ 3\n 4 _ 5 -----------> 4 2 5 \n 8 6 7 8 6 7\n Inversion count increases by 2 (changes from 2 to 4)\n " }, { "code": null, "e": 8726, "s": 8685, "text": ".....(ii) Decreases inversion count by 2" }, { "code": null, "e": 8930, "s": 8726, "text": " 1 3 4 Column Move 1 3 4\n 5 _ 6 ------------> 5 2 6\n 7 2 8 7 _ 8\n Inversion count decreases by 2 (changes from 5 to 3)" }, { "code": null, "e": 8974, "s": 8930, "text": ".....(iii) Keeps the inversion count same. " }, { "code": null, "e": 9168, "s": 8974, "text": " 1 2 3 Column Move 1 2 3\n 4 _ 5 ------------> 4 6 5\n 7 6 8 7 _ 8\n Inversion count remains 1 after the move " }, { "code": null, "e": 9354, "s": 9168, "text": "So if a move either increases/decreases inversion count by 2, or keeps the inversion count same, then it is not possible to change parity of a state by any sequence of row/column moves." }, { "code": null, "e": 9646, "s": 9354, "text": "Exercise: How to check if a given instance of 15 puzzle is solvable or not. In a 15 puzzle, we have 4×4 board where 15 tiles have a number and one empty space. Note that the above simple rules of inversion count don’t directly work for 15 puzzle, the rules need to be modified for 15 puzzle." }, { "code": null, "e": 9879, "s": 9646, "text": "Related Article: How to check if an instance of 15 puzzle is solvable?This article is contributed by Ishan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 9885, "s": 9879, "text": "jit_t" }, { "code": null, "e": 9899, "s": 9885, "text": "Chandan_Kumar" }, { "code": null, "e": 9913, "s": 9899, "text": "vibhu4agarwal" }, { "code": null, "e": 9926, "s": 9913, "text": "Akanksha_Rai" }, { "code": null, "e": 9936, "s": 9926, "text": "lukijosai" }, { "code": null, "e": 9954, "s": 9936, "text": "divyeshrabadiya07" }, { "code": null, "e": 9962, "s": 9954, "text": "rohan07" }, { "code": null, "e": 9972, "s": 9962, "text": "kk9826225" }, { "code": null, "e": 9980, "s": 9972, "text": "vho2009" }, { "code": null, "e": 9990, "s": 9980, "text": "subham348" }, { "code": null, "e": 10003, "s": 9990, "text": "Mathematical" }, { "code": null, "e": 10016, "s": 10003, "text": "Mathematical" }, { "code": null, "e": 10114, "s": 10016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10138, "s": 10114, "text": "Merge two sorted arrays" }, { "code": null, "e": 10159, "s": 10138, "text": "Operators in C / C++" }, { "code": null, "e": 10173, "s": 10159, "text": "Prime Numbers" }, { "code": null, "e": 10226, "s": 10173, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 10263, "s": 10226, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 10295, "s": 10263, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 10322, "s": 10295, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 10365, "s": 10322, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 10408, "s": 10365, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Python 3 - List len() Method
The len() method returns the number of elements in the list. Following is the syntax for len() method − len(list) list − This is a list for which number of elements to be counted. This method returns the number of elements in the list. The following example shows the usage of len() method. #!/usr/bin/python3 list1 = ['physics', 'chemistry', 'maths'] print (len(list1)) list2 = list(range(5)) #creates list of numbers between 0-4 print (len(list2)) When we run above program, it produces the following result −
[ { "code": null, "e": 2535, "s": 2474, "text": "The len() method returns the number of elements in the list." }, { "code": null, "e": 2578, "s": 2535, "text": "Following is the syntax for len() method −" }, { "code": null, "e": 2589, "s": 2578, "text": "len(list)\n" }, { "code": null, "e": 2655, "s": 2589, "text": "list − This is a list for which number of elements to be counted." }, { "code": null, "e": 2711, "s": 2655, "text": "This method returns the number of elements in the list." }, { "code": null, "e": 2766, "s": 2711, "text": "The following example shows the usage of len() method." }, { "code": null, "e": 2927, "s": 2766, "text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'chemistry', 'maths']\nprint (len(list1))\n\nlist2 = list(range(5)) #creates list of numbers between 0-4\nprint (len(list2))" } ]
Modulo of a large Binary String
10 May, 2021 Given a large binary string str and an integer K, the task is to find the value of str % K.Examples: Input: str = “1101”, K = 45 Output: 13 decimal(1101) % 45 = 13 % 45 = 13Input: str = “11010101”, K = 112 Output: 101 decimal(11010101) % 112 = 213 % 112 = 101 Approach: It is known that (str % K) where str is a binary string can be written as ((str[n – 1] * 20) + (str[n – 2] * 21) + ... + (str[0] * 2n – 1)) % K which in turn can be written as (((str[n – 1] * 20) % K) + ((str[n – 2] * 21) % K) + ... + ((str[0] * 2n – 1)) % K) % K. This can be used to find the required answer without actually converting the given binary string to its decimal equivalent.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value of (str % k)int getMod(string str, int n, int k){ // pwrTwo[i] will store ((2^i) % k) int pwrTwo[n]; pwrTwo[0] = 1 % k; for (int i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result int res = 0; int i = 0, j = n - 1; while (i < n) { // If current bit is 1 if (str[j] == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res;} // Driver codeint main(){ string str = "1101"; int n = str.length(); int k = 45; cout << getMod(str, n, k) << endl;} // This code is contributed by ashutosh450 // Java implementation of the approachimport java.util.*; class GFG { // Function to return the value of (str % k) static int getMod(String str, int n, int k) { // pwrTwo[i] will store ((2^i) % k) int pwrTwo[] = new int[n]; pwrTwo[0] = 1 % k; for (int i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result int res = 0; int i = 0, j = n - 1; while (i < n) { // If current bit is 1 if (str.charAt(j) == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res; } // Driver code public static void main(String[] args) { String str = "1101"; int n = str.length(); int k = 45; System.out.print(getMod(str, n, k)); }} # Python3 implementation of the approach # Function to return the value of (str % k)def getMod(_str, n, k) : # pwrTwo[i] will store ((2^i) % k) pwrTwo = [0] * n pwrTwo[0] = 1 % k for i in range(1, n): pwrTwo[i] = pwrTwo[i - 1] * (2 % k) pwrTwo[i] %= k # To store the result res = 0 i = 0 j = n - 1 while (i < n) : # If current bit is 1 if (_str[j] == '1') : # Add the current power of 2 res += (pwrTwo[i]) res %= k i += 1 j -= 1 return res # Driver code_str = "1101"n = len(_str)k = 45 print(getMod(_str, n, k)) # This code is contributed by# divyamohan123 // C# implementation of the above approachusing System; class GFG{ // Function to return the value of (str % k) static int getMod(string str, int n, int k) { int i; // pwrTwo[i] will store ((2^i) % k) int []pwrTwo = new int[n]; pwrTwo[0] = 1 % k; for (i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result int res = 0; i = 0; int j = n - 1; while (i < n) { // If current bit is 1 if (str[j] == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res; } // Driver code public static void Main() { string str = "1101"; int n = str.Length; int k = 45; Console.Write(getMod(str, n, k)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the approach // Function to return the value of (str % k)function getMod(str, n, k){ // pwrTwo[i] will store ((2^i) % k) var pwrTwo = Array(n); pwrTwo[0] = 1 % k; for (var i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result var res = 0; var i = 0, j = n - 1; while (i < n) { // If current bit is 1 if (str[j] == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res;} // Driver codevar str = "1101";var n = str.length;var k = 45;document.write( getMod(str, n, k)); </script> 13 divyamohan123 ankthon ashutosh450 itsok binary-string Modular Arithmetic Strings Strings Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 May, 2021" }, { "code": null, "e": 157, "s": 54, "text": "Given a large binary string str and an integer K, the task is to find the value of str % K.Examples: " }, { "code": null, "e": 318, "s": 157, "text": "Input: str = “1101”, K = 45 Output: 13 decimal(1101) % 45 = 13 % 45 = 13Input: str = “11010101”, K = 112 Output: 101 decimal(11010101) % 112 = 213 % 112 = 101 " }, { "code": null, "e": 771, "s": 320, "text": "Approach: It is known that (str % K) where str is a binary string can be written as ((str[n – 1] * 20) + (str[n – 2] * 21) + ... + (str[0] * 2n – 1)) % K which in turn can be written as (((str[n – 1] * 20) % K) + ((str[n – 2] * 21) % K) + ... + ((str[0] * 2n – 1)) % K) % K. This can be used to find the required answer without actually converting the given binary string to its decimal equivalent.Below is the implementation of the above approach: " }, { "code": null, "e": 775, "s": 771, "text": "C++" }, { "code": null, "e": 780, "s": 775, "text": "Java" }, { "code": null, "e": 788, "s": 780, "text": "Python3" }, { "code": null, "e": 791, "s": 788, "text": "C#" }, { "code": null, "e": 802, "s": 791, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value of (str % k)int getMod(string str, int n, int k){ // pwrTwo[i] will store ((2^i) % k) int pwrTwo[n]; pwrTwo[0] = 1 % k; for (int i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result int res = 0; int i = 0, j = n - 1; while (i < n) { // If current bit is 1 if (str[j] == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res;} // Driver codeint main(){ string str = \"1101\"; int n = str.length(); int k = 45; cout << getMod(str, n, k) << endl;} // This code is contributed by ashutosh450", "e": 1631, "s": 802, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to return the value of (str % k) static int getMod(String str, int n, int k) { // pwrTwo[i] will store ((2^i) % k) int pwrTwo[] = new int[n]; pwrTwo[0] = 1 % k; for (int i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result int res = 0; int i = 0, j = n - 1; while (i < n) { // If current bit is 1 if (str.charAt(j) == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res; } // Driver code public static void main(String[] args) { String str = \"1101\"; int n = str.length(); int k = 45; System.out.print(getMod(str, n, k)); }}", "e": 2582, "s": 1631, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the value of (str % k)def getMod(_str, n, k) : # pwrTwo[i] will store ((2^i) % k) pwrTwo = [0] * n pwrTwo[0] = 1 % k for i in range(1, n): pwrTwo[i] = pwrTwo[i - 1] * (2 % k) pwrTwo[i] %= k # To store the result res = 0 i = 0 j = n - 1 while (i < n) : # If current bit is 1 if (_str[j] == '1') : # Add the current power of 2 res += (pwrTwo[i]) res %= k i += 1 j -= 1 return res # Driver code_str = \"1101\"n = len(_str)k = 45 print(getMod(_str, n, k)) # This code is contributed by# divyamohan123", "e": 3262, "s": 2582, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the value of (str % k) static int getMod(string str, int n, int k) { int i; // pwrTwo[i] will store ((2^i) % k) int []pwrTwo = new int[n]; pwrTwo[0] = 1 % k; for (i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result int res = 0; i = 0; int j = n - 1; while (i < n) { // If current bit is 1 if (str[j] == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res; } // Driver code public static void Main() { string str = \"1101\"; int n = str.Length; int k = 45; Console.Write(getMod(str, n, k)); }} // This code is contributed by AnkitRai01", "e": 4298, "s": 3262, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the value of (str % k)function getMod(str, n, k){ // pwrTwo[i] will store ((2^i) % k) var pwrTwo = Array(n); pwrTwo[0] = 1 % k; for (var i = 1; i < n; i++) { pwrTwo[i] = pwrTwo[i - 1] * (2 % k); pwrTwo[i] %= k; } // To store the result var res = 0; var i = 0, j = n - 1; while (i < n) { // If current bit is 1 if (str[j] == '1') { // Add the current power of 2 res += (pwrTwo[i]); res %= k; } i++; j--; } return res;} // Driver codevar str = \"1101\";var n = str.length;var k = 45;document.write( getMod(str, n, k)); </script>", "e": 5032, "s": 4298, "text": null }, { "code": null, "e": 5035, "s": 5032, "text": "13" }, { "code": null, "e": 5051, "s": 5037, "text": "divyamohan123" }, { "code": null, "e": 5059, "s": 5051, "text": "ankthon" }, { "code": null, "e": 5071, "s": 5059, "text": "ashutosh450" }, { "code": null, "e": 5077, "s": 5071, "text": "itsok" }, { "code": null, "e": 5091, "s": 5077, "text": "binary-string" }, { "code": null, "e": 5110, "s": 5091, "text": "Modular Arithmetic" }, { "code": null, "e": 5118, "s": 5110, "text": "Strings" }, { "code": null, "e": 5126, "s": 5118, "text": "Strings" }, { "code": null, "e": 5145, "s": 5126, "text": "Modular Arithmetic" } ]
PostgreSQL – Loading a Database
20 Sep, 2021 In this article we will look into the process of loading a PostgreSQL database into the PostgreSQL database server. Before moving forward we just need to make sure of two things: PostgreSQL database server is installed on your system. A sample database. For the purpose of this article, we will be using a sample database which is DVD rental database. You can download the sample dvdrental database from here. So, the DVD rental database that we will be using ahead in the article represents a DVD rental store. The objects in the database includes: 15 tables 1 trigger 8 functions 1 domain 7 views 13 sequences ER Model of the sample Database: Tables in the Sample Database: There are 15 tables in our sample database which are listed below: actor – stores actors data including first name and last name. film – stores films data such as title, release year, length, rating, etc film_actor – stores the relationships between films and actors. category – stores film’s categories data. film_category– stores the relationships between films and categories. store – contains the store data including manager staff and address. inventory – stores inventory data. rental – stores rental data. payment – stores customer’s payments. staff – stores staff data. customer – stores customers data. address – stores address data for staff and customers city – stores the city names. country – stores the country names. actor – stores actors data including first name and last name. film – stores films data such as title, release year, length, rating, etc film_actor – stores the relationships between films and actors. category – stores film’s categories data. film_category– stores the relationships between films and categories. store – contains the store data including manager staff and address. inventory – stores inventory data. rental – stores rental data. payment – stores customer’s payments. staff – stores staff data. customer – stores customers data. address – stores address data for staff and customers city – stores the city names. country – stores the country names. So now we know everything about our sample DVD rental database, let us move on to loading the same database to the PostgreSQL database server. The steps to which are listed below: Step 1: Create a DVD rental Database, by opening the SQL shell. Once you open up the shell, you will need to add the necessary credentials for your database, which would somewhat look like below: Server [localhost]: Database [postgres]: Port [5432]: Username [postgres]: Password for user postgres: Now using the CREATE DATABASE statement create a new database as follows: CREATE DATABASE dvdrental; Step 2: Load the database file by creating a folder at your desired location(say, c:\users\sample_database\dvdrental.tar). Now open up command prompt and Navigate to the bin folder of the PostgreSQL installation folder as below: Use the pg_restore tool to load data into the dvdrental database that we had just created as using the command: pg_restore -U postgres -d dvdrental C:\users\sample_datbase\dvdrental.tar It would somewhat look like below: Now enter your database user Password and your sample database will be loaded. Now if you need to verify if the sample database is loaded, use the below command to get into the database in SQL shell: \c Now to list all the tables in the database, use the below command: \dt The result should look like below: saurabh1990aror akshaysingh98088 postgreSQL-administration postgreSQL-managing-database PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Function Returning A Table PostgreSQL - ARRAY_AGG() Function PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - ROW_NUMBER Function
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Sep, 2021" }, { "code": null, "e": 208, "s": 28, "text": "In this article we will look into the process of loading a PostgreSQL database into the PostgreSQL database server. Before moving forward we just need to make sure of two things: " }, { "code": null, "e": 265, "s": 208, "text": "PostgreSQL database server is installed on your system. " }, { "code": null, "e": 285, "s": 265, "text": "A sample database. " }, { "code": null, "e": 443, "s": 285, "text": "For the purpose of this article, we will be using a sample database which is DVD rental database. You can download the sample dvdrental database from here. " }, { "code": null, "e": 584, "s": 443, "text": "So, the DVD rental database that we will be using ahead in the article represents a DVD rental store. The objects in the database includes: " }, { "code": null, "e": 595, "s": 584, "text": "15 tables " }, { "code": null, "e": 606, "s": 595, "text": "1 trigger " }, { "code": null, "e": 619, "s": 606, "text": "8 functions " }, { "code": null, "e": 629, "s": 619, "text": "1 domain " }, { "code": null, "e": 638, "s": 629, "text": "7 views " }, { "code": null, "e": 652, "s": 638, "text": "13 sequences " }, { "code": null, "e": 687, "s": 652, "text": "ER Model of the sample Database: " }, { "code": null, "e": 786, "s": 687, "text": "Tables in the Sample Database: There are 15 tables in our sample database which are listed below: " }, { "code": null, "e": 1452, "s": 786, "text": "actor – stores actors data including first name and last name. film – stores films data such as title, release year, length, rating, etc film_actor – stores the relationships between films and actors. category – stores film’s categories data. film_category– stores the relationships between films and categories. store – contains the store data including manager staff and address. inventory – stores inventory data. rental – stores rental data. payment – stores customer’s payments. staff – stores staff data. customer – stores customers data. address – stores address data for staff and customers city – stores the city names. country – stores the country names. " }, { "code": null, "e": 1516, "s": 1452, "text": "actor – stores actors data including first name and last name. " }, { "code": null, "e": 1591, "s": 1516, "text": "film – stores films data such as title, release year, length, rating, etc " }, { "code": null, "e": 1656, "s": 1591, "text": "film_actor – stores the relationships between films and actors. " }, { "code": null, "e": 1699, "s": 1656, "text": "category – stores film’s categories data. " }, { "code": null, "e": 1770, "s": 1699, "text": "film_category– stores the relationships between films and categories. " }, { "code": null, "e": 1840, "s": 1770, "text": "store – contains the store data including manager staff and address. " }, { "code": null, "e": 1876, "s": 1840, "text": "inventory – stores inventory data. " }, { "code": null, "e": 1906, "s": 1876, "text": "rental – stores rental data. " }, { "code": null, "e": 1945, "s": 1906, "text": "payment – stores customer’s payments. " }, { "code": null, "e": 1973, "s": 1945, "text": "staff – stores staff data. " }, { "code": null, "e": 2008, "s": 1973, "text": "customer – stores customers data. " }, { "code": null, "e": 2063, "s": 2008, "text": "address – stores address data for staff and customers " }, { "code": null, "e": 2094, "s": 2063, "text": "city – stores the city names. " }, { "code": null, "e": 2131, "s": 2094, "text": "country – stores the country names. " }, { "code": null, "e": 2313, "s": 2131, "text": "So now we know everything about our sample DVD rental database, let us move on to loading the same database to the PostgreSQL database server. The steps to which are listed below: " }, { "code": null, "e": 2510, "s": 2313, "text": "Step 1: Create a DVD rental Database, by opening the SQL shell. Once you open up the shell, you will need to add the necessary credentials for your database, which would somewhat look like below: " }, { "code": null, "e": 2613, "s": 2510, "text": "Server [localhost]:\nDatabase [postgres]:\nPort [5432]:\nUsername [postgres]:\nPassword for user postgres:" }, { "code": null, "e": 2688, "s": 2613, "text": "Now using the CREATE DATABASE statement create a new database as follows: " }, { "code": null, "e": 2715, "s": 2688, "text": "CREATE DATABASE dvdrental;" }, { "code": null, "e": 2945, "s": 2715, "text": "Step 2: Load the database file by creating a folder at your desired location(say, c:\\users\\sample_database\\dvdrental.tar). Now open up command prompt and Navigate to the bin folder of the PostgreSQL installation folder as below: " }, { "code": null, "e": 3058, "s": 2945, "text": "Use the pg_restore tool to load data into the dvdrental database that we had just created as using the command: " }, { "code": null, "e": 3132, "s": 3058, "text": "pg_restore -U postgres -d dvdrental C:\\users\\sample_datbase\\dvdrental.tar" }, { "code": null, "e": 3168, "s": 3132, "text": "It would somewhat look like below: " }, { "code": null, "e": 3249, "s": 3168, "text": "Now enter your database user Password and your sample database will be loaded. " }, { "code": null, "e": 3372, "s": 3249, "text": "Now if you need to verify if the sample database is loaded, use the below command to get into the database in SQL shell: " }, { "code": null, "e": 3375, "s": 3372, "text": "\\c" }, { "code": null, "e": 3443, "s": 3375, "text": "Now to list all the tables in the database, use the below command: " }, { "code": null, "e": 3447, "s": 3443, "text": "\\dt" }, { "code": null, "e": 3484, "s": 3447, "text": "The result should look like below: " }, { "code": null, "e": 3502, "s": 3486, "text": "saurabh1990aror" }, { "code": null, "e": 3519, "s": 3502, "text": "akshaysingh98088" }, { "code": null, "e": 3545, "s": 3519, "text": "postgreSQL-administration" }, { "code": null, "e": 3574, "s": 3545, "text": "postgreSQL-managing-database" }, { "code": null, "e": 3585, "s": 3574, "text": "PostgreSQL" }, { "code": null, "e": 3683, "s": 3585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3710, "s": 3683, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 3742, "s": 3710, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 3765, "s": 3742, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 3803, "s": 3765, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 3843, "s": 3803, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 3877, "s": 3843, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 3932, "s": 3877, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 3956, "s": 3932, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 3980, "s": 3956, "text": "PostgreSQL - Copy Table" } ]
Implementation of Queue in Javascript
18 Feb, 2019 In This article, we would be implementing Queue data structure in javascript. A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic operations that is addition of elements at the end of the queue and removal of elements from the front of the queue. Like Stack, Queue is also a linear data structure. Note: Assuming a queue can grow dynamically we are not considering the overflow conditionNow let’s see an example of queue class using an array:- Example: // Queue classclass Queue{ // Array is used to implement a Queue constructor() { this.items = []; } // Functions to be implemented // enqueue(item) // dequeue() // front() // isEmpty() // printQueue()} As in the above definition we have created a skeleton of a queue class which contains a constructor in which we declare an array to implement queue. Hence, with the creation of an object of a queue class this constructor would be called automatically and the array will be declared Let’s implement each of these functions: enqueue() – Adds an element to the queue// enqueue functionenqueue(element){ // adding element to the queue this.items.push(element);}This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue.dequeue() – Removes an element from the queue// dequeue functiondequeue(){ // removing element from the queue // returns underflow when called // on empty queue if(this.isEmpty()) return "Underflow"; return this.items.shift();}This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue.front() – returns the front element of the queue// front functionfront(){ // returns the Front element of // the queue without removing it. if(this.isEmpty()) return "No elements in Queue"; return this.items[0];}This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue. enqueue() – Adds an element to the queue// enqueue functionenqueue(element){ // adding element to the queue this.items.push(element);}This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue. // enqueue functionenqueue(element){ // adding element to the queue this.items.push(element);} This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue. dequeue() – Removes an element from the queue// dequeue functiondequeue(){ // removing element from the queue // returns underflow when called // on empty queue if(this.isEmpty()) return "Underflow"; return this.items.shift();}This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue. // dequeue functiondequeue(){ // removing element from the queue // returns underflow when called // on empty queue if(this.isEmpty()) return "Underflow"; return this.items.shift();} This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue. front() – returns the front element of the queue// front functionfront(){ // returns the Front element of // the queue without removing it. if(this.isEmpty()) return "No elements in Queue"; return this.items[0];}This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue. // front functionfront(){ // returns the Front element of // the queue without removing it. if(this.isEmpty()) return "No elements in Queue"; return this.items[0];} This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue. Helper Methods Let’s declare some helper method which is quite useful while working with the queue. isEmpty() – Returns true if the queue is empty// isEmpty functionisEmpty(){ // return true if the queue is empty. return this.items.length == 0;}In this function we have used the length property of an array and if the array length is 0 then the queue is empty.printQueue()– Returns all the elements of an queue.// printQueue functionprintQueue(){ var str = ""; for(var i = 0; i < this.items.length; i++) str += this.items[i] +" "; return str;}In this method we concatenate all the elements of the queue in a string and return the string isEmpty() – Returns true if the queue is empty// isEmpty functionisEmpty(){ // return true if the queue is empty. return this.items.length == 0;}In this function we have used the length property of an array and if the array length is 0 then the queue is empty. // isEmpty functionisEmpty(){ // return true if the queue is empty. return this.items.length == 0;} In this function we have used the length property of an array and if the array length is 0 then the queue is empty. printQueue()– Returns all the elements of an queue.// printQueue functionprintQueue(){ var str = ""; for(var i = 0; i < this.items.length; i++) str += this.items[i] +" "; return str;}In this method we concatenate all the elements of the queue in a string and return the string // printQueue functionprintQueue(){ var str = ""; for(var i = 0; i < this.items.length; i++) str += this.items[i] +" "; return str;} In this method we concatenate all the elements of the queue in a string and return the string Note: Different helper method can be declared in Queue class as per the requirement. Implementation Now let’s use the queue class and its different method described above // creating object for queue classvar queue = new Queue(); // Testing dequeue and pop on an empty queue// returns Underflowconsole.log(queue.dequeue()); // returns trueconsole.log(queue.isEmpty()); // Adding elements to the queue// queue contains [10, 20, 30, 40, 50]queue.enqueue(10);queue.enqueue(20);queue.enqueue(30);queue.enqueue(40);queue.enqueue(50);queue.enqueue(60); // returns 10console.log(queue.front()); // removes 10 from the queue// queue contains [20, 30, 40, 50, 60]console.log(queue.dequeue()); // returns 20console.log(queue.front()); // removes 20// queue contains [30, 40, 50, 60]console.log(queue.dequeue()); // printing the elements of the queue// prints [30, 40, 50, 60]console.log(queue.printQueue()); Now once we are done with the implementation of Queue class we can use it different applications. Application : An Interesting Method to Generate Binary Numbers from 1 to n In this problem we generate different binary numbers from 1 to n. // function to generate binary numbersfunction generatePrintBinary(n){ // Create an empty queue of strings var q = new Queue(); // Enqueue the first binary number q.enqueue("1"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while(n-- > 0) { // print the front of queue var s1 = q.front(); q.dequeue(); console.log(s1); // Store s1 before changing it var s2 = s1; // Append "0" to s1 and enqueue it q.enqueue(s1 + "0"); // Append "1" to s2 and enqueue it. Note that s2 contains // the previous front q.enqueue(s2 + "1"); }} // calling the above function // prints [1 10 11 100 101]generatePrintBinary(5); This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. JavaScript-DS Articles JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Feb, 2019" }, { "code": null, "e": 384, "s": 52, "text": "In This article, we would be implementing Queue data structure in javascript. A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic operations that is addition of elements at the end of the queue and removal of elements from the front of the queue. Like Stack, Queue is also a linear data structure." }, { "code": null, "e": 530, "s": 384, "text": "Note: Assuming a queue can grow dynamically we are not considering the overflow conditionNow let’s see an example of queue class using an array:-" }, { "code": null, "e": 539, "s": 530, "text": "Example:" }, { "code": "// Queue classclass Queue{ // Array is used to implement a Queue constructor() { this.items = []; } // Functions to be implemented // enqueue(item) // dequeue() // front() // isEmpty() // printQueue()}", "e": 796, "s": 539, "text": null }, { "code": null, "e": 1078, "s": 796, "text": "As in the above definition we have created a skeleton of a queue class which contains a constructor in which we declare an array to implement queue. Hence, with the creation of an object of a queue class this constructor would be called automatically and the array will be declared" }, { "code": null, "e": 1119, "s": 1078, "text": "Let’s implement each of these functions:" }, { "code": null, "e": 2140, "s": 1119, "text": "enqueue() – Adds an element to the queue// enqueue functionenqueue(element){ // adding element to the queue this.items.push(element);}This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue.dequeue() – Removes an element from the queue// dequeue functiondequeue(){ // removing element from the queue // returns underflow when called // on empty queue if(this.isEmpty()) return \"Underflow\"; return this.items.shift();}This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue.front() – returns the front element of the queue// front functionfront(){ // returns the Front element of // the queue without removing it. if(this.isEmpty()) return \"No elements in Queue\"; return this.items[0];}This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue." }, { "code": null, "e": 2417, "s": 2140, "text": "enqueue() – Adds an element to the queue// enqueue functionenqueue(element){ // adding element to the queue this.items.push(element);}This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue." }, { "code": "// enqueue functionenqueue(element){ // adding element to the queue this.items.push(element);}", "e": 2522, "s": 2417, "text": null }, { "code": null, "e": 2655, "s": 2522, "text": "This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue." }, { "code": null, "e": 3041, "s": 2655, "text": "dequeue() – Removes an element from the queue// dequeue functiondequeue(){ // removing element from the queue // returns underflow when called // on empty queue if(this.isEmpty()) return \"Underflow\"; return this.items.shift();}This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue." }, { "code": "// dequeue functiondequeue(){ // removing element from the queue // returns underflow when called // on empty queue if(this.isEmpty()) return \"Underflow\"; return this.items.shift();}", "e": 3247, "s": 3041, "text": null }, { "code": null, "e": 3383, "s": 3247, "text": "This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue." }, { "code": null, "e": 3743, "s": 3383, "text": "front() – returns the front element of the queue// front functionfront(){ // returns the Front element of // the queue without removing it. if(this.isEmpty()) return \"No elements in Queue\"; return this.items[0];}This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue." }, { "code": "// front functionfront(){ // returns the Front element of // the queue without removing it. if(this.isEmpty()) return \"No elements in Queue\"; return this.items[0];}", "e": 3928, "s": 3743, "text": null }, { "code": null, "e": 4056, "s": 3928, "text": "This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue." }, { "code": null, "e": 4071, "s": 4056, "text": "Helper Methods" }, { "code": null, "e": 4156, "s": 4071, "text": "Let’s declare some helper method which is quite useful while working with the queue." }, { "code": null, "e": 4715, "s": 4156, "text": "isEmpty() – Returns true if the queue is empty// isEmpty functionisEmpty(){ // return true if the queue is empty. return this.items.length == 0;}In this function we have used the length property of an array and if the array length is 0 then the queue is empty.printQueue()– Returns all the elements of an queue.// printQueue functionprintQueue(){ var str = \"\"; for(var i = 0; i < this.items.length; i++) str += this.items[i] +\" \"; return str;}In this method we concatenate all the elements of the queue in a string and return the string" }, { "code": null, "e": 4982, "s": 4715, "text": "isEmpty() – Returns true if the queue is empty// isEmpty functionisEmpty(){ // return true if the queue is empty. return this.items.length == 0;}In this function we have used the length property of an array and if the array length is 0 then the queue is empty." }, { "code": "// isEmpty functionisEmpty(){ // return true if the queue is empty. return this.items.length == 0;}", "e": 5088, "s": 4982, "text": null }, { "code": null, "e": 5204, "s": 5088, "text": "In this function we have used the length property of an array and if the array length is 0 then the queue is empty." }, { "code": null, "e": 5497, "s": 5204, "text": "printQueue()– Returns all the elements of an queue.// printQueue functionprintQueue(){ var str = \"\"; for(var i = 0; i < this.items.length; i++) str += this.items[i] +\" \"; return str;}In this method we concatenate all the elements of the queue in a string and return the string" }, { "code": "// printQueue functionprintQueue(){ var str = \"\"; for(var i = 0; i < this.items.length; i++) str += this.items[i] +\" \"; return str;}", "e": 5646, "s": 5497, "text": null }, { "code": null, "e": 5740, "s": 5646, "text": "In this method we concatenate all the elements of the queue in a string and return the string" }, { "code": null, "e": 5825, "s": 5740, "text": "Note: Different helper method can be declared in Queue class as per the requirement." }, { "code": null, "e": 5840, "s": 5825, "text": "Implementation" }, { "code": null, "e": 5911, "s": 5840, "text": "Now let’s use the queue class and its different method described above" }, { "code": "// creating object for queue classvar queue = new Queue(); // Testing dequeue and pop on an empty queue// returns Underflowconsole.log(queue.dequeue()); // returns trueconsole.log(queue.isEmpty()); // Adding elements to the queue// queue contains [10, 20, 30, 40, 50]queue.enqueue(10);queue.enqueue(20);queue.enqueue(30);queue.enqueue(40);queue.enqueue(50);queue.enqueue(60); // returns 10console.log(queue.front()); // removes 10 from the queue// queue contains [20, 30, 40, 50, 60]console.log(queue.dequeue()); // returns 20console.log(queue.front()); // removes 20// queue contains [30, 40, 50, 60]console.log(queue.dequeue()); // printing the elements of the queue// prints [30, 40, 50, 60]console.log(queue.printQueue());", "e": 6660, "s": 5911, "text": null }, { "code": null, "e": 6758, "s": 6660, "text": "Now once we are done with the implementation of Queue class we can use it different applications." }, { "code": null, "e": 6833, "s": 6758, "text": "Application : An Interesting Method to Generate Binary Numbers from 1 to n" }, { "code": null, "e": 6899, "s": 6833, "text": "In this problem we generate different binary numbers from 1 to n." }, { "code": "// function to generate binary numbersfunction generatePrintBinary(n){ // Create an empty queue of strings var q = new Queue(); // Enqueue the first binary number q.enqueue(\"1\"); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while(n-- > 0) { // print the front of queue var s1 = q.front(); q.dequeue(); console.log(s1); // Store s1 before changing it var s2 = s1; // Append \"0\" to s1 and enqueue it q.enqueue(s1 + \"0\"); // Append \"1\" to s2 and enqueue it. Note that s2 contains // the previous front q.enqueue(s2 + \"1\"); }} // calling the above function // prints [1 10 11 100 101]generatePrintBinary(5);", "e": 7735, "s": 6899, "text": null }, { "code": null, "e": 8034, "s": 7735, "text": "This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8159, "s": 8034, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8173, "s": 8159, "text": "JavaScript-DS" }, { "code": null, "e": 8182, "s": 8173, "text": "Articles" }, { "code": null, "e": 8193, "s": 8182, "text": "JavaScript" } ]
Program to find the Area of a Parallelogram
20 Jun, 2022 Given the sides of a Parallelogram, task is calculate the area of a Parallelogram. Examples: Input: base = 30, height = 40 Output: 1200.000000 As Area of parallelogram = base * height, Therefore, Area = 30 * 40 = 1200.00 Approach: Area of parallelogram = base * height Below is the implementation of the above approach: C++ C Java Python C# PHP Javascript #include <iostream>using namespace std; // function to calculate the areafloat CalArea(float base, float height){ return (base * height);}// driver codeint main(){ float base, height, Area; base = 30; height = 40; // function calling Area = CalArea(base, height); // displaying the area cout << "Area of Parallelogram is :" << Area; return 0;} #include <stdio.h> // function to calculate the areafloat CalArea(float base, float height){ return (base * height);} // driver codeint main(){ float base, height, Area; base = 30; height = 40; // function calling Area = CalArea(base, height); // displaying the area printf("Area of Parallelogram is : %f\n", Area); return 0;} public class parallelogram { public static void main(String args[]) { int base = 30; int height = 40; // formula for calculating the area int area_parallelogram = base * height; // displayin g the area System.out.println("Area of the parallelogram = " + area_parallelogram); }} base = 30height = 40 # formula for finding the areaarea_parallelogram = base * height # displaying the outputprint("Area of the parallelogram = "+str(area_parallelogram)) using System;class parallelogram{public static void Main(){ int b_ase = 30; int height = 40; // formula for calculating the area int area_parallelogram = b_ase * height; // displayin g the area Console.WriteLine("Area of the parallelogram = " + area_parallelogram);}} // This code is contributed by vt_m <?php $base = 30; $height = 40; $area_parallelogram=$base*$height; echo "Area of the parallelogram = "; echo $area_parallelogram; ?> <script> let base = 30;let height = 40;let area_parallelogram=base*height;document.write( "Area of the parallelogram = ");document.write(area_parallelogram.toFixed(6)); // This code is contributed by Bobby </script> Area of Parallelogram is : 1200.000000 Time Complexity: O(1) Auxiliary Space: O(1) vt_m gottumukkalabobby ajaymakvana area-volume-programs Mathematical School Programming Mathematical 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 Minimum number of jumps to reach end Find minimum number of coins that make a given value Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 112, "s": 28, "text": "Given the sides of a Parallelogram, task is calculate the area of a Parallelogram. " }, { "code": null, "e": 124, "s": 112, "text": "Examples: " }, { "code": null, "e": 260, "s": 124, "text": "Input: base = 30, height = 40\nOutput: 1200.000000\n As Area of parallelogram = base * height,\n Therefore, Area = 30 * 40 = 1200.00" }, { "code": null, "e": 271, "s": 260, "text": "Approach: " }, { "code": null, "e": 309, "s": 271, "text": "Area of parallelogram = base * height" }, { "code": null, "e": 361, "s": 309, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 365, "s": 361, "text": "C++" }, { "code": null, "e": 367, "s": 365, "text": "C" }, { "code": null, "e": 372, "s": 367, "text": "Java" }, { "code": null, "e": 379, "s": 372, "text": "Python" }, { "code": null, "e": 382, "s": 379, "text": "C#" }, { "code": null, "e": 386, "s": 382, "text": "PHP" }, { "code": null, "e": 397, "s": 386, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // function to calculate the areafloat CalArea(float base, float height){ return (base * height);}// driver codeint main(){ float base, height, Area; base = 30; height = 40; // function calling Area = CalArea(base, height); // displaying the area cout << \"Area of Parallelogram is :\" << Area; return 0;}", "e": 769, "s": 397, "text": null }, { "code": "#include <stdio.h> // function to calculate the areafloat CalArea(float base, float height){ return (base * height);} // driver codeint main(){ float base, height, Area; base = 30; height = 40; // function calling Area = CalArea(base, height); // displaying the area printf(\"Area of Parallelogram is : %f\\n\", Area); return 0;}", "e": 1125, "s": 769, "text": null }, { "code": "public class parallelogram { public static void main(String args[]) { int base = 30; int height = 40; // formula for calculating the area int area_parallelogram = base * height; // displayin g the area System.out.println(\"Area of the parallelogram = \" + area_parallelogram); }}", "e": 1456, "s": 1125, "text": null }, { "code": "base = 30height = 40 # formula for finding the areaarea_parallelogram = base * height # displaying the outputprint(\"Area of the parallelogram = \"+str(area_parallelogram))", "e": 1628, "s": 1456, "text": null }, { "code": "using System;class parallelogram{public static void Main(){ int b_ase = 30; int height = 40; // formula for calculating the area int area_parallelogram = b_ase * height; // displayin g the area Console.WriteLine(\"Area of the parallelogram = \" + area_parallelogram);}} // This code is contributed by vt_m", "e": 1985, "s": 1628, "text": null }, { "code": "<?php $base = 30; $height = 40; $area_parallelogram=$base*$height; echo \"Area of the parallelogram = \"; echo $area_parallelogram; ?>", "e": 2137, "s": 1985, "text": null }, { "code": "<script> let base = 30;let height = 40;let area_parallelogram=base*height;document.write( \"Area of the parallelogram = \");document.write(area_parallelogram.toFixed(6)); // This code is contributed by Bobby </script>", "e": 2357, "s": 2137, "text": null }, { "code": null, "e": 2396, "s": 2357, "text": "Area of Parallelogram is : 1200.000000" }, { "code": null, "e": 2420, "s": 2398, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2442, "s": 2420, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2447, "s": 2442, "text": "vt_m" }, { "code": null, "e": 2465, "s": 2447, "text": "gottumukkalabobby" }, { "code": null, "e": 2477, "s": 2465, "text": "ajaymakvana" }, { "code": null, "e": 2498, "s": 2477, "text": "area-volume-programs" }, { "code": null, "e": 2511, "s": 2498, "text": "Mathematical" }, { "code": null, "e": 2530, "s": 2511, "text": "School Programming" }, { "code": null, "e": 2543, "s": 2530, "text": "Mathematical" }, { "code": null, "e": 2641, "s": 2543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2665, "s": 2641, "text": "Merge two sorted arrays" }, { "code": null, "e": 2686, "s": 2665, "text": "Operators in C / C++" }, { "code": null, "e": 2700, "s": 2686, "text": "Prime Numbers" }, { "code": null, "e": 2737, "s": 2700, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 2790, "s": 2737, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 2808, "s": 2790, "text": "Python Dictionary" }, { "code": null, "e": 2833, "s": 2808, "text": "Reverse a string in Java" }, { "code": null, "e": 2849, "s": 2833, "text": "Arrays in C/C++" }, { "code": null, "e": 2872, "s": 2849, "text": "Introduction To PYTHON" } ]
PostgreSQL – POSITION Function
01 Feb, 2021 The PostgreSQL POSITION() function returns the location of a substring in a string. Syntax: POSITION(substring in string) Let’s analyze the above syntax: The substring argument is the string that is to be located. The string argument represents the string for which the substring is to be searched. The POSITION() function returns the location of the searched substring in integer form that represents the location of the substring within the string. It returns zero (0) if no matching substring found. Example 1: The following statement returns the position of the ‘Tutorial’ in the string ‘GeeksForGeeks Tutorial’: SELECT POSITION('Tutorial' IN 'GeeksForGeeks Tutorial'); Output: Example 2: The POSITION() function returns the location of the first instance of the substring in the strings shown in the below example: SELECT POSITION('am' IN 'I am a geek'); Output: PostgreSQL-function PostgreSQL-String-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - IF Statement PostgreSQL - DROP TABLE PostgreSQL - For Loops PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Rename Table PostgreSQL - Joins PostgreSQL - Variables PostgreSQL - REPLACE Function PostgreSQL - Introduction to Stored Procedures PostgreSQL - CREATE SEQUENCE
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 112, "s": 28, "text": "The PostgreSQL POSITION() function returns the location of a substring in a string." }, { "code": null, "e": 150, "s": 112, "text": "Syntax: POSITION(substring in string)" }, { "code": null, "e": 182, "s": 150, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 242, "s": 182, "text": "The substring argument is the string that is to be located." }, { "code": null, "e": 327, "s": 242, "text": "The string argument represents the string for which the substring is to be searched." }, { "code": null, "e": 531, "s": 327, "text": "The POSITION() function returns the location of the searched substring in integer form that represents the location of the substring within the string. It returns zero (0) if no matching substring found." }, { "code": null, "e": 542, "s": 531, "text": "Example 1:" }, { "code": null, "e": 645, "s": 542, "text": "The following statement returns the position of the ‘Tutorial’ in the string ‘GeeksForGeeks Tutorial’:" }, { "code": null, "e": 702, "s": 645, "text": "SELECT POSITION('Tutorial' IN 'GeeksForGeeks Tutorial');" }, { "code": null, "e": 710, "s": 702, "text": "Output:" }, { "code": null, "e": 721, "s": 710, "text": "Example 2:" }, { "code": null, "e": 848, "s": 721, "text": "The POSITION() function returns the location of the first instance of the substring in the strings shown in the below example:" }, { "code": null, "e": 888, "s": 848, "text": "SELECT POSITION('am' IN 'I am a geek');" }, { "code": null, "e": 896, "s": 888, "text": "Output:" }, { "code": null, "e": 916, "s": 896, "text": "PostgreSQL-function" }, { "code": null, "e": 943, "s": 916, "text": "PostgreSQL-String-function" }, { "code": null, "e": 954, "s": 943, "text": "PostgreSQL" }, { "code": null, "e": 1052, "s": 954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1078, "s": 1052, "text": "PostgreSQL - IF Statement" }, { "code": null, "e": 1102, "s": 1078, "text": "PostgreSQL - DROP TABLE" }, { "code": null, "e": 1125, "s": 1102, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 1163, "s": 1125, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 1189, "s": 1163, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 1208, "s": 1189, "text": "PostgreSQL - Joins" }, { "code": null, "e": 1231, "s": 1208, "text": "PostgreSQL - Variables" }, { "code": null, "e": 1261, "s": 1231, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 1308, "s": 1261, "text": "PostgreSQL - Introduction to Stored Procedures" } ]
Recursive program to replace all occurrences of pi with 3.14 in a given string
17 Dec, 2021 Given string str of size N. The task is to write a recursive function to replace all occurrences of pi with 3.14 in the given string and print the modified string. Examples: Input : str = “pippppiiiipi” Output : 3.14ppp3.14iii3.14 Input : str = “pip” Output : 3.14p Input : str = “xpix” Output : x3.14x We have discussed an iterative function hereApproach : If there is only one character in a string or the string is empty break the recursive call Else keep the first character of the string with yourself and pass the rest of the string to recursion. If the first character is not ‘p’ then just put that character in front of the answer which came from recursionElse if the first character is ‘p’ and the first character of the part passed to recursion is ‘i’ then replace “pi” with “3.14” If the first character is not ‘p’ then just put that character in front of the answer which came from recursion Else if the first character is ‘p’ and the first character of the part passed to recursion is ‘i’ then replace “pi” with “3.14” Below is the implementation of the above approach: C++ Java Python3 C# Javascript // A recursive C++ program to replace// all pi in a given string with 3.14#include <bits/stdc++.h>using namespace std; // Recursive Function to replace all// occurrences of pi in a given// with 3.14void replacePiHelper(char str[], int start){ // Base condition // if the string is empty // or of length one if (str[start] == '\0' || str[start + 1] == '\0') { return; } // Getting the answer from // recursion for the smaller // problem replacePiHelper(str, start + 1); // Small calculation part // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace // "pi" with "3.14" if (str[start] == 'p' && str[start + 1] == 'i') { // Shifting the characters to // right side to put 3.14 in // the character array for (int i = strlen(str); i >= start + 2; i--) { str[i + 2] = str[i]; } // Replacing with "3.14" str[start] = '3'; str[start + 1] = '.'; str[start + 2] = '1'; str[start + 3] = '4'; }} // Function to replace pi with 3.14void replacePi(char str[]){ replacePiHelper(str, 0);} // Driver codeint main(){ char str[] = "pippppiiiipi"; // Function call replacePi(str); cout << str; return 0;} // A recursive Java program to replace// all pi in a given string with 3.14 class GFG { // Recursive Function to replace all // occurrences of pi in a given // with 3.14 public String replacePi(String str) { // base condition // if the string is empty // or of length one if (str.length() <= 1) { return str; } // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace //"pi" with "3.14" if (str.charAt(0) == 'p' && str.length() >= 2 && str.charAt(1) == 'i') { return "3.14" + replacePi(str.substring(2, str.length())); } // if the first character is not 'p' // then just put that character in // front of the answer which came // from recursion return str.charAt(0) + replacePi(str.substring(1, str.length())); } // Driver Code public static void main(String args[]) { GFG g = new GFG(); String str = "pippppiiiipi"; System.out.println(g.replacePi(str)); }} # A recursive Python3 program to replace# all pi in a given string with 3.14 # Recursive Function to replace all# occurrences of pi in a given# with 3.14def replacePieHelper(string, start): # Base condition # if the string is empty # or of length one if len(string) < 2 or start == len(string): return string # Getting the answer from # recursion for the smaller # problem replacePieHelper(string, start + 1) # Small calculation part # if the first character is 'p' # and the first character of the part # passed to recursion is 'i' then replace # "pi" with "3.14" if(string[start] == 'p' and string[start + 1] == 'i'): # Replacing with "3.14" string[start:start + 2] = ['3', '.', '1', '4'] # Function to replace pi with 3.14def replacePi(string): replacePieHelper(string, 0) # Driver Codeif __name__ == "__main__": string = "pippppiiiipi" string = list(string) # Function call replacePi(string) string = ''.join(string) print(string) # This code is contributed by# sanjeev2552 // A recursive C# program to replace// all pi in a given string with 3.14 using System;class gfg { // Recursive Function to replace all // occurrences of pi in a given // with 3.14 public String replacePi(String str) { // base condition // if the string is empty // or of length one if (str.Length <= 1) { return str; } // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace //"pi" with "3.14" if (str[0] == 'p' && str.Length >= 2 && str[1] == 'i') { return "3.14" + replacePi(str.Substring(2, str.Length - 2)); } // if the first character is not 'p' // then just put that character in // front of the answer which came // from recursion return str[0] + replacePi(str.Substring(1, str.Length - 1)); }} // Driver Codeclass geek { public static int Main() { gfg g = new gfg(); string input = "pippppiiiipi"; Console.WriteLine(g.replacePi(input)); return 0; }} <script> // A recursive JavaScript program to replace // all pi in a given string with 3.14 // Recursive Function to replace all // occurrences of pi in a given // with 3.14 function replacePi(str) { // base condition // if the string is empty // or of length one if (str.length <= 1) { return str; } // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace //"pi" with "3.14" if (str[0] === "p" && str.length >= 2 && str[1] === "i") { return "3.14" + replacePi(str.substring(2, str.length)); } // if the first character is not 'p' // then just put that character in // front of the answer which came // from recursion return str[0] + replacePi(str.substring(1, str.length)); } // Driver Code var input = "pippppiiiipi"; document.write(replacePi(input)); </script> 3.14ppp3.14iii3.14 Another Approach: A simple recursive approach to replace all pi in a given function with “3.14”. Firstly function is declared we don’t need any helper function. Base case if the string is empty or the length of the string is 1 return the string. If the 0th and 1st element of the string is p and we have to handle them for the rest we have to call recursion it will give the result. If not then we have to call recursion from 1st to all elements then add recursion result to 1st element and return it. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // A simple recursive approach// to replace all pi in a given// function with "3.14". Firstly// function is declared we don't// need any helper function one// function is enoughstring replacePi(string s){ // Base case if s is empty // or length of s is 1 // return the s if (s.length() == 0 || s.length() == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s[0] == 'p' && s[1] == 'i') { // Smalloutput is a variable // used to store recursion result string smallOutput = replacePi(s.substr(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return "3.14" + smallOutput; } else { // If 1st & 2nd element aren't "p" & "i", then keep // 1st index as it is & call recursion for rest of // the string. return s[0] + replacePi(s.substr(1)); }} // Driver codeint main(){ string s = "pipppiiipi"; // Function call string result = replacePi(s); cout << result << endl; return 0;} // This code is contributed by divyeshrabadiya07 // Java program for above approachclass GFG { // A simple recursive approach // to replace all pi in a given // function with "3.14". Firstly // function is declared we don't // need any helper function one // function is enough public static String replacePi(String s) { // Base case if s is empty // or length of s is 1 // return the s if (s.length() == 0 || s.length() == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s.charAt(0) == 'p' && s.charAt(1) == 'i') { // Smalloutput is a variable // used to store recursion result String smallOutput = replacePi(s.substring(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return "3.14" + smallOutput; } else { // If not then we have to call // recursion from 1st to all elements // then add recursion result to // 1st element and return it String smallOutput = replacePi(s.substring(1)); return s.charAt(0) + smallOutput; } } // Driver code public static void main(String[] args) { String s = "pipppiiipi"; // Function call String result = replacePi(s); System.out.println(result); }} // This code is contributed by divyesh072019 # Python program for above approach # A simple recursive approach# to replace all# pi in a given function with "3.14"# Firstly function is declared we don't# need any helper function one# function is enough def replacePi(string): # Base case if string is empty # or length of string is 1 # return the string if len(string) == 0 or len(string) == 1: return string # If the 0th and 1st element # of string are p # and i we have to handle them # for rest we have to call # recursion it will give the result if string[0] == 'p' and string[1] == 'i': # Smalloutput is a variable # used to store recursion result smallOutput = replacePi(string[2:]) # And we have to add the recursion # result with the first part we # handled and return the answer return "3.14" + smallOutput else: # If not then we have to call # recursion from 1st to all elements # then add recursion result to # 1st element and return it smallOutput = replacePi(string[1:]) return string[0] + smallOutput # Driver codeif __name__ == "__main__": string = "pipppiiipi" # Function call result = replacePi(string) print result // C# program for above approachusing System;using System.Collections;using System.Collections.Generic;using System.Linq; class GFG { // A simple recursive approach // to replace all pi in a given // function with "3.14". Firstly // function is declared we don't // need any helper function one // function is enough static string replacePi(string s) { // Base case if s is empty // or length of s is 1 // return the s if (s.Length == 0 || s.Length == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s[0] == 'p' && s[1] == 'i') { // Smalloutput is a variable // used to store recursion result string smallOutput = replacePi(s.Substring(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return "3.14" + smallOutput; } else { // If not then we have to call // recursion from 1st to all elements // then add recursion result to // 1st element and return it string smallOutput = replacePi(s.Substring(1)); return s[0] + smallOutput; } } // Driver Code public static void Main(string[] args) { string s = "pipppiiipi"; // Function call string result = replacePi(s); Console.Write(result); }} // This code is contributed by rutvik_56 <script> // JavaScript program for above approach // A simple recursive approach// to replace all pi in a given// function with "3.14". Firstly// function is declared we don't// need any helper function one// function is enoughfunction replacePi(s){ // Base case if s is empty // or length of s is 1 // return the s if (s.length == 0 || s.length == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s[0] == 'p' && s[1] == 'i') { // Smalloutput is a variable // used to store recursion result let smallOutput = replacePi(s.substr(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return "3.14" + smallOutput; } else { // If 1st & 2nd element aren't "p" & "i", then keep // 1st index as it is & call recursion for rest of // the string. return s[0] + replacePi(s.substr(1)); }} // Driver code let s = "pipppiiipi"; // Function call let result = replacePi(s); document.write(result); </script> Output: 3.14pp3.14ii3.14 sanjeev2552 _sharma_ rutvik_56 divyeshrabadiya07 divyesh072019 shrey3108 pranav21 niteshneo rdtank vaibhavrabadiya3 clintra sumitgumber28 Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all subsequences of a string Recursive Practice Problems with Solutions Print all possible combinations of r elements in a given array of size n Reverse a stack using recursion Write a program to reverse an array or string Reverse a string in Java C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack Longest Common Subsequence | DP-4
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2021" }, { "code": null, "e": 216, "s": 52, "text": "Given string str of size N. The task is to write a recursive function to replace all occurrences of pi with 3.14 in the given string and print the modified string." }, { "code": null, "e": 227, "s": 216, "text": "Examples: " }, { "code": null, "e": 284, "s": 227, "text": "Input : str = “pippppiiiipi” Output : 3.14ppp3.14iii3.14" }, { "code": null, "e": 319, "s": 284, "text": "Input : str = “pip” Output : 3.14p" }, { "code": null, "e": 356, "s": 319, "text": "Input : str = “xpix” Output : x3.14x" }, { "code": null, "e": 413, "s": 356, "text": "We have discussed an iterative function hereApproach : " }, { "code": null, "e": 504, "s": 413, "text": "If there is only one character in a string or the string is empty break the recursive call" }, { "code": null, "e": 847, "s": 504, "text": "Else keep the first character of the string with yourself and pass the rest of the string to recursion. If the first character is not ‘p’ then just put that character in front of the answer which came from recursionElse if the first character is ‘p’ and the first character of the part passed to recursion is ‘i’ then replace “pi” with “3.14”" }, { "code": null, "e": 959, "s": 847, "text": "If the first character is not ‘p’ then just put that character in front of the answer which came from recursion" }, { "code": null, "e": 1087, "s": 959, "text": "Else if the first character is ‘p’ and the first character of the part passed to recursion is ‘i’ then replace “pi” with “3.14”" }, { "code": null, "e": 1138, "s": 1087, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1142, "s": 1138, "text": "C++" }, { "code": null, "e": 1147, "s": 1142, "text": "Java" }, { "code": null, "e": 1155, "s": 1147, "text": "Python3" }, { "code": null, "e": 1158, "s": 1155, "text": "C#" }, { "code": null, "e": 1169, "s": 1158, "text": "Javascript" }, { "code": "// A recursive C++ program to replace// all pi in a given string with 3.14#include <bits/stdc++.h>using namespace std; // Recursive Function to replace all// occurrences of pi in a given// with 3.14void replacePiHelper(char str[], int start){ // Base condition // if the string is empty // or of length one if (str[start] == '\\0' || str[start + 1] == '\\0') { return; } // Getting the answer from // recursion for the smaller // problem replacePiHelper(str, start + 1); // Small calculation part // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace // \"pi\" with \"3.14\" if (str[start] == 'p' && str[start + 1] == 'i') { // Shifting the characters to // right side to put 3.14 in // the character array for (int i = strlen(str); i >= start + 2; i--) { str[i + 2] = str[i]; } // Replacing with \"3.14\" str[start] = '3'; str[start + 1] = '.'; str[start + 2] = '1'; str[start + 3] = '4'; }} // Function to replace pi with 3.14void replacePi(char str[]){ replacePiHelper(str, 0);} // Driver codeint main(){ char str[] = \"pippppiiiipi\"; // Function call replacePi(str); cout << str; return 0;}", "e": 2478, "s": 1169, "text": null }, { "code": "// A recursive Java program to replace// all pi in a given string with 3.14 class GFG { // Recursive Function to replace all // occurrences of pi in a given // with 3.14 public String replacePi(String str) { // base condition // if the string is empty // or of length one if (str.length() <= 1) { return str; } // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace //\"pi\" with \"3.14\" if (str.charAt(0) == 'p' && str.length() >= 2 && str.charAt(1) == 'i') { return \"3.14\" + replacePi(str.substring(2, str.length())); } // if the first character is not 'p' // then just put that character in // front of the answer which came // from recursion return str.charAt(0) + replacePi(str.substring(1, str.length())); } // Driver Code public static void main(String args[]) { GFG g = new GFG(); String str = \"pippppiiiipi\"; System.out.println(g.replacePi(str)); }}", "e": 3594, "s": 2478, "text": null }, { "code": "# A recursive Python3 program to replace# all pi in a given string with 3.14 # Recursive Function to replace all# occurrences of pi in a given# with 3.14def replacePieHelper(string, start): # Base condition # if the string is empty # or of length one if len(string) < 2 or start == len(string): return string # Getting the answer from # recursion for the smaller # problem replacePieHelper(string, start + 1) # Small calculation part # if the first character is 'p' # and the first character of the part # passed to recursion is 'i' then replace # \"pi\" with \"3.14\" if(string[start] == 'p' and string[start + 1] == 'i'): # Replacing with \"3.14\" string[start:start + 2] = ['3', '.', '1', '4'] # Function to replace pi with 3.14def replacePi(string): replacePieHelper(string, 0) # Driver Codeif __name__ == \"__main__\": string = \"pippppiiiipi\" string = list(string) # Function call replacePi(string) string = ''.join(string) print(string) # This code is contributed by# sanjeev2552", "e": 4669, "s": 3594, "text": null }, { "code": "// A recursive C# program to replace// all pi in a given string with 3.14 using System;class gfg { // Recursive Function to replace all // occurrences of pi in a given // with 3.14 public String replacePi(String str) { // base condition // if the string is empty // or of length one if (str.Length <= 1) { return str; } // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace //\"pi\" with \"3.14\" if (str[0] == 'p' && str.Length >= 2 && str[1] == 'i') { return \"3.14\" + replacePi(str.Substring(2, str.Length - 2)); } // if the first character is not 'p' // then just put that character in // front of the answer which came // from recursion return str[0] + replacePi(str.Substring(1, str.Length - 1)); }} // Driver Codeclass geek { public static int Main() { gfg g = new gfg(); string input = \"pippppiiiipi\"; Console.WriteLine(g.replacePi(input)); return 0; }}", "e": 5789, "s": 4669, "text": null }, { "code": "<script> // A recursive JavaScript program to replace // all pi in a given string with 3.14 // Recursive Function to replace all // occurrences of pi in a given // with 3.14 function replacePi(str) { // base condition // if the string is empty // or of length one if (str.length <= 1) { return str; } // if the first character is 'p' // and the first character of the part // passed to recursion is 'i' then replace //\"pi\" with \"3.14\" if (str[0] === \"p\" && str.length >= 2 && str[1] === \"i\") { return \"3.14\" + replacePi(str.substring(2, str.length)); } // if the first character is not 'p' // then just put that character in // front of the answer which came // from recursion return str[0] + replacePi(str.substring(1, str.length)); } // Driver Code var input = \"pippppiiiipi\"; document.write(replacePi(input)); </script>", "e": 6809, "s": 5789, "text": null }, { "code": null, "e": 6828, "s": 6809, "text": "3.14ppp3.14iii3.14" }, { "code": null, "e": 6846, "s": 6828, "text": "Another Approach:" }, { "code": null, "e": 6989, "s": 6846, "text": "A simple recursive approach to replace all pi in a given function with “3.14”. Firstly function is declared we don’t need any helper function." }, { "code": null, "e": 7074, "s": 6989, "text": "Base case if the string is empty or the length of the string is 1 return the string." }, { "code": null, "e": 7211, "s": 7074, "text": "If the 0th and 1st element of the string is p and we have to handle them for the rest we have to call recursion it will give the result." }, { "code": null, "e": 7330, "s": 7211, "text": "If not then we have to call recursion from 1st to all elements then add recursion result to 1st element and return it." }, { "code": null, "e": 7381, "s": 7330, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7385, "s": 7381, "text": "C++" }, { "code": null, "e": 7390, "s": 7385, "text": "Java" }, { "code": null, "e": 7397, "s": 7390, "text": "Python" }, { "code": null, "e": 7400, "s": 7397, "text": "C#" }, { "code": null, "e": 7411, "s": 7400, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // A simple recursive approach// to replace all pi in a given// function with \"3.14\". Firstly// function is declared we don't// need any helper function one// function is enoughstring replacePi(string s){ // Base case if s is empty // or length of s is 1 // return the s if (s.length() == 0 || s.length() == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s[0] == 'p' && s[1] == 'i') { // Smalloutput is a variable // used to store recursion result string smallOutput = replacePi(s.substr(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return \"3.14\" + smallOutput; } else { // If 1st & 2nd element aren't \"p\" & \"i\", then keep // 1st index as it is & call recursion for rest of // the string. return s[0] + replacePi(s.substr(1)); }} // Driver codeint main(){ string s = \"pipppiiipi\"; // Function call string result = replacePi(s); cout << result << endl; return 0;} // This code is contributed by divyeshrabadiya07", "e": 8719, "s": 7411, "text": null }, { "code": "// Java program for above approachclass GFG { // A simple recursive approach // to replace all pi in a given // function with \"3.14\". Firstly // function is declared we don't // need any helper function one // function is enough public static String replacePi(String s) { // Base case if s is empty // or length of s is 1 // return the s if (s.length() == 0 || s.length() == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s.charAt(0) == 'p' && s.charAt(1) == 'i') { // Smalloutput is a variable // used to store recursion result String smallOutput = replacePi(s.substring(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return \"3.14\" + smallOutput; } else { // If not then we have to call // recursion from 1st to all elements // then add recursion result to // 1st element and return it String smallOutput = replacePi(s.substring(1)); return s.charAt(0) + smallOutput; } } // Driver code public static void main(String[] args) { String s = \"pipppiiipi\"; // Function call String result = replacePi(s); System.out.println(result); }} // This code is contributed by divyesh072019", "e": 10287, "s": 8719, "text": null }, { "code": "# Python program for above approach # A simple recursive approach# to replace all# pi in a given function with \"3.14\"# Firstly function is declared we don't# need any helper function one# function is enough def replacePi(string): # Base case if string is empty # or length of string is 1 # return the string if len(string) == 0 or len(string) == 1: return string # If the 0th and 1st element # of string are p # and i we have to handle them # for rest we have to call # recursion it will give the result if string[0] == 'p' and string[1] == 'i': # Smalloutput is a variable # used to store recursion result smallOutput = replacePi(string[2:]) # And we have to add the recursion # result with the first part we # handled and return the answer return \"3.14\" + smallOutput else: # If not then we have to call # recursion from 1st to all elements # then add recursion result to # 1st element and return it smallOutput = replacePi(string[1:]) return string[0] + smallOutput # Driver codeif __name__ == \"__main__\": string = \"pipppiiipi\" # Function call result = replacePi(string) print result", "e": 11586, "s": 10287, "text": null }, { "code": "// C# program for above approachusing System;using System.Collections;using System.Collections.Generic;using System.Linq; class GFG { // A simple recursive approach // to replace all pi in a given // function with \"3.14\". Firstly // function is declared we don't // need any helper function one // function is enough static string replacePi(string s) { // Base case if s is empty // or length of s is 1 // return the s if (s.Length == 0 || s.Length == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s[0] == 'p' && s[1] == 'i') { // Smalloutput is a variable // used to store recursion result string smallOutput = replacePi(s.Substring(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return \"3.14\" + smallOutput; } else { // If not then we have to call // recursion from 1st to all elements // then add recursion result to // 1st element and return it string smallOutput = replacePi(s.Substring(1)); return s[0] + smallOutput; } } // Driver Code public static void Main(string[] args) { string s = \"pipppiiipi\"; // Function call string result = replacePi(s); Console.Write(result); }} // This code is contributed by rutvik_56", "e": 13201, "s": 11586, "text": null }, { "code": "<script> // JavaScript program for above approach // A simple recursive approach// to replace all pi in a given// function with \"3.14\". Firstly// function is declared we don't// need any helper function one// function is enoughfunction replacePi(s){ // Base case if s is empty // or length of s is 1 // return the s if (s.length == 0 || s.length == 1) return s; // If the 0th and 1st element // of s are p and i we have to // handle them for rest we have // to call recursion it will // give the result if (s[0] == 'p' && s[1] == 'i') { // Smalloutput is a variable // used to store recursion result let smallOutput = replacePi(s.substr(2)); // And we have to add the recursion // result with the first part we // handled and return the answer return \"3.14\" + smallOutput; } else { // If 1st & 2nd element aren't \"p\" & \"i\", then keep // 1st index as it is & call recursion for rest of // the string. return s[0] + replacePi(s.substr(1)); }} // Driver code let s = \"pipppiiipi\"; // Function call let result = replacePi(s); document.write(result); </script>", "e": 14400, "s": 13201, "text": null }, { "code": null, "e": 14408, "s": 14400, "text": "Output:" }, { "code": null, "e": 14425, "s": 14408, "text": "3.14pp3.14ii3.14" }, { "code": null, "e": 14437, "s": 14425, "text": "sanjeev2552" }, { "code": null, "e": 14446, "s": 14437, "text": "_sharma_" }, { "code": null, "e": 14456, "s": 14446, "text": "rutvik_56" }, { "code": null, "e": 14474, "s": 14456, "text": "divyeshrabadiya07" }, { "code": null, "e": 14488, "s": 14474, "text": "divyesh072019" }, { "code": null, "e": 14498, "s": 14488, "text": "shrey3108" }, { "code": null, "e": 14507, "s": 14498, "text": "pranav21" }, { "code": null, "e": 14517, "s": 14507, "text": "niteshneo" }, { "code": null, "e": 14524, "s": 14517, "text": "rdtank" }, { "code": null, "e": 14541, "s": 14524, "text": "vaibhavrabadiya3" }, { "code": null, "e": 14549, "s": 14541, "text": "clintra" }, { "code": null, "e": 14563, "s": 14549, "text": "sumitgumber28" }, { "code": null, "e": 14573, "s": 14563, "text": "Recursion" }, { "code": null, "e": 14581, "s": 14573, "text": "Strings" }, { "code": null, "e": 14589, "s": 14581, "text": "Strings" }, { "code": null, "e": 14599, "s": 14589, "text": "Recursion" }, { "code": null, "e": 14697, "s": 14599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14725, "s": 14697, "text": "Backtracking | Introduction" }, { "code": null, "e": 14760, "s": 14725, "text": "Print all subsequences of a string" }, { "code": null, "e": 14803, "s": 14760, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 14876, "s": 14803, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 14908, "s": 14876, "text": "Reverse a stack using recursion" }, { "code": null, "e": 14954, "s": 14908, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 14979, "s": 14954, "text": "Reverse a string in Java" }, { "code": null, "e": 14994, "s": 14979, "text": "C++ Data Types" }, { "code": null, "e": 15069, "s": 14994, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Delete Duplicates in MS SQL Server
08 Sep, 2020 Duplicate values in any table might be due to the poor table design or unwanted data from other sources. To delete the duplicate data from the table in SQL Server, follow the below steps – Find duplicate rows.Use DELETE statement to remove the duplicate rows. Find duplicate rows. Use DELETE statement to remove the duplicate rows. Let us create a table named Geek – CREATE TABLE Geek( Name NVARCHAR(100) NOT NULL, Email NVARCHAR(255) NOT NULL, City NVARCHAR(100) NOT NULL); Let us insert some values into the table Geek – INSERT INTO Geek (Name, Email, City) VALUES ('Nisha', 'nisha@gfg.com', 'Delhi'), ('Megha', 'megha@gfg.com', 'Noida'), ('Khushi', 'khushi@gfg.com', 'Jaipur'), ('Khushi', 'khushi@gfg.com', 'Jaipur'), ('Khushi', 'khushi@gfg.com', 'Jaipur'), ('Hina', 'hina@gfg.com', 'Kanpur'), ('Hina', 'hina@gfg.com', 'Kanpur'), ('Misha', 'misha@gfg.com', 'Gurugram'), ('Misha', 'misha@gfg.com', 'Gurugram'), ('Neha', 'neha@gfg.com', 'Pilani'); Let us display the contents of table Geek – SELECT * FROM Geek; Table – Geek SQL Server query to delete duplicate records from the table Geek : WITH CTE AS ( SELECT Name, Email, City ROW_NUMBER() OVER ( PARTITION BY Name, Email. City ORDER BY Name, Email. City ) row_num FROM Geek ) DELETE FROM CTE WHERE row_num > 1; Output –(5 rows affected) SELECT * FROM Geek; Table – Geek DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Window functions in SQL SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2020" }, { "code": null, "e": 217, "s": 28, "text": "Duplicate values in any table might be due to the poor table design or unwanted data from other sources. To delete the duplicate data from the table in SQL Server, follow the below steps –" }, { "code": null, "e": 288, "s": 217, "text": "Find duplicate rows.Use DELETE statement to remove the duplicate rows." }, { "code": null, "e": 309, "s": 288, "text": "Find duplicate rows." }, { "code": null, "e": 360, "s": 309, "text": "Use DELETE statement to remove the duplicate rows." }, { "code": null, "e": 395, "s": 360, "text": "Let us create a table named Geek –" }, { "code": null, "e": 503, "s": 395, "text": "CREATE TABLE Geek(\nName NVARCHAR(100) NOT NULL,\nEmail NVARCHAR(255) NOT NULL,\nCity NVARCHAR(100) NOT NULL);" }, { "code": null, "e": 551, "s": 503, "text": "Let us insert some values into the table Geek –" }, { "code": null, "e": 977, "s": 551, "text": "INSERT INTO Geek (Name, Email, City) VALUES\n('Nisha', 'nisha@gfg.com', 'Delhi'),\n('Megha', 'megha@gfg.com', 'Noida'),\n('Khushi', 'khushi@gfg.com', 'Jaipur'),\n('Khushi', 'khushi@gfg.com', 'Jaipur'),\n('Khushi', 'khushi@gfg.com', 'Jaipur'),\n('Hina', 'hina@gfg.com', 'Kanpur'),\n('Hina', 'hina@gfg.com', 'Kanpur'),\n('Misha', 'misha@gfg.com', 'Gurugram'),\n('Misha', 'misha@gfg.com', 'Gurugram'),\n('Neha', 'neha@gfg.com', 'Pilani');" }, { "code": null, "e": 1021, "s": 977, "text": "Let us display the contents of table Geek –" }, { "code": null, "e": 1042, "s": 1021, "text": "SELECT * \nFROM Geek;" }, { "code": null, "e": 1055, "s": 1042, "text": "Table – Geek" }, { "code": null, "e": 1122, "s": 1055, "text": "SQL Server query to delete duplicate records from the table Geek :" }, { "code": null, "e": 1296, "s": 1122, "text": "WITH CTE AS (\nSELECT Name, Email, City\nROW_NUMBER() OVER (\nPARTITION BY Name, Email. City\nORDER BY Name, Email. City\n) row_num\nFROM Geek\n)\nDELETE FROM CTE\nWHERE row_num > 1;" }, { "code": null, "e": 1322, "s": 1296, "text": "Output –(5 rows affected)" }, { "code": null, "e": 1343, "s": 1322, "text": "SELECT * \nFROM Geek;" }, { "code": null, "e": 1356, "s": 1343, "text": "Table – Geek" }, { "code": null, "e": 1365, "s": 1356, "text": "DBMS-SQL" }, { "code": null, "e": 1376, "s": 1365, "text": "SQL-Server" }, { "code": null, "e": 1380, "s": 1376, "text": "SQL" }, { "code": null, "e": 1384, "s": 1380, "text": "SQL" }, { "code": null, "e": 1482, "s": 1384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1493, "s": 1482, "text": "CTE in SQL" }, { "code": null, "e": 1559, "s": 1493, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1583, "s": 1559, "text": "SQL Interview Questions" }, { "code": null, "e": 1595, "s": 1583, "text": "SQL | Views" }, { "code": null, "e": 1640, "s": 1595, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1672, "s": 1640, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1696, "s": 1672, "text": "Window functions in SQL" }, { "code": null, "e": 1711, "s": 1696, "text": "SQL | GROUP BY" }, { "code": null, "e": 1750, "s": 1711, "text": "Difference between DDL and DML in DBMS" } ]
Pangram Strings | Practice | GeeksforGeeks
Check if the given string S is a Panagram or not. A pangram is a sentence containing every letter in the English Alphabet. Example 1: Input: S = "Pack mY box witH fIve dozen liquor jugs" Output: 1 Explanation: Given string contains all English Alphabets. Example 2: Input: S = "geeksFORgeeks" Output: 0 Explanation: Given string does not contain all English Alphabets. Your Task: You don't need to read input or print anything. Your task is to complete the function isPanagram() which takes the string as inputs and returns 1 if the given string is panagram, otherwise 0. Expected Time Complexity: O(N) Expected Auxiliary Space: O(constant) Constraints: 1 ≤ |S| ≤ 105 0 himpat2021 month ago why this is giving runtime error?int isPanagram(string str){ vector<int> v(27,0); int n =str.size(); if(n<26) { return 0; } for(int i=0;i<n;i++) { if(int(str[i])!=32){ char c = toupper(str[i]); int a_val = int(c); ++v[65-a_val]; } } for(int i=1;i<27;i++) { if(v[i]==0 ) { return 0; } } return 1;} 0 dipeshmakwane2 months ago Easy C++ Solution int isPanagram(string S){ // Your code goes here int count[256]={0}; for(int i=0;i<S.length();i++){ S[i]=tolower(S[i]); count[S[i]]++; } for(int i=97;i<=122;i++){ if(count[i]==0){ return 0; break; } } return 1;} 0 prasadchaskar2 months ago Python Solution: def isPanagram(self, S): # code here alpha = [] for i in range(97,123): alpha.append(chr(i)) l = set() for i in S: if i.isalpha(): l.add(i.lower()) l1 = list(l) l1.sort() if l1 == alpha: return 1 return 0 0 tygerx2 months ago CPP 0.0 seconds int isPanagram(string S){ int arr[26] = {0}; for(int i =0; i<S.length();i++){ if(S[i]<65 || (S[i]>90 && S[i]<97)||S[i]>122){ continue; } if(S[i]>=97 && S[i]<=122){ S[i]-=32; } arr[S[i]-65]+=1; } for(int i =0; i<26;i++){ if(arr[i] == 0){ return 0; }} return 1; } +1 avinav26113 months ago Easiest C++ Solution 0 praveenkumar1391524 months ago #User function Template for python3import stringclass Solution: def isPanagram(self, S): k=set() S=S.lower() for i in S: if i.isalpha(): k.add(i) if len(k)==26: return 1 else: return 0 #{ # Driver Code Starts#Initial Template for Python 3 if __name__ == '__main__': T=int(input()) for i in range(T): S = input() ob = Solution() answer = ob.isPanagram(S) print(answer) # } Driver Code Ends +1 pketul22124 months ago class Solution { int isPanagram(String S) { S = S.toLowerCase(); for(char ch = 'a'; ch <= 'z'; ch++) { if(S.indexOf(ch) == -1) return 0; } return 1; } } +1 sanketsupekar6 months ago Java Solution 0.2 Sec class Solution { int isPanagram(String S) { S=S.toLowerCase(); for(char i='a';i<='z';i++) if(!S.contains(Character.toString(i))) return 0; return 1; } }; +1 badgujarsachin836 months ago int isPanagram(string S) { // Your code goes here int arr[26]={0}; for(int i=0;i<S.size();i++){ arr[tolower(S[i])-'a']++; } for(int i=0;i<26;i++){ if(arr[i]==0){ return 0; } } return 1; } -1 gauravg770617 months ago int isPanagram(string S){ // Your code goes here int arr[26]={0}; for(int i=0;i<S.length();i++){ if(S[i]>='a' && S[i]<='z'){ arr[S[i]-'a']++; } else if(isupper(S[i])){ S[i]=tolower(S[i]); arr[S[i]-'a']++; } } for(int i=0;i<26;i++){ if(arr[i]==0){ return 0; } } return 1;} 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": 361, "s": 238, "text": "Check if the given string S is a Panagram or not. A pangram is a sentence containing every letter in the English Alphabet." }, { "code": null, "e": 372, "s": 361, "text": "Example 1:" }, { "code": null, "e": 508, "s": 372, "text": "Input: S = \"Pack mY box witH fIve dozen \n liquor jugs\"\nOutput: 1\nExplanation: Given string contains all \nEnglish Alphabets. " }, { "code": null, "e": 519, "s": 508, "text": "Example 2:" }, { "code": null, "e": 624, "s": 519, "text": "Input: S = \"geeksFORgeeks\"\nOutput: 0\nExplanation: Given string does not contain \nall English Alphabets. " }, { "code": null, "e": 927, "s": 624, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function isPanagram() which takes the string as inputs and returns 1 if the given string is panagram, otherwise 0.\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(constant)\n\nConstraints:\n1 ≤ |S| ≤ 105" }, { "code": null, "e": 929, "s": 927, "text": "0" }, { "code": null, "e": 950, "s": 929, "text": "himpat2021 month ago" }, { "code": null, "e": 1357, "s": 950, "text": "why this is giving runtime error?int isPanagram(string str){ vector<int> v(27,0); int n =str.size(); if(n<26) { return 0; } for(int i=0;i<n;i++) { if(int(str[i])!=32){ char c = toupper(str[i]); int a_val = int(c); ++v[65-a_val]; } } for(int i=1;i<27;i++) { if(v[i]==0 ) { return 0; } } return 1;}" }, { "code": null, "e": 1359, "s": 1357, "text": "0" }, { "code": null, "e": 1385, "s": 1359, "text": "dipeshmakwane2 months ago" }, { "code": null, "e": 1404, "s": 1385, "text": "Easy C++ Solution" }, { "code": null, "e": 1558, "s": 1404, "text": "int isPanagram(string S){ // Your code goes here int count[256]={0}; for(int i=0;i<S.length();i++){ S[i]=tolower(S[i]); count[S[i]]++;" }, { "code": null, "e": 1694, "s": 1558, "text": " } for(int i=97;i<=122;i++){ if(count[i]==0){ return 0; break; } } return 1;}" }, { "code": null, "e": 1696, "s": 1694, "text": "0" }, { "code": null, "e": 1722, "s": 1696, "text": "prasadchaskar2 months ago" }, { "code": null, "e": 1739, "s": 1722, "text": "Python Solution:" }, { "code": null, "e": 2057, "s": 1739, "text": "def isPanagram(self, S):\n\t\t# code here\n\t\talpha = []\n for i in range(97,123):\n alpha.append(chr(i))\n l = set()\n for i in S:\n if i.isalpha():\n l.add(i.lower())\n l1 = list(l)\n l1.sort()\n if l1 == alpha:\n return 1\n return 0" }, { "code": null, "e": 2059, "s": 2057, "text": "0" }, { "code": null, "e": 2078, "s": 2059, "text": "tygerx2 months ago" }, { "code": null, "e": 2094, "s": 2078, "text": "CPP 0.0 seconds" }, { "code": null, "e": 2437, "s": 2096, "text": " int isPanagram(string S){ int arr[26] = {0}; for(int i =0; i<S.length();i++){ if(S[i]<65 || (S[i]>90 && S[i]<97)||S[i]>122){ continue; } if(S[i]>=97 && S[i]<=122){ S[i]-=32; } arr[S[i]-65]+=1; } for(int i =0; i<26;i++){ if(arr[i] == 0){ return 0; }} return 1; }" }, { "code": null, "e": 2440, "s": 2437, "text": "+1" }, { "code": null, "e": 2463, "s": 2440, "text": "avinav26113 months ago" }, { "code": null, "e": 2484, "s": 2463, "text": "Easiest C++ Solution" }, { "code": null, "e": 2488, "s": 2486, "text": "0" }, { "code": null, "e": 2519, "s": 2488, "text": "praveenkumar1391524 months ago" }, { "code": null, "e": 2780, "s": 2519, "text": "#User function Template for python3import stringclass Solution: def isPanagram(self, S): k=set() S=S.lower() for i in S: if i.isalpha(): k.add(i) if len(k)==26: return 1 else: return 0" }, { "code": null, "e": 2835, "s": 2780, "text": "#{ # Driver Code Starts#Initial Template for Python 3" }, { "code": null, "e": 2992, "s": 2835, "text": "if __name__ == '__main__': T=int(input()) for i in range(T): S = input() ob = Solution() answer = ob.isPanagram(S) print(answer)" }, { "code": null, "e": 3013, "s": 2992, "text": "# } Driver Code Ends" }, { "code": null, "e": 3016, "s": 3013, "text": "+1" }, { "code": null, "e": 3039, "s": 3016, "text": "pketul22124 months ago" }, { "code": null, "e": 3287, "s": 3039, "text": "class Solution {\n int isPanagram(String S) {\n \n S = S.toLowerCase();\n \n for(char ch = 'a'; ch <= 'z'; ch++) {\n if(S.indexOf(ch) == -1)\n return 0;\n }\n \n return 1;\n }\n}" }, { "code": null, "e": 3290, "s": 3287, "text": "+1" }, { "code": null, "e": 3316, "s": 3290, "text": "sanketsupekar6 months ago" }, { "code": null, "e": 3338, "s": 3316, "text": "Java Solution 0.2 Sec" }, { "code": null, "e": 3548, "s": 3338, "text": "class Solution {\n int isPanagram(String S) {\n S=S.toLowerCase();\n for(char i='a';i<='z';i++)\n if(!S.contains(Character.toString(i)))\n return 0;\n return 1;\n }\n};" }, { "code": null, "e": 3551, "s": 3548, "text": "+1" }, { "code": null, "e": 3580, "s": 3551, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 3847, "s": 3580, "text": "\n\tint isPanagram(string S)\n\t{\n\t // Your code goes here \n\t int arr[26]={0};\n\t for(int i=0;i<S.size();i++){\n\t arr[tolower(S[i])-'a']++;\n\t }\n\t for(int i=0;i<26;i++){\n\t if(arr[i]==0){\n\t return 0;\n\t }\n\t }\n\t return 1;\n\t}" }, { "code": null, "e": 3850, "s": 3847, "text": "-1" }, { "code": null, "e": 3875, "s": 3850, "text": "gauravg770617 months ago" }, { "code": null, "e": 4256, "s": 3875, "text": " int isPanagram(string S){ // Your code goes here int arr[26]={0}; for(int i=0;i<S.length();i++){ if(S[i]>='a' && S[i]<='z'){ arr[S[i]-'a']++; } else if(isupper(S[i])){ S[i]=tolower(S[i]); arr[S[i]-'a']++; } } for(int i=0;i<26;i++){ if(arr[i]==0){ return 0; } } return 1;}" }, { "code": null, "e": 4402, "s": 4256, "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": 4438, "s": 4402, "text": " Login to access your submissions. " }, { "code": null, "e": 4448, "s": 4438, "text": "\nProblem\n" }, { "code": null, "e": 4458, "s": 4448, "text": "\nContest\n" }, { "code": null, "e": 4521, "s": 4458, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4669, "s": 4521, "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": 4877, "s": 4669, "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": 4983, "s": 4877, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Spark SQL - JSON Datasets
Spark SQL can automatically capture the schema of a JSON dataset and load it as a DataFrame. This conversion can be done using SQLContext.read.json() on either an RDD of String or a JSON file. Spark SQL provides an option for querying JSON data along with auto-capturing of JSON schemas for both reading and writing data. Spark SQL understands the nested fields in JSON data and allows users to directly access these fields without any explicit transformations. Let us consider an example of employee records in a text file named employee.json. Use the following commands to create a DataFrame (df). Read a JSON document named employee.json with the following content and generate a table based on the schema in the JSON document. employee.json − Place this file into the directory where the current scala> pointer is located. { {"id" : "1201", "name" : "satish", "age" : "25"} {"id" : "1202", "name" : "krishna", "age" : "28"} {"id" : "1203", "name" : "amith", "age" : "39"} {"id" : "1204", "name" : "javed", "age" : "23"} {"id" : "1205", "name" : "prudvi", "age" : "23"} } Let us perform some Data Frame operations on given data. DataFrame provides a domain-specific language for structured data manipulation. Here we include some basic examples of structured data processing using DataFrames. Follow the steps given below to perform DataFrame operations − First of all, we have to read the JSON document. Based on that, generate a DataFrame named dfs. Use the following command to read the JSON document named employee.json containing the fields − id, name, and age. It creates a DataFrame named dfs. scala> val dfs = sqlContext.read.json("employee.json") Output − The field names are automatically taken from employee.json. dfs: org.apache.spark.sql.DataFrame = [age: string, id: string, name: string] If you want to see the Structure (Schema) of the DataFrame, then use the following command. scala> dfs.printSchema() Output root |-- age: string (nullable = true) |-- id: string (nullable = true) |-- name: string (nullable = true) If you want to show the data in the DataFrame, then use the following command. scala> dfs.show() Output − You can see the employee data in a tabular format. <console>:22, took 0.052610 s +----+------+--------+ |age | id | name | +----+------+--------+ | 25 | 1201 | satish | | 28 | 1202 | krishna| | 39 | 1203 | amith | | 23 | 1204 | javed | | 23 | 1205 | prudvi | +----+------+--------+ Then we can run different SQL statements in it. Users can migrate data into JSON format with minimal effort, regardless of the origin of the data source. 46 Lectures 3.5 hours Arnab Chakraborty 31 Lectures 1 hours Frahaan Hussain 12 Lectures 1 hours Pranjal Srivastava 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1913, "s": 1720, "text": "Spark SQL can automatically capture the schema of a JSON dataset and load it as a DataFrame. This conversion can be done using SQLContext.read.json() on either an RDD of String or a JSON file." }, { "code": null, "e": 2182, "s": 1913, "text": "Spark SQL provides an option for querying JSON data along with auto-capturing of JSON schemas for both reading and writing data. Spark SQL understands the nested fields in JSON data and allows users to directly access these fields without any explicit transformations." }, { "code": null, "e": 2320, "s": 2182, "text": "Let us consider an example of employee records in a text file named employee.json. Use the following commands to create a DataFrame (df)." }, { "code": null, "e": 2451, "s": 2320, "text": "Read a JSON document named employee.json with the following content and generate a table based on the schema in the JSON document." }, { "code": null, "e": 2547, "s": 2451, "text": "employee.json − Place this file into the directory where the current scala> pointer is located." }, { "code": null, "e": 2810, "s": 2547, "text": "{\n {\"id\" : \"1201\", \"name\" : \"satish\", \"age\" : \"25\"}\n {\"id\" : \"1202\", \"name\" : \"krishna\", \"age\" : \"28\"}\n {\"id\" : \"1203\", \"name\" : \"amith\", \"age\" : \"39\"}\n {\"id\" : \"1204\", \"name\" : \"javed\", \"age\" : \"23\"}\n {\"id\" : \"1205\", \"name\" : \"prudvi\", \"age\" : \"23\"}\n}" }, { "code": null, "e": 2867, "s": 2810, "text": "Let us perform some Data Frame operations on given data." }, { "code": null, "e": 3031, "s": 2867, "text": "DataFrame provides a domain-specific language for structured data manipulation. Here we include some basic examples of structured data processing using DataFrames." }, { "code": null, "e": 3094, "s": 3031, "text": "Follow the steps given below to perform DataFrame operations −" }, { "code": null, "e": 3190, "s": 3094, "text": "First of all, we have to read the JSON document. Based on that, generate a DataFrame named dfs." }, { "code": null, "e": 3339, "s": 3190, "text": "Use the following command to read the JSON document named employee.json containing the fields − id, name, and age. It creates a DataFrame named dfs." }, { "code": null, "e": 3395, "s": 3339, "text": "scala> val dfs = sqlContext.read.json(\"employee.json\")\n" }, { "code": null, "e": 3464, "s": 3395, "text": "Output − The field names are automatically taken from employee.json." }, { "code": null, "e": 3543, "s": 3464, "text": "dfs: org.apache.spark.sql.DataFrame = [age: string, id: string, name: string]\n" }, { "code": null, "e": 3635, "s": 3543, "text": "If you want to see the Structure (Schema) of the DataFrame, then use the following command." }, { "code": null, "e": 3661, "s": 3635, "text": "scala> dfs.printSchema()\n" }, { "code": null, "e": 3668, "s": 3661, "text": "Output" }, { "code": null, "e": 3785, "s": 3668, "text": "root\n |-- age: string (nullable = true)\n |-- id: string (nullable = true)\n |-- name: string (nullable = true)\n" }, { "code": null, "e": 3864, "s": 3785, "text": "If you want to show the data in the DataFrame, then use the following command." }, { "code": null, "e": 3883, "s": 3864, "text": "scala> dfs.show()\n" }, { "code": null, "e": 3943, "s": 3883, "text": "Output − You can see the employee data in a tabular format." }, { "code": null, "e": 4181, "s": 3943, "text": "<console>:22, took 0.052610 s\n+----+------+--------+\n|age | id | name |\n+----+------+--------+\n| 25 | 1201 | satish |\n| 28 | 1202 | krishna|\n| 39 | 1203 | amith |\n| 23 | 1204 | javed |\n| 23 | 1205 | prudvi |\n+----+------+--------+\n" }, { "code": null, "e": 4335, "s": 4181, "text": "Then we can run different SQL statements in it. Users can migrate data into JSON format with minimal effort, regardless of the origin of the data source." }, { "code": null, "e": 4370, "s": 4335, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4389, "s": 4370, "text": " Arnab Chakraborty" }, { "code": null, "e": 4422, "s": 4389, "text": "\n 31 Lectures \n 1 hours \n" }, { "code": null, "e": 4439, "s": 4422, "text": " Frahaan Hussain" }, { "code": null, "e": 4472, "s": 4439, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 4492, "s": 4472, "text": " Pranjal Srivastava" }, { "code": null, "e": 4527, "s": 4492, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4548, "s": 4527, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 4583, "s": 4548, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4601, "s": 4583, "text": " Bigdata Engineer" }, { "code": null, "e": 4634, "s": 4601, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 4652, "s": 4634, "text": " Bigdata Engineer" }, { "code": null, "e": 4659, "s": 4652, "text": " Print" }, { "code": null, "e": 4670, "s": 4659, "text": " Add Notes" } ]
Interactive COVID-19 visualizations using Plotly with 4 lines of code | by Priya Dwivedi | Towards Data Science
In this age of technology, data is the new oil. Organizations all over the world are transforming their environments, processes and infrastructures to become more data-driven. A major reason is that data analytics and machine learning gives organizations visibility into how to run their business better. The push to remote work through COVID-19 will accelerate this trend towards technology and data. A big part of analytics is presenting data in meaningful forms to the relevant decision makers so that they can easily comprehend the story. Traditionally organizations use software like Tableau to present cool interactive dashboards. In this blog, we show that open source libraries like Plotly Express can be used to do the same with just a few lines of code. We also coded all this in Bokeh but found the code was quite complex. Plotly, on the other hand, has built-in functionality that allows changing many things with parameters. We have used the CDC data on Coronavirus to generate interactive plots. See below the plot of daily change in Coronavirus cases by country. This is a very interesting diagram that shows which countries have peaked and the number of daily cases are starting to decrease. The full code is available on Github. I hope you pull it and give it a shot. At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve problems. Please reach out to us through here if you are a Health Services company and looking for data science help in fighting this crisis. Data visualizations is the “art” of presenting your data in an interesting, accurate and comprehensible manner. There are many types of visualizations that are used across all industries; the most common ones being bar graphs, pie charts, line graphs and histograms. But in many cases, these basic visualizations are not sufficient to effectively present the data. So more analysts are gravitating to visualizations like choropleths, time-series, heat maps, radial trees, word clouds etc. In this blog, we will explore a specific type of visualization called the choropleths, and show how you can create these visualizations in python with only a few lines of code. Choropleths are thematic maps in which different areas are shaded on a map to show different statistics. Below is choropleth map of a fraction of Australians that identify as Anglicans as of 2011. This map is from Wikipedia Chloropeths page. Choropleths can be of any granularity: from as small as a neighbourhood to the entire world, depending on what needs to be projected. In this blog, we will be exploring how to create a choropleth in python using the Plotly Express library. We will do a visualization of cases for countries in the World and then deep dive into cases in the United States. So let's get started! First, we will install the dependencies required to run this code: pandas and plotly pip install pandaspip install plotly Once we have these libraries downloaded, we will download and load the data. The data used in this blog is from the website called ourworldindata.org . The data available here is updated daily. You can download the data using wget as shown below: !wget https://covid.ourworldindata.org/data/owid-covid-data.csv Please follow along with the code at my Github link The output of the above code is the first 5 rows of the data as shown below: The dataset has information on country code, location, date, total cases, new cases, total deaths, new deaths and cases per million. We want to remove the entries corresponding to the country “World” which is sum total for all countries and sort the data by date. df = pd.read_csv('owid-covid-data.csv')## Drop rows corresponding to the Worlddf = df[df.location != 'World']## Sort df by datedf = df.sort_values(by=['date']) Making choropleth maps requires two main types of input: Geometry information supplied through a GeoJson file that has coordinates for the state, area, country that you are plottingData frame with values for that geometry Geometry information supplied through a GeoJson file that has coordinates for the state, area, country that you are plotting Data frame with values for that geometry Plotly has built in geometries for World and US maps and we will use them here. To create an interactive word map of daily new COVID-19 confirmed cases, the command is: fig = px.choropleth(df, locations="iso_code", color="new_cases", hover_name="location", animation_frame="date", title = "Daily new COVID cases", color_continuous_scale=px.colors.sequential.PuRd)fig["layout"].pop("updatemenus")fig.show() Here : df — Our data frame with COVID data Location — Countries are identified by their iso code. Plotly is able to get geo data using the iso code color — Column we want to plot. New cases here animation_frame: column you want to run animation on. In our case this is the date color_continuous_scale — Allows plotly to continuously change the axis and the colors as the slider is moved fig[“layout”].pop(“updatemenus”) — This creates a slider for date that can be manually toggled. If this line is commented out then the plot has a video type start, stop button The plot below shows output for March 2, 2020. This is the trigger point where new case growth rate is slowing in China but increasing in Iran, Italy and South Korea. In the notebook, I have also added a plot of total cumulative cases by week. To do this we add another line of code that adds a week number in pandas df['new_date'] = pd.to_datetime(df['date'])df['Year-Week'] = df['new_date'].dt.strftime('%Y-%U') Looking at this it is hard to believe the US had only around 100K cases a month back!. To add data for US, we need two things — 1. Data source that has US state and county level data and 2. Geo mapping of states and counties The COVID-19 US data is from NYtimes COVID-19-data. Thanks to the NY Times to make it public for use by analysts. You can download the data using !git clone https://github.com/nytimes/covid-19-data.git We can get geo data for counties using the script below. This data has polygon coordinates for all the counties in the US. from urllib.request import urlopenimport jsonwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) We can plot total cases in Plotly using the command below. The main difference from our earlier plots is that we use FIPS code for different counties instead of iso country codes as before. df_us_week = df_us_week.sort_values(by=['Year-Week'])fig = px.choropleth(df_us_week, geojson=counties, locations='fips', color='cases', color_continuous_scale="Viridis", title = "Total Weekly Cases by Counties", scope="usa", animation_frame="Year-Week", )fig["layout"].pop("updatemenus")fig.show() The output is below. It shows how severe impact has been localized to a few counties. The Github link also has details on creating visualizations on a state level. It was amazing how easily map plotting can be done using Plotly Express. If you have a custom map, you can also plot on it using geojson data. This is explained here. I hope you give the code a try and create more interesting visualizations. At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate. This blog was written by Priya Dwivedi and Faizan Khan. Plotly Express Chloropeths Visualization
[ { "code": null, "e": 574, "s": 172, "text": "In this age of technology, data is the new oil. Organizations all over the world are transforming their environments, processes and infrastructures to become more data-driven. A major reason is that data analytics and machine learning gives organizations visibility into how to run their business better. The push to remote work through COVID-19 will accelerate this trend towards technology and data." }, { "code": null, "e": 1110, "s": 574, "text": "A big part of analytics is presenting data in meaningful forms to the relevant decision makers so that they can easily comprehend the story. Traditionally organizations use software like Tableau to present cool interactive dashboards. In this blog, we show that open source libraries like Plotly Express can be used to do the same with just a few lines of code. We also coded all this in Bokeh but found the code was quite complex. Plotly, on the other hand, has built-in functionality that allows changing many things with parameters." }, { "code": null, "e": 1457, "s": 1110, "text": "We have used the CDC data on Coronavirus to generate interactive plots. See below the plot of daily change in Coronavirus cases by country. This is a very interesting diagram that shows which countries have peaked and the number of daily cases are starting to decrease. The full code is available on Github. I hope you pull it and give it a shot." }, { "code": null, "e": 1705, "s": 1457, "text": "At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve problems. Please reach out to us through here if you are a Health Services company and looking for data science help in fighting this crisis." }, { "code": null, "e": 2194, "s": 1705, "text": "Data visualizations is the “art” of presenting your data in an interesting, accurate and comprehensible manner. There are many types of visualizations that are used across all industries; the most common ones being bar graphs, pie charts, line graphs and histograms. But in many cases, these basic visualizations are not sufficient to effectively present the data. So more analysts are gravitating to visualizations like choropleths, time-series, heat maps, radial trees, word clouds etc." }, { "code": null, "e": 2371, "s": 2194, "text": "In this blog, we will explore a specific type of visualization called the choropleths, and show how you can create these visualizations in python with only a few lines of code." }, { "code": null, "e": 2613, "s": 2371, "text": "Choropleths are thematic maps in which different areas are shaded on a map to show different statistics. Below is choropleth map of a fraction of Australians that identify as Anglicans as of 2011. This map is from Wikipedia Chloropeths page." }, { "code": null, "e": 2747, "s": 2613, "text": "Choropleths can be of any granularity: from as small as a neighbourhood to the entire world, depending on what needs to be projected." }, { "code": null, "e": 2990, "s": 2747, "text": "In this blog, we will be exploring how to create a choropleth in python using the Plotly Express library. We will do a visualization of cases for countries in the World and then deep dive into cases in the United States. So let's get started!" }, { "code": null, "e": 3075, "s": 2990, "text": "First, we will install the dependencies required to run this code: pandas and plotly" }, { "code": null, "e": 3112, "s": 3075, "text": "pip install pandaspip install plotly" }, { "code": null, "e": 3359, "s": 3112, "text": "Once we have these libraries downloaded, we will download and load the data. The data used in this blog is from the website called ourworldindata.org . The data available here is updated daily. You can download the data using wget as shown below:" }, { "code": null, "e": 3423, "s": 3359, "text": "!wget https://covid.ourworldindata.org/data/owid-covid-data.csv" }, { "code": null, "e": 3475, "s": 3423, "text": "Please follow along with the code at my Github link" }, { "code": null, "e": 3552, "s": 3475, "text": "The output of the above code is the first 5 rows of the data as shown below:" }, { "code": null, "e": 3685, "s": 3552, "text": "The dataset has information on country code, location, date, total cases, new cases, total deaths, new deaths and cases per million." }, { "code": null, "e": 3816, "s": 3685, "text": "We want to remove the entries corresponding to the country “World” which is sum total for all countries and sort the data by date." }, { "code": null, "e": 3976, "s": 3816, "text": "df = pd.read_csv('owid-covid-data.csv')## Drop rows corresponding to the Worlddf = df[df.location != 'World']## Sort df by datedf = df.sort_values(by=['date'])" }, { "code": null, "e": 4033, "s": 3976, "text": "Making choropleth maps requires two main types of input:" }, { "code": null, "e": 4198, "s": 4033, "text": "Geometry information supplied through a GeoJson file that has coordinates for the state, area, country that you are plottingData frame with values for that geometry" }, { "code": null, "e": 4323, "s": 4198, "text": "Geometry information supplied through a GeoJson file that has coordinates for the state, area, country that you are plotting" }, { "code": null, "e": 4364, "s": 4323, "text": "Data frame with values for that geometry" }, { "code": null, "e": 4444, "s": 4364, "text": "Plotly has built in geometries for World and US maps and we will use them here." }, { "code": null, "e": 4533, "s": 4444, "text": "To create an interactive word map of daily new COVID-19 confirmed cases, the command is:" }, { "code": null, "e": 4864, "s": 4533, "text": "fig = px.choropleth(df, locations=\"iso_code\", color=\"new_cases\", hover_name=\"location\", animation_frame=\"date\", title = \"Daily new COVID cases\", color_continuous_scale=px.colors.sequential.PuRd)fig[\"layout\"].pop(\"updatemenus\")fig.show()" }, { "code": null, "e": 4871, "s": 4864, "text": "Here :" }, { "code": null, "e": 4907, "s": 4871, "text": "df — Our data frame with COVID data" }, { "code": null, "e": 5012, "s": 4907, "text": "Location — Countries are identified by their iso code. Plotly is able to get geo data using the iso code" }, { "code": null, "e": 5059, "s": 5012, "text": "color — Column we want to plot. New cases here" }, { "code": null, "e": 5142, "s": 5059, "text": "animation_frame: column you want to run animation on. In our case this is the date" }, { "code": null, "e": 5251, "s": 5142, "text": "color_continuous_scale — Allows plotly to continuously change the axis and the colors as the slider is moved" }, { "code": null, "e": 5427, "s": 5251, "text": "fig[“layout”].pop(“updatemenus”) — This creates a slider for date that can be manually toggled. If this line is commented out then the plot has a video type start, stop button" }, { "code": null, "e": 5594, "s": 5427, "text": "The plot below shows output for March 2, 2020. This is the trigger point where new case growth rate is slowing in China but increasing in Iran, Italy and South Korea." }, { "code": null, "e": 5744, "s": 5594, "text": "In the notebook, I have also added a plot of total cumulative cases by week. To do this we add another line of code that adds a week number in pandas" }, { "code": null, "e": 5841, "s": 5744, "text": "df['new_date'] = pd.to_datetime(df['date'])df['Year-Week'] = df['new_date'].dt.strftime('%Y-%U')" }, { "code": null, "e": 5928, "s": 5841, "text": "Looking at this it is hard to believe the US had only around 100K cases a month back!." }, { "code": null, "e": 6066, "s": 5928, "text": "To add data for US, we need two things — 1. Data source that has US state and county level data and 2. Geo mapping of states and counties" }, { "code": null, "e": 6212, "s": 6066, "text": "The COVID-19 US data is from NYtimes COVID-19-data. Thanks to the NY Times to make it public for use by analysts. You can download the data using" }, { "code": null, "e": 6268, "s": 6212, "text": "!git clone https://github.com/nytimes/covid-19-data.git" }, { "code": null, "e": 6391, "s": 6268, "text": "We can get geo data for counties using the script below. This data has polygon coordinates for all the counties in the US." }, { "code": null, "e": 6583, "s": 6391, "text": "from urllib.request import urlopenimport jsonwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response)" }, { "code": null, "e": 6773, "s": 6583, "text": "We can plot total cases in Plotly using the command below. The main difference from our earlier plots is that we use FIPS code for different counties instead of iso country codes as before." }, { "code": null, "e": 7243, "s": 6773, "text": "df_us_week = df_us_week.sort_values(by=['Year-Week'])fig = px.choropleth(df_us_week, geojson=counties, locations='fips', color='cases', color_continuous_scale=\"Viridis\", title = \"Total Weekly Cases by Counties\", scope=\"usa\", animation_frame=\"Year-Week\", )fig[\"layout\"].pop(\"updatemenus\")fig.show()" }, { "code": null, "e": 7329, "s": 7243, "text": "The output is below. It shows how severe impact has been localized to a few counties." }, { "code": null, "e": 7407, "s": 7329, "text": "The Github link also has details on creating visualizations on a state level." }, { "code": null, "e": 7574, "s": 7407, "text": "It was amazing how easily map plotting can be done using Plotly Express. If you have a custom map, you can also plot on it using geojson data. This is explained here." }, { "code": null, "e": 7649, "s": 7574, "text": "I hope you give the code a try and create more interesting visualizations." }, { "code": null, "e": 7967, "s": 7649, "text": "At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate. This blog was written by Priya Dwivedi and Faizan Khan." } ]
How to get the javascript function parameter names/values dynamically? - GeeksforGeeks
27 Sep, 2021 Given any arbitrary JavaScript function and the task is to return the parameter names of the function. Approach: JavaScript contains a method called Function.toString() which is used to represent a function code into its string representation. This method is used to get the parameter names/values. First, get the function’s code to its string equivalent using toString() method. Then remove all the unnecessary codes like comments, function body, white spaces, and ES6 arrow (if any). Identify the first occurrence of ‘(‘, it will be just before the starting of parameters. The last character of the string will be ‘)’ which removes all comments, function body, white spaces, and ES6 arrow. Also, the last character will be just after the end of the parameters. Example: Javascript <script> // JavaScript program to get the function// name/values dynamicallyfunction getParams(func) { // String representaation of the function code var str = func.toString(); // Remove comments of the form /* ... */ // Removing comments of the form // // Remove body of the function { ... } // removing '=>' if func is arrow function str = str.replace(/\/\*[\s\S]*?\*\//g, '') .replace(/\/\/(.)*/g, '') .replace(/{[\s\S]*}/, '') .replace(/=>/g, '') .trim(); // Start parameter names after first '(' var start = str.indexOf("(") + 1; // End parameter names is just before last ')' var end = str.length - 1; var result = str.substring(start, end).split(", "); var params = []; result.forEach(element => { // Removing any default value element = element.replace(/=[\s\S]*/g, '').trim(); if(element.length > 0) params.push(element); }); return params;} // Test sample functionsvar fun1 = function(a){ }; function fun2(a = 5*6/3, // Comment b){ }; var fun3 = (a, /* */ b, //comment c) => /** */{ }; console.log(`List of parameters of ${fun1.name}:`, getParams(fun1));console.log(`List of parameters of ${fun2.name}:`, getParams(fun2));console.log(`List of parameters of ${fun3.name}:`, getParams(fun3));</script> Output: List of parameters: List of parameters of fun1: [ 'a' ] List of parameters of fun2: [ 'a', 'b' ] List of parameters of fun3: [ 'a', 'b', 'c' ] sweetyty javascript-functions Picked JavaScript Web Technologies Web technologies Questions 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 Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js 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": 37579, "s": 37551, "text": "\n27 Sep, 2021" }, { "code": null, "e": 37683, "s": 37579, "text": "Given any arbitrary JavaScript function and the task is to return the parameter names of the function. " }, { "code": null, "e": 37880, "s": 37683, "text": "Approach: JavaScript contains a method called Function.toString() which is used to represent a function code into its string representation. This method is used to get the parameter names/values. " }, { "code": null, "e": 37961, "s": 37880, "text": "First, get the function’s code to its string equivalent using toString() method." }, { "code": null, "e": 38067, "s": 37961, "text": "Then remove all the unnecessary codes like comments, function body, white spaces, and ES6 arrow (if any)." }, { "code": null, "e": 38156, "s": 38067, "text": "Identify the first occurrence of ‘(‘, it will be just before the starting of parameters." }, { "code": null, "e": 38273, "s": 38156, "text": "The last character of the string will be ‘)’ which removes all comments, function body, white spaces, and ES6 arrow." }, { "code": null, "e": 38344, "s": 38273, "text": "Also, the last character will be just after the end of the parameters." }, { "code": null, "e": 38354, "s": 38344, "text": "Example: " }, { "code": null, "e": 38365, "s": 38354, "text": "Javascript" }, { "code": "<script> // JavaScript program to get the function// name/values dynamicallyfunction getParams(func) { // String representaation of the function code var str = func.toString(); // Remove comments of the form /* ... */ // Removing comments of the form // // Remove body of the function { ... } // removing '=>' if func is arrow function str = str.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '') .replace(/\\/\\/(.)*/g, '') .replace(/{[\\s\\S]*}/, '') .replace(/=>/g, '') .trim(); // Start parameter names after first '(' var start = str.indexOf(\"(\") + 1; // End parameter names is just before last ')' var end = str.length - 1; var result = str.substring(start, end).split(\", \"); var params = []; result.forEach(element => { // Removing any default value element = element.replace(/=[\\s\\S]*/g, '').trim(); if(element.length > 0) params.push(element); }); return params;} // Test sample functionsvar fun1 = function(a){ }; function fun2(a = 5*6/3, // Comment b){ }; var fun3 = (a, /* */ b, //comment c) => /** */{ }; console.log(`List of parameters of ${fun1.name}:`, getParams(fun1));console.log(`List of parameters of ${fun2.name}:`, getParams(fun2));console.log(`List of parameters of ${fun3.name}:`, getParams(fun3));</script>", "e": 39749, "s": 38365, "text": null }, { "code": null, "e": 39758, "s": 39749, "text": "Output: " }, { "code": null, "e": 39901, "s": 39758, "text": "List of parameters:\nList of parameters of fun1: [ 'a' ]\nList of parameters of fun2: [ 'a', 'b' ]\nList of parameters of fun3: [ 'a', 'b', 'c' ]" }, { "code": null, "e": 39912, "s": 39903, "text": "sweetyty" }, { "code": null, "e": 39933, "s": 39912, "text": "javascript-functions" }, { "code": null, "e": 39940, "s": 39933, "text": "Picked" }, { "code": null, "e": 39951, "s": 39940, "text": "JavaScript" }, { "code": null, "e": 39968, "s": 39951, "text": "Web Technologies" }, { "code": null, "e": 39995, "s": 39968, "text": "Web technologies Questions" }, { "code": null, "e": 40093, "s": 39995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40102, "s": 40093, "text": "Comments" }, { "code": null, "e": 40115, "s": 40102, "text": "Old Comments" }, { "code": null, "e": 40176, "s": 40115, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40221, "s": 40176, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40293, "s": 40221, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40362, "s": 40293, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40389, "s": 40362, "text": "File uploading in React.js" }, { "code": null, "e": 40445, "s": 40389, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 40478, "s": 40445, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40540, "s": 40478, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40583, "s": 40540, "text": "How to fetch data from an API in ReactJS ?" } ]
Select column names containing a string in MySQL?
For this, you can use SHOW COLUMNS command. Following is the syntax. Here, we have set the string using LIKE − SHOW COLUMNS FROM yourTableName LIKE ‘yourStringValue’; Let us first create a table − mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstName varchar(20), -> LastName varchar(20) -> ); Query OK, 0 rows affected (0.69 sec) Here is the query to select column names containing a specific string − mysql> SHOW COLUMNS FROM DemoTable LIKE 'FirstName'; +-----------+-------------+------+-----+----------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+----------+-------+ | FirstName | varchar(20) | YES | | NULL | | +-----------+-------------+------+-----+---------+-------+ 1 row in set (0.05 sec)
[ { "code": null, "e": 1173, "s": 1062, "text": "For this, you can use SHOW COLUMNS command. Following is the syntax. Here, we have set the string using LIKE −" }, { "code": null, "e": 1229, "s": 1173, "text": "SHOW COLUMNS FROM yourTableName LIKE ‘yourStringValue’;" }, { "code": null, "e": 1259, "s": 1229, "text": "Let us first create a table −" }, { "code": null, "e": 1449, "s": 1259, "text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> FirstName varchar(20),\n -> LastName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.69 sec)" }, { "code": null, "e": 1521, "s": 1449, "text": "Here is the query to select column names containing a specific string −" }, { "code": null, "e": 1574, "s": 1521, "text": "mysql> SHOW COLUMNS FROM DemoTable LIKE 'FirstName';" }, { "code": null, "e": 1897, "s": 1574, "text": "+-----------+-------------+------+-----+----------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------+-------------+------+-----+----------+-------+\n| FirstName | varchar(20) | YES | | NULL | |\n+-----------+-------------+------+-----+---------+-------+\n1 row in set (0.05 sec)" } ]
Tree and Level | Practice | GeeksforGeeks
Given a tree with N nodes rooted at 1. Each node labeled with a value arr[i]. The task is to find the absolute difference between the sum of values of nodes at even level and odd level Note: All the nodes are numbered from 1 to N. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains a single integer N. 3. The next line contains N space-separated positive integers represents the node value. 4. Next N-1 lines contain two space-separated integers u and v, represents an edge in between them Output: For each test case, print the answer Constraints: 1. 1 <= T <= 5 2. 1 <= N <= 105 3. 1 <= arr[i] <= 105 Example: Input: 2 4 1 2 3 4 1 2 3 4 4 1 5 1 2 1 2 1 1 2 2 3 3 4 4 5 Output: 2 1 0 anutiger6 months ago Do not create adjacency list, create ab unordered map in form of adjacency list. int t; cin>> t; while(t--){ int n; cin >> n; int arr[n]; for(int i = 0 ; i < n ; i ++){ int a; cin >> a; arr[i] = a; } unordered_map<int,vector<int>> adj; for(int i = 1 ; i <= n - 1; i ++){ int a,b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } int even = 0; int odd = 0; queue<pair<int,int>>q; q.push({1,1}); vector<int> vis(n,0); while(!q.empty()){ auto it = q.front();q.pop(); if(it.second == 1){ odd+= arr[it.first - 1]; } else even += arr[it.first - 1]; vis[it.first - 1] = 1; int flag = 1; if(it.second == 1) flag = 2; for(int j : adj[it.first]){ if(vis[j - 1] == 0) q.push({j,flag}); } } cout<<abs(even - odd)<<endl; } 0 imranwahid6 months ago Easy C++ solution with BFS https://ide.geeksforgeeks.org/a6moHaGY36 #include<bits/stdc++.h> using namespace std; // helper function to find the abs value of diff of odd and even level sum int helper(unordered_map<int,vector<int>>&m,vector<int>&val) { if(val.size()==0) { return 0; } // visited array will tell whether a particular node has been visited or not vector<int>visited(val.size()+1,false); // queue for running a BFS call queue<int>q; // as 1 is the root q.push(1); // level is the current level , odd is the odd level sum and same goes for even int level=0,even=0,odd=0; // mark the root as visited visited[1]=true; // run the BFS while(!q.empty()) { int n=q.size(); while(n) { int node=q.front(); q.pop(); if(level%2==0) { even+=val[node-1]; } else { odd+=val[node-1]; } for(auto it:m[node]) { if(!visited[it]) { visited[it]=true; q.push(it); } } n--; } level++; } return abs(odd-even); } int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<int>val(n); for(int i=0;i<n;i++) { cin>>val[i]; } // the map will store the graph where each node is the label not the actual value unordered_map<int,vector<int>>m; for(int i=0;i<n-1;i++) { int u,v; cin>>u>>v; m[u].push_back(v); m[v].push_back(u); } cout<<helper(m,val)<<endl; } return 0; } 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": 459, "s": 226, "text": "Given a tree with N nodes rooted at 1. Each node labeled with a value arr[i]. The task is to find the absolute difference between the sum of values of nodes at even level and odd level\n\nNote: All the nodes are numbered from 1 to N. " }, { "code": null, "e": 856, "s": 459, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer N.\n3. The next line contains N space-separated positive integers represents the node value.\n4. Next N-1 lines contain two space-separated integers u and v, represents an edge in between them" }, { "code": null, "e": 902, "s": 856, "text": "\nOutput: For each test case, print the answer" }, { "code": null, "e": 1040, "s": 902, "text": "\nConstraints:\n1. 1 <= T <= 5\n2. 1 <= N <= 105\n3. 1 <= arr[i] <= 105\n\n\nExample:\nInput:\n2\n4\n1 2 3 4\n1 2\n3 4\n4 1\n5\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5" }, { "code": null, "e": 1052, "s": 1040, "text": "Output:\n2\n1" }, { "code": null, "e": 1054, "s": 1052, "text": "0" }, { "code": null, "e": 1075, "s": 1054, "text": "anutiger6 months ago" }, { "code": null, "e": 1157, "s": 1075, "text": "Do not create adjacency list, create ab unordered map in form of adjacency list." }, { "code": null, "e": 2050, "s": 1159, "text": " int t;\n\tcin>> t;\n\twhile(t--){\n\t int n;\n\t cin >> n;\n\t int arr[n];\n\t for(int i = 0 ; i < n ; i ++){\n\t int a; cin >> a;\n\t arr[i] = a;\n\t }\n\t unordered_map<int,vector<int>> adj;\n\t for(int i = 1 ; i <= n - 1; i ++){\n\t int a,b;\n\t cin >> a >> b;\n\t adj[a].push_back(b);\n\t adj[b].push_back(a);\n\t }\n\t int even = 0;\n\t int odd = 0;\n\t queue<pair<int,int>>q;\n\t q.push({1,1});\n\t vector<int> vis(n,0);\n\t while(!q.empty()){\n\t auto it = q.front();q.pop();\n\t if(it.second == 1){\n\t odd+= arr[it.first - 1];\n\t }\n\t else even += arr[it.first - 1];\n\t vis[it.first - 1] = 1;\n\t int flag = 1;\n\t if(it.second == 1) flag = 2;\n\t for(int j : adj[it.first]){\n\t if(vis[j - 1] == 0) q.push({j,flag});\n\t }\n\t }\n\t cout<<abs(even - odd)<<endl;\n\t}" }, { "code": null, "e": 2054, "s": 2052, "text": "0" }, { "code": null, "e": 2077, "s": 2054, "text": "imranwahid6 months ago" }, { "code": null, "e": 2104, "s": 2077, "text": "Easy C++ solution with BFS" }, { "code": null, "e": 2145, "s": 2104, "text": "https://ide.geeksforgeeks.org/a6moHaGY36" }, { "code": null, "e": 3852, "s": 2145, "text": "#include<bits/stdc++.h>\nusing namespace std;\n// helper function to find the abs value of diff of odd and even level sum\nint helper(unordered_map<int,vector<int>>&m,vector<int>&val)\n{\n if(val.size()==0)\n {\n return 0;\n }\n // visited array will tell whether a particular node has been visited or not\n vector<int>visited(val.size()+1,false);\n \n // queue for running a BFS call\n queue<int>q;\n \n // as 1 is the root\n q.push(1);\n \n // level is the current level , odd is the odd level sum and same goes for even\n int level=0,even=0,odd=0;\n \n // mark the root as visited\n visited[1]=true;\n \n // run the BFS\n while(!q.empty())\n {\n int n=q.size();\n while(n)\n {\n int node=q.front();\n q.pop();\n if(level%2==0)\n {\n even+=val[node-1];\n }\n else\n {\n odd+=val[node-1];\n }\n for(auto it:m[node])\n {\n if(!visited[it])\n {\n visited[it]=true;\n q.push(it);\n }\n }\n n--;\n }\n level++;\n }\n return abs(odd-even);\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t int n;\n\t cin>>n;\n\t vector<int>val(n);\n\t for(int i=0;i<n;i++)\n\t {\n\t cin>>val[i];\n\t }\n\t // the map will store the graph where each node is the label not the actual value\n\t unordered_map<int,vector<int>>m;\n\t for(int i=0;i<n-1;i++)\n\t {\n\t int u,v;\n\t cin>>u>>v;\n\t m[u].push_back(v);\n\t m[v].push_back(u);\n\t }\n\t cout<<helper(m,val)<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 3998, "s": 3852, "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": 4034, "s": 3998, "text": " Login to access your submissions. " }, { "code": null, "e": 4044, "s": 4034, "text": "\nProblem\n" }, { "code": null, "e": 4054, "s": 4044, "text": "\nContest\n" }, { "code": null, "e": 4117, "s": 4054, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4265, "s": 4117, "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": 4473, "s": 4265, "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": 4579, "s": 4473, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to create a thread in Java
A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called. The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread and it is the last thread to finish execution. A program that demonstrates this is given as follows: Live Demo class ThreadDemo implements Runnable { Thread t; ThreadDemo() { t = new Thread(this, "Thread"); System.out.println("Child thread: " + t); t.start(); } public void run() { try { System.out.println("Child Thread"); Thread.sleep(50); } catch (InterruptedException e) { System.out.println("The child thread is interrupted."); } System.out.println("Exiting the child thread"); } } public class Demo { public static void main(String args[]) { new ThreadDemo(); try { System.out.println("Main Thread"); Thread.sleep(100); } catch (InterruptedException e) { System.out.println("The Main thread is interrupted"); } System.out.println("Exiting the Main thread"); } } Child thread: Thread[Thread,5,main] Main Thread Child Thread Exiting the child thread Exiting the Main thread
[ { "code": null, "e": 1225, "s": 1062, "text": "A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called." }, { "code": null, "e": 1409, "s": 1225, "text": "The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread and it is the last thread to finish execution." }, { "code": null, "e": 1463, "s": 1409, "text": "A program that demonstrates this is given as follows:" }, { "code": null, "e": 1474, "s": 1463, "text": " Live Demo" }, { "code": null, "e": 2278, "s": 1474, "text": "class ThreadDemo implements Runnable {\n Thread t;\n ThreadDemo() {\n t = new Thread(this, \"Thread\");\n System.out.println(\"Child thread: \" + t);\n t.start();\n }\n public void run() {\n try {\n System.out.println(\"Child Thread\");\n Thread.sleep(50);\n } catch (InterruptedException e) {\n System.out.println(\"The child thread is interrupted.\");\n }\n System.out.println(\"Exiting the child thread\");\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n new ThreadDemo();\n try {\n System.out.println(\"Main Thread\");\n Thread.sleep(100);\n } catch (InterruptedException e) {\n System.out.println(\"The Main thread is interrupted\");\n }\n System.out.println(\"Exiting the Main thread\");\n }\n}" }, { "code": null, "e": 2388, "s": 2278, "text": "Child thread: Thread[Thread,5,main]\nMain Thread\nChild Thread\nExiting the child thread\nExiting the Main thread" } ]
How to generate 6-digit random number in MySQL?
You can use LPAD() along with rand() and floor() to generate 6-digit random number. Let us first create a table − mysql> create table DemoTable ( Value int ); Query OK, 0 rows affected (0.64 sec) Insert records in the table using insert command − mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(2); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(3); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(4); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(5); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(6); Query OK, 1 row affected (0.19 sec) Display all records from the table using select statement − mysql> select * from DemoTable; This will produce the following output − +-------+ | Value | +-------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +-------+ 6 rows in set (0.00 sec) Following is the query to generate 6-digit random number in MySQL − mysql> update DemoTable set Value=LPAD(FLOOR(RAND() * 999999.99), 6, '0'); Query OK, 6 rows affected (0.15 sec) Rows matched: 6 Changed: 6 Warnings: 0 Let us display the updated records from the table − mysql> select * from DemoTable; This will produce the following output − +--------+ | Value | +--------+ | 499540 | | 550607 | | 254419 | | 620272 | | 338104 | | 829705 | +--------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1176, "s": 1062, "text": "You can use LPAD() along with rand() and floor() to generate 6-digit random number. Let us first create a table −" }, { "code": null, "e": 1267, "s": 1176, "text": "mysql> create table DemoTable\n (\n Value int\n );\nQuery OK, 0 rows affected (0.64 sec)" }, { "code": null, "e": 1318, "s": 1267, "text": "Insert records in the table using insert command −" }, { "code": null, "e": 1774, "s": 1318, "text": "mysql> insert into DemoTable values(1);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(2);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values(3);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable values(4);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values(5);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(6);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 1834, "s": 1774, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1866, "s": 1834, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 1907, "s": 1866, "text": "This will produce the following output −" }, { "code": null, "e": 2032, "s": 1907, "text": "+-------+\n| Value |\n+-------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2100, "s": 2032, "text": "Following is the query to generate 6-digit random number in MySQL −" }, { "code": null, "e": 2251, "s": 2100, "text": "mysql> update DemoTable\nset Value=LPAD(FLOOR(RAND() * 999999.99), 6, '0');\nQuery OK, 6 rows affected (0.15 sec)\nRows matched: 6 Changed: 6 Warnings: 0" }, { "code": null, "e": 2303, "s": 2251, "text": "Let us display the updated records from the table −" }, { "code": null, "e": 2335, "s": 2303, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2376, "s": 2335, "text": "This will produce the following output −" }, { "code": null, "e": 2511, "s": 2376, "text": "+--------+\n| Value |\n+--------+\n| 499540 |\n| 550607 |\n| 254419 |\n| 620272 |\n| 338104 |\n| 829705 |\n+--------+\n6 rows in set (0.00 sec)" } ]
Java & MySQL - Batch Processing
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance. JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature. JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature. The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove. Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove. Here is a typical sequence of steps to use Batch Processing with Statement Object − Create a Statement object using either createStatement() methods. Create a Statement object using either createStatement() methods. Set auto-commit to false using setAutoCommit(). Set auto-commit to false using setAutoCommit(). Add as many as SQL statements you like into batch using addBatch() method on created statement object. Add as many as SQL statements you like into batch using addBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Finally, commit all the changes using commit() method. Finally, commit all the changes using commit() method. The following code snippet provides an example of a batch update using Statement object − // Create statement object Statement stmt = conn.createStatement(); // Set auto-commit to false conn.setAutoCommit(false); // Create SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(200,'Zia', 'Ali', 30)"; // Add above SQL statement in the batch. stmt.addBatch(SQL); // Create one more SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(201,'Raj', 'Kumar', 35)"; // Add above SQL statement in the batch. stmt.addBatch(SQL); // Create one more SQL statement String SQL = "UPDATE Employees SET age = 35 " + "WHERE id = 100"; // Add above SQL statement in the batch. stmt.addBatch(SQL); // Create an int[] to hold returned values int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes conn.commit(); Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object − Create SQL statements with placeholders. Create SQL statements with placeholders. Create PrepareStatement object using either prepareStatement() methods. Create PrepareStatement object using either prepareStatement() methods. Set auto-commit to false using setAutoCommit(). Set auto-commit to false using setAutoCommit(). Add as many as SQL statements you like into batch using addBatch() method on created statement object. Add as many as SQL statements you like into batch using addBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Finally, commit all the changes using commit() method. Finally, commit all the changes using commit() method. The following code snippet provides an example of a batch update using PrepareStatement object − // Create SQL statement String SQL = "INSERT INTO Employees (id, first, last, age) " + "VALUES(?, ?, ?, ?)"; // Create PrepareStatement object PreparedStatemen pstmt = conn.prepareStatement(SQL); //Set auto-commit to false conn.setAutoCommit(false); // Set the variables pstmt.setInt( 1, 400 ); pstmt.setString( 2, "Pappu" ); pstmt.setString( 3, "Singh" ); pstmt.setInt( 4, 33 ); // Add it to the batch pstmt.addBatch(); // Set the variables pstmt.setInt( 1, 401 ); pstmt.setString( 2, "Pawan" ); pstmt.setString( 3, "Singh" ); pstmt.setInt( 4, 31 ); // Add it to the batch pstmt.addBatch(); //add more batches . . . . //Create an int[] to hold returned values int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes conn.commit(); 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": 2806, "s": 2686, "text": "Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database." }, { "code": null, "e": 2948, "s": 2806, "text": "When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance." }, { "code": null, "e": 3206, "s": 2948, "text": "JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature." }, { "code": null, "e": 3464, "s": 3206, "text": "JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature." }, { "code": null, "e": 3682, "s": 3464, "text": "The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together." }, { "code": null, "e": 3900, "s": 3682, "text": "The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together." }, { "code": null, "e": 4044, "s": 3900, "text": "The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement." }, { "code": null, "e": 4188, "s": 4044, "text": "The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement." }, { "code": null, "e": 4439, "s": 4188, "text": "Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove." }, { "code": null, "e": 4690, "s": 4439, "text": "Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove." }, { "code": null, "e": 4774, "s": 4690, "text": "Here is a typical sequence of steps to use Batch Processing with Statement Object −" }, { "code": null, "e": 4840, "s": 4774, "text": "Create a Statement object using either createStatement() methods." }, { "code": null, "e": 4906, "s": 4840, "text": "Create a Statement object using either createStatement() methods." }, { "code": null, "e": 4954, "s": 4906, "text": "Set auto-commit to false using setAutoCommit()." }, { "code": null, "e": 5002, "s": 4954, "text": "Set auto-commit to false using setAutoCommit()." }, { "code": null, "e": 5105, "s": 5002, "text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object." }, { "code": null, "e": 5208, "s": 5105, "text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object." }, { "code": null, "e": 5296, "s": 5208, "text": "Execute all the SQL statements using executeBatch() method on created statement object." }, { "code": null, "e": 5384, "s": 5296, "text": "Execute all the SQL statements using executeBatch() method on created statement object." }, { "code": null, "e": 5439, "s": 5384, "text": "Finally, commit all the changes using commit() method." }, { "code": null, "e": 5494, "s": 5439, "text": "Finally, commit all the changes using commit() method." }, { "code": null, "e": 5584, "s": 5494, "text": "The following code snippet provides an example of a batch update using Statement object −" }, { "code": null, "e": 6424, "s": 5584, "text": "// Create statement object\nStatement stmt = conn.createStatement();\n\n// Set auto-commit to false\nconn.setAutoCommit(false);\n\n// Create SQL statement\nString SQL = \"INSERT INTO Employees (id, first, last, age) \" +\n \"VALUES(200,'Zia', 'Ali', 30)\";\n// Add above SQL statement in the batch.\nstmt.addBatch(SQL);\n\n// Create one more SQL statement\nString SQL = \"INSERT INTO Employees (id, first, last, age) \" +\n \"VALUES(201,'Raj', 'Kumar', 35)\";\n// Add above SQL statement in the batch.\nstmt.addBatch(SQL);\n\n// Create one more SQL statement\nString SQL = \"UPDATE Employees SET age = 35 \" +\n \"WHERE id = 100\";\n// Add above SQL statement in the batch.\nstmt.addBatch(SQL);\n\n// Create an int[] to hold returned values\nint[] count = stmt.executeBatch();\n\n//Explicitly commit statements to apply changes\nconn.commit();" }, { "code": null, "e": 6515, "s": 6424, "text": "Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object −" }, { "code": null, "e": 6556, "s": 6515, "text": "Create SQL statements with placeholders." }, { "code": null, "e": 6597, "s": 6556, "text": "Create SQL statements with placeholders." }, { "code": null, "e": 6670, "s": 6597, "text": "Create PrepareStatement object using either prepareStatement() methods." }, { "code": null, "e": 6743, "s": 6670, "text": "Create PrepareStatement object using either prepareStatement() methods." }, { "code": null, "e": 6791, "s": 6743, "text": "Set auto-commit to false using setAutoCommit()." }, { "code": null, "e": 6839, "s": 6791, "text": "Set auto-commit to false using setAutoCommit()." }, { "code": null, "e": 6942, "s": 6839, "text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object." }, { "code": null, "e": 7045, "s": 6942, "text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object." }, { "code": null, "e": 7133, "s": 7045, "text": "Execute all the SQL statements using executeBatch() method on created statement object." }, { "code": null, "e": 7221, "s": 7133, "text": "Execute all the SQL statements using executeBatch() method on created statement object." }, { "code": null, "e": 7276, "s": 7221, "text": "Finally, commit all the changes using commit() method." }, { "code": null, "e": 7331, "s": 7276, "text": "Finally, commit all the changes using commit() method." }, { "code": null, "e": 7428, "s": 7331, "text": "The following code snippet provides an example of a batch update using PrepareStatement object −" }, { "code": null, "e": 8206, "s": 7428, "text": "// Create SQL statement\nString SQL = \"INSERT INTO Employees (id, first, last, age) \" +\n \"VALUES(?, ?, ?, ?)\";\n\n// Create PrepareStatement object\nPreparedStatemen pstmt = conn.prepareStatement(SQL);\n\n//Set auto-commit to false\nconn.setAutoCommit(false);\n\n// Set the variables\npstmt.setInt( 1, 400 );\npstmt.setString( 2, \"Pappu\" );\npstmt.setString( 3, \"Singh\" );\npstmt.setInt( 4, 33 );\n// Add it to the batch\npstmt.addBatch();\n\n// Set the variables\npstmt.setInt( 1, 401 );\npstmt.setString( 2, \"Pawan\" );\npstmt.setString( 3, \"Singh\" );\npstmt.setInt( 4, 31 );\n// Add it to the batch\npstmt.addBatch();\n\n//add more batches\n.\n.\n.\n.\n//Create an int[] to hold returned values\nint[] count = stmt.executeBatch();\n\n//Explicitly commit statements to apply changes\nconn.commit();" }, { "code": null, "e": 8239, "s": 8206, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8255, "s": 8239, "text": " Malhar Lathkar" }, { "code": null, "e": 8288, "s": 8255, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8304, "s": 8288, "text": " Malhar Lathkar" }, { "code": null, "e": 8339, "s": 8304, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8353, "s": 8339, "text": " Anadi Sharma" }, { "code": null, "e": 8387, "s": 8353, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 8401, "s": 8387, "text": " Tushar Kale" }, { "code": null, "e": 8438, "s": 8401, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8453, "s": 8438, "text": " Monica Mittal" }, { "code": null, "e": 8486, "s": 8453, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 8505, "s": 8486, "text": " Arnab Chakraborty" }, { "code": null, "e": 8512, "s": 8505, "text": " Print" }, { "code": null, "e": 8523, "s": 8512, "text": " Add Notes" } ]
6 Weeks of Android App Development - FREE Project Based Learning - GeeksforGeeks
18 Feb, 2022 Are you among the ones who want to learn Android App Development from the beginning? Are you someone who doesn’t have any idea about Android App Development? Or you have just started your journey, but you don’t know whether you are on the right path or not. So, during your initial journey, all you need is proper guidance. If you get your guide, then you are ready to go. Yes, that’s why we have prepared a complete article on this. To help you with this, we have created a practical roadmap for “6 Weeks of Android App Development – Project-Based Learning”. We will learn Android App Development by developing 6 Android Projects. As is said before in this article, Best Way to Become Android Developer – A Complete Roadmap The best way to learn Android is by developing some basic projects to some advanced projects. This article is designed in such a way that you are going to learn Android concepts each week by developing a project which is also known as “Project Bases Learning“. This learning will give you the complete guidelines to build strong conceptual knowledge in Android and achieve your Android Developer goal. So, the very first prerequisite for entering into the Android Development World is your “Dedication” and “Motivation” towards learning and building awesome Android apps. Yes, that’s true. First, find a strong reason why you are entering this world. For example, you are practicing Data Structure and Algorithms, day and night for the reason that you are going to get a job in a top product-based company. Similarly, ask yourself,” Why Android? Why not Web Development? Why not Data Science and Machine Learning? If you find the answer, then no one can stop you from learning Android App Development. The second one is Programming Language. In Android, programming is done in two languages: JAVA or Kotlin and XML(Extension Markup Language). The XML file deals with the design, presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working of buttons, variables, storing, etc (as a back-end). So all you need is to have knowledge of Java or Kotlin and XML. Note: We have prepared this tutorial in both Java and Kotlin languages. (3 Projects in Java and 3 Projects in Kotlin). Some useful learning resource links are available at GeeksforGeeks: Java Programming Language Kotlin Programming Language XML A native app is a smartphone application developed specifically for mobile operating systems like Java/Kotlin for Android and Swift for iOS. Since the application is developed within the mature ecosystem following, the technical users and the user guidelines experience provided by the OS itself, like the swipe gestures or alignment on the left side of the center, for Android and iOS. Now of course they offer the fastest and the most reliable and most responsive experience to the user. The app will have the look and feel and consistency within most native apps which are built-in into the devices. Native applications have the significant advantage of easily accessing and utilizing the user’s devices’ built-in capabilities. For example, GPS, maybe your address book or your camera, and tons of other things. Well, on the other hand, if we talk about the Hybrid applications, they are in the core website package wrapped in a native wrapper, sometimes PhoneGap or others. They look and feel like a native app but ultimately outside the basic frame of the application. They are powered by the company’s website itself. For example, sites like Facebook or Netflix do not really make sense to have a native app platform or even recompile their app for just one feature. It’s going to take a lot of time, and it’s too heavy, so it really makes sense for them just to get started with the Hybrid application. Now, hybrid apps can also use native functionality like the Camera and GPS, but via some third-party plugins, a lot of code needs to be enclosed with that, while on the other hand, the native applications are pretty easy to use and utilize those functionalities, like the Camera or your GPS. In the real industry world, what happens is, if you are starting your career in a startup company that is working on Hybrid Apps, and when the company is funded and the team size increases, then they generally switch to Native app development. Also, keep in mind that the salary point of view of Native app developers is actually a little higher and is on top of the Hybrid app developers. “Degree Doesn’t Matter“, Yes!! If you are doing B.Sc (Computer Science), BCA, or any other degree can also learn Android App Development. All you need is “Coding Skills“. In Android Development there is no need for deep knowledge in Data Structure and Algorithm, you just have to learn Java/Kotlin in advance to be a better Android App Developer. For Windows: Microsoft Windows 7/8/10 (32-bit or 64-bit) 4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator) 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image) 1280 x 800 minimum screen resolution For Mac: Mac OS X 10.10 (Yosemite) or higher, up to 10.13 (High Sierra) 4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator) 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image) 1280 x 800 minimum screen resolution For Linux: GNOME or KDE desktop. Tested on Ubuntu 14.04 LTS, Trusty Tahr (64-bit distribution capable of running 32-bit applications) 64-bit distribution capable of running 32-bit applications GNU C Library (glibc) 2.19 or later 4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator) 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image) 1280 x 800 minimum screen resolution Implement your unique idea by developing an Android App. Build an Android App for your college minor and major projects. Take freelance Android projects and earn money during your college days. Participate in Hackathon. Apply for Internships in different companies, etc. Very Very Important Point: Please don’t copy-paste the code completely. First, try to understand the logic. And play around with it by putting different logic, values, etc. This will help to increase your development skill. On day 1 of “6 Weeks of Android App Development,” you must research and read some blogs related to Android and keep yourself motivated for Android App Development. Blogs like “Best Way to Become Android Developer – A Complete Roadmap“, “Why Kotlin will replace Java for Android App Development“, “Interesting Facts About Android“, “History of Android“, “How Does Android App Work?“, etc. Then, in the 1st week of “6 Weeks of Android App Development – Project-Based Learning“, you are going to learn how to set up an Android Studio for Android App Development, How to Create a New Project in Android Studio, How to Run Your Project on a Real Device or Emulator and also you are going to develop two basic Android Apps in 1st week. In this part, you are just going to create the following two very basic android apps The very famous “Hello World” Android AppAndroid app to add two numbers The very famous “Hello World” Android App Android app to add two numbers So excited!! Let’s begin! Android Studio Setup Before setting up Android Studio, let’s install it on your system. For Windows/Mac: Install and Set up Android Studio For Linux: How to Install Android Studio on Ubuntu? So assuming that you have successfully installed the Android Studio and you are on the screen below now. So just click on the “Create New Project” and on the next screen, you can see lots of Activities(mark this word) are there. You can explore each activity, but for a beginner, let’s choose Empty Activity and move further for a beginner Here you are going to learn the 1st important concept in Android i.e Activity. You may refer to the following articles to get an idea about what an activity is in Android. Introduction to Activities in Android Different Types of Activities in Android Studio Now on the next screen Name: Write down your suitable project name. Package name: Let’s keep it by default. Save location: Choose the location where you want to save this project. Language: Choose your language between Java and Kotlin Minimum SDK (Mark this word): As you know, Android released its version at regular intervals of time and they provide some new features in the latest version which are not supported by the older versions. So you have to choose which user base you want to hit. Suppose you select “API 21: Android 5.0 (Lollipop)”, then you can see “Your app will run on approximately 94.1% of devices”. Otherwise, you can click on the “Help me choose” button also. Finally, click on the Finish button. Here you are going to learn the 2nd important concept in Android i.e SDK. You may refer to the following article to get an idea about what SDK is in Android. Android SDK and it’s Components After click on the finish button Congratulations, the first Android Studio project is ready. Initially, it shows the tip of the day, which gives tips to improve work efficiency. Before going to explore the Android Studio, get familiar with the initial screen which is shown below. For a better understanding of the Android Studio environment, it has been divided into 4 parts: 1. Menu Part: In this section, it provides options to create a new project, open an existing android studio project, a button to run the application, dropdown for selecting the desired device to run and test an application on. 2. Coding Area: This section provides for writing code for files like .xml, .java, .kt. It allows you to open multiple files at a time in different tabs, but it allows you to edit one file at a time. 3. Project Structure: This area allows us to explore every file of the project. There are various views of the structure. Android is a summarised view of the project structure hierarchy and Project is a detailed view of the project hierarchy. Have a look at the following image. 4. Current Execution Part: One of the most important parts of the Android Studio environment. It provides a detailed view of the current execution of the process or activity. It shows what errors, build outputs, logcat results, etc. All the UI layouts of the application can be found under the res/layout directory. These are of the .xml extension, responsible for building the UIs for application. Android Studio provides two types of ways of designing UI for applications. One is Text, where one needs to design the UI by hardcoding and one is the Design section that provides a convenient drag and drop mechanism for building UI. Have a look at the following image which shows how the code is being written, it goes on to show the result in the right pane. The following image shows the drag and drops environment for widgets to pick and add in the UI of the application. One can switch to the Design layout by clicking on the bottom left button, shown as the following. As we have understood the design part similarly, another main part is the coding part. In the image below you can see a file named MainActivity.kt. Yes, this is the file where you write the backend part. The logic part. For example, you want to add two numbers. So, after entering two numbers in the EditText, when the user clicks on the Button, it will give the output as the sum of two numbers. So to calculate the sum, you have to write the logic in its part. Note: If you select Language as Java during project creation, then the file name will be MainActivity.java. To run an application there are two ways to do it. One is using an emulator, another is using a physical device by connecting it through a USB cable. Refer to How to install Android Virtual Device(AVD) how to set up an android virtual device or refer to How to Run the Android App on a Real Device? setting up a real physical android device and running applications on it. Have a look at the following video on how to run your very famous “Hello World Android App” in your Android Emulator. Yes!! You have successfully built your first Android App. Now let’s built the second one “Android App to add two numbers“ Step 1: Similarly, create a new project but this time chooses Java as the programming language. Choose the name of the project by yourself. Step 2: First of all go to the XML file Now go to the Code section and write the code for adding 3 TextView, 2 EditText, and 1 Button and Assign an ID to each component. Assign margin-top, left, right for the location. Here you are going to learn other important concepts in Android i.e What’s RelativeLayout? What’s TextView? What’s EditText? and What’s Button? You may refer to the following articles to get an idea about what those are? RelativeLayout in Android TextView widget in Android with Examples EditText widget in Android with Examples Button in Android So we are going to develop the UI something like that Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Refer to the code in detail and you can change the value and play with the UI. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:layout_editor_absoluteY="81dp"> <!-- for message input first number --> <TextView android:id="@+id/textView_first_no" android:layout_width="150dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_marginTop="50dp" android:text="First number" android:textSize="20dp" /> <!-- take the input first number --> <EditText android:id="@+id/editText_first_no" android:layout_width="150dp" android:layout_height="40dp" android:layout_marginLeft="200dp" android:layout_marginTop="40dp" android:inputType="number" /> <!-- for message input second number --> <TextView android:id="@+id/textView_second_no" android:layout_width="150dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_marginTop="100dp" android:text="Second number" android:textSize="20dp" /> <!-- take input for second number --> <EditText android:id="@+id/editText_second_no" android:layout_width="150dp" android:layout_height="40dp" android:layout_marginLeft="200dp" android:layout_marginTop="90dp" android:inputType="number" tools:ignore="MissingConstraints" /> <!-- button for run add logic and view result --> <Button android:id="@+id/add_button" android:layout_width="100dp" android:layout_height="50dp" android:layout_marginLeft="110dp" android:layout_marginTop="200dp" android:text="ADD" /> <!-- Text view for result view--> <TextView android:id="@+id/textView_answer" android:layout_width="100dp" android:layout_height="25dp" android:layout_marginLeft="130dp" android:layout_marginTop="300dp" android:text="0" android:textSize="20dp" android:textStyle="bold" /> </RelativeLayout> Step 3: Working with the MainActivity.java file In this file, we are going to write the logic for adding two numbers. Let’s have a look at the following code. Don’t worry we are going to explain each line of code in detail. Java package com.example.addtwonumbers; // Each new activity has its own layout and Java files,// here we build the logic for adding two number import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // define the global variable // variable number1, number2 // for input input number // Add_button, result textView EditText number1; EditText number2; Button Add_button; TextView result; int ans = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // by ID we can use each component which id is assign in xml file number1 = (EditText) findViewById(R.id.editText_first_no); number2 = (EditText) findViewById(R.id.editText_second_no); Add_button = (Button) findViewById(R.id.add_button); result = (TextView) findViewById(R.id.textView_answer); // Add_button add clicklistener Add_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // num1 or num2 double type // get data which is in edittext, convert it to string // using parse Double convert it to Double type double num1 = Double.parseDouble(number1.getText().toString()); double num2 = Double.parseDouble(number2.getText().toString()); // add both number and store it to sum double sum = num1 + num2; // set it ot result textview result.setText(Double.toString(sum)); } }); }} Explanation: The package name of your Android app. package com.example.addtwonumbers; List of libraries used in your app. import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; Variable number1, number2 for input number (EditText). Similarly add_button variable is for our Button used in the XML code and the result variable is for TextView. EditText number1; EditText number2; Button add_button; TextView result; Remember you have assigned an ID for each component in the XML file. Yes, they are going to use it here. By ID we can use each component which id is assigned in the XML file like the following. number1 = (EditText) findViewById(R.id.editText_first_no); number2 = (EditText) findViewById(R.id.editText_second_no); add_button = (Button) findViewById(R.id.add_button); result = (TextView) findViewById(R.id.textView_answer); And at last, we add a setOnClickListener() to our Button. So when the user clicks on the Button this will give us the Output. And inside that, we have written simple logic to add those numbers. And also setText() for our output TextView. As simple as that. That’s it. add_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { double num1 = Double.parseDouble(number1.getText().toString()); double num2 = Double.parseDouble(number2.getText().toString()); double sum = num1 + num2; result.setText(Double.toString(sum)); } }); Yes, you have successfully developed an Android App which takes two numbers from the users and adds them. Now run the app as before and you can see the output as follows. Output: For the complete article please refer to this: Android App to Add Two Numbers In the 1st week, you have built a very very basic android app that takes only two numbers and adds them. And there are only some lines of code to perform this action. So you have got some basic ideas about android app development now. Let’s move toward the next project, “A Scientific Calculator Android App” which looks like this. Note that we are going to implement this project using the Kotlin language. Don’t worry Kotlin is similar to Java. Let me share some tips in Android Studio here. How to Convert Java Code to Kotlin Code in Android Studio?How to Convert Kotlin Code to Java Code in Android Studio? How to Convert Java Code to Kotlin Code in Android Studio? How to Convert Kotlin Code to Java Code in Android Studio? Use different colors in your android app. Build some complex UI in Android and make the app’s UI awesome.RelativeLayout and LinearLayout. And the difference between them.CardView RelativeLayout and LinearLayout. And the difference between them. CardView Writing some simple logic for simple math calculation. Toast in Android Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language this time. Step 2: Adding new colors to the colors.xml file Navigate to the app > res > values > colors.xml file as below screenshot. And add the below code to it for different colors. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="purple_200">#0F9D58</color> <color name="purple_500">#0F9D58</color> <color name="purple_700">#0F9D58</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <!--three different shades of black color--> <color name="blac_shade_1">#292D36</color> <color name="black_shade_2">#272B33</color> <color name="black_shade_3">#22252D</color> <color name="yellow">#ffa500</color> </resources> Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. What we have used in this file: RelativeLayout TextView CardView LinearLayout Button We have already provided you the necessary referral links for this term. You may read them carefully. Below is the code for the activity_main.xml file. You may play with these values and see how the code works. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_3" tools:context=".MainActivity"> <TextView android:id="@+id/idTVSecondary" android:layout_width="match_parent" android:layout_height="70dp" android:background="@color/black_shade_3" android:gravity="bottom" android:maxLines="1" android:padding="10dp" android:paddingTop="30dp" android:text="" android:textAlignment="viewEnd" android:textColor="@color/white" android:textSize="15sp" tools:ignore="RtlCompat" /> <TextView android:id="@+id/idTVprimary" android:layout_width="match_parent" android:layout_height="100dp" android:layout_below="@id/idTVSecondary" android:background="@color/black_shade_3" android:gravity="bottom" android:maxLines="1" android:padding="10dp" android:text="" android:textAlignment="viewEnd" android:textColor="#fff" android:textSize="50sp" tools:ignore="RtlCompat" /> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/idTVprimary" android:background="@color/blac_shade_1" app:cardCornerRadius="4dp" app:cardElevation="2dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="7" android:background="@color/blac_shade_1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="7"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/bac" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="AC" android:textColor="@color/yellow" android:textSize="15sp" tools:targetApi="lollipop" /> <Button android:id="@+id/bc" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="C" android:textColor="@color/yellow" android:textSize="15sp" /> <Button android:id="@+id/bbrac1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="(" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bbrac2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text=")" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="5"> <Button android:id="@+id/bsin" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="sin" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bcos" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="cos" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/btan" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="tan" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/blog" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="log" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bln" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="ln" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="5"> <Button android:id="@+id/bfact" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="x!" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bsquare" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="x2" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bsqrt" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="√" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/binv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="1/x" android:textAllCaps="false" android:textColor="#ffa500" android:textSize="15sp" /> <Button android:id="@+id/bdiv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="÷" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/b7" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="7" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b8" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="8" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b9" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="9" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bmul" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="×" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/b4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="4" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b5" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="5" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b6" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="6" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bminus" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="-" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/b1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="1" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="2" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="3" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bplus" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="+" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="4"> <Button android:id="@+id/bpi" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="π" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/b0" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="0" android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bdot" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="." android:textColor="#fff" android:textSize="15sp" /> <Button android:id="@+id/bequal" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="3dp" android:layout_weight="1" android:backgroundTint="@color/black_shade_2" android:padding="6dp" android:text="=" android:textColor="#ffa500" android:textSize="15sp" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout> Step 4: Working with the MainActivity.kt file So as we have discussed earlier the backend part is written in this file. The backend part means the simple logic part. And for this project, we are going to write the code in the Kotlin language. 4.1: Creating variables for our TextView and Button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button -------------------------- -------------------------- -------------------------- // similarly create variable for all the TextView // and Button you have declared in the XML file 4.2: Initializing all the variables tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) -------------------------- -------------------------- -------------------------- // similarly initialize all the variables 4.3: Adding onClickListener() to all the Buttons b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "1") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "2") -------------------------- -------------------------- // similarly Add onClickListener() to all the Buttons At last write down the dimple logic for all the calculations (Addition, multiplication, division, etc.). Let we are going to write the code for the factorial of a number. So write down the code as below: fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for our text view and button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button lateinit var bsin: Button lateinit var bcos: Button lateinit var btan: Button lateinit var blog: Button lateinit var bln: Button lateinit var bfact: Button lateinit var bsquare: Button lateinit var bsqrt: Button lateinit var binv: Button lateinit var b0: Button lateinit var b9: Button lateinit var b8: Button lateinit var b7: Button lateinit var b6: Button lateinit var b5: Button lateinit var b4: Button lateinit var b3: Button lateinit var b2: Button lateinit var b1: Button lateinit var bpi: Button lateinit var bmul: Button lateinit var bminus: Button lateinit var bplus: Button lateinit var bequal: Button lateinit var bdot: Button lateinit var bdiv: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all our variables. tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) bbrac1 = findViewById(R.id.bbrac1) bbrac2 = findViewById(R.id.bbrac2) bsin = findViewById(R.id.bsin) bcos = findViewById(R.id.bcos) btan = findViewById(R.id.btan) blog = findViewById(R.id.blog) bln = findViewById(R.id.bln) bfact = findViewById(R.id.bfact) bsquare = findViewById(R.id.bsquare) bsqrt = findViewById(R.id.bsqrt) binv = findViewById(R.id.binv) b0 = findViewById(R.id.b0) b9 = findViewById(R.id.b9) b8 = findViewById(R.id.b8) b7 = findViewById(R.id.b7) b6 = findViewById(R.id.b6) b5 = findViewById(R.id.b5) b4 = findViewById(R.id.b4) b3 = findViewById(R.id.b3) b2 = findViewById(R.id.b2) b1 = findViewById(R.id.b1) bpi = findViewById(R.id.bpi) bmul = findViewById(R.id.bmul) bminus = findViewById(R.id.bminus) bplus = findViewById(R.id.bplus) bequal = findViewById(R.id.bequal) bdot = findViewById(R.id.bdot) bdiv = findViewById(R.id.bdiv) // adding on click listener to our all buttons. b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "1") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "2") } b3.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "3") } b4.setOnClickListener { tvMain.text = (tvMain.text.toString() + "4") } b5.setOnClickListener { tvMain.text = (tvMain.text.toString() + "5") } b6.setOnClickListener { tvMain.text = (tvMain.text.toString() + "6") } b7.setOnClickListener { tvMain.text = (tvMain.text.toString() + "7") } b8.setOnClickListener { tvMain.text = (tvMain.text.toString() + "8") } b9.setOnClickListener { tvMain.text = (tvMain.text.toString() + "9") } b0.setOnClickListener { tvMain.text = (tvMain.text.toString() + "0") } bdot.setOnClickListener { tvMain.text = (tvMain.text.toString() + ".") } bplus.setOnClickListener { tvMain.text = (tvMain.text.toString() + "+") } bdiv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "/") } bbrac1.setOnClickListener { tvMain.text = (tvMain.text.toString() + "(") } bbrac2.setOnClickListener { tvMain.text = (tvMain.text.toString() + ")") } bpi.setOnClickListener { // on clicking on pi button we are adding // pi value as 3.142 to our current value. tvMain.text = (tvMain.text.toString() + "3.142") tvsec.text = (bpi.text.toString()) } bsin.setOnClickListener { tvMain.text = (tvMain.text.toString() + "sin") } bcos.setOnClickListener { tvMain.text = (tvMain.text.toString() + "cos") } btan.setOnClickListener { tvMain.text = (tvMain.text.toString() + "tan") } binv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "^" + "(-1)") } bln.setOnClickListener { tvMain.text = (tvMain.text.toString() + "ln") } blog.setOnClickListener { tvMain.text = (tvMain.text.toString() + "log") } bminus.setOnClickListener { // on clicking on minus we are checking if // the user has already a minus operation on screen. // if minus operation is already present // then we will not do anything. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("-")) { tvMain.text = (tvMain.text.toString() + "-") } } bmul.setOnClickListener { // if mul sign is not present in our // text view then only we are adding // the multiplication operator to it. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("*")) { tvMain.text = (tvMain.text.toString() + "*") } } bsqrt.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { val str: String = tvMain.text.toString() // on below line we are calculation // square root of the given number. val r = Math.sqrt(str.toDouble()) // on below line we are converting our double // to string and then setting it to text view. val result = r.toString() tvMain.setText(result) } } bequal.setOnClickListener { val str: String = tvMain.text.toString() // on below line we are calling an evaluate // method to calculate the value of expressions. val result: Double = evaluate(str) // on below line we are getting result // and setting it to text view. val r = result.toString() tvMain.setText(r) tvsec.text = str } bac.setOnClickListener { // on clicking on ac button we are clearing // our primary and secondary text view. tvMain.setText("") tvsec.setText("") } bc.setOnClickListener { // on clicking on c button we are clearing // the last character by checking the length. var str: String = tvMain.text.toString() if (!str.equals("")) { str = str.substring(0, str.length - 1) tvMain.text = str } } bsquare.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting the expression and then calculating the square of the number val d: Double = tvMain.getText().toString().toDouble() // on below line we are calculating the square. val square = d * d // after calculating the square we // are setting it to text view. tvMain.setText(square.toString()) // on below line we are setting // the d to secondary text view. tvsec.text = "$d2" } } bfact.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting int value // and calculating the factorial value of the entered number. val value: Int = tvMain.text.toString().toInt() val fact: Int = factorial(value) tvMain.setText(fact.toString()) tvsec.text = "$value`!" } } } fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } fun evaluate(str: String): Double { return object : Any() { // on below line we are creating variable // for tracking the position and char pos. var pos = -1 var ch = 0 // below method is for moving to next character. fun nextChar() { // on below line we are incrementing our position // and moving it to next position. ch = if (++pos < str.length) str[pos].toInt() else -1 } // this method is use to check the extra space // present int the expression and removing it. fun eat(charToEat: Int): Boolean { while (ch == ' '.toInt()) nextChar() // on below line we are checking the char pos // if both is equal then we are returning it to true. if (ch == charToEat) { nextChar() return true } return false } // below method is to parse our // expression and to get the ans // in this we are calling a parse // expression method to calculate the value. fun parse(): Double { nextChar() val x = parseExpression() if (pos < str.length) throw RuntimeException("Unexpected: " + ch.toChar()) return x } // in this method we will only perform addition and // subtraction operation on the expression. fun parseExpression(): Double { var x = parseTerm() while (true) { if (eat('+'.toInt())) x += parseTerm() // addition else if (eat('-'.toInt())) x -= parseTerm() // subtraction else return x } } // in below method we will perform // only multiplication and division operation. fun parseTerm(): Double { var x = parseFactor() while (true) { if (eat('*'.toInt())) x *= parseFactor() // multiplication else if (eat('/'.toInt())) x /= parseFactor() // division else return x } } // below method is use to parse the factor fun parseFactor(): Double { //on below line we are checking for addition // and subtraction and performing unary operations. if (eat('+'.toInt())) return parseFactor() // unary plus if (eat('-'.toInt())) return -parseFactor() // unary minus // creating a double variable for ans. var x: Double // on below line we are creating // a variable for position. val startPos = pos // on below line we are checking // for opening and closing parenthesis. if (eat('('.toInt())) { // parentheses x = parseExpression() eat(')'.toInt()) } else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) { // numbers while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar() // on below line we are getting sub string from our string using start and pos. x = str.substring(startPos, pos).toDouble() } else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) { // on below function we are checking for the operator in our expression. while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar() val func = str.substring(startPos, pos) // calling a method to parse our factor. x = parseFactor() // on below line we are checking for square root. x = if (func == "sqrt") Math.sqrt(x) // on below line we are checking for sin function // and calculating sin function using Math class. else if (func == "sin") Math.sin( Math.toRadians(x) // on below line we are calculating the cos value ) else if (func == "cos") Math.cos( Math.toRadians(x) // on below line we are calculating // the tan value of our expression. ) else if (func == "tan") Math.tan(Math.toRadians(x)) // on below line we are calculating // log value of the expression. else if (func == "log") Math.log10(x) // on below line we are calculating // ln value of expression. else if (func == "ln") Math.log(x) // f we get any error then // we simply return the exception. else throw RuntimeException( "Unknown function: $func" ) } else { // if the condition not satisfy then we are returning the exception throw RuntimeException("Unexpected: " + ch.toChar()) } // on below line we are calculating the power of the expression. if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation return x } // at last calling a parse for our expression. }.parse() }} Output: For the complete article refer to this: How to Make a Scientific Calculator Android App using Android Studio? You may also refer to the following video: YouTubeGeeksforGeeks500K subscribersHow to Make a Scientific Calculator Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:10:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gwOL-4V_sNw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> In the 3rd week of Android App Development, we will learn the following very important concepts What’s REST APIVolley Library in AndroidWhat’s a JSON file?JSON Parsing in Android using Volley Library What’s REST API Volley Library in Android What’s a JSON file? JSON Parsing in Android using Volley Library 1. What’ REST API REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services simply and flexibly without having any processing. To read more refer to this article: Introduction to REST API 2. Volley Library in Android Volley is an HTTP library that makes networking very easy and fast, for Android apps. It was developed by Google and introduced during Google I/O 2013. It was developed because there is an absence in Android SDK, of a networking class capable of working without interfering with the user experience. Although Volley is a part of the Android Open Source Project(AOSP), Google announced in January 2017 that Volley will move to a standalone library. It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again. To read more refer to this article: Volley Library in Android 3. What’s a JSON file? JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript. The official media type for the JSON is application/json and to save those file .json extension. To read more refer to this article: What’s a JSON file? 4. JSON Parsing in Android using Volley Library Refer to this article for proper implementation: JSON Parsing in Android using Volley Library So after learning these important concepts, we will develop an intermediate project this week and the name of the project is “Build COVID-19 Tracker Android App“. To build this complete project please refer to this article: How to Build a COVID-19 Tracker Android App. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. YouTubeGeeksforGeeks500K subscribersHow to Make a Covid-19 Tracker Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 44:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=opCW91zYJcI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> When developers work on a real mobile application whose nature is dynamic and will expand its features according to the user’s need, then it is not possible to write core logic in activities or fragments. To structure the project’s code and to give it a modular design(separated code parts), architecture patterns are applied to separate the concerns. The most popular android architectures used by developers are the following: MVC (Model — View — Controller)MVP (Model — View — Presenter)MVVM (Model — View — ViewModel) MVC (Model — View — Controller) MVP (Model — View — Presenter) MVVM (Model — View — ViewModel) So in the 4th week are going to learn another very important concept i.e Android Architecture Patterns. Please read out the following articles and try to explore as much as you because these concepts are very very useful to become a successful Android Developer. Android Architecture Patterns MVC (Model — View — Controller) MVP (Model — View — Presenter) MVVM (Model — View — ViewModel) So using these concepts, this week we are going to develop another application “Build a Simple Note App using Android Architecture Pattern”. To build this complete project please refer to this article: How to Build a Simple Note Android App using MVVM and Room Database. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. https://youtu.be/D2F5t-phP04 Firebase! I think you have heard this word. Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides services to android, ios, web, and unity. It provides cloud storage. It uses NoSQL for the database for the storage of data. To read more refer to this article: Introduction to Firebase So in the 5th week of Android App Development, we are going to explore the Firebase database and how to perform basic authentication and CRUD (Create, Read, Update, Delete) operation with Firebase. To build this complete project please refer to this article: User Authentication and CRUD Operation with Firebase Realtime Database in Android. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. YouTubeGeeksforGeeks500K subscribersUser Authentication and CRUD Operation with Firebase Realtime Database in Android | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:15:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=-Gvpf8tXpbc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> You may also refer to this section to know more about Firebase + Android stuff. In the last week of Android App Development, we are going to develop an advanced Android App using multiple advanced concepts. We are going to build a Grocery Android App whose output is like the following. So in this project, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down the grocery items that you are going to purchase, by doing this you can’t forget any items that you want to purchase. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. In this project, we are using MVVM (Model View ViewModel) for architectural patterns, Room for database, Coroutines and RecyclerView to display the list of items. To build this complete project please refer to this article: How to Build a Grocery Android App using MVVM and Room Database. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. YouTubeGeeksforGeeks500K subscribersBuild a Grocery Android App using MVVM and Room Database in Kotlin | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:02:06•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=vdcLb_Y71Ic" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Must Refer to the Following Tutorial in Android Android Tutorial Android Studio Tutorial Android Projects Tutorial sagartomar9927 kk773572498 Android GBlog Java Kotlin Project Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Roadmap to Become a Web Developer in 2022 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 24728, "s": 24700, "text": "\n18 Feb, 2022" }, { "code": null, "e": 25453, "s": 24728, "text": "Are you among the ones who want to learn Android App Development from the beginning? Are you someone who doesn’t have any idea about Android App Development? Or you have just started your journey, but you don’t know whether you are on the right path or not. So, during your initial journey, all you need is proper guidance. If you get your guide, then you are ready to go. Yes, that’s why we have prepared a complete article on this. To help you with this, we have created a practical roadmap for “6 Weeks of Android App Development – Project-Based Learning”. We will learn Android App Development by developing 6 Android Projects. As is said before in this article, Best Way to Become Android Developer – A Complete Roadmap" }, { "code": null, "e": 25547, "s": 25453, "text": "The best way to learn Android is by developing some basic projects to some advanced projects." }, { "code": null, "e": 25856, "s": 25547, "text": "This article is designed in such a way that you are going to learn Android concepts each week by developing a project which is also known as “Project Bases Learning“. This learning will give you the complete guidelines to build strong conceptual knowledge in Android and achieve your Android Developer goal. " }, { "code": null, "e": 26457, "s": 25856, "text": "So, the very first prerequisite for entering into the Android Development World is your “Dedication” and “Motivation” towards learning and building awesome Android apps. Yes, that’s true. First, find a strong reason why you are entering this world. For example, you are practicing Data Structure and Algorithms, day and night for the reason that you are going to get a job in a top product-based company. Similarly, ask yourself,” Why Android? Why not Web Development? Why not Data Science and Machine Learning? If you find the answer, then no one can stop you from learning Android App Development. " }, { "code": null, "e": 26855, "s": 26457, "text": "The second one is Programming Language. In Android, programming is done in two languages: JAVA or Kotlin and XML(Extension Markup Language). The XML file deals with the design, presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working of buttons, variables, storing, etc (as a back-end). So all you need is to have knowledge of Java or Kotlin and XML. " }, { "code": null, "e": 26975, "s": 26855, "text": "Note: We have prepared this tutorial in both Java and Kotlin languages. (3 Projects in Java and 3 Projects in Kotlin). " }, { "code": null, "e": 27043, "s": 26975, "text": "Some useful learning resource links are available at GeeksforGeeks:" }, { "code": null, "e": 27070, "s": 27043, "text": "Java Programming Language " }, { "code": null, "e": 27098, "s": 27070, "text": "Kotlin Programming Language" }, { "code": null, "e": 27102, "s": 27098, "text": "XML" }, { "code": null, "e": 27918, "s": 27102, "text": "A native app is a smartphone application developed specifically for mobile operating systems like Java/Kotlin for Android and Swift for iOS. Since the application is developed within the mature ecosystem following, the technical users and the user guidelines experience provided by the OS itself, like the swipe gestures or alignment on the left side of the center, for Android and iOS. Now of course they offer the fastest and the most reliable and most responsive experience to the user. The app will have the look and feel and consistency within most native apps which are built-in into the devices. Native applications have the significant advantage of easily accessing and utilizing the user’s devices’ built-in capabilities. For example, GPS, maybe your address book or your camera, and tons of other things. " }, { "code": null, "e": 28808, "s": 27918, "text": "Well, on the other hand, if we talk about the Hybrid applications, they are in the core website package wrapped in a native wrapper, sometimes PhoneGap or others. They look and feel like a native app but ultimately outside the basic frame of the application. They are powered by the company’s website itself. For example, sites like Facebook or Netflix do not really make sense to have a native app platform or even recompile their app for just one feature. It’s going to take a lot of time, and it’s too heavy, so it really makes sense for them just to get started with the Hybrid application. Now, hybrid apps can also use native functionality like the Camera and GPS, but via some third-party plugins, a lot of code needs to be enclosed with that, while on the other hand, the native applications are pretty easy to use and utilize those functionalities, like the Camera or your GPS. " }, { "code": null, "e": 29200, "s": 28808, "text": "In the real industry world, what happens is, if you are starting your career in a startup company that is working on Hybrid Apps, and when the company is funded and the team size increases, then they generally switch to Native app development. Also, keep in mind that the salary point of view of Native app developers is actually a little higher and is on top of the Hybrid app developers. " }, { "code": null, "e": 29548, "s": 29200, "text": "“Degree Doesn’t Matter“, Yes!! If you are doing B.Sc (Computer Science), BCA, or any other degree can also learn Android App Development. All you need is “Coding Skills“. In Android Development there is no need for deep knowledge in Data Structure and Algorithm, you just have to learn Java/Kotlin in advance to be a better Android App Developer. " }, { "code": null, "e": 29561, "s": 29548, "text": "For Windows:" }, { "code": null, "e": 29605, "s": 29561, "text": "Microsoft Windows 7/8/10 (32-bit or 64-bit)" }, { "code": null, "e": 29681, "s": 29605, "text": "4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)" }, { "code": null, "e": 29807, "s": 29681, "text": "2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image)" }, { "code": null, "e": 29844, "s": 29807, "text": "1280 x 800 minimum screen resolution" }, { "code": null, "e": 29854, "s": 29844, "text": "For Mac: " }, { "code": null, "e": 29917, "s": 29854, "text": "Mac OS X 10.10 (Yosemite) or higher, up to 10.13 (High Sierra)" }, { "code": null, "e": 29993, "s": 29917, "text": "4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)" }, { "code": null, "e": 30119, "s": 29993, "text": "2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image)" }, { "code": null, "e": 30156, "s": 30119, "text": "1280 x 800 minimum screen resolution" }, { "code": null, "e": 30167, "s": 30156, "text": "For Linux:" }, { "code": null, "e": 30290, "s": 30167, "text": "GNOME or KDE desktop. Tested on Ubuntu 14.04 LTS, Trusty Tahr (64-bit distribution capable of running 32-bit applications)" }, { "code": null, "e": 30349, "s": 30290, "text": "64-bit distribution capable of running 32-bit applications" }, { "code": null, "e": 30385, "s": 30349, "text": "GNU C Library (glibc) 2.19 or later" }, { "code": null, "e": 30461, "s": 30385, "text": "4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)" }, { "code": null, "e": 30587, "s": 30461, "text": "2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image)" }, { "code": null, "e": 30624, "s": 30587, "text": "1280 x 800 minimum screen resolution" }, { "code": null, "e": 30681, "s": 30624, "text": "Implement your unique idea by developing an Android App." }, { "code": null, "e": 30745, "s": 30681, "text": "Build an Android App for your college minor and major projects." }, { "code": null, "e": 30818, "s": 30745, "text": "Take freelance Android projects and earn money during your college days." }, { "code": null, "e": 30844, "s": 30818, "text": "Participate in Hackathon." }, { "code": null, "e": 30895, "s": 30844, "text": "Apply for Internships in different companies, etc." }, { "code": null, "e": 31119, "s": 30895, "text": "Very Very Important Point: Please don’t copy-paste the code completely. First, try to understand the logic. And play around with it by putting different logic, values, etc. This will help to increase your development skill." }, { "code": null, "e": 31508, "s": 31119, "text": "On day 1 of “6 Weeks of Android App Development,” you must research and read some blogs related to Android and keep yourself motivated for Android App Development. Blogs like “Best Way to Become Android Developer – A Complete Roadmap“, “Why Kotlin will replace Java for Android App Development“, “Interesting Facts About Android“, “History of Android“, “How Does Android App Work?“, etc. " }, { "code": null, "e": 31935, "s": 31508, "text": "Then, in the 1st week of “6 Weeks of Android App Development – Project-Based Learning“, you are going to learn how to set up an Android Studio for Android App Development, How to Create a New Project in Android Studio, How to Run Your Project on a Real Device or Emulator and also you are going to develop two basic Android Apps in 1st week. In this part, you are just going to create the following two very basic android apps" }, { "code": null, "e": 32008, "s": 31935, "text": "The very famous “Hello World” Android AppAndroid app to add two numbers " }, { "code": null, "e": 32050, "s": 32008, "text": "The very famous “Hello World” Android App" }, { "code": null, "e": 32082, "s": 32050, "text": "Android app to add two numbers " }, { "code": null, "e": 32108, "s": 32082, "text": "So excited!! Let’s begin!" }, { "code": null, "e": 32129, "s": 32108, "text": "Android Studio Setup" }, { "code": null, "e": 32196, "s": 32129, "text": "Before setting up Android Studio, let’s install it on your system." }, { "code": null, "e": 32247, "s": 32196, "text": "For Windows/Mac: Install and Set up Android Studio" }, { "code": null, "e": 32299, "s": 32247, "text": "For Linux: How to Install Android Studio on Ubuntu?" }, { "code": null, "e": 32404, "s": 32299, "text": "So assuming that you have successfully installed the Android Studio and you are on the screen below now." }, { "code": null, "e": 32640, "s": 32404, "text": "So just click on the “Create New Project” and on the next screen, you can see lots of Activities(mark this word) are there. You can explore each activity, but for a beginner, let’s choose Empty Activity and move further for a beginner " }, { "code": null, "e": 32813, "s": 32640, "text": "Here you are going to learn the 1st important concept in Android i.e Activity. You may refer to the following articles to get an idea about what an activity is in Android. " }, { "code": null, "e": 32854, "s": 32813, "text": "Introduction to Activities in Android " }, { "code": null, "e": 32902, "s": 32854, "text": "Different Types of Activities in Android Studio" }, { "code": null, "e": 32926, "s": 32902, "text": "Now on the next screen " }, { "code": null, "e": 32971, "s": 32926, "text": "Name: Write down your suitable project name." }, { "code": null, "e": 33011, "s": 32971, "text": "Package name: Let’s keep it by default." }, { "code": null, "e": 33083, "s": 33011, "text": "Save location: Choose the location where you want to save this project." }, { "code": null, "e": 33138, "s": 33083, "text": "Language: Choose your language between Java and Kotlin" }, { "code": null, "e": 33585, "s": 33138, "text": "Minimum SDK (Mark this word): As you know, Android released its version at regular intervals of time and they provide some new features in the latest version which are not supported by the older versions. So you have to choose which user base you want to hit. Suppose you select “API 21: Android 5.0 (Lollipop)”, then you can see “Your app will run on approximately 94.1% of devices”. Otherwise, you can click on the “Help me choose” button also." }, { "code": null, "e": 33622, "s": 33585, "text": "Finally, click on the Finish button." }, { "code": null, "e": 33780, "s": 33622, "text": "Here you are going to learn the 2nd important concept in Android i.e SDK. You may refer to the following article to get an idea about what SDK is in Android." }, { "code": null, "e": 33813, "s": 33780, "text": "Android SDK and it’s Components " }, { "code": null, "e": 34094, "s": 33813, "text": "After click on the finish button Congratulations, the first Android Studio project is ready. Initially, it shows the tip of the day, which gives tips to improve work efficiency. Before going to explore the Android Studio, get familiar with the initial screen which is shown below." }, { "code": null, "e": 34190, "s": 34094, "text": "For a better understanding of the Android Studio environment, it has been divided into 4 parts:" }, { "code": null, "e": 34417, "s": 34190, "text": "1. Menu Part: In this section, it provides options to create a new project, open an existing android studio project, a button to run the application, dropdown for selecting the desired device to run and test an application on." }, { "code": null, "e": 34617, "s": 34417, "text": "2. Coding Area: This section provides for writing code for files like .xml, .java, .kt. It allows you to open multiple files at a time in different tabs, but it allows you to edit one file at a time." }, { "code": null, "e": 34896, "s": 34617, "text": "3. Project Structure: This area allows us to explore every file of the project. There are various views of the structure. Android is a summarised view of the project structure hierarchy and Project is a detailed view of the project hierarchy. Have a look at the following image." }, { "code": null, "e": 35129, "s": 34896, "text": "4. Current Execution Part: One of the most important parts of the Android Studio environment. It provides a detailed view of the current execution of the process or activity. It shows what errors, build outputs, logcat results, etc." }, { "code": null, "e": 35656, "s": 35129, "text": "All the UI layouts of the application can be found under the res/layout directory. These are of the .xml extension, responsible for building the UIs for application. Android Studio provides two types of ways of designing UI for applications. One is Text, where one needs to design the UI by hardcoding and one is the Design section that provides a convenient drag and drop mechanism for building UI. Have a look at the following image which shows how the code is being written, it goes on to show the result in the right pane." }, { "code": null, "e": 35870, "s": 35656, "text": "The following image shows the drag and drops environment for widgets to pick and add in the UI of the application. One can switch to the Design layout by clicking on the bottom left button, shown as the following." }, { "code": null, "e": 36333, "s": 35870, "text": "As we have understood the design part similarly, another main part is the coding part. In the image below you can see a file named MainActivity.kt. Yes, this is the file where you write the backend part. The logic part. For example, you want to add two numbers. So, after entering two numbers in the EditText, when the user clicks on the Button, it will give the output as the sum of two numbers. So to calculate the sum, you have to write the logic in its part." }, { "code": null, "e": 36441, "s": 36333, "text": "Note: If you select Language as Java during project creation, then the file name will be MainActivity.java." }, { "code": null, "e": 36932, "s": 36441, "text": "To run an application there are two ways to do it. One is using an emulator, another is using a physical device by connecting it through a USB cable. Refer to How to install Android Virtual Device(AVD) how to set up an android virtual device or refer to How to Run the Android App on a Real Device? setting up a real physical android device and running applications on it. Have a look at the following video on how to run your very famous “Hello World Android App” in your Android Emulator." }, { "code": null, "e": 37054, "s": 36932, "text": "Yes!! You have successfully built your first Android App. Now let’s built the second one “Android App to add two numbers“" }, { "code": null, "e": 37194, "s": 37054, "text": "Step 1: Similarly, create a new project but this time chooses Java as the programming language. Choose the name of the project by yourself." }, { "code": null, "e": 37234, "s": 37194, "text": "Step 2: First of all go to the XML file" }, { "code": null, "e": 37413, "s": 37234, "text": "Now go to the Code section and write the code for adding 3 TextView, 2 EditText, and 1 Button and Assign an ID to each component. Assign margin-top, left, right for the location." }, { "code": null, "e": 37634, "s": 37413, "text": "Here you are going to learn other important concepts in Android i.e What’s RelativeLayout? What’s TextView? What’s EditText? and What’s Button? You may refer to the following articles to get an idea about what those are?" }, { "code": null, "e": 37660, "s": 37634, "text": "RelativeLayout in Android" }, { "code": null, "e": 37701, "s": 37660, "text": "TextView widget in Android with Examples" }, { "code": null, "e": 37743, "s": 37701, "text": "EditText widget in Android with Examples" }, { "code": null, "e": 37761, "s": 37743, "text": "Button in Android" }, { "code": null, "e": 37815, "s": 37761, "text": "So we are going to develop the UI something like that" }, { "code": null, "e": 38019, "s": 37815, "text": "Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Refer to the code in detail and you can change the value and play with the UI. " }, { "code": null, "e": 38023, "s": 38019, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:layout_editor_absoluteY=\"81dp\"> <!-- for message input first number --> <TextView android:id=\"@+id/textView_first_no\" android:layout_width=\"150dp\" android:layout_height=\"25dp\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"50dp\" android:text=\"First number\" android:textSize=\"20dp\" /> <!-- take the input first number --> <EditText android:id=\"@+id/editText_first_no\" android:layout_width=\"150dp\" android:layout_height=\"40dp\" android:layout_marginLeft=\"200dp\" android:layout_marginTop=\"40dp\" android:inputType=\"number\" /> <!-- for message input second number --> <TextView android:id=\"@+id/textView_second_no\" android:layout_width=\"150dp\" android:layout_height=\"25dp\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"100dp\" android:text=\"Second number\" android:textSize=\"20dp\" /> <!-- take input for second number --> <EditText android:id=\"@+id/editText_second_no\" android:layout_width=\"150dp\" android:layout_height=\"40dp\" android:layout_marginLeft=\"200dp\" android:layout_marginTop=\"90dp\" android:inputType=\"number\" tools:ignore=\"MissingConstraints\" /> <!-- button for run add logic and view result --> <Button android:id=\"@+id/add_button\" android:layout_width=\"100dp\" android:layout_height=\"50dp\" android:layout_marginLeft=\"110dp\" android:layout_marginTop=\"200dp\" android:text=\"ADD\" /> <!-- Text view for result view--> <TextView android:id=\"@+id/textView_answer\" android:layout_width=\"100dp\" android:layout_height=\"25dp\" android:layout_marginLeft=\"130dp\" android:layout_marginTop=\"300dp\" android:text=\"0\" android:textSize=\"20dp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 40234, "s": 38023, "text": null }, { "code": null, "e": 40286, "s": 40238, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 40465, "s": 40288, "text": "In this file, we are going to write the logic for adding two numbers. Let’s have a look at the following code. Don’t worry we are going to explain each line of code in detail. " }, { "code": null, "e": 40472, "s": 40467, "text": "Java" }, { "code": "package com.example.addtwonumbers; // Each new activity has its own layout and Java files,// here we build the logic for adding two number import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // define the global variable // variable number1, number2 // for input input number // Add_button, result textView EditText number1; EditText number2; Button Add_button; TextView result; int ans = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // by ID we can use each component which id is assign in xml file number1 = (EditText) findViewById(R.id.editText_first_no); number2 = (EditText) findViewById(R.id.editText_second_no); Add_button = (Button) findViewById(R.id.add_button); result = (TextView) findViewById(R.id.textView_answer); // Add_button add clicklistener Add_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // num1 or num2 double type // get data which is in edittext, convert it to string // using parse Double convert it to Double type double num1 = Double.parseDouble(number1.getText().toString()); double num2 = Double.parseDouble(number2.getText().toString()); // add both number and store it to sum double sum = num1 + num2; // set it ot result textview result.setText(Double.toString(sum)); } }); }}", "e": 42284, "s": 40472, "text": null }, { "code": null, "e": 42301, "s": 42288, "text": "Explanation:" }, { "code": null, "e": 42342, "s": 42303, "text": "The package name of your Android app. " }, { "code": null, "e": 42379, "s": 42344, "text": "package com.example.addtwonumbers;" }, { "code": null, "e": 42417, "s": 42381, "text": "List of libraries used in your app." }, { "code": null, "e": 42615, "s": 42419, "text": "import android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\nimport androidx.appcompat.app.AppCompatActivity;" }, { "code": null, "e": 42782, "s": 42617, "text": "Variable number1, number2 for input number (EditText). Similarly add_button variable is for our Button used in the XML code and the result variable is for TextView." }, { "code": null, "e": 42856, "s": 42784, "text": "EditText number1;\nEditText number2;\nButton add_button;\nTextView result;" }, { "code": null, "e": 43052, "s": 42858, "text": "Remember you have assigned an ID for each component in the XML file. Yes, they are going to use it here. By ID we can use each component which id is assigned in the XML file like the following." }, { "code": null, "e": 43282, "s": 43054, "text": "number1 = (EditText) findViewById(R.id.editText_first_no);\nnumber2 = (EditText) findViewById(R.id.editText_second_no);\nadd_button = (Button) findViewById(R.id.add_button);\nresult = (TextView) findViewById(R.id.textView_answer);" }, { "code": null, "e": 43553, "s": 43284, "text": "And at last, we add a setOnClickListener() to our Button. So when the user clicks on the Button this will give us the Output. And inside that, we have written simple logic to add those numbers. And also setText() for our output TextView. As simple as that. That’s it. " }, { "code": null, "e": 43926, "s": 43555, "text": "add_button.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n\n double num1 = Double.parseDouble(number1.getText().toString());\n double num2 = Double.parseDouble(number2.getText().toString());\n double sum = num1 + num2;\n result.setText(Double.toString(sum));\n }\n});" }, { "code": null, "e": 44100, "s": 43928, "text": "Yes, you have successfully developed an Android App which takes two numbers from the users and adds them. Now run the app as before and you can see the output as follows. " }, { "code": null, "e": 44110, "s": 44102, "text": "Output:" }, { "code": null, "e": 44192, "s": 44114, "text": "For the complete article please refer to this: Android App to Add Two Numbers" }, { "code": null, "e": 44529, "s": 44196, "text": "In the 1st week, you have built a very very basic android app that takes only two numbers and adds them. And there are only some lines of code to perform this action. So you have got some basic ideas about android app development now. Let’s move toward the next project, “A Scientific Calculator Android App” which looks like this. " }, { "code": null, "e": 44696, "s": 44533, "text": "Note that we are going to implement this project using the Kotlin language. Don’t worry Kotlin is similar to Java. Let me share some tips in Android Studio here. " }, { "code": null, "e": 44815, "s": 44698, "text": "How to Convert Java Code to Kotlin Code in Android Studio?How to Convert Kotlin Code to Java Code in Android Studio?" }, { "code": null, "e": 44874, "s": 44815, "text": "How to Convert Java Code to Kotlin Code in Android Studio?" }, { "code": null, "e": 44933, "s": 44874, "text": "How to Convert Kotlin Code to Java Code in Android Studio?" }, { "code": null, "e": 44975, "s": 44933, "text": "Use different colors in your android app." }, { "code": null, "e": 45112, "s": 44975, "text": "Build some complex UI in Android and make the app’s UI awesome.RelativeLayout and LinearLayout. And the difference between them.CardView" }, { "code": null, "e": 45178, "s": 45112, "text": "RelativeLayout and LinearLayout. And the difference between them." }, { "code": null, "e": 45187, "s": 45178, "text": "CardView" }, { "code": null, "e": 45242, "s": 45187, "text": "Writing some simple logic for simple math calculation." }, { "code": null, "e": 45260, "s": 45242, "text": "Toast in Android " }, { "code": null, "e": 45291, "s": 45262, "text": "Step 1: Create a New Project" }, { "code": null, "e": 45467, "s": 45293, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language this time." }, { "code": null, "e": 45519, "s": 45469, "text": "Step 2: Adding new colors to the colors.xml file " }, { "code": null, "e": 45595, "s": 45521, "text": "Navigate to the app > res > values > colors.xml file as below screenshot." }, { "code": null, "e": 45651, "s": 45599, "text": "And add the below code to it for different colors. " }, { "code": null, "e": 45657, "s": 45653, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"purple_200\">#0F9D58</color> <color name=\"purple_500\">#0F9D58</color> <color name=\"purple_700\">#0F9D58</color> <color name=\"teal_200\">#FF03DAC5</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color> <!--three different shades of black color--> <color name=\"blac_shade_1\">#292D36</color> <color name=\"black_shade_2\">#272B33</color> <color name=\"black_shade_3\">#22252D</color> <color name=\"yellow\">#ffa500</color> </resources>", "e": 46264, "s": 45657, "text": null }, { "code": null, "e": 46316, "s": 46268, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 46443, "s": 46318, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. What we have used in this file:" }, { "code": null, "e": 46460, "s": 46445, "text": "RelativeLayout" }, { "code": null, "e": 46469, "s": 46460, "text": "TextView" }, { "code": null, "e": 46478, "s": 46469, "text": "CardView" }, { "code": null, "e": 46491, "s": 46478, "text": "LinearLayout" }, { "code": null, "e": 46498, "s": 46491, "text": "Button" }, { "code": null, "e": 46711, "s": 46500, "text": "We have already provided you the necessary referral links for this term. You may read them carefully. Below is the code for the activity_main.xml file. You may play with these values and see how the code works." }, { "code": null, "e": 46717, "s": 46713, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_3\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/idTVSecondary\" android:layout_width=\"match_parent\" android:layout_height=\"70dp\" android:background=\"@color/black_shade_3\" android:gravity=\"bottom\" android:maxLines=\"1\" android:padding=\"10dp\" android:paddingTop=\"30dp\" android:text=\"\" android:textAlignment=\"viewEnd\" android:textColor=\"@color/white\" android:textSize=\"15sp\" tools:ignore=\"RtlCompat\" /> <TextView android:id=\"@+id/idTVprimary\" android:layout_width=\"match_parent\" android:layout_height=\"100dp\" android:layout_below=\"@id/idTVSecondary\" android:background=\"@color/black_shade_3\" android:gravity=\"bottom\" android:maxLines=\"1\" android:padding=\"10dp\" android:text=\"\" android:textAlignment=\"viewEnd\" android:textColor=\"#fff\" android:textSize=\"50sp\" tools:ignore=\"RtlCompat\" /> <androidx.cardview.widget.CardView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_below=\"@id/idTVprimary\" android:background=\"@color/blac_shade_1\" app:cardCornerRadius=\"4dp\" app:cardElevation=\"2dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"7\" android:background=\"@color/blac_shade_1\" android:orientation=\"vertical\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:weightSum=\"7\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/bac\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"AC\" android:textColor=\"@color/yellow\" android:textSize=\"15sp\" tools:targetApi=\"lollipop\" /> <Button android:id=\"@+id/bc\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"C\" android:textColor=\"@color/yellow\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bbrac1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"(\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bbrac2\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\")\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <Button android:id=\"@+id/bsin\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"sin\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bcos\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"cos\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/btan\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"tan\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/blog\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"log\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bln\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"ln\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <Button android:id=\"@+id/bfact\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"x!\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bsquare\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"x2\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bsqrt\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"√\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/binv\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"1/x\" android:textAllCaps=\"false\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bdiv\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"÷\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/b7\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"7\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b8\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"8\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b9\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"9\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bmul\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"×\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/b4\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"4\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b5\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"5\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b6\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"6\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bminus\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"-\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/b1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"1\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b2\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"2\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b3\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"3\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bplus\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"+\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:orientation=\"horizontal\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <Button android:id=\"@+id/bpi\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"π\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/b0\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"0\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bdot\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\".\" android:textColor=\"#fff\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/bequal\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"3dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/black_shade_2\" android:padding=\"6dp\" android:text=\"=\" android:textColor=\"#ffa500\" android:textSize=\"15sp\" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>", "e": 71437, "s": 46717, "text": null }, { "code": null, "e": 71487, "s": 71441, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 71687, "s": 71489, "text": "So as we have discussed earlier the backend part is written in this file. The backend part means the simple logic part. And for this project, we are going to write the code in the Kotlin language. " }, { "code": null, "e": 71741, "s": 71689, "text": "4.1: Creating variables for our TextView and Button" }, { "code": null, "e": 72087, "s": 71743, "text": "lateinit var tvsec: TextView\nlateinit var tvMain: TextView\nlateinit var bac: Button\nlateinit var bc: Button\nlateinit var bbrac1: Button\nlateinit var bbrac2: Button\n--------------------------\n--------------------------\n--------------------------\n// similarly create variable for all the TextView \n// and Button you have declared in the XML file" }, { "code": null, "e": 72125, "s": 72089, "text": "4.2: Initializing all the variables" }, { "code": null, "e": 72387, "s": 72127, "text": "tvsec = findViewById(R.id.idTVSecondary)\ntvMain = findViewById(R.id.idTVprimary)\nbac = findViewById(R.id.bac)\nbc = findViewById(R.id.bc)\n--------------------------\n--------------------------\n--------------------------\n// similarly initialize all the variables" }, { "code": null, "e": 72438, "s": 72389, "text": "4.3: Adding onClickListener() to all the Buttons" }, { "code": null, "e": 72842, "s": 72440, "text": "b1.setOnClickListener {\n // on below line we are appending \n // the expression to our text view.\n tvMain.text = (tvMain.text.toString() + \"1\")\n}\nb2.setOnClickListener {\n // on below line we are appending \n // the expression to our text view.\n tvMain.text = (tvMain.text.toString() + \"2\")\n--------------------------\n--------------------------\n// similarly Add onClickListener() to all the Buttons" }, { "code": null, "e": 73048, "s": 72844, "text": "At last write down the dimple logic for all the calculations (Addition, multiplication, division, etc.). Let we are going to write the code for the factorial of a number. So write down the code as below:" }, { "code": null, "e": 73198, "s": 73050, "text": "fun factorial(n: Int): Int {\n // this method is use to find factorial\n return if (n == 1 || n == 0) 1 else n * factorial(n - 1)\n }" }, { "code": null, "e": 73333, "s": 73200, "text": "Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 73342, "s": 73335, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for our text view and button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button lateinit var bsin: Button lateinit var bcos: Button lateinit var btan: Button lateinit var blog: Button lateinit var bln: Button lateinit var bfact: Button lateinit var bsquare: Button lateinit var bsqrt: Button lateinit var binv: Button lateinit var b0: Button lateinit var b9: Button lateinit var b8: Button lateinit var b7: Button lateinit var b6: Button lateinit var b5: Button lateinit var b4: Button lateinit var b3: Button lateinit var b2: Button lateinit var b1: Button lateinit var bpi: Button lateinit var bmul: Button lateinit var bminus: Button lateinit var bplus: Button lateinit var bequal: Button lateinit var bdot: Button lateinit var bdiv: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all our variables. tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) bbrac1 = findViewById(R.id.bbrac1) bbrac2 = findViewById(R.id.bbrac2) bsin = findViewById(R.id.bsin) bcos = findViewById(R.id.bcos) btan = findViewById(R.id.btan) blog = findViewById(R.id.blog) bln = findViewById(R.id.bln) bfact = findViewById(R.id.bfact) bsquare = findViewById(R.id.bsquare) bsqrt = findViewById(R.id.bsqrt) binv = findViewById(R.id.binv) b0 = findViewById(R.id.b0) b9 = findViewById(R.id.b9) b8 = findViewById(R.id.b8) b7 = findViewById(R.id.b7) b6 = findViewById(R.id.b6) b5 = findViewById(R.id.b5) b4 = findViewById(R.id.b4) b3 = findViewById(R.id.b3) b2 = findViewById(R.id.b2) b1 = findViewById(R.id.b1) bpi = findViewById(R.id.bpi) bmul = findViewById(R.id.bmul) bminus = findViewById(R.id.bminus) bplus = findViewById(R.id.bplus) bequal = findViewById(R.id.bequal) bdot = findViewById(R.id.bdot) bdiv = findViewById(R.id.bdiv) // adding on click listener to our all buttons. b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + \"1\") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + \"2\") } b3.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + \"3\") } b4.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"4\") } b5.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"5\") } b6.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"6\") } b7.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"7\") } b8.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"8\") } b9.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"9\") } b0.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"0\") } bdot.setOnClickListener { tvMain.text = (tvMain.text.toString() + \".\") } bplus.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"+\") } bdiv.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"/\") } bbrac1.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"(\") } bbrac2.setOnClickListener { tvMain.text = (tvMain.text.toString() + \")\") } bpi.setOnClickListener { // on clicking on pi button we are adding // pi value as 3.142 to our current value. tvMain.text = (tvMain.text.toString() + \"3.142\") tvsec.text = (bpi.text.toString()) } bsin.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"sin\") } bcos.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"cos\") } btan.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"tan\") } binv.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"^\" + \"(-1)\") } bln.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"ln\") } blog.setOnClickListener { tvMain.text = (tvMain.text.toString() + \"log\") } bminus.setOnClickListener { // on clicking on minus we are checking if // the user has already a minus operation on screen. // if minus operation is already present // then we will not do anything. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals(\"-\")) { tvMain.text = (tvMain.text.toString() + \"-\") } } bmul.setOnClickListener { // if mul sign is not present in our // text view then only we are adding // the multiplication operator to it. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals(\"*\")) { tvMain.text = (tvMain.text.toString() + \"*\") } } bsqrt.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, \"Please enter a valid number..\", Toast.LENGTH_SHORT).show() } else { val str: String = tvMain.text.toString() // on below line we are calculation // square root of the given number. val r = Math.sqrt(str.toDouble()) // on below line we are converting our double // to string and then setting it to text view. val result = r.toString() tvMain.setText(result) } } bequal.setOnClickListener { val str: String = tvMain.text.toString() // on below line we are calling an evaluate // method to calculate the value of expressions. val result: Double = evaluate(str) // on below line we are getting result // and setting it to text view. val r = result.toString() tvMain.setText(r) tvsec.text = str } bac.setOnClickListener { // on clicking on ac button we are clearing // our primary and secondary text view. tvMain.setText(\"\") tvsec.setText(\"\") } bc.setOnClickListener { // on clicking on c button we are clearing // the last character by checking the length. var str: String = tvMain.text.toString() if (!str.equals(\"\")) { str = str.substring(0, str.length - 1) tvMain.text = str } } bsquare.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, \"Please enter a valid number..\", Toast.LENGTH_SHORT).show() } else { // on below line we are getting the expression and then calculating the square of the number val d: Double = tvMain.getText().toString().toDouble() // on below line we are calculating the square. val square = d * d // after calculating the square we // are setting it to text view. tvMain.setText(square.toString()) // on below line we are setting // the d to secondary text view. tvsec.text = \"$d2\" } } bfact.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, \"Please enter a valid number..\", Toast.LENGTH_SHORT).show() } else { // on below line we are getting int value // and calculating the factorial value of the entered number. val value: Int = tvMain.text.toString().toInt() val fact: Int = factorial(value) tvMain.setText(fact.toString()) tvsec.text = \"$value`!\" } } } fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } fun evaluate(str: String): Double { return object : Any() { // on below line we are creating variable // for tracking the position and char pos. var pos = -1 var ch = 0 // below method is for moving to next character. fun nextChar() { // on below line we are incrementing our position // and moving it to next position. ch = if (++pos < str.length) str[pos].toInt() else -1 } // this method is use to check the extra space // present int the expression and removing it. fun eat(charToEat: Int): Boolean { while (ch == ' '.toInt()) nextChar() // on below line we are checking the char pos // if both is equal then we are returning it to true. if (ch == charToEat) { nextChar() return true } return false } // below method is to parse our // expression and to get the ans // in this we are calling a parse // expression method to calculate the value. fun parse(): Double { nextChar() val x = parseExpression() if (pos < str.length) throw RuntimeException(\"Unexpected: \" + ch.toChar()) return x } // in this method we will only perform addition and // subtraction operation on the expression. fun parseExpression(): Double { var x = parseTerm() while (true) { if (eat('+'.toInt())) x += parseTerm() // addition else if (eat('-'.toInt())) x -= parseTerm() // subtraction else return x } } // in below method we will perform // only multiplication and division operation. fun parseTerm(): Double { var x = parseFactor() while (true) { if (eat('*'.toInt())) x *= parseFactor() // multiplication else if (eat('/'.toInt())) x /= parseFactor() // division else return x } } // below method is use to parse the factor fun parseFactor(): Double { //on below line we are checking for addition // and subtraction and performing unary operations. if (eat('+'.toInt())) return parseFactor() // unary plus if (eat('-'.toInt())) return -parseFactor() // unary minus // creating a double variable for ans. var x: Double // on below line we are creating // a variable for position. val startPos = pos // on below line we are checking // for opening and closing parenthesis. if (eat('('.toInt())) { // parentheses x = parseExpression() eat(')'.toInt()) } else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) { // numbers while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar() // on below line we are getting sub string from our string using start and pos. x = str.substring(startPos, pos).toDouble() } else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) { // on below function we are checking for the operator in our expression. while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar() val func = str.substring(startPos, pos) // calling a method to parse our factor. x = parseFactor() // on below line we are checking for square root. x = if (func == \"sqrt\") Math.sqrt(x) // on below line we are checking for sin function // and calculating sin function using Math class. else if (func == \"sin\") Math.sin( Math.toRadians(x) // on below line we are calculating the cos value ) else if (func == \"cos\") Math.cos( Math.toRadians(x) // on below line we are calculating // the tan value of our expression. ) else if (func == \"tan\") Math.tan(Math.toRadians(x)) // on below line we are calculating // log value of the expression. else if (func == \"log\") Math.log10(x) // on below line we are calculating // ln value of expression. else if (func == \"ln\") Math.log(x) // f we get any error then // we simply return the exception. else throw RuntimeException( \"Unknown function: $func\" ) } else { // if the condition not satisfy then we are returning the exception throw RuntimeException(\"Unexpected: \" + ch.toChar()) } // on below line we are calculating the power of the expression. if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation return x } // at last calling a parse for our expression. }.parse() }}", "e": 88537, "s": 73342, "text": null }, { "code": null, "e": 88549, "s": 88541, "text": "Output:" }, { "code": null, "e": 88663, "s": 88553, "text": "For the complete article refer to this: How to Make a Scientific Calculator Android App using Android Studio?" }, { "code": null, "e": 88708, "s": 88665, "text": "You may also refer to the following video:" }, { "code": null, "e": 89560, "s": 88710, "text": "YouTubeGeeksforGeeks500K subscribersHow to Make a Scientific Calculator Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:10:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=gwOL-4V_sNw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 89660, "s": 89564, "text": "In the 3rd week of Android App Development, we will learn the following very important concepts" }, { "code": null, "e": 89766, "s": 89662, "text": "What’s REST APIVolley Library in AndroidWhat’s a JSON file?JSON Parsing in Android using Volley Library" }, { "code": null, "e": 89782, "s": 89766, "text": "What’s REST API" }, { "code": null, "e": 89808, "s": 89782, "text": "Volley Library in Android" }, { "code": null, "e": 89828, "s": 89808, "text": "What’s a JSON file?" }, { "code": null, "e": 89873, "s": 89828, "text": "JSON Parsing in Android using Volley Library" }, { "code": null, "e": 89893, "s": 89875, "text": "1. What’ REST API" }, { "code": null, "e": 90128, "s": 89895, "text": "REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services simply and flexibly without having any processing. " }, { "code": null, "e": 90191, "s": 90130, "text": "To read more refer to this article: Introduction to REST API" }, { "code": null, "e": 90222, "s": 90193, "text": "2. Volley Library in Android" }, { "code": null, "e": 90831, "s": 90224, "text": "Volley is an HTTP library that makes networking very easy and fast, for Android apps. It was developed by Google and introduced during Google I/O 2013. It was developed because there is an absence in Android SDK, of a networking class capable of working without interfering with the user experience. Although Volley is a part of the Android Open Source Project(AOSP), Google announced in January 2017 that Volley will move to a standalone library. It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again." }, { "code": null, "e": 90895, "s": 90833, "text": "To read more refer to this article: Volley Library in Android" }, { "code": null, "e": 90920, "s": 90897, "text": "3. What’s a JSON file?" }, { "code": null, "e": 91446, "s": 90922, "text": "JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript. The official media type for the JSON is application/json and to save those file .json extension." }, { "code": null, "e": 91504, "s": 91448, "text": "To read more refer to this article: What’s a JSON file?" }, { "code": null, "e": 91554, "s": 91506, "text": "4. JSON Parsing in Android using Volley Library" }, { "code": null, "e": 91650, "s": 91556, "text": "Refer to this article for proper implementation: JSON Parsing in Android using Volley Library" }, { "code": null, "e": 91816, "s": 91652, "text": "So after learning these important concepts, we will develop an intermediate project this week and the name of the project is “Build COVID-19 Tracker Android App“. " }, { "code": null, "e": 92065, "s": 91820, "text": "To build this complete project please refer to this article: How to Build a COVID-19 Tracker Android App. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. " }, { "code": null, "e": 92910, "s": 92067, "text": "YouTubeGeeksforGeeks500K subscribersHow to Make a Covid-19 Tracker Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 44:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=opCW91zYJcI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 93343, "s": 92914, "text": "When developers work on a real mobile application whose nature is dynamic and will expand its features according to the user’s need, then it is not possible to write core logic in activities or fragments. To structure the project’s code and to give it a modular design(separated code parts), architecture patterns are applied to separate the concerns. The most popular android architectures used by developers are the following:" }, { "code": null, "e": 93438, "s": 93345, "text": "MVC (Model — View — Controller)MVP (Model — View — Presenter)MVVM (Model — View — ViewModel)" }, { "code": null, "e": 93470, "s": 93438, "text": "MVC (Model — View — Controller)" }, { "code": null, "e": 93501, "s": 93470, "text": "MVP (Model — View — Presenter)" }, { "code": null, "e": 93533, "s": 93501, "text": "MVVM (Model — View — ViewModel)" }, { "code": null, "e": 93799, "s": 93535, "text": "So in the 4th week are going to learn another very important concept i.e Android Architecture Patterns. Please read out the following articles and try to explore as much as you because these concepts are very very useful to become a successful Android Developer. " }, { "code": null, "e": 93831, "s": 93801, "text": "Android Architecture Patterns" }, { "code": null, "e": 93863, "s": 93831, "text": "MVC (Model — View — Controller)" }, { "code": null, "e": 93894, "s": 93863, "text": "MVP (Model — View — Presenter)" }, { "code": null, "e": 93926, "s": 93894, "text": "MVVM (Model — View — ViewModel)" }, { "code": null, "e": 94070, "s": 93928, "text": "So using these concepts, this week we are going to develop another application “Build a Simple Note App using Android Architecture Pattern”. " }, { "code": null, "e": 94343, "s": 94074, "text": "To build this complete project please refer to this article: How to Build a Simple Note Android App using MVVM and Room Database. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. " }, { "code": null, "e": 94374, "s": 94345, "text": "https://youtu.be/D2F5t-phP04" }, { "code": null, "e": 94899, "s": 94376, "text": "Firebase! I think you have heard this word. Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides services to android, ios, web, and unity. It provides cloud storage. It uses NoSQL for the database for the storage of data. To read more refer to this article: Introduction to Firebase " }, { "code": null, "e": 95384, "s": 94903, "text": "So in the 5th week of Android App Development, we are going to explore the Firebase database and how to perform basic authentication and CRUD (Create, Read, Update, Delete) operation with Firebase. To build this complete project please refer to this article: User Authentication and CRUD Operation with Firebase Realtime Database in Android. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. " }, { "code": null, "e": 96269, "s": 95386, "text": "YouTubeGeeksforGeeks500K subscribersUser Authentication and CRUD Operation with Firebase Realtime Database in Android | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:15:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=-Gvpf8tXpbc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 96351, "s": 96271, "text": "You may also refer to this section to know more about Firebase + Android stuff." }, { "code": null, "e": 96562, "s": 96355, "text": "In the last week of Android App Development, we are going to develop an advanced Android App using multiple advanced concepts. We are going to build a Grocery Android App whose output is like the following." }, { "code": null, "e": 97266, "s": 96566, "text": "So in this project, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down the grocery items that you are going to purchase, by doing this you can’t forget any items that you want to purchase. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. In this project, we are using MVVM (Model View ViewModel) for architectural patterns, Room for database, Coroutines and RecyclerView to display the list of items. " }, { "code": null, "e": 97533, "s": 97268, "text": "To build this complete project please refer to this article: How to Build a Grocery Android App using MVVM and Room Database. In this article, the complete step-by-step process is explained in detail also we have attached a video to understand the project deeper. " }, { "code": null, "e": 98403, "s": 97535, "text": "YouTubeGeeksforGeeks500K subscribersBuild a Grocery Android App using MVVM and Room Database in Kotlin | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:02:06•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=vdcLb_Y71Ic\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 98453, "s": 98405, "text": "Must Refer to the Following Tutorial in Android" }, { "code": null, "e": 98472, "s": 98455, "text": "Android Tutorial" }, { "code": null, "e": 98496, "s": 98472, "text": "Android Studio Tutorial" }, { "code": null, "e": 98522, "s": 98496, "text": "Android Projects Tutorial" }, { "code": null, "e": 98539, "s": 98524, "text": "sagartomar9927" }, { "code": null, "e": 98551, "s": 98539, "text": "kk773572498" }, { "code": null, "e": 98559, "s": 98551, "text": "Android" }, { "code": null, "e": 98565, "s": 98559, "text": "GBlog" }, { "code": null, "e": 98570, "s": 98565, "text": "Java" }, { "code": null, "e": 98577, "s": 98570, "text": "Kotlin" }, { "code": null, "e": 98585, "s": 98577, "text": "Project" }, { "code": null, "e": 98590, "s": 98585, "text": "Java" }, { "code": null, "e": 98598, "s": 98590, "text": "Android" }, { "code": null, "e": 98696, "s": 98598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 98705, "s": 98696, "text": "Comments" }, { "code": null, "e": 98718, "s": 98705, "text": "Old Comments" }, { "code": null, "e": 98776, "s": 98718, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 98819, "s": 98776, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 98852, "s": 98819, "text": "Services in Android with Example" }, { "code": null, "e": 98894, "s": 98852, "text": "Content Providers in Android with Example" }, { "code": null, "e": 98925, "s": 98894, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 98967, "s": 98925, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 99041, "s": 98967, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 99069, "s": 99041, "text": "Socket Programming in C/C++" }, { "code": null, "e": 99094, "s": 99069, "text": "DSA Sheet by Love Babbar" } ]
JavaScript Bubble sort for objects in an array
Suppose, we have a constructor class that creates Shoe objects like this − class Shoe { constructor(name, price, type) { this.name = name; this.price = price; this.type = type; } }; We are using this class to fill an array with objects like this − const arr = [ new Shoe('Nike AirMax 90', '120', 'Casual'), new Shoe('Jordan Retro 1', '110', 'Casual'), new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'), new Shoe('Adidas X Ghosted', '110', 'Athletic'), new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'), new Shoe('Aldo Loafers', '130', 'Formal'), new Shoe('Timberlands', '199', 'Seasonal boots'), new Shoe('Converse High Tops', '70', 'Casual'), new Shoe('Converse Low Tops', '80', 'Casual'), new Shoe('Adidas NMDs', '110', 'Athletic'), new Shoe('Heels', '130', 'Formal'), new Shoe('Nike AirForce', '150', 'Casual') ]; We are required to write a JavaScript function makes use of precisely the Bubble Sort algorithm to sort this array of objects based on the price property of the objects. The code for this will be − class Shoe { constructor(name, price, type) { this.name = name; this.price = price; this.type = type; } }; const arr = [ new Shoe('Nike AirMax 90', '120', 'Casual'), new Shoe('Jordan Retro 1', '110', 'Casual'), new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'), new Shoe('Adidas X Ghosted', '110', 'Athletic'), new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'), new Shoe('Aldo Loafers', '130', 'Formal'), new Shoe('Timberlands', '199', 'Seasonal boots'), new Shoe('Converse High Tops', '70', 'Casual'), new Shoe('Converse Low Tops', '80', 'Casual'), new Shoe('Adidas NMDs', '110', 'Athletic'), new Shoe('Heels', '130', 'Formal'), new Shoe('Nike AirForce', '150', 'Casual') ]; const bubbleSort = (arr = []) => { let swapped; do { swapped = false; for (let i = 0; i < arr.length − 1; i++) { if (+arr[i].price > +arr[i + 1].price) { let temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; swapped = true; }; }; }while (swapped); } bubbleSort(arr); console.log(arr); And the output in the console will be − [ Shoe { name: 'Converse High Tops', price: '70', type: 'Casual' }, Shoe { name: 'Converse Low Tops', price: '80', type: 'Casual' }, Shoe { name: 'Jordan Retro 1', price: '110', type: 'Casual' }, Shoe { name: 'Adidas X Ghosted', price: '110', type: 'Athletic' }, Shoe { name: 'Adidas NMDs', price: '110', type: 'Athletic' }, Shoe { name: 'Nike AirMax 90', price: '120', type: 'Casual' }, Shoe { name: 'Aldo Loafers', price: '130', type: 'Formal' }, Shoe { name: 'Heels', price: '130', type: 'Formal' }, Shoe { name: 'Nike AirForce', price: '150', type: 'Casual' }, Shoe { name: 'Timberlands', price: '199', type: 'Seasonal boots' }, Shoe { name: 'Jadon Doc Martens', price: '250', type: 'Seasonal boots'}, Shoe { name: 'Nike Vapourmax Flyknit', price: '250', type: 'Casual' } ]
[ { "code": null, "e": 1137, "s": 1062, "text": "Suppose, we have a constructor class that creates Shoe objects like this −" }, { "code": null, "e": 1268, "s": 1137, "text": "class Shoe {\n constructor(name, price, type) {\n this.name = name;\n this.price = price;\n this.type = type;\n }\n};" }, { "code": null, "e": 1334, "s": 1268, "text": "We are using this class to fill an array with objects like this −" }, { "code": null, "e": 1946, "s": 1334, "text": "const arr = [\n new Shoe('Nike AirMax 90', '120', 'Casual'),\n new Shoe('Jordan Retro 1', '110', 'Casual'),\n new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),\n new Shoe('Adidas X Ghosted', '110', 'Athletic'),\n new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),\n new Shoe('Aldo Loafers', '130', 'Formal'),\n new Shoe('Timberlands', '199', 'Seasonal boots'),\n new Shoe('Converse High Tops', '70', 'Casual'),\n new Shoe('Converse Low Tops', '80', 'Casual'),\n new Shoe('Adidas NMDs', '110', 'Athletic'),\n new Shoe('Heels', '130', 'Formal'),\n new Shoe('Nike AirForce', '150', 'Casual')\n];" }, { "code": null, "e": 2116, "s": 1946, "text": "We are required to write a JavaScript function makes use of precisely the Bubble Sort algorithm to sort this array of objects based on the price property of the objects." }, { "code": null, "e": 2144, "s": 2116, "text": "The code for this will be −" }, { "code": null, "e": 3270, "s": 2144, "text": "class Shoe {\n constructor(name, price, type) {\n this.name = name;\n this.price = price;\n this.type = type;\n }\n};\nconst arr = [\n new Shoe('Nike AirMax 90', '120', 'Casual'),\n new Shoe('Jordan Retro 1', '110', 'Casual'),\n new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),\n new Shoe('Adidas X Ghosted', '110', 'Athletic'),\n new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),\n new Shoe('Aldo Loafers', '130', 'Formal'),\n new Shoe('Timberlands', '199', 'Seasonal boots'),\n new Shoe('Converse High Tops', '70', 'Casual'),\n new Shoe('Converse Low Tops', '80', 'Casual'),\n new Shoe('Adidas NMDs', '110', 'Athletic'),\n new Shoe('Heels', '130', 'Formal'),\n new Shoe('Nike AirForce', '150', 'Casual')\n];\nconst bubbleSort = (arr = []) => {\n let swapped;\n do {\n swapped = false;\n for (let i = 0; i < arr.length − 1; i++) {\n if (+arr[i].price > +arr[i + 1].price) {\n let temp = arr[i];\n arr[i] = arr[i + 1];\n arr[i + 1] = temp;\n swapped = true;\n };\n };\n }while (swapped);\n}\nbubbleSort(arr);\nconsole.log(arr);" }, { "code": null, "e": 3310, "s": 3270, "text": "And the output in the console will be −" }, { "code": null, "e": 4124, "s": 3310, "text": "[\n Shoe { name: 'Converse High Tops', price: '70', type: 'Casual' },\n Shoe { name: 'Converse Low Tops', price: '80', type: 'Casual' },\n Shoe { name: 'Jordan Retro 1', price: '110', type: 'Casual' },\n Shoe { name: 'Adidas X Ghosted', price: '110', type: 'Athletic' },\n Shoe { name: 'Adidas NMDs', price: '110', type: 'Athletic' },\n Shoe { name: 'Nike AirMax 90', price: '120', type: 'Casual' },\n Shoe { name: 'Aldo Loafers', price: '130', type: 'Formal' },\n Shoe { name: 'Heels', price: '130', type: 'Formal' },\n Shoe { name: 'Nike AirForce', price: '150', type: 'Casual' },\n Shoe { name: 'Timberlands', price: '199', type: 'Seasonal boots' },\n Shoe { name: 'Jadon Doc Martens', price: '250', type: 'Seasonal boots'},\n Shoe { name: 'Nike Vapourmax Flyknit', price: '250', type: 'Casual' }\n]" } ]
Decision Trees Explained. Learn everything about Decision Trees... | by z_ai | Towards Data Science
In this post, I will explain Decision Trees in simple terms. It could be considered a Decision Trees for dummies post, however, I’ve never really liked that expression. Before we start, here you have some additional resources to skyrocket your Machine Learning career Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For more awesome Data Science news, tools, educative articles and platforms subscribe to my newsletter! z-ai.medium.com In the Machine Learning world, Decision Trees are a kind of non parametric models, that can be used for both classification and regression. This means that Decision trees are flexible models that don’t increase their number of parameters as we add more features (if we build them correctly), and they can either output a categorical prediction (like if a plant is of a certain kind or not) or a numerical prediction (like the price of a house). They are constructed using two kinds of elements: nodes and branches. At each node, one of the features of our data is evaluated in order to split the observations in the training process or to make an specific data point follow a certain path when making a prediction. When they are being built decision trees are constructed by recursively evaluating different features and using at each node the feature that best splits the data. This will be explained in detail later. Probably the best way to start the explanation is by seen what a decision tree looks like, to build a quick intuition of how they can be used. The following figure shows the general structure of one of these trees. In this figure we can observe three kinds of nodes: The Root Node: Is the node that starts the graph. In a normal decision tree it evaluates the variable that best splits the data. Intermediate nodes: These are nodes where variables are evaluated but which are not the final nodes where predictions are made. Leaf nodes: These are the final nodes of the tree, where the predictions of a category or a numerical value are made. Alright, now that we have a general idea of what Decision trees are, let's see how they are built. Like we mentioned previously, decision trees are built by recursively splitting our training samples using the features from the data that work best for the specific task. This is done by evaluating certain metrics, like the Gini index or the Entropy for categorical decision trees, or the Residual or Mean Squared Error for regression trees. The process is also different if the feature that we are evaluating at the node is discrete or continuous. For discrete features all of its possible values are evaluated, resulting in N calculated metrics for each of the variables, being N the number of possible value for each categorical value. For continuous features the mean of each two consecutive values (ordered from lowest to highest) of the training data are used as possible thresholds. The result of this process is, for a certain node, a list of variables, each with different thresholds, and a calculated metric (Gini or MSE) for each variable/threshold tandem. Then, we pick the variable/threshold combination that gives us the highest/lowest value for the specific metric that we are using for the resulting children nodes (the highest reduction or increase in the metric). We won’t go into how these metrics are calculated, as it is off the topic of this introductory post, however I will leave some resources at the end for you to dive deeper if you are interested. At the moment just think of these metrics (Gini for categorical trees and Mean Squared Error for regression trees) as some sort of error which we want to reduce. Let's see an example of two decision trees, a categorical one and a regressive one to get a more clear picture of this process. The following figure shows a categorical tree built for the famous Iris Dataset, where we try to predict a category out of three different flowers, using features like the petal width, length, sepal length, ... We can see that the root node starts with 50 samples of each of the three classes, and a Gini Index (as it is a categorical tree the lower the Gini Index the better) of 0,667. In this node, the feature that best split the different classes of the data is the petal width in cm, using as a threshold a value of 0,8. This results in two nodes, one with Gini 0 (perfectly pure node that only has one of the types of flowers) and one with Gini of 0.5, where the two other kinds of flowers are grouped. In this intermediate node (False path from the root node), the same feature is evaluated (yes, this can happen, and it actually happens often if the feature is important) using a threshold of 1,75. Now this results in two other children nodes that are not pure, but that have a pretty low Gini Index. In all of these nodes all the other features of the data (sepal length, sepal width, and petal length) were evaluated, and had their resulting Gini Index calculated, however, the feature that gave us the best results (lowest Gini Index) was the petal width. The reason the tree didn’t continue growing is because Decision Trees always a growth-stop condition configured, otherwise they would grow until each training sample was separated into its own leaf node. These stop conditions are maximum depth of the tree, minimum samples in leaf nodes, or minimum reduction in the error metric. Let's check out a Regression Tree now, for this, we will use the Boston House Price Dataset, resulting in the following graph: As we can see in the previous figure, now we don’t have the Gini Index, but the MSE (Mean Squared Error). As in the previous example with the Gini, our tree is built using the feature/threshold combinations that most reduced this error. The root node uses the variable LSTAT (% lower status of the population in the area) with a threshold of 9.725, to initially divide the samples. We can see that at the root node we have 506, that we divided into 212 (left children node) and 294 (right children node). The left children node uses the variable RM (number of rooms per dwelling) with a threshold of 6.631, and the right node uses the same LSTAT variable with a threshold of 16.085, resulting in four beautiful leaf nodes. As before all the other variables were evaluated at each node, but these two were the ones that best split the data. Awesome! Now we know how Decision Trees are built. Let's learn how they are used to make predictions. Predicting the category or numerical target value of a new sample is very easy using Decision Trees. That is one of the main advantages of these kinds of algorithms. All we have to do is start at the root node, look at the value of the feature that it evaluates, and depending on that value go to the left or right children node. This process is repeated until we reach a leaf node. When this happens, depending on whether we are facing a classification or a regression problem two things can happen: a) If we are facing a classification problem, the predicted category would be the mode of the categories on that leaf node. Remember how in the classification tree we had value = [0,49,5] on the middle leaf node? This means that a test sample that reaches this node has the highest probability of belonging to the class with 49 training samples on that node, so we classify it as such. b) For a regression tree, the prediction we make at the end is the mean of the values for the target variable at such leaf node. In our housing example if a leaf node had 4 samples with prices 20, 18, 22, and 24, then the predicted value at that node would be 21, the mean of the 4 training examples that end there. In the following figure, we can see how a prediction would be made for a new test sample(a house) for the previous regression tree. Note: Only the features of the house that are used in the tree are shown. Alright! Now we know how to make predictions using decision trees. Let's finish by learning their advantages and disadvantages. The main advantage of decision trees is how easy they are to interpret. While other machine Learning models are close to black boxes, decision trees provide a graphical and intuitive way to understand what our algorithm does. Compared to other Machine Learning algorithms Decision Trees require less data to train. They can be used for Classification and Regression. They are simple. They are tolerant to missing values. They are quite prone to over fitting to the training data and can be sensible to outliers. They are weak learners: a single decision tree normally does not make great predictions, so multiple trees are often combined to make ‘forests’ to give birth to stronger ensemble models. This will be discussed in a further post. z-ai.medium.com Decision trees are algorithms that are simple but intuitive, and because of this they are used a lot when trying to explain the results of a Machine Learning model. Despite being weak, they can be combined giving birth to bagging or boosting models, that are very powerful. In the next posts, we will explore some of these models. If you want to know the full process for building a tree, check out the following video: That is all, I hope you liked the post. Feel free to follow me on Twitter at @jaimezorno. Also, you can take a look at my posts on Data Science and Machine Learning here. Have a good read! For further resources on Machine Learning and Data Science check out the following repository: How to Learn Machine Learning! For career resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers. Also, for more posts like this one follow me on Medium, and stay tuned! Also, you can subscribe to my email list to get the latest update and exclusive content here: SUBSCRIBE TO EMAIL LIST. Lastly, to go further into Decision Trees and Machine Learning in general, take a look at the book described in the following article: towardsdatascience.com Thank you very much for reading, and have a great day!
[ { "code": null, "e": 340, "s": 171, "text": "In this post, I will explain Decision Trees in simple terms. It could be considered a Decision Trees for dummies post, however, I’ve never really liked that expression." }, { "code": null, "e": 439, "s": 340, "text": "Before we start, here you have some additional resources to skyrocket your Machine Learning career" }, { "code": null, "e": 642, "s": 439, "text": "Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For more awesome Data Science news, tools, educative articles and platforms subscribe to my newsletter!" }, { "code": null, "e": 658, "s": 642, "text": "z-ai.medium.com" }, { "code": null, "e": 798, "s": 658, "text": "In the Machine Learning world, Decision Trees are a kind of non parametric models, that can be used for both classification and regression." }, { "code": null, "e": 1103, "s": 798, "text": "This means that Decision trees are flexible models that don’t increase their number of parameters as we add more features (if we build them correctly), and they can either output a categorical prediction (like if a plant is of a certain kind or not) or a numerical prediction (like the price of a house)." }, { "code": null, "e": 1373, "s": 1103, "text": "They are constructed using two kinds of elements: nodes and branches. At each node, one of the features of our data is evaluated in order to split the observations in the training process or to make an specific data point follow a certain path when making a prediction." }, { "code": null, "e": 1577, "s": 1373, "text": "When they are being built decision trees are constructed by recursively evaluating different features and using at each node the feature that best splits the data. This will be explained in detail later." }, { "code": null, "e": 1792, "s": 1577, "text": "Probably the best way to start the explanation is by seen what a decision tree looks like, to build a quick intuition of how they can be used. The following figure shows the general structure of one of these trees." }, { "code": null, "e": 1844, "s": 1792, "text": "In this figure we can observe three kinds of nodes:" }, { "code": null, "e": 1973, "s": 1844, "text": "The Root Node: Is the node that starts the graph. In a normal decision tree it evaluates the variable that best splits the data." }, { "code": null, "e": 2101, "s": 1973, "text": "Intermediate nodes: These are nodes where variables are evaluated but which are not the final nodes where predictions are made." }, { "code": null, "e": 2219, "s": 2101, "text": "Leaf nodes: These are the final nodes of the tree, where the predictions of a category or a numerical value are made." }, { "code": null, "e": 2318, "s": 2219, "text": "Alright, now that we have a general idea of what Decision trees are, let's see how they are built." }, { "code": null, "e": 2661, "s": 2318, "text": "Like we mentioned previously, decision trees are built by recursively splitting our training samples using the features from the data that work best for the specific task. This is done by evaluating certain metrics, like the Gini index or the Entropy for categorical decision trees, or the Residual or Mean Squared Error for regression trees." }, { "code": null, "e": 3109, "s": 2661, "text": "The process is also different if the feature that we are evaluating at the node is discrete or continuous. For discrete features all of its possible values are evaluated, resulting in N calculated metrics for each of the variables, being N the number of possible value for each categorical value. For continuous features the mean of each two consecutive values (ordered from lowest to highest) of the training data are used as possible thresholds." }, { "code": null, "e": 3501, "s": 3109, "text": "The result of this process is, for a certain node, a list of variables, each with different thresholds, and a calculated metric (Gini or MSE) for each variable/threshold tandem. Then, we pick the variable/threshold combination that gives us the highest/lowest value for the specific metric that we are using for the resulting children nodes (the highest reduction or increase in the metric)." }, { "code": null, "e": 3857, "s": 3501, "text": "We won’t go into how these metrics are calculated, as it is off the topic of this introductory post, however I will leave some resources at the end for you to dive deeper if you are interested. At the moment just think of these metrics (Gini for categorical trees and Mean Squared Error for regression trees) as some sort of error which we want to reduce." }, { "code": null, "e": 4196, "s": 3857, "text": "Let's see an example of two decision trees, a categorical one and a regressive one to get a more clear picture of this process. The following figure shows a categorical tree built for the famous Iris Dataset, where we try to predict a category out of three different flowers, using features like the petal width, length, sepal length, ..." }, { "code": null, "e": 4372, "s": 4196, "text": "We can see that the root node starts with 50 samples of each of the three classes, and a Gini Index (as it is a categorical tree the lower the Gini Index the better) of 0,667." }, { "code": null, "e": 4694, "s": 4372, "text": "In this node, the feature that best split the different classes of the data is the petal width in cm, using as a threshold a value of 0,8. This results in two nodes, one with Gini 0 (perfectly pure node that only has one of the types of flowers) and one with Gini of 0.5, where the two other kinds of flowers are grouped." }, { "code": null, "e": 4995, "s": 4694, "text": "In this intermediate node (False path from the root node), the same feature is evaluated (yes, this can happen, and it actually happens often if the feature is important) using a threshold of 1,75. Now this results in two other children nodes that are not pure, but that have a pretty low Gini Index." }, { "code": null, "e": 5253, "s": 4995, "text": "In all of these nodes all the other features of the data (sepal length, sepal width, and petal length) were evaluated, and had their resulting Gini Index calculated, however, the feature that gave us the best results (lowest Gini Index) was the petal width." }, { "code": null, "e": 5583, "s": 5253, "text": "The reason the tree didn’t continue growing is because Decision Trees always a growth-stop condition configured, otherwise they would grow until each training sample was separated into its own leaf node. These stop conditions are maximum depth of the tree, minimum samples in leaf nodes, or minimum reduction in the error metric." }, { "code": null, "e": 5710, "s": 5583, "text": "Let's check out a Regression Tree now, for this, we will use the Boston House Price Dataset, resulting in the following graph:" }, { "code": null, "e": 5947, "s": 5710, "text": "As we can see in the previous figure, now we don’t have the Gini Index, but the MSE (Mean Squared Error). As in the previous example with the Gini, our tree is built using the feature/threshold combinations that most reduced this error." }, { "code": null, "e": 6215, "s": 5947, "text": "The root node uses the variable LSTAT (% lower status of the population in the area) with a threshold of 9.725, to initially divide the samples. We can see that at the root node we have 506, that we divided into 212 (left children node) and 294 (right children node)." }, { "code": null, "e": 6550, "s": 6215, "text": "The left children node uses the variable RM (number of rooms per dwelling) with a threshold of 6.631, and the right node uses the same LSTAT variable with a threshold of 16.085, resulting in four beautiful leaf nodes. As before all the other variables were evaluated at each node, but these two were the ones that best split the data." }, { "code": null, "e": 6652, "s": 6550, "text": "Awesome! Now we know how Decision Trees are built. Let's learn how they are used to make predictions." }, { "code": null, "e": 6982, "s": 6652, "text": "Predicting the category or numerical target value of a new sample is very easy using Decision Trees. That is one of the main advantages of these kinds of algorithms. All we have to do is start at the root node, look at the value of the feature that it evaluates, and depending on that value go to the left or right children node." }, { "code": null, "e": 7153, "s": 6982, "text": "This process is repeated until we reach a leaf node. When this happens, depending on whether we are facing a classification or a regression problem two things can happen:" }, { "code": null, "e": 7539, "s": 7153, "text": "a) If we are facing a classification problem, the predicted category would be the mode of the categories on that leaf node. Remember how in the classification tree we had value = [0,49,5] on the middle leaf node? This means that a test sample that reaches this node has the highest probability of belonging to the class with 49 training samples on that node, so we classify it as such." }, { "code": null, "e": 7855, "s": 7539, "text": "b) For a regression tree, the prediction we make at the end is the mean of the values for the target variable at such leaf node. In our housing example if a leaf node had 4 samples with prices 20, 18, 22, and 24, then the predicted value at that node would be 21, the mean of the 4 training examples that end there." }, { "code": null, "e": 7987, "s": 7855, "text": "In the following figure, we can see how a prediction would be made for a new test sample(a house) for the previous regression tree." }, { "code": null, "e": 8061, "s": 7987, "text": "Note: Only the features of the house that are used in the tree are shown." }, { "code": null, "e": 8189, "s": 8061, "text": "Alright! Now we know how to make predictions using decision trees. Let's finish by learning their advantages and disadvantages." }, { "code": null, "e": 8415, "s": 8189, "text": "The main advantage of decision trees is how easy they are to interpret. While other machine Learning models are close to black boxes, decision trees provide a graphical and intuitive way to understand what our algorithm does." }, { "code": null, "e": 8504, "s": 8415, "text": "Compared to other Machine Learning algorithms Decision Trees require less data to train." }, { "code": null, "e": 8556, "s": 8504, "text": "They can be used for Classification and Regression." }, { "code": null, "e": 8573, "s": 8556, "text": "They are simple." }, { "code": null, "e": 8610, "s": 8573, "text": "They are tolerant to missing values." }, { "code": null, "e": 8701, "s": 8610, "text": "They are quite prone to over fitting to the training data and can be sensible to outliers." }, { "code": null, "e": 8930, "s": 8701, "text": "They are weak learners: a single decision tree normally does not make great predictions, so multiple trees are often combined to make ‘forests’ to give birth to stronger ensemble models. This will be discussed in a further post." }, { "code": null, "e": 8946, "s": 8930, "text": "z-ai.medium.com" }, { "code": null, "e": 9277, "s": 8946, "text": "Decision trees are algorithms that are simple but intuitive, and because of this they are used a lot when trying to explain the results of a Machine Learning model. Despite being weak, they can be combined giving birth to bagging or boosting models, that are very powerful. In the next posts, we will explore some of these models." }, { "code": null, "e": 9366, "s": 9277, "text": "If you want to know the full process for building a tree, check out the following video:" }, { "code": null, "e": 9555, "s": 9366, "text": "That is all, I hope you liked the post. Feel free to follow me on Twitter at @jaimezorno. Also, you can take a look at my posts on Data Science and Machine Learning here. Have a good read!" }, { "code": null, "e": 9818, "s": 9555, "text": "For further resources on Machine Learning and Data Science check out the following repository: How to Learn Machine Learning! For career resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers." }, { "code": null, "e": 9890, "s": 9818, "text": "Also, for more posts like this one follow me on Medium, and stay tuned!" }, { "code": null, "e": 10009, "s": 9890, "text": "Also, you can subscribe to my email list to get the latest update and exclusive content here: SUBSCRIBE TO EMAIL LIST." }, { "code": null, "e": 10144, "s": 10009, "text": "Lastly, to go further into Decision Trees and Machine Learning in general, take a look at the book described in the following article:" }, { "code": null, "e": 10167, "s": 10144, "text": "towardsdatascience.com" } ]
Python Pandas - Comparison with SQL
Since many potential Pandas users have some familiarity with SQL, this page is meant to provide some examples of how various SQL operations can be performed using pandas. import pandas as pd url = 'https://raw.github.com/pandasdev/ pandas/master/pandas/tests/data/tips.csv' tips=pd.read_csv(url) print tips.head() Its output is as follows − total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 In SQL, selection is done using a comma-separated list of columns that you select (or a * to select all columns) − SELECT total_bill, tip, smoker, time FROM tips LIMIT 5; With Pandas, column selection is done by passing a list of column names to your DataFrame − tips[['total_bill', 'tip', 'smoker', 'time']].head(5) Let’s check the full program − import pandas as pd url = 'https://raw.github.com/pandasdev/ pandas/master/pandas/tests/data/tips.csv' tips=pd.read_csv(url) print tips[['total_bill', 'tip', 'smoker', 'time']].head(5) Its output is as follows − total_bill tip smoker time 0 16.99 1.01 No Dinner 1 10.34 1.66 No Dinner 2 21.01 3.50 No Dinner 3 23.68 3.31 No Dinner 4 24.59 3.61 No Dinner Calling the DataFrame without the list of column names will display all columns (akin to SQL’s *). Filtering in SQL is done via a WHERE clause. SELECT * FROM tips WHERE time = 'Dinner' LIMIT 5; DataFrames can be filtered in multiple ways; the most intuitive of which is using Boolean indexing. tips[tips['time'] == 'Dinner'].head(5) Let’s check the full program − import pandas as pd url = 'https://raw.github.com/pandasdev/ pandas/master/pandas/tests/data/tips.csv' tips=pd.read_csv(url) print tips[tips['time'] == 'Dinner'].head(5) Its output is as follows − total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 The above statement passes a Series of True/False objects to the DataFrame, returning all rows with True. This operation fetches the count of records in each group throughout a dataset. For instance, a query fetching us the number of tips left by sex − SELECT sex, count(*) FROM tips GROUP BY sex; The Pandas equivalent would be − tips.groupby('sex').size() Let’s check the full program − import pandas as pd url = 'https://raw.github.com/pandasdev/ pandas/master/pandas/tests/data/tips.csv' tips=pd.read_csv(url) print tips.groupby('sex').size() Its output is as follows − sex Female 87 Male 157 dtype: int64 SQL returns the top n rows using LIMIT − SELECT * FROM tips LIMIT 5 ; The Pandas equivalent would be − tips.head(5) Let’s check the full example − import pandas as pd url = 'https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv' tips=pd.read_csv(url) tips = tips[['smoker', 'day', 'time']].head(5) print tips Its output is as follows − smoker day time 0 No Sun Dinner 1 No Sun Dinner 2 No Sun Dinner 3 No Sun Dinner 4 No Sun Dinner These are the few basic operations we compared are, which we learnt, in the previous chapters of the Pandas Library. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2614, "s": 2443, "text": "Since many potential Pandas users have some familiarity with SQL, this page is meant to provide some examples of how various SQL operations can be performed using pandas." }, { "code": null, "e": 2759, "s": 2614, "text": "import pandas as pd\n\nurl = 'https://raw.github.com/pandasdev/\npandas/master/pandas/tests/data/tips.csv'\n\ntips=pd.read_csv(url)\nprint tips.head()" }, { "code": null, "e": 2786, "s": 2759, "text": "Its output is as follows −" }, { "code": null, "e": 3135, "s": 2786, "text": " total_bill tip sex smoker day time size\n0 16.99 1.01 Female No Sun Dinner 2\n1 10.34 1.66 Male No Sun Dinner 3\n2 21.01 3.50 Male No Sun Dinner 3\n3 23.68 3.31 Male No Sun Dinner 2\n4 24.59 3.61 Female No Sun Dinner 4\n" }, { "code": null, "e": 3250, "s": 3135, "text": "In SQL, selection is done using a comma-separated list of columns that you select (or a * to select all columns) −" }, { "code": null, "e": 3307, "s": 3250, "text": "SELECT total_bill, tip, smoker, time\nFROM tips\nLIMIT 5;\n" }, { "code": null, "e": 3399, "s": 3307, "text": "With Pandas, column selection is done by passing a list of column names to your DataFrame −" }, { "code": null, "e": 3454, "s": 3399, "text": "tips[['total_bill', 'tip', 'smoker', 'time']].head(5)\n" }, { "code": null, "e": 3485, "s": 3454, "text": "Let’s check the full program −" }, { "code": null, "e": 3673, "s": 3485, "text": "import pandas as pd\n\nurl = 'https://raw.github.com/pandasdev/\npandas/master/pandas/tests/data/tips.csv'\n \ntips=pd.read_csv(url)\nprint tips[['total_bill', 'tip', 'smoker', 'time']].head(5)" }, { "code": null, "e": 3700, "s": 3673, "text": "Its output is as follows −" }, { "code": null, "e": 3923, "s": 3700, "text": " total_bill tip smoker time\n0 16.99 1.01 No Dinner\n1 10.34 1.66 No Dinner\n2 21.01 3.50 No Dinner\n3 23.68 3.31 No Dinner\n4 24.59 3.61 No Dinner\n" }, { "code": null, "e": 4022, "s": 3923, "text": "Calling the DataFrame without the list of column names will display all columns (akin to SQL’s *)." }, { "code": null, "e": 4067, "s": 4022, "text": "Filtering in SQL is done via a WHERE clause." }, { "code": null, "e": 4120, "s": 4067, "text": " SELECT * FROM tips WHERE time = 'Dinner' LIMIT 5;\n" }, { "code": null, "e": 4220, "s": 4120, "text": "DataFrames can be filtered in multiple ways; the most intuitive of which is using Boolean indexing." }, { "code": null, "e": 4262, "s": 4220, "text": " tips[tips['time'] == 'Dinner'].head(5)\n" }, { "code": null, "e": 4293, "s": 4262, "text": "Let’s check the full program −" }, { "code": null, "e": 4465, "s": 4293, "text": "import pandas as pd\n\nurl = 'https://raw.github.com/pandasdev/\npandas/master/pandas/tests/data/tips.csv'\n\ntips=pd.read_csv(url)\nprint tips[tips['time'] == 'Dinner'].head(5)" }, { "code": null, "e": 4492, "s": 4465, "text": "Its output is as follows −" }, { "code": null, "e": 4824, "s": 4492, "text": " total_bill tip sex smoker day time size\n0 16.99 1.01 Female No Sun Dinner 2\n1 10.34 1.66 Male No Sun Dinner 3\n2 21.01 3.50 Male No Sun Dinner 3\n3 23.68 3.31 Male No Sun Dinner 2\n4 24.59 3.61 Female No Sun Dinner 4\n" }, { "code": null, "e": 4930, "s": 4824, "text": "The above statement passes a Series of True/False objects to the DataFrame, returning all rows with True." }, { "code": null, "e": 5077, "s": 4930, "text": "This operation fetches the count of records in each group throughout a dataset. For instance, a query fetching us the number of tips left by sex −" }, { "code": null, "e": 5123, "s": 5077, "text": "SELECT sex, count(*)\nFROM tips\nGROUP BY sex;\n" }, { "code": null, "e": 5156, "s": 5123, "text": "The Pandas equivalent would be −" }, { "code": null, "e": 5184, "s": 5156, "text": "tips.groupby('sex').size()\n" }, { "code": null, "e": 5215, "s": 5184, "text": "Let’s check the full program −" }, { "code": null, "e": 5375, "s": 5215, "text": "import pandas as pd\n\nurl = 'https://raw.github.com/pandasdev/\npandas/master/pandas/tests/data/tips.csv'\n\ntips=pd.read_csv(url)\nprint tips.groupby('sex').size()" }, { "code": null, "e": 5402, "s": 5375, "text": "Its output is as follows −" }, { "code": null, "e": 5444, "s": 5402, "text": "sex\nFemale 87\nMale 157\ndtype: int64\n" }, { "code": null, "e": 5485, "s": 5444, "text": "SQL returns the top n rows using LIMIT −" }, { "code": null, "e": 5515, "s": 5485, "text": "SELECT * FROM tips\nLIMIT 5 ;\n" }, { "code": null, "e": 5548, "s": 5515, "text": "The Pandas equivalent would be −" }, { "code": null, "e": 5562, "s": 5548, "text": "tips.head(5)\n" }, { "code": null, "e": 5593, "s": 5562, "text": "Let’s check the full example −" }, { "code": null, "e": 5778, "s": 5593, "text": "import pandas as pd\n\nurl = 'https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv'\n\ntips=pd.read_csv(url)\ntips = tips[['smoker', 'day', 'time']].head(5)\nprint tips" }, { "code": null, "e": 5805, "s": 5778, "text": "Its output is as follows −" }, { "code": null, "e": 5956, "s": 5805, "text": " smoker day time\n0 No Sun Dinner\n1 No Sun Dinner\n2 No Sun Dinner\n3 No Sun Dinner\n4 No Sun Dinner\n" }, { "code": null, "e": 6073, "s": 5956, "text": "These are the few basic operations we compared are, which we learnt, in the previous chapters of the Pandas Library." }, { "code": null, "e": 6110, "s": 6073, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6126, "s": 6110, "text": " Malhar Lathkar" }, { "code": null, "e": 6159, "s": 6126, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6178, "s": 6159, "text": " Arnab Chakraborty" }, { "code": null, "e": 6213, "s": 6178, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6235, "s": 6213, "text": " In28Minutes Official" }, { "code": null, "e": 6269, "s": 6235, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6297, "s": 6269, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6332, "s": 6297, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6346, "s": 6332, "text": " Lets Kode It" }, { "code": null, "e": 6379, "s": 6346, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6396, "s": 6379, "text": " Abhilash Nelson" }, { "code": null, "e": 6403, "s": 6396, "text": " Print" }, { "code": null, "e": 6414, "s": 6403, "text": " Add Notes" } ]
How to click camera programmatically in android?
This example demonstrates how do I click camera programmatically in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center_horizontal" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click the below button to take photo from camera"/> <ImageView android:id="@+id/imageView" android:scaleType="centerCrop" android:layout_width="300dp" android:layout_height="400dp" android:src="@drawable/ic_image_black" android:layout_marginTop="16dp"/> <Button android:id="@+id/btnCaptureImage" android:text="Capture Image" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.Manifest; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_CODE = 1000; Button mCaptureBtn; ImageView mImageView; Uri imageUri; private int IMAGE_CAPTURE_CODE = 1001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView = findViewById(R.id.imageView); mCaptureBtn = findViewById(R.id.btnCaptureImage); mCaptureBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){ if (checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED(Manifest.permission.CAMERA).PERMISSION_DENIED){ String[] permission = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}; requestPermissions(permission,PERMISSION_CODE); } else{ openCamera(); } } } }); } private void openCamera() { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "New Picture"); values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera"); imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE); } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case PERMISSION_CODE:{ if (grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){ openCamera(); } else { Toast.makeText(this, "Permissiondenied...", Toast.LENGTH_SHORT).show(); } } } } @Override protected void onActivityResult(int requestCode, intresultCode, Intent data) { if (resultCode == RESULT_OK){ mImageView.setImageURI(imageUri); } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CAMERA"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrates how do I click camera programmatically in android." }, { "code": null, "e": 1268, "s": 1139, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2202, "s": 1333, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:layout_height=\"match_parent\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Click the below button to take photo from camera\"/>\n <ImageView\n android:id=\"@+id/imageView\"\n android:scaleType=\"centerCrop\"\n android:layout_width=\"300dp\"\n android:layout_height=\"400dp\"\n android:src=\"@drawable/ic_image_black\"\n android:layout_marginTop=\"16dp\"/>\n <Button\n android:id=\"@+id/btnCaptureImage\"\n android:text=\"Capture Image\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2259, "s": 2202, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4991, "s": 2259, "text": "import android.Manifest;\nimport android.content.ContentValues;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.provider.MediaStore;\nimport android.support.annotation.NonNull;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_CODE = 1000;\n Button mCaptureBtn;\n ImageView mImageView;\n Uri imageUri;\n private int IMAGE_CAPTURE_CODE = 1001;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n mImageView = findViewById(R.id.imageView);\n mCaptureBtn = findViewById(R.id.btnCaptureImage);\n mCaptureBtn.setOnClickListener(new\n View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){\n if (checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED(Manifest.permission.CAMERA).PERMISSION_DENIED){\n String[] permission = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};\n requestPermissions(permission,PERMISSION_CODE);\n } else{\n openCamera();\n }\n }\n }\n });\n }\n private void openCamera() {\n ContentValues values = new ContentValues();\n values.put(MediaStore.Images.Media.TITLE, \"New Picture\");\n values.put(MediaStore.Images.Media.DESCRIPTION, \"From the Camera\");\n imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);\n cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);\n startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);\n }\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n switch (requestCode){\n case PERMISSION_CODE:{\n if (grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){\n openCamera();\n } else {\n Toast.makeText(this, \"Permissiondenied...\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n }\n @Override\n protected void onActivityResult(int requestCode, intresultCode, Intent data) {\n if (resultCode == RESULT_OK){\n mImageView.setImageURI(imageUri);\n }\n }\n}" }, { "code": null, "e": 5046, "s": 4991, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5858, "s": 5046, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <uses-permission android:name=\"android.permission.CAMERA\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6205, "s": 5858, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 6246, "s": 6205, "text": "Click here to download the project code." } ]
Customize Django Admin Interface - GeeksforGeeks
06 Mar, 2020 Django admin by default is highly responsive GUI, which offers various features and an overall CRUD application to help developers and users. Moreover, Django admin can be customized to fulfill one’s needs such as showing fields on the home page of the table, etc. In this article, we will discuss how to enhance Django-admin Interface. Project structure looks like: Let us create an app called state which has one model with the same name(state). When we register app to admin.py it shows like. from django.db import modelsfrom django.utils import timezone class State(models.Model): name = models.CharField(max_length = 50) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now, null = True, blank = True ) def __str__(self): return self.name class Meta: db_table = 'state' state/admin.py: from django.contrib import adminfrom .models import State admin.site.register(State) Check it in the django admin interfaceNow lets’ customize django admin according to available options. 1. Change model name:If you want to change name of model which is States here so open model.py file and add verbose_name attribute in meta section. state/model.py from django.db import modelsfrom django.utils import timezone class State(models.Model): name = models.CharField(max_length = 50) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now, null = True, blank = True ) def __str__(self): return self.name class Meta: db_table = 'state' # Add verbose name verbose_name = 'State List' Output : 2. By default django admin shows only object name in listing. One can show multiple fields data from model. Add some lines of code in your admin.py file. state/admin.py: from django.contrib import adminfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True admin.site.register(State, StateAdmin) Output : 3. By default there is only one option which is delete option.One can add more option on Action dropdown: state/admin.py: from django.contrib import adminfrom django.contrib import messagesfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True def make_active(modeladmin, request, queryset): queryset.update(is_active = 1) messages.success(request, "Selected Record(s) Marked as Active Successfully !!") def make_inactive(modeladmin, request, queryset): queryset.update(is_active = 0) messages.success(request, "Selected Record(s) Marked as Inactive Successfully !!") admin.site.add_action(make_active, "Make Active") admin.site.add_action(make_inactive, "Make Inactive") admin.site.register(State, StateAdmin) Output: 4. Disable Delete option: state/admin.py: from django.contrib import adminfrom django.contrib import messagesfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True def make_active(modeladmin, request, queryset): queryset.update(is_active = 1) messages.success(request, "Selected Record(s) Marked as Active Successfully !!") def make_inactive(modeladmin, request, queryset): queryset.update(is_active = 0) messages.success(request, "Selected Record(s) Marked as Inactive Successfully !!") admin.site.add_action(make_active, "Make Active") admin.site.add_action(make_inactive, "Make Inactive") def has_delete_permission(self, request, obj = None): return False admin.site.register(State, StateAdmin) Output: 5. Remove Add option: state/admin.py: from django.contrib import adminfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True def has_add_permission(self, request): return False admin.site.register(State, StateAdmin) Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25883, "s": 25855, "text": "\n06 Mar, 2020" }, { "code": null, "e": 26220, "s": 25883, "text": "Django admin by default is highly responsive GUI, which offers various features and an overall CRUD application to help developers and users. Moreover, Django admin can be customized to fulfill one’s needs such as showing fields on the home page of the table, etc. In this article, we will discuss how to enhance Django-admin Interface." }, { "code": null, "e": 26250, "s": 26220, "text": "Project structure looks like:" }, { "code": null, "e": 26379, "s": 26250, "text": "Let us create an app called state which has one model with the same name(state). When we register app to admin.py it shows like." }, { "code": "from django.db import modelsfrom django.utils import timezone class State(models.Model): name = models.CharField(max_length = 50) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now, null = True, blank = True ) def __str__(self): return self.name class Meta: db_table = 'state'", "e": 27225, "s": 26379, "text": null }, { "code": null, "e": 27241, "s": 27225, "text": "state/admin.py:" }, { "code": "from django.contrib import adminfrom .models import State admin.site.register(State)", "e": 27327, "s": 27241, "text": null }, { "code": null, "e": 27430, "s": 27327, "text": "Check it in the django admin interfaceNow lets’ customize django admin according to available options." }, { "code": null, "e": 27578, "s": 27430, "text": "1. Change model name:If you want to change name of model which is States here so open model.py file and add verbose_name attribute in meta section." }, { "code": null, "e": 27593, "s": 27578, "text": "state/model.py" }, { "code": "from django.db import modelsfrom django.utils import timezone class State(models.Model): name = models.CharField(max_length = 50) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now, null = True, blank = True ) def __str__(self): return self.name class Meta: db_table = 'state' # Add verbose name verbose_name = 'State List'", "e": 28498, "s": 27593, "text": null }, { "code": null, "e": 28507, "s": 28498, "text": "Output :" }, { "code": null, "e": 28569, "s": 28507, "text": "2. By default django admin shows only object name in listing." }, { "code": null, "e": 28661, "s": 28569, "text": "One can show multiple fields data from model. Add some lines of code in your admin.py file." }, { "code": null, "e": 28677, "s": 28661, "text": "state/admin.py:" }, { "code": "from django.contrib import adminfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True admin.site.register(State, StateAdmin)", "e": 28951, "s": 28677, "text": null }, { "code": null, "e": 28960, "s": 28951, "text": "Output :" }, { "code": null, "e": 29066, "s": 28960, "text": "3. By default there is only one option which is delete option.One can add more option on Action dropdown:" }, { "code": null, "e": 29082, "s": 29066, "text": "state/admin.py:" }, { "code": "from django.contrib import adminfrom django.contrib import messagesfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True def make_active(modeladmin, request, queryset): queryset.update(is_active = 1) messages.success(request, \"Selected Record(s) Marked as Active Successfully !!\") def make_inactive(modeladmin, request, queryset): queryset.update(is_active = 0) messages.success(request, \"Selected Record(s) Marked as Inactive Successfully !!\") admin.site.add_action(make_active, \"Make Active\") admin.site.add_action(make_inactive, \"Make Inactive\") admin.site.register(State, StateAdmin)", "e": 29865, "s": 29082, "text": null }, { "code": null, "e": 29873, "s": 29865, "text": "Output:" }, { "code": null, "e": 29899, "s": 29873, "text": "4. Disable Delete option:" }, { "code": null, "e": 29915, "s": 29899, "text": "state/admin.py:" }, { "code": "from django.contrib import adminfrom django.contrib import messagesfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True def make_active(modeladmin, request, queryset): queryset.update(is_active = 1) messages.success(request, \"Selected Record(s) Marked as Active Successfully !!\") def make_inactive(modeladmin, request, queryset): queryset.update(is_active = 0) messages.success(request, \"Selected Record(s) Marked as Inactive Successfully !!\") admin.site.add_action(make_active, \"Make Active\") admin.site.add_action(make_inactive, \"Make Inactive\") def has_delete_permission(self, request, obj = None): return False admin.site.register(State, StateAdmin)", "e": 30777, "s": 29915, "text": null }, { "code": null, "e": 30785, "s": 30777, "text": "Output:" }, { "code": null, "e": 30807, "s": 30785, "text": "5. Remove Add option:" }, { "code": null, "e": 30823, "s": 30807, "text": "state/admin.py:" }, { "code": "from django.contrib import adminfrom .models import State class StateAdmin(admin.ModelAdmin): list_display = ('name', 'active', 'created_on') def active(self, obj): return obj.is_active == 1 active.boolean = True def has_add_permission(self, request): return False admin.site.register(State, StateAdmin)", "e": 31161, "s": 30823, "text": null }, { "code": null, "e": 31175, "s": 31161, "text": "Python Django" }, { "code": null, "e": 31182, "s": 31175, "text": "Python" }, { "code": null, "e": 31280, "s": 31182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31298, "s": 31280, "text": "Python Dictionary" }, { "code": null, "e": 31333, "s": 31298, "text": "Read a file line by line in Python" }, { "code": null, "e": 31365, "s": 31333, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31387, "s": 31365, "text": "Enumerate() in Python" }, { "code": null, "e": 31429, "s": 31387, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31459, "s": 31429, "text": "Iterate over a list in Python" }, { "code": null, "e": 31485, "s": 31459, "text": "Python String | replace()" }, { "code": null, "e": 31514, "s": 31485, "text": "*args and **kwargs in Python" }, { "code": null, "e": 31558, "s": 31514, "text": "Reading and Writing to text files in Python" } ]
Create a vignette filter using Python - OpenCV - GeeksforGeeks
27 Dec, 2021 In general, Images in computers are stored in the form of a matrix. In case of color image, Image is represented in the form of 3-dimensional matrix or one can say that we use three 2d matrices for representing three color channels one 2d matrix for representing red channel, one for green and one for representing blue. In the case of grayscale image, there exist a single channel so we use a single 2d matrix to represent grayscale images. Whenever we say kernel or mask, we generally refer to a small size matrix which can be used to apply effects on our image such as blurring, embossing, edge detection, sharpening etc and the process of applying these effect pixel by pixel is known as Convolution. To imagine how convolution works let’s consider the kernel of size 3×3 and consider the image matrix of size 9×9 as shown. Now we select the 3×3(same size as of kernel) block of pixels in the image matrix and multiply the block selected in the image with our kernel and then take the sum. That sum obtained as a resultant becomes our new pixel value and the position of this pixel value is the central position as shown by the blue color in the diagram. For obtaining the complete filtered image we roll the kernel matrix pixel by pixel over image matrix and carry out this process in the cycle. The Vignette filter is generally used to focus viewer attention on certain parts of the image without hiding other parts completely. Generally focused part has higher brightness and saturation and brightness and saturation decrease as we go radially out from center to periphery. Since we wish to keep the image’s brightness and saturation normal at the center and try to reduce this as we go radially outward from the center of the image so we should use a distribution function that assigns more weights to the nearest pixel as compare to the pixel which is far. This is the main reason we will be using Gaussian distribution and since we know that in Gaussian distribution most of the values are effectively close to zero and none zero. So we will be creating a mask of sufficiently large size. For creating 2-d Gaussian function we will be creating two 1-d Gaussian functions and multiply these two. One belonging to X-direction and other to the Y-direction. Since our current kernel matrix large in size so we will be normalizing to reduce the kernel size otherwise cost of applying a filter will be too large. OpenCV provides a function called getGaussianKernel which we will be using to build our 2D kernel whose size matches the size of the image. The first parameter of the function i.e. ksize: decide the size of kernel and we generally prefer odd, positive value. The second parameter of the function i.e. sigma : is the standard deviation of the Gaussian and it controls the radius of the bright central image. The function computes and returns the matrix of the size assigned in the first parameter and contains Gaussian filter coefficients. Mask = (scale size) * (Normalized kernel matrix ) After the Creation of the mask, we will iterate over all the color channels and apply the mask to each channel. Scaling is an important step otherwise all the pixel value be close to 0 after you superimpose the mask on image and the image will look black.Below is the implementation. Python3 import numpy as npimport cv2 #reading the imageinput_image = cv2.imread('food.jpeg') #resizing the image according to our need# resize() function takes 2 parameters, # the image and the dimensionsinput_image = cv2.resize(input_image, (480, 480)) # Extracting the height and width of an imagerows, cols = input_image.shape[:2] # generating vignette mask using Gaussian# resultant_kernelsX_resultant_kernel = cv2.getGaussianKernel(cols,200)Y_resultant_kernel = cv2.getGaussianKernel(rows,200) #generating resultant_kernel matrixresultant_kernel = Y_resultant_kernel * X_resultant_kernel.T #creating mask and normalising by using np.linalg# functionmask = 255 * resultant_kernel / np.linalg.norm(resultant_kernel)output = np.copy(input_image) # applying the mask to each channel in the input imagefor i in range(3): output[:,:,i] = output[:,:,i] * mask #displaying the original image cv2.imshow('Original', input_image) #displaying the vignette filter imagecv2.imshow('VIGNETTE', output) # Maintain output window utill# user presses a keycv2.waitKey(0) # Destroying present windows on screencv2.destroyAllWindows() Output: gulshankumarar231 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24579, "s": 24551, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25021, "s": 24579, "text": "In general, Images in computers are stored in the form of a matrix. In case of color image, Image is represented in the form of 3-dimensional matrix or one can say that we use three 2d matrices for representing three color channels one 2d matrix for representing red channel, one for green and one for representing blue. In the case of grayscale image, there exist a single channel so we use a single 2d matrix to represent grayscale images." }, { "code": null, "e": 25284, "s": 25021, "text": "Whenever we say kernel or mask, we generally refer to a small size matrix which can be used to apply effects on our image such as blurring, embossing, edge detection, sharpening etc and the process of applying these effect pixel by pixel is known as Convolution." }, { "code": null, "e": 25880, "s": 25284, "text": "To imagine how convolution works let’s consider the kernel of size 3×3 and consider the image matrix of size 9×9 as shown. Now we select the 3×3(same size as of kernel) block of pixels in the image matrix and multiply the block selected in the image with our kernel and then take the sum. That sum obtained as a resultant becomes our new pixel value and the position of this pixel value is the central position as shown by the blue color in the diagram. For obtaining the complete filtered image we roll the kernel matrix pixel by pixel over image matrix and carry out this process in the cycle." }, { "code": null, "e": 26161, "s": 25880, "text": "The Vignette filter is generally used to focus viewer attention on certain parts of the image without hiding other parts completely. Generally focused part has higher brightness and saturation and brightness and saturation decrease as we go radially out from center to periphery. " }, { "code": null, "e": 26997, "s": 26161, "text": "Since we wish to keep the image’s brightness and saturation normal at the center and try to reduce this as we go radially outward from the center of the image so we should use a distribution function that assigns more weights to the nearest pixel as compare to the pixel which is far. This is the main reason we will be using Gaussian distribution and since we know that in Gaussian distribution most of the values are effectively close to zero and none zero. So we will be creating a mask of sufficiently large size. For creating 2-d Gaussian function we will be creating two 1-d Gaussian functions and multiply these two. One belonging to X-direction and other to the Y-direction. Since our current kernel matrix large in size so we will be normalizing to reduce the kernel size otherwise cost of applying a filter will be too large." }, { "code": null, "e": 27137, "s": 26997, "text": "OpenCV provides a function called getGaussianKernel which we will be using to build our 2D kernel whose size matches the size of the image." }, { "code": null, "e": 27536, "s": 27137, "text": "The first parameter of the function i.e. ksize: decide the size of kernel and we generally prefer odd, positive value. The second parameter of the function i.e. sigma : is the standard deviation of the Gaussian and it controls the radius of the bright central image. The function computes and returns the matrix of the size assigned in the first parameter and contains Gaussian filter coefficients." }, { "code": null, "e": 27586, "s": 27536, "text": "Mask = (scale size) * (Normalized kernel matrix )" }, { "code": null, "e": 27870, "s": 27586, "text": "After the Creation of the mask, we will iterate over all the color channels and apply the mask to each channel. Scaling is an important step otherwise all the pixel value be close to 0 after you superimpose the mask on image and the image will look black.Below is the implementation." }, { "code": null, "e": 27878, "s": 27870, "text": "Python3" }, { "code": "import numpy as npimport cv2 #reading the imageinput_image = cv2.imread('food.jpeg') #resizing the image according to our need# resize() function takes 2 parameters, # the image and the dimensionsinput_image = cv2.resize(input_image, (480, 480)) # Extracting the height and width of an imagerows, cols = input_image.shape[:2] # generating vignette mask using Gaussian# resultant_kernelsX_resultant_kernel = cv2.getGaussianKernel(cols,200)Y_resultant_kernel = cv2.getGaussianKernel(rows,200) #generating resultant_kernel matrixresultant_kernel = Y_resultant_kernel * X_resultant_kernel.T #creating mask and normalising by using np.linalg# functionmask = 255 * resultant_kernel / np.linalg.norm(resultant_kernel)output = np.copy(input_image) # applying the mask to each channel in the input imagefor i in range(3): output[:,:,i] = output[:,:,i] * mask #displaying the original image cv2.imshow('Original', input_image) #displaying the vignette filter imagecv2.imshow('VIGNETTE', output) # Maintain output window utill# user presses a keycv2.waitKey(0) # Destroying present windows on screencv2.destroyAllWindows()", "e": 29025, "s": 27878, "text": null }, { "code": null, "e": 29034, "s": 29025, "text": "Output: " }, { "code": null, "e": 29054, "s": 29036, "text": "gulshankumarar231" }, { "code": null, "e": 29068, "s": 29054, "text": "Python-OpenCV" }, { "code": null, "e": 29075, "s": 29068, "text": "Python" }, { "code": null, "e": 29173, "s": 29075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29182, "s": 29173, "text": "Comments" }, { "code": null, "e": 29195, "s": 29182, "text": "Old Comments" }, { "code": null, "e": 29213, "s": 29195, "text": "Python Dictionary" }, { "code": null, "e": 29248, "s": 29213, "text": "Read a file line by line in Python" }, { "code": null, "e": 29270, "s": 29248, "text": "Enumerate() in Python" }, { "code": null, "e": 29302, "s": 29270, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29332, "s": 29302, "text": "Iterate over a list in Python" }, { "code": null, "e": 29374, "s": 29332, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29400, "s": 29374, "text": "Python String | replace()" }, { "code": null, "e": 29443, "s": 29400, "text": "Python program to convert a list to string" }, { "code": null, "e": 29487, "s": 29443, "text": "Reading and Writing to text files in Python" } ]
C++ program to check whether a String is a Pangram or not - GeeksforGeeks
30 Jul, 2020 Given string str, the task is to check whether a string is pangram or not using in C++. A string is a Pangram if the string contains all the English alphabet letters. Examples: Input: str = “We promptly judged antique ivory buckles for the next prize”Output: YesExplanations: In the above string, str has all the English alphabet letters. Input: str = “We promptly judged antique ivory buckles for the prize”Output: No This approach is based on Hashing. A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’ and so on. Traverse the string character by character and mark the particular character as present in the Hash. After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False. A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’ and so on. Traverse the string character by character and mark the particular character as present in the Hash. After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False. Below is the implementation of the above approach: C++ // C++ Program to check if the given// string is a pangram or not #include <bits/stdc++.h>using namespace std; // Returns true if the string is// pangram else falsebool checkPangram(string& str){ // Create a hash table to mark // the characters // present in the string vector<bool> mark(26, false); // For indexing in mark[] int index; // Traverse all characters for (int i = 0; i < str.length(); i++) { // If uppercase character, // subtract 'A' to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, // subtract 'a' to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is not // an alphabet, skip to next one. else continue; mark[index] = true; } // Return false // if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true);} // Driver Codeint main(){ string str = "We promptly judged" " antique ivory" " buckles for the next prize"; if (checkPangram(str) == true) printf("Yes"); else printf("No"); return (0);} Yes Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(1) The transform() method of STL can be used to check whether the given string is Pangram or not. Syntax: transform(s.begin(), s.end(), s.begin(), ::toupper); Approach:In order to check if the string contains all the alphabets of the English alphabet: Step 1: Firstly convert all the letters into uppercase or lowercase because if it will check without converting, the lowercase and uppercase alphabets will be considered as different letters. Step 2: Sort the string and check the distinct letter. Step 3: Space will also be considered as a distinct entity. Step 4: Now check if count =27 then the string contains all the 26 alphabets. Below is the implementation of the above approach: CPP // C++ Program to check whether// a string pangram or not using STL #include <bits/stdc++.h>using namespace std; // Function to return given string// str is pangrams yes or nostring pangrams(string s){ // Initialization of count int count = 0; // Convert each letter into // uppercase to avoid counting // of both uppercase and // lowercase as different letters transform(s.begin(), s.end(), s.begin(), ::toupper); // Sort the string sort(s.begin(), s.end()); // Count distinct alphabets for (int i = 0; i < s.size(); i++) { if (s[i] != s[i + 1]) count++; } // If count is 27 then the string // contains all the alphabets // including space as a // distinct character if (count == 27) return "Yes"; else return "No";} // Driver codeint main(){ // Given string str string str = "We promptly " "judged antique" "ivory buckles for " "the next prize"; // Function Call cout << pangrams(str); return 0;} Yes Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(1) cpp-strings STL C++ Hash Strings cpp-strings Hash Strings STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 23810, "s": 23782, "text": "\n30 Jul, 2020" }, { "code": null, "e": 23898, "s": 23810, "text": "Given string str, the task is to check whether a string is pangram or not using in C++." }, { "code": null, "e": 23977, "s": 23898, "text": "A string is a Pangram if the string contains all the English alphabet letters." }, { "code": null, "e": 23988, "s": 23977, "text": "Examples: " }, { "code": null, "e": 24150, "s": 23988, "text": "Input: str = “We promptly judged antique ivory buckles for the next prize”Output: YesExplanations: In the above string, str has all the English alphabet letters." }, { "code": null, "e": 24230, "s": 24150, "text": "Input: str = “We promptly judged antique ivory buckles for the prize”Output: No" }, { "code": null, "e": 24266, "s": 24230, "text": "This approach is based on Hashing. " }, { "code": null, "e": 24706, "s": 24266, "text": "A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’ and so on. Traverse the string character by character and mark the particular character as present in the Hash. After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False." }, { "code": null, "e": 24861, "s": 24706, "text": "A Hashing data structure of boolean type is created of size 26, such that index 0 represents the character ‘a’, 1 represents the character ‘b’ and so on. " }, { "code": null, "e": 24963, "s": 24861, "text": "Traverse the string character by character and mark the particular character as present in the Hash. " }, { "code": null, "e": 25148, "s": 24963, "text": "After complete traversal and marking of the string, traverse the Hash and see if all characters are present, i.e. every index has true. If all are marked, then return true, else False." }, { "code": null, "e": 25199, "s": 25148, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25203, "s": 25199, "text": "C++" }, { "code": "// C++ Program to check if the given// string is a pangram or not #include <bits/stdc++.h>using namespace std; // Returns true if the string is// pangram else falsebool checkPangram(string& str){ // Create a hash table to mark // the characters // present in the string vector<bool> mark(26, false); // For indexing in mark[] int index; // Traverse all characters for (int i = 0; i < str.length(); i++) { // If uppercase character, // subtract 'A' to find index. if ('A' <= str[i] && str[i] <= 'Z') index = str[i] - 'A'; // If lowercase character, // subtract 'a' to find index. else if ('a' <= str[i] && str[i] <= 'z') index = str[i] - 'a'; // If this character is not // an alphabet, skip to next one. else continue; mark[index] = true; } // Return false // if any character is unmarked for (int i = 0; i <= 25; i++) if (mark[i] == false) return (false); // If all characters were present return (true);} // Driver Codeint main(){ string str = \"We promptly judged\" \" antique ivory\" \" buckles for the next prize\"; if (checkPangram(str) == true) printf(\"Yes\"); else printf(\"No\"); return (0);}", "e": 26556, "s": 25203, "text": null }, { "code": null, "e": 26560, "s": 26556, "text": "Yes" }, { "code": null, "e": 26641, "s": 26560, "text": "Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(1)" }, { "code": null, "e": 26736, "s": 26641, "text": "The transform() method of STL can be used to check whether the given string is Pangram or not." }, { "code": null, "e": 26744, "s": 26736, "text": "Syntax:" }, { "code": null, "e": 26797, "s": 26744, "text": "transform(s.begin(), s.end(), s.begin(), ::toupper);" }, { "code": null, "e": 26891, "s": 26797, "text": "Approach:In order to check if the string contains all the alphabets of the English alphabet: " }, { "code": null, "e": 27277, "s": 26891, "text": "Step 1: Firstly convert all the letters into uppercase or lowercase because if it will check without converting, the lowercase and uppercase alphabets will be considered as different letters. Step 2: Sort the string and check the distinct letter. Step 3: Space will also be considered as a distinct entity. Step 4: Now check if count =27 then the string contains all the 26 alphabets. " }, { "code": null, "e": 27328, "s": 27277, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27332, "s": 27328, "text": "CPP" }, { "code": "// C++ Program to check whether// a string pangram or not using STL #include <bits/stdc++.h>using namespace std; // Function to return given string// str is pangrams yes or nostring pangrams(string s){ // Initialization of count int count = 0; // Convert each letter into // uppercase to avoid counting // of both uppercase and // lowercase as different letters transform(s.begin(), s.end(), s.begin(), ::toupper); // Sort the string sort(s.begin(), s.end()); // Count distinct alphabets for (int i = 0; i < s.size(); i++) { if (s[i] != s[i + 1]) count++; } // If count is 27 then the string // contains all the alphabets // including space as a // distinct character if (count == 27) return \"Yes\"; else return \"No\";} // Driver codeint main(){ // Given string str string str = \"We promptly \" \"judged antique\" \"ivory buckles for \" \"the next prize\"; // Function Call cout << pangrams(str); return 0;}", "e": 28440, "s": 27332, "text": null }, { "code": null, "e": 28444, "s": 28440, "text": "Yes" }, { "code": null, "e": 28525, "s": 28444, "text": "Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(1)" }, { "code": null, "e": 28537, "s": 28525, "text": "cpp-strings" }, { "code": null, "e": 28541, "s": 28537, "text": "STL" }, { "code": null, "e": 28545, "s": 28541, "text": "C++" }, { "code": null, "e": 28550, "s": 28545, "text": "Hash" }, { "code": null, "e": 28558, "s": 28550, "text": "Strings" }, { "code": null, "e": 28570, "s": 28558, "text": "cpp-strings" }, { "code": null, "e": 28575, "s": 28570, "text": "Hash" }, { "code": null, "e": 28583, "s": 28575, "text": "Strings" }, { "code": null, "e": 28587, "s": 28583, "text": "STL" }, { "code": null, "e": 28591, "s": 28587, "text": "CPP" }, { "code": null, "e": 28689, "s": 28591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28698, "s": 28689, "text": "Comments" }, { "code": null, "e": 28711, "s": 28698, "text": "Old Comments" }, { "code": null, "e": 28739, "s": 28711, "text": "Operator Overloading in C++" }, { "code": null, "e": 28763, "s": 28739, "text": "Sorting a vector in C++" }, { "code": null, "e": 28783, "s": 28763, "text": "Polymorphism in C++" }, { "code": null, "e": 28816, "s": 28783, "text": "Friend class and function in C++" }, { "code": null, "e": 28860, "s": 28816, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 28945, "s": 28860, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 28981, "s": 28945, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 29012, "s": 28981, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 29039, "s": 29012, "text": "Count pairs with given sum" } ]
Suppress Warnings Globally in R - GeeksforGeeks
31 Aug, 2021 In this article, we are going to discuss how to suppress warnings globally in R programming language. A warning is a message that does not disturb the program flow but displays the warning along with the output. In order to suppress the warnings globally, we have to set warn=-1 in the options function Syntax: options(warn = – 1) If you want to see the warnings then set warn=0 Example: R program to see the warning when using pmax and pmin R # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5)) # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5)) Output: Example: R program to suppress the warning messages when using pmax and pmin R # suppress the warnings by setting warn=-1options(warn=-1) # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5)) # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5)) Output: 12345 12312 If we want to see the warnings again, set warn=0 Example: R program to again see the warnings R # display the warnings by setting warn=0options(warn=0) # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5)) # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5)) Output: Picked R-basics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24953, "s": 24851, "text": "In this article, we are going to discuss how to suppress warnings globally in R programming language." }, { "code": null, "e": 25154, "s": 24953, "text": "A warning is a message that does not disturb the program flow but displays the warning along with the output. In order to suppress the warnings globally, we have to set warn=-1 in the options function" }, { "code": null, "e": 25162, "s": 25154, "text": "Syntax:" }, { "code": null, "e": 25185, "s": 25162, "text": "options(warn = – 1) " }, { "code": null, "e": 25233, "s": 25185, "text": "If you want to see the warnings then set warn=0" }, { "code": null, "e": 25296, "s": 25233, "text": "Example: R program to see the warning when using pmax and pmin" }, { "code": null, "e": 25298, "s": 25296, "text": "R" }, { "code": "# pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5)) # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5))", "e": 25577, "s": 25298, "text": null }, { "code": null, "e": 25585, "s": 25577, "text": "Output:" }, { "code": null, "e": 25662, "s": 25585, "text": "Example: R program to suppress the warning messages when using pmax and pmin" }, { "code": null, "e": 25664, "s": 25662, "text": "R" }, { "code": "# suppress the warnings by setting warn=-1options(warn=-1) # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5)) # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5))", "e": 26003, "s": 25664, "text": null }, { "code": null, "e": 26011, "s": 26003, "text": "Output:" }, { "code": null, "e": 26023, "s": 26011, "text": "12345\n12312" }, { "code": null, "e": 26072, "s": 26023, "text": "If we want to see the warnings again, set warn=0" }, { "code": null, "e": 26117, "s": 26072, "text": "Example: R program to again see the warnings" }, { "code": null, "e": 26119, "s": 26117, "text": "R" }, { "code": "# display the warnings by setting warn=0options(warn=0) # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5)) # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5))", "e": 26455, "s": 26119, "text": null }, { "code": null, "e": 26463, "s": 26455, "text": "Output:" }, { "code": null, "e": 26470, "s": 26463, "text": "Picked" }, { "code": null, "e": 26479, "s": 26470, "text": "R-basics" }, { "code": null, "e": 26490, "s": 26479, "text": "R Language" }, { "code": null, "e": 26588, "s": 26490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26597, "s": 26588, "text": "Comments" }, { "code": null, "e": 26610, "s": 26597, "text": "Old Comments" }, { "code": null, "e": 26662, "s": 26610, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26700, "s": 26662, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26735, "s": 26700, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26793, "s": 26735, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26842, "s": 26793, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26885, "s": 26842, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26935, "s": 26885, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26952, "s": 26935, "text": "R - if statement" }, { "code": null, "e": 26989, "s": 26952, "text": "How to import an Excel File into R ?" } ]
Tryit Editor v3.7 - Show Java
public class Main { public static void main(String[] args) { int myNum = 5; // integer (whole number) float myFloatNum = 5.99f; // floating point number char myLetter = 'D'; // character boolean myBool = true; // boolean String myText = "Hello"; // String
[]
Space Science with Python #1 - Setup and first steps | Towards Data Science
Space Science with Python. It may sound challenging, complex and broad. During my time in the university, I got some experience in different Space Science related fields that I linked to data science and machine learning methods. With this part #1 of my tutorial series, I would like to share my experience and knowledge with the community: with all the developers, makers, students or passionate space and programming fans out there. I provide a lot of details in the beginning so that everyone is able to follow the tutorial and the content of the library. After some time, when we get more familiar with everything, we can focus on scientific tasks beyond the basics. To follow and understand the tutorials I recommend having a solid basic knowledge of Python. We will work with Python 3 and I recommend setting up a virtual environment on your machine, where you can install all necessary packages and where you can “play around”. Below, you will find a brief description of how to set up a virtual environment. All scripts are uploaded on my public GitHub (https://github.com/ThomasAlbin/SpaceScienceTutorial) repository where you can find the Jupyter notebooks and stand-alone Python scripts. I would recommend cloning the repository. The installation of all shown libraries has been tested on Linux (Ubuntu and Debian) as well as on Mac OS. If you encounter any issues on Windows, let’s try to figure it out together, for example on the corresponding Reddit post that brought you here. Some basic knowledge of the Solar System and its celestial bodies is a small advantage, but again: do not worry. We start with basic concepts, and between the tutorials, you will have some time to read into these topics. If you would like to have more explanations in this regard, please let me know. First, we need to set up a virtual environment where we can install our packages. Open the terminal and change to the directory, where you want to install your environment. Assuming that you already installed Python 3, you can set up the environment by executing the following command. pythonenv will be the name of the environment: python3 -m venv pythonenv You can now activate the virtual environment by executing: source pythonenv/bin/activate In the terminal, next to your username, the name of the environment should be displayed in round brackets like (pythonenv). With the Python package manager pip3 one can easily install any Python library. For starters, I would recommend installing the SciPy suite that will be used frequently. It also contains Jupyter (it can be started within the cloned Git project by executing jupyter notebook): pip3 install numpy scipy matplotlib ipython jupyter pandas sympy nose In the next couple of weeks, we will focus together on the Solar System, its bodies, spacecraft missions and scientific results. We will learn miscellaneous methods, data scientific approaches and libraries. On my very first post, I mentioned a NASA toolkit called SPICE (Spacecraft Planet Instrument C-matrix Events). This toolkit will be the core of our first sessions. SPICE is a huge toolkit that is being used by the Solar System science community to determine e.g., a planet’s position, the coordinates of an asteroid in the sky, or whether the Field-Of-View of a spacecraft camera aims to the surface of a celestial body (and much more). NASA provides a sophisticated overview with documentation and presentations on their website: SPICE NAIF. The toolkit is provided in C, Fortran, IDL, Matlab and Java. Thanks to the community member AndrewAnnex, a Python wrapper is available that uses the C version of SPICE: https://github.com/AndrewAnnex/SpiceyPy. You can install the Python wrapper by executing the following command. However, please ensure that you have a C compiler installed like gcc on Linux. XCode should provide all necessary software requirements for your Mac system: pip3 install spiceypy Now we are ready for lift-off. Before we dive into the programming part, let’s have a look at SPICE. SPICE has been developed to provide a common toolkit for planetary scientists and engineers to compute miscellaneous space mission-relevant information like: Reference frames Positions and velocities Orientation/Pointing Size/Shapes/Physical parameters Time conversion We will aim all these topics to understand what they mean and where to use them. SPICE does not calculate computational heavy tasks like N-body simulations, re-entry scenarios or complex manoeuvrers. It uses existing data to provide common access to a large variety of Solar System related problems (a short overview that is provided by NASA can be seen here: NASA Spice Overview). Out of the box, SPICE cannot calculate a lot. It requires auxiliary data, so-called kernels to work properly. These kernels are separated into different categories, like: spk contain trajectory information of planetary bodies, spacecraft, etc. pck contain physical parameters of bodies like the size or orientation ik contain instrument-specific information that are e.g., mounted on a spacecraft ck contain information regarding the orientation of a spacecraft in space fk contain reference frame information that is needed to calculate positions in a less common reference system lsk contain time information that is crucial to convert e.g., the UTC time into ephemeris time ET (a standard time format that is being used in space science and astronomy) We will get in touch with all of these kernels. You may ask: Why are the information stored in additional files? Why is the data not stored in one huge toolkit, since we should know the trajectory of certain spacecraft? Well, you are right, but there are dozens of missions out there and a lot of missions are being prepared. Especially the planned missions have “pre-planned” or “predicted” trajectories that are frequently updated. Further, different institutes work on different missions. It would be a struggle to contact everyone to gather all information. Thus, each mission, instrument and so on is separated. NASA and ESA provide repositories with a lot of kernels. One example is here: SPICE Kernels The screenshot above shows some mission kernel folders, like the Apollo missions or the Cassini spacecraft that went to Saturn. A core part is stored in the generic_kernels folders, where planetary information are stored. For starters, all kernels that are needed for this article are stored on my GitHub repository. Later, however, we will need kernels that are huge and need to be downloaded and manually stored by you. We will get to this point in a few weeks. As you can see in the downloaded repository, I prepared a kernel folder called _kernels. We will use the kernels in a few moments. Now that we are set up, we can define the first goal for today. Let’s compute the Earth’s position and velocity vector (so-called state vector) for today, midnight. Further, we compare the orbital speed of our home planet with the theoretical expectation. First, we import the SPICE wrapper library spicepy. If no error occurs the installation went well and we can continue. We want to determine the position of our home planet with respect to the Sun. How can we achieve this with SPICE? Let’s have a look at the reference guide of SPICE: SPICE Docs. Well, there are a lot of functions (and do not forget that we need kernels, too). It appears to be overwhelming, but that’s what the tutorial is for: to support you in this regard. What we need is the function spkgeo (Please note: this is the documentation of the C library, thus every function name has the _C suffix that needs to be removed for Python): spkgeo doc. The documentation says: Abstract Compute the geometric state (position and velocity) of a target body relative to an observing body. That’s what we need. The input parameters are the target body (Earth), the ET, the reference frame and the observer (Sun). So in a first step, we need to convert a UTC string to the ET. We use the function utc2et for this purpose: utc2et doc. We determine today’s date and create a string of the format year-month-day-hours:minutes:seconds. The documentation of the utc2et function provides all possible time formats in the section Examples. Although it is not required to explicitly write 00:00:00 for midnight, we do it for the sake of completeness (Spoiler: the following code snippet causes an error!): An error occurred. Why? As mentioned before, most information is stored in the kernel files. Here, we cannot convert between the times, because of a missing lsk. The tutorial repository contains the needed file (naif0012.tls) and can be found in the official repository here: SPICE lsk kernels. The kernel is loaded with the SPICE function furnsh. We re-execute the command... ... and no error occurs. Let’s have a look at the value: For today (2020.04.21) the result is 640699269.1855832. Now let’s try the command spkgeo that shall compute the Earth’s state vector. But what are the target’s and observer’s name? Apparently “Earth” and “Sun”; however, SPICE uses the so-called NAIF IDs to identify an object. The complete list can be found here: NAIF IDs. Search for the number 399. That’s the Earth! And the Sun has the number 10. The reference frame is set as “ECLIPJ2000” and refers to the ecliptic reference frame at the time J2000 (no kernel needed for this basic frame). Image a table and at the centre of the table, you put something that represents the Sun. Use another object representing the Earth and circle it around the Sun. The table is the so-called “Ecliptic Plane” of our planet. Other planets have their own plane and are slightly inclined with respect to the Earth’s plane. Why J2000? Astronomers set the plane for our planet at a certain time of the year 2000. Due to gravitational perturbations, our current “2020 plane” is very, very slightly inclined with respect to the J2000 plane. Instead of re-defining it every year, we use the 2000-version (Spoiler: another error appears here (the last one, I promise!)): Another kernel is missing. This time it’s an spk. Let’s have a deep dive into this problem. We go to the repository page (you do not need to download anything, since I already put it in the _kernel folder): SPICE kernels ... and go to generic_kernels. There we need to go into spk and then planets since we want to compute the state vector of our planet. We find the following status for today: Every folder has aa_*.txt files. Let’s check aa_summaries.txt. The file lists meta data for miscellaneous kernels. It shows which objects are computed w.r.t. which other body object. Note: Mercury’s barycentre and Venus’ barycentre are both available w.r.t. the Solar System barycentre. Thanks to simple addition SPICE can easily compute the distance between both planetary barycentres. The last line shows the time coverage. We take the file de432s.bsp, since it is quite small and covers the time interval of our interest: We load the kernel: Re-compute the state vector: And print it out. We get: [-1.28760839e+08, -7.76110220e+07, 4.32943029e+03, 1.48939328e+01, -2.56361729e+01, 1.00712291e-03]. The first 3 values are the x, y, z components in km. The last 3 values are the corresponding velocity components in km/s. We can verify the results by using NASA’s HORIZONS Web-Interface. In an extra tutorial, I will explain to you how to use this web application, since it allows one to adjust a lot of parameters. After some clicking I got the following results: [-1.287618689589618E+08, -7.760924828577068E+07, 4.329366157151759E+03, 1.489358282611585E+01, -2.563638289196221E+01, 1.007311359298768E-03]. We compare the x-position component and notice a deviation of around 1000 km. That is not a lot, but theoretically, it should be 0 km?! Well, in this case, HORIZONS uses a kernel called DE431mx. Different kernels may have different precise values. Another simple way to check whether our results make sense is to determine the distance between the Sun and Earth. It should be around 1 astronomical unit (1 AU). First, we compute the distance in km: And with the SPICE function convrt (convrt doc) we can change the km values to AU (no kernel needed). The results is close to 1 AU. Let’s do the last task. We compute the orbital speed of the Earth in km/s: The value is close to 30 km/s. But does it make sense? The theoretical expectation of the orbital velocity can be approximated with the following equation, where G is the gravitational constant, M is the mass of the Sun, and r is the distance between the Earth and Sun: We use the kernel gm_de431.tpc from the generic_kernels directory (pck) and load it. With the function bodvcd we get the G*M value for the Sun (bodvcd doc). The bodyid is again 10, the required item is GM and maxn is an input parameter that sets the number of expected returns (here, it is 1): Again, we get a value close to 30 km/s! I hope you enjoyed the first tutorial and got an impression of how SPICE “thinks” and how to use it. We will use this library and explore further features in the next tutorials to get more hands-on experience. The SPICE introductions will be a solid basis for later scientific tutorials. Please let me know (here or on Reddit: https://www.reddit.com/user/MrAstroThomas), if you liked it, what you missed or any other question. I try to answer as many as possible. The next tutorial will be published on Saturday (2020.04.25), hopefully with a GitHub Gist integration. We will analyse the first law of Kepler’s law: The orbit of a planet is an ellipse with the Sun at one of the two foci Is this statement 100 % correct? We will see. I wish you all the best during these challenging times,
[ { "code": null, "e": 482, "s": 47, "text": "Space Science with Python. It may sound challenging, complex and broad. During my time in the university, I got some experience in different Space Science related fields that I linked to data science and machine learning methods. With this part #1 of my tutorial series, I would like to share my experience and knowledge with the community: with all the developers, makers, students or passionate space and programming fans out there." }, { "code": null, "e": 718, "s": 482, "text": "I provide a lot of details in the beginning so that everyone is able to follow the tutorial and the content of the library. After some time, when we get more familiar with everything, we can focus on scientific tasks beyond the basics." }, { "code": null, "e": 1540, "s": 718, "text": "To follow and understand the tutorials I recommend having a solid basic knowledge of Python. We will work with Python 3 and I recommend setting up a virtual environment on your machine, where you can install all necessary packages and where you can “play around”. Below, you will find a brief description of how to set up a virtual environment. All scripts are uploaded on my public GitHub (https://github.com/ThomasAlbin/SpaceScienceTutorial) repository where you can find the Jupyter notebooks and stand-alone Python scripts. I would recommend cloning the repository. The installation of all shown libraries has been tested on Linux (Ubuntu and Debian) as well as on Mac OS. If you encounter any issues on Windows, let’s try to figure it out together, for example on the corresponding Reddit post that brought you here." }, { "code": null, "e": 1841, "s": 1540, "text": "Some basic knowledge of the Solar System and its celestial bodies is a small advantage, but again: do not worry. We start with basic concepts, and between the tutorials, you will have some time to read into these topics. If you would like to have more explanations in this regard, please let me know." }, { "code": null, "e": 2174, "s": 1841, "text": "First, we need to set up a virtual environment where we can install our packages. Open the terminal and change to the directory, where you want to install your environment. Assuming that you already installed Python 3, you can set up the environment by executing the following command. pythonenv will be the name of the environment:" }, { "code": null, "e": 2200, "s": 2174, "text": "python3 -m venv pythonenv" }, { "code": null, "e": 2259, "s": 2200, "text": "You can now activate the virtual environment by executing:" }, { "code": null, "e": 2289, "s": 2259, "text": "source pythonenv/bin/activate" }, { "code": null, "e": 2413, "s": 2289, "text": "In the terminal, next to your username, the name of the environment should be displayed in round brackets like (pythonenv)." }, { "code": null, "e": 2688, "s": 2413, "text": "With the Python package manager pip3 one can easily install any Python library. For starters, I would recommend installing the SciPy suite that will be used frequently. It also contains Jupyter (it can be started within the cloned Git project by executing jupyter notebook):" }, { "code": null, "e": 2758, "s": 2688, "text": "pip3 install numpy scipy matplotlib ipython jupyter pandas sympy nose" }, { "code": null, "e": 3403, "s": 2758, "text": "In the next couple of weeks, we will focus together on the Solar System, its bodies, spacecraft missions and scientific results. We will learn miscellaneous methods, data scientific approaches and libraries. On my very first post, I mentioned a NASA toolkit called SPICE (Spacecraft Planet Instrument C-matrix Events). This toolkit will be the core of our first sessions. SPICE is a huge toolkit that is being used by the Solar System science community to determine e.g., a planet’s position, the coordinates of an asteroid in the sky, or whether the Field-Of-View of a spacecraft camera aims to the surface of a celestial body (and much more)." }, { "code": null, "e": 3719, "s": 3403, "text": "NASA provides a sophisticated overview with documentation and presentations on their website: SPICE NAIF. The toolkit is provided in C, Fortran, IDL, Matlab and Java. Thanks to the community member AndrewAnnex, a Python wrapper is available that uses the C version of SPICE: https://github.com/AndrewAnnex/SpiceyPy." }, { "code": null, "e": 3947, "s": 3719, "text": "You can install the Python wrapper by executing the following command. However, please ensure that you have a C compiler installed like gcc on Linux. XCode should provide all necessary software requirements for your Mac system:" }, { "code": null, "e": 3969, "s": 3947, "text": "pip3 install spiceypy" }, { "code": null, "e": 4000, "s": 3969, "text": "Now we are ready for lift-off." }, { "code": null, "e": 4228, "s": 4000, "text": "Before we dive into the programming part, let’s have a look at SPICE. SPICE has been developed to provide a common toolkit for planetary scientists and engineers to compute miscellaneous space mission-relevant information like:" }, { "code": null, "e": 4245, "s": 4228, "text": "Reference frames" }, { "code": null, "e": 4270, "s": 4245, "text": "Positions and velocities" }, { "code": null, "e": 4291, "s": 4270, "text": "Orientation/Pointing" }, { "code": null, "e": 4323, "s": 4291, "text": "Size/Shapes/Physical parameters" }, { "code": null, "e": 4339, "s": 4323, "text": "Time conversion" }, { "code": null, "e": 4420, "s": 4339, "text": "We will aim all these topics to understand what they mean and where to use them." }, { "code": null, "e": 4721, "s": 4420, "text": "SPICE does not calculate computational heavy tasks like N-body simulations, re-entry scenarios or complex manoeuvrers. It uses existing data to provide common access to a large variety of Solar System related problems (a short overview that is provided by NASA can be seen here: NASA Spice Overview)." }, { "code": null, "e": 4892, "s": 4721, "text": "Out of the box, SPICE cannot calculate a lot. It requires auxiliary data, so-called kernels to work properly. These kernels are separated into different categories, like:" }, { "code": null, "e": 4965, "s": 4892, "text": "spk contain trajectory information of planetary bodies, spacecraft, etc." }, { "code": null, "e": 5036, "s": 4965, "text": "pck contain physical parameters of bodies like the size or orientation" }, { "code": null, "e": 5118, "s": 5036, "text": "ik contain instrument-specific information that are e.g., mounted on a spacecraft" }, { "code": null, "e": 5192, "s": 5118, "text": "ck contain information regarding the orientation of a spacecraft in space" }, { "code": null, "e": 5303, "s": 5192, "text": "fk contain reference frame information that is needed to calculate positions in a less common reference system" }, { "code": null, "e": 5476, "s": 5303, "text": "lsk contain time information that is crucial to convert e.g., the UTC time into ephemeris time ET (a standard time format that is being used in space science and astronomy)" }, { "code": null, "e": 6185, "s": 5476, "text": "We will get in touch with all of these kernels. You may ask: Why are the information stored in additional files? Why is the data not stored in one huge toolkit, since we should know the trajectory of certain spacecraft? Well, you are right, but there are dozens of missions out there and a lot of missions are being prepared. Especially the planned missions have “pre-planned” or “predicted” trajectories that are frequently updated. Further, different institutes work on different missions. It would be a struggle to contact everyone to gather all information. Thus, each mission, instrument and so on is separated. NASA and ESA provide repositories with a lot of kernels. One example is here: SPICE Kernels" }, { "code": null, "e": 6780, "s": 6185, "text": "The screenshot above shows some mission kernel folders, like the Apollo missions or the Cassini spacecraft that went to Saturn. A core part is stored in the generic_kernels folders, where planetary information are stored. For starters, all kernels that are needed for this article are stored on my GitHub repository. Later, however, we will need kernels that are huge and need to be downloaded and manually stored by you. We will get to this point in a few weeks. As you can see in the downloaded repository, I prepared a kernel folder called _kernels. We will use the kernels in a few moments." }, { "code": null, "e": 7036, "s": 6780, "text": "Now that we are set up, we can define the first goal for today. Let’s compute the Earth’s position and velocity vector (so-called state vector) for today, midnight. Further, we compare the orbital speed of our home planet with the theoretical expectation." }, { "code": null, "e": 7155, "s": 7036, "text": "First, we import the SPICE wrapper library spicepy. If no error occurs the installation went well and we can continue." }, { "code": null, "e": 7332, "s": 7155, "text": "We want to determine the position of our home planet with respect to the Sun. How can we achieve this with SPICE? Let’s have a look at the reference guide of SPICE: SPICE Docs." }, { "code": null, "e": 7513, "s": 7332, "text": "Well, there are a lot of functions (and do not forget that we need kernels, too). It appears to be overwhelming, but that’s what the tutorial is for: to support you in this regard." }, { "code": null, "e": 7700, "s": 7513, "text": "What we need is the function spkgeo (Please note: this is the documentation of the C library, thus every function name has the _C suffix that needs to be removed for Python): spkgeo doc." }, { "code": null, "e": 7724, "s": 7700, "text": "The documentation says:" }, { "code": null, "e": 7733, "s": 7724, "text": "Abstract" }, { "code": null, "e": 7833, "s": 7733, "text": "Compute the geometric state (position and velocity) of a target body relative to an observing body." }, { "code": null, "e": 7956, "s": 7833, "text": "That’s what we need. The input parameters are the target body (Earth), the ET, the reference frame and the observer (Sun)." }, { "code": null, "e": 8076, "s": 7956, "text": "So in a first step, we need to convert a UTC string to the ET. We use the function utc2et for this purpose: utc2et doc." }, { "code": null, "e": 8440, "s": 8076, "text": "We determine today’s date and create a string of the format year-month-day-hours:minutes:seconds. The documentation of the utc2et function provides all possible time formats in the section Examples. Although it is not required to explicitly write 00:00:00 for midnight, we do it for the sake of completeness (Spoiler: the following code snippet causes an error!):" }, { "code": null, "e": 8788, "s": 8440, "text": "An error occurred. Why? As mentioned before, most information is stored in the kernel files. Here, we cannot convert between the times, because of a missing lsk. The tutorial repository contains the needed file (naif0012.tls) and can be found in the official repository here: SPICE lsk kernels. The kernel is loaded with the SPICE function furnsh." }, { "code": null, "e": 8817, "s": 8788, "text": "We re-execute the command..." }, { "code": null, "e": 8874, "s": 8817, "text": "... and no error occurs. Let’s have a look at the value:" }, { "code": null, "e": 8930, "s": 8874, "text": "For today (2020.04.21) the result is 640699269.1855832." }, { "code": null, "e": 9198, "s": 8930, "text": "Now let’s try the command spkgeo that shall compute the Earth’s state vector. But what are the target’s and observer’s name? Apparently “Earth” and “Sun”; however, SPICE uses the so-called NAIF IDs to identify an object. The complete list can be found here: NAIF IDs." }, { "code": null, "e": 10077, "s": 9198, "text": "Search for the number 399. That’s the Earth! And the Sun has the number 10. The reference frame is set as “ECLIPJ2000” and refers to the ecliptic reference frame at the time J2000 (no kernel needed for this basic frame). Image a table and at the centre of the table, you put something that represents the Sun. Use another object representing the Earth and circle it around the Sun. The table is the so-called “Ecliptic Plane” of our planet. Other planets have their own plane and are slightly inclined with respect to the Earth’s plane. Why J2000? Astronomers set the plane for our planet at a certain time of the year 2000. Due to gravitational perturbations, our current “2020 plane” is very, very slightly inclined with respect to the J2000 plane. Instead of re-defining it every year, we use the 2000-version (Spoiler: another error appears here (the last one, I promise!)):" }, { "code": null, "e": 10298, "s": 10077, "text": "Another kernel is missing. This time it’s an spk. Let’s have a deep dive into this problem. We go to the repository page (you do not need to download anything, since I already put it in the _kernel folder): SPICE kernels" }, { "code": null, "e": 10472, "s": 10298, "text": "... and go to generic_kernels. There we need to go into spk and then planets since we want to compute the state vector of our planet. We find the following status for today:" }, { "code": null, "e": 10997, "s": 10472, "text": "Every folder has aa_*.txt files. Let’s check aa_summaries.txt. The file lists meta data for miscellaneous kernels. It shows which objects are computed w.r.t. which other body object. Note: Mercury’s barycentre and Venus’ barycentre are both available w.r.t. the Solar System barycentre. Thanks to simple addition SPICE can easily compute the distance between both planetary barycentres. The last line shows the time coverage. We take the file de432s.bsp, since it is quite small and covers the time interval of our interest:" }, { "code": null, "e": 11017, "s": 10997, "text": "We load the kernel:" }, { "code": null, "e": 11046, "s": 11017, "text": "Re-compute the state vector:" }, { "code": null, "e": 11295, "s": 11046, "text": "And print it out. We get: [-1.28760839e+08, -7.76110220e+07, 4.32943029e+03, 1.48939328e+01, -2.56361729e+01, 1.00712291e-03]. The first 3 values are the x, y, z components in km. The last 3 values are the corresponding velocity components in km/s." }, { "code": null, "e": 11361, "s": 11295, "text": "We can verify the results by using NASA’s HORIZONS Web-Interface." }, { "code": null, "e": 11929, "s": 11361, "text": "In an extra tutorial, I will explain to you how to use this web application, since it allows one to adjust a lot of parameters. After some clicking I got the following results: [-1.287618689589618E+08, -7.760924828577068E+07, 4.329366157151759E+03, 1.489358282611585E+01, -2.563638289196221E+01, 1.007311359298768E-03]. We compare the x-position component and notice a deviation of around 1000 km. That is not a lot, but theoretically, it should be 0 km?! Well, in this case, HORIZONS uses a kernel called DE431mx. Different kernels may have different precise values." }, { "code": null, "e": 12130, "s": 11929, "text": "Another simple way to check whether our results make sense is to determine the distance between the Sun and Earth. It should be around 1 astronomical unit (1 AU). First, we compute the distance in km:" }, { "code": null, "e": 12262, "s": 12130, "text": "And with the SPICE function convrt (convrt doc) we can change the km values to AU (no kernel needed). The results is close to 1 AU." }, { "code": null, "e": 12337, "s": 12262, "text": "Let’s do the last task. We compute the orbital speed of the Earth in km/s:" }, { "code": null, "e": 12607, "s": 12337, "text": "The value is close to 30 km/s. But does it make sense? The theoretical expectation of the orbital velocity can be approximated with the following equation, where G is the gravitational constant, M is the mass of the Sun, and r is the distance between the Earth and Sun:" }, { "code": null, "e": 12901, "s": 12607, "text": "We use the kernel gm_de431.tpc from the generic_kernels directory (pck) and load it. With the function bodvcd we get the G*M value for the Sun (bodvcd doc). The bodyid is again 10, the required item is GM and maxn is an input parameter that sets the number of expected returns (here, it is 1):" }, { "code": null, "e": 12941, "s": 12901, "text": "Again, we get a value close to 30 km/s!" }, { "code": null, "e": 13229, "s": 12941, "text": "I hope you enjoyed the first tutorial and got an impression of how SPICE “thinks” and how to use it. We will use this library and explore further features in the next tutorials to get more hands-on experience. The SPICE introductions will be a solid basis for later scientific tutorials." }, { "code": null, "e": 13405, "s": 13229, "text": "Please let me know (here or on Reddit: https://www.reddit.com/user/MrAstroThomas), if you liked it, what you missed or any other question. I try to answer as many as possible." }, { "code": null, "e": 13556, "s": 13405, "text": "The next tutorial will be published on Saturday (2020.04.25), hopefully with a GitHub Gist integration. We will analyse the first law of Kepler’s law:" }, { "code": null, "e": 13628, "s": 13556, "text": "The orbit of a planet is an ellipse with the Sun at one of the two foci" }, { "code": null, "e": 13674, "s": 13628, "text": "Is this statement 100 % correct? We will see." } ]
Perl - Packages and Modules
The package statement switches the current naming context to a specified namespace (symbol table). Thus − A package is a collection of code which lives in its own namespace. A package is a collection of code which lives in its own namespace. A namespace is a named collection of unique variable names (also called a symbol table). A namespace is a named collection of unique variable names (also called a symbol table). Namespaces prevent variable name collisions between packages. Namespaces prevent variable name collisions between packages. Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace. Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace. The package stays in effect until either another package statement is invoked, or until the end of the current block or file. The package stays in effect until either another package statement is invoked, or until the end of the current block or file. You can explicitly refer to variables within a package using the :: package qualifier. You can explicitly refer to variables within a package using the :: package qualifier. Following is an example having main and Foo packages in a file. Here special variable __PACKAGE__ has been used to print the package name. #!/usr/bin/perl # This is main package $i = 1; print "Package name : " , __PACKAGE__ , " $i\n"; package Foo; # This is Foo package $i = 10; print "Package name : " , __PACKAGE__ , " $i\n"; package main; # This is again main package $i = 100; print "Package name : " , __PACKAGE__ , " $i\n"; print "Package name : " , __PACKAGE__ , " $Foo::i\n"; 1; When above code is executed, it produces the following result − Package name : main 1 Package name : Foo 10 Package name : main 100 Package name : main 10 You may define any number of code blocks named BEGIN and END, which act as constructors and destructors respectively. BEGIN { ... } END { ... } BEGIN { ... } END { ... } Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed. Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed. Every END block is executed just before the perl interpreter exits. Every END block is executed just before the perl interpreter exits. The BEGIN and END blocks are particularly useful when creating Perl modules. The BEGIN and END blocks are particularly useful when creating Perl modules. Following example shows its usage − #!/usr/bin/perl package Foo; print "Begin and Block Demo\n"; BEGIN { print "This is BEGIN Block\n" } END { print "This is END Block\n" } 1; When above code is executed, it produces the following result − This is BEGIN Block Begin and Block Demo This is END Block A Perl module is a reusable package defined in a library file whose name is the same as the name of the package with a .pm as extension. A Perl module file called Foo.pm might contain statements like this. #!/usr/bin/perl package Foo; sub bar { print "Hello $_[0]\n" } sub blat { print "World $_[0]\n" } 1; Few important points about Perl modules The functions require and use will load a module. The functions require and use will load a module. Both use the list of search paths in @INC to find the module. Both use the list of search paths in @INC to find the module. Both functions require and use call the eval function to process the code. Both functions require and use call the eval function to process the code. The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail). The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail). A module can be loaded by calling the require function as follows − #!/usr/bin/perl require Foo; Foo::bar( "a" ); Foo::blat( "b" ); You must have noticed that the subroutine names must be fully qualified to call them. It would be nice to enable the subroutine bar and blat to be imported into our own namespace so we wouldn't have to use the Foo:: qualifier. A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" ); Notice that we didn't have to fully qualify the package's function names. The use function will export a list of symbols from a module given a few added statements inside a module. require Exporter; @ISA = qw(Exporter); Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the list variable named @EXPORT: For Example − package Module; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(bar blat); sub bar { print "Hello $_[0]\n" } sub blat { print "World $_[0]\n" } sub splat { print "Not $_[0]\n" } # Not exported! 1; When you are ready to ship your Perl module, then there is standard way of creating a Perl Module Tree. This is done using h2xs utility. This utility comes along with Perl. Here is the syntax to use h2xs − $h2xs -AX -n ModuleName For example, if your module is available in Person.pm file, then simply issue the following command − $h2xs -AX -n Person This will produce the following result − Writing Person/lib/Person.pm Writing Person/Makefile.PL Writing Person/README Writing Person/t/Person.t Writing Person/Changes Writing Person/MANIFEST Here is the descritpion of these options − -A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines). -A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines). -X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e., C). -X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e., C). -n specifies the name of the module. -n specifies the name of the module. So above command creates the following structure inside Person directory. Actual result is shown above. Changes Makefile.PL MANIFEST (contains the list of all files in the package) README t/ (test files) lib/ ( Actual source code goes here So finally, you tar this directory structure into a file Person.tar.gz and you can ship it. You will have to update README file with the proper instructions. You can also provide some test examples files in t directory. Download a Perl module in the form tar.gz file. Use the following sequence to install any Perl Module Person.pm which has been downloaded in as Person.tar.gz file. tar xvfz Person.tar.gz cd Person perl Makefile.PL make make install The Perl interpreter has a list of directories in which it searches for modules (global array @INC). 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2326, "s": 2220, "text": "The package statement switches the current naming context to a specified namespace (symbol table). Thus −" }, { "code": null, "e": 2394, "s": 2326, "text": "A package is a collection of code which lives in its own namespace." }, { "code": null, "e": 2462, "s": 2394, "text": "A package is a collection of code which lives in its own namespace." }, { "code": null, "e": 2551, "s": 2462, "text": "A namespace is a named collection of unique variable names (also called a symbol table)." }, { "code": null, "e": 2640, "s": 2551, "text": "A namespace is a named collection of unique variable names (also called a symbol table)." }, { "code": null, "e": 2702, "s": 2640, "text": "Namespaces prevent variable name collisions between packages." }, { "code": null, "e": 2764, "s": 2702, "text": "Namespaces prevent variable name collisions between packages." }, { "code": null, "e": 2904, "s": 2764, "text": "Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace." }, { "code": null, "e": 3044, "s": 2904, "text": "Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace." }, { "code": null, "e": 3170, "s": 3044, "text": "The package stays in effect until either another package statement is invoked, or until the end of the current block or file." }, { "code": null, "e": 3296, "s": 3170, "text": "The package stays in effect until either another package statement is invoked, or until the end of the current block or file." }, { "code": null, "e": 3383, "s": 3296, "text": "You can explicitly refer to variables within a package using the :: package qualifier." }, { "code": null, "e": 3470, "s": 3383, "text": "You can explicitly refer to variables within a package using the :: package qualifier." }, { "code": null, "e": 3609, "s": 3470, "text": "Following is an example having main and Foo packages in a file. Here special variable __PACKAGE__ has been used to print the package name." }, { "code": null, "e": 3969, "s": 3609, "text": "#!/usr/bin/perl\n\n# This is main package\n$i = 1; \nprint \"Package name : \" , __PACKAGE__ , \" $i\\n\"; \n\npackage Foo;\n# This is Foo package\n$i = 10; \nprint \"Package name : \" , __PACKAGE__ , \" $i\\n\"; \n\npackage main;\n# This is again main package\n$i = 100; \nprint \"Package name : \" , __PACKAGE__ , \" $i\\n\"; \nprint \"Package name : \" , __PACKAGE__ , \" $Foo::i\\n\"; \n\n1;" }, { "code": null, "e": 4033, "s": 3969, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 4125, "s": 4033, "text": "Package name : main 1\nPackage name : Foo 10\nPackage name : main 100\nPackage name : main 10\n" }, { "code": null, "e": 4243, "s": 4125, "text": "You may define any number of code blocks named BEGIN and END, which act as constructors and destructors respectively." }, { "code": null, "e": 4296, "s": 4243, "text": "BEGIN { ... }\nEND { ... }\nBEGIN { ... }\nEND { ... }\n" }, { "code": null, "e": 4415, "s": 4296, "text": "Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed." }, { "code": null, "e": 4534, "s": 4415, "text": "Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed." }, { "code": null, "e": 4602, "s": 4534, "text": "Every END block is executed just before the perl interpreter exits." }, { "code": null, "e": 4670, "s": 4602, "text": "Every END block is executed just before the perl interpreter exits." }, { "code": null, "e": 4747, "s": 4670, "text": "The BEGIN and END blocks are particularly useful when creating Perl modules." }, { "code": null, "e": 4824, "s": 4747, "text": "The BEGIN and END blocks are particularly useful when creating Perl modules." }, { "code": null, "e": 4860, "s": 4824, "text": "Following example shows its usage −" }, { "code": null, "e": 5014, "s": 4860, "text": "#!/usr/bin/perl\n\npackage Foo;\nprint \"Begin and Block Demo\\n\";\n\nBEGIN { \n print \"This is BEGIN Block\\n\" \n}\n\nEND { \n print \"This is END Block\\n\" \n}\n\n1;" }, { "code": null, "e": 5078, "s": 5014, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 5138, "s": 5078, "text": "This is BEGIN Block\nBegin and Block Demo\nThis is END Block\n" }, { "code": null, "e": 5275, "s": 5138, "text": "A Perl module is a reusable package defined in a library file whose name is the same as the name of the package with a .pm as extension." }, { "code": null, "e": 5344, "s": 5275, "text": "A Perl module file called Foo.pm might contain statements like this." }, { "code": null, "e": 5457, "s": 5344, "text": "#!/usr/bin/perl\n\npackage Foo;\nsub bar { \n print \"Hello $_[0]\\n\" \n}\n\nsub blat { \n print \"World $_[0]\\n\" \n}\n1;" }, { "code": null, "e": 5497, "s": 5457, "text": "Few important points about Perl modules" }, { "code": null, "e": 5547, "s": 5497, "text": "The functions require and use will load a module." }, { "code": null, "e": 5597, "s": 5547, "text": "The functions require and use will load a module." }, { "code": null, "e": 5659, "s": 5597, "text": "Both use the list of search paths in @INC to find the module." }, { "code": null, "e": 5721, "s": 5659, "text": "Both use the list of search paths in @INC to find the module." }, { "code": null, "e": 5796, "s": 5721, "text": "Both functions require and use call the eval function to process the code." }, { "code": null, "e": 5871, "s": 5796, "text": "Both functions require and use call the eval function to process the code." }, { "code": null, "e": 5945, "s": 5871, "text": "The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail)." }, { "code": null, "e": 6019, "s": 5945, "text": "The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail)." }, { "code": null, "e": 6087, "s": 6019, "text": "A module can be loaded by calling the require function as follows −" }, { "code": null, "e": 6153, "s": 6087, "text": "#!/usr/bin/perl\n\nrequire Foo;\n\nFoo::bar( \"a\" );\nFoo::blat( \"b\" );" }, { "code": null, "e": 6380, "s": 6153, "text": "You must have noticed that the subroutine names must be fully qualified to call them. It would be nice to enable the subroutine bar and blat to be imported into our own namespace so we wouldn't have to use the Foo:: qualifier." }, { "code": null, "e": 6432, "s": 6380, "text": "A module can be loaded by calling the use function." }, { "code": null, "e": 6484, "s": 6432, "text": "#!/usr/bin/perl\n\nuse Foo;\n\nbar( \"a\" );\nblat( \"b\" );" }, { "code": null, "e": 6665, "s": 6484, "text": "Notice that we didn't have to fully qualify the package's function names. The use function will export a list of symbols from a module given a few added statements inside a module." }, { "code": null, "e": 6704, "s": 6665, "text": "require Exporter;\n@ISA = qw(Exporter);" }, { "code": null, "e": 6837, "s": 6704, "text": "Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the list variable named @EXPORT: For Example −" }, { "code": null, "e": 7042, "s": 6837, "text": "package Module;\n\nrequire Exporter;\n@ISA = qw(Exporter);\n@EXPORT = qw(bar blat);\n\nsub bar { print \"Hello $_[0]\\n\" }\nsub blat { print \"World $_[0]\\n\" }\nsub splat { print \"Not $_[0]\\n\" } # Not exported!\n\n1;" }, { "code": null, "e": 7248, "s": 7042, "text": "When you are ready to ship your Perl module, then there is standard way of creating a Perl Module Tree. This is done using h2xs utility. This utility comes along with Perl. Here is the syntax to use h2xs −" }, { "code": null, "e": 7274, "s": 7248, "text": "$h2xs -AX -n ModuleName\n" }, { "code": null, "e": 7376, "s": 7274, "text": "For example, if your module is available in Person.pm file, then simply issue the following command −" }, { "code": null, "e": 7397, "s": 7376, "text": "$h2xs -AX -n Person\n" }, { "code": null, "e": 7438, "s": 7397, "text": "This will produce the following result −" }, { "code": null, "e": 7590, "s": 7438, "text": "Writing Person/lib/Person.pm\nWriting Person/Makefile.PL\nWriting Person/README\nWriting Person/t/Person.t\nWriting Person/Changes\nWriting Person/MANIFEST\n" }, { "code": null, "e": 7633, "s": 7590, "text": "Here is the descritpion of these options −" }, { "code": null, "e": 7746, "s": 7633, "text": "-A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines)." }, { "code": null, "e": 7859, "s": 7746, "text": "-A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines)." }, { "code": null, "e": 7951, "s": 7859, "text": "-X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e., C)." }, { "code": null, "e": 8043, "s": 7951, "text": "-X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e., C)." }, { "code": null, "e": 8080, "s": 8043, "text": "-n specifies the name of the module." }, { "code": null, "e": 8117, "s": 8080, "text": "-n specifies the name of the module." }, { "code": null, "e": 8221, "s": 8117, "text": "So above command creates the following structure inside Person directory. Actual result is shown above." }, { "code": null, "e": 8229, "s": 8221, "text": "Changes" }, { "code": null, "e": 8241, "s": 8229, "text": "Makefile.PL" }, { "code": null, "e": 8298, "s": 8241, "text": "MANIFEST (contains the list of all files in the package)" }, { "code": null, "e": 8305, "s": 8298, "text": "README" }, { "code": null, "e": 8321, "s": 8305, "text": "t/ (test files)" }, { "code": null, "e": 8357, "s": 8321, "text": "lib/ ( Actual source code goes here" }, { "code": null, "e": 8577, "s": 8357, "text": "So finally, you tar this directory structure into a file Person.tar.gz and you can ship it. You will have to update README file with the proper instructions. You can also provide some test examples files in t directory." }, { "code": null, "e": 8741, "s": 8577, "text": "Download a Perl module in the form tar.gz file. Use the following sequence to install any Perl Module Person.pm which has been downloaded in as Person.tar.gz file." }, { "code": null, "e": 8810, "s": 8741, "text": "tar xvfz Person.tar.gz\ncd Person\nperl Makefile.PL\nmake\nmake install\n" }, { "code": null, "e": 8911, "s": 8810, "text": "The Perl interpreter has a list of directories in which it searches for modules (global array @INC)." }, { "code": null, "e": 8946, "s": 8911, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8960, "s": 8946, "text": " Devi Killada" }, { "code": null, "e": 8995, "s": 8960, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9015, "s": 8995, "text": " Harshit Srivastava" }, { "code": null, "e": 9048, "s": 9015, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 9064, "s": 9048, "text": " TELCOMA Global" }, { "code": null, "e": 9097, "s": 9064, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 9114, "s": 9097, "text": " Mohammad Nauman" }, { "code": null, "e": 9147, "s": 9114, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 9170, "s": 9147, "text": " Stone River ELearning" }, { "code": null, "e": 9205, "s": 9170, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 9228, "s": 9205, "text": " Stone River ELearning" }, { "code": null, "e": 9235, "s": 9228, "text": " Print" }, { "code": null, "e": 9246, "s": 9235, "text": " Add Notes" } ]
Convert CSV to JSON using the Jackson library in Java?
A Jackson is a Java JSON API that provides several different ways to work with JSON. We can convert CSV data to JSON data using the CsvMapper class, it is specialized ObjectMapper, with extended functionality to produce CsvSchema instances out of POJOs. We can use the reader() method for constructing ObjectReader with default settings. In order to convert this, we need to import the com.fasterxml.jackson.dataformat.csv package. In the below example, convert a CSV to JSON. import java.io.*; import java.util.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.dataformat.csv.*; public class CsvToJsonTest { public static void main(String args[]) throws Exception { File input = new File("input.csv"); try { CsvSchema csv = CsvSchema.emptySchema().withHeader(); CsvMapper csvMapper = new CsvMapper(); MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader().forType(Map.class).with(csv).readValues(input); List<Map<?, ?>> list = mappingIterator.readAll(); System.out.println(list); } catch(Exception e) { e.printStackTrace(); } } } [{last name=Chandra, first name=Ravi, location=Bangalore}]
[ { "code": null, "e": 1494, "s": 1062, "text": "A Jackson is a Java JSON API that provides several different ways to work with JSON. We can convert CSV data to JSON data using the CsvMapper class, it is specialized ObjectMapper, with extended functionality to produce CsvSchema instances out of POJOs. We can use the reader() method for constructing ObjectReader with default settings. In order to convert this, we need to import the com.fasterxml.jackson.dataformat.csv package." }, { "code": null, "e": 1539, "s": 1494, "text": "In the below example, convert a CSV to JSON." }, { "code": null, "e": 2209, "s": 1539, "text": "import java.io.*;\nimport java.util.*;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.dataformat.csv.*;\npublic class CsvToJsonTest {\n public static void main(String args[]) throws Exception {\n File input = new File(\"input.csv\");\n try {\n CsvSchema csv = CsvSchema.emptySchema().withHeader();\n CsvMapper csvMapper = new CsvMapper();\n MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader().forType(Map.class).with(csv).readValues(input);\n List<Map<?, ?>> list = mappingIterator.readAll();\n System.out.println(list);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2268, "s": 2209, "text": "[{last name=Chandra, first name=Ravi, location=Bangalore}]" } ]
HiveQL - Select-Where
The Hive Query Language (HiveQL) is a query language for Hive to process and analyze structured data in a Metastore. This chapter explains how to use the SELECT statement with WHERE clause. SELECT statement is used to retrieve the data from a table. WHERE clause works similar to a condition. It filters the data using the condition and gives you a finite result. The built-in operators and functions generate an expression, which fulfils the condition. Given below is the syntax of the SELECT query: SELECT [ALL | DISTINCT] select_expr, select_expr, ... FROM table_reference [WHERE where_condition] [GROUP BY col_list] [HAVING having_condition] [CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]] [LIMIT number]; Let us take an example for SELECT...WHERE clause. Assume we have the employee table as given below, with fields named Id, Name, Salary, Designation, and Dept. Generate a query to retrieve the employee details who earn a salary of more than Rs 30000. +------+--------------+-------------+-------------------+--------+ | ID | Name | Salary | Designation | Dept | +------+--------------+-------------+-------------------+--------+ |1201 | Gopal | 45000 | Technical manager | TP | |1202 | Manisha | 45000 | Proofreader | PR | |1203 | Masthanvali | 40000 | Technical writer | TP | |1204 | Krian | 40000 | Hr Admin | HR | |1205 | Kranthi | 30000 | Op Admin | Admin | +------+--------------+-------------+-------------------+--------+ The following query retrieves the employee details using the above scenario: hive> SELECT * FROM employee WHERE salary>30000; On successful execution of the query, you get to see the following response: +------+--------------+-------------+-------------------+--------+ | ID | Name | Salary | Designation | Dept | +------+--------------+-------------+-------------------+--------+ |1201 | Gopal | 45000 | Technical manager | TP | |1202 | Manisha | 45000 | Proofreader | PR | |1203 | Masthanvali | 40000 | Technical writer | TP | |1204 | Krian | 40000 | Hr Admin | HR | +------+--------------+-------------+-------------------+--------+ The JDBC program to apply where clause for the given example is as follows. import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveQLWhere { private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver"; public static void main(String[] args) throws SQLException { // Register driver and create driver instance Class.forName(driverName); // get connection Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", ""); // create statement Statement stmt = con.createStatement(); // execute statement Resultset res = stmt.executeQuery("SELECT * FROM employee WHERE salary>30000;"); System.out.println("Result:"); System.out.println(" ID \t Name \t Salary \t Designation \t Dept "); while (res.next()) { System.out.println(res.getInt(1) + " " + res.getString(2) + " " + res.getDouble(3) + " " + res.getString(4) + " " + res.getString(5)); } con.close(); } } Save the program in a file named HiveQLWhere.java. Use the following commands to compile and execute this program. $ javac HiveQLWhere.java $ java HiveQLWhere ID Name Salary Designation Dept 1201 Gopal 45000 Technical manager TP 1202 Manisha 45000 Proofreader PR 1203 Masthanvali 40000 Technical writer TP 1204 Krian 40000 Hr Admin HR 50 Lectures 4 hours Navdeep Kaur 67 Lectures 4 hours Bigdata Engineer 109 Lectures 2 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2140, "s": 1950, "text": "The Hive Query Language (HiveQL) is a query language for Hive to process and analyze structured data in a Metastore. This chapter explains how to use the SELECT statement with WHERE clause." }, { "code": null, "e": 2404, "s": 2140, "text": "SELECT statement is used to retrieve the data from a table. WHERE clause works similar to a condition. It filters the data using the condition and gives you a finite result. The built-in operators and functions generate an expression, which fulfils the condition." }, { "code": null, "e": 2451, "s": 2404, "text": "Given below is the syntax of the SELECT query:" }, { "code": null, "e": 2686, "s": 2451, "text": "SELECT [ALL | DISTINCT] select_expr, select_expr, ... \nFROM table_reference \n[WHERE where_condition] \n[GROUP BY col_list] \n[HAVING having_condition] \n[CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]] \n[LIMIT number];" }, { "code": null, "e": 2936, "s": 2686, "text": "Let us take an example for SELECT...WHERE clause. Assume we have the employee table as given below, with fields named Id, Name, Salary, Designation, and Dept. Generate a query to retrieve the employee details who earn a salary of more than Rs 30000." }, { "code": null, "e": 3541, "s": 2936, "text": "+------+--------------+-------------+-------------------+--------+\n| ID | Name | Salary | Designation | Dept |\n+------+--------------+-------------+-------------------+--------+\n|1201 | Gopal | 45000 | Technical manager | TP |\n|1202 | Manisha | 45000 | Proofreader | PR |\n|1203 | Masthanvali | 40000 | Technical writer | TP |\n|1204 | Krian | 40000 | Hr Admin | HR |\n|1205 | Kranthi | 30000 | Op Admin | Admin | \n+------+--------------+-------------+-------------------+--------+\n" }, { "code": null, "e": 3618, "s": 3541, "text": "The following query retrieves the employee details using the above scenario:" }, { "code": null, "e": 3667, "s": 3618, "text": "hive> SELECT * FROM employee WHERE salary>30000;" }, { "code": null, "e": 3744, "s": 3667, "text": "On successful execution of the query, you get to see the following response:" }, { "code": null, "e": 4281, "s": 3744, "text": "+------+--------------+-------------+-------------------+--------+\n| ID | Name | Salary | Designation | Dept |\n+------+--------------+-------------+-------------------+--------+\n|1201 | Gopal | 45000 | Technical manager | TP |\n|1202 | Manisha | 45000 | Proofreader | PR |\n|1203 | Masthanvali | 40000 | Technical writer | TP |\n|1204 | Krian | 40000 | Hr Admin | HR |\n+------+--------------+-------------+-------------------+--------+\n" }, { "code": null, "e": 4357, "s": 4281, "text": "The JDBC program to apply where clause for the given example is as follows." }, { "code": null, "e": 5425, "s": 4357, "text": "import java.sql.SQLException;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.sql.DriverManager;\n\npublic class HiveQLWhere {\n private static String driverName = \"org.apache.hadoop.hive.jdbc.HiveDriver\";\n \n public static void main(String[] args) throws SQLException {\n \n // Register driver and create driver instance\n Class.forName(driverName);\n \n // get connection\n Connection con = DriverManager.getConnection(\"jdbc:hive://localhost:10000/userdb\", \"\", \"\");\n \n // create statement\n Statement stmt = con.createStatement();\n \n // execute statement\n Resultset res = stmt.executeQuery(\"SELECT * FROM employee WHERE salary>30000;\");\n \n System.out.println(\"Result:\");\n System.out.println(\" ID \\t Name \\t Salary \\t Designation \\t Dept \");\n \n while (res.next()) {\n System.out.println(res.getInt(1) + \" \" + res.getString(2) + \" \" + res.getDouble(3) + \" \" + res.getString(4) + \" \" + res.getString(5));\n }\n con.close();\n }\n}" }, { "code": null, "e": 5540, "s": 5425, "text": "Save the program in a file named HiveQLWhere.java. Use the following commands to compile and execute this program." }, { "code": null, "e": 5584, "s": 5540, "text": "$ javac HiveQLWhere.java\n$ java HiveQLWhere" }, { "code": null, "e": 5887, "s": 5584, "text": "ID Name Salary Designation Dept\n1201 Gopal 45000 Technical manager TP\n1202 Manisha 45000 Proofreader PR\n1203 Masthanvali 40000 Technical writer TP\n1204 Krian 40000 Hr Admin HR\n" }, { "code": null, "e": 5920, "s": 5887, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 5934, "s": 5920, "text": " Navdeep Kaur" }, { "code": null, "e": 5967, "s": 5934, "text": "\n 67 Lectures \n 4 hours \n" }, { "code": null, "e": 5985, "s": 5967, "text": " Bigdata Engineer" }, { "code": null, "e": 6019, "s": 5985, "text": "\n 109 Lectures \n 2 hours \n" }, { "code": null, "e": 6037, "s": 6019, "text": " Bigdata Engineer" }, { "code": null, "e": 6044, "s": 6037, "text": " Print" }, { "code": null, "e": 6055, "s": 6044, "text": " Add Notes" } ]
HTML5 - Audio & Video
HTML5 features include native audio and video support without the need for Flash. The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set src attribute to identify the media source and include a controls attribute so the user can play and pause the media. Here is the simplest form of embedding a video file in your webpage − <video src = "foo.mp4" width = "300" height = "200" controls> Your browser does not support the <video> element. </video> The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most commonly used video formats are − Ogg − Ogg files with Thedora video codec and Vorbis audio codec. Ogg − Ogg files with Thedora video codec and Vorbis audio codec. mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec. mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec. You can use <source> tag to specify media along with media type and many other attributes. A video element allows multiple source elements and browser will use the first recognized format − <!DOCTYPE HTML> <html> <body> <video width = "300" height = "200" controls autoplay> <source src = "/html5/foo.ogg" type ="video/ogg" /> <source src = "/html5/foo.mp4" type = "video/mp4" /> Your browser does not support the <video> element. </video> </body> </html> This will produce the following result − The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the control − autoplay This Boolean attribute if specified, the video will automatically begin to play back as soon as it can do so without stopping to finish loading the data. autobuffer This Boolean attribute if specified, the video will automatically begin buffering even if it's not set to automatically play. controls If this attribute is present, it will allow the user to control video playback, including volume, seeking, and pause/resume playback. height This attribute specifies the height of the video's display area, in CSS pixels. loop This Boolean attribute if specified, will allow video automatically seek back to the start after reaching at the end. preload This attribute specifies that the video will be loaded at page load, and ready to run. Ignored if autoplay is present. poster This is a URL of an image to show until the user plays or seeks. src The URL of the video to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed. width This attribute specifies the width of the video's display area, in CSS pixels. HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document as follows. <audio src = "foo.wav" controls autoplay> Your browser does not support the <audio> element. </audio> The current HTML5 draft specification does not specify which audio formats browsers should support in the audio tag. But most commonly used audio formats are ogg, mp3 and wav. You can use <source&ggt; tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format − <!DOCTYPE HTML> <html> <body> <audio controls autoplay> <source src = "/html5/audio.ogg" type = "audio/ogg" /> <source src = "/html5/audio.wav" type = "audio/wav" /> Your browser does not support the <audio> element. </audio> </body> </html> This will produce the following result − The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the control − autoplay This Boolean attribute if specified, the audio will automatically begin to play back as soon as it can do so without stopping to finish loading the data. autobuffer This Boolean attribute if specified, the audio will automatically begin buffering even if it's not set to automatically play. controls If this attribute is present, it will allow the user to control audio playback, including volume, seeking, and pause/resume playback. loop This Boolean attribute if specified, will allow audio automatically seek back to the start after reaching at the end. preload This attribute specifies that the audio will be loaded at page load, and ready to run. Ignored if autoplay is present. src The URL of the audio to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed. The HTML5 audio and video tag can have a number of attributes to control various functionalities of the control using JavaScript − abort This event is generated when playback is aborted. canplay This event is generated when enough data is available that the media can be played. ended This event is generated when playback completes. error This event is generated when an error occurs. loadeddata This event is generated when the first frame of the media has finished loading. loadstart This event is generated when loading of the media begins. pause This event is generated when playback is paused. play This event is generated when playback starts or resumes. progress This event is generated periodically to inform the progress of the downloading the media. ratechange This event is generated when the playback speed changes. seeked This event is generated when a seek operation completes. seeking This event is generated when a seek operation begins. suspend This event is generated when loading of the media is suspended. volumechange This event is generated when the audio volume changes. waiting This event is generated when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). Following is the example which allows to play the given video − <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function PlayVideo() { var v = document.getElementsByTagName("video")[0]; v.play(); } </script> </head> <body> <form> <video width = "300" height = "200" src = "/html5/foo.mp4"> Your browser does not support the video element. </video> <br /> <input type = "button" onclick = "PlayVideo();" value = "Play"/> </form> </body> </html> This will produce the following result − Most servers don't by default serve Ogg or mp4 media with the correct MIME types, so you'll likely need to add the appropriate configuration for this. AddType audio/ogg .oga AddType audio/wav .wav AddType video/ogg .ogv .ogg AddType video/mp4 .mp4 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2690, "s": 2608, "text": "HTML5 features include native audio and video support without the need for Flash." }, { "code": null, "e": 2901, "s": 2690, "text": "The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set src attribute to identify the media source and include a controls attribute so the user can play and pause the media." }, { "code": null, "e": 2971, "s": 2901, "text": "Here is the simplest form of embedding a video file in your webpage −" }, { "code": null, "e": 3101, "s": 2971, "text": "<video src = \"foo.mp4\" width = \"300\" height = \"200\" controls>\n Your browser does not support the <video> element. \n</video>\n" }, { "code": null, "e": 3261, "s": 3101, "text": "The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most commonly used video formats are −" }, { "code": null, "e": 3326, "s": 3261, "text": "Ogg − Ogg files with Thedora video codec and Vorbis audio codec." }, { "code": null, "e": 3391, "s": 3326, "text": "Ogg − Ogg files with Thedora video codec and Vorbis audio codec." }, { "code": null, "e": 3455, "s": 3391, "text": "mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec." }, { "code": null, "e": 3519, "s": 3455, "text": "mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec." }, { "code": null, "e": 3709, "s": 3519, "text": "You can use <source> tag to specify media along with media type and many other attributes. A video element allows multiple source elements and browser will use the first recognized format −" }, { "code": null, "e": 4036, "s": 3709, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n \n <video width = \"300\" height = \"200\" controls autoplay>\n <source src = \"/html5/foo.ogg\" type =\"video/ogg\" />\n <source src = \"/html5/foo.mp4\" type = \"video/mp4\" />\n Your browser does not support the <video> element.\n </video>\n \n </body>\n</html>" }, { "code": null, "e": 4077, "s": 4036, "text": "This will produce the following result −" }, { "code": null, "e": 4203, "s": 4077, "text": "The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the control −" }, { "code": null, "e": 4212, "s": 4203, "text": "autoplay" }, { "code": null, "e": 4366, "s": 4212, "text": "This Boolean attribute if specified, the video will automatically begin to play back as soon as it can do so without stopping to finish loading the data." }, { "code": null, "e": 4377, "s": 4366, "text": "autobuffer" }, { "code": null, "e": 4503, "s": 4377, "text": "This Boolean attribute if specified, the video will automatically begin buffering even if it's not set to automatically play." }, { "code": null, "e": 4512, "s": 4503, "text": "controls" }, { "code": null, "e": 4646, "s": 4512, "text": "If this attribute is present, it will allow the user to control video playback, including volume, seeking, and pause/resume playback." }, { "code": null, "e": 4653, "s": 4646, "text": "height" }, { "code": null, "e": 4733, "s": 4653, "text": "This attribute specifies the height of the video's display area, in CSS pixels." }, { "code": null, "e": 4738, "s": 4733, "text": "loop" }, { "code": null, "e": 4856, "s": 4738, "text": "This Boolean attribute if specified, will allow video automatically seek back to the start after reaching at the end." }, { "code": null, "e": 4864, "s": 4856, "text": "preload" }, { "code": null, "e": 4983, "s": 4864, "text": "This attribute specifies that the video will be loaded at page load, and ready to run. Ignored if autoplay is present." }, { "code": null, "e": 4990, "s": 4983, "text": "poster" }, { "code": null, "e": 5055, "s": 4990, "text": "This is a URL of an image to show until the user plays or seeks." }, { "code": null, "e": 5059, "s": 5055, "text": "src" }, { "code": null, "e": 5203, "s": 5059, "text": "The URL of the video to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed." }, { "code": null, "e": 5209, "s": 5203, "text": "width" }, { "code": null, "e": 5288, "s": 5209, "text": "This attribute specifies the width of the video's display area, in CSS pixels." }, { "code": null, "e": 5393, "s": 5288, "text": "HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document as follows." }, { "code": null, "e": 5502, "s": 5393, "text": "<audio src = \"foo.wav\" controls autoplay>\n Your browser does not support the <audio> element. \n</audio>\n" }, { "code": null, "e": 5678, "s": 5502, "text": "The current HTML5 draft specification does not specify which audio formats browsers should support in the audio tag. But most commonly used audio formats are ogg, mp3 and wav." }, { "code": null, "e": 5873, "s": 5678, "text": "You can use <source&ggt; tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format −" }, { "code": null, "e": 6175, "s": 5873, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n \n <audio controls autoplay>\n <source src = \"/html5/audio.ogg\" type = \"audio/ogg\" />\n <source src = \"/html5/audio.wav\" type = \"audio/wav\" />\n Your browser does not support the <audio> element.\n </audio>\n \n </body>\n</html>" }, { "code": null, "e": 6216, "s": 6175, "text": "This will produce the following result −" }, { "code": null, "e": 6342, "s": 6216, "text": "The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the control −" }, { "code": null, "e": 6351, "s": 6342, "text": "autoplay" }, { "code": null, "e": 6505, "s": 6351, "text": "This Boolean attribute if specified, the audio will automatically begin to play back as soon as it can do so without stopping to finish loading the data." }, { "code": null, "e": 6516, "s": 6505, "text": "autobuffer" }, { "code": null, "e": 6642, "s": 6516, "text": "This Boolean attribute if specified, the audio will automatically begin buffering even if it's not set to automatically play." }, { "code": null, "e": 6651, "s": 6642, "text": "controls" }, { "code": null, "e": 6785, "s": 6651, "text": "If this attribute is present, it will allow the user to control audio playback, including volume, seeking, and pause/resume playback." }, { "code": null, "e": 6790, "s": 6785, "text": "loop" }, { "code": null, "e": 6908, "s": 6790, "text": "This Boolean attribute if specified, will allow audio automatically seek back to the start after reaching at the end." }, { "code": null, "e": 6916, "s": 6908, "text": "preload" }, { "code": null, "e": 7035, "s": 6916, "text": "This attribute specifies that the audio will be loaded at page load, and ready to run. Ignored if autoplay is present." }, { "code": null, "e": 7039, "s": 7035, "text": "src" }, { "code": null, "e": 7183, "s": 7039, "text": "The URL of the audio to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed." }, { "code": null, "e": 7314, "s": 7183, "text": "The HTML5 audio and video tag can have a number of attributes to control various functionalities of the control using JavaScript −" }, { "code": null, "e": 7320, "s": 7314, "text": "abort" }, { "code": null, "e": 7370, "s": 7320, "text": "This event is generated when playback is aborted." }, { "code": null, "e": 7378, "s": 7370, "text": "canplay" }, { "code": null, "e": 7462, "s": 7378, "text": "This event is generated when enough data is available that the media can be played." }, { "code": null, "e": 7468, "s": 7462, "text": "ended" }, { "code": null, "e": 7517, "s": 7468, "text": "This event is generated when playback completes." }, { "code": null, "e": 7523, "s": 7517, "text": "error" }, { "code": null, "e": 7569, "s": 7523, "text": "This event is generated when an error occurs." }, { "code": null, "e": 7580, "s": 7569, "text": "loadeddata" }, { "code": null, "e": 7660, "s": 7580, "text": "This event is generated when the first frame of the media has finished loading." }, { "code": null, "e": 7670, "s": 7660, "text": "loadstart" }, { "code": null, "e": 7728, "s": 7670, "text": "This event is generated when loading of the media begins." }, { "code": null, "e": 7734, "s": 7728, "text": "pause" }, { "code": null, "e": 7783, "s": 7734, "text": "This event is generated when playback is paused." }, { "code": null, "e": 7788, "s": 7783, "text": "play" }, { "code": null, "e": 7845, "s": 7788, "text": "This event is generated when playback starts or resumes." }, { "code": null, "e": 7854, "s": 7845, "text": "progress" }, { "code": null, "e": 7944, "s": 7854, "text": "This event is generated periodically to inform the progress of the downloading the media." }, { "code": null, "e": 7955, "s": 7944, "text": "ratechange" }, { "code": null, "e": 8012, "s": 7955, "text": "This event is generated when the playback speed changes." }, { "code": null, "e": 8019, "s": 8012, "text": "seeked" }, { "code": null, "e": 8076, "s": 8019, "text": "This event is generated when a seek operation completes." }, { "code": null, "e": 8084, "s": 8076, "text": "seeking" }, { "code": null, "e": 8138, "s": 8084, "text": "This event is generated when a seek operation begins." }, { "code": null, "e": 8146, "s": 8138, "text": "suspend" }, { "code": null, "e": 8210, "s": 8146, "text": "This event is generated when loading of the media is suspended." }, { "code": null, "e": 8223, "s": 8210, "text": "volumechange" }, { "code": null, "e": 8278, "s": 8223, "text": "This event is generated when the audio volume changes." }, { "code": null, "e": 8286, "s": 8278, "text": "waiting" }, { "code": null, "e": 8431, "s": 8286, "text": "This event is generated when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek)." }, { "code": null, "e": 8495, "s": 8431, "text": "Following is the example which allows to play the given video −" }, { "code": null, "e": 9046, "s": 8495, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n function PlayVideo() {\n var v = document.getElementsByTagName(\"video\")[0]; \n v.play(); \n }\n </script>\n </head>\n \n <body>\n \n <form> \n <video width = \"300\" height = \"200\" src = \"/html5/foo.mp4\">\n Your browser does not support the video element.\n </video>\n <br />\n <input type = \"button\" onclick = \"PlayVideo();\" value = \"Play\"/>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 9087, "s": 9046, "text": "This will produce the following result −" }, { "code": null, "e": 9238, "s": 9087, "text": "Most servers don't by default serve Ogg or mp4 media with the correct MIME types, so you'll likely need to add the appropriate configuration for this." }, { "code": null, "e": 9336, "s": 9238, "text": "AddType audio/ogg .oga\nAddType audio/wav .wav\nAddType video/ogg .ogv .ogg\nAddType video/mp4 .mp4\n" }, { "code": null, "e": 9369, "s": 9336, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 9383, "s": 9369, "text": " Anadi Sharma" }, { "code": null, "e": 9418, "s": 9383, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9432, "s": 9418, "text": " Anadi Sharma" }, { "code": null, "e": 9467, "s": 9432, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9484, "s": 9467, "text": " Frahaan Hussain" }, { "code": null, "e": 9519, "s": 9484, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9550, "s": 9519, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9583, "s": 9550, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9614, "s": 9583, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9649, "s": 9614, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9680, "s": 9649, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9687, "s": 9680, "text": " Print" }, { "code": null, "e": 9698, "s": 9687, "text": " Add Notes" } ]
Introducing SHAP Decision Plots. Visualize the inner workings of machine... | by Floid Gilbert | Towards Data Science
The SHAP (SHapley Additive exPlanations) framework has proved to be an important advancement in the field of machine learning model interpretation. Developed by Scott Lundberg and Su-In Lee, SHAP combines several existing methods to create an intuitive, theoretically-sound approach to explain predictions for any model. SHAP builds model explanations by asking the same question for every prediction and feature: “How does prediction i change when feature j is removed from the model?” So-called SHAP values are the answers. They quantify the magnitude and direction (positive or negative) of a feature’s effect on a prediction. As this article will show, SHAP values can produce model explanations with the clarity of a linear model. The Python software package shap, developed by Scott Lundberg et al., provides utilities to calculate and plot SHAP values. The project’s main page demonstrates typical SHAP plots and provides links to example notebooks. Recently, a new class of plots known as decision plots have been added to the shap package. Decision plots offer a detailed view of a model’s inner workings; that is, they show how models make decisions. This article briefly presents several use cases for decision plots: Show a large number of feature effects clearly.Visualize multioutput predictions.Display the cumulative effect of interactions.Explore feature effects for a range of feature values.Compare and contrast predictions for several models.Identify typical prediction paths. Show a large number of feature effects clearly. Visualize multioutput predictions. Display the cumulative effect of interactions. Explore feature effects for a range of feature values. Compare and contrast predictions for several models. Identify typical prediction paths. For additional details and source code, see the decision plot documentation/vignette or download the notebook. Update: In addition to learning SHAP, I recommend exploring Explainable Boosting Machines (EBMs) in the interpretML package (official docs, video). EBMs are inherently explainable and the associated package includes interactive plots. interpretML also integrates SHAP, among other methods/models, facilitating side-by-side comparisons. To date, force plots (introduced in Nature BME) have been the default method for visualizing individual model predictions via the shap package. Consider the following plot. It shows the prediction for a LightGBM model trained on the UCI Adult Income data set. The prediction is the probability that the individual makes over $50K a year. Red arrows represent feature effects (SHAP values) that drive the prediction value higher while blue arrows are those effects that drive the prediction value lower. Each arrow’s size represents the magnitude of the corresponding feature’s effect. The “base value” (see the grey print towards the upper-left of the image) marks the model’s average prediction over the training set. The “output value” is the model’s prediction: probability 0.64. The feature values for the largest effects are printed at the bottom of the plot. Overall, the force plot provides an effective summary for this prediction. Compare the force plot above to the decision plot below. The decision plot’s straight vertical line marks the model’s base value. The colored line is the prediction. Feature values are printed next to the prediction line for reference. Starting at the bottom of the plot, the prediction line shows how the SHAP values (i.e., the feature effects) accumulate from the base value to arrive at the model’s final score at the top of the plot. (Roughly speaking, this is similar to a statistical linear model where the sum of effects, plus an intercept, equals the prediction.) Decision plots are literal representations of SHAP values, making them easy to interpret. The force plot and the decision plot are both effective at explaining the foregoing model’s prediction. The magnitude and direction of the major effects are easy to identify. However, as we will show next, decision plots are more effective than force plots when many significant features are involved. The next example uses a LightGBM model trained on the UCI Communities and Crime data set to predict the number of non-violent crimes per 100,000 people in the population. The model uses 101 features. The same prediction is explained using a force plot and a decision plot. Notice that the force plot’s horizontal format prevents it from showing all the significant features clearly. In contrast, the decision plot’s vertical format can display the effects of any number of features clearly. This plot was configured to show the 30 most important features out of the total 101 features. The foregoing examples show that decision plots are similar to force plots in their explanation, but the linear, vertical format of the decision plot allows for more effects to be described. Decision plots can effectively explain multioutput models. This example explains a Catboost classification model trained on the UCI Heart Disease data set. There are five classes that indicate the extent of the disease for each observation: Class 1 indicates no disease; Class 5 indicates advanced disease. The decision plot below shows the model’s multiple outputs for a single observation. In this case, the x-axis represents the raw score, not a probability. The scores are included in the plot’s legend to facilitate identification. The model predicts class 4 (the dotted line). The plot shows that the model confidently predicts that disease is present (Class 1 has a very low score), but the model cannot easily differentiate between classes 3, 4, and 5. Those familiar with the shap package know that it produces a separate base value for each model output. The decision plot displays the average of the model’s base values and shifts the SHAP values accordingly to accurately reproduce the model’s scores. This approach simplifies the visualization and allows any number of outputs to be plotted and compared on the same scale. Decision plots support SHAP interaction values: the first-order interactions estimated from tree-based models. In contrast to a dependence plot that shows a single interaction for many predictions, a decision plot displays all main effects and interactions together. This decision plot explains a single prediction from the UCI Adult Income data set using both main effects and interactions. It is configured to show the 20 most important effects. The plot shows plainly that several interactions drive this prediction’s score higher. Decision plots can expose a model’s behaviors in detail. In this example, we explore how the model’s predictions change as feature values change given a specific scenario. We start with the following record in the UCI Adult Income data set. Age 56Workclass Local-govEducation-Num 13Marital Status Married-civ-spouseOccupation Tech-supportRelationship HusbandRace WhiteSex MaleCapital Gain 0Capital Loss 0Hours per week 40Country United-States We create a synthetic data set by duplicating the reference record several times, but varying the capital gain values from $0 to $10,000 by $100 increments. This approach allows us to evaluate and debug the model. Analysts may also find this method useful for presenting hypothetical scenarios. Keep in mind that the effects for capital gains shown in this example are specific to the reference record, and therefore cannot be generalized. A dependence plot can show the change in SHAP values across a feature’s value range. The SHAP values for this model represent a change in log odds. This plot shows that there is a sharp shift in SHAP values around $5,000. It also shows some significant outliers at $0 and approximately $3,000. Though the dependence plot is helpful, it is difficult to discern the practical effects of the SHAP values in context. For that purpose, we can plot the synthetic data set with a decision plot on the probability scale. First, we plot the reference record to establish context. The features are ordered manually to match the plot of the synthetic data that follows. The prediction is probability 0.76. Capital gain is zero, for which the model assigns a small, negative effect. Now, we plot the synthetic data. The reference record is highlighted using a dashed line. The features are ordered via hierarchical clustering to group similar prediction paths. We see that, in practical terms, the effect of capital gain is largely polarized; only a handful of predictions lie between 0.2 and 0.8. Upon further inspection of the predictions, we found a threshold around $4,300, but there are anomalies. Capital gains of $0, $3,000, and $3,100 contribute to unexpectedly high predictions; capital gains of $5,000 contribute to unexpectedly low predictions. These anomalies are plotted here with a legend to help identify each prediction. The predictions paths for $3,000 and $3,100 are identical. Overall, model behaviors are easy to explain using decision plots simply because several predictions can be plotted side-by-side in full detail. The remaining examples in this article take advantage of this same feature. Decision plots are useful for comparing predictions from different models or for interpreting the predictions from ensembles of models. The predictions from an ensemble of five LightGBM models trained on the UCI Adult Income data set are plotted below. If probability 0.5 is the threshold for this binary classification task, we see that this observation is difficult to classify. However, Model 2 is confident that the individual makes less than $50K per year. If this is a typical observation, it is worth examining why this model is different. A decision plot can expose a model’s typical prediction paths. Here, we plot all of the predictions from the UCI Adult Income data set in the probability interval [0.98, 1.0] to see what high-scoring predictions have in common. The features are ordered using hierarchical clustering to group similar prediction paths. The plot shows two distinct paths: one is dominated by capital gain while the other is dominated by capital loss. The effects related to relationship, age, and education are also notable. Alpha blending (partial transparency) is used to indicate areas of high and low density. For comparison, a multi-prediction force plot is shown here. It is a combination of many individual force plots that are rotated 90 degrees and stacked horizontally. There are several differences between the plots; we will point out a few. The force plot shows that approximately three-quarters of the predictions follow the prediction path dominated by capital gain. The decision plot cannot convey this sense of proportion. In the force plot, it is not evident that the predictions on the left are dominated by capital loss unless it is viewed in interactive mode where feature labels appear on mouse-over. Furthermore, the general patterns for age and relationship do not stand out. The decision plot reveals these aspects more effectively. Decision plots are a natural addition to the shap package. They effectively communicate model decisions with the simplicity and clarity afforded by the SHAP framework. They are also flexible, allowing for a variety of use cases ranging from single-prediction explanations to model diagnostics. Please comment if you discover a new way to use decision plots.
[ { "code": null, "e": 367, "s": 46, "text": "The SHAP (SHapley Additive exPlanations) framework has proved to be an important advancement in the field of machine learning model interpretation. Developed by Scott Lundberg and Su-In Lee, SHAP combines several existing methods to create an intuitive, theoretically-sound approach to explain predictions for any model." }, { "code": null, "e": 782, "s": 367, "text": "SHAP builds model explanations by asking the same question for every prediction and feature: “How does prediction i change when feature j is removed from the model?” So-called SHAP values are the answers. They quantify the magnitude and direction (positive or negative) of a feature’s effect on a prediction. As this article will show, SHAP values can produce model explanations with the clarity of a linear model." }, { "code": null, "e": 1003, "s": 782, "text": "The Python software package shap, developed by Scott Lundberg et al., provides utilities to calculate and plot SHAP values. The project’s main page demonstrates typical SHAP plots and provides links to example notebooks." }, { "code": null, "e": 1275, "s": 1003, "text": "Recently, a new class of plots known as decision plots have been added to the shap package. Decision plots offer a detailed view of a model’s inner workings; that is, they show how models make decisions. This article briefly presents several use cases for decision plots:" }, { "code": null, "e": 1543, "s": 1275, "text": "Show a large number of feature effects clearly.Visualize multioutput predictions.Display the cumulative effect of interactions.Explore feature effects for a range of feature values.Compare and contrast predictions for several models.Identify typical prediction paths." }, { "code": null, "e": 1591, "s": 1543, "text": "Show a large number of feature effects clearly." }, { "code": null, "e": 1626, "s": 1591, "text": "Visualize multioutput predictions." }, { "code": null, "e": 1673, "s": 1626, "text": "Display the cumulative effect of interactions." }, { "code": null, "e": 1728, "s": 1673, "text": "Explore feature effects for a range of feature values." }, { "code": null, "e": 1781, "s": 1728, "text": "Compare and contrast predictions for several models." }, { "code": null, "e": 1816, "s": 1781, "text": "Identify typical prediction paths." }, { "code": null, "e": 1927, "s": 1816, "text": "For additional details and source code, see the decision plot documentation/vignette or download the notebook." }, { "code": null, "e": 2263, "s": 1927, "text": "Update: In addition to learning SHAP, I recommend exploring Explainable Boosting Machines (EBMs) in the interpretML package (official docs, video). EBMs are inherently explainable and the associated package includes interactive plots. interpretML also integrates SHAP, among other methods/models, facilitating side-by-side comparisons." }, { "code": null, "e": 3203, "s": 2263, "text": "To date, force plots (introduced in Nature BME) have been the default method for visualizing individual model predictions via the shap package. Consider the following plot. It shows the prediction for a LightGBM model trained on the UCI Adult Income data set. The prediction is the probability that the individual makes over $50K a year. Red arrows represent feature effects (SHAP values) that drive the prediction value higher while blue arrows are those effects that drive the prediction value lower. Each arrow’s size represents the magnitude of the corresponding feature’s effect. The “base value” (see the grey print towards the upper-left of the image) marks the model’s average prediction over the training set. The “output value” is the model’s prediction: probability 0.64. The feature values for the largest effects are printed at the bottom of the plot. Overall, the force plot provides an effective summary for this prediction." }, { "code": null, "e": 3865, "s": 3203, "text": "Compare the force plot above to the decision plot below. The decision plot’s straight vertical line marks the model’s base value. The colored line is the prediction. Feature values are printed next to the prediction line for reference. Starting at the bottom of the plot, the prediction line shows how the SHAP values (i.e., the feature effects) accumulate from the base value to arrive at the model’s final score at the top of the plot. (Roughly speaking, this is similar to a statistical linear model where the sum of effects, plus an intercept, equals the prediction.) Decision plots are literal representations of SHAP values, making them easy to interpret." }, { "code": null, "e": 4167, "s": 3865, "text": "The force plot and the decision plot are both effective at explaining the foregoing model’s prediction. The magnitude and direction of the major effects are easy to identify. However, as we will show next, decision plots are more effective than force plots when many significant features are involved." }, { "code": null, "e": 4550, "s": 4167, "text": "The next example uses a LightGBM model trained on the UCI Communities and Crime data set to predict the number of non-violent crimes per 100,000 people in the population. The model uses 101 features. The same prediction is explained using a force plot and a decision plot. Notice that the force plot’s horizontal format prevents it from showing all the significant features clearly." }, { "code": null, "e": 4753, "s": 4550, "text": "In contrast, the decision plot’s vertical format can display the effects of any number of features clearly. This plot was configured to show the 30 most important features out of the total 101 features." }, { "code": null, "e": 4944, "s": 4753, "text": "The foregoing examples show that decision plots are similar to force plots in their explanation, but the linear, vertical format of the decision plot allows for more effects to be described." }, { "code": null, "e": 5251, "s": 4944, "text": "Decision plots can effectively explain multioutput models. This example explains a Catboost classification model trained on the UCI Heart Disease data set. There are five classes that indicate the extent of the disease for each observation: Class 1 indicates no disease; Class 5 indicates advanced disease." }, { "code": null, "e": 5705, "s": 5251, "text": "The decision plot below shows the model’s multiple outputs for a single observation. In this case, the x-axis represents the raw score, not a probability. The scores are included in the plot’s legend to facilitate identification. The model predicts class 4 (the dotted line). The plot shows that the model confidently predicts that disease is present (Class 1 has a very low score), but the model cannot easily differentiate between classes 3, 4, and 5." }, { "code": null, "e": 6080, "s": 5705, "text": "Those familiar with the shap package know that it produces a separate base value for each model output. The decision plot displays the average of the model’s base values and shifts the SHAP values accordingly to accurately reproduce the model’s scores. This approach simplifies the visualization and allows any number of outputs to be plotted and compared on the same scale." }, { "code": null, "e": 6347, "s": 6080, "text": "Decision plots support SHAP interaction values: the first-order interactions estimated from tree-based models. In contrast to a dependence plot that shows a single interaction for many predictions, a decision plot displays all main effects and interactions together." }, { "code": null, "e": 6615, "s": 6347, "text": "This decision plot explains a single prediction from the UCI Adult Income data set using both main effects and interactions. It is configured to show the 20 most important effects. The plot shows plainly that several interactions drive this prediction’s score higher." }, { "code": null, "e": 6856, "s": 6615, "text": "Decision plots can expose a model’s behaviors in detail. In this example, we explore how the model’s predictions change as feature values change given a specific scenario. We start with the following record in the UCI Adult Income data set." }, { "code": null, "e": 7301, "s": 6856, "text": "Age 56Workclass Local-govEducation-Num 13Marital Status Married-civ-spouseOccupation Tech-supportRelationship HusbandRace WhiteSex MaleCapital Gain 0Capital Loss 0Hours per week 40Country United-States" }, { "code": null, "e": 7741, "s": 7301, "text": "We create a synthetic data set by duplicating the reference record several times, but varying the capital gain values from $0 to $10,000 by $100 increments. This approach allows us to evaluate and debug the model. Analysts may also find this method useful for presenting hypothetical scenarios. Keep in mind that the effects for capital gains shown in this example are specific to the reference record, and therefore cannot be generalized." }, { "code": null, "e": 8035, "s": 7741, "text": "A dependence plot can show the change in SHAP values across a feature’s value range. The SHAP values for this model represent a change in log odds. This plot shows that there is a sharp shift in SHAP values around $5,000. It also shows some significant outliers at $0 and approximately $3,000." }, { "code": null, "e": 8512, "s": 8035, "text": "Though the dependence plot is helpful, it is difficult to discern the practical effects of the SHAP values in context. For that purpose, we can plot the synthetic data set with a decision plot on the probability scale. First, we plot the reference record to establish context. The features are ordered manually to match the plot of the synthetic data that follows. The prediction is probability 0.76. Capital gain is zero, for which the model assigns a small, negative effect." }, { "code": null, "e": 8827, "s": 8512, "text": "Now, we plot the synthetic data. The reference record is highlighted using a dashed line. The features are ordered via hierarchical clustering to group similar prediction paths. We see that, in practical terms, the effect of capital gain is largely polarized; only a handful of predictions lie between 0.2 and 0.8." }, { "code": null, "e": 9225, "s": 8827, "text": "Upon further inspection of the predictions, we found a threshold around $4,300, but there are anomalies. Capital gains of $0, $3,000, and $3,100 contribute to unexpectedly high predictions; capital gains of $5,000 contribute to unexpectedly low predictions. These anomalies are plotted here with a legend to help identify each prediction. The predictions paths for $3,000 and $3,100 are identical." }, { "code": null, "e": 9446, "s": 9225, "text": "Overall, model behaviors are easy to explain using decision plots simply because several predictions can be plotted side-by-side in full detail. The remaining examples in this article take advantage of this same feature." }, { "code": null, "e": 9582, "s": 9446, "text": "Decision plots are useful for comparing predictions from different models or for interpreting the predictions from ensembles of models." }, { "code": null, "e": 9993, "s": 9582, "text": "The predictions from an ensemble of five LightGBM models trained on the UCI Adult Income data set are plotted below. If probability 0.5 is the threshold for this binary classification task, we see that this observation is difficult to classify. However, Model 2 is confident that the individual makes less than $50K per year. If this is a typical observation, it is worth examining why this model is different." }, { "code": null, "e": 10588, "s": 9993, "text": "A decision plot can expose a model’s typical prediction paths. Here, we plot all of the predictions from the UCI Adult Income data set in the probability interval [0.98, 1.0] to see what high-scoring predictions have in common. The features are ordered using hierarchical clustering to group similar prediction paths. The plot shows two distinct paths: one is dominated by capital gain while the other is dominated by capital loss. The effects related to relationship, age, and education are also notable. Alpha blending (partial transparency) is used to indicate areas of high and low density." }, { "code": null, "e": 11332, "s": 10588, "text": "For comparison, a multi-prediction force plot is shown here. It is a combination of many individual force plots that are rotated 90 degrees and stacked horizontally. There are several differences between the plots; we will point out a few. The force plot shows that approximately three-quarters of the predictions follow the prediction path dominated by capital gain. The decision plot cannot convey this sense of proportion. In the force plot, it is not evident that the predictions on the left are dominated by capital loss unless it is viewed in interactive mode where feature labels appear on mouse-over. Furthermore, the general patterns for age and relationship do not stand out. The decision plot reveals these aspects more effectively." } ]
How to store the contents of arrays in a file using Java?
You can use write data into a file using the Writer classes. In the example given below, we are writing the contents of the array using the BufferedWriter. Live Demo import java.io.BufferedWriter; import java.io.FileWriter; public class WritingStringArrayToFile { public static void main(String args[]) throws Exception { String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop", "Neo4j"}; BufferedWriter writer = new BufferedWriter(new FileWriter("myFile.txt", false)); for(int i = 0; i < myArray.length; i++) { writer.write(myArray[i].toString()); writer.newLine(); } writer.flush(); System.out.println("Data Entered in to the file successfully"); } } Data Entered in to the file successfully If you verify the file you can observe that the file with the contents of an array − Live Demo import java.io.BufferedWriter; import java.io.FileWriter; public class WritingIntArrayToFile { public static void main(String args[]) throws Exception { Integer[] myArray = {23, 93, 56, 92, 39}; BufferedWriter writer = new BufferedWriter(new FileWriter("myFile.txt", false)); for(int i = 0; i < myArray.length; i++) { writer.write(myArray[i].toString()); writer.newLine(); } writer.flush(); System.out.println("Data Entered in to the file successfully"); } } Data Entered in to the file successfully If you verify the file you can observe that the file with the contents of an array −
[ { "code": null, "e": 1218, "s": 1062, "text": "You can use write data into a file using the Writer classes. In the example given below, we are writing the contents of the array using the BufferedWriter." }, { "code": null, "e": 1228, "s": 1218, "text": "Live Demo" }, { "code": null, "e": 1786, "s": 1228, "text": "import java.io.BufferedWriter;\nimport java.io.FileWriter;\n\npublic class WritingStringArrayToFile {\n public static void main(String args[]) throws Exception {\n String[] myArray = {\"JavaFX\", \"HBase\", \"OpenCV\", \"Java\", \"Hadoop\", \"Neo4j\"};\n BufferedWriter writer = new BufferedWriter(new FileWriter(\"myFile.txt\", false));\n for(int i = 0; i < myArray.length; i++) {\n writer.write(myArray[i].toString());\n writer.newLine();\n }\n writer.flush();\n System.out.println(\"Data Entered in to the file successfully\");\n }\n}" }, { "code": null, "e": 1827, "s": 1786, "text": "Data Entered in to the file successfully" }, { "code": null, "e": 1912, "s": 1827, "text": "If you verify the file you can observe that the file with the contents of an array −" }, { "code": null, "e": 1922, "s": 1912, "text": "Live Demo" }, { "code": null, "e": 2442, "s": 1922, "text": "import java.io.BufferedWriter;\nimport java.io.FileWriter;\n\npublic class WritingIntArrayToFile {\n public static void main(String args[]) throws Exception {\n Integer[] myArray = {23, 93, 56, 92, 39};\n BufferedWriter writer = new BufferedWriter(new FileWriter(\"myFile.txt\", false));\n for(int i = 0; i < myArray.length; i++) {\n writer.write(myArray[i].toString());\n writer.newLine();\n }\n writer.flush();\n System.out.println(\"Data Entered in to the file successfully\");\n }\n}" }, { "code": null, "e": 2483, "s": 2442, "text": "Data Entered in to the file successfully" }, { "code": null, "e": 2568, "s": 2483, "text": "If you verify the file you can observe that the file with the contents of an array −" } ]
Erosion and Dilation of images using OpenCV in python - GeeksforGeeks
25 Jun, 2021 Morphological operations are a set of operations that process images based on shapes. They apply a structuring element to an input image and generate an output image. The most basic morphological operations are two: Erosion and Dilation Basics of Erosion: Erodes away the boundaries of the foreground object Used to diminish the features of an image. Working of erosion: A kernel(a matrix of odd size(3,5,7) is convolved with the image.A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel are 1, otherwise, it is eroded (made to zero).Thus all the pixels near the boundary will be discarded depending upon the size of the kernel.So the thickness or size of the foreground object decreases or simply the white region decreases in the image. A kernel(a matrix of odd size(3,5,7) is convolved with the image. A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel are 1, otherwise, it is eroded (made to zero). Thus all the pixels near the boundary will be discarded depending upon the size of the kernel. So the thickness or size of the foreground object decreases or simply the white region decreases in the image. Basics of dilation: Increases the object area Used to accentuate features Working of dilation: A kernel(a matrix of odd size(3,5,7) is convolved with the imageA pixel element in the original image is ‘1’ if at least one pixel under the kernel is ‘1’.It increases the white region in the image or the size of the foreground object increases A kernel(a matrix of odd size(3,5,7) is convolved with the image A pixel element in the original image is ‘1’ if at least one pixel under the kernel is ‘1’. It increases the white region in the image or the size of the foreground object increases Python # Python program to demonstrate erosion and# dilation of images.import cv2import numpy as np # Reading the input imageimg = cv2.imread('input.png', 0) # Taking a matrix of size 5 as the kernelkernel = np.ones((5,5), np.uint8) # The first parameter is the original image,# kernel is the matrix with which image is# convolved and third parameter is the number# of iterations, which will determine how much# you want to erode/dilate a given image.img_erosion = cv2.erode(img, kernel, iterations=1)img_dilation = cv2.dilate(img, kernel, iterations=1) cv2.imshow('Input', img)cv2.imshow('Erosion', img_erosion)cv2.imshow('Dilation', img_dilation) cv2.waitKey(0) The second image is the eroded form of the original image and the third image is the dilated form. Uses of Erosion and Dilation: Erosion: It is useful for removing small white noises.Used to detach two connected objects etc.Dilation:In cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases.It is also useful in joining broken parts of an object. Erosion: It is useful for removing small white noises.Used to detach two connected objects etc. It is useful for removing small white noises. Used to detach two connected objects etc. Dilation:In cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases.It is also useful in joining broken parts of an object. In cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases. It is also useful in joining broken parts of an object. This article is contributed by Pratima Upadhyay. 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. Kashif_Iftikhar Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string
[ { "code": null, "e": 41161, "s": 41133, "text": "\n25 Jun, 2021" }, { "code": null, "e": 41419, "s": 41161, "text": "Morphological operations are a set of operations that process images based on shapes. They apply a structuring element to an input image and generate an output image. The most basic morphological operations are two: Erosion and Dilation Basics of Erosion: " }, { "code": null, "e": 41471, "s": 41419, "text": "Erodes away the boundaries of the foreground object" }, { "code": null, "e": 41514, "s": 41471, "text": "Used to diminish the features of an image." }, { "code": null, "e": 41536, "s": 41514, "text": "Working of erosion: " }, { "code": null, "e": 41959, "s": 41536, "text": "A kernel(a matrix of odd size(3,5,7) is convolved with the image.A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel are 1, otherwise, it is eroded (made to zero).Thus all the pixels near the boundary will be discarded depending upon the size of the kernel.So the thickness or size of the foreground object decreases or simply the white region decreases in the image." }, { "code": null, "e": 42025, "s": 41959, "text": "A kernel(a matrix of odd size(3,5,7) is convolved with the image." }, { "code": null, "e": 42179, "s": 42025, "text": "A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel are 1, otherwise, it is eroded (made to zero)." }, { "code": null, "e": 42274, "s": 42179, "text": "Thus all the pixels near the boundary will be discarded depending upon the size of the kernel." }, { "code": null, "e": 42385, "s": 42274, "text": "So the thickness or size of the foreground object decreases or simply the white region decreases in the image." }, { "code": null, "e": 42407, "s": 42385, "text": "Basics of dilation: " }, { "code": null, "e": 42433, "s": 42407, "text": "Increases the object area" }, { "code": null, "e": 42461, "s": 42433, "text": "Used to accentuate features" }, { "code": null, "e": 42483, "s": 42461, "text": "Working of dilation: " }, { "code": null, "e": 42730, "s": 42483, "text": "A kernel(a matrix of odd size(3,5,7) is convolved with the imageA pixel element in the original image is ‘1’ if at least one pixel under the kernel is ‘1’.It increases the white region in the image or the size of the foreground object increases " }, { "code": null, "e": 42795, "s": 42730, "text": "A kernel(a matrix of odd size(3,5,7) is convolved with the image" }, { "code": null, "e": 42887, "s": 42795, "text": "A pixel element in the original image is ‘1’ if at least one pixel under the kernel is ‘1’." }, { "code": null, "e": 42979, "s": 42887, "text": "It increases the white region in the image or the size of the foreground object increases " }, { "code": null, "e": 42988, "s": 42981, "text": "Python" }, { "code": "# Python program to demonstrate erosion and# dilation of images.import cv2import numpy as np # Reading the input imageimg = cv2.imread('input.png', 0) # Taking a matrix of size 5 as the kernelkernel = np.ones((5,5), np.uint8) # The first parameter is the original image,# kernel is the matrix with which image is# convolved and third parameter is the number# of iterations, which will determine how much# you want to erode/dilate a given image.img_erosion = cv2.erode(img, kernel, iterations=1)img_dilation = cv2.dilate(img, kernel, iterations=1) cv2.imshow('Input', img)cv2.imshow('Erosion', img_erosion)cv2.imshow('Dilation', img_dilation) cv2.waitKey(0)", "e": 43645, "s": 42988, "text": null }, { "code": null, "e": 43746, "s": 43645, "text": "The second image is the eroded form of the original image and the third image is the dilated form. " }, { "code": null, "e": 43778, "s": 43746, "text": "Uses of Erosion and Dilation: " }, { "code": null, "e": 44161, "s": 43778, "text": "Erosion: It is useful for removing small white noises.Used to detach two connected objects etc.Dilation:In cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases.It is also useful in joining broken parts of an object." }, { "code": null, "e": 44257, "s": 44161, "text": "Erosion: It is useful for removing small white noises.Used to detach two connected objects etc." }, { "code": null, "e": 44303, "s": 44257, "text": "It is useful for removing small white noises." }, { "code": null, "e": 44345, "s": 44303, "text": "Used to detach two connected objects etc." }, { "code": null, "e": 44633, "s": 44345, "text": "Dilation:In cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases.It is also useful in joining broken parts of an object." }, { "code": null, "e": 44857, "s": 44633, "text": "In cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases." }, { "code": null, "e": 44913, "s": 44857, "text": "It is also useful in joining broken parts of an object." }, { "code": null, "e": 45338, "s": 44913, "text": "This article is contributed by Pratima Upadhyay. 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": 45354, "s": 45338, "text": "Kashif_Iftikhar" }, { "code": null, "e": 45371, "s": 45354, "text": "Image-Processing" }, { "code": null, "e": 45378, "s": 45371, "text": "OpenCV" }, { "code": null, "e": 45385, "s": 45378, "text": "Python" }, { "code": null, "e": 45483, "s": 45385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45492, "s": 45483, "text": "Comments" }, { "code": null, "e": 45505, "s": 45492, "text": "Old Comments" }, { "code": null, "e": 45533, "s": 45505, "text": "Read JSON file using Python" }, { "code": null, "e": 45583, "s": 45533, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 45605, "s": 45583, "text": "Python map() function" }, { "code": null, "e": 45649, "s": 45605, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 45684, "s": 45649, "text": "Read a file line by line in Python" }, { "code": null, "e": 45706, "s": 45684, "text": "Enumerate() in Python" }, { "code": null, "e": 45738, "s": 45706, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 45768, "s": 45738, "text": "Iterate over a list in Python" }, { "code": null, "e": 45810, "s": 45768, "text": "Different ways to create Pandas Dataframe" } ]
GATE | GATE-CS-2003 | Question 80 - GeeksforGeeks
27 Oct, 2021 Suppose we want to synchronize two concurrent processes P and Q using binary semaphores S and T. The code for the processes P and Q is shown below. Process P: while (1) { W: print '0'; print '0'; X: } Process Q: while (1) { Y: print '1'; print '1'; Z: } Synchronization statements can be inserted only at points W, X, Y and Z.Which of the following will always lead to an output starting with ‘001100110011’ ?(A) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S and T initially 1(B) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S initially 1, and T initially 0(C) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S and T initially 1(D) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S initially 1, and T initially 0Answer: (B)Explanation: P(S) means wait on semaphore ‘S’ and V(S) means signal on semaphore ‘S’. Wait(S){ while (i <= 0) --S;} Signal(S){ S++;} Initially, we assume S = 1 and T = 0 to support mutual exclusion in process P and Q.Since S = 1, only process P will be executed and wait(S) will decrement the value of S. Therefore, S = 0.At the same instant, in process Q, value of T = 0. Therefore, in process Q, control will be stuck in while loop till the time process P prints 00 and increments the value of T by calling the function V(T).While the control is in process Q, semaphore S = 0 and process P would be stuck in while loop and would not execute till the time process Q prints 11 and makes the value of S = 1 by calling the function V(S).This whole process will repeat to give the output 00 11 00 11 ... . Thus, B is the correct choice. Watch GeeksforGeeks Video Explanation : YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersExamples of Semaphore with Viomesh Singh | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:009:36 / 24:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yFyCUSn7jkY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please comment below if you find anything wrong in the above post.Quiz of this Question anikaseth98 GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 7 GATE | GATE-IT-2004 | Question 71 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2012 | Question 54 GATE | GATE CS 2019 | Question 27 GATE | GATE-CS-2006 | Question 49
[ { "code": null, "e": 24594, "s": 24566, "text": "\n27 Oct, 2021" }, { "code": null, "e": 24742, "s": 24594, "text": "Suppose we want to synchronize two concurrent processes P and Q using binary semaphores S and T. The code for the processes P and Q is shown below." }, { "code": null, "e": 24862, "s": 24742, "text": "Process P:\nwhile (1) {\nW:\n print '0';\n print '0';\nX:\n}\n\t\nProcess Q:\nwhile (1) {\nY:\n print '1';\n print '1';\nZ:\n}" }, { "code": null, "e": 25408, "s": 24862, "text": "Synchronization statements can be inserted only at points W, X, Y and Z.Which of the following will always lead to an output starting with ‘001100110011’ ?(A) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S and T initially 1(B) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S initially 1, and T initially 0(C) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S and T initially 1(D) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S initially 1, and T initially 0Answer: (B)Explanation: P(S) means wait on semaphore ‘S’ and V(S) means signal on semaphore ‘S’." }, { "code": "Wait(S){ while (i <= 0) --S;} Signal(S){ S++;}", "e": 25468, "s": 25408, "text": null }, { "code": null, "e": 26169, "s": 25468, "text": "Initially, we assume S = 1 and T = 0 to support mutual exclusion in process P and Q.Since S = 1, only process P will be executed and wait(S) will decrement the value of S. Therefore, S = 0.At the same instant, in process Q, value of T = 0. Therefore, in process Q, control will be stuck in while loop till the time process P prints 00 and increments the value of T by calling the function V(T).While the control is in process Q, semaphore S = 0 and process P would be stuck in while loop and would not execute till the time process Q prints 11 and makes the value of S = 1 by calling the function V(S).This whole process will repeat to give the output 00 11 00 11 ... . Thus, B is the correct choice." }, { "code": null, "e": 26209, "s": 26169, "text": "Watch GeeksforGeeks Video Explanation :" }, { "code": null, "e": 27077, "s": 26209, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersExamples of Semaphore with Viomesh Singh | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:009:36 / 24:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=yFyCUSn7jkY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 27166, "s": 27077, "text": " Please comment below if you find anything wrong in the above post.Quiz of this Question" }, { "code": null, "e": 27178, "s": 27166, "text": "anikaseth98" }, { "code": null, "e": 27191, "s": 27178, "text": "GATE-CS-2003" }, { "code": null, "e": 27209, "s": 27191, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 27214, "s": 27209, "text": "GATE" }, { "code": null, "e": 27312, "s": 27214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27346, "s": 27312, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 27388, "s": 27346, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 27430, "s": 27388, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 27464, "s": 27430, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 27497, "s": 27464, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 27531, "s": 27497, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 27564, "s": 27531, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 27598, "s": 27564, "text": "GATE | GATE CS 2012 | Question 54" }, { "code": null, "e": 27632, "s": 27598, "text": "GATE | GATE CS 2019 | Question 27" } ]
Working With Android WorkManager Using Kotlin | by Himanshu Verma | Towards Data Science
The WorkManager is an API which can schedule your future asynchronous tasks and can run them in the background. The tasks assigned to the WorkManager are executed even if the user is outside the app or app is closed. WorkManager can run your task(s) for one time only as well as many times or periodically. It provides backward compatibility up to API level 14 You can add one or many constraints, such as execute tasks only when phone is charging or phone is restarted etc. You can schedule onetime task or periodic tasks You can also chain multiple tasks. For instance, task (B) should only be executed when task (A) is finished. It can help you to execute tasks on particular events. Note: WorkManager is not intended for in-process background work that can safely be terminated if the app process goes away or for tasks that require immediate execution. Worker: The work needed to be done is defined here. WorkRequest: It decides which worker class is going to be executed. It's an abstract class, so we’re going to use its direct classes, and they’re OneTimeWorkRequest and PeriodWorkRequest. WorkManger: It enqueues and manages the work request. WorkInfo: It gives us information about the work, whether its success, running or failed. Let’s start coding now... We’re going to create a notification in the background and this notification can be created only once because we’re using the OneTimeWorkRequest class. Later on, We’ll use some constraints to generate the notification on the basis of events. First of all, add the following dependency. implementation "androidx.work:work-runtime-ktx:2.3.4" We’ll create our worker class first by extending the Worker class, and override its doWork() method for background processing. When doWork() method is called by WorkManager, then it calls user defined method createNotification(). In our MainActivity.kt class, I’ve created a button, when user clicks on the button, then immediately notification gets generated. Here, I’m creating the object of OneTimeWorkRequest and passing the class name of our MyWork class. In the real world, we can have many worker classes, so which class should be executed is decided by this request object. val request = OneTimeWorkRequestBuilder<MyWork>().build() As user clicks on the button, WorkManager enqueues the request. WorkManager.getInstance(this).enqueue(request) Here, we’re creating a toast to display the status of our task, whether its RUNNING, SUCCESS, and FAILED. The getWorkInfoByIdLiveData method takes the request id and gives the information about the task. WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.id) .observe(this, Observer { val status: String = it.state.name Toast.makeText(this,status, Toast.LENGTH_SHORT).show() })} Now run your application and click on the button, you’ll see a notification. Now we’ll see how we can add constraints to create notification only when the phone is charging. Add the following line of code to create the constraint and modify your request object. In the request object, I’m just setting the constraints and that’s it. Now notification will only be generated when this particular criterion is met. val constraints = Constraints.Builder() .setRequiresCharging(true) .build()var request = OneTimeWorkRequestBuilder<MyWork>() .setConstraints(constraints) .build() Note: When multiple constraints are specified, your task will run only when all the constraints are met. If you click on the button and your phone is not charging, then you’ll see a status saying “Enqueued”, this means that your request has been put in the queue and this will only execute when your phone will be charging. If you’re facing any problem running the code, then you can download this project from my Github account. Subscribe my mailing list to get the early access of my articles directly in your inbox and Don’t forget to follow my own publication on Medium The Code Monster to polish your technical knowledge. We’ve seen how we can use WorkManager class to perform some background processing. In this article, I’ve created a notification in the background. And also seen how we can schedule our future tasks based on the events going to happen in the future.
[ { "code": null, "e": 479, "s": 172, "text": "The WorkManager is an API which can schedule your future asynchronous tasks and can run them in the background. The tasks assigned to the WorkManager are executed even if the user is outside the app or app is closed. WorkManager can run your task(s) for one time only as well as many times or periodically." }, { "code": null, "e": 533, "s": 479, "text": "It provides backward compatibility up to API level 14" }, { "code": null, "e": 647, "s": 533, "text": "You can add one or many constraints, such as execute tasks only when phone is charging or phone is restarted etc." }, { "code": null, "e": 695, "s": 647, "text": "You can schedule onetime task or periodic tasks" }, { "code": null, "e": 804, "s": 695, "text": "You can also chain multiple tasks. For instance, task (B) should only be executed when task (A) is finished." }, { "code": null, "e": 859, "s": 804, "text": "It can help you to execute tasks on particular events." }, { "code": null, "e": 1030, "s": 859, "text": "Note: WorkManager is not intended for in-process background work that can safely be terminated if the app process goes away or for tasks that require immediate execution." }, { "code": null, "e": 1082, "s": 1030, "text": "Worker: The work needed to be done is defined here." }, { "code": null, "e": 1270, "s": 1082, "text": "WorkRequest: It decides which worker class is going to be executed. It's an abstract class, so we’re going to use its direct classes, and they’re OneTimeWorkRequest and PeriodWorkRequest." }, { "code": null, "e": 1324, "s": 1270, "text": "WorkManger: It enqueues and manages the work request." }, { "code": null, "e": 1414, "s": 1324, "text": "WorkInfo: It gives us information about the work, whether its success, running or failed." }, { "code": null, "e": 1440, "s": 1414, "text": "Let’s start coding now..." }, { "code": null, "e": 1682, "s": 1440, "text": "We’re going to create a notification in the background and this notification can be created only once because we’re using the OneTimeWorkRequest class. Later on, We’ll use some constraints to generate the notification on the basis of events." }, { "code": null, "e": 1726, "s": 1682, "text": "First of all, add the following dependency." }, { "code": null, "e": 1780, "s": 1726, "text": "implementation \"androidx.work:work-runtime-ktx:2.3.4\"" }, { "code": null, "e": 2010, "s": 1780, "text": "We’ll create our worker class first by extending the Worker class, and override its doWork() method for background processing. When doWork() method is called by WorkManager, then it calls user defined method createNotification()." }, { "code": null, "e": 2141, "s": 2010, "text": "In our MainActivity.kt class, I’ve created a button, when user clicks on the button, then immediately notification gets generated." }, { "code": null, "e": 2362, "s": 2141, "text": "Here, I’m creating the object of OneTimeWorkRequest and passing the class name of our MyWork class. In the real world, we can have many worker classes, so which class should be executed is decided by this request object." }, { "code": null, "e": 2420, "s": 2362, "text": "val request = OneTimeWorkRequestBuilder<MyWork>().build()" }, { "code": null, "e": 2484, "s": 2420, "text": "As user clicks on the button, WorkManager enqueues the request." }, { "code": null, "e": 2531, "s": 2484, "text": "WorkManager.getInstance(this).enqueue(request)" }, { "code": null, "e": 2735, "s": 2531, "text": "Here, we’re creating a toast to display the status of our task, whether its RUNNING, SUCCESS, and FAILED. The getWorkInfoByIdLiveData method takes the request id and gives the information about the task." }, { "code": null, "e": 2973, "s": 2735, "text": "WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.id) .observe(this, Observer { val status: String = it.state.name Toast.makeText(this,status, Toast.LENGTH_SHORT).show() })}" }, { "code": null, "e": 3050, "s": 2973, "text": "Now run your application and click on the button, you’ll see a notification." }, { "code": null, "e": 3147, "s": 3050, "text": "Now we’ll see how we can add constraints to create notification only when the phone is charging." }, { "code": null, "e": 3385, "s": 3147, "text": "Add the following line of code to create the constraint and modify your request object. In the request object, I’m just setting the constraints and that’s it. Now notification will only be generated when this particular criterion is met." }, { "code": null, "e": 3576, "s": 3385, "text": "val constraints = Constraints.Builder() .setRequiresCharging(true) .build()var request = OneTimeWorkRequestBuilder<MyWork>() .setConstraints(constraints) .build()" }, { "code": null, "e": 3681, "s": 3576, "text": "Note: When multiple constraints are specified, your task will run only when all the constraints are met." }, { "code": null, "e": 3900, "s": 3681, "text": "If you click on the button and your phone is not charging, then you’ll see a status saying “Enqueued”, this means that your request has been put in the queue and this will only execute when your phone will be charging." }, { "code": null, "e": 4006, "s": 3900, "text": "If you’re facing any problem running the code, then you can download this project from my Github account." }, { "code": null, "e": 4203, "s": 4006, "text": "Subscribe my mailing list to get the early access of my articles directly in your inbox and Don’t forget to follow my own publication on Medium The Code Monster to polish your technical knowledge." } ]
Additive Secret Sharing and Share Proactivization - Using Python - GeeksforGeeks
16 Jul, 2021 A Secret Sharing Scheme is a Cryptographic Scheme that involves the breaking up of a secret value into multiple fragments/shares in a manner that prevents a single shareholder from having complete knowledge of the original secret. Thus, the secret is divided into multiple shares and distributed among multiple participants. Therefore, the control over the secret value is distributed and not held by a single party. The simplest example of a Secret Sharing Scheme is Additive Secret Sharing which involves breaking a numeric secret into fragments that add up to the original secret. Once divided into shares, each share is distributed to different participants. None of the individual participants have enough information to reconstruct the secret. To reconstruct the secret, all participant must pool their shares together to reveal the original secret value. Fig 1: Division of a secret among three parties using Additive Sharing Example Assume that the following conditions exist: The secret we want to divide is given by the value s = 12345 The number of participants in the system are n = 3. Thus, we need to obtain three shares, one for each party When all parties pool and combine their shares, the secret is revealed One arbitrary division of the secret might be: . Thus, the first party is given a share with value 3512, the second party is given 2100 and the third party gets 6733. Clearly, unless all three parties pool their shares, the secret cannot be revealed. Such a scheme is called an n-out-of-n sharing scheme since all shares are required for secret reconstruction. Conventionally, the secret values and share values are bound to a finite field where all computations take place. All but the last shares, in such a scheme, are picked randomly, ensuring they belong to the chosen finite field. Assume (n-1) out of the total n shares are S(1), S(2), ..., S(n-1). The final share is computed as S(n) = V – (S(1) + S(2) + ... + S(n-1)) where V is the value of the original secret.To recapitulate, we pick (n-1) random shares and compute the final share. Python3 import random def getAdditiveShares(secret, N, fieldSize): '''Generate N additive shares from 'secret' in finite field of size 'fieldSize'.''' # Generate n-1 shares randomly shares = [random.randrange(fieldSize) for i in range(N-1)] # Append final share by subtracting all shares from secret # Modulo is done with fieldSize to ensure share is within finite field shares.append((secret - sum(shares)) % fieldSize ) return shares def reconstructSecret(shares, fieldSize): '''Regenerate secret from additive shares''' return sum(shares) % fieldSize if __name__ == "__main__": # Generating the shares shares = getAdditiveShares(1234, 5, 10**5) print('Shares are:', shares) # Reconstructing the secret from shares print('Reconstructed secret:', reconstructSecret(shares, 10**5)) Shares are: [488, 62586, 9652, 49515, 78993] Reconstructed secret: 1234 Proactivization refers to the refreshing of the shares after fixed intervals to reduce the possibility of an attacker accessing the secret. It is assumed that an attacker can gain access to the shares held by any participant in some reasonable time. However, the compromise of a single share does not reveal the entire secret. As such, the attacker will have to compromise all the generated shares to gain access to the actual secret. This is where Proactivization comes into play. Using Proactivization, all shares are arbitrarily refreshed after a fixed interval such that the attacker may never have access to all of the most current shares. Thus, if the shares are refreshed at a rate such that the adversary only has access to just a subset of all shares at any given point, the scheme is protected from compromise.The goal with Proactivization is to maintain the same key value yet to change its share representation. A new set of additive shares are generated after each lifecycle as follows: Each additive share S(i) is subdivided into sub-fragments d(i, 1), d(i, 2), ..., d(i, n) such the summation of all d(i, j) yields S(i) and n is the number of participants in the system The sub-fragment d(i, j) is distributed by the owning party, “i“, to the party “j“. In this manner, all participants exchange their subfragments.To compute its refreshed share, party i adds the sub-fragments it received from all other participants as follows: Each additive share S(i) is subdivided into sub-fragments d(i, 1), d(i, 2), ..., d(i, n) such the summation of all d(i, j) yields S(i) and n is the number of participants in the system The sub-fragment d(i, j) is distributed by the owning party, “i“, to the party “j“. In this manner, all participants exchange their subfragments. To compute its refreshed share, party i adds the sub-fragments it received from all other participants as follows: On closer observation, we see that each shareholder essentially performs additive sharing on their own shares and distributed the generated sub-shares among the participants. Subsequently, each participant adds up the received sub-shares. In this manner, the original secret is preserved while refreshing the shares held by the participants. Fig 02: Additive shares are refreshed in Proactivization without altering the secret itself Python3 # Additive Sharing with facility to Refresh shares via Proactivizationimport random def getAdditiveShares(secret, N, fieldSize): '''Generate N additive shares from 'secret' in finite field of size 'fieldSize'.''' # Generate n-1 shares randomly shares = [random.randrange(fieldSize) for i in range(N-1)] # Append final share by subtracting all shares from secret shares.append((secret - sum(shares)) % fieldSize ) return shares def reconstructSecret(shares, fieldSize): '''Regenerate secret from additive shares''' return sum(shares) % fieldSize def proactivizeShares(shares): '''Refreshed shares by proactivization''' n = len(shares) refreshedShares = [0]*n for s in shares: # Divide each share into sub-fragments using additive sharing subShares = getAdditiveShares(s, n, 10**5) # Add subfragments of corresponding parties for p, sub in enumerate(subShares): refreshedShares[p] += sub return refreshedShares if __name__ == "__main__": # Generating the shares shares = getAdditiveShares(1234, 5, 10**5) print('Shares are:', shares) # Running Proactivization newShares = proactivizeShares(shares) print('Refreshed Shares are:', newShares) # Reconstructing secret from refreshed shares print('Secret:', reconstructSecret(newShares, 10**5)) Shares are: [45142, 41833, 39277, 49009, 25973] Refreshed Shares are: [298371, 255404, 117787, 239851, 189821] Secret: 1234 singghakshay abhishek0719kadiyan sweetyty cryptography Network-security Computer Networks Python cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Multiple Access Protocols in Computer Network GSM in Wireless Communication Cryptography and its Types Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24510, "s": 24482, "text": "\n16 Jul, 2021" }, { "code": null, "e": 25373, "s": 24510, "text": "A Secret Sharing Scheme is a Cryptographic Scheme that involves the breaking up of a secret value into multiple fragments/shares in a manner that prevents a single shareholder from having complete knowledge of the original secret. Thus, the secret is divided into multiple shares and distributed among multiple participants. Therefore, the control over the secret value is distributed and not held by a single party. The simplest example of a Secret Sharing Scheme is Additive Secret Sharing which involves breaking a numeric secret into fragments that add up to the original secret. Once divided into shares, each share is distributed to different participants. None of the individual participants have enough information to reconstruct the secret. To reconstruct the secret, all participant must pool their shares together to reveal the original secret value. " }, { "code": null, "e": 25444, "s": 25373, "text": "Fig 1: Division of a secret among three parties using Additive Sharing" }, { "code": null, "e": 25498, "s": 25444, "text": "Example Assume that the following conditions exist: " }, { "code": null, "e": 25559, "s": 25498, "text": "The secret we want to divide is given by the value s = 12345" }, { "code": null, "e": 25668, "s": 25559, "text": "The number of participants in the system are n = 3. Thus, we need to obtain three shares, one for each party" }, { "code": null, "e": 25739, "s": 25668, "text": "When all parties pool and combine their shares, the secret is revealed" }, { "code": null, "e": 26101, "s": 25739, "text": "One arbitrary division of the secret might be: . Thus, the first party is given a share with value 3512, the second party is given 2100 and the third party gets 6733. Clearly, unless all three parties pool their shares, the secret cannot be revealed. Such a scheme is called an n-out-of-n sharing scheme since all shares are required for secret reconstruction. " }, { "code": null, "e": 26587, "s": 26101, "text": "Conventionally, the secret values and share values are bound to a finite field where all computations take place. All but the last shares, in such a scheme, are picked randomly, ensuring they belong to the chosen finite field. Assume (n-1) out of the total n shares are S(1), S(2), ..., S(n-1). The final share is computed as S(n) = V – (S(1) + S(2) + ... + S(n-1)) where V is the value of the original secret.To recapitulate, we pick (n-1) random shares and compute the final share. " }, { "code": null, "e": 26595, "s": 26587, "text": "Python3" }, { "code": "import random def getAdditiveShares(secret, N, fieldSize): '''Generate N additive shares from 'secret' in finite field of size 'fieldSize'.''' # Generate n-1 shares randomly shares = [random.randrange(fieldSize) for i in range(N-1)] # Append final share by subtracting all shares from secret # Modulo is done with fieldSize to ensure share is within finite field shares.append((secret - sum(shares)) % fieldSize ) return shares def reconstructSecret(shares, fieldSize): '''Regenerate secret from additive shares''' return sum(shares) % fieldSize if __name__ == \"__main__\": # Generating the shares shares = getAdditiveShares(1234, 5, 10**5) print('Shares are:', shares) # Reconstructing the secret from shares print('Reconstructed secret:', reconstructSecret(shares, 10**5))", "e": 27418, "s": 26595, "text": null }, { "code": null, "e": 27490, "s": 27418, "text": "Shares are: [488, 62586, 9652, 49515, 78993]\nReconstructed secret: 1234" }, { "code": null, "e": 28494, "s": 27492, "text": "Proactivization refers to the refreshing of the shares after fixed intervals to reduce the possibility of an attacker accessing the secret. It is assumed that an attacker can gain access to the shares held by any participant in some reasonable time. However, the compromise of a single share does not reveal the entire secret. As such, the attacker will have to compromise all the generated shares to gain access to the actual secret. This is where Proactivization comes into play. Using Proactivization, all shares are arbitrarily refreshed after a fixed interval such that the attacker may never have access to all of the most current shares. Thus, if the shares are refreshed at a rate such that the adversary only has access to just a subset of all shares at any given point, the scheme is protected from compromise.The goal with Proactivization is to maintain the same key value yet to change its share representation. A new set of additive shares are generated after each lifecycle as follows: " }, { "code": null, "e": 28941, "s": 28494, "text": "Each additive share S(i) is subdivided into sub-fragments d(i, 1), d(i, 2), ..., d(i, n) such the summation of all d(i, j) yields S(i) and n is the number of participants in the system The sub-fragment d(i, j) is distributed by the owning party, “i“, to the party “j“. In this manner, all participants exchange their subfragments.To compute its refreshed share, party i adds the sub-fragments it received from all other participants as follows: " }, { "code": null, "e": 29128, "s": 28941, "text": "Each additive share S(i) is subdivided into sub-fragments d(i, 1), d(i, 2), ..., d(i, n) such the summation of all d(i, j) yields S(i) and n is the number of participants in the system " }, { "code": null, "e": 29274, "s": 29128, "text": "The sub-fragment d(i, j) is distributed by the owning party, “i“, to the party “j“. In this manner, all participants exchange their subfragments." }, { "code": null, "e": 29390, "s": 29274, "text": "To compute its refreshed share, party i adds the sub-fragments it received from all other participants as follows: " }, { "code": null, "e": 29734, "s": 29390, "text": "On closer observation, we see that each shareholder essentially performs additive sharing on their own shares and distributed the generated sub-shares among the participants. Subsequently, each participant adds up the received sub-shares. In this manner, the original secret is preserved while refreshing the shares held by the participants. " }, { "code": null, "e": 29826, "s": 29734, "text": "Fig 02: Additive shares are refreshed in Proactivization without altering the secret itself" }, { "code": null, "e": 29836, "s": 29828, "text": "Python3" }, { "code": "# Additive Sharing with facility to Refresh shares via Proactivizationimport random def getAdditiveShares(secret, N, fieldSize): '''Generate N additive shares from 'secret' in finite field of size 'fieldSize'.''' # Generate n-1 shares randomly shares = [random.randrange(fieldSize) for i in range(N-1)] # Append final share by subtracting all shares from secret shares.append((secret - sum(shares)) % fieldSize ) return shares def reconstructSecret(shares, fieldSize): '''Regenerate secret from additive shares''' return sum(shares) % fieldSize def proactivizeShares(shares): '''Refreshed shares by proactivization''' n = len(shares) refreshedShares = [0]*n for s in shares: # Divide each share into sub-fragments using additive sharing subShares = getAdditiveShares(s, n, 10**5) # Add subfragments of corresponding parties for p, sub in enumerate(subShares): refreshedShares[p] += sub return refreshedShares if __name__ == \"__main__\": # Generating the shares shares = getAdditiveShares(1234, 5, 10**5) print('Shares are:', shares) # Running Proactivization newShares = proactivizeShares(shares) print('Refreshed Shares are:', newShares) # Reconstructing secret from refreshed shares print('Secret:', reconstructSecret(newShares, 10**5))", "e": 31204, "s": 29836, "text": null }, { "code": null, "e": 31328, "s": 31204, "text": "Shares are: [45142, 41833, 39277, 49009, 25973]\nRefreshed Shares are: [298371, 255404, 117787, 239851, 189821]\nSecret: 1234" }, { "code": null, "e": 31343, "s": 31330, "text": "singghakshay" }, { "code": null, "e": 31363, "s": 31343, "text": "abhishek0719kadiyan" }, { "code": null, "e": 31372, "s": 31363, "text": "sweetyty" }, { "code": null, "e": 31385, "s": 31372, "text": "cryptography" }, { "code": null, "e": 31402, "s": 31385, "text": "Network-security" }, { "code": null, "e": 31420, "s": 31402, "text": "Computer Networks" }, { "code": null, "e": 31427, "s": 31420, "text": "Python" }, { "code": null, "e": 31440, "s": 31427, "text": "cryptography" }, { "code": null, "e": 31458, "s": 31440, "text": "Computer Networks" }, { "code": null, "e": 31556, "s": 31458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31591, "s": 31556, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 31624, "s": 31591, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 31670, "s": 31624, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 31700, "s": 31670, "text": "GSM in Wireless Communication" }, { "code": null, "e": 31727, "s": 31700, "text": "Cryptography and its Types" }, { "code": null, "e": 31755, "s": 31727, "text": "Read JSON file using Python" }, { "code": null, "e": 31805, "s": 31755, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31827, "s": 31805, "text": "Python map() function" } ]
Visualizing spatial data with geojson heatmaps | by Jan Majewski | Towards Data Science
Have you ever worked with spatial data and faced the challenge of having to choose between overcrowded scatter plots or choropleth maps limited to administrative boundaries such as districts? Working as a data scientist in the real estate industry, I often deal with spatial data, however, I was struggling to find the optimal way of visualizing spatial data in a way that would make it easy to grasp key spatial features from large data sets. The basic features provided by Plotly or Folium felt limiting so I decided to do a bit of research on how to create custom heatmaps on top of a map, which I want to share with you in this article. I will be working on a data set of >10k Real Estate offers in Warsaw from May 2020, which you can download from my GitHub in the link below. Whole code and data sources are available on GitHub: https://github.com/Jan-Majewski/Project_Portfolio/blob/master/03_Real_Estate_pricing_in_Warsaw/03_02_Data_Vizualization.ipynb For interactive visualizations, I recommend using nbviewer link: https://nbviewer.jupyter.org/github/Jan-Majewski/Project_Portfolio/blob/c770f21dc410b1495dbdf5b9f4f443ecd4d986ba/03_Real_Estate_pricing_in_Warsaw/03_02_Data_Vizualization.ipynb The data used can be downloaded from GitHub df = pd.read_excel(r"https://raw.githubusercontent.com/Jan-Majewski/Project_Portfolio/master/03_Real_Estate_pricing_in_Warsaw/Warsaw_RE_data.xlsx") As the data has many more features than needed for this project let’s select just key 8 columns. key_columns=['Id', 'Area', 'Price', 'latitude', 'longitude', 'City','district']df=df[key_columns]df.head(10) First, let’s explore the most common ways of visualizing spatial data with basic Plotly features. Scatter plots on a map are probably the most common and easiest ways of visualizing spatial data. You take the coordinates, set one feature as colour and there is your map. It even looks quite effective at first glance, but if you are dealing with a larger data set it gets overcrowded and you actually lose sight of the map below. We can simplify the scatter by creating a grid by rounding coordinates and calculating the mean for each tile. It looks easier to read but we also lose a lot of detail. Grid plot is based on data summarized by clipping lat and on and creating lat_mod and lon_mod features and grouping data to create df_map. Not being satisfied with the previous outcomes, I decided to look for ways to create heatmaps based on contour plots. For me the best solution turned out to be a 4 step process: Creating a contour plot in matplotlib Converting it to geojson with use of geojsoncountour library Extracting values from geojson to df_contour Creating a choropleth map using plotly We got quite a nice contour plot, now all we need to do is convert it to geojson so that it is compatible with plotly. Warning! When choosing boundaries for contour plot, make sure that each layer has at least one data point. If the max and min are to wide or the step size is too small and one of the layers is empty it could make the whole geojson not appear at all in plotly. To convert contour plot to geojson you will need geojsoncontour library. pip install geojsoncontour As plotly needs a DataFrame with values used for fill colour for spatial objects within geojson, we need to extract them by iterating the “features” key in geojson dict. This key contains a list of dictionaries, one for each layer of the heatmap. The value is stored in “properties” key of the subdictionary as “title” key. Let’s also add “id” key to each dictionary within the list to match spatial object with DataFrame row. Now we have all we need to create a beautiful heatmap. Let’s plot! I recommend referencing nbviewer link at the top of the page to explore the full scope of possibilities to zoom and deep-dive the most interesting areas of the plot. I hope this tutorial will help you make your spatial visualizations more effective and easier to grasp the key insights at a glance. This type of visualization works with all sorts of data, where spatial features are one of the key drivers. To wrap up enjoy a similar viz, based on google commute data. If you are interested in the analysis, the notebook referenced at the top of the article also deals with extraction and processing drivetime data using Google API.
[ { "code": null, "e": 364, "s": 172, "text": "Have you ever worked with spatial data and faced the challenge of having to choose between overcrowded scatter plots or choropleth maps limited to administrative boundaries such as districts?" }, { "code": null, "e": 616, "s": 364, "text": "Working as a data scientist in the real estate industry, I often deal with spatial data, however, I was struggling to find the optimal way of visualizing spatial data in a way that would make it easy to grasp key spatial features from large data sets." }, { "code": null, "e": 954, "s": 616, "text": "The basic features provided by Plotly or Folium felt limiting so I decided to do a bit of research on how to create custom heatmaps on top of a map, which I want to share with you in this article. I will be working on a data set of >10k Real Estate offers in Warsaw from May 2020, which you can download from my GitHub in the link below." }, { "code": null, "e": 1133, "s": 954, "text": "Whole code and data sources are available on GitHub: https://github.com/Jan-Majewski/Project_Portfolio/blob/master/03_Real_Estate_pricing_in_Warsaw/03_02_Data_Vizualization.ipynb" }, { "code": null, "e": 1375, "s": 1133, "text": "For interactive visualizations, I recommend using nbviewer link: https://nbviewer.jupyter.org/github/Jan-Majewski/Project_Portfolio/blob/c770f21dc410b1495dbdf5b9f4f443ecd4d986ba/03_Real_Estate_pricing_in_Warsaw/03_02_Data_Vizualization.ipynb" }, { "code": null, "e": 1419, "s": 1375, "text": "The data used can be downloaded from GitHub" }, { "code": null, "e": 1567, "s": 1419, "text": "df = pd.read_excel(r\"https://raw.githubusercontent.com/Jan-Majewski/Project_Portfolio/master/03_Real_Estate_pricing_in_Warsaw/Warsaw_RE_data.xlsx\")" }, { "code": null, "e": 1664, "s": 1567, "text": "As the data has many more features than needed for this project let’s select just key 8 columns." }, { "code": null, "e": 1778, "s": 1664, "text": "key_columns=['Id', 'Area', 'Price', 'latitude', 'longitude', 'City','district']df=df[key_columns]df.head(10)" }, { "code": null, "e": 1876, "s": 1778, "text": "First, let’s explore the most common ways of visualizing spatial data with basic Plotly features." }, { "code": null, "e": 2208, "s": 1876, "text": "Scatter plots on a map are probably the most common and easiest ways of visualizing spatial data. You take the coordinates, set one feature as colour and there is your map. It even looks quite effective at first glance, but if you are dealing with a larger data set it gets overcrowded and you actually lose sight of the map below." }, { "code": null, "e": 2377, "s": 2208, "text": "We can simplify the scatter by creating a grid by rounding coordinates and calculating the mean for each tile. It looks easier to read but we also lose a lot of detail." }, { "code": null, "e": 2516, "s": 2377, "text": "Grid plot is based on data summarized by clipping lat and on and creating lat_mod and lon_mod features and grouping data to create df_map." }, { "code": null, "e": 2634, "s": 2516, "text": "Not being satisfied with the previous outcomes, I decided to look for ways to create heatmaps based on contour plots." }, { "code": null, "e": 2694, "s": 2634, "text": "For me the best solution turned out to be a 4 step process:" }, { "code": null, "e": 2732, "s": 2694, "text": "Creating a contour plot in matplotlib" }, { "code": null, "e": 2793, "s": 2732, "text": "Converting it to geojson with use of geojsoncountour library" }, { "code": null, "e": 2838, "s": 2793, "text": "Extracting values from geojson to df_contour" }, { "code": null, "e": 2877, "s": 2838, "text": "Creating a choropleth map using plotly" }, { "code": null, "e": 2996, "s": 2877, "text": "We got quite a nice contour plot, now all we need to do is convert it to geojson so that it is compatible with plotly." }, { "code": null, "e": 3256, "s": 2996, "text": "Warning! When choosing boundaries for contour plot, make sure that each layer has at least one data point. If the max and min are to wide or the step size is too small and one of the layers is empty it could make the whole geojson not appear at all in plotly." }, { "code": null, "e": 3329, "s": 3256, "text": "To convert contour plot to geojson you will need geojsoncontour library." }, { "code": null, "e": 3356, "s": 3329, "text": "pip install geojsoncontour" }, { "code": null, "e": 3783, "s": 3356, "text": "As plotly needs a DataFrame with values used for fill colour for spatial objects within geojson, we need to extract them by iterating the “features” key in geojson dict. This key contains a list of dictionaries, one for each layer of the heatmap. The value is stored in “properties” key of the subdictionary as “title” key. Let’s also add “id” key to each dictionary within the list to match spatial object with DataFrame row." }, { "code": null, "e": 3850, "s": 3783, "text": "Now we have all we need to create a beautiful heatmap. Let’s plot!" }, { "code": null, "e": 4016, "s": 3850, "text": "I recommend referencing nbviewer link at the top of the page to explore the full scope of possibilities to zoom and deep-dive the most interesting areas of the plot." }, { "code": null, "e": 4149, "s": 4016, "text": "I hope this tutorial will help you make your spatial visualizations more effective and easier to grasp the key insights at a glance." } ]
Data visualization with R and ggplot2 - GeeksforGeeks
07 Dec, 2021 ggplot2 package in R Programming Language also termed as Grammar of Graphics is a free, open-source, and easy-to-use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham. It includes several layers on which it is governed. The layers are as follows: Data: The element is the data set itself Aesthetics: The data is to map onto the Aesthetics attributes such as x-axis, y-axis, color, fill, size, labels, alpha, shape, line width, line type Geometrics: How our data being displayed using point, line, histogram, bar, boxplot Facets: It displays the subset of the data using Columns and rows Statistics: Binning, smoothing, descriptive, intermediate Coordinates: the space between data and display using Cartesian, fixed, polar, limits Themes: Non-data link mtcars(motor trend car road test) comprise fuel consumption and 10 aspects of automobile design and performance for 32 automobiles and come pre-installed with dplyr package in R. R # Installing the packageinstall.packages("dplyr") # Loading packagelibrary(dplyr) # Summary of dataset in packagesummary(mtcars) Output: mpg cyl disp hp Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5 Median :19.20 Median :6.000 Median :196.3 Median :123.0 Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0 Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0 drat wt qsec vs Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000 Median :3.695 Median :3.325 Median :17.71 Median :0.0000 Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000 Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000 am gear carb Min. :0.0000 Min. :3.000 Min. :1.000 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000 Median :0.0000 Median :4.000 Median :2.000 Mean :0.4062 Mean :3.688 Mean :2.812 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000 Max. :1.0000 Max. :5.000 Max. :8.000 We devise visualizations on mtcars dataset which includes 32 car brands and 11 attributes using ggplot2 layers. In the data Layer we define the source of the information to be visualize, let’s use the mtcars dataset in the ggplot2 package R # Loading packageslibrary(ggplot2)library(dplyr) # Data Layerggplot(data = mtcars) Output: Here we will display and map dataset into certain aesthetics. R # Aesthetic Layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) Output: In geometric layer control the essential elements, see how our data being displayed using point, line, histogram, bar, boxplot R # Geometric layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) + geom_point() Output: Geometric layer: Adding Size, color, and shape and then plotting Histogram plot R # Adding sizeggplot(data = mtcars, aes(x = hp, y = mpg, size = disp)) + geom_point() # Adding color and shapeggplot(data = mtcars, aes(x = hp, y = mpg, col = factor(cyl), shape = factor(am))) +geom_point() # Histogram plotggplot(data = mtcars, aes(x = hp)) + geom_histogram(binwidth = 5) Output: It is used to split the data up into subsets of the entire dataset and it allows the subsets to be visualized on the same plot. Here we separate rows according to transmission type and Separate columns according to cylinders R # Facet Layerp <- ggplot(data = mtcars, aes(x = hp, y = mpg, shape = factor(cyl))) + geom_point() # Separate rows according to transmission typep + facet_grid(am ~ .) # Separate columns according to cylindersp + facet_grid(. ~ cyl) Output: In this layer, we transform our data using binning, smoothing, descriptive, intermediate R # Statistics layerggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + stat_smooth(method = lm, col = "red") Output: In these layers, data coordinates are mapped together to the mentioned plane of the graphic and we adjust the axis and changes the spacing of displayed data with Control plot dimensions. R # Coordinates layer: Control plot dimensionsggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point() + stat_smooth(method = lm, col = "red") + scale_y_continuous("mpg", limits = c(2, 35), expand = c(0, 0)) + scale_x_continuous("wt", limits = c(0, 25), expand = c(0, 0)) + coord_equal() Output: Coord_cartesian() to proper zoom in: R # Add coord_cartesian() to proper zoom inggplot(data = mtcars, aes(x = wt, y = hp, col = am)) + geom_point() + geom_smooth() + coord_cartesian(xlim = c(3, 6)) Output: This layer controls the finer points of display like the font size and background color properties. Example 1: Theme layer – element_rect() function R # Theme layerggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_grid(. ~ cyl) + theme(plot.background = element_rect( fill = "black", colour = "gray")) Output: Example 2: R ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_grid(am ~ cyl) + theme_gray() Output: ggplot2 provides various types of visualizations. More parameters can be used included in the package as the package gives greater control over the visualizations of data. Many packages can integrate with the ggplot2 package to make the visualizations interactive and animated. clintra kumar_satyam R-Graphs R-Packages R-plots R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) Convert Factor to Numeric and Numeric to Factor in R Programming How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 28964, "s": 28936, "text": "\n07 Dec, 2021" }, { "code": null, "e": 29194, "s": 28964, "text": "ggplot2 package in R Programming Language also termed as Grammar of Graphics is a free, open-source, and easy-to-use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham." }, { "code": null, "e": 29273, "s": 29194, "text": "It includes several layers on which it is governed. The layers are as follows:" }, { "code": null, "e": 29314, "s": 29273, "text": "Data: The element is the data set itself" }, { "code": null, "e": 29463, "s": 29314, "text": "Aesthetics: The data is to map onto the Aesthetics attributes such as x-axis, y-axis, color, fill, size, labels, alpha, shape, line width, line type" }, { "code": null, "e": 29547, "s": 29463, "text": "Geometrics: How our data being displayed using point, line, histogram, bar, boxplot" }, { "code": null, "e": 29613, "s": 29547, "text": "Facets: It displays the subset of the data using Columns and rows" }, { "code": null, "e": 29671, "s": 29613, "text": "Statistics: Binning, smoothing, descriptive, intermediate" }, { "code": null, "e": 29757, "s": 29671, "text": "Coordinates: the space between data and display using Cartesian, fixed, polar, limits" }, { "code": null, "e": 29779, "s": 29757, "text": "Themes: Non-data link" }, { "code": null, "e": 29958, "s": 29779, "text": "mtcars(motor trend car road test) comprise fuel consumption and 10 aspects of automobile design and performance for 32 automobiles and come pre-installed with dplyr package in R." }, { "code": null, "e": 29960, "s": 29958, "text": "R" }, { "code": "# Installing the packageinstall.packages(\"dplyr\") # Loading packagelibrary(dplyr) # Summary of dataset in packagesummary(mtcars)", "e": 30091, "s": 29960, "text": null }, { "code": null, "e": 30099, "s": 30091, "text": "Output:" }, { "code": null, "e": 31366, "s": 30099, "text": " mpg cyl disp hp \n Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0 \n 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5 \n Median :19.20 Median :6.000 Median :196.3 Median :123.0 \n Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7 \n 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0 \n Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0 \n drat wt qsec vs \n Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000 \n 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000 \n Median :3.695 Median :3.325 Median :17.71 Median :0.0000 \n Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375 \n 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000 \n Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000 \n am gear carb \n Min. :0.0000 Min. :3.000 Min. :1.000 \n 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000 \n Median :0.0000 Median :4.000 Median :2.000 \n Mean :0.4062 Mean :3.688 Mean :2.812 \n 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000 \n Max. :1.0000 Max. :5.000 Max. :8.000 " }, { "code": null, "e": 31478, "s": 31366, "text": "We devise visualizations on mtcars dataset which includes 32 car brands and 11 attributes using ggplot2 layers." }, { "code": null, "e": 31605, "s": 31478, "text": "In the data Layer we define the source of the information to be visualize, let’s use the mtcars dataset in the ggplot2 package" }, { "code": null, "e": 31607, "s": 31605, "text": "R" }, { "code": "# Loading packageslibrary(ggplot2)library(dplyr) # Data Layerggplot(data = mtcars)", "e": 31692, "s": 31607, "text": null }, { "code": null, "e": 31700, "s": 31692, "text": "Output:" }, { "code": null, "e": 31762, "s": 31700, "text": "Here we will display and map dataset into certain aesthetics." }, { "code": null, "e": 31764, "s": 31762, "text": "R" }, { "code": "# Aesthetic Layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp))", "e": 31837, "s": 31764, "text": null }, { "code": null, "e": 31845, "s": 31837, "text": "Output:" }, { "code": null, "e": 31972, "s": 31845, "text": "In geometric layer control the essential elements, see how our data being displayed using point, line, histogram, bar, boxplot" }, { "code": null, "e": 31974, "s": 31972, "text": "R" }, { "code": "# Geometric layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) + geom_point()", "e": 32069, "s": 31974, "text": null }, { "code": null, "e": 32077, "s": 32069, "text": "Output:" }, { "code": null, "e": 32157, "s": 32077, "text": "Geometric layer: Adding Size, color, and shape and then plotting Histogram plot" }, { "code": null, "e": 32159, "s": 32157, "text": "R" }, { "code": "# Adding sizeggplot(data = mtcars, aes(x = hp, y = mpg, size = disp)) + geom_point() # Adding color and shapeggplot(data = mtcars, aes(x = hp, y = mpg, col = factor(cyl), shape = factor(am))) +geom_point() # Histogram plotggplot(data = mtcars, aes(x = hp)) + geom_histogram(binwidth = 5)", "e": 32497, "s": 32159, "text": null }, { "code": null, "e": 32505, "s": 32497, "text": "Output:" }, { "code": null, "e": 32730, "s": 32505, "text": "It is used to split the data up into subsets of the entire dataset and it allows the subsets to be visualized on the same plot. Here we separate rows according to transmission type and Separate columns according to cylinders" }, { "code": null, "e": 32732, "s": 32730, "text": "R" }, { "code": "# Facet Layerp <- ggplot(data = mtcars, aes(x = hp, y = mpg, shape = factor(cyl))) + geom_point() # Separate rows according to transmission typep + facet_grid(am ~ .) # Separate columns according to cylindersp + facet_grid(. ~ cyl) ", "e": 32997, "s": 32732, "text": null }, { "code": null, "e": 33005, "s": 32997, "text": "Output:" }, { "code": null, "e": 33094, "s": 33005, "text": "In this layer, we transform our data using binning, smoothing, descriptive, intermediate" }, { "code": null, "e": 33096, "s": 33094, "text": "R" }, { "code": "# Statistics layerggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + stat_smooth(method = lm, col = \"red\")", "e": 33251, "s": 33096, "text": null }, { "code": null, "e": 33259, "s": 33251, "text": "Output:" }, { "code": null, "e": 33446, "s": 33259, "text": "In these layers, data coordinates are mapped together to the mentioned plane of the graphic and we adjust the axis and changes the spacing of displayed data with Control plot dimensions." }, { "code": null, "e": 33448, "s": 33446, "text": "R" }, { "code": "# Coordinates layer: Control plot dimensionsggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point() + stat_smooth(method = lm, col = \"red\") + scale_y_continuous(\"mpg\", limits = c(2, 35), expand = c(0, 0)) + scale_x_continuous(\"wt\", limits = c(0, 25), expand = c(0, 0)) + coord_equal()", "e": 33809, "s": 33448, "text": null }, { "code": null, "e": 33817, "s": 33809, "text": "Output:" }, { "code": null, "e": 33854, "s": 33817, "text": "Coord_cartesian() to proper zoom in:" }, { "code": null, "e": 33856, "s": 33854, "text": "R" }, { "code": "# Add coord_cartesian() to proper zoom inggplot(data = mtcars, aes(x = wt, y = hp, col = am)) + geom_point() + geom_smooth() + coord_cartesian(xlim = c(3, 6))", "e": 34061, "s": 33856, "text": null }, { "code": null, "e": 34069, "s": 34061, "text": "Output:" }, { "code": null, "e": 34169, "s": 34069, "text": "This layer controls the finer points of display like the font size and background color properties." }, { "code": null, "e": 34218, "s": 34169, "text": "Example 1: Theme layer – element_rect() function" }, { "code": null, "e": 34220, "s": 34218, "text": "R" }, { "code": "# Theme layerggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_grid(. ~ cyl) + theme(plot.background = element_rect( fill = \"black\", colour = \"gray\"))", "e": 34414, "s": 34220, "text": null }, { "code": null, "e": 34422, "s": 34414, "text": "Output:" }, { "code": null, "e": 34433, "s": 34422, "text": "Example 2:" }, { "code": null, "e": 34435, "s": 34433, "text": "R" }, { "code": "ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_grid(am ~ cyl) + theme_gray()", "e": 34547, "s": 34435, "text": null }, { "code": null, "e": 34555, "s": 34547, "text": "Output:" }, { "code": null, "e": 34833, "s": 34555, "text": "ggplot2 provides various types of visualizations. More parameters can be used included in the package as the package gives greater control over the visualizations of data. Many packages can integrate with the ggplot2 package to make the visualizations interactive and animated." }, { "code": null, "e": 34841, "s": 34833, "text": "clintra" }, { "code": null, "e": 34854, "s": 34841, "text": "kumar_satyam" }, { "code": null, "e": 34863, "s": 34854, "text": "R-Graphs" }, { "code": null, "e": 34874, "s": 34863, "text": "R-Packages" }, { "code": null, "e": 34882, "s": 34874, "text": "R-plots" }, { "code": null, "e": 34895, "s": 34882, "text": "R-Statistics" }, { "code": null, "e": 34906, "s": 34895, "text": "R Language" }, { "code": null, "e": 35004, "s": 34906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35013, "s": 35004, "text": "Comments" }, { "code": null, "e": 35026, "s": 35013, "text": "Old Comments" }, { "code": null, "e": 35071, "s": 35026, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 35129, "s": 35071, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 35192, "s": 35129, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 35244, "s": 35192, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 35296, "s": 35244, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 35328, "s": 35296, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 35393, "s": 35328, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 35437, "s": 35393, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 35475, "s": 35437, "text": "How to Change Axis Scales in R Plots?" } ]
Hash Function for String data in C# - GeeksforGeeks
01 Feb, 2019 Question: Write code in C# to Hash an array of keys and display them with their hash code. Answer: Hashtable is a widely used data structure to store values (i.e. keys) indexed with their hash code. Hash code is the result of the hash function and is used as the value of the index for storing a key. If two distinct keys hash to the same value the situation is called a collision and a good hash function minimizes collisions. Question: How to choose a hash function appropriate for the data? Answer: If your data consists of integers then the easiest hash function is to return the remainder of the division of key and the size of the table. It is important to keep the size of the table as a prime number. But more complex functions can be written to avoid the collision. If your data consists of strings then you can add all the ASCII values of the alphabets and modulo the sum with the size of the table (the code below depicts the same). Example 1: // C# Program to create a Hash // Function for String datausing System; class Geeks { // Main Method public static void Main(String []args) { // Declaring the an string array string[] values = new string[50]; string str; // Values of the keys stored string[] keys = new string[] {"Alphabets", "Roman", "Numbers", "Alphanumeric", "Tallypoints"}; int hashCode; for (int k = 0; k < 5; k++) { str = keys[k]; // calling HashFunction hashCode = HashFunction(str, values); // Storing keys at their hashcode's index values[hashCode] = str; } // Displaying Hashcodes along with key values for (int k = 0; k < (values.GetUpperBound(0)); k++) { if (values[k] != null) Console.WriteLine(k + " " + values[k]); } } // Defining the hash function static int HashFunction(string s, string[] array) { int total = 0; char[] c; c = s.ToCharArray(); // Summing up all the ASCII values // of each alphabet in the string for (int k = 0; k <= c.GetUpperBound(0); k++) total += (int)c[k]; return total % array.GetUpperBound(0); }} 11 Tallypoints 16 Alphanumeric 19 Roman 34 Alphabets 46 Numbers Example 2: // C# Program to create a Hash // Function for String datausing System; class Geeks { // Main Method public static void Main(String []args) { // Declaring the an string array string[] values = new string[50]; string str; // Values of the keys stored string[] keys = new string[] {"C", "C++", "Java", "Python", "C#", "HTML"}; int hashCode; for (int k = 0; k < 5; k++) { str = keys[k]; hashCode = HashFunction2(str, values); // Storing keys at their hashcode's index values[hashCode] = str; } // Displaying Hashcodes along with key values for (int k = 0; k < (values.GetUpperBound(0)); k++) { if (values[k] != null) Console.WriteLine(k + " " + values[k]); } } // Defining the hash function static int HashFunction2(string s, string[] array) { long total = 0; char[] c; c = s.ToCharArray(); // Horner's rule for generating a polynomial // of 11 using ASCII values of the characters for (int k = 0; k <= c.GetUpperBound(0); k++) total += 11 * total + (int)c[k]; total = total % array.GetUpperBound(0); if (total < 0) total += array.GetUpperBound(0); return (int)total; }} 6 C# 15 C++ 18 C 19 Python 28 Java Explanation: In HashFunction, we pass the arguments as a string to be hashed and the string data ‘values‘. The method ToCharArray converts the string to the character array and then we start a for loop from the start to the end of the character array. Inside the for loop we calculate the sum total of the ASCII values of each character in the array. The method GetUpperBound returns the value of the highest index of the array. Then hash function returns modulo of the sum total by the upper bound of the array ( in this case 49 since string[] values = new string[50] ). Whereas in HashFunction2, we are passing the same arguments but this function is less likely to have collisions. Everything is basically the same except here we use Horner’s Rule to compute the polynomial function of 11. CSharp-string C# C# Programs Hash Technical Scripter Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Convert String to Character Array in C# Getting a Month Name Using Month Number in C# Program to Print a New Line in C# Socket Programming in C# Program to find absolute value of a given number
[ { "code": null, "e": 26183, "s": 26155, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26274, "s": 26183, "text": "Question: Write code in C# to Hash an array of keys and display them with their hash code." }, { "code": null, "e": 26611, "s": 26274, "text": "Answer: Hashtable is a widely used data structure to store values (i.e. keys) indexed with their hash code. Hash code is the result of the hash function and is used as the value of the index for storing a key. If two distinct keys hash to the same value the situation is called a collision and a good hash function minimizes collisions." }, { "code": null, "e": 26677, "s": 26611, "text": "Question: How to choose a hash function appropriate for the data?" }, { "code": null, "e": 27127, "s": 26677, "text": "Answer: If your data consists of integers then the easiest hash function is to return the remainder of the division of key and the size of the table. It is important to keep the size of the table as a prime number. But more complex functions can be written to avoid the collision. If your data consists of strings then you can add all the ASCII values of the alphabets and modulo the sum with the size of the table (the code below depicts the same)." }, { "code": null, "e": 27138, "s": 27127, "text": "Example 1:" }, { "code": "// C# Program to create a Hash // Function for String datausing System; class Geeks { // Main Method public static void Main(String []args) { // Declaring the an string array string[] values = new string[50]; string str; // Values of the keys stored string[] keys = new string[] {\"Alphabets\", \"Roman\", \"Numbers\", \"Alphanumeric\", \"Tallypoints\"}; int hashCode; for (int k = 0; k < 5; k++) { str = keys[k]; // calling HashFunction hashCode = HashFunction(str, values); // Storing keys at their hashcode's index values[hashCode] = str; } // Displaying Hashcodes along with key values for (int k = 0; k < (values.GetUpperBound(0)); k++) { if (values[k] != null) Console.WriteLine(k + \" \" + values[k]); } } // Defining the hash function static int HashFunction(string s, string[] array) { int total = 0; char[] c; c = s.ToCharArray(); // Summing up all the ASCII values // of each alphabet in the string for (int k = 0; k <= c.GetUpperBound(0); k++) total += (int)c[k]; return total % array.GetUpperBound(0); }}", "e": 28510, "s": 27138, "text": null }, { "code": null, "e": 28575, "s": 28510, "text": "11 Tallypoints\n16 Alphanumeric\n19 Roman\n34 Alphabets\n46 Numbers\n" }, { "code": null, "e": 28586, "s": 28575, "text": "Example 2:" }, { "code": "// C# Program to create a Hash // Function for String datausing System; class Geeks { // Main Method public static void Main(String []args) { // Declaring the an string array string[] values = new string[50]; string str; // Values of the keys stored string[] keys = new string[] {\"C\", \"C++\", \"Java\", \"Python\", \"C#\", \"HTML\"}; int hashCode; for (int k = 0; k < 5; k++) { str = keys[k]; hashCode = HashFunction2(str, values); // Storing keys at their hashcode's index values[hashCode] = str; } // Displaying Hashcodes along with key values for (int k = 0; k < (values.GetUpperBound(0)); k++) { if (values[k] != null) Console.WriteLine(k + \" \" + values[k]); } } // Defining the hash function static int HashFunction2(string s, string[] array) { long total = 0; char[] c; c = s.ToCharArray(); // Horner's rule for generating a polynomial // of 11 using ASCII values of the characters for (int k = 0; k <= c.GetUpperBound(0); k++) total += 11 * total + (int)c[k]; total = total % array.GetUpperBound(0); if (total < 0) total += array.GetUpperBound(0); return (int)total; }}", "e": 30011, "s": 28586, "text": null }, { "code": null, "e": 30047, "s": 30011, "text": "6 C#\n15 C++\n18 C\n19 Python\n28 Java\n" }, { "code": null, "e": 30840, "s": 30047, "text": "Explanation: In HashFunction, we pass the arguments as a string to be hashed and the string data ‘values‘. The method ToCharArray converts the string to the character array and then we start a for loop from the start to the end of the character array. Inside the for loop we calculate the sum total of the ASCII values of each character in the array. The method GetUpperBound returns the value of the highest index of the array. Then hash function returns modulo of the sum total by the upper bound of the array ( in this case 49 since string[] values = new string[50] ). Whereas in HashFunction2, we are passing the same arguments but this function is less likely to have collisions. Everything is basically the same except here we use Horner’s Rule to compute the polynomial function of 11." }, { "code": null, "e": 30854, "s": 30840, "text": "CSharp-string" }, { "code": null, "e": 30857, "s": 30854, "text": "C#" }, { "code": null, "e": 30869, "s": 30857, "text": "C# Programs" }, { "code": null, "e": 30874, "s": 30869, "text": "Hash" }, { "code": null, "e": 30893, "s": 30874, "text": "Technical Scripter" }, { "code": null, "e": 30898, "s": 30893, "text": "Hash" }, { "code": null, "e": 30996, "s": 30898, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31024, "s": 30996, "text": "C# Dictionary with examples" }, { "code": null, "e": 31039, "s": 31024, "text": "C# | Delegates" }, { "code": null, "e": 31062, "s": 31039, "text": "C# | Method Overriding" }, { "code": null, "e": 31084, "s": 31062, "text": "C# | Abstract Classes" }, { "code": null, "e": 31130, "s": 31084, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 31170, "s": 31130, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 31216, "s": 31170, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 31250, "s": 31216, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 31275, "s": 31250, "text": "Socket Programming in C#" } ]
How to check if PSCustomObject is empty in PowerShell?
To check if the PSCustomObject is empty or not in PowerShell, we need to check the fields of the PSCustomObject. Consider the below example, $output = [PSCustomObject]@{ Name = 'John' City = 'New York' Country = 'US' Company = 'Alpha' } $output1 = [PSCustomObject]@{ Name = '' City = '' Country = '' Company = '' } PS C:\WINDOWS\system32> $output Name City Country Company ---- ---- ------- ------- John New York US Alpha PS C:\WINDOWS\system32> $output1 Name City Country Company ---- ---- ------- ------- In this example, we have Output and Output1 PSCustomObjects and the output1 is the empty one. First of all, we can’t determine by the Count property because no such direct method exists for the Custom Objects. For example, PS C:\WINDOWS\system32> $output.count PS C:\WINDOWS\system32> $output1.count There will be no output because Count is not supported in the PSCustomObject but if we convert it to the string using the ToString() method then we can use the count method. For example, PS C:\WINDOWS\system32> $output.ToString().Count 1 PS C:\WINDOWS\system32> $output1.ToString().Count 1 But it entirely considers PSCustomObject as one so always gives the count 1. But we can determine if the PSCustoObject is empty or not by checking its field. So we will check here any property of the column of the object and if it is null then the PSCustomObject is null. PS C:\WINDOWS\system32> $output.Country -eq "" False PS C:\WINDOWS\system32> $output1.Country -eq "" True So the Output1 Object is empty. In some cases, you can check multiple properties to confirm if the PSCustomObject is empty.
[ { "code": null, "e": 1203, "s": 1062, "text": "To check if the PSCustomObject is empty or not in PowerShell, we need to check the fields of the PSCustomObject. Consider the below example," }, { "code": null, "e": 1403, "s": 1203, "text": "$output = [PSCustomObject]@{\n Name = 'John'\n City = 'New York'\n Country = 'US'\n Company = 'Alpha' \n}\n$output1 = [PSCustomObject]@{\n Name = ''\n City = ''\n Country = ''\n Company = ''\n}" }, { "code": null, "e": 1646, "s": 1403, "text": "PS C:\\WINDOWS\\system32> $output\nName City Country Company\n---- ---- ------- -------\nJohn New York US Alpha\nPS C:\\WINDOWS\\system32> $output1\nName City Country Company\n---- ---- ------- -------" }, { "code": null, "e": 1869, "s": 1646, "text": "In this example, we have Output and Output1 PSCustomObjects and the output1 is the empty one. First of all, we can’t determine by the Count property because no such direct method exists for the Custom Objects. For example," }, { "code": null, "e": 1946, "s": 1869, "text": "PS C:\\WINDOWS\\system32> $output.count\nPS C:\\WINDOWS\\system32> $output1.count" }, { "code": null, "e": 2133, "s": 1946, "text": "There will be no output because Count is not supported in the PSCustomObject but if we convert it to the string using the ToString() method then we can use the count method. For example," }, { "code": null, "e": 2236, "s": 2133, "text": "PS C:\\WINDOWS\\system32> $output.ToString().Count\n1\nPS C:\\WINDOWS\\system32> $output1.ToString().Count\n1" }, { "code": null, "e": 2508, "s": 2236, "text": "But it entirely considers PSCustomObject as one so always gives the count 1. But we can determine if the PSCustoObject is empty or not by checking its field. So we will check here any property of the column of the object and if it is null then the PSCustomObject is null." }, { "code": null, "e": 2614, "s": 2508, "text": "PS C:\\WINDOWS\\system32> $output.Country -eq \"\"\nFalse\nPS C:\\WINDOWS\\system32> $output1.Country -eq \"\"\nTrue" }, { "code": null, "e": 2738, "s": 2614, "text": "So the Output1 Object is empty. In some cases, you can check multiple properties to confirm if the PSCustomObject is empty." } ]
Output of C Program | Set 28 - GeeksforGeeks
27 Dec, 2016 Predict the output of following C program. Question 1 #include <stdio.h> int main(){ char a = 30; char b = 40; char c = 10; char d = (a * b) / c; printf ("%d ", d); return 0;} At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200. For example, the following code snippet prints -80 on a 32 bit little endian machine. char d = 1200; printf ("%d ", d); Arithmetic overflow doesn’t happen in the original program and the output of the program is 120. In C, char and short are converted to int for arithmetic calculations. So in the expression ‘(a*b)/c’, a, b and c are promoted to int and no overflow happens. Question 2 #include<stdio.h>int main(){ int a, b = 10; a = -b--; printf("a = %d, b = %d", a, b); return 0;} Output: a = -10, b = 9 The statement ‘a = -b–;’ compiles fine. Unary minus and unary decrement have save precedence and right to left associativity. Therefore ‘-b–‘ is treated as -(b–) which is valid. So -10 will be assigned to ‘a’, and ‘b’ will become 9.Try the following program as an exercise. #include<stdio.h>int main(){ int a, b = 10; a = b---; printf("a = %d, b = %d", a, b); return 0;} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways to copy a string in C/C++ Output of Java Program | Set 3 Runtime Errors Output of Java Programs | Set 14 (Constructors) Output of Java program | Set 5 Output of Java Program | Set 7 Output of C programs | Set 57 (for loop) unsigned specifier (%u) in C with Examples Output of Java Program | Set 4 Output of Java program | Set 26
[ { "code": null, "e": 24250, "s": 24222, "text": "\n27 Dec, 2016" }, { "code": null, "e": 24293, "s": 24250, "text": "Predict the output of following C program." }, { "code": null, "e": 24304, "s": 24293, "text": "Question 1" }, { "code": "#include <stdio.h> int main(){ char a = 30; char b = 40; char c = 10; char d = (a * b) / c; printf (\"%d \", d); return 0;}", "e": 24447, "s": 24304, "text": null }, { "code": null, "e": 24748, "s": 24447, "text": "At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200. For example, the following code snippet prints -80 on a 32 bit little endian machine." }, { "code": null, "e": 24790, "s": 24748, "text": " char d = 1200;\n printf (\"%d \", d);" }, { "code": null, "e": 25046, "s": 24790, "text": "Arithmetic overflow doesn’t happen in the original program and the output of the program is 120. In C, char and short are converted to int for arithmetic calculations. So in the expression ‘(a*b)/c’, a, b and c are promoted to int and no overflow happens." }, { "code": null, "e": 25057, "s": 25046, "text": "Question 2" }, { "code": "#include<stdio.h>int main(){ int a, b = 10; a = -b--; printf(\"a = %d, b = %d\", a, b); return 0;}", "e": 25166, "s": 25057, "text": null }, { "code": null, "e": 25174, "s": 25166, "text": "Output:" }, { "code": null, "e": 25190, "s": 25174, "text": "a = -10, b = 9\n" }, { "code": null, "e": 25464, "s": 25190, "text": "The statement ‘a = -b–;’ compiles fine. Unary minus and unary decrement have save precedence and right to left associativity. Therefore ‘-b–‘ is treated as -(b–) which is valid. So -10 will be assigned to ‘a’, and ‘b’ will become 9.Try the following program as an exercise." }, { "code": "#include<stdio.h>int main(){ int a, b = 10; a = b---; printf(\"a = %d, b = %d\", a, b); return 0;}", "e": 25573, "s": 25464, "text": null }, { "code": null, "e": 25698, "s": 25573, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25707, "s": 25698, "text": "C-Output" }, { "code": null, "e": 25722, "s": 25707, "text": "Program Output" }, { "code": null, "e": 25820, "s": 25722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25829, "s": 25820, "text": "Comments" }, { "code": null, "e": 25842, "s": 25829, "text": "Old Comments" }, { "code": null, "e": 25883, "s": 25842, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 25914, "s": 25883, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 25929, "s": 25914, "text": "Runtime Errors" }, { "code": null, "e": 25977, "s": 25929, "text": "Output of Java Programs | Set 14 (Constructors)" }, { "code": null, "e": 26008, "s": 25977, "text": "Output of Java program | Set 5" }, { "code": null, "e": 26039, "s": 26008, "text": "Output of Java Program | Set 7" }, { "code": null, "e": 26080, "s": 26039, "text": "Output of C programs | Set 57 (for loop)" }, { "code": null, "e": 26123, "s": 26080, "text": "unsigned specifier (%u) in C with Examples" }, { "code": null, "e": 26154, "s": 26123, "text": "Output of Java Program | Set 4" } ]