title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
A gentle guide to Tidy statistics in R (part 2) | by Thomas Mock | Towards Data Science
|
Part 1 starts you on the journey of running your statistics in R code.
After a great discussion started by Jesse Maegan (@kiersi) on Twitter, I decided to post a workthrough of some (fake) experimental treatment data. These data correspond to a new (fake) research drug called AD-x37, a theoretical drug that has been shown to have beneficial outcomes on cognitive decline in mouse models of Alzheimer’s disease. In the current experiment we will be statistically testing whether the drug was effective in reducing cognitive impairment in dementia patients. See the data here.
We will be using MMSE (mini-mental status exam) scores to assess the degree of cognitive impairment. In a real clinical trial, many other variables would be recorded, but for the sake of a straightforward but multi-variate example we will stick to just MMSE.
We will be working through loading, plotting, analyzing, and saving the outputs of our analysis through the tidyverse, an “opinionated collection of R packages” designed for data analysis. We will limit dependence to two packages: tidyverse and broomwhile using base R for the rest. These two packages dramatically improve the data analysis workflow in my opinion. While other stats-heavy packages provide additional statistical testing, base R has a decent ability to perform statistical analyses out of the box. I will use knitr::kable to generate some html tables for a markdown document, but it is not necessary for the workflow.
Additionally, I will be uploading the excel sheet used in this example, so that you can re-create the workflow on your own. You can simply copy-paste the code seen here and it will run in R. If you would rather see the entire workflow in an R-Markdown document, please see here. R Markdown is a document created inside R that allows you to write code, execute it inline, and write comments/notes as you go. You could think of it like being able to write R code inside a basic Word document (but it can do a lot more than that!).
Although you may not be interested in the dataset I have provided, this hopefully provides a clear workflow for you to swap in your data of interest and accomplish a basic analysis!
Using the library function we will load the tidyverse. If you have never installed it before you can also use the install.packages("tidyverse")call to install it for the first time. This package includes ggplot2 (graphs), dplyr/ tidyr(summary statistics, data manipulation), and readxl(reading excel files) as well as the pipe %>% which will make our code much more readable! We will also load the broom package to tidy up some of our statistical outputs. Lastly we will load knitr for making nice html tables via knitr::kable,but not necessary for simply saving the outputs to Excel.
# Load librarieslibrary(tidyverse)library(broom)library(knitr)library(readxl)
This will output some message about the packages being loaded and any conflicts of function calls.
Loading the data
While I am calling readxl::read_xlsx you could also simply use read_xlsx, but in the interest of transparency, I will be using the full call to begin. The concept of calling a function with the use of :: is important as some packages have conflicts in functions, for example multiple packages include the function select and summarize. As such, we can clarify from which package we want R to call our function from, so package::function ! To read more about the concept of “namespace” when calling functions, please look here.
readxl is unfortunately a funny case, as installing the tidyverse installs readxl, but readxl is not loaded when loading the tidyverse via a library call. As such we must either load readxl like any other package or call both the package and the name as in readxl::read_xlsx. readxl allows us to read .xls, .xlsx files into R. Alternatively, you could convert your Excel sheet into .csv, which can be read by read_csv(). By using the glimpse function from dplyr we can see how the variables were imported, as well as the first few rows.
# Read excel fileraw_df <- readxl::read_xlsx("ad_treatment.xlsx")dplyr::glimpse(raw_df)# this is the output from glimpse(raw_df)Observations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79, ...$ sex <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, ...$ health_status <chr> "Healthy", "Healthy", "Healthy", ...$ drug_treatment <chr> "Placebo", "Placebo", "Placebo", ...$ mmse <dbl> 24.78988, 24.88192, 25.10903, 23.38...
We can collect some information about the dataset now. Namely, we have our 3 categorical/factor variables: sex, health_status, and drug_treatment and 1 dependent variable (DV): mmse. We also have age, but importantly it is recorded as a discrete number instead of as a factor (eg as 85 years, instead of old). Thus we can look at age, but we will not use it as a factor in our ANOVA.
Checking the data distribution
We will use our first ggplot2call to create a graph showing the distribution of age. To break down what we are doing, we need to call ggplot, tell it what data to use, and use the aes or `aesthetic` call to assign the x coordinate. We then add a + which tells ggplot to include the next line of code. The geom_density tells R that we want to make create a density distribution layer and we want to fillit with a blue color! For more info about ggplot2 please go here or here.
ggplot(data = raw_df, aes(x = age)) + geom_density(fill = "blue")
The graph shows us that age really only goes from 79–85 years, and that there is really not any age over or underrepresented. We can confirm the age range s by a dplyr summarize call or by calling range in base R. As a slight aside, we can now talk about using the pipe or %>%. The pipe passes the results or data from the left of it to the right. For more info about the pipe, please see here.
We can read the following code as takeraw_df and then summarize it by taking the min and max of the age variable. Now because we started with raw_df R understands we want to take the column age from this dataframe.
raw_df %>% summarize( min = min(age), max = max(age))# A tibble: 1 x 2 min max <dbl> <dbl>1 79.0 85.0
Alternatively we could use the base R range function, which requires the use of $ . The dollar sign indicates that R should use the agecolumn from raw_df. Both of these functions give us the same results, the minimum number and maximum number.
range(raw_df$age)[1] 79 85
For more information about using these two syntaxes look here or for cheat sheets look here.
What about the experimental variables levels?
Now while I am very aware of the variables in this dataframe, you might not be without exploring it! To quickly determine drug_treatment groups, health_status groups and how they interact we can do a table call. By calling it on both drug_treatment and health_status, we get a nice table breaking down how many rows are in each of the variable groups.
table(raw_df$drug_treatment, raw_df$health_status)#output below Alzheimer's Healthy High Dose 100 100 Low dose 100 100 Placebo 100 100
Alternatively we can do the same thing in dplyr with the following code.
raw_df %>% group_by(drug_treatment, health_status) %>% count()
Now we know the levels of our variables of interest, and that there are 100 patients per overall treatment group!
Data exploration of dependent variable
Before running our summary statistics we can actually visualize the range, central tendency and quartiles via a geom_boxplot call.
ggplot(data = raw_df, # add the data aes(x = drug_treatment, y = mmse, # set x, y coordinates color = drug_treatment)) + # color by treatment geom_boxplot() + facet_grid(~health_status) # create panes base on health status
We have split the data into separate graph facets (or panes) for healthy and Alzheimer’s patients, as well as into groups within each facet by drug treatment. This graph tells us a few things of interest for later. It definitely looks like we have an effect with our (fake) awesome drug! Let’s explore that with descriptive statistics.
While this is an exploratory graph and we don’t necessarily want to “tweak” it to perfection, we can take note that our drug treatment should be ordered Placebo < Low dose < High Dose and we should have Healthy patients presented first, and Alzheimer’s patients second. This is something we can fix in our next section!
Summary Statistics
We are looking to generate the mean and standard error for mmse scores, this is useful as a measure of central tendency, and for creating our final publication graphs. We have our categorical variables of sex, drug treatment, and health status. However going back to our glimpse call from earlier, we can see that the data is not ‘coded’ properly. Namely, sex is a dbl (number), without a descriptive name, and health_status / drug_treatment are chr (characters)! These need to be converted into factors!
Observations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79, ...$ sex <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1...$ health_status <chr> "Healthy", "Healthy", "Healthy", ...$ drug_treatment <chr> "Placebo", "Placebo", "Placebo", ...$ mmse <dbl> 24.78988, 24.88192, 25.10903, 23.38...
We can use the dplyr::mutate function to tell R we want to change (mutate) the rows within a variable of interest. So we will take the data in the sex, drug_treatment, and health_status columns and convert them from either just numbers or characters into a factor variable! dplyr::mutate can also perform math, and many other interesting things. For more information please see here.
We will use the mutate function and the base R factorfunction to convert our variables into the proper factors, and give them labels (for sex) or reorder the levels of the factors.
We need to be REALLY careful to type the labels EXACTLY as they appear in the column or it will replace those misspelled with a NA. For example, did you notice that High Dose has a capital “D” while Low dose has a lower case “d”?
sum_df <- raw_df %>% mutate( sex = factor(sex, labels = c("Male", "Females")), drug_treatment = factor(drug_treatment, levels = c("Placebo", "Low dose", "High Dose")), health_status = factor(health_status, levels = c("Healthy", "Alzheimer's")) )
As powerful as R is, it needs explicit and accurate code input to accomplish the end goals. As such, if we had typed “High dose” it would give an NA, while “High Dose” outputs correctly. We now see age and mmse as dbl (numerics) and sex, health_status, and drug_treatment as factors.
Observations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79,...$ sex <fct> Male, Male, Male, Male, Male, Females, Mal...$ health_status <fct> Healthy, Healthy, Healthy, Healthy, Health...$ drug_treatment <fct> Placebo, Placebo, Placebo, Placebo, Placeb...$ mmse <dbl> 24.78988, 24.88192, 25.10903, 24.92636,...
Now that everything is coded properly, we can calculate our mean and standard error (se = standard deviation/square root of number of samples)! We will use the group_by to tell R which factors we want to... group by! Then we will create named summaries by first calling summarize and then specifying which summaries we want with mmse_mean and mmse_seand the number of samples n(). Lastly we will ungroup, which removes the group_by code from the dataframe.
sum_df <- sum_df %>% group_by(sex, health_status, drug_treatment) %>% summarize(mmse_mean = mean(mmse), mmse_se = sd(mmse)/sqrt(n()), n_samples = n()) %>% ungroup() # ungrouping variable is a good habit to prevent errors
Now we have a nicely formatted dataframe that can be saved to Excel, or used in graphing. We need to indicate what data we are writing (sum_df) and what we want the resulting file to be named (“adx37_sum_stats.csv”).
# code to save the table into a .csv Excel filewrite.csv(sum_df, "adx37_sum_stats.csv")
Summary graph
By calling a ggplot function we can generate a preliminary summary graph.
ggplot(data = sum_df, # add the data aes(x = drug_treatment, #set x, y coordinates y = mmse_mean, group = drug_treatment, # group by treatment color = drug_treatment)) + # color by treatment geom_point(size = 3) + # set size of the dots facet_grid(sex~health_status) # create facets by sex and status
We can now see that the graph is properly sorted by drug treatment and by health status. We still have some work to do on the final graph, but let’s move on to the ANOVAs first!
The ANOVA finally!
We will be prepping a dataframe for analysis via ANOVA. We need to again make sure we have our factors as factors via mutate, and in the correct order. This is necessary for the ANOVA/post-hoc testing to work, and to make the post-hocs and the ANOVA outputs easier to read.
stats_df <- raw_df %>% # start with data mutate(drug_treatment = factor(drug_treatment, levels = c("Placebo", "Low dose", "High Dose")), sex = factor(sex, labels = c("Male", "Female")), health_status = factor(health_status, levels = c("Healthy", "Alzheimer's")))glimpse(stats_df)#output belowObservations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79...$ sex <fct> Male, Male, Male, Male, Male, Male, ...$ health_status <fct> Healthy, Healthy, Healthy, Healthy...$ drug_treatment <fct> Placebo, Placebo, Placebo, Placebo,...$ mmse <dbl> 24.78988, 24.88192, 25.10903...
That gets our dataframe into working status!
Calling the ANOVA is a done via the aov function. The basic syntax is shown via pseudocode below. We put the dependent variable first (mmse in our case), then a ~ then the independent variable we want to test. Lastly we specify what data to use.
aov(dependent_variable ~ independent variable, data = data_df)
We can add our real data set via the code below:
# this gives main effects AND interactionsad_aov <- aov(mmse ~ sex * drug_treatment * health_status, data = stats_df)# this would give ONLY main effectsad_aov <- aov(mmse ~ sex + drug_treatment + health_status, data = stats_df)
Because we have 3 independent variables we have a choice to make. We can simply look for main effects by adding a + in between each of our variables, or we can look for both main effects and interactions by adding a * between each variable. Make sure to not replace the + or * with commas, as that will lead to an error!
# this throws an error because we shouldn't use commas in between!ad_aov <- aov(mmse ~ sex, drug_treatment, health_status, data = stats_df)
By assigning the ANOVA to the ad_aov object, we can then call summary on it to look at the results of the ANOVA.
# look at effects and interactionssummary(ad_aov) Df Sum Sq Mean Sq F value Pr(>F) sex 1 0 0 0.047 0.828 drug_treatment 2 3601 1801 909.213 <2e-16 health_status 1 10789 10789 5447.953 <2e-16 sex:drug_treatment 2 8 4 2.070 0.127 sex:health_status 1 5 5 2.448 0.118 drug_treatment:health_status 2 2842 1421 717.584 <2e-16 sex:drug_treatment:health_status 2 5 2 1.213 0.298 Residuals 588 1164 2 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
The summary gives us the degrees of freedom, sum of squares, mean squares, F value, and the p value. I added a bold emphasis on the <2e -16, these p values are so small that R switches to scientific notation. So we see significant main effects of drug treatment, health status, and an interaction of drug treatment by health status. We can interpret that Alzheimer’s patients had different cognitive scores than healthy, and that drug treatment had an effect on cognitive scores. Importantly, sex was not a significant factor, as p = 0.828. Variables being scored as significant or non-significant can both be important!
We can also use broom::tidy to clean up the results of the ANOVA and put them into a dataframe. This is useful for storage, or for automation of some analysis for future ANOVAs.
# this extracts ANOVA output into a nice tidy dataframetidy_ad_aov <- tidy(ad_aov)# which we can save to Excelwrite.csv(tidy_ad_aov, "ad_aov.csv")
However, we don’t know the direction of changes, or where the changes occurred. Was it just the high dose? Low dose? Both? We need follow-up post hoc tests to determine these answers!
Post-hocs > Post-docs (academia jokes < dad jokes)
We have multiple ways of looking at post-hocs. I will show two in this section.
For the pairwise, we need to use the $ to select columns from each of the dataframes and look at the interaction via :. Our first pairwise has NO correction for multiple comparisons, and is comparable to a unprotected Fisher’s-LSD post-hoc. This is not stringent at all, and given the amount of comparisons we have it is advisable to either move forward with a p.adjusting Bonferonni correction (change p.adj = “none” to p.adj = “bonf”) or the Tukey post-hoc test seen in the next example. You can see that this method is a little jumbled to read due to the dataset$column method and the need for : in between each interaction. We can read this as we want pairwise.t.test for the interaction of sex by drug_treatment by health_status, which gives us every iteration of these factors against the other.
# call and save the pair.t.testad_pairwise <- pairwise.t.test(stats_df$mmse, stats_df$sex:stats_df$drug_treatment:stats_df$health_status, p.adj = "none")
Additionally, we need to extract the matrix of p values and save to an Excel file for future use.
We do this by simply wrapping our ad_last posthoc with broom::tidy .
# tidy the post hoctidy_ad_pairwise <- broom::tidy(ad_pairwise)# save to excelwrite.csv(tidy_ad_pairwise, "tidy_ad_pairwise.csv")
The Tukey post-hoc is a little cleaner to call, and is preferable to the unadjusted pairwise t-test. Notice we also are already wrapping the Tukey results in broom::tidy to save as a tidy dataframe! The TukeyHSD call incorporates the results of the ANOVA call, and is preferable to the previous method.
The following code can be read as we want a Tukey post-hoc test on the results of our ad_aov ANOVA across the interactions of sex by drug_treatment by health_status. Notice the quotation marks around ‘sex:drug_treatment:health_status’ and the : in between each variable. These are necessary to tell R how we want the Tukey to be run! Once this is done, R then runs tidy on it to make it into a nice dataframe similar to our previous pairwise test. We can then save the results to Excel!
# call and tidy the tukey posthoctidy_ad_tukey <- tidy(TukeyHSD(ad_aov, which = 'sex:drug_treatment:health_status'))# save to excelwrite.csv(tidy_tukey_ad, "tukey_ad.csv")
Publication Graph
Now that we have generated our ANOVAs and post-hocs , and saved them to Excel for storage, we can start making a publication-grade graph!
ggplot2 graphs allow for extreme customization, some of the additions I make to this graph are a personal choice, and as such I would recommend discussion with a mentor or experienced member in your field. Bar graphs are ubiquitous in my field, and while I think plotting as a boxplot would tell more about the data, I will initially start with a bar graph.
Our goal is to plot the means, standard errors, and indicate significance where it occurs. Rather than relying on a package to label significance, I will be handmaking a custom dataframe with the tribble function. There are alternatives to doing it this way, but I can easily control what happens with this method, and it is explicitly apparent what the dataframe contains. The basics of tribble are shown in the below example. We assign columns with the ~ and then explicitly write out what we want in each row of the columns.
tribble( ~colA, ~colB, "a", 1, "b", 2, "c", 3)# Output below# A tibble: 3 x 2 colA colB <chr> <dbl>1 a 12 b 23 c 3
And here is our actual code for making the custom dataframe.
# make the dataframe with specific points of interest to add *sig_df <- tribble( ~drug_treatment, ~ health_status, ~sex, ~mmse_mean, "Low dose", "Alzheimer's", "Male", 17, "High Dose", "Alzheimer's", "Male", 25, "Low dose", "Alzheimer's", "Female", 18, "High Dose", "Alzheimer's", "Female", 24 )# convert the variables to factors again :)sig_df <- sig_df %>% mutate(drug_treatment = factor(drug_treatment, levels = c("Placebo", "Low dose", "High Dose")), sex = factor(sex, levels = c("Male", "Female")), health_status = factor(health_status, levels = c("Healthy", "Alzheimer's")))# Output below# A tibble: 4 x 4 drug_treatment health_status sex mmse_mean <fctr> <fctr> <fctr> <dbl>1 Low dose Alzheimer's Male 17.02 High Dose Alzheimer's Male 25.03 Low dose Alzheimer's Female 18.04 High Dose Alzheimer's Female 24.0
Now that we have this data frame, we can use it in a geom_text call to label our bars with significance labels as indicated by a *.
Here is what the final publication graph looks like in ggplot2 code. You’ll notice I assigned it to g1 rather than just calling it directly. This means I will have to call g1 to view the graph, but I can save it now! To read what we are doing, I am calling the initial ggplot call as before, but adding an error bar layer, a bar graph layer, separating into panes for sex and health_status, switching to an alternate appearance (theme_bw), setting the colors manually, making minor adjustments via theme, adding the * for indication of significance, and lastly altering the axis labels while adding a figure caption.
g1 <- ggplot(data = sum_df, aes(x = drug_treatment, y = mmse_mean, fill = drug_treatment, group = drug_treatment)) + geom_errorbar(aes(ymin = mmse_mean - mmse_se, ymax = mmse_mean + mmse_se), width = 0.5) + geom_bar(color = "black", stat = "identity", width = 0.7) + facet_grid(sex~health_status) + theme_bw() + scale_fill_manual(values = c("white", "grey", "black")) + theme(legend.position = "NULL", legend.title = element_blank(), axis.title = element_text(size = 20), legend.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text = element_text(size = 12)) + geom_text(data = sig_df, label = "*", size = 8) + labs(x = "\nDrug Treatment", y = "Cognitive Function (MMSE)\n", caption = "\nFigure 1. Effect of novel drug treatment AD-x37 on cognitive function in healthy and demented elderly adults. \nn = 100/treatment group (total n = 600), * indicates significance at p < 0.001")g1# save the graph!ggsave("ad_publication_graph.png", g1, height = 7, width = 8, units = "in")
Saving is done via the ggsave function, where we will need to name the resulting file with surrounding “ “, tell R which ggplot object we want (g1), and indicate the size via height, width, and units.
And the final graph!
I think it would be a disservice to say you can learn ggplot by simply recreating my example. As such, I would like to point you in the direction of the R for Data Science textbook, as well as the Modern Dive ebook. These free ebooks have a tremendous amount of information that may be beyond what you need to accomplish today, but would serve you well in your future endeavors. Their chapters on data visualization are very helpful for getting started in R plotting!
If you have made it this far, good for you! I hope this was helpful and if you have any questions, I would recommend reaching out on Twitter via the #rstats hashtag, or you can find me @thomas_mock on twitter.
Additionally, Jesse Maegan has a R for Data Science Slack channel where you can learn and ask questions. R Studio (caretakers of the Tidyverse) hosts their own forums at https://community.rstudio.com/.
|
[
{
"code": null,
"e": 242,
"s": 171,
"text": "Part 1 starts you on the journey of running your statistics in R code."
},
{
"code": null,
"e": 748,
"s": 242,
"text": "After a great discussion started by Jesse Maegan (@kiersi) on Twitter, I decided to post a workthrough of some (fake) experimental treatment data. These data correspond to a new (fake) research drug called AD-x37, a theoretical drug that has been shown to have beneficial outcomes on cognitive decline in mouse models of Alzheimer’s disease. In the current experiment we will be statistically testing whether the drug was effective in reducing cognitive impairment in dementia patients. See the data here."
},
{
"code": null,
"e": 1007,
"s": 748,
"text": "We will be using MMSE (mini-mental status exam) scores to assess the degree of cognitive impairment. In a real clinical trial, many other variables would be recorded, but for the sake of a straightforward but multi-variate example we will stick to just MMSE."
},
{
"code": null,
"e": 1641,
"s": 1007,
"text": "We will be working through loading, plotting, analyzing, and saving the outputs of our analysis through the tidyverse, an “opinionated collection of R packages” designed for data analysis. We will limit dependence to two packages: tidyverse and broomwhile using base R for the rest. These two packages dramatically improve the data analysis workflow in my opinion. While other stats-heavy packages provide additional statistical testing, base R has a decent ability to perform statistical analyses out of the box. I will use knitr::kable to generate some html tables for a markdown document, but it is not necessary for the workflow."
},
{
"code": null,
"e": 2170,
"s": 1641,
"text": "Additionally, I will be uploading the excel sheet used in this example, so that you can re-create the workflow on your own. You can simply copy-paste the code seen here and it will run in R. If you would rather see the entire workflow in an R-Markdown document, please see here. R Markdown is a document created inside R that allows you to write code, execute it inline, and write comments/notes as you go. You could think of it like being able to write R code inside a basic Word document (but it can do a lot more than that!)."
},
{
"code": null,
"e": 2352,
"s": 2170,
"text": "Although you may not be interested in the dataset I have provided, this hopefully provides a clear workflow for you to swap in your data of interest and accomplish a basic analysis!"
},
{
"code": null,
"e": 2937,
"s": 2352,
"text": "Using the library function we will load the tidyverse. If you have never installed it before you can also use the install.packages(\"tidyverse\")call to install it for the first time. This package includes ggplot2 (graphs), dplyr/ tidyr(summary statistics, data manipulation), and readxl(reading excel files) as well as the pipe %>% which will make our code much more readable! We will also load the broom package to tidy up some of our statistical outputs. Lastly we will load knitr for making nice html tables via knitr::kable,but not necessary for simply saving the outputs to Excel."
},
{
"code": null,
"e": 3015,
"s": 2937,
"text": "# Load librarieslibrary(tidyverse)library(broom)library(knitr)library(readxl)"
},
{
"code": null,
"e": 3114,
"s": 3015,
"text": "This will output some message about the packages being loaded and any conflicts of function calls."
},
{
"code": null,
"e": 3131,
"s": 3114,
"text": "Loading the data"
},
{
"code": null,
"e": 3658,
"s": 3131,
"text": "While I am calling readxl::read_xlsx you could also simply use read_xlsx, but in the interest of transparency, I will be using the full call to begin. The concept of calling a function with the use of :: is important as some packages have conflicts in functions, for example multiple packages include the function select and summarize. As such, we can clarify from which package we want R to call our function from, so package::function ! To read more about the concept of “namespace” when calling functions, please look here."
},
{
"code": null,
"e": 4195,
"s": 3658,
"text": "readxl is unfortunately a funny case, as installing the tidyverse installs readxl, but readxl is not loaded when loading the tidyverse via a library call. As such we must either load readxl like any other package or call both the package and the name as in readxl::read_xlsx. readxl allows us to read .xls, .xlsx files into R. Alternatively, you could convert your Excel sheet into .csv, which can be read by read_csv(). By using the glimpse function from dplyr we can see how the variables were imported, as well as the first few rows."
},
{
"code": null,
"e": 4663,
"s": 4195,
"text": "# Read excel fileraw_df <- readxl::read_xlsx(\"ad_treatment.xlsx\")dplyr::glimpse(raw_df)# this is the output from glimpse(raw_df)Observations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79, ...$ sex <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, ...$ health_status <chr> \"Healthy\", \"Healthy\", \"Healthy\", ...$ drug_treatment <chr> \"Placebo\", \"Placebo\", \"Placebo\", ...$ mmse <dbl> 24.78988, 24.88192, 25.10903, 23.38..."
},
{
"code": null,
"e": 5047,
"s": 4663,
"text": "We can collect some information about the dataset now. Namely, we have our 3 categorical/factor variables: sex, health_status, and drug_treatment and 1 dependent variable (DV): mmse. We also have age, but importantly it is recorded as a discrete number instead of as a factor (eg as 85 years, instead of old). Thus we can look at age, but we will not use it as a factor in our ANOVA."
},
{
"code": null,
"e": 5078,
"s": 5047,
"text": "Checking the data distribution"
},
{
"code": null,
"e": 5554,
"s": 5078,
"text": "We will use our first ggplot2call to create a graph showing the distribution of age. To break down what we are doing, we need to call ggplot, tell it what data to use, and use the aes or `aesthetic` call to assign the x coordinate. We then add a + which tells ggplot to include the next line of code. The geom_density tells R that we want to make create a density distribution layer and we want to fillit with a blue color! For more info about ggplot2 please go here or here."
},
{
"code": null,
"e": 5621,
"s": 5554,
"text": "ggplot(data = raw_df, aes(x = age)) + geom_density(fill = \"blue\")"
},
{
"code": null,
"e": 6016,
"s": 5621,
"text": "The graph shows us that age really only goes from 79–85 years, and that there is really not any age over or underrepresented. We can confirm the age range s by a dplyr summarize call or by calling range in base R. As a slight aside, we can now talk about using the pipe or %>%. The pipe passes the results or data from the left of it to the right. For more info about the pipe, please see here."
},
{
"code": null,
"e": 6231,
"s": 6016,
"text": "We can read the following code as takeraw_df and then summarize it by taking the min and max of the age variable. Now because we started with raw_df R understands we want to take the column age from this dataframe."
},
{
"code": null,
"e": 6342,
"s": 6231,
"text": "raw_df %>% summarize( min = min(age), max = max(age))# A tibble: 1 x 2 min max <dbl> <dbl>1 79.0 85.0"
},
{
"code": null,
"e": 6586,
"s": 6342,
"text": "Alternatively we could use the base R range function, which requires the use of $ . The dollar sign indicates that R should use the agecolumn from raw_df. Both of these functions give us the same results, the minimum number and maximum number."
},
{
"code": null,
"e": 6613,
"s": 6586,
"text": "range(raw_df$age)[1] 79 85"
},
{
"code": null,
"e": 6706,
"s": 6613,
"text": "For more information about using these two syntaxes look here or for cheat sheets look here."
},
{
"code": null,
"e": 6752,
"s": 6706,
"text": "What about the experimental variables levels?"
},
{
"code": null,
"e": 7104,
"s": 6752,
"text": "Now while I am very aware of the variables in this dataframe, you might not be without exploring it! To quickly determine drug_treatment groups, health_status groups and how they interact we can do a table call. By calling it on both drug_treatment and health_status, we get a nice table breaking down how many rows are in each of the variable groups."
},
{
"code": null,
"e": 7292,
"s": 7104,
"text": "table(raw_df$drug_treatment, raw_df$health_status)#output below Alzheimer's Healthy High Dose 100 100 Low dose 100 100 Placebo 100 100"
},
{
"code": null,
"e": 7365,
"s": 7292,
"text": "Alternatively we can do the same thing in dplyr with the following code."
},
{
"code": null,
"e": 7432,
"s": 7365,
"text": "raw_df %>% group_by(drug_treatment, health_status) %>% count()"
},
{
"code": null,
"e": 7546,
"s": 7432,
"text": "Now we know the levels of our variables of interest, and that there are 100 patients per overall treatment group!"
},
{
"code": null,
"e": 7585,
"s": 7546,
"text": "Data exploration of dependent variable"
},
{
"code": null,
"e": 7716,
"s": 7585,
"text": "Before running our summary statistics we can actually visualize the range, central tendency and quartiles via a geom_boxplot call."
},
{
"code": null,
"e": 7960,
"s": 7716,
"text": "ggplot(data = raw_df, # add the data aes(x = drug_treatment, y = mmse, # set x, y coordinates color = drug_treatment)) + # color by treatment geom_boxplot() + facet_grid(~health_status) # create panes base on health status"
},
{
"code": null,
"e": 8296,
"s": 7960,
"text": "We have split the data into separate graph facets (or panes) for healthy and Alzheimer’s patients, as well as into groups within each facet by drug treatment. This graph tells us a few things of interest for later. It definitely looks like we have an effect with our (fake) awesome drug! Let’s explore that with descriptive statistics."
},
{
"code": null,
"e": 8616,
"s": 8296,
"text": "While this is an exploratory graph and we don’t necessarily want to “tweak” it to perfection, we can take note that our drug treatment should be ordered Placebo < Low dose < High Dose and we should have Healthy patients presented first, and Alzheimer’s patients second. This is something we can fix in our next section!"
},
{
"code": null,
"e": 8635,
"s": 8616,
"text": "Summary Statistics"
},
{
"code": null,
"e": 9140,
"s": 8635,
"text": "We are looking to generate the mean and standard error for mmse scores, this is useful as a measure of central tendency, and for creating our final publication graphs. We have our categorical variables of sex, drug treatment, and health status. However going back to our glimpse call from earlier, we can see that the data is not ‘coded’ properly. Namely, sex is a dbl (number), without a descriptive name, and health_status / drug_treatment are chr (characters)! These need to be converted into factors!"
},
{
"code": null,
"e": 9481,
"s": 9140,
"text": "Observations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79, ...$ sex <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1...$ health_status <chr> \"Healthy\", \"Healthy\", \"Healthy\", ...$ drug_treatment <chr> \"Placebo\", \"Placebo\", \"Placebo\", ...$ mmse <dbl> 24.78988, 24.88192, 25.10903, 23.38..."
},
{
"code": null,
"e": 9865,
"s": 9481,
"text": "We can use the dplyr::mutate function to tell R we want to change (mutate) the rows within a variable of interest. So we will take the data in the sex, drug_treatment, and health_status columns and convert them from either just numbers or characters into a factor variable! dplyr::mutate can also perform math, and many other interesting things. For more information please see here."
},
{
"code": null,
"e": 10046,
"s": 9865,
"text": "We will use the mutate function and the base R factorfunction to convert our variables into the proper factors, and give them labels (for sex) or reorder the levels of the factors."
},
{
"code": null,
"e": 10276,
"s": 10046,
"text": "We need to be REALLY careful to type the labels EXACTLY as they appear in the column or it will replace those misspelled with a NA. For example, did you notice that High Dose has a capital “D” while Low dose has a lower case “d”?"
},
{
"code": null,
"e": 10641,
"s": 10276,
"text": "sum_df <- raw_df %>% mutate( sex = factor(sex, labels = c(\"Male\", \"Females\")), drug_treatment = factor(drug_treatment, levels = c(\"Placebo\", \"Low dose\", \"High Dose\")), health_status = factor(health_status, levels = c(\"Healthy\", \"Alzheimer's\")) )"
},
{
"code": null,
"e": 10925,
"s": 10641,
"text": "As powerful as R is, it needs explicit and accurate code input to accomplish the end goals. As such, if we had typed “High dose” it would give an NA, while “High Dose” outputs correctly. We now see age and mmse as dbl (numerics) and sex, health_status, and drug_treatment as factors."
},
{
"code": null,
"e": 11289,
"s": 10925,
"text": "Observations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79,...$ sex <fct> Male, Male, Male, Male, Male, Females, Mal...$ health_status <fct> Healthy, Healthy, Healthy, Healthy, Health...$ drug_treatment <fct> Placebo, Placebo, Placebo, Placebo, Placeb...$ mmse <dbl> 24.78988, 24.88192, 25.10903, 24.92636,..."
},
{
"code": null,
"e": 11746,
"s": 11289,
"text": "Now that everything is coded properly, we can calculate our mean and standard error (se = standard deviation/square root of number of samples)! We will use the group_by to tell R which factors we want to... group by! Then we will create named summaries by first calling summarize and then specifying which summaries we want with mmse_mean and mmse_seand the number of samples n(). Lastly we will ungroup, which removes the group_by code from the dataframe."
},
{
"code": null,
"e": 12000,
"s": 11746,
"text": "sum_df <- sum_df %>% group_by(sex, health_status, drug_treatment) %>% summarize(mmse_mean = mean(mmse), mmse_se = sd(mmse)/sqrt(n()), n_samples = n()) %>% ungroup() # ungrouping variable is a good habit to prevent errors"
},
{
"code": null,
"e": 12217,
"s": 12000,
"text": "Now we have a nicely formatted dataframe that can be saved to Excel, or used in graphing. We need to indicate what data we are writing (sum_df) and what we want the resulting file to be named (“adx37_sum_stats.csv”)."
},
{
"code": null,
"e": 12305,
"s": 12217,
"text": "# code to save the table into a .csv Excel filewrite.csv(sum_df, \"adx37_sum_stats.csv\")"
},
{
"code": null,
"e": 12319,
"s": 12305,
"text": "Summary graph"
},
{
"code": null,
"e": 12393,
"s": 12319,
"text": "By calling a ggplot function we can generate a preliminary summary graph."
},
{
"code": null,
"e": 12737,
"s": 12393,
"text": "ggplot(data = sum_df, # add the data aes(x = drug_treatment, #set x, y coordinates y = mmse_mean, group = drug_treatment, # group by treatment color = drug_treatment)) + # color by treatment geom_point(size = 3) + # set size of the dots facet_grid(sex~health_status) # create facets by sex and status"
},
{
"code": null,
"e": 12915,
"s": 12737,
"text": "We can now see that the graph is properly sorted by drug treatment and by health status. We still have some work to do on the final graph, but let’s move on to the ANOVAs first!"
},
{
"code": null,
"e": 12934,
"s": 12915,
"text": "The ANOVA finally!"
},
{
"code": null,
"e": 13208,
"s": 12934,
"text": "We will be prepping a dataframe for analysis via ANOVA. We need to again make sure we have our factors as factors via mutate, and in the correct order. This is necessary for the ANOVA/post-hoc testing to work, and to make the post-hocs and the ANOVA outputs easier to read."
},
{
"code": null,
"e": 13888,
"s": 13208,
"text": "stats_df <- raw_df %>% # start with data mutate(drug_treatment = factor(drug_treatment, levels = c(\"Placebo\", \"Low dose\", \"High Dose\")), sex = factor(sex, labels = c(\"Male\", \"Female\")), health_status = factor(health_status, levels = c(\"Healthy\", \"Alzheimer's\")))glimpse(stats_df)#output belowObservations: 600Variables: 5$ age <dbl> 80, 85, 82, 80, 83, 79, 82, 79, 80, 79...$ sex <fct> Male, Male, Male, Male, Male, Male, ...$ health_status <fct> Healthy, Healthy, Healthy, Healthy...$ drug_treatment <fct> Placebo, Placebo, Placebo, Placebo,...$ mmse <dbl> 24.78988, 24.88192, 25.10903..."
},
{
"code": null,
"e": 13933,
"s": 13888,
"text": "That gets our dataframe into working status!"
},
{
"code": null,
"e": 14179,
"s": 13933,
"text": "Calling the ANOVA is a done via the aov function. The basic syntax is shown via pseudocode below. We put the dependent variable first (mmse in our case), then a ~ then the independent variable we want to test. Lastly we specify what data to use."
},
{
"code": null,
"e": 14242,
"s": 14179,
"text": "aov(dependent_variable ~ independent variable, data = data_df)"
},
{
"code": null,
"e": 14291,
"s": 14242,
"text": "We can add our real data set via the code below:"
},
{
"code": null,
"e": 14527,
"s": 14291,
"text": "# this gives main effects AND interactionsad_aov <- aov(mmse ~ sex * drug_treatment * health_status, data = stats_df)# this would give ONLY main effectsad_aov <- aov(mmse ~ sex + drug_treatment + health_status, data = stats_df)"
},
{
"code": null,
"e": 14848,
"s": 14527,
"text": "Because we have 3 independent variables we have a choice to make. We can simply look for main effects by adding a + in between each of our variables, or we can look for both main effects and interactions by adding a * between each variable. Make sure to not replace the + or * with commas, as that will lead to an error!"
},
{
"code": null,
"e": 14988,
"s": 14848,
"text": "# this throws an error because we shouldn't use commas in between!ad_aov <- aov(mmse ~ sex, drug_treatment, health_status, data = stats_df)"
},
{
"code": null,
"e": 15101,
"s": 14988,
"text": "By assigning the ANOVA to the ad_aov object, we can then call summary on it to look at the results of the ANOVA."
},
{
"code": null,
"e": 15847,
"s": 15101,
"text": "# look at effects and interactionssummary(ad_aov) Df Sum Sq Mean Sq F value Pr(>F) sex 1 0 0 0.047 0.828 drug_treatment 2 3601 1801 909.213 <2e-16 health_status 1 10789 10789 5447.953 <2e-16 sex:drug_treatment 2 8 4 2.070 0.127 sex:health_status 1 5 5 2.448 0.118 drug_treatment:health_status 2 2842 1421 717.584 <2e-16 sex:drug_treatment:health_status 2 5 2 1.213 0.298 Residuals 588 1164 2 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 16468,
"s": 15847,
"text": "The summary gives us the degrees of freedom, sum of squares, mean squares, F value, and the p value. I added a bold emphasis on the <2e -16, these p values are so small that R switches to scientific notation. So we see significant main effects of drug treatment, health status, and an interaction of drug treatment by health status. We can interpret that Alzheimer’s patients had different cognitive scores than healthy, and that drug treatment had an effect on cognitive scores. Importantly, sex was not a significant factor, as p = 0.828. Variables being scored as significant or non-significant can both be important!"
},
{
"code": null,
"e": 16646,
"s": 16468,
"text": "We can also use broom::tidy to clean up the results of the ANOVA and put them into a dataframe. This is useful for storage, or for automation of some analysis for future ANOVAs."
},
{
"code": null,
"e": 16793,
"s": 16646,
"text": "# this extracts ANOVA output into a nice tidy dataframetidy_ad_aov <- tidy(ad_aov)# which we can save to Excelwrite.csv(tidy_ad_aov, \"ad_aov.csv\")"
},
{
"code": null,
"e": 16977,
"s": 16793,
"text": "However, we don’t know the direction of changes, or where the changes occurred. Was it just the high dose? Low dose? Both? We need follow-up post hoc tests to determine these answers!"
},
{
"code": null,
"e": 17028,
"s": 16977,
"text": "Post-hocs > Post-docs (academia jokes < dad jokes)"
},
{
"code": null,
"e": 17108,
"s": 17028,
"text": "We have multiple ways of looking at post-hocs. I will show two in this section."
},
{
"code": null,
"e": 17910,
"s": 17108,
"text": "For the pairwise, we need to use the $ to select columns from each of the dataframes and look at the interaction via :. Our first pairwise has NO correction for multiple comparisons, and is comparable to a unprotected Fisher’s-LSD post-hoc. This is not stringent at all, and given the amount of comparisons we have it is advisable to either move forward with a p.adjusting Bonferonni correction (change p.adj = “none” to p.adj = “bonf”) or the Tukey post-hoc test seen in the next example. You can see that this method is a little jumbled to read due to the dataset$column method and the need for : in between each interaction. We can read this as we want pairwise.t.test for the interaction of sex by drug_treatment by health_status, which gives us every iteration of these factors against the other."
},
{
"code": null,
"e": 18067,
"s": 17910,
"text": "# call and save the pair.t.testad_pairwise <- pairwise.t.test(stats_df$mmse, stats_df$sex:stats_df$drug_treatment:stats_df$health_status, p.adj = \"none\")"
},
{
"code": null,
"e": 18165,
"s": 18067,
"text": "Additionally, we need to extract the matrix of p values and save to an Excel file for future use."
},
{
"code": null,
"e": 18234,
"s": 18165,
"text": "We do this by simply wrapping our ad_last posthoc with broom::tidy ."
},
{
"code": null,
"e": 18364,
"s": 18234,
"text": "# tidy the post hoctidy_ad_pairwise <- broom::tidy(ad_pairwise)# save to excelwrite.csv(tidy_ad_pairwise, \"tidy_ad_pairwise.csv\")"
},
{
"code": null,
"e": 18667,
"s": 18364,
"text": "The Tukey post-hoc is a little cleaner to call, and is preferable to the unadjusted pairwise t-test. Notice we also are already wrapping the Tukey results in broom::tidy to save as a tidy dataframe! The TukeyHSD call incorporates the results of the ANOVA call, and is preferable to the previous method."
},
{
"code": null,
"e": 19154,
"s": 18667,
"text": "The following code can be read as we want a Tukey post-hoc test on the results of our ad_aov ANOVA across the interactions of sex by drug_treatment by health_status. Notice the quotation marks around ‘sex:drug_treatment:health_status’ and the : in between each variable. These are necessary to tell R how we want the Tukey to be run! Once this is done, R then runs tidy on it to make it into a nice dataframe similar to our previous pairwise test. We can then save the results to Excel!"
},
{
"code": null,
"e": 19338,
"s": 19154,
"text": "# call and tidy the tukey posthoctidy_ad_tukey <- tidy(TukeyHSD(ad_aov, which = 'sex:drug_treatment:health_status'))# save to excelwrite.csv(tidy_tukey_ad, \"tukey_ad.csv\")"
},
{
"code": null,
"e": 19356,
"s": 19338,
"text": "Publication Graph"
},
{
"code": null,
"e": 19494,
"s": 19356,
"text": "Now that we have generated our ANOVAs and post-hocs , and saved them to Excel for storage, we can start making a publication-grade graph!"
},
{
"code": null,
"e": 19852,
"s": 19494,
"text": "ggplot2 graphs allow for extreme customization, some of the additions I make to this graph are a personal choice, and as such I would recommend discussion with a mentor or experienced member in your field. Bar graphs are ubiquitous in my field, and while I think plotting as a boxplot would tell more about the data, I will initially start with a bar graph."
},
{
"code": null,
"e": 20380,
"s": 19852,
"text": "Our goal is to plot the means, standard errors, and indicate significance where it occurs. Rather than relying on a package to label significance, I will be handmaking a custom dataframe with the tribble function. There are alternatives to doing it this way, but I can easily control what happens with this method, and it is explicitly apparent what the dataframe contains. The basics of tribble are shown in the below example. We assign columns with the ~ and then explicitly write out what we want in each row of the columns."
},
{
"code": null,
"e": 20533,
"s": 20380,
"text": "tribble( ~colA, ~colB, \"a\", 1, \"b\", 2, \"c\", 3)# Output below# A tibble: 3 x 2 colA colB <chr> <dbl>1 a 12 b 23 c 3"
},
{
"code": null,
"e": 20594,
"s": 20533,
"text": "And here is our actual code for making the custom dataframe."
},
{
"code": null,
"e": 21558,
"s": 20594,
"text": "# make the dataframe with specific points of interest to add *sig_df <- tribble( ~drug_treatment, ~ health_status, ~sex, ~mmse_mean, \"Low dose\", \"Alzheimer's\", \"Male\", 17, \"High Dose\", \"Alzheimer's\", \"Male\", 25, \"Low dose\", \"Alzheimer's\", \"Female\", 18, \"High Dose\", \"Alzheimer's\", \"Female\", 24 )# convert the variables to factors again :)sig_df <- sig_df %>% mutate(drug_treatment = factor(drug_treatment, levels = c(\"Placebo\", \"Low dose\", \"High Dose\")), sex = factor(sex, levels = c(\"Male\", \"Female\")), health_status = factor(health_status, levels = c(\"Healthy\", \"Alzheimer's\")))# Output below# A tibble: 4 x 4 drug_treatment health_status sex mmse_mean <fctr> <fctr> <fctr> <dbl>1 Low dose Alzheimer's Male 17.02 High Dose Alzheimer's Male 25.03 Low dose Alzheimer's Female 18.04 High Dose Alzheimer's Female 24.0"
},
{
"code": null,
"e": 21690,
"s": 21558,
"text": "Now that we have this data frame, we can use it in a geom_text call to label our bars with significance labels as indicated by a *."
},
{
"code": null,
"e": 22307,
"s": 21690,
"text": "Here is what the final publication graph looks like in ggplot2 code. You’ll notice I assigned it to g1 rather than just calling it directly. This means I will have to call g1 to view the graph, but I can save it now! To read what we are doing, I am calling the initial ggplot call as before, but adding an error bar layer, a bar graph layer, separating into panes for sex and health_status, switching to an alternate appearance (theme_bw), setting the colors manually, making minor adjustments via theme, adding the * for indication of significance, and lastly altering the axis labels while adding a figure caption."
},
{
"code": null,
"e": 23446,
"s": 22307,
"text": "g1 <- ggplot(data = sum_df, aes(x = drug_treatment, y = mmse_mean, fill = drug_treatment, group = drug_treatment)) + geom_errorbar(aes(ymin = mmse_mean - mmse_se, ymax = mmse_mean + mmse_se), width = 0.5) + geom_bar(color = \"black\", stat = \"identity\", width = 0.7) + facet_grid(sex~health_status) + theme_bw() + scale_fill_manual(values = c(\"white\", \"grey\", \"black\")) + theme(legend.position = \"NULL\", legend.title = element_blank(), axis.title = element_text(size = 20), legend.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text = element_text(size = 12)) + geom_text(data = sig_df, label = \"*\", size = 8) + labs(x = \"\\nDrug Treatment\", y = \"Cognitive Function (MMSE)\\n\", caption = \"\\nFigure 1. Effect of novel drug treatment AD-x37 on cognitive function in healthy and demented elderly adults. \\nn = 100/treatment group (total n = 600), * indicates significance at p < 0.001\")g1# save the graph!ggsave(\"ad_publication_graph.png\", g1, height = 7, width = 8, units = \"in\")"
},
{
"code": null,
"e": 23647,
"s": 23446,
"text": "Saving is done via the ggsave function, where we will need to name the resulting file with surrounding “ “, tell R which ggplot object we want (g1), and indicate the size via height, width, and units."
},
{
"code": null,
"e": 23668,
"s": 23647,
"text": "And the final graph!"
},
{
"code": null,
"e": 24136,
"s": 23668,
"text": "I think it would be a disservice to say you can learn ggplot by simply recreating my example. As such, I would like to point you in the direction of the R for Data Science textbook, as well as the Modern Dive ebook. These free ebooks have a tremendous amount of information that may be beyond what you need to accomplish today, but would serve you well in your future endeavors. Their chapters on data visualization are very helpful for getting started in R plotting!"
},
{
"code": null,
"e": 24346,
"s": 24136,
"text": "If you have made it this far, good for you! I hope this was helpful and if you have any questions, I would recommend reaching out on Twitter via the #rstats hashtag, or you can find me @thomas_mock on twitter."
}
] |
Find n-variables from n sum equations with one missing - GeeksforGeeks
|
29 Apr, 2021
You are given an array a[] of n values as a[1], a[2]...a[n] which are part of n-equations in n-variables where equations are as: Eqn1 => X2 + X3 +.....+Xn = a1 Eqn2 => X1 + X3 +.....+Xn = a2 Eqni => X1 + X2 +...+Xi-1 + Xi+1..+Xn = ai Eqnn => X1 + X2 +.....+Xn-1 = anAs you have n-equations in n-variables find the value of all variables(X1, X2...Xn).Examples :
Input : a[] = {4, 4, 4, 4, 4}
Output : X1 = 1
X2 = 1
X3 = 1
X4 = 1
X5 = 1
Input : a[] = {2, 5, 6, 4, 8}
Output : X1 = 4.25
X2 = 1.25
X3 = 0.25
X4 = 2.25
X5 = -1.75
Approach: Let, X1+X2+X3+....Xn= SUM Using value SUM we have our equations as
SUM - X1 = a1 -----(1)
SUM - X2 = a2 -----(2)
SUM - Xi = ai -----(i)
SUM - Xn = an -------(n)
---------------------------------------------------------------
Now, if we add all these equation we will have an equation as :
n*SUM -(X1+X2+...Xn) = a1 + a2 + ...an
n*SUM - SUM = a1 + a2 + ...an
SUM = (a1+a2+...an)/(n-1)
Calculate SUM from above equation.
putting value of SUM in (i), (ii).... we have
X1 = SUM - a1
X2 = SUM - a2
Solution :
X1 = SUM - a1
X2 = SUM - a2
Xi = SUM - ai
Xn = SUM - an
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find n-variables#include <bits/stdc++.h>using namespace std; // function to print n-variable valuesvoid findVar(int a[], int n){ // calculate value of array SUM float SUM = 0; for (int i = 0; i < n; i++) SUM += a[i]; // Every variable contributes n-1 // times to sum. So dividing by // n-1 to get sum of all. SUM /= (n - 1); // print the values of n-variables for (int i = 0; i < n; i++) cout << "X" << (i + 1) << " = " << SUM - a[i] << endl;} // driver programint main(){ int a[] = { 2, 5, 6, 4, 8 }; int n = sizeof(a) / sizeof(a[0]); findVar(a, n); return 0;}
// Java program to// find n-variablesimport java.io.*; class GFG{ // function to print // n-variable values static void findVar(int []a, int n) { // calculate value+ // of array SUM float SUM = 0; for (int i = 0; i < n; i++) SUM += a[i]; // Every variable contributes // n-1 times to sum. So dividing // by n-1 to get sum of all. SUM /= (n - 1); // print the values // of n-variables for (int i = 0; i < n; i++) System.out.print("X" + (i + 1) + " = " + (SUM - a[i]) + "\n"); } // Driver Code public static void main(String args[]) { int []a = new int[]{2, 5, 6, 4, 8}; int n = a.length; findVar(a, n); }} // This code is contributed by// Manish Shaw(manishshaw1)
# Python3 program to# find n-variables # function to print# n-variable valuesdef findVar(a, n): # calculate value of # array SUM SUM = 0; for i in range(n): SUM += a[i]; # Every variable contributes # n-1 times to sum. So # dividing by n-1 to get sum # of all. SUM = SUM / (n - 1); # print the values # of n-variables for i in range(n): print("X" , (i + 1), " = ", SUM - a[i]); # Driver Codea = [2, 5, 6, 4, 8];n = len(a);findVar(a, n); # This code is contributed# by mits
// C# program to find n-variablesusing System;using System.Linq;using System.Collections.Generic; class GFG{ // function to print // n-variable values static void findVar(int []a, int n) { // calculate value+ // of array SUM float SUM = 0; for (int i = 0; i < n; i++) SUM += a[i]; // Every variable contributes // n-1 times to sum. So dividing // by n-1 to get sum of all. SUM /= (n - 1); // print the values // of n-variables for (int i = 0; i < n; i++) Console.Write("X" + (i + 1) + " = " + (SUM - a[i]) + "\n"); } // Driver Code static void Main() { int []a = { 2, 5, 6, 4, 8 }; int n = a.Length; findVar(a, n); }} // This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program to// find n-variables // function to print// n-variable valuesfunction findVar($a, $n){ // calculate value of // array SUM $SUM = 0; for ($i = 0; $i < $n; $i++) $SUM += $a[$i]; // Every variable contributes n-1 // times to sum. So dividing by // n-1 to get sum of all. $SUM /= ($n - 1); // print the values // of n-variables for ( $i = 0; $i < $n; $i++) echo "\nX" , ($i + 1) , " = " , $SUM - $a[$i];} // Driver Code $a = array(2, 5, 6, 4, 8); $n = count($a); findVar($a, $n); // This code is contributed by anuj_67.?>
<script> // function to print// n-variable valuesfunction findVar(a,n){ // calculate value+ // of array SUM let SUM = 0; for (let i = 0; i < n; i++) SUM += a[i]; // Every variable contributes // n-1 times to sum. So dividing // by n-1 to get sum of all. SUM /= (n - 1); // print the values // of n-variables for (let i = 0; i < n; i++) document.write("X" + (i + 1) + " = " + (SUM - a[i]) + "<br>");} let a = [2, 5, 6, 4, 8 ];let n = a.length;findVar(a, n); // This code is contributed by mohit kumar 29. </script>
X1 = 4.25
X2 = 1.25
X3 = 0.25
X4 = 2.25
X5 = -1.75
Time Complexity : O(n) Auxiliary Space : O(1)
vt_m
manishshaw1
Mithun Kumar
mohit kumar 29
Algebra
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 24768,
"s": 24405,
"text": "You are given an array a[] of n values as a[1], a[2]...a[n] which are part of n-equations in n-variables where equations are as: Eqn1 => X2 + X3 +.....+Xn = a1 Eqn2 => X1 + X3 +.....+Xn = a2 Eqni => X1 + X2 +...+Xi-1 + Xi+1..+Xn = ai Eqnn => X1 + X2 +.....+Xn-1 = anAs you have n-equations in n-variables find the value of all variables(X1, X2...Xn).Examples : "
},
{
"code": null,
"e": 25005,
"s": 24768,
"text": "Input : a[] = {4, 4, 4, 4, 4}\nOutput : X1 = 1\n X2 = 1\n X3 = 1\n X4 = 1\n X5 = 1\n\nInput : a[] = {2, 5, 6, 4, 8}\nOutput : X1 = 4.25\n X2 = 1.25\n X3 = 0.25\n X4 = 2.25\n X5 = -1.75"
},
{
"code": null,
"e": 25086,
"s": 25007,
"text": "Approach: Let, X1+X2+X3+....Xn= SUM Using value SUM we have our equations as "
},
{
"code": null,
"e": 25515,
"s": 25086,
"text": "SUM - X1 = a1 -----(1)\nSUM - X2 = a2 -----(2)\nSUM - Xi = ai -----(i)\nSUM - Xn = an -------(n)\n---------------------------------------------------------------\nNow, if we add all these equation we will have an equation as :\nn*SUM -(X1+X2+...Xn) = a1 + a2 + ...an\nn*SUM - SUM = a1 + a2 + ...an\nSUM = (a1+a2+...an)/(n-1)\n\nCalculate SUM from above equation.\nputting value of SUM in (i), (ii).... we have\nX1 = SUM - a1\nX2 = SUM - a2"
},
{
"code": null,
"e": 25528,
"s": 25515,
"text": "Solution : "
},
{
"code": null,
"e": 25584,
"s": 25528,
"text": "X1 = SUM - a1\nX2 = SUM - a2\nXi = SUM - ai\nXn = SUM - an"
},
{
"code": null,
"e": 25590,
"s": 25586,
"text": "C++"
},
{
"code": null,
"e": 25595,
"s": 25590,
"text": "Java"
},
{
"code": null,
"e": 25603,
"s": 25595,
"text": "Python3"
},
{
"code": null,
"e": 25606,
"s": 25603,
"text": "C#"
},
{
"code": null,
"e": 25610,
"s": 25606,
"text": "PHP"
},
{
"code": null,
"e": 25621,
"s": 25610,
"text": "Javascript"
},
{
"code": "// CPP program to find n-variables#include <bits/stdc++.h>using namespace std; // function to print n-variable valuesvoid findVar(int a[], int n){ // calculate value of array SUM float SUM = 0; for (int i = 0; i < n; i++) SUM += a[i]; // Every variable contributes n-1 // times to sum. So dividing by // n-1 to get sum of all. SUM /= (n - 1); // print the values of n-variables for (int i = 0; i < n; i++) cout << \"X\" << (i + 1) << \" = \" << SUM - a[i] << endl;} // driver programint main(){ int a[] = { 2, 5, 6, 4, 8 }; int n = sizeof(a) / sizeof(a[0]); findVar(a, n); return 0;}",
"e": 26271,
"s": 25621,
"text": null
},
{
"code": "// Java program to// find n-variablesimport java.io.*; class GFG{ // function to print // n-variable values static void findVar(int []a, int n) { // calculate value+ // of array SUM float SUM = 0; for (int i = 0; i < n; i++) SUM += a[i]; // Every variable contributes // n-1 times to sum. So dividing // by n-1 to get sum of all. SUM /= (n - 1); // print the values // of n-variables for (int i = 0; i < n; i++) System.out.print(\"X\" + (i + 1) + \" = \" + (SUM - a[i]) + \"\\n\"); } // Driver Code public static void main(String args[]) { int []a = new int[]{2, 5, 6, 4, 8}; int n = a.length; findVar(a, n); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 27175,
"s": 26271,
"text": null
},
{
"code": "# Python3 program to# find n-variables # function to print# n-variable valuesdef findVar(a, n): # calculate value of # array SUM SUM = 0; for i in range(n): SUM += a[i]; # Every variable contributes # n-1 times to sum. So # dividing by n-1 to get sum # of all. SUM = SUM / (n - 1); # print the values # of n-variables for i in range(n): print(\"X\" , (i + 1), \" = \", SUM - a[i]); # Driver Codea = [2, 5, 6, 4, 8];n = len(a);findVar(a, n); # This code is contributed# by mits",
"e": 27723,
"s": 27175,
"text": null
},
{
"code": "// C# program to find n-variablesusing System;using System.Linq;using System.Collections.Generic; class GFG{ // function to print // n-variable values static void findVar(int []a, int n) { // calculate value+ // of array SUM float SUM = 0; for (int i = 0; i < n; i++) SUM += a[i]; // Every variable contributes // n-1 times to sum. So dividing // by n-1 to get sum of all. SUM /= (n - 1); // print the values // of n-variables for (int i = 0; i < n; i++) Console.Write(\"X\" + (i + 1) + \" = \" + (SUM - a[i]) + \"\\n\"); } // Driver Code static void Main() { int []a = { 2, 5, 6, 4, 8 }; int n = a.Length; findVar(a, n); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 28602,
"s": 27723,
"text": null
},
{
"code": "<?php// PHP program to// find n-variables // function to print// n-variable valuesfunction findVar($a, $n){ // calculate value of // array SUM $SUM = 0; for ($i = 0; $i < $n; $i++) $SUM += $a[$i]; // Every variable contributes n-1 // times to sum. So dividing by // n-1 to get sum of all. $SUM /= ($n - 1); // print the values // of n-variables for ( $i = 0; $i < $n; $i++) echo \"\\nX\" , ($i + 1) , \" = \" , $SUM - $a[$i];} // Driver Code $a = array(2, 5, 6, 4, 8); $n = count($a); findVar($a, $n); // This code is contributed by anuj_67.?>",
"e": 29223,
"s": 28602,
"text": null
},
{
"code": "<script> // function to print// n-variable valuesfunction findVar(a,n){ // calculate value+ // of array SUM let SUM = 0; for (let i = 0; i < n; i++) SUM += a[i]; // Every variable contributes // n-1 times to sum. So dividing // by n-1 to get sum of all. SUM /= (n - 1); // print the values // of n-variables for (let i = 0; i < n; i++) document.write(\"X\" + (i + 1) + \" = \" + (SUM - a[i]) + \"<br>\");} let a = [2, 5, 6, 4, 8 ];let n = a.length;findVar(a, n); // This code is contributed by mohit kumar 29. </script>",
"e": 29792,
"s": 29223,
"text": null
},
{
"code": null,
"e": 29843,
"s": 29792,
"text": "X1 = 4.25\nX2 = 1.25\nX3 = 0.25\nX4 = 2.25\nX5 = -1.75"
},
{
"code": null,
"e": 29892,
"s": 29845,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 29897,
"s": 29892,
"text": "vt_m"
},
{
"code": null,
"e": 29909,
"s": 29897,
"text": "manishshaw1"
},
{
"code": null,
"e": 29922,
"s": 29909,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29937,
"s": 29922,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29945,
"s": 29937,
"text": "Algebra"
},
{
"code": null,
"e": 29952,
"s": 29945,
"text": "Arrays"
},
{
"code": null,
"e": 29965,
"s": 29952,
"text": "Mathematical"
},
{
"code": null,
"e": 29972,
"s": 29965,
"text": "Arrays"
},
{
"code": null,
"e": 29985,
"s": 29972,
"text": "Mathematical"
},
{
"code": null,
"e": 30083,
"s": 29985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30092,
"s": 30083,
"text": "Comments"
},
{
"code": null,
"e": 30105,
"s": 30092,
"text": "Old Comments"
},
{
"code": null,
"e": 30126,
"s": 30105,
"text": "Next Greater Element"
},
{
"code": null,
"e": 30151,
"s": 30126,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30178,
"s": 30151,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 30227,
"s": 30178,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30265,
"s": 30227,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30295,
"s": 30265,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30310,
"s": 30295,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30370,
"s": 30310,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30413,
"s": 30370,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to programmatically turn off and turn on WiFi in Kotlin?
|
This example demonstrates programmatically turning off and turning on WiFi in 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="enableWifi"
android:text="Wifi On!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_centerInParent="true"
android:onClick="disableWifi"
android:text="Wifi Off!" />
</RelativeLayout>
Step 3 − Add the following code to MainActivity.kt
import android.net.wifi.WifiManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var wifiManager: WifiManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
fun enableWifi(view: View) {
wifiManager.isWifiEnabled = true
Toast.makeText(this, "Wifi enabled", Toast.LENGTH_SHORT).show()
}
fun disableWifi(view: View) {
wifiManager.isWifiEnabled = false
Toast.makeText(this, "Wifi disabled", Toast.LENGTH_SHORT).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="app.com.q36">
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<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 −
Click here to download the project code.
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates programmatically turning off and turning on WiFi in Kotlin."
},
{
"code": null,
"e": 1277,
"s": 1148,
"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": 1342,
"s": 1277,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2500,
"s": 1342,
"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:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"enableWifi\"\n android:text=\"Wifi On!\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/button\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"disableWifi\"\n android:text=\"Wifi Off!\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2551,
"s": 2500,
"text": "Step 3 − Add the following code to MainActivity.kt"
},
{
"code": null,
"e": 3267,
"s": 2551,
"text": "import android.net.wifi.WifiManager\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.Toast\nclass MainActivity : AppCompatActivity() {\n lateinit var wifiManager: WifiManager\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n fun enableWifi(view: View) {\n wifiManager.isWifiEnabled = true\n Toast.makeText(this, \"Wifi enabled\", Toast.LENGTH_SHORT).show()\n }\n fun disableWifi(view: View) {\n wifiManager.isWifiEnabled = false\n Toast.makeText(this, \"Wifi disabled\", Toast.LENGTH_SHORT).show()\n }\n}"
},
{
"code": null,
"e": 3322,
"s": 3267,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4064,
"s": 3322,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.q36\">\n<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\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": 4415,
"s": 4064,
"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 −"
},
{
"code": null,
"e": 4456,
"s": 4415,
"text": "Click here to download the project code."
}
] |
Tryit Editor v3.7
|
Tryit: HTML link titles
|
[] |
Tk - Message Widget
|
A message widget is used for displaying multiple lines of text. The syntax for message widget is shown below −
message messageName options
The options available for the message widget are listed below in the following table −
-background color
Used to set background color for widget.
-borderwidth width
Used to draw with border in 3D effects.
-font fontDescriptor
Used to set font for widget.
-foreground color
Used to set foreground color for widget.
-padx number
Sets the padx for the widget.
-pady number
Sets the pady for the widget.
-relief condition
Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove.
-text text
Sets the text for the widget.
-textvariable varName
Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.
-justify alignment
Sets the alignment of text, which can be left, center, or right.
-aspect ratio
Sets the aspect ratio in percent. The default is 150. It is available when width option is not used.
-width number
Sets the width for widget.
A simple example for message widget is shown below −
#!/usr/bin/wish
grid [message .myMessage -background red -foreground white -text "Hello\nWorld" -relief
ridge -borderwidth 8 -padx 10 -pady 10 -font {Helvetica -18 bold} -textvariable
myvariable -justify right -aspect 100 ]
When we run the above program, we will get the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2312,
"s": 2201,
"text": "A message widget is used for displaying multiple lines of text. The syntax for message widget is shown below −"
},
{
"code": null,
"e": 2341,
"s": 2312,
"text": "message messageName options\n"
},
{
"code": null,
"e": 2428,
"s": 2341,
"text": "The options available for the message widget are listed below in the following table −"
},
{
"code": null,
"e": 2446,
"s": 2428,
"text": "-background color"
},
{
"code": null,
"e": 2487,
"s": 2446,
"text": "Used to set background color for widget."
},
{
"code": null,
"e": 2506,
"s": 2487,
"text": "-borderwidth width"
},
{
"code": null,
"e": 2546,
"s": 2506,
"text": "Used to draw with border in 3D effects."
},
{
"code": null,
"e": 2567,
"s": 2546,
"text": "-font fontDescriptor"
},
{
"code": null,
"e": 2596,
"s": 2567,
"text": "Used to set font for widget."
},
{
"code": null,
"e": 2614,
"s": 2596,
"text": "-foreground color"
},
{
"code": null,
"e": 2655,
"s": 2614,
"text": "Used to set foreground color for widget."
},
{
"code": null,
"e": 2668,
"s": 2655,
"text": "-padx number"
},
{
"code": null,
"e": 2698,
"s": 2668,
"text": "Sets the padx for the widget."
},
{
"code": null,
"e": 2711,
"s": 2698,
"text": "-pady number"
},
{
"code": null,
"e": 2741,
"s": 2711,
"text": "Sets the pady for the widget."
},
{
"code": null,
"e": 2759,
"s": 2741,
"text": "-relief condition"
},
{
"code": null,
"e": 2863,
"s": 2759,
"text": "Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove."
},
{
"code": null,
"e": 2874,
"s": 2863,
"text": "-text text"
},
{
"code": null,
"e": 2904,
"s": 2874,
"text": "Sets the text for the widget."
},
{
"code": null,
"e": 2926,
"s": 2904,
"text": "-textvariable varName"
},
{
"code": null,
"e": 3035,
"s": 2926,
"text": "Variable associated with the widget. When the text of widget changes, the variable is set to text of widget."
},
{
"code": null,
"e": 3054,
"s": 3035,
"text": "-justify alignment"
},
{
"code": null,
"e": 3119,
"s": 3054,
"text": "Sets the alignment of text, which can be left, center, or right."
},
{
"code": null,
"e": 3133,
"s": 3119,
"text": "-aspect ratio"
},
{
"code": null,
"e": 3234,
"s": 3133,
"text": "Sets the aspect ratio in percent. The default is 150. It is available when width option is not used."
},
{
"code": null,
"e": 3248,
"s": 3234,
"text": "-width number"
},
{
"code": null,
"e": 3275,
"s": 3248,
"text": "Sets the width for widget."
},
{
"code": null,
"e": 3328,
"s": 3275,
"text": "A simple example for message widget is shown below −"
},
{
"code": null,
"e": 3559,
"s": 3328,
"text": "#!/usr/bin/wish\n\ngrid [message .myMessage -background red -foreground white -text \"Hello\\nWorld\" -relief\n ridge -borderwidth 8 -padx 10 -pady 10 -font {Helvetica -18 bold} -textvariable\n myvariable -justify right -aspect 100 ]"
},
{
"code": null,
"e": 3625,
"s": 3559,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 3632,
"s": 3625,
"text": " Print"
},
{
"code": null,
"e": 3643,
"s": 3632,
"text": " Add Notes"
}
] |
node2vec: Embeddings for Graph Data | by Elior Cohen | Towards Data Science
|
Hotlinks:Original article: node2vec: Scalable Feature Learning for Networks, Aditya Grover and Jure LeskovecAlgorithm implementation — By me: Github repo — Python3Algorithm implementation — By the algo author: Github repo (by Aditya Grover) — Python2Showcase code: https://github.com/eliorc/Medium/blob/master/Nod2Vec-FIFA17-Example.ipynb
Embeddings... A word that every data scientist has heard by now, but mostly in the context of NLP. So why do we even bother embedding stuff?As I see it, creating quality embeddings and feeding it into models, is the exact opposite of the famous say “Garbage in, garbage out” .When you feed low quality data into your models, you put the entire load of learning on your model, as it will have to learn all the necessary conclusions that could be derived from the data.On the contrary, when you use quality embeddings, you already put some knowledge in your data and thus make the task of learning the problem easier for your models.Another point to think about is information vs domain knowledge.For example, let’s consider word embeddings (word2vec) and bag of words representations.While both of them can have the entire information about which words are in a sentence, word embeddings also include domain knowledge like relationship between words and such.In this post, I’m going to talk about a technique called node2vec which aims to create embeddings for nodes in a graph (in the G(V, E, W) sense of the word).
I will explain how it works and finally supply my own implementation for Python 3, with some extras.
So how is done?The embedding themselves, are learnt in the same way as word2vec’s embeddings are learnt — using a skip-gram model.If you are familiar with the word2vec skip-gram model, great, if not I recommend this great post which explains it in great detail as from this point forward I assume you are familiar with it.
The most natural way I can think about explaining node2vec is to explain how node2vec generates a “corpus” — and if we understand word2vec we already know how to embed a corpus.
So how do we generate this corpus from a graph? That’s exactly the innovative part of node2vec and it does so in an intelligent way which is done using the sampling strategy.
In order to generate our corpus from the input graph, let’s think about a corpus as a group of directed acyclic graphs, with a maximum out degree of 1. If we think about it this is a perfect representation for a text sentence, where each word in the sentence is a node and it points on the next word in the sentence.
In this way, we can see that word2vec can already embed graphs, but a very specific type of them.Most graphs though, aren’t that simple, they can be (un)directed, (un)weighted, (a)cyclic and are basically much more complex in structure than text.
In order to solve that, node2vec uses a tweakable (by hyperparameters) sampling strategy, to sample these directed acyclic subgraphs. This is done by generating random walks from each node of the graph. Quite simple right?
Before we delve how the sampling strategy uses the hyperparameters to generate these sub graphs, lets visualize the process:
By now we get the big picture and it’s time to dig deeper.Node2vec’s sampling strategy, accepts 4 arguments: — Number of walks: Number of random walks to be generated from each node in the graph — Walk length: How many nodes are in each random walk — P: Return hyperparameter — Q: Inout hyperaprameterand also the standard skip-gram parameters (context window size, number of iterations etc.)
The first two hyperparameters are pretty self explanatory.The algorithm for the random walk generation will go over each node in the graph and will generate <number of walks> random walks, of length <walk length>.Q and P, are better explained with a visualization.Consider you are on the random walk, and have just transitioned from node <t> to node <v> in the following diagram (taken from the article).
The probability to transition from <v> to any one of his neighbors is <edge weight>*<α> (normalized), where <α> is depended on the hyperparameters.P controls the probability to go back to <t> after visiting <v>.Q controls the probability to go explore undiscovered parts of the graphs.In a intuitive way, this is somewhat like the perplexity parameter in tSNE, it allows you to emphasize the local/global structure of the graph.Do not forget that the weight is also taken into consideration, so the final travel probability is a function of: 1. The previous node in the walk 2. P and Q 3. Edge weight
This part is important to understand as it is the essence of node2vec. If you did not fully comprehend the idea behind the sampling strategy I strongly advise you to read this part again.
Using the sampling strategy, node2vec will generate “sentences” (the directed subgraphs) which are will be used for embedding just like text sentences are used in word2vec. Why change something if it works right?
Now its time to put node2vec into action.You can find the entire code for this node2vec test drive here.I am using for the example my implementation of the node2vec algorithm, which adds support for assigning node specific parameters (q, p, num_walks and walk length).
What we are going to do, using formation of European football teams, is to embed the teams, players and positions of 7 different clubs.The data I’m going to be using is taken from the FIFA 17 dataset on Kaggle.In FIFA (by EASports) each team can be represented as a graph, see picture below.
As we can see, each position is connected to other positions and when playing each position is assigned a player.There dozens of different formations, and the connectivity between them differs. Also there are type of positions that are in some formations but are non existent in others, for example the ‘LM’ position is not existent in this formation but is in others.
This is how we are going to do this:1. Nodes will be players, team names and positions2. For each team, create a separate graph where each player node is connected to his team name node, connected to his teammates nodes and connected to his teammate position nodes.3. Apply node2vec to the resulting graphs
*Notice: In order to create separate nodes for each position inside and between teams, I added suffixes to similar nodes and after the walk generation I have removed them. This is a technicality, inspect code in repo for better understanding
First rows of the input data looks like this (after some permutations):
Then we construct the graph, using the FIFA17 formations.Using my node2vec package the graph must be an instance of networkx.Graph.Inspecting the graph edges after this, we will get the following
for edge in graph.edges: print(edge)>>> ('james_rodriguez', 'real_madrid')>>> ('james_rodriguez', 'cm_1_real_madrid')>>> ('james_rodriguez', 'toni_kroos')>>> ('james_rodriguez', 'cm_2_real_madrid')>>> ('james_rodriguez', 'luka_modric')>>> ('lw_real_madrid', 'cm_1_real_madrid')>>> ('lw_real_madrid', 'lb_real_madrid')>>> ('lw_real_madrid', 'toni_kroos')>>> ('lw_real_madrid', 'marcelo')...
As we can see, each player is connected to his team, the positions and teammates according to the formation.All of the suffixes attached to the positions will be returned to their original string after the walks are computed ( lw_real_madrid→ lw).
So now that we have the graph, we execute node2vec
# pip install node2vecfrom node2vec import Node2Vec# Generate walksnode2vec = Node2Vec(graph, dimensions=20, walk_length=16, num_walks=100)# Reformat position nodesfix_formatted_positions = lambda x: x.split('_')[0] if x in formatted_positions else xreformatted_walks = [list(map(fix_formatted_positions, walk)) for walk in node2vec.walks]node2vec.walks = reformatted_walks# Learn embeddings model = node2vec.fit(window=10, min_count=1)
We give node2vec.Node2Vec a networkx.Graph instance, and after using .fit() (which accepts any parameter accepted by we get a gensim.models.Word2Vec) we get in return a gensim.models.Word2Vec instance.
First we will inspect the similarity between different nodes.We expect the most similar nodes to a team, would be its teammates:
for node, _ in model.most_similar('real_madrid'): print(node)>>> james_rodriguez>>> luka_modric>>> marcelo>>> karim_benzema>>> cristiano_ronaldo>>> pepe>>> gareth_bale>>> sergio_ramos>>> carvajal>>> toni_kroos
For those who are not familiar with European football, these are all indeed Real Madrid’s players!
Next, we inspect similarities to a specific position. We would expect to get players playing in that position or near it at worse
# Right Wingersfor node, _ in model.most_similar('rw'): # Show only players if len(node) > 3: print(node)>>> pedro>>> jose_callejon>>> raheem_sterling>>> henrikh_mkhitaryan>>> gareth_bale>>> dries_mertens# Goal keepersfor node, _ in model.most_similar('gk'): # Show only players if len(node) > 3: print(node)>>> thibaut_courtois>>> gianluigi_buffon>>> keylor_navas>>> azpilicueta>>> manuel_neuer
In the first try (right wingers) we indeed get different right wingers from different clubs, again a perfect match.In the second try though, we get all goalkeepers except Azpilicueta which is actually a defender — this could be due to the fact that goalkeepers are not very connected to the team, only to central backs usually.
Works pretty good right? Just before we finish, lets use tSNE to reduce dimensionality and visualize the player nodes.
Check it out, we get beautiful clusters based on the different clubs.
Graph data is almost everywhere, and where its not you can usually put it on a graph yet the node2vec algorithm is not so popular.The algorithm also grants great flexibility with its hyperparameters so you can decide which kind of information you wish to embed, and if you have the the option to construct the graph yourself (and is not a given) your options are limitless.Hopefully you will find use in this article and have added a new tool to your machine learning arsenal.
If someone wants to contribute to my node2vec implementation, please contact me.
|
[
{
"code": null,
"e": 511,
"s": 172,
"text": "Hotlinks:Original article: node2vec: Scalable Feature Learning for Networks, Aditya Grover and Jure LeskovecAlgorithm implementation — By me: Github repo — Python3Algorithm implementation — By the algo author: Github repo (by Aditya Grover) — Python2Showcase code: https://github.com/eliorc/Medium/blob/master/Nod2Vec-FIFA17-Example.ipynb"
},
{
"code": null,
"e": 1627,
"s": 511,
"text": "Embeddings... A word that every data scientist has heard by now, but mostly in the context of NLP. So why do we even bother embedding stuff?As I see it, creating quality embeddings and feeding it into models, is the exact opposite of the famous say “Garbage in, garbage out” .When you feed low quality data into your models, you put the entire load of learning on your model, as it will have to learn all the necessary conclusions that could be derived from the data.On the contrary, when you use quality embeddings, you already put some knowledge in your data and thus make the task of learning the problem easier for your models.Another point to think about is information vs domain knowledge.For example, let’s consider word embeddings (word2vec) and bag of words representations.While both of them can have the entire information about which words are in a sentence, word embeddings also include domain knowledge like relationship between words and such.In this post, I’m going to talk about a technique called node2vec which aims to create embeddings for nodes in a graph (in the G(V, E, W) sense of the word)."
},
{
"code": null,
"e": 1728,
"s": 1627,
"text": "I will explain how it works and finally supply my own implementation for Python 3, with some extras."
},
{
"code": null,
"e": 2051,
"s": 1728,
"text": "So how is done?The embedding themselves, are learnt in the same way as word2vec’s embeddings are learnt — using a skip-gram model.If you are familiar with the word2vec skip-gram model, great, if not I recommend this great post which explains it in great detail as from this point forward I assume you are familiar with it."
},
{
"code": null,
"e": 2229,
"s": 2051,
"text": "The most natural way I can think about explaining node2vec is to explain how node2vec generates a “corpus” — and if we understand word2vec we already know how to embed a corpus."
},
{
"code": null,
"e": 2404,
"s": 2229,
"text": "So how do we generate this corpus from a graph? That’s exactly the innovative part of node2vec and it does so in an intelligent way which is done using the sampling strategy."
},
{
"code": null,
"e": 2721,
"s": 2404,
"text": "In order to generate our corpus from the input graph, let’s think about a corpus as a group of directed acyclic graphs, with a maximum out degree of 1. If we think about it this is a perfect representation for a text sentence, where each word in the sentence is a node and it points on the next word in the sentence."
},
{
"code": null,
"e": 2968,
"s": 2721,
"text": "In this way, we can see that word2vec can already embed graphs, but a very specific type of them.Most graphs though, aren’t that simple, they can be (un)directed, (un)weighted, (a)cyclic and are basically much more complex in structure than text."
},
{
"code": null,
"e": 3191,
"s": 2968,
"text": "In order to solve that, node2vec uses a tweakable (by hyperparameters) sampling strategy, to sample these directed acyclic subgraphs. This is done by generating random walks from each node of the graph. Quite simple right?"
},
{
"code": null,
"e": 3316,
"s": 3191,
"text": "Before we delve how the sampling strategy uses the hyperparameters to generate these sub graphs, lets visualize the process:"
},
{
"code": null,
"e": 3709,
"s": 3316,
"text": "By now we get the big picture and it’s time to dig deeper.Node2vec’s sampling strategy, accepts 4 arguments: — Number of walks: Number of random walks to be generated from each node in the graph — Walk length: How many nodes are in each random walk — P: Return hyperparameter — Q: Inout hyperaprameterand also the standard skip-gram parameters (context window size, number of iterations etc.)"
},
{
"code": null,
"e": 4114,
"s": 3709,
"text": "The first two hyperparameters are pretty self explanatory.The algorithm for the random walk generation will go over each node in the graph and will generate <number of walks> random walks, of length <walk length>.Q and P, are better explained with a visualization.Consider you are on the random walk, and have just transitioned from node <t> to node <v> in the following diagram (taken from the article)."
},
{
"code": null,
"e": 4717,
"s": 4114,
"text": "The probability to transition from <v> to any one of his neighbors is <edge weight>*<α> (normalized), where <α> is depended on the hyperparameters.P controls the probability to go back to <t> after visiting <v>.Q controls the probability to go explore undiscovered parts of the graphs.In a intuitive way, this is somewhat like the perplexity parameter in tSNE, it allows you to emphasize the local/global structure of the graph.Do not forget that the weight is also taken into consideration, so the final travel probability is a function of: 1. The previous node in the walk 2. P and Q 3. Edge weight"
},
{
"code": null,
"e": 4905,
"s": 4717,
"text": "This part is important to understand as it is the essence of node2vec. If you did not fully comprehend the idea behind the sampling strategy I strongly advise you to read this part again."
},
{
"code": null,
"e": 5118,
"s": 4905,
"text": "Using the sampling strategy, node2vec will generate “sentences” (the directed subgraphs) which are will be used for embedding just like text sentences are used in word2vec. Why change something if it works right?"
},
{
"code": null,
"e": 5387,
"s": 5118,
"text": "Now its time to put node2vec into action.You can find the entire code for this node2vec test drive here.I am using for the example my implementation of the node2vec algorithm, which adds support for assigning node specific parameters (q, p, num_walks and walk length)."
},
{
"code": null,
"e": 5679,
"s": 5387,
"text": "What we are going to do, using formation of European football teams, is to embed the teams, players and positions of 7 different clubs.The data I’m going to be using is taken from the FIFA 17 dataset on Kaggle.In FIFA (by EASports) each team can be represented as a graph, see picture below."
},
{
"code": null,
"e": 6048,
"s": 5679,
"text": "As we can see, each position is connected to other positions and when playing each position is assigned a player.There dozens of different formations, and the connectivity between them differs. Also there are type of positions that are in some formations but are non existent in others, for example the ‘LM’ position is not existent in this formation but is in others."
},
{
"code": null,
"e": 6355,
"s": 6048,
"text": "This is how we are going to do this:1. Nodes will be players, team names and positions2. For each team, create a separate graph where each player node is connected to his team name node, connected to his teammates nodes and connected to his teammate position nodes.3. Apply node2vec to the resulting graphs"
},
{
"code": null,
"e": 6597,
"s": 6355,
"text": "*Notice: In order to create separate nodes for each position inside and between teams, I added suffixes to similar nodes and after the walk generation I have removed them. This is a technicality, inspect code in repo for better understanding"
},
{
"code": null,
"e": 6669,
"s": 6597,
"text": "First rows of the input data looks like this (after some permutations):"
},
{
"code": null,
"e": 6865,
"s": 6669,
"text": "Then we construct the graph, using the FIFA17 formations.Using my node2vec package the graph must be an instance of networkx.Graph.Inspecting the graph edges after this, we will get the following"
},
{
"code": null,
"e": 7258,
"s": 6865,
"text": "for edge in graph.edges: print(edge)>>> ('james_rodriguez', 'real_madrid')>>> ('james_rodriguez', 'cm_1_real_madrid')>>> ('james_rodriguez', 'toni_kroos')>>> ('james_rodriguez', 'cm_2_real_madrid')>>> ('james_rodriguez', 'luka_modric')>>> ('lw_real_madrid', 'cm_1_real_madrid')>>> ('lw_real_madrid', 'lb_real_madrid')>>> ('lw_real_madrid', 'toni_kroos')>>> ('lw_real_madrid', 'marcelo')..."
},
{
"code": null,
"e": 7506,
"s": 7258,
"text": "As we can see, each player is connected to his team, the positions and teammates according to the formation.All of the suffixes attached to the positions will be returned to their original string after the walks are computed ( lw_real_madrid→ lw)."
},
{
"code": null,
"e": 7557,
"s": 7506,
"text": "So now that we have the graph, we execute node2vec"
},
{
"code": null,
"e": 7994,
"s": 7557,
"text": "# pip install node2vecfrom node2vec import Node2Vec# Generate walksnode2vec = Node2Vec(graph, dimensions=20, walk_length=16, num_walks=100)# Reformat position nodesfix_formatted_positions = lambda x: x.split('_')[0] if x in formatted_positions else xreformatted_walks = [list(map(fix_formatted_positions, walk)) for walk in node2vec.walks]node2vec.walks = reformatted_walks# Learn embeddings model = node2vec.fit(window=10, min_count=1)"
},
{
"code": null,
"e": 8196,
"s": 7994,
"text": "We give node2vec.Node2Vec a networkx.Graph instance, and after using .fit() (which accepts any parameter accepted by we get a gensim.models.Word2Vec) we get in return a gensim.models.Word2Vec instance."
},
{
"code": null,
"e": 8325,
"s": 8196,
"text": "First we will inspect the similarity between different nodes.We expect the most similar nodes to a team, would be its teammates:"
},
{
"code": null,
"e": 8538,
"s": 8325,
"text": "for node, _ in model.most_similar('real_madrid'): print(node)>>> james_rodriguez>>> luka_modric>>> marcelo>>> karim_benzema>>> cristiano_ronaldo>>> pepe>>> gareth_bale>>> sergio_ramos>>> carvajal>>> toni_kroos"
},
{
"code": null,
"e": 8637,
"s": 8538,
"text": "For those who are not familiar with European football, these are all indeed Real Madrid’s players!"
},
{
"code": null,
"e": 8767,
"s": 8637,
"text": "Next, we inspect similarities to a specific position. We would expect to get players playing in that position or near it at worse"
},
{
"code": null,
"e": 9189,
"s": 8767,
"text": "# Right Wingersfor node, _ in model.most_similar('rw'): # Show only players if len(node) > 3: print(node)>>> pedro>>> jose_callejon>>> raheem_sterling>>> henrikh_mkhitaryan>>> gareth_bale>>> dries_mertens# Goal keepersfor node, _ in model.most_similar('gk'): # Show only players if len(node) > 3: print(node)>>> thibaut_courtois>>> gianluigi_buffon>>> keylor_navas>>> azpilicueta>>> manuel_neuer"
},
{
"code": null,
"e": 9517,
"s": 9189,
"text": "In the first try (right wingers) we indeed get different right wingers from different clubs, again a perfect match.In the second try though, we get all goalkeepers except Azpilicueta which is actually a defender — this could be due to the fact that goalkeepers are not very connected to the team, only to central backs usually."
},
{
"code": null,
"e": 9636,
"s": 9517,
"text": "Works pretty good right? Just before we finish, lets use tSNE to reduce dimensionality and visualize the player nodes."
},
{
"code": null,
"e": 9706,
"s": 9636,
"text": "Check it out, we get beautiful clusters based on the different clubs."
},
{
"code": null,
"e": 10183,
"s": 9706,
"text": "Graph data is almost everywhere, and where its not you can usually put it on a graph yet the node2vec algorithm is not so popular.The algorithm also grants great flexibility with its hyperparameters so you can decide which kind of information you wish to embed, and if you have the the option to construct the graph yourself (and is not a given) your options are limitless.Hopefully you will find use in this article and have added a new tool to your machine learning arsenal."
}
] |
Laravel - Event Handling
|
Events provide a simple observer implementation which allows a user to subscribe and listen to various events triggered in the web application. All the event classes in Laravel are stored in the app/Events folder and the listeners are stored in the app/Listeners folder.
The artisan command for generating events and listeners in your web application is shown below −
php artisan event:generate
This command generates the events and listeners to the respective folders as discussed above.
Events and Listeners serve a great way to decouple a web application, since one event can have multiple listeners which are independent of each other. The events folder created by the artisan command includes the following two files: event.php and SomeEvent.php. They are shown here −
<?php
namespace App\Events;
abstract class Event{
//
}
As mentioned above, event.php includes the basic definition of class Event and calls for namespace App\Events. Please note that the user defined or custom events are created in this file.
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class SomeEvent extends Event{
use SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct() {
//
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn() {
return [];
}
}
Observe that this file uses serialization for broadcasting events in a web application and that the necessary parameters are also initialized in this file.
For example, if we need to initialize order variable in the constructor for registering an event, we can do it in the following way −
public function __construct(Order $order) {
$this->order = $order;
}
Listeners handle all the activities mentioned in an event that is being registered. The artisan command event:generate creates all the listeners in the app/listeners directory. The Listeners folder includes a file EventListener.php which has all the methods required for handling listeners.
<?php
namespace App\Listeners;
use App\Events\SomeEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class EventListener{
/**
* Create the event listener.
*
* @return void
*/
public function __construct() {
//
}
/**
* Handle the event.
*
* @param SomeEvent $event
* @return void
*/
public function handle(SomeEvent $event) {
//
}
}
As mentioned in the code, it includes handle function for managing various events. We can create various independent listeners that target a single event.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2743,
"s": 2472,
"text": "Events provide a simple observer implementation which allows a user to subscribe and listen to various events triggered in the web application. All the event classes in Laravel are stored in the app/Events folder and the listeners are stored in the app/Listeners folder."
},
{
"code": null,
"e": 2840,
"s": 2743,
"text": "The artisan command for generating events and listeners in your web application is shown below −"
},
{
"code": null,
"e": 2868,
"s": 2840,
"text": "php artisan event:generate\n"
},
{
"code": null,
"e": 2962,
"s": 2868,
"text": "This command generates the events and listeners to the respective folders as discussed above."
},
{
"code": null,
"e": 3247,
"s": 2962,
"text": "Events and Listeners serve a great way to decouple a web application, since one event can have multiple listeners which are independent of each other. The events folder created by the artisan command includes the following two files: event.php and SomeEvent.php. They are shown here −"
},
{
"code": null,
"e": 3305,
"s": 3247,
"text": "<?php\nnamespace App\\Events;\nabstract class Event{\n //\n}"
},
{
"code": null,
"e": 3493,
"s": 3305,
"text": "As mentioned above, event.php includes the basic definition of class Event and calls for namespace App\\Events. Please note that the user defined or custom events are created in this file."
},
{
"code": null,
"e": 3997,
"s": 3493,
"text": "<?php\n\nnamespace App\\Events;\n\nuse App\\Events\\Event;\nuse Illuminate\\Queue\\SerializesModels;\nuse Illuminate\\Contracts\\Broadcasting\\ShouldBroadcast;\n\nclass SomeEvent extends Event{\n use SerializesModels;\n /**\n * Create a new event instance.\n *\n * @return void\n */\n \n public function __construct() {\n //\n }\n \n /**\n * Get the channels the event should be broadcast on.\n *\n * @return array\n */\n \n public function broadcastOn() {\n return [];\n }\n}"
},
{
"code": null,
"e": 4153,
"s": 3997,
"text": "Observe that this file uses serialization for broadcasting events in a web application and that the necessary parameters are also initialized in this file."
},
{
"code": null,
"e": 4287,
"s": 4153,
"text": "For example, if we need to initialize order variable in the constructor for registering an event, we can do it in the following way −"
},
{
"code": null,
"e": 4359,
"s": 4287,
"text": "public function __construct(Order $order) {\n $this->order = $order;\n}"
},
{
"code": null,
"e": 4650,
"s": 4359,
"text": "Listeners handle all the activities mentioned in an event that is being registered. The artisan command event:generate creates all the listeners in the app/listeners directory. The Listeners folder includes a file EventListener.php which has all the methods required for handling listeners."
},
{
"code": null,
"e": 5113,
"s": 4650,
"text": "<?php\n\nnamespace App\\Listeners;\n\nuse App\\Events\\SomeEvent;\nuse Illuminate\\Queue\\InteractsWithQueue;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\n\nclass EventListener{\n /**\n * Create the event listener.\n *\n * @return void\n */\n \n public function __construct() {\n //\n }\n\n /**\n * Handle the event.\n *\n * @param SomeEvent $event\n * @return void\n */\n \n public function handle(SomeEvent $event) {\n //\n }\n}"
},
{
"code": null,
"e": 5268,
"s": 5113,
"text": "As mentioned in the code, it includes handle function for managing various events. We can create various independent listeners that target a single event."
},
{
"code": null,
"e": 5301,
"s": 5268,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5321,
"s": 5301,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 5356,
"s": 5321,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5370,
"s": 5356,
"text": " Antonio Papa"
},
{
"code": null,
"e": 5404,
"s": 5370,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5424,
"s": 5404,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 5457,
"s": 5424,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5477,
"s": 5457,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5512,
"s": 5477,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5535,
"s": 5512,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 5570,
"s": 5535,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5590,
"s": 5570,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 5597,
"s": 5590,
"text": " Print"
},
{
"code": null,
"e": 5608,
"s": 5597,
"text": " Add Notes"
}
] |
PHP - Function popen()
|
The popen() function can open a pipe to the program specified in the command parameter, and return false if an error occurs.
resource popen ( string $command , string $mode )
This function can open a pipe to the process executed by forking the command given by command.
<?php
$handle = popen("/bin/ls", "r");
?>
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2884,
"s": 2757,
"text": " The popen() function can open a pipe to the program specified in the command parameter, and return false if an error occurs. "
},
{
"code": null,
"e": 2935,
"s": 2884,
"text": "resource popen ( string $command , string $mode )\n"
},
{
"code": null,
"e": 3032,
"s": 2935,
"text": " This function can open a pipe to the process executed by forking the command given by command. "
},
{
"code": null,
"e": 3077,
"s": 3032,
"text": "<?php\n $handle = popen(\"/bin/ls\", \"r\");\n?>"
},
{
"code": null,
"e": 3110,
"s": 3077,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3126,
"s": 3110,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3159,
"s": 3126,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3170,
"s": 3159,
"text": " Syed Raza"
},
{
"code": null,
"e": 3205,
"s": 3170,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3205,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3255,
"s": 3222,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3270,
"s": 3255,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3305,
"s": 3270,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3317,
"s": 3305,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3352,
"s": 3317,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3380,
"s": 3352,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3387,
"s": 3380,
"text": " Print"
},
{
"code": null,
"e": 3398,
"s": 3387,
"text": " Add Notes"
}
] |
Navigating links using get method - Selenium Python - GeeksforGeeks
|
10 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python to navigate to any link on web using get method of Selenium Webdriver in python.
If you have not installed Selenium and its components yet, install them from here – Selenium Python Introduction and Installation.
The first thing one’ll want to do with WebDriver is navigate to a link. The normal way to do this is by calling get method:Syntax –
driver.get(url)
Example-
driver.get("http://www.google.com")
WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.
Project Example –After you have installed Selenium, create a file called run.py as –Program –
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get google.co.indriver.get("https://google.co.in / search?q = geeksforgeeks")
Output-
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Adding new column to existing DataFrame in Pandas
Python map() function
Read JSON file using Python
How to get column names in Pandas dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python OOPs Concepts
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 41137,
"s": 41109,
"text": "\n10 Apr, 2020"
},
{
"code": null,
"e": 41568,
"s": 41137,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python to navigate to any link on web using get method of Selenium Webdriver in python."
},
{
"code": null,
"e": 41699,
"s": 41568,
"text": "If you have not installed Selenium and its components yet, install them from here – Selenium Python Introduction and Installation."
},
{
"code": null,
"e": 41831,
"s": 41699,
"text": "The first thing one’ll want to do with WebDriver is navigate to a link. The normal way to do this is by calling get method:Syntax –"
},
{
"code": null,
"e": 41848,
"s": 41831,
"text": "driver.get(url)\n"
},
{
"code": null,
"e": 41857,
"s": 41848,
"text": "Example-"
},
{
"code": null,
"e": 41893,
"s": 41857,
"text": "driver.get(\"http://www.google.com\")"
},
{
"code": null,
"e": 42228,
"s": 41893,
"text": "WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits."
},
{
"code": null,
"e": 42322,
"s": 42228,
"text": "Project Example –After you have installed Selenium, create a file called run.py as –Program –"
},
{
"code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get google.co.indriver.get(\"https://google.co.in / search?q = geeksforgeeks\")",
"e": 42550,
"s": 42322,
"text": null
},
{
"code": null,
"e": 42558,
"s": 42550,
"text": "Output-"
},
{
"code": null,
"e": 42574,
"s": 42558,
"text": "Python-selenium"
},
{
"code": null,
"e": 42583,
"s": 42574,
"text": "selenium"
},
{
"code": null,
"e": 42590,
"s": 42583,
"text": "Python"
},
{
"code": null,
"e": 42688,
"s": 42590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42697,
"s": 42688,
"text": "Comments"
},
{
"code": null,
"e": 42710,
"s": 42697,
"text": "Old Comments"
},
{
"code": null,
"e": 42760,
"s": 42710,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 42782,
"s": 42760,
"text": "Python map() function"
},
{
"code": null,
"e": 42810,
"s": 42782,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 42854,
"s": 42810,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 42876,
"s": 42854,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 42908,
"s": 42876,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 42929,
"s": 42908,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 42964,
"s": 42929,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 42994,
"s": 42964,
"text": "Iterate over a list in Python"
}
] |
Intuitive Understanding of Logistic Regression (python) | by Andrew Hershy | Towards Data Science
|
A logistic regression is a model used to predict the “either-or” of a target variable. The example we will be working on is:
Target variable: Student will pass or fail the exam.
Independent variable: Hours spent studying per week
Logistic models are essentially linear models with an extra step. In logistic models, a linear regression is ran through a “sigmoid function” which compresses its output into dichotomous 1’s and 0’s.
If we wanted to predict actual test scores, we would use a linear model. If we wanted to predict “pass”/ “fail”, we would use a logistic regression model.
y = b0 + b1x
p = 1 / 1 + e ^-(b0 + b1x)
In the image below, the straight line is linear , and the “S” shaped line is logistic. Logistic regressions have higher accuracy when used for “either-or” models due to their shape.
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_excel(r”C:\Users\x\x\Log_test.xlsx”)x = df[‘W_hours’]y = df[‘Y’]plt.scatter(x,y)plt.show()
df.info()x.plot.hist()y.plot.hist()
There are 23 rows in the dataset. Below is the distribution of hours studied:
Below is the distribution of pass (1)/fail (0):
Next, we will use the sklearn library to import “LogisticRegression”. Details about the parameters can be found here.
We are converting our bivariate model into 2 dimensions with the .reshape() function. We are defining 1 column, but we are leaving the number of rows to be the size of the dataset. So we get the new shape for x as (23, 1), a vertical array. This is needed to make the sklearn function work properly.
Use the “logreg.fit(x,y)” to fit the regression.
from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression(C=1.0, solver=’lbfgs’, multi_class=’ovr’)#Convert a 1D array to a 2D array in numpyx = x.reshape(-1,1)#Run Logistic Regressionlogreg.fit(x, y)
Let’s write a program where we can get the predicted probability of passing and failing by hours studied. We input the study time in the code below: Examples of 12, 16, and 20 hours studied.
print(logreg.predict_proba([[12]]))print(logreg.predict_proba([[16]]))print(logreg.predict_proba([[20]]))
The output on the left is the probability of failing, the output on the right is passing.
In order to visualize the model, let’s make a loop where we run each half-hour of study time into the regression from 0 to 33.
hours = np.arange(0, 33, 0.5)probabilities= []for i in hours: p_fail, p_pass = logreg.predict_proba([[i]])[0] probabilities.append(p_pass)plt.scatter(hours,probabilities)plt.title("Logistic Regression Model")plt.xlabel('Hours')plt.ylabel('Status (1:Pass, 0:Fail)')plt.show()
In this fictional set of data, a student is guaranteed to pass if he/she studies more than 20 hours and is guaranteed to fail if less than 10 hours. 17 hours is the 50/50 mark.
Thanks for reading,
Is Random Forest better than Logistic Regression? (a comparison)
Excel vs SQL: A Conceptual Comparison
Predicting Cancer with Logistic Regression in Python
Optimize your Investments using Math and Python
Uber Reviews Text Analysis
|
[
{
"code": null,
"e": 297,
"s": 172,
"text": "A logistic regression is a model used to predict the “either-or” of a target variable. The example we will be working on is:"
},
{
"code": null,
"e": 350,
"s": 297,
"text": "Target variable: Student will pass or fail the exam."
},
{
"code": null,
"e": 402,
"s": 350,
"text": "Independent variable: Hours spent studying per week"
},
{
"code": null,
"e": 602,
"s": 402,
"text": "Logistic models are essentially linear models with an extra step. In logistic models, a linear regression is ran through a “sigmoid function” which compresses its output into dichotomous 1’s and 0’s."
},
{
"code": null,
"e": 757,
"s": 602,
"text": "If we wanted to predict actual test scores, we would use a linear model. If we wanted to predict “pass”/ “fail”, we would use a logistic regression model."
},
{
"code": null,
"e": 770,
"s": 757,
"text": "y = b0 + b1x"
},
{
"code": null,
"e": 797,
"s": 770,
"text": "p = 1 / 1 + e ^-(b0 + b1x)"
},
{
"code": null,
"e": 979,
"s": 797,
"text": "In the image below, the straight line is linear , and the “S” shaped line is logistic. Logistic regressions have higher accuracy when used for “either-or” models due to their shape."
},
{
"code": null,
"e": 1169,
"s": 979,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_excel(r”C:\\Users\\x\\x\\Log_test.xlsx”)x = df[‘W_hours’]y = df[‘Y’]plt.scatter(x,y)plt.show()"
},
{
"code": null,
"e": 1205,
"s": 1169,
"text": "df.info()x.plot.hist()y.plot.hist()"
},
{
"code": null,
"e": 1283,
"s": 1205,
"text": "There are 23 rows in the dataset. Below is the distribution of hours studied:"
},
{
"code": null,
"e": 1331,
"s": 1283,
"text": "Below is the distribution of pass (1)/fail (0):"
},
{
"code": null,
"e": 1449,
"s": 1331,
"text": "Next, we will use the sklearn library to import “LogisticRegression”. Details about the parameters can be found here."
},
{
"code": null,
"e": 1749,
"s": 1449,
"text": "We are converting our bivariate model into 2 dimensions with the .reshape() function. We are defining 1 column, but we are leaving the number of rows to be the size of the dataset. So we get the new shape for x as (23, 1), a vertical array. This is needed to make the sklearn function work properly."
},
{
"code": null,
"e": 1798,
"s": 1749,
"text": "Use the “logreg.fit(x,y)” to fit the regression."
},
{
"code": null,
"e": 2020,
"s": 1798,
"text": "from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression(C=1.0, solver=’lbfgs’, multi_class=’ovr’)#Convert a 1D array to a 2D array in numpyx = x.reshape(-1,1)#Run Logistic Regressionlogreg.fit(x, y)"
},
{
"code": null,
"e": 2211,
"s": 2020,
"text": "Let’s write a program where we can get the predicted probability of passing and failing by hours studied. We input the study time in the code below: Examples of 12, 16, and 20 hours studied."
},
{
"code": null,
"e": 2317,
"s": 2211,
"text": "print(logreg.predict_proba([[12]]))print(logreg.predict_proba([[16]]))print(logreg.predict_proba([[20]]))"
},
{
"code": null,
"e": 2407,
"s": 2317,
"text": "The output on the left is the probability of failing, the output on the right is passing."
},
{
"code": null,
"e": 2534,
"s": 2407,
"text": "In order to visualize the model, let’s make a loop where we run each half-hour of study time into the regression from 0 to 33."
},
{
"code": null,
"e": 2815,
"s": 2534,
"text": "hours = np.arange(0, 33, 0.5)probabilities= []for i in hours: p_fail, p_pass = logreg.predict_proba([[i]])[0] probabilities.append(p_pass)plt.scatter(hours,probabilities)plt.title(\"Logistic Regression Model\")plt.xlabel('Hours')plt.ylabel('Status (1:Pass, 0:Fail)')plt.show()"
},
{
"code": null,
"e": 2992,
"s": 2815,
"text": "In this fictional set of data, a student is guaranteed to pass if he/she studies more than 20 hours and is guaranteed to fail if less than 10 hours. 17 hours is the 50/50 mark."
},
{
"code": null,
"e": 3012,
"s": 2992,
"text": "Thanks for reading,"
},
{
"code": null,
"e": 3077,
"s": 3012,
"text": "Is Random Forest better than Logistic Regression? (a comparison)"
},
{
"code": null,
"e": 3115,
"s": 3077,
"text": "Excel vs SQL: A Conceptual Comparison"
},
{
"code": null,
"e": 3168,
"s": 3115,
"text": "Predicting Cancer with Logistic Regression in Python"
},
{
"code": null,
"e": 3216,
"s": 3168,
"text": "Optimize your Investments using Math and Python"
}
] |
Algorithms | InsertionSort | Question 2 - GeeksforGeeks
|
28 Jun, 2021
Which is the correct order of the following algorithms with respect to their time Complexity in the best case ?(A) Merge sort > Quick sort >Insertion sort > selection sort(B) insertion sort < Quick sort < Merge sort < selection sort(C) Merge sort > selection sort > quick sort > insertion sort(D) Merge sort > Quick sort > selection sort > insertion sortAnswer: (B)Explanation:
In best case,
Quick sort: O (nlogn)
Merge sort: O (nlogn)
Insertion sort: O (n)
Selection sort: O (n^2)
Quiz of this Question
Algorithms-InsertionSort
InsertionSort
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Bit Algorithms | Question 3
Algorithms | Bit Algorithms | Question 2
Algorithms | Divide and Conquer | Question 2
Algorithms | Bit Algorithms | Question 1
Data Structures and Algorithms | Set 38
Algorithms | Divide and Conquer | Question 4
Algorithms | Analysis of Algorithms | Question 19
|
[
{
"code": null,
"e": 24289,
"s": 24261,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24667,
"s": 24289,
"text": "Which is the correct order of the following algorithms with respect to their time Complexity in the best case ?(A) Merge sort > Quick sort >Insertion sort > selection sort(B) insertion sort < Quick sort < Merge sort < selection sort(C) Merge sort > selection sort > quick sort > insertion sort(D) Merge sort > Quick sort > selection sort > insertion sortAnswer: (B)Explanation:"
},
{
"code": null,
"e": 24776,
"s": 24667,
"text": "In best case, \n\nQuick sort: O (nlogn) \nMerge sort: O (nlogn)\nInsertion sort: O (n)\nSelection sort: O (n^2) "
},
{
"code": null,
"e": 24798,
"s": 24776,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 24823,
"s": 24798,
"text": "Algorithms-InsertionSort"
},
{
"code": null,
"e": 24837,
"s": 24823,
"text": "InsertionSort"
},
{
"code": null,
"e": 24853,
"s": 24837,
"text": "Algorithms Quiz"
},
{
"code": null,
"e": 24951,
"s": 24853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24960,
"s": 24951,
"text": "Comments"
},
{
"code": null,
"e": 24973,
"s": 24960,
"text": "Old Comments"
},
{
"code": null,
"e": 25019,
"s": 24973,
"text": "Algorithms | Dynamic Programming | Question 2"
},
{
"code": null,
"e": 25065,
"s": 25019,
"text": "Algorithms | Dynamic Programming | Question 3"
},
{
"code": null,
"e": 25116,
"s": 25065,
"text": "Algorithms Quiz | Dynamic Programming | Question 8"
},
{
"code": null,
"e": 25157,
"s": 25116,
"text": "Algorithms | Bit Algorithms | Question 3"
},
{
"code": null,
"e": 25198,
"s": 25157,
"text": "Algorithms | Bit Algorithms | Question 2"
},
{
"code": null,
"e": 25243,
"s": 25198,
"text": "Algorithms | Divide and Conquer | Question 2"
},
{
"code": null,
"e": 25284,
"s": 25243,
"text": "Algorithms | Bit Algorithms | Question 1"
},
{
"code": null,
"e": 25324,
"s": 25284,
"text": "Data Structures and Algorithms | Set 38"
},
{
"code": null,
"e": 25369,
"s": 25324,
"text": "Algorithms | Divide and Conquer | Question 4"
}
] |
Largest of two distinct numbers without using any conditional statements or operators - GeeksforGeeks
|
01 Apr, 2021
Given two positive and distinct numbers, the task is to find the greatest of two given numbers without using any conditional statements(if...) and operators(?: in C/C++/Java).
Examples:
Input: a = 14, b = 15
Output: 15
Input: a = 1233133, b = 124
Output: 1233133
The Approach is to return the value on the basis of the below expression:
a * (bool)(a / b) + b * (bool)(b / a)
The expression a / b will give 1 if a > b and 0 if a < b (only after typecasting the result to bool). Hence, the answer will be of the form either a + 0 or 0 + b depending upon which one is greater.
C++
Java
Python3
C#
PHP
Javascript
// C++ program for above implementation#include <iostream>using namespace std; // Function to find the largest numberint largestNum(int a, int b){ return a * (bool)(a / b) + b * (bool)(b / a);} // Drivers codeint main(){ int a = 22, b = 1231; cout << largestNum(a, b); return 0;}
// Java program for above implementationclass GFG{ // Function to find the largest number static int largestNum(int a, int b) { return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0); } // Drivers code public static void main(String[] args) { int a = 22, b = 1231; System.out.print(largestNum(a, b)); }} // This code is contributed by 29AjayKumar
# Function to find the largest numberdef largestNum(a, b): return a * (bool)(a // b) + \ b * (bool)(b // a); # Driver Codea = 22;b = 1231;print(largestNum(a, b)); # This code is contributed by Rajput-Ji
// C# program for above implementationusing System; class GFG{ // Function to find the largest number static int largestNum(int a, int b) { return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0); } // Driver code public static void Main(String[] args) { int a = 22, b = 1231; Console.Write(largestNum(a, b)); }} // This code is contributed by Rajput-Ji
<?php// PHP program for above implementation // Function to find the largest numberfunction largestNum($a, $b){ return ($a * (boolean)floor(($a / $b))) + ($b * (boolean)floor(($b / $a)));} // Drivers code$a = 22; $b = 1231;echo(largestNum($a, $b)); // This code is contributed// by Mukul Singh
<script> // Javascript program for above implementation // Function to find the largest numberfunction largestNum(a , b){ return a * (parseInt(a / b) > 0 ? 1 : 0) + b * (parseInt(b / a) > 0 ? 1 : 0);} // Driver codevar a = 22, b = 1231; document.write(largestNum(a, b)); // This code is contributed by shikhasingrajput </script>
1231
Code_Mech
29AjayKumar
Rajput-Ji
shikhasingrajput
Mathematical
Misc
School Programming
Misc
Mathematical
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Program to convert a given number to words
Program to multiply two matrices
Modular multiplicative inverse
Program to print prime numbers from 1 to N.
vector::push_back() and vector::pop_back() in C++ STL
Top 10 algorithms in Interview Questions
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
Software Engineering | Prototyping Model
|
[
{
"code": null,
"e": 24637,
"s": 24609,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 24813,
"s": 24637,
"text": "Given two positive and distinct numbers, the task is to find the greatest of two given numbers without using any conditional statements(if...) and operators(?: in C/C++/Java)."
},
{
"code": null,
"e": 24825,
"s": 24813,
"text": "Examples: "
},
{
"code": null,
"e": 24903,
"s": 24825,
"text": "Input: a = 14, b = 15\nOutput: 15\n\nInput: a = 1233133, b = 124\nOutput: 1233133"
},
{
"code": null,
"e": 24978,
"s": 24903,
"text": "The Approach is to return the value on the basis of the below expression: "
},
{
"code": null,
"e": 25018,
"s": 24978,
"text": "a * (bool)(a / b) + b * (bool)(b / a) "
},
{
"code": null,
"e": 25218,
"s": 25018,
"text": "The expression a / b will give 1 if a > b and 0 if a < b (only after typecasting the result to bool). Hence, the answer will be of the form either a + 0 or 0 + b depending upon which one is greater. "
},
{
"code": null,
"e": 25222,
"s": 25218,
"text": "C++"
},
{
"code": null,
"e": 25227,
"s": 25222,
"text": "Java"
},
{
"code": null,
"e": 25235,
"s": 25227,
"text": "Python3"
},
{
"code": null,
"e": 25238,
"s": 25235,
"text": "C#"
},
{
"code": null,
"e": 25242,
"s": 25238,
"text": "PHP"
},
{
"code": null,
"e": 25253,
"s": 25242,
"text": "Javascript"
},
{
"code": "// C++ program for above implementation#include <iostream>using namespace std; // Function to find the largest numberint largestNum(int a, int b){ return a * (bool)(a / b) + b * (bool)(b / a);} // Drivers codeint main(){ int a = 22, b = 1231; cout << largestNum(a, b); return 0;}",
"e": 25546,
"s": 25253,
"text": null
},
{
"code": "// Java program for above implementationclass GFG{ // Function to find the largest number static int largestNum(int a, int b) { return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0); } // Drivers code public static void main(String[] args) { int a = 22, b = 1231; System.out.print(largestNum(a, b)); }} // This code is contributed by 29AjayKumar",
"e": 25946,
"s": 25546,
"text": null
},
{
"code": "# Function to find the largest numberdef largestNum(a, b): return a * (bool)(a // b) + \\ b * (bool)(b // a); # Driver Codea = 22;b = 1231;print(largestNum(a, b)); # This code is contributed by Rajput-Ji",
"e": 26162,
"s": 25946,
"text": null
},
{
"code": " // C# program for above implementationusing System; class GFG{ // Function to find the largest number static int largestNum(int a, int b) { return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0); } // Driver code public static void Main(String[] args) { int a = 22, b = 1231; Console.Write(largestNum(a, b)); }} // This code is contributed by Rajput-Ji",
"e": 26573,
"s": 26162,
"text": null
},
{
"code": "<?php// PHP program for above implementation // Function to find the largest numberfunction largestNum($a, $b){ return ($a * (boolean)floor(($a / $b))) + ($b * (boolean)floor(($b / $a)));} // Drivers code$a = 22; $b = 1231;echo(largestNum($a, $b)); // This code is contributed// by Mukul Singh",
"e": 26880,
"s": 26573,
"text": null
},
{
"code": "<script> // Javascript program for above implementation // Function to find the largest numberfunction largestNum(a , b){ return a * (parseInt(a / b) > 0 ? 1 : 0) + b * (parseInt(b / a) > 0 ? 1 : 0);} // Driver codevar a = 22, b = 1231; document.write(largestNum(a, b)); // This code is contributed by shikhasingrajput </script>",
"e": 27222,
"s": 26880,
"text": null
},
{
"code": null,
"e": 27227,
"s": 27222,
"text": "1231"
},
{
"code": null,
"e": 27239,
"s": 27229,
"text": "Code_Mech"
},
{
"code": null,
"e": 27251,
"s": 27239,
"text": "29AjayKumar"
},
{
"code": null,
"e": 27261,
"s": 27251,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 27278,
"s": 27261,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 27291,
"s": 27278,
"text": "Mathematical"
},
{
"code": null,
"e": 27296,
"s": 27291,
"text": "Misc"
},
{
"code": null,
"e": 27315,
"s": 27296,
"text": "School Programming"
},
{
"code": null,
"e": 27320,
"s": 27315,
"text": "Misc"
},
{
"code": null,
"e": 27333,
"s": 27320,
"text": "Mathematical"
},
{
"code": null,
"e": 27338,
"s": 27333,
"text": "Misc"
},
{
"code": null,
"e": 27436,
"s": 27338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27445,
"s": 27436,
"text": "Comments"
},
{
"code": null,
"e": 27458,
"s": 27445,
"text": "Old Comments"
},
{
"code": null,
"e": 27490,
"s": 27458,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 27533,
"s": 27490,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 27566,
"s": 27533,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 27597,
"s": 27566,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 27641,
"s": 27597,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 27695,
"s": 27641,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 27736,
"s": 27695,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 27797,
"s": 27736,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 27831,
"s": 27797,
"text": "How to write Regular Expressions?"
}
] |
Git Push to GitHub
|
Let's try making some changes to our local git and pushing them to GitHub.
Commit the changes:
git commit -a -m "Updated index.html. Resized image"
[master e7de78f] Updated index.html. Resized image
1 file changed, 1 insertion(+), 1 deletion(-)
And check the status:
git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
nothing to commit, working tree clean
Now push our changes to our remote origin:
git push origin
Enumerating objects: 9, done.
Counting objects: 100% (8/8), done.
Delta compression using up to 16 threads
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 578 bytes | 578.00 KiB/s, done.
Total 5 (delta 3), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (3/3), completed with 3 local objects.
To https://github.com/w3schools-test/hello-world.git
5a04b6f..facaeae master -> master
Go to GitHub, and confirm that the repository has a new commit:
Now, we are going to start working on branches on GitHub.
push the current branch to its default remote origin:
git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 75,
"s": 0,
"text": "Let's try making some changes to our local git and pushing them to GitHub."
},
{
"code": null,
"e": 95,
"s": 75,
"text": "Commit the changes:"
},
{
"code": null,
"e": 246,
"s": 95,
"text": "git commit -a -m \"Updated index.html. Resized image\"\n[master e7de78f] Updated index.html. Resized image\n 1 file changed, 1 insertion(+), 1 deletion(-)"
},
{
"code": null,
"e": 268,
"s": 246,
"text": "And check the status:"
},
{
"code": null,
"e": 437,
"s": 268,
"text": "git status\nOn branch master\nYour branch is ahead of 'origin/master' by 1 commit.\n (use \"git push\" to publish your local commits)\n\nnothing to commit, working tree clean"
},
{
"code": null,
"e": 480,
"s": 437,
"text": "Now push our changes to our remote origin:"
},
{
"code": null,
"e": 917,
"s": 480,
"text": "git push origin\nEnumerating objects: 9, done.\nCounting objects: 100% (8/8), done.\nDelta compression using up to 16 threads\nCompressing objects: 100% (5/5), done.\nWriting objects: 100% (5/5), 578 bytes | 578.00 KiB/s, done.\nTotal 5 (delta 3), reused 0 (delta 0), pack-reused 0\nremote: Resolving deltas: 100% (3/3), completed with 3 local objects.\nTo https://github.com/w3schools-test/hello-world.git\n 5a04b6f..facaeae master -> master"
},
{
"code": null,
"e": 981,
"s": 917,
"text": "Go to GitHub, and confirm that the repository has a new commit:"
},
{
"code": null,
"e": 1039,
"s": 981,
"text": "Now, we are going to start working on branches on GitHub."
},
{
"code": null,
"e": 1093,
"s": 1039,
"text": "push the current branch to its default remote origin:"
},
{
"code": null,
"e": 1100,
"s": 1093,
"text": "git \n"
},
{
"code": null,
"e": 1120,
"s": 1100,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 1153,
"s": 1120,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1195,
"s": 1153,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1302,
"s": 1195,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1321,
"s": 1302,
"text": "[email protected]"
}
] |
Explain scope of a variable in C language.
|
Storage classes specify the scope, lifetime and binding of variables.
To fully define a variable, one needs to mention not only its ‘type’ but also its storage class.
A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable.
Storage class tells us the following factors −
Where the variable is stored (in memory or cpu register)?
What will be the initial value of variable, if nothing is initialized?
What is the scope of variable (where it can be accessed)?
What is the life of a variable?
Scope defines the visibility of an object. It defines where an object can be accessed.
The scope variable is local or global
The variable defined within the block has local scope. They are visible only to the block in which they are defined.
The variable defined in global area is visible from their definition until the end of program. It is visible everywhere in program.
Following is the C program for the scope of a variable −
#include<stdio.h>
int c= 30; /* global area */
main ( ) {
int a = 10; //local scope//
printf ("a=%d,c=%d"a,c);
fun ( );
}
fun ( ){
printf ("c=%d",c); //global variable
}
When the above program is executed, it produces the following output −
a =10, c = 30
c = 30
Following is the C program for the local and global variables −
Live Demo
#include<stdio.h>
int a,b;
a=1,b=2;
main() {
int c,d;
printf("enter c and d values:");
scanf("%d%d",&c,&d);
c=c+d; //local variables
b=a*b; //global variables
printf("c value is:%d\n",c);
printf("b value is:%d\n",b);
}
When the above program is executed, it produces the following output −
enter c and d values:4 7
c value is:11
b value is:2
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "Storage classes specify the scope, lifetime and binding of variables."
},
{
"code": null,
"e": 1229,
"s": 1132,
"text": "To fully define a variable, one needs to mention not only its ‘type’ but also its storage class."
},
{
"code": null,
"e": 1376,
"s": 1229,
"text": "A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable."
},
{
"code": null,
"e": 1423,
"s": 1376,
"text": "Storage class tells us the following factors −"
},
{
"code": null,
"e": 1481,
"s": 1423,
"text": "Where the variable is stored (in memory or cpu register)?"
},
{
"code": null,
"e": 1552,
"s": 1481,
"text": "What will be the initial value of variable, if nothing is initialized?"
},
{
"code": null,
"e": 1610,
"s": 1552,
"text": "What is the scope of variable (where it can be accessed)?"
},
{
"code": null,
"e": 1642,
"s": 1610,
"text": "What is the life of a variable?"
},
{
"code": null,
"e": 1729,
"s": 1642,
"text": "Scope defines the visibility of an object. It defines where an object can be accessed."
},
{
"code": null,
"e": 1767,
"s": 1729,
"text": "The scope variable is local or global"
},
{
"code": null,
"e": 1884,
"s": 1767,
"text": "The variable defined within the block has local scope. They are visible only to the block in which they are defined."
},
{
"code": null,
"e": 2016,
"s": 1884,
"text": "The variable defined in global area is visible from their definition until the end of program. It is visible everywhere in program."
},
{
"code": null,
"e": 2073,
"s": 2016,
"text": "Following is the C program for the scope of a variable −"
},
{
"code": null,
"e": 2255,
"s": 2073,
"text": "#include<stdio.h>\nint c= 30; /* global area */\nmain ( ) {\n int a = 10; //local scope//\n printf (\"a=%d,c=%d\"a,c);\n fun ( );\n}\nfun ( ){\n printf (\"c=%d\",c); //global variable\n}"
},
{
"code": null,
"e": 2326,
"s": 2255,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2347,
"s": 2326,
"text": "a =10, c = 30\nc = 30"
},
{
"code": null,
"e": 2411,
"s": 2347,
"text": "Following is the C program for the local and global variables −"
},
{
"code": null,
"e": 2422,
"s": 2411,
"text": " Live Demo"
},
{
"code": null,
"e": 2662,
"s": 2422,
"text": "#include<stdio.h>\nint a,b;\na=1,b=2;\nmain() {\n int c,d;\n printf(\"enter c and d values:\");\n scanf(\"%d%d\",&c,&d);\n c=c+d; //local variables\n b=a*b; //global variables\n printf(\"c value is:%d\\n\",c);\n printf(\"b value is:%d\\n\",b);\n}"
},
{
"code": null,
"e": 2733,
"s": 2662,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2785,
"s": 2733,
"text": "enter c and d values:4 7\nc value is:11\nb value is:2"
}
] |
How to do Multiprocessing in Python - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how to do multiprocessing in Python using an example.
It is a way to run multiple processes at the same time given that the machine has support for multiple processors. The main advantage is of multiprocessing is that the system actually performs multiple independently executable parts of an application at the same time which eventually increases the efficiency and performance of the system. Before moving further let’s see what is a process identifier.
A Process Identifier or PID, in short, is a number that uniquely identifies each running process in an operating system which can be Unix, Linux, macOS, and MS Windows.
Python provides an inbuilt package named multiprocessing which provide API that effectively supports concurrency, distributing the input data across processes or parallel executions of different processes. In the above section, we have learned about process identifier and the built-in os module of python provides us with a method named getpid() which returns the PID of the process.
Let’s create a function that takes an integer and return whether it is positive or not and print the PIDs.
import multiprocessing
import os
def isPositive(n):
print("isPositive function with Process ID:",os.getpid())
if n>=0:
print("Integer passed is Positive:")
else:
print("Integer passed is Negative:")
if __name__ == "__main__":
print("Main function with Process ID:",os.getpid())
isPositive(-1)
isPositive(2)
Output:
Main function has Process ID: 7644
isPositive function has Process ID: 7644
Integer passed is Negative:
isPositive function has Process ID: 7644
Integer passed is Positive:
Note: PID can be different from the above output.
From the output, we see that all the function calls that we have called has the same Process ID which is same as that of the main function.
Next, we will use the components of the multiprocessing module to run the tasks as different processes.
Whenever we want to create a new process we create an object of the Process class whose constructor takes the following arguments.
target – It is the callable object to be invoked by the run() method and default value is None.
args – It is the argument tuple that is passed in the function specified in the target.
name – It is the process name as a string. the default value is None.
There are some other methods provided by this class which are as follows.
start() – It will start the process’s activity and is called at most once for each process.
run() – This invokes function passed as the target argument.
join([timeout]) – This method blocks until the process whose join() method is called terminates.
is_alive() – Returns True if a process is alive else False.
pid – Return the process Id of a process
start() – It will start the process’s activity and is called at most once for each process.
run() – This invokes function passed as the target argument.
join([timeout]) – This method blocks until the process whose join() method is called terminates.
is_alive() – Returns True if a process is alive else False.
pid – Return the process Id of a process
We will try to perform multiprocessing on the above example using the Process class.
import multiprocessing
import os
def isPositive(n):
print("isPositive function with Process ID:",os.getpid())
if n>=0:
print("Integer passed is Positive")
else:
print("Integer passed is Negative")
if __name__ == "__main__":
print("Main function with Process ID:",os.getpid())
proc1 = multiprocessing.Process(target=isPositive,args=(8,))
proc2 = multiprocessing.Process(target=isPositive,args=(-6,))
proc1.start()
proc2.start()
print("Process proc1 has Process ID:",proc1.pid)
print("Process proc2 has Process ID:",proc2.pid)
proc1.join()
proc2.join()
Output:
Main function with Process ID: 10124
Process proc1 has Process ID: 14912
Process proc2 has Process ID: 11708
isPositive function with Process ID: 14912
Integer passed is Positive
isPositive function with Process ID: 11708
Integer passed is Negative
From the output above, we can see that in total we have 3 processes running, one main process and two subprocesses of the main process.
So we learned about multiprocessing in python.
Official Documentation
Python Classes and Objects
Happy Learning 🙂
Different ways to use Lambdas in Python
How to pass Command line Arguments in Python
Python raw_input read input from keyboard
Python Decorators – Classes and Functions
How to Remove Spaces from String in Python
How to access for loop index in Python
What are Python default function parameters ?
How to sort python dictionary by key ?
Python – How to merge two dict in Python ?
Python TypeCasting for Different Types
How to remove empty lists from a Python List
Python How to read input from keyboard
How to Create or Delete Directories in Python ?
What are the different ways to Sort Objects in Python ?
How to use *args and **kwargs in Python
Different ways to use Lambdas in Python
How to pass Command line Arguments in Python
Python raw_input read input from keyboard
Python Decorators – Classes and Functions
How to Remove Spaces from String in Python
How to access for loop index in Python
What are Python default function parameters ?
How to sort python dictionary by key ?
Python – How to merge two dict in Python ?
Python TypeCasting for Different Types
How to remove empty lists from a Python List
Python How to read input from keyboard
How to Create or Delete Directories in Python ?
What are the different ways to Sort Objects in Python ?
How to use *args and **kwargs in Python
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 482,
"s": 398,
"text": "In this tutorial, we will see how to do multiprocessing in Python using an example."
},
{
"code": null,
"e": 885,
"s": 482,
"text": "It is a way to run multiple processes at the same time given that the machine has support for multiple processors. The main advantage is of multiprocessing is that the system actually performs multiple independently executable parts of an application at the same time which eventually increases the efficiency and performance of the system. Before moving further let’s see what is a process identifier."
},
{
"code": null,
"e": 1056,
"s": 885,
"text": "A Process Identifier or PID, in short, is a number that uniquely identifies each running process in an operating system which can be Unix, Linux, macOS, and MS Windows."
},
{
"code": null,
"e": 1441,
"s": 1056,
"text": "Python provides an inbuilt package named multiprocessing which provide API that effectively supports concurrency, distributing the input data across processes or parallel executions of different processes. In the above section, we have learned about process identifier and the built-in os module of python provides us with a method named getpid() which returns the PID of the process."
},
{
"code": null,
"e": 1548,
"s": 1441,
"text": "Let’s create a function that takes an integer and return whether it is positive or not and print the PIDs."
},
{
"code": null,
"e": 1902,
"s": 1548,
"text": "import multiprocessing \nimport os \n\ndef isPositive(n): \n print(\"isPositive function with Process ID:\",os.getpid())\n if n>=0:\n print(\"Integer passed is Positive:\")\n else:\n print(\"Integer passed is Negative:\")\n\nif __name__ == \"__main__\": \n print(\"Main function with Process ID:\",os.getpid()) \n isPositive(-1)\n isPositive(2)"
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Output:"
},
{
"code": null,
"e": 2083,
"s": 1910,
"text": "Main function has Process ID: 7644\nisPositive function has Process ID: 7644\nInteger passed is Negative:\nisPositive function has Process ID: 7644\nInteger passed is Positive:"
},
{
"code": null,
"e": 2133,
"s": 2083,
"text": "Note: PID can be different from the above output."
},
{
"code": null,
"e": 2273,
"s": 2133,
"text": "From the output, we see that all the function calls that we have called has the same Process ID which is same as that of the main function."
},
{
"code": null,
"e": 2377,
"s": 2273,
"text": "Next, we will use the components of the multiprocessing module to run the tasks as different processes."
},
{
"code": null,
"e": 2508,
"s": 2377,
"text": "Whenever we want to create a new process we create an object of the Process class whose constructor takes the following arguments."
},
{
"code": null,
"e": 2604,
"s": 2508,
"text": "target – It is the callable object to be invoked by the run() method and default value is None."
},
{
"code": null,
"e": 2692,
"s": 2604,
"text": "args – It is the argument tuple that is passed in the function specified in the target."
},
{
"code": null,
"e": 2762,
"s": 2692,
"text": "name – It is the process name as a string. the default value is None."
},
{
"code": null,
"e": 2836,
"s": 2762,
"text": "There are some other methods provided by this class which are as follows."
},
{
"code": null,
"e": 3189,
"s": 2836,
"text": "\nstart() – It will start the process’s activity and is called at most once for each process.\nrun() – This invokes function passed as the target argument.\njoin([timeout]) – This method blocks until the process whose join() method is called terminates.\nis_alive() – Returns True if a process is alive else False.\npid – Return the process Id of a process\n"
},
{
"code": null,
"e": 3281,
"s": 3189,
"text": "start() – It will start the process’s activity and is called at most once for each process."
},
{
"code": null,
"e": 3342,
"s": 3281,
"text": "run() – This invokes function passed as the target argument."
},
{
"code": null,
"e": 3439,
"s": 3342,
"text": "join([timeout]) – This method blocks until the process whose join() method is called terminates."
},
{
"code": null,
"e": 3499,
"s": 3439,
"text": "is_alive() – Returns True if a process is alive else False."
},
{
"code": null,
"e": 3540,
"s": 3499,
"text": "pid – Return the process Id of a process"
},
{
"code": null,
"e": 3625,
"s": 3540,
"text": "We will try to perform multiprocessing on the above example using the Process class."
},
{
"code": null,
"e": 4251,
"s": 3625,
"text": "import multiprocessing \nimport os \n\ndef isPositive(n): \n print(\"isPositive function with Process ID:\",os.getpid())\n if n>=0:\n print(\"Integer passed is Positive\")\n else:\n print(\"Integer passed is Negative\")\n\nif __name__ == \"__main__\": \n print(\"Main function with Process ID:\",os.getpid())\n proc1 = multiprocessing.Process(target=isPositive,args=(8,))\n proc2 = multiprocessing.Process(target=isPositive,args=(-6,))\n proc1.start() \n proc2.start() \n print(\"Process proc1 has Process ID:\",proc1.pid) \n print(\"Process proc2 has Process ID:\",proc2.pid) \n proc1.join() \n proc2.join()"
},
{
"code": null,
"e": 4259,
"s": 4251,
"text": "Output:"
},
{
"code": null,
"e": 4508,
"s": 4259,
"text": "Main function with Process ID: 10124\nProcess proc1 has Process ID: 14912\nProcess proc2 has Process ID: 11708\nisPositive function with Process ID: 14912\nInteger passed is Positive\nisPositive function with Process ID: 11708\nInteger passed is Negative"
},
{
"code": null,
"e": 4644,
"s": 4508,
"text": "From the output above, we can see that in total we have 3 processes running, one main process and two subprocesses of the main process."
},
{
"code": null,
"e": 4691,
"s": 4644,
"text": "So we learned about multiprocessing in python."
},
{
"code": null,
"e": 4714,
"s": 4691,
"text": "Official Documentation"
},
{
"code": null,
"e": 4741,
"s": 4714,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4758,
"s": 4741,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 5406,
"s": 4758,
"text": "\nDifferent ways to use Lambdas in Python\nHow to pass Command line Arguments in Python\nPython raw_input read input from keyboard\nPython Decorators – Classes and Functions\nHow to Remove Spaces from String in Python\nHow to access for loop index in Python\nWhat are Python default function parameters ?\nHow to sort python dictionary by key ?\nPython – How to merge two dict in Python ?\nPython TypeCasting for Different Types\nHow to remove empty lists from a Python List\nPython How to read input from keyboard\nHow to Create or Delete Directories in Python ?\nWhat are the different ways to Sort Objects in Python ?\nHow to use *args and **kwargs in Python\n"
},
{
"code": null,
"e": 5446,
"s": 5406,
"text": "Different ways to use Lambdas in Python"
},
{
"code": null,
"e": 5491,
"s": 5446,
"text": "How to pass Command line Arguments in Python"
},
{
"code": null,
"e": 5533,
"s": 5491,
"text": "Python raw_input read input from keyboard"
},
{
"code": null,
"e": 5575,
"s": 5533,
"text": "Python Decorators – Classes and Functions"
},
{
"code": null,
"e": 5618,
"s": 5575,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 5657,
"s": 5618,
"text": "How to access for loop index in Python"
},
{
"code": null,
"e": 5703,
"s": 5657,
"text": "What are Python default function parameters ?"
},
{
"code": null,
"e": 5742,
"s": 5703,
"text": "How to sort python dictionary by key ?"
},
{
"code": null,
"e": 5785,
"s": 5742,
"text": "Python – How to merge two dict in Python ?"
},
{
"code": null,
"e": 5824,
"s": 5785,
"text": "Python TypeCasting for Different Types"
},
{
"code": null,
"e": 5869,
"s": 5824,
"text": "How to remove empty lists from a Python List"
},
{
"code": null,
"e": 5908,
"s": 5869,
"text": "Python How to read input from keyboard"
},
{
"code": null,
"e": 5956,
"s": 5908,
"text": "How to Create or Delete Directories in Python ?"
},
{
"code": null,
"e": 6012,
"s": 5956,
"text": "What are the different ways to Sort Objects in Python ?"
},
{
"code": null,
"e": 6052,
"s": 6012,
"text": "How to use *args and **kwargs in Python"
},
{
"code": null,
"e": 6058,
"s": 6056,
"text": "Δ"
},
{
"code": null,
"e": 6081,
"s": 6058,
"text": " Python – Introduction"
},
{
"code": null,
"e": 6100,
"s": 6081,
"text": " Python – Features"
},
{
"code": null,
"e": 6129,
"s": 6100,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 6156,
"s": 6129,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 6180,
"s": 6156,
"text": " Python – Number System"
},
{
"code": null,
"e": 6202,
"s": 6180,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 6222,
"s": 6202,
"text": " Python – Operators"
},
{
"code": null,
"e": 6249,
"s": 6222,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 6282,
"s": 6249,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 6301,
"s": 6282,
"text": " Python – Keywords"
},
{
"code": null,
"e": 6322,
"s": 6301,
"text": " Python – Data Types"
},
{
"code": null,
"e": 6351,
"s": 6322,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 6381,
"s": 6351,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 6404,
"s": 6381,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 6428,
"s": 6404,
"text": " Python – String to Int"
},
{
"code": null,
"e": 6461,
"s": 6428,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 6484,
"s": 6461,
"text": " Python – if statement"
},
{
"code": null,
"e": 6513,
"s": 6484,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 6539,
"s": 6513,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 6574,
"s": 6539,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 6594,
"s": 6574,
"text": " Python – raw_input"
},
{
"code": null,
"e": 6618,
"s": 6594,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 6647,
"s": 6618,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 6670,
"s": 6647,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 6700,
"s": 6670,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 6725,
"s": 6700,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 6755,
"s": 6725,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 6785,
"s": 6755,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 6808,
"s": 6785,
"text": " Python – Constructors"
},
{
"code": null,
"e": 6839,
"s": 6808,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 6861,
"s": 6839,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 6882,
"s": 6861,
"text": " Python – Decorators"
},
{
"code": null,
"e": 6918,
"s": 6882,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 6948,
"s": 6918,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 6982,
"s": 6948,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 7008,
"s": 6982,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 7046,
"s": 7008,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 7074,
"s": 7046,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 7098,
"s": 7074,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 7124,
"s": 7098,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 7156,
"s": 7124,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 7182,
"s": 7156,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 7210,
"s": 7182,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 7241,
"s": 7210,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 7272,
"s": 7241,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 7305,
"s": 7272,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 7340,
"s": 7305,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 7377,
"s": 7340,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 7415,
"s": 7377,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 7441,
"s": 7415,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 7466,
"s": 7441,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 7506,
"s": 7466,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 7541,
"s": 7506,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 7576,
"s": 7541,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 7605,
"s": 7576,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 7631,
"s": 7605,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 7657,
"s": 7631,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 7689,
"s": 7657,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 7717,
"s": 7689,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 7757,
"s": 7717,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 7791,
"s": 7757,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 7816,
"s": 7791,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 7837,
"s": 7816,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 7868,
"s": 7837,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 7905,
"s": 7868,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 7942,
"s": 7905,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 7964,
"s": 7942,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 8002,
"s": 7964,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 8025,
"s": 8002,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 8063,
"s": 8025,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 8094,
"s": 8063,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 8132,
"s": 8094,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 8172,
"s": 8132,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 8219,
"s": 8172,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 8251,
"s": 8219,
"text": " Howto – Sort dictionary by key"
}
] |
Check if an array is sorted and rotated in C++
|
Given an array of integers, the task is to check if the array is sorted (increasing order) and rotated after some number of position or not.
For Example
Input-1:
N = [7, 8, 9, 4, 5, 6]
Output:
True
Explanation: Since the given array is in increasing order and the elements after the 3rd position are rotated, we will return True in this case.
Input-2:
N = [1, 5, 7, 6, 2, 3]
Output:
False
Explanation: Since the given array is neither in increasing order nor rotated with some specific position, the output is False.
We have an array with the element either in increasing order or unsorted. If the array has to be sorted and rotated, then at least one element will be there such that N[i] > N[i+1].
Thus, for every N[i], we will count if there lies any element which satisfies the condition and return True or False accordingly.
Take Input of an array element.
A Boolean function checkSortedandRotated(int *arr, int n) takes an array and its size as the input and returns true if the array is sorted and rotated otherwise false.
Iterate over the whole array and count the number of elements which are (arr[i] > arr[i+1]%n). If the count is '1', then return True, otherwise return False.
Return the output.
Live Demo
#include <bits/stdc++.h>
using namespace std;
bool checkSortedandRotated(int * arr, int n) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > arr[(i + 1) % n])
count++;
}
return (count <= 1);
}
int main() {
int arr[] = {5,6,7,1,2,3,4};
int n = sizeof(arr) / sizeof(int);
if (checkSortedandRotated(arr, n)) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
return 0;
}
Running the above code will generate the output as,
True
Since the given array [5, 6, 7, 1, 2, 3, 4] is sorted and rotated from the 3rd position, we get the output as 'True' in this case.
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Given an array of integers, the task is to check if the array is sorted (increasing order) and rotated after some number of position or not."
},
{
"code": null,
"e": 1215,
"s": 1203,
"text": "For Example"
},
{
"code": null,
"e": 1224,
"s": 1215,
"text": "Input-1:"
},
{
"code": null,
"e": 1247,
"s": 1224,
"text": "N = [7, 8, 9, 4, 5, 6]"
},
{
"code": null,
"e": 1255,
"s": 1247,
"text": "Output:"
},
{
"code": null,
"e": 1260,
"s": 1255,
"text": "True"
},
{
"code": null,
"e": 1405,
"s": 1260,
"text": "Explanation: Since the given array is in increasing order and the elements after the 3rd position are rotated, we will return True in this case."
},
{
"code": null,
"e": 1414,
"s": 1405,
"text": "Input-2:"
},
{
"code": null,
"e": 1437,
"s": 1414,
"text": "N = [1, 5, 7, 6, 2, 3]"
},
{
"code": null,
"e": 1445,
"s": 1437,
"text": "Output:"
},
{
"code": null,
"e": 1451,
"s": 1445,
"text": "False"
},
{
"code": null,
"e": 1579,
"s": 1451,
"text": "Explanation: Since the given array is neither in increasing order nor rotated with some specific position, the output is False."
},
{
"code": null,
"e": 1761,
"s": 1579,
"text": "We have an array with the element either in increasing order or unsorted. If the array has to be sorted and rotated, then at least one element will be there such that N[i] > N[i+1]."
},
{
"code": null,
"e": 1891,
"s": 1761,
"text": "Thus, for every N[i], we will count if there lies any element which satisfies the condition and return True or False accordingly."
},
{
"code": null,
"e": 1923,
"s": 1891,
"text": "Take Input of an array element."
},
{
"code": null,
"e": 2091,
"s": 1923,
"text": "A Boolean function checkSortedandRotated(int *arr, int n) takes an array and its size as the input and returns true if the array is sorted and rotated otherwise false."
},
{
"code": null,
"e": 2249,
"s": 2091,
"text": "Iterate over the whole array and count the number of elements which are (arr[i] > arr[i+1]%n). If the count is '1', then return True, otherwise return False."
},
{
"code": null,
"e": 2268,
"s": 2249,
"text": "Return the output."
},
{
"code": null,
"e": 2278,
"s": 2268,
"text": "Live Demo"
},
{
"code": null,
"e": 2724,
"s": 2278,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nbool checkSortedandRotated(int * arr, int n) {\n int count = 0;\n for (int i = 0; i < n; i++) {\n if (arr[i] > arr[(i + 1) % n])\n count++;\n }\n return (count <= 1);\n}\nint main() {\n int arr[] = {5,6,7,1,2,3,4};\n int n = sizeof(arr) / sizeof(int);\n if (checkSortedandRotated(arr, n)) {\n cout << \"True\" << endl;\n } else {\n cout << \"False\" << endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2776,
"s": 2724,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 2781,
"s": 2776,
"text": "True"
},
{
"code": null,
"e": 2912,
"s": 2781,
"text": "Since the given array [5, 6, 7, 1, 2, 3, 4] is sorted and rotated from the 3rd position, we get the output as 'True' in this case."
}
] |
How to Install Packages in Python on MacOS? - GeeksforGeeks
|
16 Oct, 2021
To get started with using pip, you should install Python on your system. Make sure that you have a working pip.
Follow the below steps to install python packages on MacOS:
Step 1: As the first step, you should check that you have a working Python with pip installed. This can be done by running the following commands and the output will be similar to like this:
$ python --version
Python 3.N.N
$ python -m pip --version
pip X.Y.Z from ... (python 3.N.N
If the output looks like this, You have a working pip in your environment.
If your output doesn’t look like this then refer to this pip document. It provides guidance on how to install pip within a Python environment that doesn’t have it.
Step 2: To install a package, run the following commands in the terminal:
python -m pip install SomePackage # latest version
python -m pip install SomePackage==1.0.4 # specific version
python -m pip install 'SomePackage>=1.0.4' # minimum version
Note: replace the SomePackage with the package name which you want to install.
By default, pip will fetch packages from Python Package Index, a repository of software for the Python programming language where anyone can upload packages.
Run the following commands:
$ python -m pip install git+https://github.com/pypa/SomePackage.git@main
[...]
Successfully installed SomePackage
Use the below command to upgrade an installed package:
$ python -m pip install --upgrade SomePackage
Uninstalling SomePackage:
[...]
Proceed (y/n)? y
Successfully uninstalled SomePackage
To uninstall a Python package use the below command:
python -m pip uninstall SomePackage
Note: replace the SomePackage with the package name which you want to install.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Recover a Deleted File in Linux?
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 24509,
"s": 24481,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 24621,
"s": 24509,
"text": "To get started with using pip, you should install Python on your system. Make sure that you have a working pip."
},
{
"code": null,
"e": 24681,
"s": 24621,
"text": "Follow the below steps to install python packages on MacOS:"
},
{
"code": null,
"e": 24872,
"s": 24681,
"text": "Step 1: As the first step, you should check that you have a working Python with pip installed. This can be done by running the following commands and the output will be similar to like this:"
},
{
"code": null,
"e": 24963,
"s": 24872,
"text": "$ python --version\nPython 3.N.N\n$ python -m pip --version\npip X.Y.Z from ... (python 3.N.N"
},
{
"code": null,
"e": 25038,
"s": 24963,
"text": "If the output looks like this, You have a working pip in your environment."
},
{
"code": null,
"e": 25203,
"s": 25038,
"text": "If your output doesn’t look like this then refer to this pip document. It provides guidance on how to install pip within a Python environment that doesn’t have it."
},
{
"code": null,
"e": 25277,
"s": 25203,
"text": "Step 2: To install a package, run the following commands in the terminal:"
},
{
"code": null,
"e": 25468,
"s": 25277,
"text": "python -m pip install SomePackage # latest version\npython -m pip install SomePackage==1.0.4 # specific version\npython -m pip install 'SomePackage>=1.0.4' # minimum version"
},
{
"code": null,
"e": 25547,
"s": 25468,
"text": "Note: replace the SomePackage with the package name which you want to install."
},
{
"code": null,
"e": 25705,
"s": 25547,
"text": "By default, pip will fetch packages from Python Package Index, a repository of software for the Python programming language where anyone can upload packages."
},
{
"code": null,
"e": 25733,
"s": 25705,
"text": "Run the following commands:"
},
{
"code": null,
"e": 25847,
"s": 25733,
"text": "$ python -m pip install git+https://github.com/pypa/SomePackage.git@main\n[...]\nSuccessfully installed SomePackage"
},
{
"code": null,
"e": 25902,
"s": 25847,
"text": "Use the below command to upgrade an installed package:"
},
{
"code": null,
"e": 26036,
"s": 25902,
"text": "$ python -m pip install --upgrade SomePackage\nUninstalling SomePackage:\n [...]\nProceed (y/n)? y\nSuccessfully uninstalled SomePackage"
},
{
"code": null,
"e": 26089,
"s": 26036,
"text": "To uninstall a Python package use the below command:"
},
{
"code": null,
"e": 26125,
"s": 26089,
"text": "python -m pip uninstall SomePackage"
},
{
"code": null,
"e": 26204,
"s": 26125,
"text": "Note: replace the SomePackage with the package name which you want to install."
},
{
"code": null,
"e": 26219,
"s": 26204,
"text": "how-to-install"
},
{
"code": null,
"e": 26226,
"s": 26219,
"text": "Picked"
},
{
"code": null,
"e": 26233,
"s": 26226,
"text": "How To"
},
{
"code": null,
"e": 26252,
"s": 26233,
"text": "Installation Guide"
},
{
"code": null,
"e": 26350,
"s": 26252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26359,
"s": 26350,
"text": "Comments"
},
{
"code": null,
"e": 26372,
"s": 26359,
"text": "Old Comments"
},
{
"code": null,
"e": 26406,
"s": 26372,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26455,
"s": 26406,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 26513,
"s": 26455,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 26553,
"s": 26513,
"text": "How to Recover a Deleted File in Linux?"
},
{
"code": null,
"e": 26595,
"s": 26553,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 26628,
"s": 26595,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26662,
"s": 26628,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26697,
"s": 26662,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 26755,
"s": 26697,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
EJB - Create Application
|
To create a simple EJB module, we will use NetBeans, "New project" wizard. In the example given below, We will create an EJB module project named Component.
In NetBeans IDE, select File > New Project >. You will see the following screen
Select project type under category Java EE, Project type as EJB Module. Click Next > button. You will see the following screen.
Enter project name and location. Click Next > button. You will see the following screen.
Select Server as JBoss Application Server. Click Finish button. You will see the following project created by NetBeans.
To create a simple EJB, we will use NetBeans "New" wizard. In the example given below, We will create a stateless EJB class named librarySessionBean under EjbComponent project.
Select project EjbComponent in project explorer window and right click on it. Select, New > Session Bean. You will see the New Session Bean wizard.
Enter session bean name and package name. Click Finish button. You will see the following EJB classes created by NetBeans.
LibrarySessionBean − stateless session bean
LibrarySessionBean − stateless session bean
LibrarySessionBeanLocal − local interface for session bean
LibrarySessionBeanLocal − local interface for session bean
I am changing local interface to remote interface as we are going to access our EJB in a console based application. Remote/Local interface is used to expose business methods that an EJB has to implement.
LibrarySessionBeanLocal is renamed to LibrarySessionBeanRemote and LibrarySessionBean implements LibrarySessionBeanRemote interface.
package com.tutorialspoint.stateless;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface LibrarySessionBeanRemote {
void addBook(String bookName);
List getBooks();
}
package com.tutorialspoint.stateless;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
@Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {
List<String> bookShelf;
public LibrarySessionBean() {
bookShelf = new ArrayList<String>();
}
public void addBook(String bookName) {
bookShelf.add(bookName);
}
public List<String> getBooks() {
return bookShelf;
}
}
Select EjbComponent project in Project Explorer window.
Right click on it to open context menu.
Select clean and build.
You will see the following output in NetBeans console output.
ant -f C:\\EJB\\EjbComponent clean dist
init:
undeploy-clean:
deps-clean:
Deleting directory C:\EJB\EjbComponent\build
Deleting directory C:\EJB\EjbComponent\dist
clean:
init:
deps-jar:
Created dir: C:\EJB\EjbComponent\build\classes
Copying 3 files to C:\EJB\EjbComponent\build\classes\META-INF
Created dir: C:\EJB\EjbComponent\build\empty
Created dir: C:\EJB\EjbComponent\build\generated-sources\ap-source-output
Compiling 2 source files to C:\EJB\EjbComponent\build\classes
warning: [options] bootstrap class path not set in conjunction with -source 1.6
Note: C:\EJB\EjbComponent\src\java\com\tutorialspoint\stateless
\LibraryPersistentBean.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 warning
compile:
library-inclusion-in-archive:
Created dir: C:\EJB\EjbComponent\dist
Building jar: C:\EJB\EjbComponent\dist\EjbComponent.jar
dist:
BUILD SUCCESSFUL (total time: 3 seconds)
Select JBoss application server under Servers in Services window.
Right click on it to open context menu.
Select start.
You will see the following output in NetBeans, output under JBoss Application Server.
Calling C:\jboss-5.1.0.GA\bin\run.conf.bat
=========================================================================
JBoss Bootstrap Environment
JBOSS_HOME: C:\jboss-5.1.0.GA
JAVA: C:\Program Files (x86)\Java\jdk1.6.0_21\bin\java
JAVA_OPTS: -Dprogram.name=run.bat -Xms128m -Xmx512m -server
CLASSPATH: C:\jboss-5.1.0.GA\bin\run.jar
=========================================================================
16:25:50,062 INFO [ServerImpl] Starting JBoss (Microcontainer)...
16:25:50,062 INFO [ServerImpl] Release ID: JBoss
[The Oracle] 5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)
...
16:26:40,420 INFO [TomcatDeployment] deploy, ctxPath=/admin-console
16:26:40,485 INFO [config] Initializing Mojarra (1.2_12-b01-FCS) for context '/admin-console'
16:26:42,362 INFO [TomcatDeployment] deploy, ctxPath=/
16:26:42,406 INFO [TomcatDeployment] deploy, ctxPath=/jmx-console
16:26:42,471 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8080
16:26:42,487 INFO [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009
16:26:42,493 INFO [ServerImpl] JBoss (Microcontainer)
[5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 52s:427ms
Select EjbComponent project in Project Explorer window.
Right click on it to open context menu.
Select Deploy.
You will see the following output in NetBeans console output.
ant -f C:\\EJB\\EjbComponent -DforceRedeploy=true -Ddirectory.deployment.supported=false -Dnb.wait.for.caches=true run
init:
deps-jar:
compile:
library-inclusion-in-archive:
Building jar: C:\EJB\EjbComponent\dist\EjbComponent.jar
dist-directory-deploy:
pre-run-deploy:
Checking data source definitions for missing JDBC drivers...
Distributing C:\EJB\EjbComponent\dist\EjbComponent.jar to [org.jboss.deployment.spi.LocalhostTarget@1e4f84ee]
Deploying C:\EJB\EjbComponent\dist\EjbComponent.jar
Application Deployed
Operation start started
Operation start completed
post-run-deploy:
run-deploy:
run:
BUILD SUCCESSFUL (total time: 2 seconds)
16:30:00,963 INFO [DeployHandler] Begin start, [EjbComponent.jar]
...
16:30:01,233 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@12038795{vfszip:/C:/jboss-5.1.0.GA/server/default/deploy/EjbComponent.jar/}
...
16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO [JBossASKernel] Class:com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote
16:30:01,281 INFO [JBossASKernel] Added bean(jboss.j2ee:jar=EjbComponent.jar,name=
LibrarySessionBean,service=EJB3) to KernelDeployment of: EjbComponent.jar
16:30:01,282 INFO [JBossASKernel] installing bean: jboss.j2ee:jar=EjbComponent.jar,name=BookMessageHandler,service=EJB3
16:30:01,282 INFO [JBossASKernel] with dependencies:
16:30:01,282 INFO [JBossASKernel] and demands:
16:30:01,282 INFO [JBossASKernel] jboss.ejb:service=EJBTimerService
...
16:30:01,283 INFO [EJB3EndpointDeployer] Deploy
AbstractBeanMetaData@5497cb{name=jboss.j2ee:jar=EjbComponent.jar,
name=LibrarySessionBean, service=EJB3_endpoint bean=org.jboss.ejb3.endpoint.deployers.impl.EndpointImpl properties=[container] constructor=null autowireCandidate=true}
...
16:30:01,394 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:01,395 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
In NetBeans IDE, select File > New Project >.
In NetBeans IDE, select File > New Project >.
Select project type under category Java, Project type as Java Application. Click Next > button
Select project type under category Java, Project type as Java Application. Click Next > button
Enter project name and location. Click Finish > button. We have chosen name as EjbTester.
Enter project name and location. Click Finish > button. We have chosen name as EjbTester.
Right click on project name in Project explorer window. Select properties.
Right click on project name in Project explorer window. Select properties.
Add EJB component project created earlier under libraries using Add Project button in compile tab.
Add EJB component project created earlier under libraries using Add Project button in compile tab.
Add jboss libraries using Add jar/folder button in compile tab. Jboss libraries can be located at <jboss installation folder>> client folder.
Add jboss libraries using Add jar/folder button in compile tab. Jboss libraries can be located at <jboss installation folder>> client folder.
Create jndi.properties under project say EjbTester.
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
Create package com.tutorialspoint.test and EJBTester.java class under it.
package com.tutorialspoint.test;
import com.tutorialspoint.stateless.LibrarySessionBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTester {
BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
try {
props.load(new FileInputStream("jndi.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTester ejbTester = new EJBTester();
ejbTester.testStatelessEjb();
}
private void showGUI() {
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testStatelessEjb() {
try {
int choice = 1;
LibrarySessionBeanRemote libraryBean =
(LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
while (choice != 2) {
String bookName;
showGUI();
String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enter book name: ");
bookName = brConsoleReader.readLine();
libraryBean.addBook(bookName);
}else if (choice == 2) {
break;
}
}
List<String> booksList = libraryBean.getBooks();
System.out.println("Book(s) entered so far: " + booksList.size());
for (int i = 0; i < booksList.size(); ++i) {
System.out.println((i+1)+". " + booksList.get(i));
}
LibrarySessionBeanRemote libraryBean1 =
(LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
List<String> booksList1 = libraryBean1.getBooks();
System.out.println(
"***Using second lookup to get library stateless object***");
System.out.println(
"Book(s) entered so far: " + booksList1.size());
for (int i = 0; i < booksList1.size(); ++i) {
System.out.println((i+1)+". " + booksList1.get(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
try {
if(brConsoleReader !=null) {
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file.
Verify the following output in Netbeans console.
run:
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 1
Enter book name: Learn Java
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 1
1. Learn Java
***Using second lookup to get library stateless object***
Book(s) entered so far: 0
BUILD SUCCESSFUL (total time: 13 seconds)
In the following chapters, we will cover multiple aspects of this complete EJB application.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2204,
"s": 2047,
"text": "To create a simple EJB module, we will use NetBeans, \"New project\" wizard. In the example given below, We will create an EJB module project named Component."
},
{
"code": null,
"e": 2284,
"s": 2204,
"text": "In NetBeans IDE, select File > New Project >. You will see the following screen"
},
{
"code": null,
"e": 2412,
"s": 2284,
"text": "Select project type under category Java EE, Project type as EJB Module. Click Next > button. You will see the following screen."
},
{
"code": null,
"e": 2501,
"s": 2412,
"text": "Enter project name and location. Click Next > button. You will see the following screen."
},
{
"code": null,
"e": 2621,
"s": 2501,
"text": "Select Server as JBoss Application Server. Click Finish button. You will see the following project created by NetBeans."
},
{
"code": null,
"e": 2798,
"s": 2621,
"text": "To create a simple EJB, we will use NetBeans \"New\" wizard. In the example given below, We will create a stateless EJB class named librarySessionBean under EjbComponent project."
},
{
"code": null,
"e": 2946,
"s": 2798,
"text": "Select project EjbComponent in project explorer window and right click on it. Select, New > Session Bean. You will see the New Session Bean wizard."
},
{
"code": null,
"e": 3069,
"s": 2946,
"text": "Enter session bean name and package name. Click Finish button. You will see the following EJB classes created by NetBeans."
},
{
"code": null,
"e": 3113,
"s": 3069,
"text": "LibrarySessionBean − stateless session bean"
},
{
"code": null,
"e": 3157,
"s": 3113,
"text": "LibrarySessionBean − stateless session bean"
},
{
"code": null,
"e": 3216,
"s": 3157,
"text": "LibrarySessionBeanLocal − local interface for session bean"
},
{
"code": null,
"e": 3275,
"s": 3216,
"text": "LibrarySessionBeanLocal − local interface for session bean"
},
{
"code": null,
"e": 3479,
"s": 3275,
"text": "I am changing local interface to remote interface as we are going to access our EJB in a console based application. Remote/Local interface is used to expose business methods that an EJB has to implement."
},
{
"code": null,
"e": 3612,
"s": 3479,
"text": "LibrarySessionBeanLocal is renamed to LibrarySessionBeanRemote and LibrarySessionBean implements LibrarySessionBeanRemote interface."
},
{
"code": null,
"e": 3810,
"s": 3612,
"text": "package com.tutorialspoint.stateless;\n \nimport java.util.List;\nimport javax.ejb.Remote;\n \n@Remote\npublic interface LibrarySessionBeanRemote {\n void addBook(String bookName);\n List getBooks();\n}"
},
{
"code": null,
"e": 4288,
"s": 3810,
"text": "package com.tutorialspoint.stateless;\n \nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.ejb.Stateless;\n \n@Stateless\npublic class LibrarySessionBean implements LibrarySessionBeanRemote {\n \n List<String> bookShelf; \n \n public LibrarySessionBean() {\n bookShelf = new ArrayList<String>();\n }\n \n public void addBook(String bookName) {\n bookShelf.add(bookName);\n } \n \n public List<String> getBooks() {\n return bookShelf;\n }\n}"
},
{
"code": null,
"e": 4344,
"s": 4288,
"text": "Select EjbComponent project in Project Explorer window."
},
{
"code": null,
"e": 4384,
"s": 4344,
"text": "Right click on it to open context menu."
},
{
"code": null,
"e": 4408,
"s": 4384,
"text": "Select clean and build."
},
{
"code": null,
"e": 4470,
"s": 4408,
"text": "You will see the following output in NetBeans console output."
},
{
"code": null,
"e": 5397,
"s": 4470,
"text": "ant -f C:\\\\EJB\\\\EjbComponent clean dist\ninit:\nundeploy-clean:\ndeps-clean:\nDeleting directory C:\\EJB\\EjbComponent\\build\nDeleting directory C:\\EJB\\EjbComponent\\dist\nclean:\ninit:\ndeps-jar:\nCreated dir: C:\\EJB\\EjbComponent\\build\\classes\nCopying 3 files to C:\\EJB\\EjbComponent\\build\\classes\\META-INF\nCreated dir: C:\\EJB\\EjbComponent\\build\\empty\nCreated dir: C:\\EJB\\EjbComponent\\build\\generated-sources\\ap-source-output\nCompiling 2 source files to C:\\EJB\\EjbComponent\\build\\classes\nwarning: [options] bootstrap class path not set in conjunction with -source 1.6\nNote: C:\\EJB\\EjbComponent\\src\\java\\com\\tutorialspoint\\stateless\n\\LibraryPersistentBean.java uses unchecked or unsafe operations.\nNote: Recompile with -Xlint:unchecked for details.\n1 warning\ncompile:\nlibrary-inclusion-in-archive:\nCreated dir: C:\\EJB\\EjbComponent\\dist\nBuilding jar: C:\\EJB\\EjbComponent\\dist\\EjbComponent.jar\ndist:\nBUILD SUCCESSFUL (total time: 3 seconds)\n"
},
{
"code": null,
"e": 5463,
"s": 5397,
"text": "Select JBoss application server under Servers in Services window."
},
{
"code": null,
"e": 5503,
"s": 5463,
"text": "Right click on it to open context menu."
},
{
"code": null,
"e": 5517,
"s": 5503,
"text": "Select start."
},
{
"code": null,
"e": 5603,
"s": 5517,
"text": "You will see the following output in NetBeans, output under JBoss Application Server."
},
{
"code": null,
"e": 6826,
"s": 5603,
"text": "Calling C:\\jboss-5.1.0.GA\\bin\\run.conf.bat\n=========================================================================\n \n JBoss Bootstrap Environment\n \n JBOSS_HOME: C:\\jboss-5.1.0.GA\n \n JAVA: C:\\Program Files (x86)\\Java\\jdk1.6.0_21\\bin\\java\n \n JAVA_OPTS: -Dprogram.name=run.bat -Xms128m -Xmx512m -server\n \n CLASSPATH: C:\\jboss-5.1.0.GA\\bin\\run.jar\n \n=========================================================================\n \n16:25:50,062 INFO [ServerImpl] Starting JBoss (Microcontainer)...\n16:25:50,062 INFO [ServerImpl] Release ID: JBoss \n [The Oracle] 5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)\n...\n \n16:26:40,420 INFO [TomcatDeployment] deploy, ctxPath=/admin-console\n16:26:40,485 INFO [config] Initializing Mojarra (1.2_12-b01-FCS) for context '/admin-console'\n16:26:42,362 INFO [TomcatDeployment] deploy, ctxPath=/\n16:26:42,406 INFO [TomcatDeployment] deploy, ctxPath=/jmx-console\n16:26:42,471 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8080\n16:26:42,487 INFO [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009\n16:26:42,493 INFO [ServerImpl] JBoss (Microcontainer) \n [5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 52s:427ms\n"
},
{
"code": null,
"e": 6882,
"s": 6826,
"text": "Select EjbComponent project in Project Explorer window."
},
{
"code": null,
"e": 6922,
"s": 6882,
"text": "Right click on it to open context menu."
},
{
"code": null,
"e": 6937,
"s": 6922,
"text": "Select Deploy."
},
{
"code": null,
"e": 6999,
"s": 6937,
"text": "You will see the following output in NetBeans console output."
},
{
"code": null,
"e": 7638,
"s": 6999,
"text": "ant -f C:\\\\EJB\\\\EjbComponent -DforceRedeploy=true -Ddirectory.deployment.supported=false -Dnb.wait.for.caches=true run\ninit:\ndeps-jar:\ncompile:\nlibrary-inclusion-in-archive:\nBuilding jar: C:\\EJB\\EjbComponent\\dist\\EjbComponent.jar\ndist-directory-deploy:\npre-run-deploy:\nChecking data source definitions for missing JDBC drivers...\nDistributing C:\\EJB\\EjbComponent\\dist\\EjbComponent.jar to [org.jboss.deployment.spi.LocalhostTarget@1e4f84ee]\nDeploying C:\\EJB\\EjbComponent\\dist\\EjbComponent.jar\nApplication Deployed\nOperation start started\nOperation start completed\npost-run-deploy:\nrun-deploy:\nrun:\nBUILD SUCCESSFUL (total time: 2 seconds)\n"
},
{
"code": null,
"e": 9981,
"s": 7638,
"text": "16:30:00,963 INFO [DeployHandler] Begin start, [EjbComponent.jar]\n...\n16:30:01,233 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@12038795{vfszip:/C:/jboss-5.1.0.GA/server/default/deploy/EjbComponent.jar/}\n...\n16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote\n16:30:01,281 INFO [JBossASKernel] Class:com.tutorialspoint.stateless.LibrarySessionBeanRemote\n16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote\n16:30:01,281 INFO [JBossASKernel] Added bean(jboss.j2ee:jar=EjbComponent.jar,name=\nLibrarySessionBean,service=EJB3) to KernelDeployment of: EjbComponent.jar\n16:30:01,282 INFO [JBossASKernel] installing bean: jboss.j2ee:jar=EjbComponent.jar,name=BookMessageHandler,service=EJB3\n16:30:01,282 INFO [JBossASKernel] with dependencies:\n16:30:01,282 INFO [JBossASKernel] and demands:\n16:30:01,282 INFO [JBossASKernel] jboss.ejb:service=EJBTimerService\n...\n16:30:01,283 INFO [EJB3EndpointDeployer] Deploy \nAbstractBeanMetaData@5497cb{name=jboss.j2ee:jar=EjbComponent.jar, \nname=LibrarySessionBean, service=EJB3_endpoint bean=org.jboss.ejb3.endpoint.deployers.impl.EndpointImpl properties=[container] constructor=null autowireCandidate=true}\n...\n16:30:01,394 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3\n16:30:01,395 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean\n16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n LibrarySessionBean/remote - EJB3.x Default Remote Business Interface\n LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean\n16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n \n LibrarySessionBean/remote - EJB3.x Default Remote Business Interface\n LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface\n"
},
{
"code": null,
"e": 10027,
"s": 9981,
"text": "In NetBeans IDE, select File > New Project >."
},
{
"code": null,
"e": 10073,
"s": 10027,
"text": "In NetBeans IDE, select File > New Project >."
},
{
"code": null,
"e": 10168,
"s": 10073,
"text": "Select project type under category Java, Project type as Java Application. Click Next > button"
},
{
"code": null,
"e": 10263,
"s": 10168,
"text": "Select project type under category Java, Project type as Java Application. Click Next > button"
},
{
"code": null,
"e": 10353,
"s": 10263,
"text": "Enter project name and location. Click Finish > button. We have chosen name as EjbTester."
},
{
"code": null,
"e": 10443,
"s": 10353,
"text": "Enter project name and location. Click Finish > button. We have chosen name as EjbTester."
},
{
"code": null,
"e": 10518,
"s": 10443,
"text": "Right click on project name in Project explorer window. Select properties."
},
{
"code": null,
"e": 10593,
"s": 10518,
"text": "Right click on project name in Project explorer window. Select properties."
},
{
"code": null,
"e": 10692,
"s": 10593,
"text": "Add EJB component project created earlier under libraries using Add Project button in compile tab."
},
{
"code": null,
"e": 10791,
"s": 10692,
"text": "Add EJB component project created earlier under libraries using Add Project button in compile tab."
},
{
"code": null,
"e": 10933,
"s": 10791,
"text": "Add jboss libraries using Add jar/folder button in compile tab. Jboss libraries can be located at <jboss installation folder>> client folder."
},
{
"code": null,
"e": 11075,
"s": 10933,
"text": "Add jboss libraries using Add jar/folder button in compile tab. Jboss libraries can be located at <jboss installation folder>> client folder."
},
{
"code": null,
"e": 11127,
"s": 11075,
"text": "Create jndi.properties under project say EjbTester."
},
{
"code": null,
"e": 11295,
"s": 11127,
"text": "java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\njava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces\njava.naming.provider.url=localhost"
},
{
"code": null,
"e": 11369,
"s": 11295,
"text": "Create package com.tutorialspoint.test and EJBTester.java class under it."
},
{
"code": null,
"e": 14451,
"s": 11369,
"text": "package com.tutorialspoint.test;\n \nimport com.tutorialspoint.stateless.LibrarySessionBeanRemote;\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.List;\nimport java.util.Properties;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n \n \npublic class EJBTester {\n BufferedReader brConsoleReader = null; \n Properties props;\n InitialContext ctx;\n {\n props = new Properties();\n try {\n props.load(new FileInputStream(\"jndi.properties\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n try {\n ctx = new InitialContext(props); \n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n brConsoleReader = \n new BufferedReader(new InputStreamReader(System.in));\n }\n public static void main(String[] args) {\n \n EJBTester ejbTester = new EJBTester();\n \n ejbTester.testStatelessEjb();\n }\n private void showGUI() {\n System.out.println(\"**********************\");\n System.out.println(\"Welcome to Book Store\");\n System.out.println(\"**********************\");\n System.out.print(\"Options \\n1. Add Book\\n2. Exit \\nEnter Choice: \");\n }\n private void testStatelessEjb() {\n try {\n int choice = 1; \n LibrarySessionBeanRemote libraryBean = \n (LibrarySessionBeanRemote)ctx.lookup(\"LibrarySessionBean/remote\");\n while (choice != 2) {\n String bookName;\n showGUI();\n String strChoice = brConsoleReader.readLine();\n choice = Integer.parseInt(strChoice);\n if (choice == 1) {\n System.out.print(\"Enter book name: \");\n bookName = brConsoleReader.readLine(); \n libraryBean.addBook(bookName); \n }else if (choice == 2) {\n break;\n }\n }\n List<String> booksList = libraryBean.getBooks();\n System.out.println(\"Book(s) entered so far: \" + booksList.size());\n for (int i = 0; i < booksList.size(); ++i) {\n System.out.println((i+1)+\". \" + booksList.get(i));\n }\n LibrarySessionBeanRemote libraryBean1 = \n (LibrarySessionBeanRemote)ctx.lookup(\"LibrarySessionBean/remote\");\n List<String> booksList1 = libraryBean1.getBooks();\n System.out.println(\n \"***Using second lookup to get library stateless object***\");\n System.out.println(\n \"Book(s) entered so far: \" + booksList1.size());\n for (int i = 0; i < booksList1.size(); ++i) {\n System.out.println((i+1)+\". \" + booksList1.get(i));\n }\n } catch (Exception e) {\n System.out.println(e.getMessage());\n e.printStackTrace();\n } finally {\n try {\n if(brConsoleReader !=null) {\n brConsoleReader.close();\n }\n } catch (IOException ex) {\n System.out.println(ex.getMessage());\n }\n }\n } \n}"
},
{
"code": null,
"e": 14546,
"s": 14451,
"text": "Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file."
},
{
"code": null,
"e": 14595,
"s": 14546,
"text": "Verify the following output in Netbeans console."
},
{
"code": null,
"e": 15023,
"s": 14595,
"text": "run:\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 1\nEnter book name: Learn Java\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 2\nBook(s) entered so far: 1\n1. Learn Java\n***Using second lookup to get library stateless object***\nBook(s) entered so far: 0\nBUILD SUCCESSFUL (total time: 13 seconds)\n"
},
{
"code": null,
"e": 15115,
"s": 15023,
"text": "In the following chapters, we will cover multiple aspects of this complete EJB application."
},
{
"code": null,
"e": 15122,
"s": 15115,
"text": " Print"
},
{
"code": null,
"e": 15133,
"s": 15122,
"text": " Add Notes"
}
] |
Possible to form a triangle from array values in C++
|
In this problem, we are given an array of integers. Our task is to check if the creation of a non-degenerate triangle taking the elements of the array as sides of the triangle.
Non-degenerate triangle − it is a triangle that has a positive area. The condition for a non-degenerate triangle with sides a, b, c is −
a + b > c
a + c > b
b + c > a
Let’s take an example to understand the problem better −
Input − arr[2, 5 ,9, 4, 3]
Output − Yes
Explanation − the triangle formed is 2 3 4.
To solve this problem, we will check that the above condition is satisfied by the values of the array.
A navie solution will involve direct checking of every triplet of the array.
A more effective solution will involve sorting the array elements and the checking three consecutive triplets of the array. As for sorted array if the sum of two elements is not greater than the next one check values after that is not worthy (they are already large).
Program to show the implementation of our solution
Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isTrianglePossible(int arr[], int N){
if (N < 3)
return false;
sort(arr, arr + N);
for (int i = 0; i < N - 2; i++)
if (arr[i] + arr[i + 1] > arr[i + 2])
return true;
}
int main() {
int arr[] = {5, 12, 13, 65, 6, 1};
int N = sizeof(arr) / sizeof(int);
cout<<"Creation of triangle from elements of array ";
isTrianglePossible(arr, N)?cout<<"is Possible": cout<<"is not Possible";
return 0;
}
Creation of triangle from elements of array is Possible
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "In this problem, we are given an array of integers. Our task is to check if the creation of a non-degenerate triangle taking the elements of the array as sides of the triangle."
},
{
"code": null,
"e": 1376,
"s": 1239,
"text": "Non-degenerate triangle − it is a triangle that has a positive area. The condition for a non-degenerate triangle with sides a, b, c is −"
},
{
"code": null,
"e": 1406,
"s": 1376,
"text": "a + b > c\na + c > b\nb + c > a"
},
{
"code": null,
"e": 1463,
"s": 1406,
"text": "Let’s take an example to understand the problem better −"
},
{
"code": null,
"e": 1490,
"s": 1463,
"text": "Input − arr[2, 5 ,9, 4, 3]"
},
{
"code": null,
"e": 1503,
"s": 1490,
"text": "Output − Yes"
},
{
"code": null,
"e": 1547,
"s": 1503,
"text": "Explanation − the triangle formed is 2 3 4."
},
{
"code": null,
"e": 1650,
"s": 1547,
"text": "To solve this problem, we will check that the above condition is satisfied by the values of the array."
},
{
"code": null,
"e": 1727,
"s": 1650,
"text": "A navie solution will involve direct checking of every triplet of the array."
},
{
"code": null,
"e": 1995,
"s": 1727,
"text": "A more effective solution will involve sorting the array elements and the checking three consecutive triplets of the array. As for sorted array if the sum of two elements is not greater than the next one check values after that is not worthy (they are already large)."
},
{
"code": null,
"e": 2046,
"s": 1995,
"text": "Program to show the implementation of our solution"
},
{
"code": null,
"e": 2057,
"s": 2046,
"text": " Live Demo"
},
{
"code": null,
"e": 2543,
"s": 2057,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isTrianglePossible(int arr[], int N){\n if (N < 3)\n return false;\n sort(arr, arr + N);\n for (int i = 0; i < N - 2; i++)\n if (arr[i] + arr[i + 1] > arr[i + 2])\n return true;\n}\nint main() {\n int arr[] = {5, 12, 13, 65, 6, 1};\n int N = sizeof(arr) / sizeof(int);\n cout<<\"Creation of triangle from elements of array \";\n isTrianglePossible(arr, N)?cout<<\"is Possible\": cout<<\"is not Possible\";\n return 0;\n}"
},
{
"code": null,
"e": 2599,
"s": 2543,
"text": "Creation of triangle from elements of array is Possible"
}
] |
WSDL - <ports> Element
|
A <port> element defines an individual endpoint by specifying a single address for a binding.
Here is the grammar to specify a port −
<wsdl:definitions .... >
<wsdl:service .... > *
<wsdl:port name = "nmtoken" binding = "qname"> *
<-- extensibility element (1) -->
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
The port element has two attributes: name and binding .
The port element has two attributes: name and binding .
The name attribute provides a unique name among all ports defined within the enclosing WSDL document.
The name attribute provides a unique name among all ports defined within the enclosing WSDL document.
The binding attribute refers to the binding using the linking rules defined by WSDL.
The binding attribute refers to the binding using the linking rules defined by WSDL.
Binding extensibility elements are used to specify the address information for the port.
Binding extensibility elements are used to specify the address information for the port.
A port MUST NOT specify more than one address.
A port MUST NOT specify more than one address.
A port MUST NOT specify any binding information other than address information.
A port MUST NOT specify any binding information other than address information.
Here is a piece of code from the Example chapter −
<service name = "Hello_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding = "tns:Hello_Binding" name = "Hello_Port">
<soap:address
location = "http://www.examples.com/SayHello/">
</port>
</service>
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1898,
"s": 1804,
"text": "A <port> element defines an individual endpoint by specifying a single address for a binding."
},
{
"code": null,
"e": 1938,
"s": 1898,
"text": "Here is the grammar to specify a port −"
},
{
"code": null,
"e": 2145,
"s": 1938,
"text": "<wsdl:definitions .... >\n <wsdl:service .... > *\n <wsdl:port name = \"nmtoken\" binding = \"qname\"> *\n <-- extensibility element (1) -->\n </wsdl:port>\n </wsdl:service>\n</wsdl:definitions>"
},
{
"code": null,
"e": 2201,
"s": 2145,
"text": "The port element has two attributes: name and binding ."
},
{
"code": null,
"e": 2257,
"s": 2201,
"text": "The port element has two attributes: name and binding ."
},
{
"code": null,
"e": 2359,
"s": 2257,
"text": "The name attribute provides a unique name among all ports defined within the enclosing WSDL document."
},
{
"code": null,
"e": 2461,
"s": 2359,
"text": "The name attribute provides a unique name among all ports defined within the enclosing WSDL document."
},
{
"code": null,
"e": 2546,
"s": 2461,
"text": "The binding attribute refers to the binding using the linking rules defined by WSDL."
},
{
"code": null,
"e": 2631,
"s": 2546,
"text": "The binding attribute refers to the binding using the linking rules defined by WSDL."
},
{
"code": null,
"e": 2720,
"s": 2631,
"text": "Binding extensibility elements are used to specify the address information for the port."
},
{
"code": null,
"e": 2809,
"s": 2720,
"text": "Binding extensibility elements are used to specify the address information for the port."
},
{
"code": null,
"e": 2856,
"s": 2809,
"text": "A port MUST NOT specify more than one address."
},
{
"code": null,
"e": 2903,
"s": 2856,
"text": "A port MUST NOT specify more than one address."
},
{
"code": null,
"e": 2983,
"s": 2903,
"text": "A port MUST NOT specify any binding information other than address information."
},
{
"code": null,
"e": 3063,
"s": 2983,
"text": "A port MUST NOT specify any binding information other than address information."
},
{
"code": null,
"e": 3114,
"s": 3063,
"text": "Here is a piece of code from the Example chapter −"
},
{
"code": null,
"e": 3367,
"s": 3114,
"text": "<service name = \"Hello_Service\">\n <documentation>WSDL File for HelloService</documentation>\n <port binding = \"tns:Hello_Binding\" name = \"Hello_Port\">\n <soap:address\n location = \"http://www.examples.com/SayHello/\">\n </port>\n</service>"
},
{
"code": null,
"e": 3374,
"s": 3367,
"text": " Print"
},
{
"code": null,
"e": 3385,
"s": 3374,
"text": " Add Notes"
}
] |
Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values - GeeksforGeeks
|
25 Mar, 2022
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers.
Examples:
Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, then the possible value of A and B is 3 and 6 respectively. Therefore, (A | B) = (3 | 6) = 7.
Input: X = 14, Y = 1 Output: 15 Explanation: If A and B are two positive integers such that A ^ B = 14, A & B = 1, then the possible value of A and B is 7 and 9 respectively. Therefore, (A | B) = (7 | 9) = 15.
Naive Approach: The simplest approach to solve this problem is to iterate up to the maximum of X and Y, say N, and generate all possible pairs of the first N natural numbers. For each pair, check if Bitwise XOR and the Bitwise AND of the pair is X and Y, respectively, or not. If found to be true, then print the Bitwise OR of that pair.
Time Complexity: O(N2), where N = max(X, Y) Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the following observations:
(A ^ B) = (A | B) – (A & B) => (A | B) = (A ^ B) + (A & B) = X + Y
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate Bitwise OR from given// bitwise XOR and bitwise AND valuesint findBitwiseORGivenXORAND(int X, int Y) { return X + Y; } // Driver Codeint main(){ int X = 5, Y = 2; cout << findBitwiseORGivenXORAND(X, Y);}
// C program to implement// the above approach#include <stdio.h> // Function to calculate Bitwise OR from given// bitwise XOR and bitwise AND valuesint findBitwiseORGivenXORAND(int X, int Y){ return X + Y;} // Driver Codeint main(){ int X = 5, Y = 2; printf("%d\n", findBitwiseORGivenXORAND(X, Y));} // This code is contributed by phalashi.
// Java program to implement// the above approachclass GFG { // Function to calculate Bitwise OR from given // bitwise XOR and bitwise AND values static int findBitwiseORGivenXORAND(int X, int Y) { return X + Y; } // Driver Code public static void main(String[] args) { int X = 5, Y = 2; System.out.print(findBitwiseORGivenXORAND(X, Y)); }} // This code is contributed by AnkitRai01
# Python3 program to implement# the above approach # Function to calculate Bitwise OR from# given bitwise XOR and bitwise AND values def findBitwiseORGivenXORAND(X, Y): return X + Y # Driver Codeif __name__ == "__main__": X = 5 Y = 2 print(findBitwiseORGivenXORAND(X, Y)) # This code is contributed by AnkitRai01
// C# program to implement// the above approachusing System; class GFG { // Function to calculate Bitwise OR from given // bitwise XOR and bitwise AND values static int findBitwiseORGivenXORAND(int X, int Y) { return X + Y; } // Driver Code public static void Main(string[] args) { int X = 5, Y = 2; Console.Write(findBitwiseORGivenXORAND(X, Y)); }} // This code is contributed by ipg2016107
<script>// JavaScript program to implement// the above approach // Function to calculate Bitwise OR from given// bitwise XOR and bitwise AND valuesfunction findBitwiseORGivenXORAND(X, Y){ return X + Y;} // Driver Code let X = 5, Y = 2; document.write(findBitwiseORGivenXORAND(X, Y)); // This code is contributed by Surbhi Tyagi. </script>
7
Time Complexity: O(1) Auxiliary Space: O(1)
ankthon
ipg2016107
khushboogoyal499
surbhityagi15
phasing17
Bit Algorithms
Bitwise-AND
Bitwise-OR
Bitwise-XOR
Bit Magic
Greedy
Mathematical
Greedy
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Set, Clear and Toggle a given bit of a number in C
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": 25149,
"s": 25121,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 25322,
"s": 25149,
"text": "Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers."
},
{
"code": null,
"e": 25332,
"s": 25322,
"text": "Examples:"
},
{
"code": null,
"e": 25538,
"s": 25332,
"text": "Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, then the possible value of A and B is 3 and 6 respectively. Therefore, (A | B) = (3 | 6) = 7."
},
{
"code": null,
"e": 25748,
"s": 25538,
"text": "Input: X = 14, Y = 1 Output: 15 Explanation: If A and B are two positive integers such that A ^ B = 14, A & B = 1, then the possible value of A and B is 7 and 9 respectively. Therefore, (A | B) = (7 | 9) = 15."
},
{
"code": null,
"e": 26086,
"s": 25748,
"text": "Naive Approach: The simplest approach to solve this problem is to iterate up to the maximum of X and Y, say N, and generate all possible pairs of the first N natural numbers. For each pair, check if Bitwise XOR and the Bitwise AND of the pair is X and Y, respectively, or not. If found to be true, then print the Bitwise OR of that pair."
},
{
"code": null,
"e": 26152,
"s": 26086,
"text": "Time Complexity: O(N2), where N = max(X, Y) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26253,
"s": 26152,
"text": "Efficient Approach: To optimize the above approach, the idea is based on the following observations:"
},
{
"code": null,
"e": 26322,
"s": 26253,
"text": "(A ^ B) = (A | B) – (A & B) => (A | B) = (A ^ B) + (A & B) = X + Y "
},
{
"code": null,
"e": 26373,
"s": 26322,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26377,
"s": 26373,
"text": "C++"
},
{
"code": null,
"e": 26379,
"s": 26377,
"text": "C"
},
{
"code": null,
"e": 26384,
"s": 26379,
"text": "Java"
},
{
"code": null,
"e": 26392,
"s": 26384,
"text": "Python3"
},
{
"code": null,
"e": 26395,
"s": 26392,
"text": "C#"
},
{
"code": null,
"e": 26406,
"s": 26395,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate Bitwise OR from given// bitwise XOR and bitwise AND valuesint findBitwiseORGivenXORAND(int X, int Y) { return X + Y; } // Driver Codeint main(){ int X = 5, Y = 2; cout << findBitwiseORGivenXORAND(X, Y);}",
"e": 26735,
"s": 26406,
"text": null
},
{
"code": "// C program to implement// the above approach#include <stdio.h> // Function to calculate Bitwise OR from given// bitwise XOR and bitwise AND valuesint findBitwiseORGivenXORAND(int X, int Y){ return X + Y;} // Driver Codeint main(){ int X = 5, Y = 2; printf(\"%d\\n\", findBitwiseORGivenXORAND(X, Y));} // This code is contributed by phalashi.",
"e": 27083,
"s": 26735,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG { // Function to calculate Bitwise OR from given // bitwise XOR and bitwise AND values static int findBitwiseORGivenXORAND(int X, int Y) { return X + Y; } // Driver Code public static void main(String[] args) { int X = 5, Y = 2; System.out.print(findBitwiseORGivenXORAND(X, Y)); }} // This code is contributed by AnkitRai01",
"e": 27516,
"s": 27083,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to calculate Bitwise OR from# given bitwise XOR and bitwise AND values def findBitwiseORGivenXORAND(X, Y): return X + Y # Driver Codeif __name__ == \"__main__\": X = 5 Y = 2 print(findBitwiseORGivenXORAND(X, Y)) # This code is contributed by AnkitRai01",
"e": 27846,
"s": 27516,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG { // Function to calculate Bitwise OR from given // bitwise XOR and bitwise AND values static int findBitwiseORGivenXORAND(int X, int Y) { return X + Y; } // Driver Code public static void Main(string[] args) { int X = 5, Y = 2; Console.Write(findBitwiseORGivenXORAND(X, Y)); }} // This code is contributed by ipg2016107",
"e": 28289,
"s": 27846,
"text": null
},
{
"code": "<script>// JavaScript program to implement// the above approach // Function to calculate Bitwise OR from given// bitwise XOR and bitwise AND valuesfunction findBitwiseORGivenXORAND(X, Y){ return X + Y;} // Driver Code let X = 5, Y = 2; document.write(findBitwiseORGivenXORAND(X, Y)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 28638,
"s": 28289,
"text": null
},
{
"code": null,
"e": 28640,
"s": 28638,
"text": "7"
},
{
"code": null,
"e": 28686,
"s": 28642,
"text": "Time Complexity: O(1) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28694,
"s": 28686,
"text": "ankthon"
},
{
"code": null,
"e": 28705,
"s": 28694,
"text": "ipg2016107"
},
{
"code": null,
"e": 28722,
"s": 28705,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 28736,
"s": 28722,
"text": "surbhityagi15"
},
{
"code": null,
"e": 28746,
"s": 28736,
"text": "phasing17"
},
{
"code": null,
"e": 28761,
"s": 28746,
"text": "Bit Algorithms"
},
{
"code": null,
"e": 28773,
"s": 28761,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 28784,
"s": 28773,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 28796,
"s": 28784,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 28806,
"s": 28796,
"text": "Bit Magic"
},
{
"code": null,
"e": 28813,
"s": 28806,
"text": "Greedy"
},
{
"code": null,
"e": 28826,
"s": 28813,
"text": "Mathematical"
},
{
"code": null,
"e": 28833,
"s": 28826,
"text": "Greedy"
},
{
"code": null,
"e": 28846,
"s": 28833,
"text": "Mathematical"
},
{
"code": null,
"e": 28856,
"s": 28846,
"text": "Bit Magic"
},
{
"code": null,
"e": 28954,
"s": 28856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28963,
"s": 28954,
"text": "Comments"
},
{
"code": null,
"e": 28976,
"s": 28963,
"text": "Old Comments"
},
{
"code": null,
"e": 29022,
"s": 28976,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 29052,
"s": 29022,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 29105,
"s": 29052,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 29145,
"s": 29105,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 29196,
"s": 29145,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 29247,
"s": 29196,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 29305,
"s": 29247,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 29356,
"s": 29305,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 29383,
"s": 29356,
"text": "Program for array rotation"
}
] |
What is the difference between a python tuple and a dictionary?
|
They are very different data structures. Elements in a tuple have the following properties −
Order is maintained.
Order is maintained.
They are immutable
They are immutable
They can hold any type, and types can be mixed.
They can hold any type, and types can be mixed.
Elements are accessed via numeric (zero based) indices.
Elements are accessed via numeric (zero based) indices.
A Python dictionary is an implementation of a hash table. Elements of a dictionary have the following properties −
Ordering is not guaranteed
Ordering is not guaranteed
Every entry has a key and a value
Every entry has a key and a value
Elements are accessed using key's values
Elements are accessed using key's values
Entries in a dictionary can be changed.
Entries in a dictionary can be changed.
Key values can be of any hashable type (i.e. not a dict) and types can be mixed while values can be of any type (including other dict’s), and types can be mixed
Key values can be of any hashable type (i.e. not a dict) and types can be mixed while values can be of any type (including other dict’s), and types can be mixed
Both of these data structures can be created using comprehensions. Examples −
Tuple: (1, 'a', (3, 6, 8), 'string')
Dictionary: {'foo': [1, 2, 3], 'bar': 'baz'}
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "They are very different data structures. Elements in a tuple have the following properties −"
},
{
"code": null,
"e": 1176,
"s": 1155,
"text": "Order is maintained."
},
{
"code": null,
"e": 1197,
"s": 1176,
"text": "Order is maintained."
},
{
"code": null,
"e": 1216,
"s": 1197,
"text": "They are immutable"
},
{
"code": null,
"e": 1235,
"s": 1216,
"text": "They are immutable"
},
{
"code": null,
"e": 1283,
"s": 1235,
"text": "They can hold any type, and types can be mixed."
},
{
"code": null,
"e": 1331,
"s": 1283,
"text": "They can hold any type, and types can be mixed."
},
{
"code": null,
"e": 1387,
"s": 1331,
"text": "Elements are accessed via numeric (zero based) indices."
},
{
"code": null,
"e": 1443,
"s": 1387,
"text": "Elements are accessed via numeric (zero based) indices."
},
{
"code": null,
"e": 1558,
"s": 1443,
"text": "A Python dictionary is an implementation of a hash table. Elements of a dictionary have the following properties −"
},
{
"code": null,
"e": 1585,
"s": 1558,
"text": "Ordering is not guaranteed"
},
{
"code": null,
"e": 1612,
"s": 1585,
"text": "Ordering is not guaranteed"
},
{
"code": null,
"e": 1646,
"s": 1612,
"text": "Every entry has a key and a value"
},
{
"code": null,
"e": 1680,
"s": 1646,
"text": "Every entry has a key and a value"
},
{
"code": null,
"e": 1721,
"s": 1680,
"text": "Elements are accessed using key's values"
},
{
"code": null,
"e": 1762,
"s": 1721,
"text": "Elements are accessed using key's values"
},
{
"code": null,
"e": 1802,
"s": 1762,
"text": "Entries in a dictionary can be changed."
},
{
"code": null,
"e": 1842,
"s": 1802,
"text": "Entries in a dictionary can be changed."
},
{
"code": null,
"e": 2003,
"s": 1842,
"text": "Key values can be of any hashable type (i.e. not a dict) and types can be mixed while values can be of any type (including other dict’s), and types can be mixed"
},
{
"code": null,
"e": 2164,
"s": 2003,
"text": "Key values can be of any hashable type (i.e. not a dict) and types can be mixed while values can be of any type (including other dict’s), and types can be mixed"
},
{
"code": null,
"e": 2242,
"s": 2164,
"text": "Both of these data structures can be created using comprehensions. Examples −"
},
{
"code": null,
"e": 2324,
"s": 2242,
"text": "Tuple: (1, 'a', (3, 6, 8), 'string')\nDictionary: {'foo': [1, 2, 3], 'bar': 'baz'}"
}
] |
Go Arithmetic Operators
|
Arithmetic operators are used to perform common mathematical operations.
Multiply 10 with 5, and print the result.
package main
import ("fmt")
func main() {
fmt.Print(105)
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 73,
"s": 0,
"text": "Arithmetic operators are used to perform common mathematical operations."
},
{
"code": null,
"e": 115,
"s": 73,
"text": "Multiply 10 with 5, and print the result."
},
{
"code": null,
"e": 181,
"s": 115,
"text": "package main \nimport (\"fmt\") \nfunc main() {\n fmt.Print(105)\n}\n"
},
{
"code": null,
"e": 200,
"s": 181,
"text": "Start the Exercise"
},
{
"code": null,
"e": 233,
"s": 200,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 275,
"s": 233,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 382,
"s": 275,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 401,
"s": 382,
"text": "[email protected]"
}
] |
C# | Remove the element at the specified index of the ArrayList - GeeksforGeeks
|
01 Feb, 2019
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveAt(Int32) method is used to remove the element at the specified index of the ArrayList.
Properties:
Elements can be added or removed from the Array List collection at any point in time.
The ArrayList is not guaranteed to be sorted.
The capacity of an ArrayList is the number of elements the ArrayList can hold.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
It also allows duplicate elements.
Using multidimensional arrays as elements in an ArrayList collection is not supported.
Syntax:
public virtual void RemoveAt (int index);
Here, index is the zero-based index of the element to remove.
Exceptions:
ArgumentOutOfRangeException: If index is less than zero or index is equal to or greater than Count, where Count is number of elements in ArrayList.
NotSupportedException: If the ArrayList is read-only or the ArrayList has a fixed size.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to remove the element at// the specified index of ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); // Displaying the elements in ArrayList Console.WriteLine("The elements in ArrayList initially are :"); foreach(string str in myList) Console.WriteLine(str); // Removing the element present at index 4 myList.RemoveAt(4); // Displaying the elements in ArrayList Console.WriteLine("The elements in ArrayList are :"); foreach(string str in myList) Console.WriteLine(str); }}
Output:
The elements in ArrayList initially are:
A
B
C
D
E
F
The elements in ArrayList are:
A
B
C
D
F
Example 2:
// C# code to remove the element at// the specified index of ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(2); myList.Add(3); myList.Add(4); myList.Add(5); myList.Add(6); myList.Add(7); // Removing the element present at index 7 // It should raise System.ArgumentOutOfRangeException myList.RemoveAt(7); // Displaying the elements in ArrayList Console.WriteLine("The elements in ArrayList are :"); foreach(int i in myList) Console.WriteLine(i); }}
Output:
Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
Note:
This method is an O(n) operation, where n is Count.
After the element is removed, the size of the collection is adjusted and the value of the Count property is decreased by one.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.removeat?view=netframework-4.7.2
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Extension Method in C#
C# | Constructors
C# | Delegates
Introduction to .NET Framework
Difference between Ref and Out keywords in C#
C# | Data Types
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
|
[
{
"code": null,
"e": 24664,
"s": 24636,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24993,
"s": 24664,
"text": "ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveAt(Int32) method is used to remove the element at the specified index of the ArrayList."
},
{
"code": null,
"e": 25005,
"s": 24993,
"text": "Properties:"
},
{
"code": null,
"e": 25091,
"s": 25005,
"text": "Elements can be added or removed from the Array List collection at any point in time."
},
{
"code": null,
"e": 25137,
"s": 25091,
"text": "The ArrayList is not guaranteed to be sorted."
},
{
"code": null,
"e": 25216,
"s": 25137,
"text": "The capacity of an ArrayList is the number of elements the ArrayList can hold."
},
{
"code": null,
"e": 25327,
"s": 25216,
"text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based."
},
{
"code": null,
"e": 25362,
"s": 25327,
"text": "It also allows duplicate elements."
},
{
"code": null,
"e": 25449,
"s": 25362,
"text": "Using multidimensional arrays as elements in an ArrayList collection is not supported."
},
{
"code": null,
"e": 25457,
"s": 25449,
"text": "Syntax:"
},
{
"code": null,
"e": 25500,
"s": 25457,
"text": "public virtual void RemoveAt (int index);\n"
},
{
"code": null,
"e": 25562,
"s": 25500,
"text": "Here, index is the zero-based index of the element to remove."
},
{
"code": null,
"e": 25574,
"s": 25562,
"text": "Exceptions:"
},
{
"code": null,
"e": 25722,
"s": 25574,
"text": "ArgumentOutOfRangeException: If index is less than zero or index is equal to or greater than Count, where Count is number of elements in ArrayList."
},
{
"code": null,
"e": 25810,
"s": 25722,
"text": "NotSupportedException: If the ArrayList is read-only or the ArrayList has a fixed size."
},
{
"code": null,
"e": 25890,
"s": 25810,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 25901,
"s": 25890,
"text": "Example 1:"
},
{
"code": "// C# code to remove the element at// the specified index of ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(\"A\"); myList.Add(\"B\"); myList.Add(\"C\"); myList.Add(\"D\"); myList.Add(\"E\"); myList.Add(\"F\"); // Displaying the elements in ArrayList Console.WriteLine(\"The elements in ArrayList initially are :\"); foreach(string str in myList) Console.WriteLine(str); // Removing the element present at index 4 myList.RemoveAt(4); // Displaying the elements in ArrayList Console.WriteLine(\"The elements in ArrayList are :\"); foreach(string str in myList) Console.WriteLine(str); }}",
"e": 26804,
"s": 25901,
"text": null
},
{
"code": null,
"e": 26812,
"s": 26804,
"text": "Output:"
},
{
"code": null,
"e": 26907,
"s": 26812,
"text": "The elements in ArrayList initially are:\nA\nB\nC\nD\nE\nF\nThe elements in ArrayList are:\nA\nB\nC\nD\nF\n"
},
{
"code": null,
"e": 26918,
"s": 26907,
"text": "Example 2:"
},
{
"code": "// C# code to remove the element at// the specified index of ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(2); myList.Add(3); myList.Add(4); myList.Add(5); myList.Add(6); myList.Add(7); // Removing the element present at index 7 // It should raise System.ArgumentOutOfRangeException myList.RemoveAt(7); // Displaying the elements in ArrayList Console.WriteLine(\"The elements in ArrayList are :\"); foreach(int i in myList) Console.WriteLine(i); }}",
"e": 27669,
"s": 26918,
"text": null
},
{
"code": null,
"e": 27677,
"s": 27669,
"text": "Output:"
},
{
"code": null,
"e": 27841,
"s": 27677,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
},
{
"code": null,
"e": 27847,
"s": 27841,
"text": "Note:"
},
{
"code": null,
"e": 27899,
"s": 27847,
"text": "This method is an O(n) operation, where n is Count."
},
{
"code": null,
"e": 28025,
"s": 27899,
"text": "After the element is removed, the size of the collection is adjusted and the value of the Count property is decreased by one."
},
{
"code": null,
"e": 28036,
"s": 28025,
"text": "Reference:"
},
{
"code": null,
"e": 28142,
"s": 28036,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.removeat?view=netframework-4.7.2"
},
{
"code": null,
"e": 28171,
"s": 28142,
"text": "CSharp-Collections-ArrayList"
},
{
"code": null,
"e": 28200,
"s": 28171,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 28214,
"s": 28200,
"text": "CSharp-method"
},
{
"code": null,
"e": 28217,
"s": 28214,
"text": "C#"
},
{
"code": null,
"e": 28315,
"s": 28217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28324,
"s": 28315,
"text": "Comments"
},
{
"code": null,
"e": 28337,
"s": 28324,
"text": "Old Comments"
},
{
"code": null,
"e": 28365,
"s": 28337,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28388,
"s": 28365,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28410,
"s": 28388,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28433,
"s": 28410,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28451,
"s": 28433,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28466,
"s": 28451,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28497,
"s": 28466,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28543,
"s": 28497,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28559,
"s": 28543,
"text": "C# | Data Types"
}
] |
Routing in Angular 9/10 - GeeksforGeeks
|
17 Jun, 2021
Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties.
Approach:
Create an Angular app that to be used.
Create the navigation links inside the app component and then provide the “routerLink” directive to each route and pass the route value to “routerLink” directive.
Then add the routes to the routing.module.ts file and then import the routing.module.ts into the app.module.ts file.
Syntax:
HTML:
<li><a routerLink="/about" >About Us</a></li>
<router-outlet></router-outlet>
TS:
TS:
{ path: 'about', component: AboutComponent }
Example: We are going to create a simple angular application that uses angular routing. So first, we create an Angular app by running the below command in CLI.
ng new learn-routing
Then we are creating simple navigation that allows us to navigate between the different components, and we have created some components as well, so users can switch between these components using routing.
app.component.html
<span> <ul> <li><a routerLink="/" >Home</a></li> <li><a routerLink="/products" >Products</a></li> <li><a routerLink="/about" >About Us</a></li> <li><a routerLink="/contact" >Contact Us</a></li> </ul></span><router-outlet></router-outlet>
Here the router-outlet is routing functionality that is used by the router to mark wherein a template, a matched component should be inserted.
Then inside the app-routing.module.ts file, we have provided these routes and let the angular know about these routes.
app-routing.module.ts
import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { HomeComponent } from './home.component'import { ProductComponent } from './product.component'import { AboutComponent } from './about.component'import { ContactComponent } from './contact.component' const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent, },]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: []})export class AppRoutingModule { }
And then simply import “AppRouting” module inside the app/module.ts file inside the @NgModule imports.
app.module.ts
import { NgModule } from '@angular/core';import { HomeComponent } from './home.component'import { ProductComponent } from './product.component'import { AboutComponent } from './about.component'import { ContactComponent } from './contact.component'import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, ProductComponent, AboutComponent, ContactComponent ], imports: [ AppRoutingModule, ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
So now run this using “ng serve” in CLI and open localhost://4200 in the browser here you see your navigation bar, and you can navigate from one component to another without page reload.
Output:
Angular10
AngularJS-API
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer 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 ?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25327,
"s": 25109,
"text": "Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties."
},
{
"code": null,
"e": 25337,
"s": 25327,
"text": "Approach:"
},
{
"code": null,
"e": 25376,
"s": 25337,
"text": "Create an Angular app that to be used."
},
{
"code": null,
"e": 25539,
"s": 25376,
"text": "Create the navigation links inside the app component and then provide the “routerLink” directive to each route and pass the route value to “routerLink” directive."
},
{
"code": null,
"e": 25656,
"s": 25539,
"text": "Then add the routes to the routing.module.ts file and then import the routing.module.ts into the app.module.ts file."
},
{
"code": null,
"e": 25664,
"s": 25656,
"text": "Syntax:"
},
{
"code": null,
"e": 25670,
"s": 25664,
"text": "HTML:"
},
{
"code": null,
"e": 25748,
"s": 25670,
"text": "<li><a routerLink=\"/about\" >About Us</a></li>\n<router-outlet></router-outlet>"
},
{
"code": null,
"e": 25752,
"s": 25748,
"text": "TS:"
},
{
"code": null,
"e": 25756,
"s": 25752,
"text": "TS:"
},
{
"code": null,
"e": 25802,
"s": 25756,
"text": " { path: 'about', component: AboutComponent }"
},
{
"code": null,
"e": 25962,
"s": 25802,
"text": "Example: We are going to create a simple angular application that uses angular routing. So first, we create an Angular app by running the below command in CLI."
},
{
"code": null,
"e": 25983,
"s": 25962,
"text": "ng new learn-routing"
},
{
"code": null,
"e": 26188,
"s": 25983,
"text": "Then we are creating simple navigation that allows us to navigate between the different components, and we have created some components as well, so users can switch between these components using routing."
},
{
"code": null,
"e": 26207,
"s": 26188,
"text": "app.component.html"
},
{
"code": "<span> <ul> <li><a routerLink=\"/\" >Home</a></li> <li><a routerLink=\"/products\" >Products</a></li> <li><a routerLink=\"/about\" >About Us</a></li> <li><a routerLink=\"/contact\" >Contact Us</a></li> </ul></span><router-outlet></router-outlet>",
"e": 26479,
"s": 26207,
"text": null
},
{
"code": null,
"e": 26622,
"s": 26479,
"text": "Here the router-outlet is routing functionality that is used by the router to mark wherein a template, a matched component should be inserted."
},
{
"code": null,
"e": 26741,
"s": 26622,
"text": "Then inside the app-routing.module.ts file, we have provided these routes and let the angular know about these routes."
},
{
"code": null,
"e": 26763,
"s": 26741,
"text": "app-routing.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { HomeComponent } from './home.component'import { ProductComponent } from './product.component'import { AboutComponent } from './about.component'import { ContactComponent } from './contact.component' const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent, },]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: []})export class AppRoutingModule { }",
"e": 27417,
"s": 26763,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27417,
"text": "And then simply import “AppRouting” module inside the app/module.ts file inside the @NgModule imports."
},
{
"code": null,
"e": 27534,
"s": 27520,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { HomeComponent } from './home.component'import { ProductComponent } from './product.component'import { AboutComponent } from './about.component'import { ContactComponent } from './contact.component'import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, ProductComponent, AboutComponent, ContactComponent ], imports: [ AppRoutingModule, ], providers: [], bootstrap: [AppComponent]})export class AppModule { }",
"e": 28122,
"s": 27534,
"text": null
},
{
"code": null,
"e": 28309,
"s": 28122,
"text": "So now run this using “ng serve” in CLI and open localhost://4200 in the browser here you see your navigation bar, and you can navigate from one component to another without page reload."
},
{
"code": null,
"e": 28317,
"s": 28309,
"text": "Output:"
},
{
"code": null,
"e": 28327,
"s": 28317,
"text": "Angular10"
},
{
"code": null,
"e": 28341,
"s": 28327,
"text": "AngularJS-API"
},
{
"code": null,
"e": 28351,
"s": 28341,
"text": "AngularJS"
},
{
"code": null,
"e": 28368,
"s": 28351,
"text": "Web Technologies"
},
{
"code": null,
"e": 28466,
"s": 28368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28510,
"s": 28466,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28534,
"s": 28510,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28569,
"s": 28534,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28622,
"s": 28569,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28671,
"s": 28622,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 28713,
"s": 28671,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28746,
"s": 28713,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28808,
"s": 28746,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28851,
"s": 28808,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
What is the purpose of OPTIMIZE FOR ROWS in DB2 SQLs? How is it useful?
|
The OPTIMIZE FOR N ROWS is a DB2 clause which we can add in the query to give priority for the retrieval of the first few rows only. This clause will enable the optimizer to choose the access path that minimizes the response time for fetching first few rows.
The OPTIMIZE FOR N ROWS clause is not effective on SELECT DISTINCT and COUNT function because DB2 will need the entire qualifying rows in order to fetch the DISTINCT rows or COUNT the number of rows. The OPTIMIZE FOR N ROWS clause gives DB2 a better opportunity to establish the access path.
The OPTIMIZE FOR N rows clause can be used in a SQL query as given below.
SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS
ORDER BY ORDER_TOTAL DESC
OPTIMIZE FOR 2 ROWS
We will use “FETCH FIRST n ROWS ONLY” to limit the number of rows returned and it will not consider the actual number of qualifying rows.
A practical scenario in which we can use OPTIMIZE FOR N ROWS would be a CICS screen where we can display a list of 5 orders only.
SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS
ORDER BY ORDER_TOTAL DESC
OPTIMIZE FOR 5 ROWS
For example, our DB2 ORDERS table has the below data.
The result of our OPTIMIZE FOR 5 ROWS query will be as given below.
|
[
{
"code": null,
"e": 1321,
"s": 1062,
"text": "The OPTIMIZE FOR N ROWS is a DB2 clause which we can add in the query to give priority for the retrieval of the first few rows only. This clause will enable the optimizer to choose the access path that minimizes the response time for fetching first few rows."
},
{
"code": null,
"e": 1613,
"s": 1321,
"text": "The OPTIMIZE FOR N ROWS clause is not effective on SELECT DISTINCT and COUNT function because DB2 will need the entire qualifying rows in order to fetch the DISTINCT rows or COUNT the number of rows. The OPTIMIZE FOR N ROWS clause gives DB2 a better opportunity to establish the access path."
},
{
"code": null,
"e": 1687,
"s": 1613,
"text": "The OPTIMIZE FOR N rows clause can be used in a SQL query as given below."
},
{
"code": null,
"e": 1780,
"s": 1687,
"text": "SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS\n ORDER BY ORDER_TOTAL DESC\n OPTIMIZE FOR 2 ROWS"
},
{
"code": null,
"e": 1918,
"s": 1780,
"text": "We will use “FETCH FIRST n ROWS ONLY” to limit the number of rows returned and it will not consider the actual number of qualifying rows."
},
{
"code": null,
"e": 2048,
"s": 1918,
"text": "A practical scenario in which we can use OPTIMIZE FOR N ROWS would be a CICS screen where we can display a list of 5 orders only."
},
{
"code": null,
"e": 2141,
"s": 2048,
"text": "SELECT ORDER_ID, ORDER_TOTAL FROM ORDERS\n ORDER BY ORDER_TOTAL DESC\n OPTIMIZE FOR 5 ROWS"
},
{
"code": null,
"e": 2195,
"s": 2141,
"text": "For example, our DB2 ORDERS table has the below data."
},
{
"code": null,
"e": 2265,
"s": 2197,
"text": "The result of our OPTIMIZE FOR 5 ROWS query will be as given below."
}
] |
How can you order the result obtained by select query in MySQL?
|
It is common to select certain data or rows from a table. The rows are returned in the order in which they appear in the table. We may sometimes require that the rows we select from the table must be returned to us in ascending or descending order with respect to some column.
The “ORDER BY” statement is used to order the results with respect to some column. The following example will provide more clarity.
Suppose, we have a table which consists of various fields including the “name” field. We want to select all the rows from the table but we want the rows must be ordered in alphabetic order of the names. Here is where the “ORDER BY” statement comes into play. This scenario requires us to order the results in ascending order of the “name” field.
The “ORDER BY” statement ,by default, orders the specified column in ascending order. If you want the result to be ordered in descending order, you need to specify the same. To oder the result in descending order, the keyword “DESC” is to be specified.
Ascending order
SELECT * FROM table_name ORDER BY column_name
Descending order
SELECT * FROM table_name ORDER BY column_name DESC
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
close the connection
close the connection
Suppose we have a table named “Student” as follows −
+----------+---------+-----------+------------+
| Name | Class | City | Marks |
+----------+---------+-----------+------------+
| Karan | 4 | Amritsar | 95 |
| Sahil | 6 | Amritsar | 93 |
| Kriti | 3 | Batala | 88 |
| Khushi | 9 | Delhi | 90 |
| Kirat | 5 | Delhi | 85 |
+----------+---------+-----------+------------+
We want to select all the rows from the table but in alphabetic order of their names. In short, we want to order the result in ascending order of names.
import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")
cursor=db.cursor()
query= "SELECT * FROM Students ORDER BY Name"
cursor.execute(query)
for row in cursor:
print(row)
The above code when executed succesfully returns the rows in ascending or alphabetic order of the names of the students.
(‘Amit’ , 9 , ‘Delhi’ , 90)
(‘Karan’, 4 ,’Amritsar’ , 95)
(‘Kriti’ , 3 , ‘Batala’ ,88)
(‘Priya’ , 5 , ‘Delhi’ ,85)
(‘Sahil’ , 6 , ‘Amritsar’ ,93)
All the rows displayed are in alphabetic order of the names. Similarly, the rows could have been arranged in ascending or descending order of the marks following the similar syntax.
|
[
{
"code": null,
"e": 1339,
"s": 1062,
"text": "It is common to select certain data or rows from a table. The rows are returned in the order in which they appear in the table. We may sometimes require that the rows we select from the table must be returned to us in ascending or descending order with respect to some column."
},
{
"code": null,
"e": 1471,
"s": 1339,
"text": "The “ORDER BY” statement is used to order the results with respect to some column. The following example will provide more clarity."
},
{
"code": null,
"e": 1817,
"s": 1471,
"text": "Suppose, we have a table which consists of various fields including the “name” field. We want to select all the rows from the table but we want the rows must be ordered in alphabetic order of the names. Here is where the “ORDER BY” statement comes into play. This scenario requires us to order the results in ascending order of the “name” field."
},
{
"code": null,
"e": 2070,
"s": 1817,
"text": "The “ORDER BY” statement ,by default, orders the specified column in ascending order. If you want the result to be ordered in descending order, you need to specify the same. To oder the result in descending order, the keyword “DESC” is to be specified."
},
{
"code": null,
"e": 2086,
"s": 2070,
"text": "Ascending order"
},
{
"code": null,
"e": 2132,
"s": 2086,
"text": "SELECT * FROM table_name ORDER BY column_name"
},
{
"code": null,
"e": 2149,
"s": 2132,
"text": "Descending order"
},
{
"code": null,
"e": 2200,
"s": 2149,
"text": "SELECT * FROM table_name ORDER BY column_name DESC"
},
{
"code": null,
"e": 2223,
"s": 2200,
"text": "import MySQL connector"
},
{
"code": null,
"e": 2246,
"s": 2223,
"text": "import MySQL connector"
},
{
"code": null,
"e": 2302,
"s": 2246,
"text": "establish connection with the connector using connect()"
},
{
"code": null,
"e": 2358,
"s": 2302,
"text": "establish connection with the connector using connect()"
},
{
"code": null,
"e": 2405,
"s": 2358,
"text": "create the cursor object using cursor() method"
},
{
"code": null,
"e": 2452,
"s": 2405,
"text": "create the cursor object using cursor() method"
},
{
"code": null,
"e": 2506,
"s": 2452,
"text": "create a query using the appropriate mysql statements"
},
{
"code": null,
"e": 2560,
"s": 2506,
"text": "create a query using the appropriate mysql statements"
},
{
"code": null,
"e": 2605,
"s": 2560,
"text": "execute the SQL query using execute() method"
},
{
"code": null,
"e": 2650,
"s": 2605,
"text": "execute the SQL query using execute() method"
},
{
"code": null,
"e": 2671,
"s": 2650,
"text": "close the connection"
},
{
"code": null,
"e": 2692,
"s": 2671,
"text": "close the connection"
},
{
"code": null,
"e": 2745,
"s": 2692,
"text": "Suppose we have a table named “Student” as follows −"
},
{
"code": null,
"e": 3177,
"s": 2745,
"text": "+----------+---------+-----------+------------+\n| Name | Class | City | Marks |\n+----------+---------+-----------+------------+\n| Karan | 4 | Amritsar | 95 |\n| Sahil | 6 | Amritsar | 93 |\n| Kriti | 3 | Batala | 88 |\n| Khushi | 9 | Delhi | 90 |\n| Kirat | 5 | Delhi | 85 |\n+----------+---------+-----------+------------+"
},
{
"code": null,
"e": 3330,
"s": 3177,
"text": "We want to select all the rows from the table but in alphabetic order of their names. In short, we want to order the result in ascending order of names."
},
{
"code": null,
"e": 3594,
"s": 3330,
"text": "import mysql.connector\n\ndb=mysql.connector.connect(host=\"your host\", user=\"your username\", password=\"your\npassword\",database=\"database_name\")\n\ncursor=db.cursor()\n\nquery= \"SELECT * FROM Students ORDER BY Name\"\ncursor.execute(query)\nfor row in cursor:\n print(row)"
},
{
"code": null,
"e": 3715,
"s": 3594,
"text": "The above code when executed succesfully returns the rows in ascending or alphabetic order of the names of the students."
},
{
"code": null,
"e": 3861,
"s": 3715,
"text": "(‘Amit’ , 9 , ‘Delhi’ , 90)\n(‘Karan’, 4 ,’Amritsar’ , 95)\n(‘Kriti’ , 3 , ‘Batala’ ,88)\n(‘Priya’ , 5 , ‘Delhi’ ,85)\n(‘Sahil’ , 6 , ‘Amritsar’ ,93)"
},
{
"code": null,
"e": 4043,
"s": 3861,
"text": "All the rows displayed are in alphabetic order of the names. Similarly, the rows could have been arranged in ascending or descending order of the marks following the similar syntax."
}
] |
Style every checked <input> element with CSS
|
To style every checked <input> element, use the CSS :checked selector. You can try to run the following code to implement the :checked selector −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
input:checked {
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<p>Fav sports:</p>
<form action="">
<input type = "checkbox" value = "Football">Football<br>
<input type = "checkbox" value = "Cricket">Cricket<br>
<input type = "checkbox" checked = "checked" value = "Tennis"> Tennis<br>
<input type = "checkbox" value = "Badminton">Tennis
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "To style every checked <input> element, use the CSS :checked selector. You can try to run the following code to implement the :checked selector −"
},
{
"code": null,
"e": 1218,
"s": 1208,
"text": "Live Demo"
},
{
"code": null,
"e": 1743,
"s": 1218,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n input:checked {\n height: 20px;\n width: 20px;\n }\n </style>\n </head>\n <body>\n <p>Fav sports:</p>\n <form action=\"\">\n <input type = \"checkbox\" value = \"Football\">Football<br>\n <input type = \"checkbox\" value = \"Cricket\">Cricket<br>\n <input type = \"checkbox\" checked = \"checked\" value = \"Tennis\"> Tennis<br>\n <input type = \"checkbox\" value = \"Badminton\">Tennis\n </form>\n </body>\n</html>"
}
] |
Counters in Python?
|
A Counters is a container which keeps track to how many times equivalent values are added. Python counter class is a part of collections module and is a subclass of dictionary.
We may think of counter as an unordered collection of items where items are stored as dictionary keys and their count as dictionary value.
Counter items count can be positive, zero or negative integers. Though there is no restrict on its keys and values but generally values are intended to be numbers but we can store other object types too.
Counter supports three forms of initialization. Its constructor can be called with a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts.
import collections
print (collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))
print (collections.Counter({'a': 2, 'b': 3, 'c':1}))
print(collections.Counter(a=2, b=3, c=1))
The output from all three forms of initialization are the same -
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
To create an empty counter, pass the counter with no argument and populate it via the update method.
import collections
c = collections.Counter()
print('Initial: ', c)
c.update('abcddcba')
print('Sequence: ', c)
c.update({'a': 1, 'd':5})
print('Dict: ', c)
Initial: Counter()
Sequence: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})
Dict: Counter({'d': 7, 'a': 3, 'b': 2, 'c': 2})
Once the counter is populated, it values can be fetched via dictionary API.
import collections
c = collections.Counter('abcddcba')
for letter in 'abcdef':
print('%s : %d' %(letter, c[letter]))
a : 2
b : 2
c : 2
d : 2
e : 0
f : 0
Counter does not raise KeyError for unknown items(like the items e & f we have mentioned in above program). If a value has not been seen in the input, its count is 0 (like for unknown item e & f in above output).
The elements() method returns an iterator that produces all of the items known to the Counter.
import collections
c = collections.Counter('Python Counters')
c['z'] = 0
print(c)
print(list(c.elements()))
Counter({'t': 2, 'o': 2, 'n': 2, 'P': 1, 'y': 1, 'h': 1, ' ': 1, 'C': 1, 'u': 1, 'e': 1, 'r': 1, 's': 1, 'z': 0})
['P', 'y', 't', 't', 'h', 'o', 'o', 'n', 'n', ' ', 'C', 'u', 'e', 'r', 's']
The order of elements is not fixed, and items with counts less than zero are not included.
To produce common inputs out of n inputs and their respective counts we use most_common() function.
import collections
c = collections.Counter()
texts = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.'''
for word in texts:
c.update(word.rstrip().lower())
print("Five most common letters in the texts: ")
for letter, count in c.most_common(5):
print("%s: %7d" %(letter, count))
Five most common letters in the texts:
i: 42
e: 38
t: 32
o: 29
u: 29
Above example counts the letters appearing in the texts (or you can consider a file) to produce a frequency distribution, then prints the five most common. Leaving out the argument to most_common() produces a list of all the items, in order of frequency.
Counter instances support arithmetic and set operations for aggregating results.
import collections
c1 = collections.Counter(['a', 'b', 'c', 'a' ,'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1: ', c1)
print('C2: ', c2)
print ('\nCombined counts: ')
print(c1 + c2)
print('\nSubtraction: ')
print(c1 - c2)
print('\nIntersection (taking positive minimums): ')
print(c1 & c2)
print('\nUnion (taking maximums): ')
print(c1 | c2)
C1: Counter({'b': 3, 'a': 2, 'c': 1})
C2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})
Combined counts:
Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
Subtraction:
Counter({'b': 2, 'c': 1})
Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})
Union (taking maximums):
Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
Each time a new counter is produced through an operation, any items with zero or negative counts are discarded.
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "A Counters is a container which keeps track to how many times equivalent values are added. Python counter class is a part of collections module and is a subclass of dictionary."
},
{
"code": null,
"e": 1378,
"s": 1239,
"text": "We may think of counter as an unordered collection of items where items are stored as dictionary keys and their count as dictionary value."
},
{
"code": null,
"e": 1582,
"s": 1378,
"text": "Counter items count can be positive, zero or negative integers. Though there is no restrict on its keys and values but generally values are intended to be numbers but we can store other object types too."
},
{
"code": null,
"e": 1786,
"s": 1582,
"text": "Counter supports three forms of initialization. Its constructor can be called with a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts."
},
{
"code": null,
"e": 1960,
"s": 1786,
"text": "import collections\nprint (collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))\nprint (collections.Counter({'a': 2, 'b': 3, 'c':1}))\nprint(collections.Counter(a=2, b=3, c=1))"
},
{
"code": null,
"e": 2025,
"s": 1960,
"text": "The output from all three forms of initialization are the same -"
},
{
"code": null,
"e": 2127,
"s": 2025,
"text": "Counter({'b': 3, 'a': 2, 'c': 1})\nCounter({'b': 3, 'a': 2, 'c': 1})\nCounter({'b': 3, 'a': 2, 'c': 1})"
},
{
"code": null,
"e": 2228,
"s": 2127,
"text": "To create an empty counter, pass the counter with no argument and populate it via the update method."
},
{
"code": null,
"e": 2384,
"s": 2228,
"text": "import collections\nc = collections.Counter()\nprint('Initial: ', c)\nc.update('abcddcba')\nprint('Sequence: ', c)\nc.update({'a': 1, 'd':5})\nprint('Dict: ', c)"
},
{
"code": null,
"e": 2503,
"s": 2384,
"text": "Initial: Counter()\nSequence: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})\nDict: Counter({'d': 7, 'a': 3, 'b': 2, 'c': 2})"
},
{
"code": null,
"e": 2579,
"s": 2503,
"text": "Once the counter is populated, it values can be fetched via dictionary API."
},
{
"code": null,
"e": 2699,
"s": 2579,
"text": "import collections\nc = collections.Counter('abcddcba')\nfor letter in 'abcdef':\n print('%s : %d' %(letter, c[letter]))"
},
{
"code": null,
"e": 2735,
"s": 2699,
"text": "a : 2\nb : 2\nc : 2\nd : 2\ne : 0\nf : 0"
},
{
"code": null,
"e": 2948,
"s": 2735,
"text": "Counter does not raise KeyError for unknown items(like the items e & f we have mentioned in above program). If a value has not been seen in the input, its count is 0 (like for unknown item e & f in above output)."
},
{
"code": null,
"e": 3043,
"s": 2948,
"text": "The elements() method returns an iterator that produces all of the items known to the Counter."
},
{
"code": null,
"e": 3151,
"s": 3043,
"text": "import collections\nc = collections.Counter('Python Counters')\nc['z'] = 0\nprint(c)\nprint(list(c.elements()))"
},
{
"code": null,
"e": 3341,
"s": 3151,
"text": "Counter({'t': 2, 'o': 2, 'n': 2, 'P': 1, 'y': 1, 'h': 1, ' ': 1, 'C': 1, 'u': 1, 'e': 1, 'r': 1, 's': 1, 'z': 0})\n['P', 'y', 't', 't', 'h', 'o', 'o', 'n', 'n', ' ', 'C', 'u', 'e', 'r', 's']"
},
{
"code": null,
"e": 3432,
"s": 3341,
"text": "The order of elements is not fixed, and items with counts less than zero are not included."
},
{
"code": null,
"e": 3532,
"s": 3432,
"text": "To produce common inputs out of n inputs and their respective counts we use most_common() function."
},
{
"code": null,
"e": 4210,
"s": 3532,
"text": "import collections\nc = collections.Counter()\ntexts = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in\nreprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa\nqui officia deserunt mollit anim id est laborum.'''\nfor word in texts:\nc.update(word.rstrip().lower())\nprint(\"Five most common letters in the texts: \")\nfor letter, count in c.most_common(5):\nprint(\"%s: %7d\" %(letter, count))"
},
{
"code": null,
"e": 4279,
"s": 4210,
"text": "Five most common letters in the texts:\ni: 42\ne: 38\nt: 32\no: 29\nu: 29"
},
{
"code": null,
"e": 4534,
"s": 4279,
"text": "Above example counts the letters appearing in the texts (or you can consider a file) to produce a frequency distribution, then prints the five most common. Leaving out the argument to most_common() produces a list of all the items, in order of frequency."
},
{
"code": null,
"e": 4615,
"s": 4534,
"text": "Counter instances support arithmetic and set operations for aggregating results."
},
{
"code": null,
"e": 4969,
"s": 4615,
"text": "import collections\nc1 = collections.Counter(['a', 'b', 'c', 'a' ,'b', 'b'])\nc2 = collections.Counter('alphabet')\nprint('C1: ', c1)\nprint('C2: ', c2)\nprint ('\\nCombined counts: ')\nprint(c1 + c2)\nprint('\\nSubtraction: ')\nprint(c1 - c2)\nprint('\\nIntersection (taking positive minimums): ')\nprint(c1 & c2)\nprint('\\nUnion (taking maximums): ')\nprint(c1 | c2)"
},
{
"code": null,
"e": 5373,
"s": 4969,
"text": "C1: Counter({'b': 3, 'a': 2, 'c': 1})\nC2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})\nCombined counts:\nCounter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})\nSubtraction:\nCounter({'b': 2, 'c': 1})\nIntersection (taking positive minimums):\nCounter({'a': 2, 'b': 1})\nUnion (taking maximums):\nCounter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})"
},
{
"code": null,
"e": 5485,
"s": 5373,
"text": "Each time a new counter is produced through an operation, any items with zero or negative counts are discarded."
}
] |
Groovy - If Statement
|
The first decision making statement is the if statement. The general form of this statement is −
if(condition) {
statement #1
statement #2
...
}
The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements. The following diagram shows the flow of the if statement.
Following is an example of a if/else statement −
class Example {
static void main(String[] args) {
// Initializing a local variable
int a = 2
//Check for the boolean condition
if (a<100) {
//If the condition is true print the following statement
println("The value is less than 100");
}
}
}
In the above example, we are first initializing a variable to a value of 2. We are then evaluating the value of the variable and then deciding whether the println statement should be executed. The output of the above code would be −
The value is less than 100
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2335,
"s": 2238,
"text": "The first decision making statement is the if statement. The general form of this statement is −"
},
{
"code": null,
"e": 2397,
"s": 2335,
"text": "if(condition) { \n statement #1 \n statement #2 \n ... \n}\n"
},
{
"code": null,
"e": 2612,
"s": 2397,
"text": "The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements. The following diagram shows the flow of the if statement."
},
{
"code": null,
"e": 2661,
"s": 2612,
"text": "Following is an example of a if/else statement −"
},
{
"code": null,
"e": 2970,
"s": 2661,
"text": "class Example { \n static void main(String[] args) { \n // Initializing a local variable \n int a = 2 \n\t\t\n //Check for the boolean condition \n if (a<100) { \n //If the condition is true print the following statement \n println(\"The value is less than 100\"); \n } \n } \n}"
},
{
"code": null,
"e": 3203,
"s": 2970,
"text": "In the above example, we are first initializing a variable to a value of 2. We are then evaluating the value of the variable and then deciding whether the println statement should be executed. The output of the above code would be −"
},
{
"code": null,
"e": 3231,
"s": 3203,
"text": "The value is less than 100\n"
},
{
"code": null,
"e": 3264,
"s": 3231,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3282,
"s": 3264,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3317,
"s": 3282,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3335,
"s": 3317,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3342,
"s": 3335,
"text": " Print"
},
{
"code": null,
"e": 3353,
"s": 3342,
"text": " Add Notes"
}
] |
TypeScript - Calling a Function
|
A function must be called so as to execute it. This process is termed as function invocation.
Function_name()
The following example illustrates how a function can be invoked −
function test() { // function definition
console.log("function called")
}
test() // function invocation
On compiling, it will generate the same JavaScript code.
function test() {
console.log("function called");
}
test(); // function invocation
It will produce the following output −
function called
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2142,
"s": 2048,
"text": "A function must be called so as to execute it. This process is termed as function invocation."
},
{
"code": null,
"e": 2159,
"s": 2142,
"text": "Function_name()\n"
},
{
"code": null,
"e": 2225,
"s": 2159,
"text": "The following example illustrates how a function can be invoked −"
},
{
"code": null,
"e": 2354,
"s": 2225,
"text": "function test() { // function definition \n console.log(\"function called\") \n} \ntest() // function invocation\n"
},
{
"code": null,
"e": 2411,
"s": 2354,
"text": "On compiling, it will generate the same JavaScript code."
},
{
"code": null,
"e": 2504,
"s": 2411,
"text": "function test() { \n console.log(\"function called\"); \n} \ntest(); // function invocation\n"
},
{
"code": null,
"e": 2543,
"s": 2504,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 2560,
"s": 2543,
"text": "function called\n"
},
{
"code": null,
"e": 2593,
"s": 2560,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2607,
"s": 2593,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2640,
"s": 2607,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2654,
"s": 2640,
"text": " Haider Malik"
},
{
"code": null,
"e": 2689,
"s": 2654,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2709,
"s": 2689,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2742,
"s": 2709,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2756,
"s": 2742,
"text": " Sean Bradley"
},
{
"code": null,
"e": 2791,
"s": 2756,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2807,
"s": 2791,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2840,
"s": 2807,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2860,
"s": 2840,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 2867,
"s": 2860,
"text": " Print"
},
{
"code": null,
"e": 2878,
"s": 2867,
"text": " Add Notes"
}
] |
Going Bastion-less: Accessing Private EC2 instance with Session Manager | by Daniel Da Costa | Towards Data Science
|
In this post we will set up a private EC2 instance (in a private subnet), and use SSM session manager to access the instance that hosts a Jupyter Notebook server. We will then use PostForwarding with AWS Session Manager to access our server from our local machine.
We'll set up this infrastructure without opening inbound ports or setting up bastion hosts or managing SSH keys!.
It is well known that we can not directly connect to a private EC2 instance unless there is VPN Connectivity or Direct Connect or other network connectivity source with the VPC. A common approach to connect to an EC2 instance on a private subnet of your VPC is to use a Bastion Host.
A Bastion Host is a server whose purpose is to provide access to a private network from an external network (such as the Internet). Because of its exposure to potential attacks, a bastion host must minimize the chances of penetrations. When using a bastion host, you log into the bastion host first, and then into your target private instance. With this approach, only the bastion host will have an external IP address.
However, there are some drawbacks:
You will need to allow SSH inbound rule at your bastion
You need to open ports on your private EC2 instance in order to connect it to your bastion
You will need to manage the SSH key credentials of your users: You will need to generate an ssh key pair for each user or get a copy of the same SSH key for your users
Cost: The bastion host also has a cost associated with it as it is a running EC2 instance. Even a t2.micro costs about $10/month.
Session Manager can be used to access instances within private subnets that allow no ingress from the internet. AWS SSM provides the ability to establish a shell on your systems through its native service, or by using it as a tunnel for other protocols, such as Secure Shell (SSH). Advantages:
It will log the commands issued during the session, as well as the results. You can save the logs in s3 if you wish.
Shell access is completely contained within Identity and Access Management (IAM) policies, you won’t need to manage SSH keys
The user does not need to use a bastion host and Public IPs.
No need to open the ports in the security groups
You will need to Install the Session Manager plugin for the AWS CLI in order to use the CLI to start and end sessions that connect you to your managed instances.
You can check on how to install the plugin for different OS here!
Before creating the EC2 instance you will need a VPC with a Public and Private Subnets. Since will be hosting a Jupyter Notebook on our instance located on the Private Subnet, it will need internet access (so that we can install and update Python packages).
In order to give access to the internet to our private subnet we will be using a NAT Gateway. In addition, to enable internet connectivity, this gateway make sure that the internet doesn’t initiate a connection with the instance.
The network configuration that will be used is represented below:
You can create the network directly on the AWS Console or you can build it using Terraform, you can check the Terraform code here.
Our instance will be deployed on the Private Subnet without a Public IP address configuration since we won't need it.
In order to allow Session Manager access to our instance will need to attach the following IAM role: AmazonSSMManagedInstanceCore. This policy grant instances the permissions needed for core Systems Manager functionality.
For the VPC security group, we won't need to include any inbound rules, allowing only outbound traffic.
With everything set up you can access your instance from the command line:
$ aws ssm start-session --target {YOUR_TARGET_INSTANCE_ID}
It's important to notice that the connection was successfully made without opening any port at the EC2 Security Group and without a Bastion Host!
The following image shows the actual configuration that we are using:
Session Manager has an in-built audit log: AWS Session Manager provides audit logs by default; so each command is logged and stored in CloudWatch Logs or an S3 bucket as per necessary security and compliance regulations.
You can also have a Session History on the console:
Many customers use SSH Tunnel to remotely access services not exposed to the public internet. Basically, the SSH client listens for connections on a configured port, and when it receives a connection, it tunnels the connection to an SSH server. The server connects to a configurated destination port, possibly on a different machine than the SSH server.
In OpenSSH, local port forwarding is configured using the -L option:
ssh -L 9999:localhost:8888 user@instance
This example opens a connection to the instance as user user, open port 9999 on the local computer, a forward everything from there to localhost:8888.
Port Forwarding for AWS System Manager Session Manager allows you to securely create tunnels between your instances deployed in private subnets, without the need to start the SSH service on the server, to open the SSH port in the security group, or the need to use a bastion host.
In this post, we won’t go through on how to set up a Jupyter Notebook Server on an EC2 instance, but you can find all the information need to do so on this link.
Once the prerequisites are met, you use the AWS CLI to create the tunnel:
$ aws ssm start-session --target {YOUR_TARGET_INSTANCE_ID} --document-name AWS-StartPortForwardingSession --parameters "portNumber"=["8888"],"localPortNumber"=["8888"]
OBS: While I was using the Jupyter Notebook Server, I faced a very high latency problem; I think it might be because of the Port Forwarding from Session Manager. If you are facing the same problem, please, leave a comment.
In this post, we saw how to use Session Manager to access a private EC2 instance, without the need to add inbound rules to the instance Security Group, manage SSH Keys and use another instance as a Bastion Host. We also learned how to use Post Forwarding using Session Manager.
All the Terraform Code used in this post can be found Here!
|
[
{
"code": null,
"e": 436,
"s": 171,
"text": "In this post we will set up a private EC2 instance (in a private subnet), and use SSM session manager to access the instance that hosts a Jupyter Notebook server. We will then use PostForwarding with AWS Session Manager to access our server from our local machine."
},
{
"code": null,
"e": 550,
"s": 436,
"text": "We'll set up this infrastructure without opening inbound ports or setting up bastion hosts or managing SSH keys!."
},
{
"code": null,
"e": 834,
"s": 550,
"text": "It is well known that we can not directly connect to a private EC2 instance unless there is VPN Connectivity or Direct Connect or other network connectivity source with the VPC. A common approach to connect to an EC2 instance on a private subnet of your VPC is to use a Bastion Host."
},
{
"code": null,
"e": 1254,
"s": 834,
"text": "A Bastion Host is a server whose purpose is to provide access to a private network from an external network (such as the Internet). Because of its exposure to potential attacks, a bastion host must minimize the chances of penetrations. When using a bastion host, you log into the bastion host first, and then into your target private instance. With this approach, only the bastion host will have an external IP address."
},
{
"code": null,
"e": 1289,
"s": 1254,
"text": "However, there are some drawbacks:"
},
{
"code": null,
"e": 1345,
"s": 1289,
"text": "You will need to allow SSH inbound rule at your bastion"
},
{
"code": null,
"e": 1436,
"s": 1345,
"text": "You need to open ports on your private EC2 instance in order to connect it to your bastion"
},
{
"code": null,
"e": 1604,
"s": 1436,
"text": "You will need to manage the SSH key credentials of your users: You will need to generate an ssh key pair for each user or get a copy of the same SSH key for your users"
},
{
"code": null,
"e": 1734,
"s": 1604,
"text": "Cost: The bastion host also has a cost associated with it as it is a running EC2 instance. Even a t2.micro costs about $10/month."
},
{
"code": null,
"e": 2028,
"s": 1734,
"text": "Session Manager can be used to access instances within private subnets that allow no ingress from the internet. AWS SSM provides the ability to establish a shell on your systems through its native service, or by using it as a tunnel for other protocols, such as Secure Shell (SSH). Advantages:"
},
{
"code": null,
"e": 2145,
"s": 2028,
"text": "It will log the commands issued during the session, as well as the results. You can save the logs in s3 if you wish."
},
{
"code": null,
"e": 2270,
"s": 2145,
"text": "Shell access is completely contained within Identity and Access Management (IAM) policies, you won’t need to manage SSH keys"
},
{
"code": null,
"e": 2331,
"s": 2270,
"text": "The user does not need to use a bastion host and Public IPs."
},
{
"code": null,
"e": 2380,
"s": 2331,
"text": "No need to open the ports in the security groups"
},
{
"code": null,
"e": 2542,
"s": 2380,
"text": "You will need to Install the Session Manager plugin for the AWS CLI in order to use the CLI to start and end sessions that connect you to your managed instances."
},
{
"code": null,
"e": 2608,
"s": 2542,
"text": "You can check on how to install the plugin for different OS here!"
},
{
"code": null,
"e": 2866,
"s": 2608,
"text": "Before creating the EC2 instance you will need a VPC with a Public and Private Subnets. Since will be hosting a Jupyter Notebook on our instance located on the Private Subnet, it will need internet access (so that we can install and update Python packages)."
},
{
"code": null,
"e": 3096,
"s": 2866,
"text": "In order to give access to the internet to our private subnet we will be using a NAT Gateway. In addition, to enable internet connectivity, this gateway make sure that the internet doesn’t initiate a connection with the instance."
},
{
"code": null,
"e": 3162,
"s": 3096,
"text": "The network configuration that will be used is represented below:"
},
{
"code": null,
"e": 3293,
"s": 3162,
"text": "You can create the network directly on the AWS Console or you can build it using Terraform, you can check the Terraform code here."
},
{
"code": null,
"e": 3411,
"s": 3293,
"text": "Our instance will be deployed on the Private Subnet without a Public IP address configuration since we won't need it."
},
{
"code": null,
"e": 3633,
"s": 3411,
"text": "In order to allow Session Manager access to our instance will need to attach the following IAM role: AmazonSSMManagedInstanceCore. This policy grant instances the permissions needed for core Systems Manager functionality."
},
{
"code": null,
"e": 3737,
"s": 3633,
"text": "For the VPC security group, we won't need to include any inbound rules, allowing only outbound traffic."
},
{
"code": null,
"e": 3812,
"s": 3737,
"text": "With everything set up you can access your instance from the command line:"
},
{
"code": null,
"e": 3871,
"s": 3812,
"text": "$ aws ssm start-session --target {YOUR_TARGET_INSTANCE_ID}"
},
{
"code": null,
"e": 4017,
"s": 3871,
"text": "It's important to notice that the connection was successfully made without opening any port at the EC2 Security Group and without a Bastion Host!"
},
{
"code": null,
"e": 4087,
"s": 4017,
"text": "The following image shows the actual configuration that we are using:"
},
{
"code": null,
"e": 4308,
"s": 4087,
"text": "Session Manager has an in-built audit log: AWS Session Manager provides audit logs by default; so each command is logged and stored in CloudWatch Logs or an S3 bucket as per necessary security and compliance regulations."
},
{
"code": null,
"e": 4360,
"s": 4308,
"text": "You can also have a Session History on the console:"
},
{
"code": null,
"e": 4714,
"s": 4360,
"text": "Many customers use SSH Tunnel to remotely access services not exposed to the public internet. Basically, the SSH client listens for connections on a configured port, and when it receives a connection, it tunnels the connection to an SSH server. The server connects to a configurated destination port, possibly on a different machine than the SSH server."
},
{
"code": null,
"e": 4783,
"s": 4714,
"text": "In OpenSSH, local port forwarding is configured using the -L option:"
},
{
"code": null,
"e": 4824,
"s": 4783,
"text": "ssh -L 9999:localhost:8888 user@instance"
},
{
"code": null,
"e": 4975,
"s": 4824,
"text": "This example opens a connection to the instance as user user, open port 9999 on the local computer, a forward everything from there to localhost:8888."
},
{
"code": null,
"e": 5256,
"s": 4975,
"text": "Port Forwarding for AWS System Manager Session Manager allows you to securely create tunnels between your instances deployed in private subnets, without the need to start the SSH service on the server, to open the SSH port in the security group, or the need to use a bastion host."
},
{
"code": null,
"e": 5418,
"s": 5256,
"text": "In this post, we won’t go through on how to set up a Jupyter Notebook Server on an EC2 instance, but you can find all the information need to do so on this link."
},
{
"code": null,
"e": 5492,
"s": 5418,
"text": "Once the prerequisites are met, you use the AWS CLI to create the tunnel:"
},
{
"code": null,
"e": 5660,
"s": 5492,
"text": "$ aws ssm start-session --target {YOUR_TARGET_INSTANCE_ID} --document-name AWS-StartPortForwardingSession --parameters \"portNumber\"=[\"8888\"],\"localPortNumber\"=[\"8888\"]"
},
{
"code": null,
"e": 5883,
"s": 5660,
"text": "OBS: While I was using the Jupyter Notebook Server, I faced a very high latency problem; I think it might be because of the Port Forwarding from Session Manager. If you are facing the same problem, please, leave a comment."
},
{
"code": null,
"e": 6161,
"s": 5883,
"text": "In this post, we saw how to use Session Manager to access a private EC2 instance, without the need to add inbound rules to the instance Security Group, manage SSH Keys and use another instance as a Bastion Host. We also learned how to use Post Forwarding using Session Manager."
}
] |
Why addEventListener to 'select' element does not work in JavaScript?
|
Instead, use querySelector() along with addEventListener().
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<select id="selectDemo">
<option value="Java">Java</option>
<option value="Javascript">Javascript</option>
<option value="MySQL">MySQL</option>
<option value="MongoDB">MongoDB</option>
</select>
</body>
<script>
document.querySelector('#selectDemo').addEventListener('change', subjectMarks);
function subjectMarks() {
console.log(58);
}
</script>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the
file. Select the option “Open with live server” in VS Code editor.
This will produce the following output −
Now, select the value from dropdown list −
This will produce the following output −
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "Instead, use querySelector() along with addEventListener()."
},
{
"code": null,
"e": 1146,
"s": 1122,
"text": "Following is the code −"
},
{
"code": null,
"e": 1940,
"s": 1146,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n</head>\n<link rel=\"stylesheet\"\nhref=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n <select id=\"selectDemo\">\n <option value=\"Java\">Java</option>\n <option value=\"Javascript\">Javascript</option>\n <option value=\"MySQL\">MySQL</option>\n <option value=\"MongoDB\">MongoDB</option>\n </select>\n</body>\n<script>\n document.querySelector('#selectDemo').addEventListener('change', subjectMarks);\n function subjectMarks() {\n console.log(58);\n }\n</script>\n</html>"
},
{
"code": null,
"e": 2100,
"s": 1940,
"text": "To run the above program, save the file name anyName.html(index.html) and right click on the\nfile. Select the option “Open with live server” in VS Code editor."
},
{
"code": null,
"e": 2141,
"s": 2100,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2184,
"s": 2141,
"text": "Now, select the value from dropdown list −"
},
{
"code": null,
"e": 2225,
"s": 2184,
"text": "This will produce the following output −"
}
] |
Program to print GP (Geometric Progression) - GeeksforGeeks
|
24 Nov, 2021
Given first term (a), common ratio (r) and a integer n of the Geometric Progression series, the task is to print th n terms of the series.Examples:
Input : a = 2 r = 2, n = 4
Output : 2 4 8 16
Approach :
We know the Geometric Progression series is like = 2, 4, 8, 16, 32 ....... In this series 2 is the starting term of the series . Common ratio = 4 / 2 = 2 (ratio common in the series). so we can write the series as :t1 = a1 t2 = a1 * r(2-1) t3 = a1 * r(3-1) t4 = a1 * r(4-1) . . . . tN = a1 * r(n-1)
To print the Geometric Progression series we use the simple formula .
TN = a1 * r(n-1)
CPP
Java
Python3
C#
PHP
Javascript
// CPP program to print GP.#include <bits/stdc++.h>using namespace std; void printGP(int a, int r, int n){ int curr_term; for (int i = 0; i < n; i++) { curr_term = a * pow(r, i); cout << curr_term << " "; }} // Driver codeint main(){ int a = 2; // starting number int r = 3; // Common ratio int n = 5; // N th term to be find printGP(a, r, n); return 0;}
// Java program to print GP.class GFG { static void printGP(int a, int r, int n) { int curr_term; for (int i = 0; i < n; i++) { curr_term = a * (int)Math.pow(r, i); System.out.print(curr_term + " "); } } // Driver code public static void main(String[] args) { int a = 2; // starting number int r = 3; // Common ratio int n = 5; // N th term to be find printGP(a, r, n); }}// This code is contributed by Anant Agarwal.
# Python 3 program to print GP. def printGP(a, r, n): for i in range(0, n): curr_term = a * pow(r, i) print(curr_term, end =" ") # Driver code a = 2 # starting numberr = 3 # Common ration = 5 # N th term to be find printGP(a, r, n) # This code is contributed by# Smitha Dinesh Semwal
// C# program to print GP.using System; class GFG { static void printGP(int a, int r, int n) { int curr_term; for (int i = 0; i < n; i++) { curr_term = a * (int)Math.Pow(r, i); Console.Write(curr_term + " "); } } // Driver code public static void Main() { int a = 2; // starting number int r = 3; // Common ratio int n = 5; // N th term to be find printGP(a, r, n); }} // This code is contributed by vt_m.
<?php// PHP program to print GP. // function to print GPfunction printGP($a, $r, $n){ for ($i = 0; $i < $n; $i++) { $curr_term = $a * pow($r, $i); echo $curr_term, " "; }} // Driver Code // starting number $a = 2; // Common ratio $r = 3; // N th term to be find $n = 5; printGP($a, $r, $n); // This code is contributed by ajit.?>
<script> // JavaScript program to print GP. function printGP(a, r, n){ let curr_term; for (let i = 0; i < n; i++) { curr_term = a * Math.pow(r, i); document.write(curr_term + " "); }} // Driver code let a = 2; // starting number let r = 3; // Common ratio let n = 5; // N th term to be find printGP(a, r, n); // This code is contributed by Surbhi Tyagi </script>
2 6 18 54 162
jit_t
PankajMishra10
surbhityagi15
rs1686740
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
|
[
{
"code": null,
"e": 25357,
"s": 25329,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25507,
"s": 25357,
"text": "Given first term (a), common ratio (r) and a integer n of the Geometric Progression series, the task is to print th n terms of the series.Examples: "
},
{
"code": null,
"e": 25552,
"s": 25507,
"text": "Input : a = 2 r = 2, n = 4\nOutput : 2 4 8 16"
},
{
"code": null,
"e": 25567,
"s": 25554,
"text": "Approach : "
},
{
"code": null,
"e": 25868,
"s": 25567,
"text": "We know the Geometric Progression series is like = 2, 4, 8, 16, 32 ....... In this series 2 is the starting term of the series . Common ratio = 4 / 2 = 2 (ratio common in the series). so we can write the series as :t1 = a1 t2 = a1 * r(2-1) t3 = a1 * r(3-1) t4 = a1 * r(4-1) . . . . tN = a1 * r(n-1) "
},
{
"code": null,
"e": 25940,
"s": 25868,
"text": "To print the Geometric Progression series we use the simple formula . "
},
{
"code": null,
"e": 25957,
"s": 25940,
"text": "TN = a1 * r(n-1)"
},
{
"code": null,
"e": 25963,
"s": 25959,
"text": "CPP"
},
{
"code": null,
"e": 25968,
"s": 25963,
"text": "Java"
},
{
"code": null,
"e": 25976,
"s": 25968,
"text": "Python3"
},
{
"code": null,
"e": 25979,
"s": 25976,
"text": "C#"
},
{
"code": null,
"e": 25983,
"s": 25979,
"text": "PHP"
},
{
"code": null,
"e": 25994,
"s": 25983,
"text": "Javascript"
},
{
"code": "// CPP program to print GP.#include <bits/stdc++.h>using namespace std; void printGP(int a, int r, int n){ int curr_term; for (int i = 0; i < n; i++) { curr_term = a * pow(r, i); cout << curr_term << \" \"; }} // Driver codeint main(){ int a = 2; // starting number int r = 3; // Common ratio int n = 5; // N th term to be find printGP(a, r, n); return 0;}",
"e": 26387,
"s": 25994,
"text": null
},
{
"code": "// Java program to print GP.class GFG { static void printGP(int a, int r, int n) { int curr_term; for (int i = 0; i < n; i++) { curr_term = a * (int)Math.pow(r, i); System.out.print(curr_term + \" \"); } } // Driver code public static void main(String[] args) { int a = 2; // starting number int r = 3; // Common ratio int n = 5; // N th term to be find printGP(a, r, n); }}// This code is contributed by Anant Agarwal.",
"e": 26898,
"s": 26387,
"text": null
},
{
"code": "# Python 3 program to print GP. def printGP(a, r, n): for i in range(0, n): curr_term = a * pow(r, i) print(curr_term, end =\" \") # Driver code a = 2 # starting numberr = 3 # Common ration = 5 # N th term to be find printGP(a, r, n) # This code is contributed by# Smitha Dinesh Semwal",
"e": 27204,
"s": 26898,
"text": null
},
{
"code": "// C# program to print GP.using System; class GFG { static void printGP(int a, int r, int n) { int curr_term; for (int i = 0; i < n; i++) { curr_term = a * (int)Math.Pow(r, i); Console.Write(curr_term + \" \"); } } // Driver code public static void Main() { int a = 2; // starting number int r = 3; // Common ratio int n = 5; // N th term to be find printGP(a, r, n); }} // This code is contributed by vt_m.",
"e": 27708,
"s": 27204,
"text": null
},
{
"code": "<?php// PHP program to print GP. // function to print GPfunction printGP($a, $r, $n){ for ($i = 0; $i < $n; $i++) { $curr_term = $a * pow($r, $i); echo $curr_term, \" \"; }} // Driver Code // starting number $a = 2; // Common ratio $r = 3; // N th term to be find $n = 5; printGP($a, $r, $n); // This code is contributed by ajit.?>",
"e": 28101,
"s": 27708,
"text": null
},
{
"code": "<script> // JavaScript program to print GP. function printGP(a, r, n){ let curr_term; for (let i = 0; i < n; i++) { curr_term = a * Math.pow(r, i); document.write(curr_term + \" \"); }} // Driver code let a = 2; // starting number let r = 3; // Common ratio let n = 5; // N th term to be find printGP(a, r, n); // This code is contributed by Surbhi Tyagi </script>",
"e": 28506,
"s": 28101,
"text": null
},
{
"code": null,
"e": 28520,
"s": 28506,
"text": "2 6 18 54 162"
},
{
"code": null,
"e": 28528,
"s": 28522,
"text": "jit_t"
},
{
"code": null,
"e": 28543,
"s": 28528,
"text": "PankajMishra10"
},
{
"code": null,
"e": 28557,
"s": 28543,
"text": "surbhityagi15"
},
{
"code": null,
"e": 28567,
"s": 28557,
"text": "rs1686740"
},
{
"code": null,
"e": 28574,
"s": 28567,
"text": "series"
},
{
"code": null,
"e": 28587,
"s": 28574,
"text": "Mathematical"
},
{
"code": null,
"e": 28606,
"s": 28587,
"text": "School Programming"
},
{
"code": null,
"e": 28619,
"s": 28606,
"text": "Mathematical"
},
{
"code": null,
"e": 28626,
"s": 28619,
"text": "series"
},
{
"code": null,
"e": 28724,
"s": 28626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28733,
"s": 28724,
"text": "Comments"
},
{
"code": null,
"e": 28746,
"s": 28733,
"text": "Old Comments"
},
{
"code": null,
"e": 28789,
"s": 28746,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28831,
"s": 28789,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 28855,
"s": 28831,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 28869,
"s": 28855,
"text": "Prime Numbers"
},
{
"code": null,
"e": 28918,
"s": 28869,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28936,
"s": 28918,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28952,
"s": 28936,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28971,
"s": 28952,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28996,
"s": 28971,
"text": "Reverse a string in Java"
}
] |
Automate your Feature Selection Workflow in one line of Python code | by Satyam Kumar | Towards Data Science
|
More training data in terms of the number of instances leads to a better data science model, but this does not hold true for the number of features. A real-world dataset has a lot of features, some of them are useful to train a robust data science model, others are redundant features that can impact the performance of the model.
Feature selection is an important element of a data science model development workflow. Selecting all the possible combinations of features is a polynomial solution. There are various feature selection techniques and hacks that data scientists use to remove the redundant features.
Read this article, to know 7 feature selection techniques.
In this article, we will focus on automating the feature selection workflow using an open-source Python package — Featurewiz.
Featurewiz is an open-source library used for creating and selecting the best features from the dataset, which can be further used to train a robust data science model. Featurewiz also comes up with feature engineering capabilities. It can create hundreds of new features with just a click of code. Featurewiz API has a parameter ‘feature_engg’, that can be set to ‘interactions’, ‘group by’, and ‘target’, and it will create hundreds of features in one go.
Feature Engineering or creating new features is not only the capabilities of featurewiz. It can reduce the number of features, and select the best set of features to train a robust model.
Featurewiz uses two algorithms to select the best features from the dataset.
SULOV
Recursive XGBoost
SULOV stands for Searching for Uncorrelated List of Variables, very similar to the mRMR algorithm. Steps SULOV algorithms follows are:
Compute all the pairs of correlated variables that exceed a threshold.Compute MIS (Mutual Information Score) with respect to the target variable.Compare each pair of correlated variables, and remove the features with low MIS.The remaining features have high MIS and low correlation.
Compute all the pairs of correlated variables that exceed a threshold.
Compute MIS (Mutual Information Score) with respect to the target variable.
Compare each pair of correlated variables, and remove the features with low MIS.
The remaining features have high MIS and low correlation.
After SULOV algorithms select the best set of features having high MIS and log correlation, the repetitive XGBoost algorithm is used to compute the best features among the remaining variables. The steps are as follows:
Build a dataset for the remaining set of features and split them into train and validation.Compute the top 10 features on the train using validation.Repeat steps 1 and 2 with a different set of features each time.Combine all sets of 10 features and de-duplicate them, this will result in the best set of features.
Build a dataset for the remaining set of features and split them into train and validation.
Compute the top 10 features on the train using validation.
Repeat steps 1 and 2 with a different set of features each time.
Combine all sets of 10 features and de-duplicate them, this will result in the best set of features.
Featurewiz uses the above two discussed algorithms to find the best set of features, that can be further used to train a robust machine learning model.
Featurewiz can be installed using Pypl
pip install featurewiz
After installation, featurewiz can be imported:
from featurewiz import featurewiz
Now the developer needs to write only one line of code, to get the best set of features from the dataset.
out1, out2 = featurewiz(dataname, target, corr_limit=0.7, verbose=0, sep=",", header=0, test_data="", feature_engg="", category_encoders="")
Featurewiz can not only handle datasets with one target variable but can also handle datasets with multi-label target variables. The data frame returned from featurewiz contains the best set of features and is ready to use for model training. Developers don’t need to specify the types of problem, if it's a regression or classification, features can decide it automatically.
In this article, we have discussed an open-source library featurewiz, that automates the feature selection of the dataset. Along with feature selection, featurewiz also has the capabilities to perform feature engineering and generate hundreds of features, just with a click of code.Featurewiz using two algorithms (SULOV, and recursive XGBoost) to select the best set of features. Featurewiz speeds up the workflow of a data scientist by doing the entire feature selection just in a click of a single line of code. A data scientist can use several feature selection techniques to filter out the best of features, you can read 7 of these feature selection techniques in the below-mentioned article.
towardsdatascience.com
[1] Featurewiz GitHub repo: https://github.com/AutoViML/featurewiz
Thank You for Reading
|
[
{
"code": null,
"e": 503,
"s": 172,
"text": "More training data in terms of the number of instances leads to a better data science model, but this does not hold true for the number of features. A real-world dataset has a lot of features, some of them are useful to train a robust data science model, others are redundant features that can impact the performance of the model."
},
{
"code": null,
"e": 785,
"s": 503,
"text": "Feature selection is an important element of a data science model development workflow. Selecting all the possible combinations of features is a polynomial solution. There are various feature selection techniques and hacks that data scientists use to remove the redundant features."
},
{
"code": null,
"e": 844,
"s": 785,
"text": "Read this article, to know 7 feature selection techniques."
},
{
"code": null,
"e": 970,
"s": 844,
"text": "In this article, we will focus on automating the feature selection workflow using an open-source Python package — Featurewiz."
},
{
"code": null,
"e": 1428,
"s": 970,
"text": "Featurewiz is an open-source library used for creating and selecting the best features from the dataset, which can be further used to train a robust data science model. Featurewiz also comes up with feature engineering capabilities. It can create hundreds of new features with just a click of code. Featurewiz API has a parameter ‘feature_engg’, that can be set to ‘interactions’, ‘group by’, and ‘target’, and it will create hundreds of features in one go."
},
{
"code": null,
"e": 1616,
"s": 1428,
"text": "Feature Engineering or creating new features is not only the capabilities of featurewiz. It can reduce the number of features, and select the best set of features to train a robust model."
},
{
"code": null,
"e": 1693,
"s": 1616,
"text": "Featurewiz uses two algorithms to select the best features from the dataset."
},
{
"code": null,
"e": 1699,
"s": 1693,
"text": "SULOV"
},
{
"code": null,
"e": 1717,
"s": 1699,
"text": "Recursive XGBoost"
},
{
"code": null,
"e": 1852,
"s": 1717,
"text": "SULOV stands for Searching for Uncorrelated List of Variables, very similar to the mRMR algorithm. Steps SULOV algorithms follows are:"
},
{
"code": null,
"e": 2135,
"s": 1852,
"text": "Compute all the pairs of correlated variables that exceed a threshold.Compute MIS (Mutual Information Score) with respect to the target variable.Compare each pair of correlated variables, and remove the features with low MIS.The remaining features have high MIS and low correlation."
},
{
"code": null,
"e": 2206,
"s": 2135,
"text": "Compute all the pairs of correlated variables that exceed a threshold."
},
{
"code": null,
"e": 2282,
"s": 2206,
"text": "Compute MIS (Mutual Information Score) with respect to the target variable."
},
{
"code": null,
"e": 2363,
"s": 2282,
"text": "Compare each pair of correlated variables, and remove the features with low MIS."
},
{
"code": null,
"e": 2421,
"s": 2363,
"text": "The remaining features have high MIS and low correlation."
},
{
"code": null,
"e": 2640,
"s": 2421,
"text": "After SULOV algorithms select the best set of features having high MIS and log correlation, the repetitive XGBoost algorithm is used to compute the best features among the remaining variables. The steps are as follows:"
},
{
"code": null,
"e": 2954,
"s": 2640,
"text": "Build a dataset for the remaining set of features and split them into train and validation.Compute the top 10 features on the train using validation.Repeat steps 1 and 2 with a different set of features each time.Combine all sets of 10 features and de-duplicate them, this will result in the best set of features."
},
{
"code": null,
"e": 3046,
"s": 2954,
"text": "Build a dataset for the remaining set of features and split them into train and validation."
},
{
"code": null,
"e": 3105,
"s": 3046,
"text": "Compute the top 10 features on the train using validation."
},
{
"code": null,
"e": 3170,
"s": 3105,
"text": "Repeat steps 1 and 2 with a different set of features each time."
},
{
"code": null,
"e": 3271,
"s": 3170,
"text": "Combine all sets of 10 features and de-duplicate them, this will result in the best set of features."
},
{
"code": null,
"e": 3423,
"s": 3271,
"text": "Featurewiz uses the above two discussed algorithms to find the best set of features, that can be further used to train a robust machine learning model."
},
{
"code": null,
"e": 3462,
"s": 3423,
"text": "Featurewiz can be installed using Pypl"
},
{
"code": null,
"e": 3485,
"s": 3462,
"text": "pip install featurewiz"
},
{
"code": null,
"e": 3533,
"s": 3485,
"text": "After installation, featurewiz can be imported:"
},
{
"code": null,
"e": 3567,
"s": 3533,
"text": "from featurewiz import featurewiz"
},
{
"code": null,
"e": 3673,
"s": 3567,
"text": "Now the developer needs to write only one line of code, to get the best set of features from the dataset."
},
{
"code": null,
"e": 3816,
"s": 3673,
"text": "out1, out2 = featurewiz(dataname, target, corr_limit=0.7, verbose=0, sep=\",\", header=0, test_data=\"\", feature_engg=\"\", category_encoders=\"\")"
},
{
"code": null,
"e": 4192,
"s": 3816,
"text": "Featurewiz can not only handle datasets with one target variable but can also handle datasets with multi-label target variables. The data frame returned from featurewiz contains the best set of features and is ready to use for model training. Developers don’t need to specify the types of problem, if it's a regression or classification, features can decide it automatically."
},
{
"code": null,
"e": 4890,
"s": 4192,
"text": "In this article, we have discussed an open-source library featurewiz, that automates the feature selection of the dataset. Along with feature selection, featurewiz also has the capabilities to perform feature engineering and generate hundreds of features, just with a click of code.Featurewiz using two algorithms (SULOV, and recursive XGBoost) to select the best set of features. Featurewiz speeds up the workflow of a data scientist by doing the entire feature selection just in a click of a single line of code. A data scientist can use several feature selection techniques to filter out the best of features, you can read 7 of these feature selection techniques in the below-mentioned article."
},
{
"code": null,
"e": 4913,
"s": 4890,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4980,
"s": 4913,
"text": "[1] Featurewiz GitHub repo: https://github.com/AutoViML/featurewiz"
}
] |
Spring JDBC - Delete Query
|
The following example will demonstrate how to delete a query using Spring JDBC. We'll delete one of the available records in Student Table.
String deleteQuery = "delete from Student where id = ?";
jdbcTemplateObject.update(deleteQuery, id);
Where,
deleteQuery − Delete query to delete student with placeholders.
deleteQuery − Delete query to delete student with placeholders.
jdbcTemplateObject − StudentJDBCTemplate object to delete student object in the database.
jdbcTemplateObject − StudentJDBCTemplate object to delete student object in the database.
To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will delete a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of the Data Access Object interface file StudentDAO.java.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
/**
* This is the method to be used to delete
* a record from the Student table corresponding
* to a passed student id.
*/
public void delete(Integer id);
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Following is the content of the StudentMapper.java file.
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
public void delete(Integer id){
String SQL = "delete from Student where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("----Delete Record with ID = 2 -----" );
studentJDBCTemplate.delete(2);
System.out.println("------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id = "studentJDBCTemplate"
class = "com.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message.
----Updating Record with ID = 2 -----
Updated Record with ID = 2
----Listing Record with ID = 2 -----
ID : 2, Name : Nuha, Age : 20
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2536,
"s": 2396,
"text": "The following example will demonstrate how to delete a query using Spring JDBC. We'll delete one of the available records in Student Table."
},
{
"code": null,
"e": 2638,
"s": 2536,
"text": "String deleteQuery = \"delete from Student where id = ?\";\njdbcTemplateObject.update(deleteQuery, id);\n"
},
{
"code": null,
"e": 2645,
"s": 2638,
"text": "Where,"
},
{
"code": null,
"e": 2709,
"s": 2645,
"text": "deleteQuery − Delete query to delete student with placeholders."
},
{
"code": null,
"e": 2773,
"s": 2709,
"text": "deleteQuery − Delete query to delete student with placeholders."
},
{
"code": null,
"e": 2863,
"s": 2773,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to delete student object in the database."
},
{
"code": null,
"e": 2953,
"s": 2863,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to delete student object in the database."
},
{
"code": null,
"e": 3196,
"s": 2953,
"text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will delete a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 3279,
"s": 3196,
"text": "Following is the content of the Data Access Object interface file StudentDAO.java."
},
{
"code": null,
"e": 3892,
"s": 3279,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to list down\n * all the records from the Student table.\n */\n public List<Student> listStudents();\n \n /** \n * This is the method to be used to delete\n * a record from the Student table corresponding\n * to a passed student id.\n */\n public void delete(Integer id); \n}"
},
{
"code": null,
"e": 3943,
"s": 3892,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 4415,
"s": 3943,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 4472,
"s": 4415,
"text": "Following is the content of the StudentMapper.java file."
},
{
"code": null,
"e": 4930,
"s": 4472,
"text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}"
},
{
"code": null,
"e": 5040,
"s": 4930,
"text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO."
},
{
"code": null,
"e": 5880,
"s": 5040,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public List<Student> listStudents() {\n String SQL = \"select * from Student\";\n List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());\n return students;\n }\n public void delete(Integer id){\n String SQL = \"delete from Student where id = ?\";\n jdbcTemplateObject.update(SQL, id);\n System.out.println(\"Deleted Record with ID = \" + id );\n return;\n }\n}"
},
{
"code": null,
"e": 5931,
"s": 5880,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 6918,
"s": 5931,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = \n (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n \n System.out.println(\"----Delete Record with ID = 2 -----\" );\n studentJDBCTemplate.delete(2);\n\n System.out.println(\"------Listing Multiple Records--------\" );\n List<Student> students = studentJDBCTemplate.listStudents();\n \n for (Student record : students) {\n System.out.print(\"ID : \" + record.getId() );\n System.out.print(\", Name : \" + record.getName() );\n System.out.println(\", Age : \" + record.getAge());\n } \n }\n}"
},
{
"code": null,
"e": 6965,
"s": 6918,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 7920,
"s": 6965,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean>\n \n</beans>"
},
{
"code": null,
"e": 8098,
"s": 7920,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 8231,
"s": 8098,
"text": "----Updating Record with ID = 2 -----\nUpdated Record with ID = 2\n----Listing Record with ID = 2 -----\nID : 2, Name : Nuha, Age : 20\n"
},
{
"code": null,
"e": 8238,
"s": 8231,
"text": " Print"
},
{
"code": null,
"e": 8249,
"s": 8238,
"text": " Add Notes"
}
] |
Python Data Persistence - Shelve Module
|
The shelve module in Python’s standard library provides simple yet effective object persistence mechanism. The shelf object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems.
The shelf dictionary has certain restrictions. Only string data type can be used as key in this special dictionary object, whereas any picklable Python object can be used as value.
The shelve module defines three classes as follows −
Shelf
This is the base class for shelf implementations. It is initialized with dict-like object.
BsdDbShelf
This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods.
DbfilenameShelf
This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object.
The open() function defined in shelve module which return a DbfilenameShelf object.
open(filename, flag='c', protocol=None, writeback=False)
The filename parameter is assigned to the database created. Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write).
The serialization itself is governed by pickle protocol, default is none. Last parameter writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations, hence process may be slow.
Following code creates a database and stores dictionary entries in it.
import shelve
s=shelve.open("test")
s['name']="Ajay"
s['age']=23
s['marks']=75
s.close()
This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available −
close()
synchronise and close persistent dict object.
sync()
Write back all entries in the cache if shelf was opened with writeback set to True.
get()
returns value associated with key
items()
list of tuples – each tuple is key value pair
keys()
list of shelf keys
pop()
remove specified key and return the corresponding value.
update()
Update shelf from another dict/iterable
values()
list of shelf values
To access value of a particular key in shelf −
s=shelve.open('test')
print (s['age']) #this will print 23
s['age']=25
print (s.get('age')) #this will print 25
s.pop('marks') #this will remove corresponding k-v pair
As in a built-in dictionary object, the items(), keys() and values() methods return view objects.
print (list(s.items()))
[('name', 'Ajay'), ('age', 25), ('marks', 75)]
print (list(s.keys()))
['name', 'age', 'marks']
print (list(s.values()))
['Ajay', 25, 75]
To merge items of another dictionary with shelf use update() method.
d={'salary':10000, 'designation':'manager'}
s.update(d)
print (list(s.items()))
[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]
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": 2639,
"s": 2355,
"text": "The shelve module in Python’s standard library provides simple yet effective object persistence mechanism. The shelf object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems."
},
{
"code": null,
"e": 2820,
"s": 2639,
"text": "The shelf dictionary has certain restrictions. Only string data type can be used as key in this special dictionary object, whereas any picklable Python object can be used as value."
},
{
"code": null,
"e": 2873,
"s": 2820,
"text": "The shelve module defines three classes as follows −"
},
{
"code": null,
"e": 2879,
"s": 2873,
"text": "Shelf"
},
{
"code": null,
"e": 2970,
"s": 2879,
"text": "This is the base class for shelf implementations. It is initialized with dict-like object."
},
{
"code": null,
"e": 2981,
"s": 2970,
"text": "BsdDbShelf"
},
{
"code": null,
"e": 3135,
"s": 2981,
"text": "This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods."
},
{
"code": null,
"e": 3151,
"s": 3135,
"text": "DbfilenameShelf"
},
{
"code": null,
"e": 3264,
"s": 3151,
"text": "This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object."
},
{
"code": null,
"e": 3348,
"s": 3264,
"text": "The open() function defined in shelve module which return a DbfilenameShelf object."
},
{
"code": null,
"e": 3406,
"s": 3348,
"text": "open(filename, flag='c', protocol=None, writeback=False)\n"
},
{
"code": null,
"e": 3609,
"s": 3406,
"text": "The filename parameter is assigned to the database created. Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write)."
},
{
"code": null,
"e": 3865,
"s": 3609,
"text": "The serialization itself is governed by pickle protocol, default is none. Last parameter writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations, hence process may be slow."
},
{
"code": null,
"e": 3936,
"s": 3865,
"text": "Following code creates a database and stores dictionary entries in it."
},
{
"code": null,
"e": 4025,
"s": 3936,
"text": "import shelve\ns=shelve.open(\"test\")\ns['name']=\"Ajay\"\ns['age']=23\ns['marks']=75\ns.close()"
},
{
"code": null,
"e": 4169,
"s": 4025,
"text": "This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available −"
},
{
"code": null,
"e": 4177,
"s": 4169,
"text": "close()"
},
{
"code": null,
"e": 4223,
"s": 4177,
"text": "synchronise and close persistent dict object."
},
{
"code": null,
"e": 4230,
"s": 4223,
"text": "sync()"
},
{
"code": null,
"e": 4314,
"s": 4230,
"text": "Write back all entries in the cache if shelf was opened with writeback set to True."
},
{
"code": null,
"e": 4320,
"s": 4314,
"text": "get()"
},
{
"code": null,
"e": 4354,
"s": 4320,
"text": "returns value associated with key"
},
{
"code": null,
"e": 4362,
"s": 4354,
"text": "items()"
},
{
"code": null,
"e": 4408,
"s": 4362,
"text": "list of tuples – each tuple is key value pair"
},
{
"code": null,
"e": 4415,
"s": 4408,
"text": "keys()"
},
{
"code": null,
"e": 4434,
"s": 4415,
"text": "list of shelf keys"
},
{
"code": null,
"e": 4440,
"s": 4434,
"text": "pop()"
},
{
"code": null,
"e": 4497,
"s": 4440,
"text": "remove specified key and return the corresponding value."
},
{
"code": null,
"e": 4506,
"s": 4497,
"text": "update()"
},
{
"code": null,
"e": 4546,
"s": 4506,
"text": "Update shelf from another dict/iterable"
},
{
"code": null,
"e": 4555,
"s": 4546,
"text": "values()"
},
{
"code": null,
"e": 4576,
"s": 4555,
"text": "list of shelf values"
},
{
"code": null,
"e": 4623,
"s": 4576,
"text": "To access value of a particular key in shelf −"
},
{
"code": null,
"e": 4794,
"s": 4623,
"text": "s=shelve.open('test')\nprint (s['age']) #this will print 23\n s['age']=25\nprint (s.get('age')) #this will print 25\ns.pop('marks') #this will remove corresponding k-v pair"
},
{
"code": null,
"e": 4892,
"s": 4794,
"text": "As in a built-in dictionary object, the items(), keys() and values() methods return view objects."
},
{
"code": null,
"e": 5057,
"s": 4892,
"text": "print (list(s.items()))\n[('name', 'Ajay'), ('age', 25), ('marks', 75)] \n\nprint (list(s.keys()))\n['name', 'age', 'marks']\n\nprint (list(s.values()))\n['Ajay', 25, 75]"
},
{
"code": null,
"e": 5126,
"s": 5057,
"text": "To merge items of another dictionary with shelf use update() method."
},
{
"code": null,
"e": 5286,
"s": 5126,
"text": "d={'salary':10000, 'designation':'manager'}\ns.update(d)\nprint (list(s.items()))\n\n[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]"
},
{
"code": null,
"e": 5323,
"s": 5286,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5339,
"s": 5323,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5372,
"s": 5339,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5391,
"s": 5372,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5426,
"s": 5391,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5448,
"s": 5426,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5482,
"s": 5448,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5510,
"s": 5482,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5545,
"s": 5510,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5559,
"s": 5545,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5592,
"s": 5559,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5609,
"s": 5592,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5616,
"s": 5609,
"text": " Print"
},
{
"code": null,
"e": 5627,
"s": 5616,
"text": " Add Notes"
}
] |
C# | How to copy the entire ArrayList to a one-dimensional Array
|
01 Feb, 2019
ArrayList.CopyTo Method is used to copy the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array.
Syntax:
public virtual void CopyTo (Array array);
Here, array is the one-dimensional Array which is the destination of the elements copied from ArrayList. The Array must have zero-based indexing.
Exceptions:
ArgumentNullException: If the array is null.
ArgumentException: If the array is multidimensional OR the number of elements in the source ArrayList is greater than the number of elements that the destination array can contain.
InvalidCastException: If the type of the source ArrayList cannot be cast automatically to the type of the destination array.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to illustrate the// ArrayList.CopyTo Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); myList.Add("G"); myList.Add("H"); // Creates and initializes the // one-dimensional target Array. String[] arr = new String[9]; arr[0] = "C"; arr[1] = "C++"; arr[2] = "Java"; arr[3] = "Python"; arr[4] = "C#"; arr[5] = "HTML"; arr[6] = "CSS"; arr[7] = "PHP"; arr[8] = "DBMS"; Console.WriteLine("Before CopyTo Method: "); Console.WriteLine("\nArrayList Contains: "); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine("{0}", obj); Console.WriteLine("\nString Array Contains: "); // printing String elements foreach(Object obj1 in arr) Console.WriteLine("{0}", obj1); Console.WriteLine("After CopyTo Method: "); // using CopyTo Method to copy // the entire source ArrayList // to the target Array starting // at index 0 myList.CopyTo(arr); Console.WriteLine("\nArrayList Contains: "); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine("{0}", obj); Console.WriteLine("\nString Array Contains: "); // printing String elements foreach(Object obj1 in arr) Console.WriteLine("{0}", obj1); }}
Output:
Before CopyTo Method:
ArrayList Contains:
A
B
C
D
E
F
G
H
String Array Contains:
C
C++
Java
Python
C#
HTML
CSS
PHP
DBMS
After CopyTo Method:
ArrayList Contains:
A
B
C
D
E
F
G
H
String Array Contains:
A
B
C
D
E
F
G
H
DBMS
Example 2:
// C# code to illustrate the// ArrayList.CopyTo Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add("HTML"); myList.Add("CSS"); myList.Add("PHP"); myList.Add("DBMS"); // Creates and initializes the // one-dimensional target Array. // Here array size is only 2 i.e // it can hold only 3 elements. String[] arr = new String[2]; Console.WriteLine("Before CopyTo Method: "); Console.WriteLine("\nArrayList Contains: "); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine("{0}", obj); Console.WriteLine("\nString Array Contains: "); // printing String elements foreach(Object obj1 in arr) Console.WriteLine("{0}", obj1); Console.WriteLine("After CopyTo Method: "); // using CopyTo Method but It will give // Runtime Error as number of elements // in the source ArrayList is greater // than the number of elements that // the destination array can contain myList.CopyTo(arr); Console.WriteLine("\nArrayList Contains: "); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine("{0}", obj); Console.WriteLine("\nString Array Contains: "); // printing String elements foreach(Object obj1 in arr) Console.WriteLine("{0}", obj1); }}
Runtime Error:
Unhandled Exception:System.ArgumentException: Destination array was not long enough. Check destIndex and length, and the array’s lower boundsParameter name: destinationArray
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.copyto?view=netframework-4.7.2#System_Collections_ArrayList_CopyTo_System_Array_
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
C# Dictionary with examples
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Data Types
C# | Method Overriding
C# | Class and Object
C# | Constructors
C# | Arrays
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "ArrayList.CopyTo Method is used to copy the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array."
},
{
"code": null,
"e": 183,
"s": 175,
"text": "Syntax:"
},
{
"code": null,
"e": 225,
"s": 183,
"text": "public virtual void CopyTo (Array array);"
},
{
"code": null,
"e": 371,
"s": 225,
"text": "Here, array is the one-dimensional Array which is the destination of the elements copied from ArrayList. The Array must have zero-based indexing."
},
{
"code": null,
"e": 383,
"s": 371,
"text": "Exceptions:"
},
{
"code": null,
"e": 428,
"s": 383,
"text": "ArgumentNullException: If the array is null."
},
{
"code": null,
"e": 609,
"s": 428,
"text": "ArgumentException: If the array is multidimensional OR the number of elements in the source ArrayList is greater than the number of elements that the destination array can contain."
},
{
"code": null,
"e": 734,
"s": 609,
"text": "InvalidCastException: If the type of the source ArrayList cannot be cast automatically to the type of the destination array."
},
{
"code": null,
"e": 795,
"s": 734,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 806,
"s": 795,
"text": "Example 1:"
},
{
"code": "// C# code to illustrate the// ArrayList.CopyTo Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(\"A\"); myList.Add(\"B\"); myList.Add(\"C\"); myList.Add(\"D\"); myList.Add(\"E\"); myList.Add(\"F\"); myList.Add(\"G\"); myList.Add(\"H\"); // Creates and initializes the // one-dimensional target Array. String[] arr = new String[9]; arr[0] = \"C\"; arr[1] = \"C++\"; arr[2] = \"Java\"; arr[3] = \"Python\"; arr[4] = \"C#\"; arr[5] = \"HTML\"; arr[6] = \"CSS\"; arr[7] = \"PHP\"; arr[8] = \"DBMS\"; Console.WriteLine(\"Before CopyTo Method: \"); Console.WriteLine(\"\\nArrayList Contains: \"); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine(\"{0}\", obj); Console.WriteLine(\"\\nString Array Contains: \"); // printing String elements foreach(Object obj1 in arr) Console.WriteLine(\"{0}\", obj1); Console.WriteLine(\"After CopyTo Method: \"); // using CopyTo Method to copy // the entire source ArrayList // to the target Array starting // at index 0 myList.CopyTo(arr); Console.WriteLine(\"\\nArrayList Contains: \"); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine(\"{0}\", obj); Console.WriteLine(\"\\nString Array Contains: \"); // printing String elements foreach(Object obj1 in arr) Console.WriteLine(\"{0}\", obj1); }}",
"e": 2573,
"s": 806,
"text": null
},
{
"code": null,
"e": 2581,
"s": 2573,
"text": "Output:"
},
{
"code": null,
"e": 2814,
"s": 2581,
"text": "Before CopyTo Method: \n\nArrayList Contains: \nA\nB\nC\nD\nE\nF\nG\nH\n\nString Array Contains: \nC\nC++\nJava\nPython\nC#\nHTML\nCSS\nPHP\nDBMS\n\nAfter CopyTo Method: \n\nArrayList Contains: \nA\nB\nC\nD\nE\nF\nG\nH\n\nString Array Contains: \nA\nB\nC\nD\nE\nF\nG\nH\nDBMS\n"
},
{
"code": null,
"e": 2825,
"s": 2814,
"text": "Example 2:"
},
{
"code": "// C# code to illustrate the// ArrayList.CopyTo Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(\"HTML\"); myList.Add(\"CSS\"); myList.Add(\"PHP\"); myList.Add(\"DBMS\"); // Creates and initializes the // one-dimensional target Array. // Here array size is only 2 i.e // it can hold only 3 elements. String[] arr = new String[2]; Console.WriteLine(\"Before CopyTo Method: \"); Console.WriteLine(\"\\nArrayList Contains: \"); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine(\"{0}\", obj); Console.WriteLine(\"\\nString Array Contains: \"); // printing String elements foreach(Object obj1 in arr) Console.WriteLine(\"{0}\", obj1); Console.WriteLine(\"After CopyTo Method: \"); // using CopyTo Method but It will give // Runtime Error as number of elements // in the source ArrayList is greater // than the number of elements that // the destination array can contain myList.CopyTo(arr); Console.WriteLine(\"\\nArrayList Contains: \"); // printing ArrayList elements foreach(Object obj in myList) Console.WriteLine(\"{0}\", obj); Console.WriteLine(\"\\nString Array Contains: \"); // printing String elements foreach(Object obj1 in arr) Console.WriteLine(\"{0}\", obj1); }}",
"e": 4462,
"s": 2825,
"text": null
},
{
"code": null,
"e": 4477,
"s": 4462,
"text": "Runtime Error:"
},
{
"code": null,
"e": 4651,
"s": 4477,
"text": "Unhandled Exception:System.ArgumentException: Destination array was not long enough. Check destIndex and length, and the array’s lower boundsParameter name: destinationArray"
},
{
"code": null,
"e": 4662,
"s": 4651,
"text": "Reference:"
},
{
"code": null,
"e": 4816,
"s": 4662,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.copyto?view=netframework-4.7.2#System_Collections_ArrayList_CopyTo_System_Array_"
},
{
"code": null,
"e": 4845,
"s": 4816,
"text": "CSharp-Collections-ArrayList"
},
{
"code": null,
"e": 4874,
"s": 4845,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 4888,
"s": 4874,
"text": "CSharp-method"
},
{
"code": null,
"e": 4891,
"s": 4888,
"text": "C#"
},
{
"code": null,
"e": 4989,
"s": 4891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5032,
"s": 4989,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 5060,
"s": 5032,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 5091,
"s": 5060,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 5140,
"s": 5091,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 5155,
"s": 5140,
"text": "C# | Delegates"
},
{
"code": null,
"e": 5171,
"s": 5155,
"text": "C# | Data Types"
},
{
"code": null,
"e": 5194,
"s": 5171,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 5216,
"s": 5194,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 5234,
"s": 5216,
"text": "C# | Constructors"
}
] |
Python Tkinter – Scale Widget
|
23 Dec, 2021
Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs.
Note: For more information, refer to Python GUI – tkinter
The Scale widget is used whenever we want to select a specific value from a range of values. It provides a sliding bar through which we can select the values by sliding from left to right or top to bottom depending upon the orientation of our sliding bar.
Syntax:
S = Scale(root, bg, fg, bd, command, orient, from_, to, ..)
Optional parameters
root – root window.
bg – background colour
fg – foreground colour
bd – border
orient – orientation(vertical or horizontal)
from_ – starting value
to – ending value
troughcolor – set colour for trough.
state – decides if the widget will be responsive or unresponsive.
sliderlength – decides the length of the slider.
label – to display label in the widget.
highlightbackground – the colour of the focus when widget is not focused.
cursor – The cursor on the widget which could be arrow, circle, dot etc.
Methods
set(value) – set the value for scale.
get() – get the value of scale.
Example 1: Creating a horizontal bar
# Python program to demonstrate# scale widget from tkinter import * root = Tk() root.geometry("400x300") v1 = DoubleVar() def show1(): sel = "Horizontal Scale Value = " + str(v1.get()) l1.config(text = sel, font =("Courier", 14)) s1 = Scale( root, variable = v1, from_ = 1, to = 100, orient = HORIZONTAL) l3 = Label(root, text = "Horizontal Scaler") b1 = Button(root, text ="Display Horizontal", command = show1, bg = "yellow") l1 = Label(root) s1.pack(anchor = CENTER) l3.pack()b1.pack(anchor = CENTER)l1.pack() root.mainloop()
Output:
Example 2: Creating a vertical slider
from tkinter import * root = Tk() root.geometry("400x300") v2 = DoubleVar() def show2(): sel = "Vertical Scale Value = " + str(v2.get()) l2.config(text = sel, font =("Courier", 14)) s2 = Scale( root, variable = v2, from_ = 50, to = 1, orient = VERTICAL) l4 = Label(root, text = "Vertical Scaler") b2 = Button(root, text ="Display Vertical", command = show2, bg = "purple", fg = "white") l2 = Label(root) s2.pack(anchor = CENTER) l4.pack()b2.pack()l2.pack() root.mainloop()
Output:
avtarkumar719
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 264,
"s": 54,
"text": "Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs."
},
{
"code": null,
"e": 322,
"s": 264,
"text": "Note: For more information, refer to Python GUI – tkinter"
},
{
"code": null,
"e": 578,
"s": 322,
"text": "The Scale widget is used whenever we want to select a specific value from a range of values. It provides a sliding bar through which we can select the values by sliding from left to right or top to bottom depending upon the orientation of our sliding bar."
},
{
"code": null,
"e": 586,
"s": 578,
"text": "Syntax:"
},
{
"code": null,
"e": 648,
"s": 586,
"text": "S = Scale(root, bg, fg, bd, command, orient, from_, to, ..) \n"
},
{
"code": null,
"e": 668,
"s": 648,
"text": "Optional parameters"
},
{
"code": null,
"e": 688,
"s": 668,
"text": "root – root window."
},
{
"code": null,
"e": 711,
"s": 688,
"text": "bg – background colour"
},
{
"code": null,
"e": 734,
"s": 711,
"text": "fg – foreground colour"
},
{
"code": null,
"e": 746,
"s": 734,
"text": "bd – border"
},
{
"code": null,
"e": 791,
"s": 746,
"text": "orient – orientation(vertical or horizontal)"
},
{
"code": null,
"e": 814,
"s": 791,
"text": "from_ – starting value"
},
{
"code": null,
"e": 832,
"s": 814,
"text": "to – ending value"
},
{
"code": null,
"e": 869,
"s": 832,
"text": "troughcolor – set colour for trough."
},
{
"code": null,
"e": 935,
"s": 869,
"text": "state – decides if the widget will be responsive or unresponsive."
},
{
"code": null,
"e": 984,
"s": 935,
"text": "sliderlength – decides the length of the slider."
},
{
"code": null,
"e": 1024,
"s": 984,
"text": "label – to display label in the widget."
},
{
"code": null,
"e": 1098,
"s": 1024,
"text": "highlightbackground – the colour of the focus when widget is not focused."
},
{
"code": null,
"e": 1171,
"s": 1098,
"text": "cursor – The cursor on the widget which could be arrow, circle, dot etc."
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Methods"
},
{
"code": null,
"e": 1217,
"s": 1179,
"text": "set(value) – set the value for scale."
},
{
"code": null,
"e": 1249,
"s": 1217,
"text": "get() – get the value of scale."
},
{
"code": null,
"e": 1286,
"s": 1249,
"text": "Example 1: Creating a horizontal bar"
},
{
"code": "# Python program to demonstrate# scale widget from tkinter import * root = Tk() root.geometry(\"400x300\") v1 = DoubleVar() def show1(): sel = \"Horizontal Scale Value = \" + str(v1.get()) l1.config(text = sel, font =(\"Courier\", 14)) s1 = Scale( root, variable = v1, from_ = 1, to = 100, orient = HORIZONTAL) l3 = Label(root, text = \"Horizontal Scaler\") b1 = Button(root, text =\"Display Horizontal\", command = show1, bg = \"yellow\") l1 = Label(root) s1.pack(anchor = CENTER) l3.pack()b1.pack(anchor = CENTER)l1.pack() root.mainloop()",
"e": 1902,
"s": 1286,
"text": null
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Output:"
},
{
"code": null,
"e": 1948,
"s": 1910,
"text": "Example 2: Creating a vertical slider"
},
{
"code": "from tkinter import * root = Tk() root.geometry(\"400x300\") v2 = DoubleVar() def show2(): sel = \"Vertical Scale Value = \" + str(v2.get()) l2.config(text = sel, font =(\"Courier\", 14)) s2 = Scale( root, variable = v2, from_ = 50, to = 1, orient = VERTICAL) l4 = Label(root, text = \"Vertical Scaler\") b2 = Button(root, text =\"Display Vertical\", command = show2, bg = \"purple\", fg = \"white\") l2 = Label(root) s2.pack(anchor = CENTER) l4.pack()b2.pack()l2.pack() root.mainloop()",
"e": 2498,
"s": 1948,
"text": null
},
{
"code": null,
"e": 2506,
"s": 2498,
"text": "Output:"
},
{
"code": null,
"e": 2520,
"s": 2506,
"text": "avtarkumar719"
},
{
"code": null,
"e": 2535,
"s": 2520,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2542,
"s": 2535,
"text": "Python"
},
{
"code": null,
"e": 2640,
"s": 2542,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2668,
"s": 2640,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2718,
"s": 2668,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2740,
"s": 2718,
"text": "Python map() function"
},
{
"code": null,
"e": 2784,
"s": 2740,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2806,
"s": 2784,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2848,
"s": 2806,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2883,
"s": 2848,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2915,
"s": 2883,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2941,
"s": 2915,
"text": "Python String | replace()"
}
] |
How to show full column content in a PySpark Dataframe ?
|
06 Aug, 2021
Sometimes in Dataframe, when column data containing the long content or large sentence, then PySpark SQL shows the dataframe in compressed form means the first few words of the sentence are shown and others are followed by dots that refers that some more data is available.
From the above sample Dataframe, we can easily see that the content of the Name column is not fully shown. This thing is automatically done by the PySpark to show the dataframe systematically through this way dataframe doesn’t look messy, but in some cases, we are required to read or see the full content of the particular column.
So in this article, we are going to learn how to show the full column content in PySpark Dataframe. The only way to show the full column content we are using show() function.
Syntax: df.show(n, truncate=True)
Where df is the dataframe
show(): Function is used to show the Dataframe.
n: Number of rows to display.
truncate: Through this parameter we can tell the Output sink to display the full column content by setting truncate option to false, by default this value is true.
Example 1: Showing full column content of PySpark Dataframe.
Python
# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSession def create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_details.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Mobile(Fluid Black, 8GB RAM, 128GB Storage)", 112345, 4.0, 12499), ("LED TV", 114567, 4.2, 49999), ("Refrigerator", 123543, 4.4, 13899), ("6.5 kg Fully-Automatic Top Loading Washing Machine \ (WA65A4002VS/TL, Imperial Silver, Center Jet Technology)", 113465, 3.9, 6999), ("T-shirt", 124378, 4.1, 1999), ("Jeans", 126754, 3.7, 3999), ("Men's Casual Shoes in White Sneakers for Outdoor and\ Daily use", 134565, 4.7, 1499), ("Vitamin C Ultra Light Gel Oil-Free Moisturizer", 145234, 4.6, 999), ] schema = ["Name", "ID", "Rating", "Price"] # calling function to create dataframe df = create_df(spark, input_data, schema) # visualizing full content of the Dataframe # by setting truncate to False df.show(truncate=False)
Output:
Example 2: Showing Full column content of the Dataframe by setting truncate to 0.
In the example, we are setting the parameter truncate=0, here if we set any integer from 1 onwards such as 3, then it will show the column content up to three character or integer places, not more than that as shown in the below fig. But here in place of False if we pass 0 this will also act as the False, like in binary number 0 refers to false and show the full column content in the Dataframe.
Python
# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Student_report.com") \ .getOrCreate() return spk def create_df(spark,data,schema): df1 = spark.createDataFrame(data,schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [(1,"Shivansh","Male",80,"Good Performance"), (2,"Arpita","Female",18,"Have to work hard otherwise \ result will not improve"), (3,"Raj","Male",21,"Work hard can do better"), (4,"Swati","Female",69,"Good performance can do more better"), (5,"Arpit","Male",20,"Focus on some subject to improve"), (6,"Swaroop","Male",65,"Good performance"), (7,"Reshabh","Male",70,"Good performance"), (8,"Dinesh","Male",65,"Can do better"), (9,"Rohit","Male",55,"Can do better"), (10,"Sanjana","Female",67,"Have to work hard")] schema = ["ID","Name","Gender","Percentage","Remark"] # calling function to create dataframe df = create_df(spark,input_data,schema) # visualizing full column content of the dataframe by setting truncate to 0 df.show(truncate=0)
Output:
Example 3: Showing Full column content of PySpark Dataframe using show() function.
In the code for showing the full column content we are using show() function by passing parameter df.count(),truncate=False, we can write as df.show(df.count(), truncate=False), here show function takes the first parameter as n i.e, the number of rows to show, since df.count() returns the count of the total number of rows present in the Dataframe, as in the above case total number of rows is 10, so in show() function n is passed as 10 which is nothing but the total number of rows to show.
Python
# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSession def create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Student_report.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [(1, "Shivansh", "Male", (70, 66, 78, 70, 71, 50), 80, "Good Performance"), (2, "Arpita", "Female", (20, 16, 8, 40, 11, 20), 18, "Have to work hard otherwise result will not improve"), (3, "Raj", "Male", (10, 26, 28, 10, 31, 20), 21, "Work hard can do better"), (4, "Swati", "Female", (70, 66, 78, 70, 71, 50), 69, "Good performance can do more better"), (5, "Arpit", "Male", (20, 46, 18, 20, 31, 10), 20, "Focus on some subject to improve"), (6, "Swaroop", "Male", (70, 66, 48, 30, 61, 50), 65, "Good performance"), (7, "Reshabh", "Male", (70, 66, 78, 70, 71, 50), 70, "Good performance"), (8, "Dinesh", "Male", (40, 66, 68, 70, 71, 50), 65, "Can do better"), (9, "Rohit", "Male", (50, 66, 58, 50, 51, 50), 55, "Can do better"), (10, "Sanjana", "Female", (60, 66, 68, 60, 61, 50), 67, "Have to work hard")] schema = ["ID", "Name", "Gender", "Sessionals Marks", "Percentage", "Remark"] # calling function to create dataframe df = create_df(spark, input_data, schema) # visualizing full column content of the # dataframe by setting n and truncate to # False df.show(df.count(), truncate=False)
Output:
adnanirshad158
Picked
Python-Pyspark
Program Output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Sometimes in Dataframe, when column data containing the long content or large sentence, then PySpark SQL shows the dataframe in compressed form means the first few words of the sentence are shown and others are followed by dots that refers that some more data is available."
},
{
"code": null,
"e": 634,
"s": 302,
"text": "From the above sample Dataframe, we can easily see that the content of the Name column is not fully shown. This thing is automatically done by the PySpark to show the dataframe systematically through this way dataframe doesn’t look messy, but in some cases, we are required to read or see the full content of the particular column."
},
{
"code": null,
"e": 809,
"s": 634,
"text": "So in this article, we are going to learn how to show the full column content in PySpark Dataframe. The only way to show the full column content we are using show() function."
},
{
"code": null,
"e": 843,
"s": 809,
"text": "Syntax: df.show(n, truncate=True)"
},
{
"code": null,
"e": 869,
"s": 843,
"text": "Where df is the dataframe"
},
{
"code": null,
"e": 917,
"s": 869,
"text": "show(): Function is used to show the Dataframe."
},
{
"code": null,
"e": 947,
"s": 917,
"text": "n: Number of rows to display."
},
{
"code": null,
"e": 1111,
"s": 947,
"text": "truncate: Through this parameter we can tell the Output sink to display the full column content by setting truncate option to false, by default this value is true."
},
{
"code": null,
"e": 1172,
"s": 1111,
"text": "Example 1: Showing full column content of PySpark Dataframe."
},
{
"code": null,
"e": 1179,
"s": 1172,
"text": "Python"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSession def create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_details.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Mobile(Fluid Black, 8GB RAM, 128GB Storage)\", 112345, 4.0, 12499), (\"LED TV\", 114567, 4.2, 49999), (\"Refrigerator\", 123543, 4.4, 13899), (\"6.5 kg Fully-Automatic Top Loading Washing Machine \\ (WA65A4002VS/TL, Imperial Silver, Center Jet Technology)\", 113465, 3.9, 6999), (\"T-shirt\", 124378, 4.1, 1999), (\"Jeans\", 126754, 3.7, 3999), (\"Men's Casual Shoes in White Sneakers for Outdoor and\\ Daily use\", 134565, 4.7, 1499), (\"Vitamin C Ultra Light Gel Oil-Free Moisturizer\", 145234, 4.6, 999), ] schema = [\"Name\", \"ID\", \"Rating\", \"Price\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # visualizing full content of the Dataframe # by setting truncate to False df.show(truncate=False)",
"e": 2759,
"s": 1179,
"text": null
},
{
"code": null,
"e": 2767,
"s": 2759,
"text": "Output:"
},
{
"code": null,
"e": 2849,
"s": 2767,
"text": "Example 2: Showing Full column content of the Dataframe by setting truncate to 0."
},
{
"code": null,
"e": 3247,
"s": 2849,
"text": "In the example, we are setting the parameter truncate=0, here if we set any integer from 1 onwards such as 3, then it will show the column content up to three character or integer places, not more than that as shown in the below fig. But here in place of False if we pass 0 this will also act as the False, like in binary number 0 refers to false and show the full column content in the Dataframe."
},
{
"code": null,
"e": 3254,
"s": 3247,
"text": "Python"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Student_report.com\") \\ .getOrCreate() return spk def create_df(spark,data,schema): df1 = spark.createDataFrame(data,schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(1,\"Shivansh\",\"Male\",80,\"Good Performance\"), (2,\"Arpita\",\"Female\",18,\"Have to work hard otherwise \\ result will not improve\"), (3,\"Raj\",\"Male\",21,\"Work hard can do better\"), (4,\"Swati\",\"Female\",69,\"Good performance can do more better\"), (5,\"Arpit\",\"Male\",20,\"Focus on some subject to improve\"), (6,\"Swaroop\",\"Male\",65,\"Good performance\"), (7,\"Reshabh\",\"Male\",70,\"Good performance\"), (8,\"Dinesh\",\"Male\",65,\"Can do better\"), (9,\"Rohit\",\"Male\",55,\"Can do better\"), (10,\"Sanjana\",\"Female\",67,\"Have to work hard\")] schema = [\"ID\",\"Name\",\"Gender\",\"Percentage\",\"Remark\"] # calling function to create dataframe df = create_df(spark,input_data,schema) # visualizing full column content of the dataframe by setting truncate to 0 df.show(truncate=0)",
"e": 4549,
"s": 3254,
"text": null
},
{
"code": null,
"e": 4560,
"s": 4552,
"text": "Output:"
},
{
"code": null,
"e": 4645,
"s": 4562,
"text": "Example 3: Showing Full column content of PySpark Dataframe using show() function."
},
{
"code": null,
"e": 5141,
"s": 4647,
"text": "In the code for showing the full column content we are using show() function by passing parameter df.count(),truncate=False, we can write as df.show(df.count(), truncate=False), here show function takes the first parameter as n i.e, the number of rows to show, since df.count() returns the count of the total number of rows present in the Dataframe, as in the above case total number of rows is 10, so in show() function n is passed as 10 which is nothing but the total number of rows to show."
},
{
"code": null,
"e": 5150,
"s": 5143,
"text": "Python"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSession def create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Student_report.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(1, \"Shivansh\", \"Male\", (70, 66, 78, 70, 71, 50), 80, \"Good Performance\"), (2, \"Arpita\", \"Female\", (20, 16, 8, 40, 11, 20), 18, \"Have to work hard otherwise result will not improve\"), (3, \"Raj\", \"Male\", (10, 26, 28, 10, 31, 20), 21, \"Work hard can do better\"), (4, \"Swati\", \"Female\", (70, 66, 78, 70, 71, 50), 69, \"Good performance can do more better\"), (5, \"Arpit\", \"Male\", (20, 46, 18, 20, 31, 10), 20, \"Focus on some subject to improve\"), (6, \"Swaroop\", \"Male\", (70, 66, 48, 30, 61, 50), 65, \"Good performance\"), (7, \"Reshabh\", \"Male\", (70, 66, 78, 70, 71, 50), 70, \"Good performance\"), (8, \"Dinesh\", \"Male\", (40, 66, 68, 70, 71, 50), 65, \"Can do better\"), (9, \"Rohit\", \"Male\", (50, 66, 58, 50, 51, 50), 55, \"Can do better\"), (10, \"Sanjana\", \"Female\", (60, 66, 68, 60, 61, 50), 67, \"Have to work hard\")] schema = [\"ID\", \"Name\", \"Gender\", \"Sessionals Marks\", \"Percentage\", \"Remark\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # visualizing full column content of the # dataframe by setting n and truncate to # False df.show(df.count(), truncate=False)",
"e": 7230,
"s": 5150,
"text": null
},
{
"code": null,
"e": 7238,
"s": 7230,
"text": "Output:"
},
{
"code": null,
"e": 7253,
"s": 7238,
"text": "adnanirshad158"
},
{
"code": null,
"e": 7260,
"s": 7253,
"text": "Picked"
},
{
"code": null,
"e": 7275,
"s": 7260,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 7290,
"s": 7275,
"text": "Program Output"
},
{
"code": null,
"e": 7297,
"s": 7290,
"text": "Python"
}
] |
NLP | Part of speech tagged – word corpus
|
11 Apr, 2022
What is Part-of-speech (POS) tagging ? It is a process of converting a sentence to forms – list of words, list of tuples (where each tuple is having a form (word, tag)). The tag in case of is a part-of-speech tag, and signifies whether the word is a noun, adjective, verb, and so on.
Example of Part-of-speech (POS) tagged corpus
The/at-tl expense/nn and/cc time/nn involved/vbn are/ber astronomical/jj ./.
format for a tagged corpus is of the form word/tag. Each word is with a tag denoting its POS. For example, nn refers to a noun, vb is a verb.
Code #1 : Creating a TaggedCorpusReader. for words
Python3
# Using TaggedCorpusReaderfrom nltk.corpus.reader import TaggedCorpusReader # initializingx = TaggedCorpusReader('.', r'.*\.pos') words = x.words()print ("Words : \n", words) tag_words = x.tagged_words()print ("\ntag_words : \n", tag_words)
Output :
Words :
['The', 'expense', 'and', 'time', 'involved', 'are', ...]
tag_words :
[('The', 'AT-TL'), ('expense', 'NN'), ('and', 'CC'), ...]
Code #2 : For sentence
Python3
tagged_sent = x.tagged_sents()print ("tagged_sent : \n", tagged_sent)
Output :
tagged_sent :
[[('The', 'AT-TL'), ('expense', 'NN'), ('and', 'CC'), ('time', 'NN'),
('involved', 'VBN'), ('are', 'BER'), ('astronomical', 'JJ'), ('.', '.')]]
Code #3 : For paragraphs
Python3
para = x.para()print ("para : \n", para) tagged_para = x.tagged_paras()print ("\ntagged_paras : \n", tagged_paras)
Output :
para:
[[['The', 'expense', 'and', 'time', 'involved', 'are', 'astronomical', '.']]]
tagged_paras :
[[[('The', 'AT-TL'), ('expense', 'NN'), ('and', 'CC'), ('time', 'NN'),
('involved', 'VBN'), ('are', 'BER'), ('astronomical', 'JJ'), ('.', '.')]]]
simranarora5sos
abhisheksharma975689
rkbhola5
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "What is Part-of-speech (POS) tagging ? It is a process of converting a sentence to forms – list of words, list of tuples (where each tuple is having a form (word, tag)). The tag in case of is a part-of-speech tag, and signifies whether the word is a noun, adjective, verb, and so on. "
},
{
"code": null,
"e": 360,
"s": 313,
"text": "Example of Part-of-speech (POS) tagged corpus "
},
{
"code": null,
"e": 437,
"s": 360,
"text": "The/at-tl expense/nn and/cc time/nn involved/vbn are/ber astronomical/jj ./."
},
{
"code": null,
"e": 580,
"s": 437,
"text": "format for a tagged corpus is of the form word/tag. Each word is with a tag denoting its POS. For example, nn refers to a noun, vb is a verb. "
},
{
"code": null,
"e": 632,
"s": 580,
"text": "Code #1 : Creating a TaggedCorpusReader. for words "
},
{
"code": null,
"e": 640,
"s": 632,
"text": "Python3"
},
{
"code": "# Using TaggedCorpusReaderfrom nltk.corpus.reader import TaggedCorpusReader # initializingx = TaggedCorpusReader('.', r'.*\\.pos') words = x.words()print (\"Words : \\n\", words) tag_words = x.tagged_words()print (\"\\ntag_words : \\n\", tag_words)",
"e": 887,
"s": 640,
"text": null
},
{
"code": null,
"e": 897,
"s": 887,
"text": "Output : "
},
{
"code": null,
"e": 1036,
"s": 897,
"text": "Words : \n['The', 'expense', 'and', 'time', 'involved', 'are', ...]\n\ntag_words : \n[('The', 'AT-TL'), ('expense', 'NN'), ('and', 'CC'), ...]"
},
{
"code": null,
"e": 1061,
"s": 1036,
"text": "Code #2 : For sentence "
},
{
"code": null,
"e": 1069,
"s": 1061,
"text": "Python3"
},
{
"code": "tagged_sent = x.tagged_sents()print (\"tagged_sent : \\n\", tagged_sent)",
"e": 1139,
"s": 1069,
"text": null
},
{
"code": null,
"e": 1149,
"s": 1139,
"text": "Output : "
},
{
"code": null,
"e": 1308,
"s": 1149,
"text": "tagged_sent : \n[[('The', 'AT-TL'), ('expense', 'NN'), ('and', 'CC'), ('time', 'NN'),\n('involved', 'VBN'), ('are', 'BER'), ('astronomical', 'JJ'), ('.', '.')]]"
},
{
"code": null,
"e": 1335,
"s": 1308,
"text": "Code #3 : For paragraphs "
},
{
"code": null,
"e": 1343,
"s": 1335,
"text": "Python3"
},
{
"code": "para = x.para()print (\"para : \\n\", para) tagged_para = x.tagged_paras()print (\"\\ntagged_paras : \\n\", tagged_paras)",
"e": 1460,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1460,
"text": "Output : "
},
{
"code": null,
"e": 1719,
"s": 1470,
"text": "para: \n[[['The', 'expense', 'and', 'time', 'involved', 'are', 'astronomical', '.']]]\n\ntagged_paras : \n[[[('The', 'AT-TL'), ('expense', 'NN'), ('and', 'CC'), ('time', 'NN'),\n('involved', 'VBN'), ('are', 'BER'), ('astronomical', 'JJ'), ('.', '.')]]] "
},
{
"code": null,
"e": 1737,
"s": 1721,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1758,
"s": 1737,
"text": "abhisheksharma975689"
},
{
"code": null,
"e": 1767,
"s": 1758,
"text": "rkbhola5"
},
{
"code": null,
"e": 1795,
"s": 1767,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 1807,
"s": 1795,
"text": "Python-nltk"
},
{
"code": null,
"e": 1824,
"s": 1807,
"text": "Machine Learning"
},
{
"code": null,
"e": 1831,
"s": 1824,
"text": "Python"
},
{
"code": null,
"e": 1848,
"s": 1831,
"text": "Machine Learning"
}
] |
How to convert a dictionary into a NumPy array?
|
25 Aug, 2020
It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a dictionary into NumPy array but before applying this method we have to do some pre-task. As a pre-task follow this simple three steps
First of all call dict.items() to return a group of the key-value pairs in the dictionary. Then use list(obj) with this group as an object to convert it to a list. At last, call numpy.array(data) with this list as data to convert it to an array.
First of all call dict.items() to return a group of the key-value pairs in the dictionary.
Then use list(obj) with this group as an object to convert it to a list.
At last, call numpy.array(data) with this list as data to convert it to an array.
Syntax:
numpy.array(object, dtype = None, *, copy = True, order = ‘K’, subok = False, ndmin = 0)
Parameters:
object: An array, any object exposing the array interface
dtype: The desired data-type for the array.
copy: If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy
order: Specify the memory layout of the array
subok: If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default)
ndmin: Specifies the minimum number of dimensions that the resulting array should have.
Returns:
ndarray: An array object satisfying the specified requirements.
Example 1:
Python
# Python program to convert# dictionary to numpy array # Import required packageimport numpy as np # Creating a Dictionary# with Integer Keysdict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # to return a group of the key-value# pairs in the dictionaryresult = dict.items() # Convert object to a listdata = list(result) # Convert list to an arraynumpyArray = np.array(data) # print the numpy arrayprint(numpyArray)
Output:
[['1' 'Geeks']
['2' 'For']
['3' 'Geeks']]
Example 2:
Python
# Python program to convert# dictionary to numpy array # Import required packageimport numpy as np # Creating a Nested Dictionarydict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'} } # to return a group of the key-value# pairs in the dictionaryresult = dict.items() # Convert object to a listdata = list(result) # Convert list to an arraynumpyArray = np.array(data) # print the numpy arrayprint(numpyArray)
Output:
[[1 'Geeks']
[2 'For']
[3 {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}]]
Example 3:
Python
# Python program to convert# dictionary to numpy array # Import required packageimport numpy as np # Creating a Dictionary# with Mixed keysdict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} # to return a group of the key-value# pairs in the dictionaryresult = dict.items() # Convert object to a listdata = list(result) # Convert list to an arraynumpyArray = np.array(data) # print the numpy arrayprint(numpyArray)
Output:
[['Name' 'Geeks']
[1 list([1, 2, 3, 4])]]
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 462,
"s": 28,
"text": "It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a dictionary into NumPy array but before applying this method we have to do some pre-task. As a pre-task follow this simple three steps"
},
{
"code": null,
"e": 708,
"s": 462,
"text": "First of all call dict.items() to return a group of the key-value pairs in the dictionary. Then use list(obj) with this group as an object to convert it to a list. At last, call numpy.array(data) with this list as data to convert it to an array."
},
{
"code": null,
"e": 800,
"s": 708,
"text": "First of all call dict.items() to return a group of the key-value pairs in the dictionary. "
},
{
"code": null,
"e": 874,
"s": 800,
"text": "Then use list(obj) with this group as an object to convert it to a list. "
},
{
"code": null,
"e": 956,
"s": 874,
"text": "At last, call numpy.array(data) with this list as data to convert it to an array."
},
{
"code": null,
"e": 964,
"s": 956,
"text": "Syntax:"
},
{
"code": null,
"e": 1053,
"s": 964,
"text": "numpy.array(object, dtype = None, *, copy = True, order = ‘K’, subok = False, ndmin = 0)"
},
{
"code": null,
"e": 1065,
"s": 1053,
"text": "Parameters:"
},
{
"code": null,
"e": 1123,
"s": 1065,
"text": "object: An array, any object exposing the array interface"
},
{
"code": null,
"e": 1168,
"s": 1123,
"text": "dtype: The desired data-type for the array. "
},
{
"code": null,
"e": 1284,
"s": 1168,
"text": "copy: If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy"
},
{
"code": null,
"e": 1330,
"s": 1284,
"text": "order: Specify the memory layout of the array"
},
{
"code": null,
"e": 1466,
"s": 1330,
"text": "subok: If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default)"
},
{
"code": null,
"e": 1554,
"s": 1466,
"text": "ndmin: Specifies the minimum number of dimensions that the resulting array should have."
},
{
"code": null,
"e": 1563,
"s": 1554,
"text": "Returns:"
},
{
"code": null,
"e": 1627,
"s": 1563,
"text": "ndarray: An array object satisfying the specified requirements."
},
{
"code": null,
"e": 1638,
"s": 1627,
"text": "Example 1:"
},
{
"code": null,
"e": 1645,
"s": 1638,
"text": "Python"
},
{
"code": "# Python program to convert# dictionary to numpy array # Import required packageimport numpy as np # Creating a Dictionary# with Integer Keysdict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # to return a group of the key-value# pairs in the dictionaryresult = dict.items() # Convert object to a listdata = list(result) # Convert list to an arraynumpyArray = np.array(data) # print the numpy arrayprint(numpyArray)",
"e": 2072,
"s": 1645,
"text": null
},
{
"code": null,
"e": 2080,
"s": 2072,
"text": "Output:"
},
{
"code": null,
"e": 2125,
"s": 2080,
"text": "[['1' 'Geeks']\n ['2' 'For']\n ['3' 'Geeks']]\n"
},
{
"code": null,
"e": 2136,
"s": 2125,
"text": "Example 2:"
},
{
"code": null,
"e": 2143,
"s": 2136,
"text": "Python"
},
{
"code": "# Python program to convert# dictionary to numpy array # Import required packageimport numpy as np # Creating a Nested Dictionarydict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'} } # to return a group of the key-value# pairs in the dictionaryresult = dict.items() # Convert object to a listdata = list(result) # Convert list to an arraynumpyArray = np.array(data) # print the numpy arrayprint(numpyArray)",
"e": 2622,
"s": 2143,
"text": null
},
{
"code": null,
"e": 2630,
"s": 2622,
"text": "Output:"
},
{
"code": null,
"e": 2703,
"s": 2630,
"text": "[[1 'Geeks']\n [2 'For']\n [3 {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}]]\n"
},
{
"code": null,
"e": 2714,
"s": 2703,
"text": "Example 3:"
},
{
"code": null,
"e": 2721,
"s": 2714,
"text": "Python"
},
{
"code": "# Python program to convert# dictionary to numpy array # Import required packageimport numpy as np # Creating a Dictionary# with Mixed keysdict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} # to return a group of the key-value# pairs in the dictionaryresult = dict.items() # Convert object to a listdata = list(result) # Convert list to an arraynumpyArray = np.array(data) # print the numpy arrayprint(numpyArray)",
"e": 3139,
"s": 2721,
"text": null
},
{
"code": null,
"e": 3147,
"s": 3139,
"text": "Output:"
},
{
"code": null,
"e": 3192,
"s": 3147,
"text": "[['Name' 'Geeks']\n [1 list([1, 2, 3, 4])]]\n\n"
},
{
"code": null,
"e": 3213,
"s": 3192,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 3226,
"s": 3213,
"text": "Python-numpy"
},
{
"code": null,
"e": 3233,
"s": 3226,
"text": "Python"
}
] |
Overlapping Histograms with Matplotlib in Python
|
26 Nov, 2020
Histograms are a way of visualizing the data. Here, we will learn how to plot overlapping histograms in python using Matplotlib library. matplotlib.pyplot.hist() is used for making histograms.
Let’s take the iris dataset and plot various overlapping histograms with Matplotlib.
Step 1: Import the libraries
Python3
# importing librariesimport matplotlib.pyplot as pltimport seaborn as sns
Step 2: Load the dataset
Python3
# load the iris datasetdata = sns.load_dataset('iris') # view the datasetprint(data.head(5))
Step 3: Let us plot histograms for sepal_length and petal_length.
Python3
# plotting histogramsplt.hist(data['petal_length'], label='petal_length') plt.hist(data['sepal_length'], label='sepal_length') plt.legend(loc='upper right')plt.title('Overlapping')plt.show()
Here, we can see that some part of the histogram for ‘petal_length’ has been hidden behind the histogram for ‘sepal_length’. To properly visualize both the histograms, we need to set the transparency parameter, alpha to a suitable value. So let’s check various values for alpha and find out the suitable one.
Step 4: Set alpha=0.5 for both sepal_length and petal_length
Python3
plt.hist(data['petal_length'], alpha=0.5, # the transaparency parameter label='petal_length') plt.hist(data['sepal_length'], alpha=0.5, label='sepal_length') plt.legend(loc='upper right')plt.title('Overlapping with both alpha=0.5')plt.show()
Step 5: Set alpha=0.1 for sepal_length and 0.9 for petal_length
Python3
plt.hist(data['petal_length'], alpha=0.9, label='petal_length') plt.hist(data['sepal_length'], alpha=0.1, label='sepal_length') plt.legend(loc='upper right')plt.title('Overlapping with alpha=0.1 and 0.9 for sepal and petal')plt.show()
Through the above two steps, we can infer that for a better visualization for both the histograms, alpha=0.5 would be the most suitable option for the transparency parameter.
Now, to plot more than two overlapping histograms where we need custom colors, let’s follow step 6.
Step 6: Create more than 2 overlapping histograms with customized colors.
Python3
# plotting more than 2 overlapping histogramsplt.hist(data['sepal_width'], alpha=0.5, label='sepal_width', color='red') # customized color parameter plt.hist(data['petal_width'], alpha=0.5, label='petal_width', color='green') plt.hist(data['petal_length'], alpha=0.5, label='petal_length', color='yellow') plt.hist(data['sepal_length'], alpha=0.5, label='sepal_length', color='purple') plt.legend(loc='upper right')plt.show()
Thus, in this article, we learned how to plot overlapping histograms using Matplotlib, how to set their transparency values, and customize their colors.
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "Histograms are a way of visualizing the data. Here, we will learn how to plot overlapping histograms in python using Matplotlib library. matplotlib.pyplot.hist() is used for making histograms."
},
{
"code": null,
"e": 306,
"s": 221,
"text": "Let’s take the iris dataset and plot various overlapping histograms with Matplotlib."
},
{
"code": null,
"e": 335,
"s": 306,
"text": "Step 1: Import the libraries"
},
{
"code": null,
"e": 343,
"s": 335,
"text": "Python3"
},
{
"code": "# importing librariesimport matplotlib.pyplot as pltimport seaborn as sns",
"e": 417,
"s": 343,
"text": null
},
{
"code": null,
"e": 442,
"s": 417,
"text": "Step 2: Load the dataset"
},
{
"code": null,
"e": 450,
"s": 442,
"text": "Python3"
},
{
"code": "# load the iris datasetdata = sns.load_dataset('iris') # view the datasetprint(data.head(5))",
"e": 544,
"s": 450,
"text": null
},
{
"code": null,
"e": 610,
"s": 544,
"text": "Step 3: Let us plot histograms for sepal_length and petal_length."
},
{
"code": null,
"e": 618,
"s": 610,
"text": "Python3"
},
{
"code": "# plotting histogramsplt.hist(data['petal_length'], label='petal_length') plt.hist(data['sepal_length'], label='sepal_length') plt.legend(loc='upper right')plt.title('Overlapping')plt.show()",
"e": 829,
"s": 618,
"text": null
},
{
"code": null,
"e": 1138,
"s": 829,
"text": "Here, we can see that some part of the histogram for ‘petal_length’ has been hidden behind the histogram for ‘sepal_length’. To properly visualize both the histograms, we need to set the transparency parameter, alpha to a suitable value. So let’s check various values for alpha and find out the suitable one."
},
{
"code": null,
"e": 1199,
"s": 1138,
"text": "Step 4: Set alpha=0.5 for both sepal_length and petal_length"
},
{
"code": null,
"e": 1207,
"s": 1199,
"text": "Python3"
},
{
"code": "plt.hist(data['petal_length'], alpha=0.5, # the transaparency parameter label='petal_length') plt.hist(data['sepal_length'], alpha=0.5, label='sepal_length') plt.legend(loc='upper right')plt.title('Overlapping with both alpha=0.5')plt.show()",
"e": 1484,
"s": 1207,
"text": null
},
{
"code": null,
"e": 1548,
"s": 1484,
"text": "Step 5: Set alpha=0.1 for sepal_length and 0.9 for petal_length"
},
{
"code": null,
"e": 1556,
"s": 1548,
"text": "Python3"
},
{
"code": "plt.hist(data['petal_length'], alpha=0.9, label='petal_length') plt.hist(data['sepal_length'], alpha=0.1, label='sepal_length') plt.legend(loc='upper right')plt.title('Overlapping with alpha=0.1 and 0.9 for sepal and petal')plt.show()",
"e": 1826,
"s": 1556,
"text": null
},
{
"code": null,
"e": 2001,
"s": 1826,
"text": "Through the above two steps, we can infer that for a better visualization for both the histograms, alpha=0.5 would be the most suitable option for the transparency parameter."
},
{
"code": null,
"e": 2101,
"s": 2001,
"text": "Now, to plot more than two overlapping histograms where we need custom colors, let’s follow step 6."
},
{
"code": null,
"e": 2175,
"s": 2101,
"text": "Step 6: Create more than 2 overlapping histograms with customized colors."
},
{
"code": null,
"e": 2183,
"s": 2175,
"text": "Python3"
},
{
"code": "# plotting more than 2 overlapping histogramsplt.hist(data['sepal_width'], alpha=0.5, label='sepal_width', color='red') # customized color parameter plt.hist(data['petal_width'], alpha=0.5, label='petal_width', color='green') plt.hist(data['petal_length'], alpha=0.5, label='petal_length', color='yellow') plt.hist(data['sepal_length'], alpha=0.5, label='sepal_length', color='purple') plt.legend(loc='upper right')plt.show()",
"e": 2714,
"s": 2183,
"text": null
},
{
"code": null,
"e": 2867,
"s": 2714,
"text": "Thus, in this article, we learned how to plot overlapping histograms using Matplotlib, how to set their transparency values, and customize their colors."
},
{
"code": null,
"e": 2885,
"s": 2867,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2892,
"s": 2885,
"text": "Python"
}
] |
Node-RED
|
08 Feb, 2022
NODE-RED is a stream based advancement instrument for visual programming and basically its main focus on visual apparatus for wiring the Internet of Things. This programming instrument is developed for wiring together equipment gadget(Hardware), APIs and online administrations in new and intriguing manners.
Developed by: At first, it is developed by IBM Emerging Technology organization and it is a free source programming instrument.
Developers:
Nick O’Leary
Dave Conway-Jones
Latest version: v1.0.6 (npm) Written In: JavaScript
A NODE-RED stream works by passing messages between hubs. The messages in NODE-RED are straightforward JavaScript objects that can have any arrangement of properties.
Installing NODE-RED
Installing with npm (Node package manager)
sudo npm install -g --unsafe-perm node-red
If you have installed Node-RED as a global npm package, you can upgrade to the latest version with the following command:
sudo npm install -g --unsafe-perm node-red
Installing with docker
docker run -it -p 1880:1880 --name mynodered nodered/node-red
Installing with snap
sudo snap install node-red
Running NODE-RED:
When the Node-RED establishment and introductory arrangement is finished, it can be used. Three ways to run NODE-RED:
Locally On a device In the identified cloud environment
Locally
On a device
In the identified cloud environment
Top reasons to use NODE-RED: Browser-based flow editing:
Browser-based flow editing
It provides a browser-based editor that makes it easy to wire together flows using the wide range of nodes in the palette that can be deployed to its runtime in a single-click.
Written in JavaScript:
javascript
Thus, it is build in javascript then NODE-RED took all the advantages of this language that is Event-Based Programming language, Procedural programming capabilities, Platform independent and beyond all this it comparatively fast and easy to learn.
Easily Run on various Operating System: Raspbian, Ubuntu,Windows,Docker,Debian, macOS and Other’s
Not just for IoT: It has increased enormous approval in the IoT space, by demonstrating bits of use between IoT gadgets like sensors, cameras, and remote switches. Beyond IoT, it can hold so many ready-made nodes when someone wants to design any creative feature.
List of Cloud and pre-installed Devices:
Cloud
NODE-RED makes it perfect to run at the edge of the system on minimal effort equipment. For example, the Raspberry Pi as well as in the cloud.
Cloud are:
IBM CloudSenseTecnic FREDAmazon Web ServicesMicrosoft Azure
IBM Cloud
SenseTecnic FRED
Amazon Web Services
Microsoft Azure
Pre-installed Device:
Raspberry PiBeagleBone BlackInteracting with ArduinoAndroid
Raspberry Pi
BeagleBone Black
Interacting with Arduino
Android
Types of NODE: Inject Node:
This node permits manual activating of streams.
It encourages us to infuse occasions at booked spans.
Debug Node: This node helps in showing the substance of a message—either the payload or the whole item.
Template Node: Adjusts the yield dependent on a Mustache (rationale less) layout.
There are various input, output and function nodes:
rkbhola5
JavaScript-Misc
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
REST API (Introduction)
Node.js fs.readFileSync() Method
How to float three div side by side using CSS?
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 363,
"s": 54,
"text": "NODE-RED is a stream based advancement instrument for visual programming and basically its main focus on visual apparatus for wiring the Internet of Things. This programming instrument is developed for wiring together equipment gadget(Hardware), APIs and online administrations in new and intriguing manners."
},
{
"code": null,
"e": 492,
"s": 363,
"text": "Developed by: At first, it is developed by IBM Emerging Technology organization and it is a free source programming instrument. "
},
{
"code": null,
"e": 506,
"s": 492,
"text": "Developers: "
},
{
"code": null,
"e": 519,
"s": 506,
"text": "Nick O’Leary"
},
{
"code": null,
"e": 537,
"s": 519,
"text": "Dave Conway-Jones"
},
{
"code": null,
"e": 592,
"s": 537,
"text": "Latest version: v1.0.6 (npm) Written In: JavaScript "
},
{
"code": null,
"e": 759,
"s": 592,
"text": "A NODE-RED stream works by passing messages between hubs. The messages in NODE-RED are straightforward JavaScript objects that can have any arrangement of properties."
},
{
"code": null,
"e": 780,
"s": 759,
"text": "Installing NODE-RED "
},
{
"code": null,
"e": 823,
"s": 780,
"text": "Installing with npm (Node package manager)"
},
{
"code": null,
"e": 866,
"s": 823,
"text": "sudo npm install -g --unsafe-perm node-red"
},
{
"code": null,
"e": 988,
"s": 866,
"text": "If you have installed Node-RED as a global npm package, you can upgrade to the latest version with the following command:"
},
{
"code": null,
"e": 1031,
"s": 988,
"text": "sudo npm install -g --unsafe-perm node-red"
},
{
"code": null,
"e": 1054,
"s": 1031,
"text": "Installing with docker"
},
{
"code": null,
"e": 1116,
"s": 1054,
"text": "docker run -it -p 1880:1880 --name mynodered nodered/node-red"
},
{
"code": null,
"e": 1139,
"s": 1118,
"text": "Installing with snap"
},
{
"code": null,
"e": 1166,
"s": 1139,
"text": "sudo snap install node-red"
},
{
"code": null,
"e": 1184,
"s": 1166,
"text": "Running NODE-RED:"
},
{
"code": null,
"e": 1302,
"s": 1184,
"text": "When the Node-RED establishment and introductory arrangement is finished, it can be used. Three ways to run NODE-RED:"
},
{
"code": null,
"e": 1360,
"s": 1304,
"text": "Locally On a device In the identified cloud environment"
},
{
"code": null,
"e": 1369,
"s": 1360,
"text": "Locally "
},
{
"code": null,
"e": 1382,
"s": 1369,
"text": "On a device "
},
{
"code": null,
"e": 1418,
"s": 1382,
"text": "In the identified cloud environment"
},
{
"code": null,
"e": 1475,
"s": 1418,
"text": "Top reasons to use NODE-RED: Browser-based flow editing:"
},
{
"code": null,
"e": 1502,
"s": 1475,
"text": "Browser-based flow editing"
},
{
"code": null,
"e": 1681,
"s": 1502,
"text": "It provides a browser-based editor that makes it easy to wire together flows using the wide range of nodes in the palette that can be deployed to its runtime in a single-click. "
},
{
"code": null,
"e": 1706,
"s": 1681,
"text": "Written in JavaScript: "
},
{
"code": null,
"e": 1717,
"s": 1706,
"text": "javascript"
},
{
"code": null,
"e": 1965,
"s": 1717,
"text": "Thus, it is build in javascript then NODE-RED took all the advantages of this language that is Event-Based Programming language, Procedural programming capabilities, Platform independent and beyond all this it comparatively fast and easy to learn."
},
{
"code": null,
"e": 2065,
"s": 1965,
"text": " Easily Run on various Operating System: Raspbian, Ubuntu,Windows,Docker,Debian, macOS and Other’s "
},
{
"code": null,
"e": 2330,
"s": 2065,
"text": "Not just for IoT: It has increased enormous approval in the IoT space, by demonstrating bits of use between IoT gadgets like sensors, cameras, and remote switches. Beyond IoT, it can hold so many ready-made nodes when someone wants to design any creative feature. "
},
{
"code": null,
"e": 2373,
"s": 2330,
"text": "List of Cloud and pre-installed Devices: "
},
{
"code": null,
"e": 2379,
"s": 2373,
"text": "Cloud"
},
{
"code": null,
"e": 2523,
"s": 2379,
"text": "NODE-RED makes it perfect to run at the edge of the system on minimal effort equipment. For example, the Raspberry Pi as well as in the cloud. "
},
{
"code": null,
"e": 2534,
"s": 2523,
"text": "Cloud are:"
},
{
"code": null,
"e": 2594,
"s": 2534,
"text": "IBM CloudSenseTecnic FREDAmazon Web ServicesMicrosoft Azure"
},
{
"code": null,
"e": 2604,
"s": 2594,
"text": "IBM Cloud"
},
{
"code": null,
"e": 2621,
"s": 2604,
"text": "SenseTecnic FRED"
},
{
"code": null,
"e": 2641,
"s": 2621,
"text": "Amazon Web Services"
},
{
"code": null,
"e": 2657,
"s": 2641,
"text": "Microsoft Azure"
},
{
"code": null,
"e": 2679,
"s": 2657,
"text": "Pre-installed Device:"
},
{
"code": null,
"e": 2741,
"s": 2681,
"text": "Raspberry PiBeagleBone BlackInteracting with ArduinoAndroid"
},
{
"code": null,
"e": 2754,
"s": 2741,
"text": "Raspberry Pi"
},
{
"code": null,
"e": 2771,
"s": 2754,
"text": "BeagleBone Black"
},
{
"code": null,
"e": 2796,
"s": 2771,
"text": "Interacting with Arduino"
},
{
"code": null,
"e": 2804,
"s": 2796,
"text": "Android"
},
{
"code": null,
"e": 2832,
"s": 2804,
"text": "Types of NODE: Inject Node:"
},
{
"code": null,
"e": 2882,
"s": 2832,
"text": "This node permits manual activating of streams. "
},
{
"code": null,
"e": 2936,
"s": 2882,
"text": "It encourages us to infuse occasions at booked spans."
},
{
"code": null,
"e": 3041,
"s": 2936,
"text": "Debug Node: This node helps in showing the substance of a message—either the payload or the whole item. "
},
{
"code": null,
"e": 3124,
"s": 3041,
"text": "Template Node: Adjusts the yield dependent on a Mustache (rationale less) layout. "
},
{
"code": null,
"e": 3176,
"s": 3124,
"text": "There are various input, output and function nodes:"
},
{
"code": null,
"e": 3191,
"s": 3182,
"text": "rkbhola5"
},
{
"code": null,
"e": 3207,
"s": 3191,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3224,
"s": 3207,
"text": "Web Technologies"
},
{
"code": null,
"e": 3322,
"s": 3224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3383,
"s": 3322,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3426,
"s": 3383,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3498,
"s": 3426,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3538,
"s": 3498,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3580,
"s": 3538,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3604,
"s": 3580,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3637,
"s": 3604,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3684,
"s": 3637,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 3744,
"s": 3684,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Minimum number of nodes in an AVL Tree with given height - GeeksforGeeks
|
18 Jun, 2021
Given the height of an AVL tree ‘h’, the task is to find the minimum number of nodes the tree can have.
Examples :
Input : H = 0
Output : N = 1
Only '1' node is possible if the height
of the tree is '0' which is the root node.
Input : H = 3
Output : N = 7
Recursive Approach : In an AVL tree, we have to maintain the height balance property, i.e. difference in the height of the left and the right subtrees can not be other than -1, 0 or 1 for each node.
We will try to create a recurrence relation to find minimum number of nodes for a given height, n(h).
For height = 0, we can only have a single node in an AVL tree, i.e. n(0) = 1
For height = 1, we can have a minimum of two nodes in an AVL tree, i.e. n(1) = 2
Now for any height ‘h’, root will have two subtrees (left and right). Out of which one has to be of height h-1 and other of h-2. [root node excluded]
So, n(h) = 1 + n(h-1) + n(h-2) is the required recurrence relation for h>=2 [1 is added for the root node]
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find// minimum number of nodesint AVLnodes(int height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver Codeint main(){ int H = 3; cout << AVLnodes(H) << endl;}
// Java implementation of the approach class GFG{ // Function to find// minimum number of nodesstatic int AVLnodes(int height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver Codepublic static void main(String args[]){ int H = 3; System.out.println(AVLnodes(H));}}
# Python3 implementation of the approach # Function to find minimum# number of nodesdef AVLnodes(height): # Base Conditions if (height == 0): return 1 elif (height == 1): return 2 # Recursive function call # for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2)) # Driver Codeif __name__ == '__main__': H = 3 print(AVLnodes(H)) # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ // Function to find// minimum number of nodesstatic int AVLnodes(int height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver Codepublic static void Main(){ int H = 3; Console.Write(AVLnodes(H));}} // This code is contributed// by Akanksha Rai
<?php// PHP implementation of the approach // Function to find minimum// number of nodesfunction AVLnodes($height){ // Base Conditions if ($height == 0) return 1; else if ($height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes($height - 1) + AVLnodes($height - 2));} // Driver Code$H = 3;echo(AVLnodes($H)); // This code is contributed// by Code_Mech.
<script> // Javascript implementation of the approach // Function to find// minimum number of nodesfunction AVLnodes(height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver codelet H = 3; document.write(AVLnodes(H)); // This code is contributed by decode2207 </script>
7
Tail Recursive Approach :
The recursive function for finding n(h) (minimum number of nodes possible in an AVL Tree with height ‘h’) is n(h) = 1 + n(h-1) + n(h-2) ; h>=2 ; n(0)=1 ; n(1)=2;
To create a Tail Recursive Function, we will maintain 1 + n(h-1) + n(h-2) as function arguments such that rather than calculating it, we directly return its value to main function.
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return//minimum number of nodesint AVLtree(int H, int a = 1, int b = 2){ // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1);} // Driver Codeint main(){ int H = 5; int answer = AVLtree(H); // Output the result cout << "n(" << H << ") = " << answer << endl; return 0;}
// Java implementation of the approachclass GFG{ // Function to return//minimum number of nodesstatic int AVLtree(int H, int a, int b){ // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1);} // Driver Codepublic static void main(String[] args){ int H = 5; int answer = AVLtree(H, 1, 2); // Output the result System.out.println("n(" + H + ") = " + answer);}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # Function to return# minimum number of nodesdef AVLtree(H, a, b): # Base Conditions if(H == 0): return 1; if(H == 1): return b; # Tail Recursive Call return AVLtree(H - 1, b, a + b + 1); # Driver Codeif __name__ == '__main__': H = 5; answer = AVLtree(H, 1, 2); # Output the result print("n(", H , ") = "\ , answer); # This code is contributed by 29AjayKumar
// C# implementation of the approachusing System; class GFG{ // Function to return//minimum number of nodesstatic int AVLtree(int H, int a, int b){ // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1);} // Driver Codepublic static void Main(String[] args){ int H = 5; int answer = AVLtree(H, 1, 2); // Output the result Console.WriteLine("n(" + H + ") = " + answer);}} // This code is contributed by Princi Singh
<script> // Javascript implementation of the approach // Function to return //minimum number of nodes function AVLtree(H, a, b) { // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1); } let H = 5; let answer = AVLtree(H, 1, 2); // Output the result document.write("n(" + H + ") = " + answer); // This code is contributed by mukesh07.</script>
n(5) = 20
krikti
tufan_gupta2000
SURENDRA_GANGWAR
Akanksha_Rai
Code_Mech
princiraj1992
princi singh
29AjayKumar
decode2207
mukesh07
AVL-Tree
Self-Balancing-BST
Binary Search Tree
Binary Search Tree
AVL-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
set vs unordered_set in C++ STL
Floor and Ceil from a BST
Check if a triplet with given sum exists in BST
Construct BST from given preorder traversal | Set 2
Convert BST to Min Heap
Print BST keys in the given range
Red Black Tree vs AVL Tree
Optimal sequence for AVL tree insertion (without any rotations)
Construct a Binary Search Tree from given postorder
Find the largest BST subtree in a given Binary Tree | Set 1
|
[
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n18 Jun, 2021"
},
{
"code": null,
"e": 25328,
"s": 25224,
"text": "Given the height of an AVL tree ‘h’, the task is to find the minimum number of nodes the tree can have."
},
{
"code": null,
"e": 25340,
"s": 25328,
"text": "Examples : "
},
{
"code": null,
"e": 25483,
"s": 25340,
"text": "Input : H = 0\nOutput : N = 1\nOnly '1' node is possible if the height \nof the tree is '0' which is the root node.\n\nInput : H = 3\nOutput : N = 7"
},
{
"code": null,
"e": 25683,
"s": 25483,
"text": "Recursive Approach : In an AVL tree, we have to maintain the height balance property, i.e. difference in the height of the left and the right subtrees can not be other than -1, 0 or 1 for each node. "
},
{
"code": null,
"e": 25786,
"s": 25683,
"text": "We will try to create a recurrence relation to find minimum number of nodes for a given height, n(h). "
},
{
"code": null,
"e": 25863,
"s": 25786,
"text": "For height = 0, we can only have a single node in an AVL tree, i.e. n(0) = 1"
},
{
"code": null,
"e": 25944,
"s": 25863,
"text": "For height = 1, we can have a minimum of two nodes in an AVL tree, i.e. n(1) = 2"
},
{
"code": null,
"e": 26094,
"s": 25944,
"text": "Now for any height ‘h’, root will have two subtrees (left and right). Out of which one has to be of height h-1 and other of h-2. [root node excluded]"
},
{
"code": null,
"e": 26201,
"s": 26094,
"text": "So, n(h) = 1 + n(h-1) + n(h-2) is the required recurrence relation for h>=2 [1 is added for the root node]"
},
{
"code": null,
"e": 26254,
"s": 26201,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26258,
"s": 26254,
"text": "C++"
},
{
"code": null,
"e": 26263,
"s": 26258,
"text": "Java"
},
{
"code": null,
"e": 26271,
"s": 26263,
"text": "Python3"
},
{
"code": null,
"e": 26274,
"s": 26271,
"text": "C#"
},
{
"code": null,
"e": 26278,
"s": 26274,
"text": "PHP"
},
{
"code": null,
"e": 26289,
"s": 26278,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find// minimum number of nodesint AVLnodes(int height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver Codeint main(){ int H = 3; cout << AVLnodes(H) << endl;}",
"e": 26743,
"s": 26289,
"text": null
},
{
"code": "// Java implementation of the approach class GFG{ // Function to find// minimum number of nodesstatic int AVLnodes(int height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver Codepublic static void main(String args[]){ int H = 3; System.out.println(AVLnodes(H));}}",
"e": 27212,
"s": 26743,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to find minimum# number of nodesdef AVLnodes(height): # Base Conditions if (height == 0): return 1 elif (height == 1): return 2 # Recursive function call # for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2)) # Driver Codeif __name__ == '__main__': H = 3 print(AVLnodes(H)) # This code is contributed by# Surendra_Gangwar",
"e": 27681,
"s": 27212,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to find// minimum number of nodesstatic int AVLnodes(int height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver Codepublic static void Main(){ int H = 3; Console.Write(AVLnodes(H));}} // This code is contributed// by Akanksha Rai",
"e": 28201,
"s": 27681,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to find minimum// number of nodesfunction AVLnodes($height){ // Base Conditions if ($height == 0) return 1; else if ($height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes($height - 1) + AVLnodes($height - 2));} // Driver Code$H = 3;echo(AVLnodes($H)); // This code is contributed// by Code_Mech.",
"e": 28649,
"s": 28201,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to find// minimum number of nodesfunction AVLnodes(height){ // Base Conditions if (height == 0) return 1; else if (height == 1) return 2; // Recursive function call // for the recurrence relation return (1 + AVLnodes(height - 1) + AVLnodes(height - 2));} // Driver codelet H = 3; document.write(AVLnodes(H)); // This code is contributed by decode2207 </script>",
"e": 29129,
"s": 28649,
"text": null
},
{
"code": null,
"e": 29131,
"s": 29129,
"text": "7"
},
{
"code": null,
"e": 29161,
"s": 29133,
"text": "Tail Recursive Approach : "
},
{
"code": null,
"e": 29323,
"s": 29161,
"text": "The recursive function for finding n(h) (minimum number of nodes possible in an AVL Tree with height ‘h’) is n(h) = 1 + n(h-1) + n(h-2) ; h>=2 ; n(0)=1 ; n(1)=2;"
},
{
"code": null,
"e": 29504,
"s": 29323,
"text": "To create a Tail Recursive Function, we will maintain 1 + n(h-1) + n(h-2) as function arguments such that rather than calculating it, we directly return its value to main function."
},
{
"code": null,
"e": 29558,
"s": 29504,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 29562,
"s": 29558,
"text": "C++"
},
{
"code": null,
"e": 29567,
"s": 29562,
"text": "Java"
},
{
"code": null,
"e": 29575,
"s": 29567,
"text": "Python3"
},
{
"code": null,
"e": 29578,
"s": 29575,
"text": "C#"
},
{
"code": null,
"e": 29589,
"s": 29578,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return//minimum number of nodesint AVLtree(int H, int a = 1, int b = 2){ // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1);} // Driver Codeint main(){ int H = 5; int answer = AVLtree(H); // Output the result cout << \"n(\" << H << \") = \" << answer << endl; return 0;}",
"e": 30073,
"s": 29589,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return//minimum number of nodesstatic int AVLtree(int H, int a, int b){ // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1);} // Driver Codepublic static void main(String[] args){ int H = 5; int answer = AVLtree(H, 1, 2); // Output the result System.out.println(\"n(\" + H + \") = \" + answer);}} // This code is contributed by PrinciRaj1992",
"e": 30588,
"s": 30073,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return# minimum number of nodesdef AVLtree(H, a, b): # Base Conditions if(H == 0): return 1; if(H == 1): return b; # Tail Recursive Call return AVLtree(H - 1, b, a + b + 1); # Driver Codeif __name__ == '__main__': H = 5; answer = AVLtree(H, 1, 2); # Output the result print(\"n(\", H , \") = \"\\ , answer); # This code is contributed by 29AjayKumar",
"e": 31043,
"s": 30588,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return//minimum number of nodesstatic int AVLtree(int H, int a, int b){ // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1);} // Driver Codepublic static void Main(String[] args){ int H = 5; int answer = AVLtree(H, 1, 2); // Output the result Console.WriteLine(\"n(\" + H + \") = \" + answer);}} // This code is contributed by Princi Singh",
"e": 31572,
"s": 31043,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return //minimum number of nodes function AVLtree(H, a, b) { // Base Conditions if (H == 0) return 1; if (H == 1) return b; // Tail Recursive Call return AVLtree(H - 1, b, a + b + 1); } let H = 5; let answer = AVLtree(H, 1, 2); // Output the result document.write(\"n(\" + H + \") = \" + answer); // This code is contributed by mukesh07.</script>",
"e": 32085,
"s": 31572,
"text": null
},
{
"code": null,
"e": 32095,
"s": 32085,
"text": "n(5) = 20"
},
{
"code": null,
"e": 32104,
"s": 32097,
"text": "krikti"
},
{
"code": null,
"e": 32120,
"s": 32104,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 32137,
"s": 32120,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32150,
"s": 32137,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32160,
"s": 32150,
"text": "Code_Mech"
},
{
"code": null,
"e": 32174,
"s": 32160,
"text": "princiraj1992"
},
{
"code": null,
"e": 32187,
"s": 32174,
"text": "princi singh"
},
{
"code": null,
"e": 32199,
"s": 32187,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32210,
"s": 32199,
"text": "decode2207"
},
{
"code": null,
"e": 32219,
"s": 32210,
"text": "mukesh07"
},
{
"code": null,
"e": 32228,
"s": 32219,
"text": "AVL-Tree"
},
{
"code": null,
"e": 32247,
"s": 32228,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 32266,
"s": 32247,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 32285,
"s": 32266,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 32294,
"s": 32285,
"text": "AVL-Tree"
},
{
"code": null,
"e": 32392,
"s": 32294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32401,
"s": 32392,
"text": "Comments"
},
{
"code": null,
"e": 32414,
"s": 32401,
"text": "Old Comments"
},
{
"code": null,
"e": 32446,
"s": 32414,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 32472,
"s": 32446,
"text": "Floor and Ceil from a BST"
},
{
"code": null,
"e": 32520,
"s": 32472,
"text": "Check if a triplet with given sum exists in BST"
},
{
"code": null,
"e": 32572,
"s": 32520,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 32596,
"s": 32572,
"text": "Convert BST to Min Heap"
},
{
"code": null,
"e": 32630,
"s": 32596,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 32657,
"s": 32630,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 32721,
"s": 32657,
"text": "Optimal sequence for AVL tree insertion (without any rotations)"
},
{
"code": null,
"e": 32773,
"s": 32721,
"text": "Construct a Binary Search Tree from given postorder"
}
] |
Properties Class in Java - GeeksforGeeks
|
24 Nov, 2020
The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. It belongs to java.util package. Properties define the following instance variable. This variable holds a default property list associated with a Properties object.
Properties defaults: This variable holds a default property list associated with a Properties object.
Features of Properties class:
Properties is a subclass of Hashtable.
It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file.
Properties class can specify other properties list as it’s the default. If a particular key property is not present in the original Properties list, the default properties will be searched.
Properties object does not require external synchronization and Multiple threads can share a single Properties object.
Also, it can be used to retrieve the properties of the system.
Advantage of a Properties file
In the event that any data is changed from the properties record, you don’t have to recompile the java class. It is utilized to store data that is to be changed habitually.
Note: The Properties class does not inherit the concept of a load factor from its superclass, Hashtable.
Declaration
public class Properties extends Hashtable<Object,Object>
1. Properties(): This creates a Properties object that has no default values.
Properties p = new Properties();
2. Properties(Properties propDefault): The second creates an object that uses propDefault for its default value.
Properties p = new Properties(Properties propDefault);
Example 1: The below program shows how to use Properties class to get information from the properties file.
Let us create a properties file and name it as db.properties.
db.properties
username = coder
password = geeksforgeeks
Code
Java
// Java program to demonstrate Properties class to get// information from the properties file import java.util.*;import java.io.*;public class GFG { public static void main(String[] args) throws Exception { // create a reader object on the properties file FileReader reader = new FileReader("db.properties"); // create properties object Properties p = new Properties(); // Add a wrapper around reader object p.load(reader); // access properties data System.out.println(p.getProperty("username")); System.out.println(p.getProperty("password")); }}
Output
Example 2: The below program shows how to use the Properties class to get all the system properties. Using System.getProperties() method, we can get all the properties of the system.
Java
// Java program to demonstrate Properties class to get all// the system properties import java.util.*;import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // get all the system properties Properties p = System.getProperties(); // stores set of properties information Set set = p.entrySet(); // iterate over the set Iterator itr = set.iterator(); while (itr.hasNext()) { // print each property Map.Entry entry = (Map.Entry)itr.next(); System.out.println(entry.getKey() + " = " + entry.getValue()); } }}
Output
Example 3: The below program shows how to use the Properties class to create a properties file.
Java
// Java program to demonstrate Properties class to create// the properties file import java.util.*;import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // create an instance of Properties Properties p = new Properties(); // add properties to it p.setProperty("name", "Ganesh Chowdhary Sadanala"); p.setProperty("email", "[email protected]"); // store the properties to a file p.store(new FileWriter("info.properties"), "GeeksforGeeks Properties Example"); }}
Output
METHOD
DESCRIPTION
Deprecated.
This method does not throw an IOException if an I/O error occurs while saving the property list.
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Ganeshchowdharysadanala
Java - util package
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 25058,
"s": 25030,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 25353,
"s": 25058,
"text": "The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. It belongs to java.util package. Properties define the following instance variable. This variable holds a default property list associated with a Properties object. "
},
{
"code": null,
"e": 25456,
"s": 25353,
"text": "Properties defaults: This variable holds a default property list associated with a Properties object. "
},
{
"code": null,
"e": 25486,
"s": 25456,
"text": "Features of Properties class:"
},
{
"code": null,
"e": 25525,
"s": 25486,
"text": "Properties is a subclass of Hashtable."
},
{
"code": null,
"e": 25710,
"s": 25525,
"text": "It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file."
},
{
"code": null,
"e": 25900,
"s": 25710,
"text": "Properties class can specify other properties list as it’s the default. If a particular key property is not present in the original Properties list, the default properties will be searched."
},
{
"code": null,
"e": 26019,
"s": 25900,
"text": "Properties object does not require external synchronization and Multiple threads can share a single Properties object."
},
{
"code": null,
"e": 26082,
"s": 26019,
"text": "Also, it can be used to retrieve the properties of the system."
},
{
"code": null,
"e": 26113,
"s": 26082,
"text": "Advantage of a Properties file"
},
{
"code": null,
"e": 26286,
"s": 26113,
"text": "In the event that any data is changed from the properties record, you don’t have to recompile the java class. It is utilized to store data that is to be changed habitually."
},
{
"code": null,
"e": 26391,
"s": 26286,
"text": "Note: The Properties class does not inherit the concept of a load factor from its superclass, Hashtable."
},
{
"code": null,
"e": 26403,
"s": 26391,
"text": "Declaration"
},
{
"code": null,
"e": 26461,
"s": 26403,
"text": "public class Properties extends Hashtable<Object,Object>"
},
{
"code": null,
"e": 26540,
"s": 26461,
"text": "1. Properties(): This creates a Properties object that has no default values. "
},
{
"code": null,
"e": 26573,
"s": 26540,
"text": "Properties p = new Properties();"
},
{
"code": null,
"e": 26687,
"s": 26573,
"text": "2. Properties(Properties propDefault): The second creates an object that uses propDefault for its default value. "
},
{
"code": null,
"e": 26742,
"s": 26687,
"text": "Properties p = new Properties(Properties propDefault);"
},
{
"code": null,
"e": 26851,
"s": 26742,
"text": "Example 1: The below program shows how to use Properties class to get information from the properties file. "
},
{
"code": null,
"e": 26913,
"s": 26851,
"text": "Let us create a properties file and name it as db.properties."
},
{
"code": null,
"e": 26927,
"s": 26913,
"text": "db.properties"
},
{
"code": null,
"e": 26969,
"s": 26927,
"text": "username = coder\npassword = geeksforgeeks"
},
{
"code": null,
"e": 26974,
"s": 26969,
"text": "Code"
},
{
"code": null,
"e": 26979,
"s": 26974,
"text": "Java"
},
{
"code": "// Java program to demonstrate Properties class to get// information from the properties file import java.util.*;import java.io.*;public class GFG { public static void main(String[] args) throws Exception { // create a reader object on the properties file FileReader reader = new FileReader(\"db.properties\"); // create properties object Properties p = new Properties(); // Add a wrapper around reader object p.load(reader); // access properties data System.out.println(p.getProperty(\"username\")); System.out.println(p.getProperty(\"password\")); }}",
"e": 27605,
"s": 26979,
"text": null
},
{
"code": null,
"e": 27612,
"s": 27605,
"text": "Output"
},
{
"code": null,
"e": 27795,
"s": 27612,
"text": "Example 2: The below program shows how to use the Properties class to get all the system properties. Using System.getProperties() method, we can get all the properties of the system."
},
{
"code": null,
"e": 27800,
"s": 27795,
"text": "Java"
},
{
"code": "// Java program to demonstrate Properties class to get all// the system properties import java.util.*;import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // get all the system properties Properties p = System.getProperties(); // stores set of properties information Set set = p.entrySet(); // iterate over the set Iterator itr = set.iterator(); while (itr.hasNext()) { // print each property Map.Entry entry = (Map.Entry)itr.next(); System.out.println(entry.getKey() + \" = \" + entry.getValue()); } }}",
"e": 28480,
"s": 27800,
"text": null
},
{
"code": null,
"e": 28487,
"s": 28480,
"text": "Output"
},
{
"code": null,
"e": 28583,
"s": 28487,
"text": "Example 3: The below program shows how to use the Properties class to create a properties file."
},
{
"code": null,
"e": 28588,
"s": 28583,
"text": "Java"
},
{
"code": "// Java program to demonstrate Properties class to create// the properties file import java.util.*;import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // create an instance of Properties Properties p = new Properties(); // add properties to it p.setProperty(\"name\", \"Ganesh Chowdhary Sadanala\"); p.setProperty(\"email\", \"[email protected]\"); // store the properties to a file p.store(new FileWriter(\"info.properties\"), \"GeeksforGeeks Properties Example\"); }}",
"e": 29193,
"s": 28588,
"text": null
},
{
"code": null,
"e": 29200,
"s": 29193,
"text": "Output"
},
{
"code": null,
"e": 29207,
"s": 29200,
"text": "METHOD"
},
{
"code": null,
"e": 29219,
"s": 29207,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 29231,
"s": 29219,
"text": "Deprecated."
},
{
"code": null,
"e": 29328,
"s": 29231,
"text": "This method does not throw an IOException if an I/O error occurs while saving the property list."
},
{
"code": null,
"e": 29335,
"s": 29328,
"text": "METHOD"
},
{
"code": null,
"e": 29347,
"s": 29335,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 29354,
"s": 29347,
"text": "METHOD"
},
{
"code": null,
"e": 29366,
"s": 29354,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 29390,
"s": 29366,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 29410,
"s": 29390,
"text": "Java - util package"
},
{
"code": null,
"e": 29427,
"s": 29410,
"text": "Java-Collections"
},
{
"code": null,
"e": 29432,
"s": 29427,
"text": "Java"
},
{
"code": null,
"e": 29437,
"s": 29432,
"text": "Java"
},
{
"code": null,
"e": 29454,
"s": 29437,
"text": "Java-Collections"
},
{
"code": null,
"e": 29552,
"s": 29454,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29561,
"s": 29552,
"text": "Comments"
},
{
"code": null,
"e": 29574,
"s": 29561,
"text": "Old Comments"
},
{
"code": null,
"e": 29604,
"s": 29574,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29636,
"s": 29604,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29687,
"s": 29636,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29706,
"s": 29687,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29724,
"s": 29706,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29755,
"s": 29724,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29787,
"s": 29755,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29811,
"s": 29787,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29831,
"s": 29811,
"text": "Stack Class in Java"
}
] |
Python | Uploading images in Django - GeeksforGeeks
|
21 Aug, 2020
Prerequisite – Introduction to Django
In most of the websites, we often deal with media data such as images, files etc. In django we can deal with the images with the help of model field which is ImageField.
In this article, we have created the app image_app in a sample project named image_upload.
The very first step is to add below code in the settings.py file.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/media/'
MEDIA_ROOT is for server path to store files in the computer.MEDIA_URL is the reference URL for browser to access the files over Http.
In the urls.py we should edit the configuration like this
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
A sample models.py should be like this, in that we have created a Hotel model which consists of hotel name and its image.In this project we are taking the hotel name and its image from the user for hotel booking website.
# models.py class Hotel(models.Model): name = models.CharField(max_length=50) hotel_Main_Img = models.ImageField(upload_to='images/')
Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when we upload an image. No need of explicit creation of media directory.
We have to create a forms.py file under image_app, here we are dealing with model form to make content easier to understand.
# forms.pyfrom django import formsfrom .models import * class HotelForm(forms.ModelForm): class Meta: model = Hotel fields = ['name', 'hotel_Main_Img']
Django will implicitly handle the form verification’s with out declaring explicitly in the script, and it will create the analogous form fields in the page according to model fields we specified in the models.py file.This is the advantage of model form.
Now create a templates directory under image_app in that we have to create a html file for uploading the images. HTML file should look like this.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Hotel_image</title></head><body> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form></body></html>
When making a POST request, we have to encode the data that forms the body of the request in some way. So, we have to specify the encoding format in the form tag. multipart/form-data is significantly more complicated but it allows entire files to be included in the data.
The csrf_token is for protection against Cross Site Request Forgeries.
form.as_p simply wraps all the elements in HTML paragraph tags. The advantage is not having to write a loop in the template to explicitly add HTML to surround each title and field.
In the views.py under image_app in that we have to write a view for taking requests from user and gives back some html page.
from django.http import HttpResponsefrom django.shortcuts import render, redirectfrom .forms import * # Create your views here.def hotel_image_view(request): if request.method == 'POST': form = HotelForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = HotelForm() return render(request, 'hotel_image_form.html', {'form' : form}) def success(request): return HttpResponse('successfully uploaded')
whenever the hotel_image_view hits and that request is POST, we are creating an instance of model form form = HotelForm(request.POST, request.FILES) image will be stored under request.FILES one. If it is valid save into the database and redirects to success url which indicates successful uploading of the image. If the method is not POST we are rendering with html template created.
urls.py will look like this –
from django.contrib import adminfrom django.urls import pathfrom django.conf import settingsfrom django.conf.urls.static import staticfrom .views import * urlpatterns = [ path('image_upload', hotel_image_view, name = 'image_upload'), path('success', success, name = 'success'),] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now make the migrations and run the server.
When we hit the URL in the browser, in this way it looks.
After uploading the image it will show success.
Now in the project directory media directory will be created, in that images directory will be created and the image will be stored under it. Here is the final result.
Final output stored in the database
Now we can write a view for accessing those images, for simplicity let’s take example with one image and it is also applicable for many images.
# Python program to view # for displaying images def display_hotel_images(request): if request.method == 'GET': # getting all the objects of hotel. Hotels = Hotel.objects.all() return render((request, 'display_hotel_images.html', {'hotel_images' : Hotels}))
A sample html file template for displaying images.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Hotel Images</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script></head><body> {% for hotel in hotel_images %} <div class="col-md-4"> {{ hotel.name }} <img src="{{ hotel.hotel_Main_Img.url }}" class="img-responsive" style="width: 100%; float: left; margin-right: 10px;" /> </div> {% endfor %} </body></html>
Insert the url path in the urls.py file
# urls.py
path('hotel_images', display_hotel_images, name = 'hotel_images'),
Here is the final view on the browser when we try to access the image.
Hotel Image
Saivasanth
nidhi_biet
deekshant149
Python Django
Technical Scripter 2018
Python
Technical Scripter
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
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24391,
"s": 24363,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 24429,
"s": 24391,
"text": "Prerequisite – Introduction to Django"
},
{
"code": null,
"e": 24599,
"s": 24429,
"text": "In most of the websites, we often deal with media data such as images, files etc. In django we can deal with the images with the help of model field which is ImageField."
},
{
"code": null,
"e": 24690,
"s": 24599,
"text": "In this article, we have created the app image_app in a sample project named image_upload."
},
{
"code": null,
"e": 24756,
"s": 24690,
"text": "The very first step is to add below code in the settings.py file."
},
{
"code": "MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/media/'",
"e": 24823,
"s": 24756,
"text": null
},
{
"code": null,
"e": 24958,
"s": 24823,
"text": "MEDIA_ROOT is for server path to store files in the computer.MEDIA_URL is the reference URL for browser to access the files over Http."
},
{
"code": null,
"e": 25016,
"s": 24958,
"text": "In the urls.py we should edit the configuration like this"
},
{
"code": null,
"e": 25227,
"s": 25016,
"text": "from django.conf import settings\nfrom django.conf.urls.static import static\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n"
},
{
"code": null,
"e": 25448,
"s": 25227,
"text": "A sample models.py should be like this, in that we have created a Hotel model which consists of hotel name and its image.In this project we are taking the hotel name and its image from the user for hotel booking website."
},
{
"code": "# models.py class Hotel(models.Model): name = models.CharField(max_length=50) hotel_Main_Img = models.ImageField(upload_to='images/')",
"e": 25588,
"s": 25448,
"text": null
},
{
"code": null,
"e": 25834,
"s": 25588,
"text": "Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when we upload an image. No need of explicit creation of media directory."
},
{
"code": null,
"e": 25959,
"s": 25834,
"text": "We have to create a forms.py file under image_app, here we are dealing with model form to make content easier to understand."
},
{
"code": "# forms.pyfrom django import formsfrom .models import * class HotelForm(forms.ModelForm): class Meta: model = Hotel fields = ['name', 'hotel_Main_Img']",
"e": 26131,
"s": 25959,
"text": null
},
{
"code": null,
"e": 26385,
"s": 26131,
"text": "Django will implicitly handle the form verification’s with out declaring explicitly in the script, and it will create the analogous form fields in the page according to model fields we specified in the models.py file.This is the advantage of model form."
},
{
"code": null,
"e": 26531,
"s": 26385,
"text": "Now create a templates directory under image_app in that we have to create a html file for uploading the images. HTML file should look like this."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Hotel_image</title></head><body> <form method = \"post\" enctype=\"multipart/form-data\"> {% csrf_token %} {{ form.as_p }} <button type=\"submit\">Upload</button> </form></body></html>",
"e": 26811,
"s": 26531,
"text": null
},
{
"code": null,
"e": 27083,
"s": 26811,
"text": "When making a POST request, we have to encode the data that forms the body of the request in some way. So, we have to specify the encoding format in the form tag. multipart/form-data is significantly more complicated but it allows entire files to be included in the data."
},
{
"code": null,
"e": 27154,
"s": 27083,
"text": "The csrf_token is for protection against Cross Site Request Forgeries."
},
{
"code": null,
"e": 27335,
"s": 27154,
"text": "form.as_p simply wraps all the elements in HTML paragraph tags. The advantage is not having to write a loop in the template to explicitly add HTML to surround each title and field."
},
{
"code": null,
"e": 27460,
"s": 27335,
"text": "In the views.py under image_app in that we have to write a view for taking requests from user and gives back some html page."
},
{
"code": "from django.http import HttpResponsefrom django.shortcuts import render, redirectfrom .forms import * # Create your views here.def hotel_image_view(request): if request.method == 'POST': form = HotelForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = HotelForm() return render(request, 'hotel_image_form.html', {'form' : form}) def success(request): return HttpResponse('successfully uploaded')",
"e": 27972,
"s": 27460,
"text": null
},
{
"code": null,
"e": 28356,
"s": 27972,
"text": "whenever the hotel_image_view hits and that request is POST, we are creating an instance of model form form = HotelForm(request.POST, request.FILES) image will be stored under request.FILES one. If it is valid save into the database and redirects to success url which indicates successful uploading of the image. If the method is not POST we are rendering with html template created."
},
{
"code": null,
"e": 28386,
"s": 28356,
"text": "urls.py will look like this –"
},
{
"code": "from django.contrib import adminfrom django.urls import pathfrom django.conf import settingsfrom django.conf.urls.static import staticfrom .views import * urlpatterns = [ path('image_upload', hotel_image_view, name = 'image_upload'), path('success', success, name = 'success'),] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)",
"e": 28805,
"s": 28386,
"text": null
},
{
"code": null,
"e": 28849,
"s": 28805,
"text": "Now make the migrations and run the server."
},
{
"code": null,
"e": 28907,
"s": 28849,
"text": "When we hit the URL in the browser, in this way it looks."
},
{
"code": null,
"e": 28955,
"s": 28907,
"text": "After uploading the image it will show success."
},
{
"code": null,
"e": 29123,
"s": 28955,
"text": "Now in the project directory media directory will be created, in that images directory will be created and the image will be stored under it. Here is the final result."
},
{
"code": null,
"e": 29159,
"s": 29123,
"text": "Final output stored in the database"
},
{
"code": null,
"e": 29303,
"s": 29159,
"text": "Now we can write a view for accessing those images, for simplicity let’s take example with one image and it is also applicable for many images."
},
{
"code": "# Python program to view # for displaying images def display_hotel_images(request): if request.method == 'GET': # getting all the objects of hotel. Hotels = Hotel.objects.all() return render((request, 'display_hotel_images.html', {'hotel_images' : Hotels}))",
"e": 29611,
"s": 29303,
"text": null
},
{
"code": null,
"e": 29662,
"s": 29611,
"text": "A sample html file template for displaying images."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Hotel Images</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script></head><body> {% for hotel in hotel_images %} <div class=\"col-md-4\"> {{ hotel.name }} <img src=\"{{ hotel.hotel_Main_Img.url }}\" class=\"img-responsive\" style=\"width: 100%; float: left; margin-right: 10px;\" /> </div> {% endfor %} </body></html>",
"e": 30454,
"s": 29662,
"text": null
},
{
"code": null,
"e": 30494,
"s": 30454,
"text": "Insert the url path in the urls.py file"
},
{
"code": null,
"e": 30572,
"s": 30494,
"text": "# urls.py\npath('hotel_images', display_hotel_images, name = 'hotel_images'),\n"
},
{
"code": null,
"e": 30643,
"s": 30572,
"text": "Here is the final view on the browser when we try to access the image."
},
{
"code": null,
"e": 30655,
"s": 30643,
"text": "Hotel Image"
},
{
"code": null,
"e": 30666,
"s": 30655,
"text": "Saivasanth"
},
{
"code": null,
"e": 30677,
"s": 30666,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30690,
"s": 30677,
"text": "deekshant149"
},
{
"code": null,
"e": 30704,
"s": 30690,
"text": "Python Django"
},
{
"code": null,
"e": 30728,
"s": 30704,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30735,
"s": 30728,
"text": "Python"
},
{
"code": null,
"e": 30754,
"s": 30735,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30852,
"s": 30754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30861,
"s": 30852,
"text": "Comments"
},
{
"code": null,
"e": 30874,
"s": 30861,
"text": "Old Comments"
},
{
"code": null,
"e": 30892,
"s": 30874,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30927,
"s": 30892,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30959,
"s": 30927,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30981,
"s": 30959,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31011,
"s": 30981,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31053,
"s": 31011,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31079,
"s": 31053,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31122,
"s": 31079,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 31159,
"s": 31122,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to apply a theme to an activity only in Android?
|
This example demonstrates how do I apply theme to an activity 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"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
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">
<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" android:theme="@style/Theme.AppCompat.Dialog.MinWidth">
<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": 1136,
"s": 1062,
"text": "This example demonstrates how do I apply theme to an activity in android."
},
{
"code": null,
"e": 1265,
"s": 1136,
"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": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2080,
"s": 1330,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2137,
"s": 2080,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2430,
"s": 2137,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 2485,
"s": 2430,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3210,
"s": 2485,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\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\" android:theme=\"@style/Theme.AppCompat.Dialog.MinWidth\">\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": 3557,
"s": 3210,
"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": 3598,
"s": 3557,
"text": "Click here to download the project code."
}
] |
Apex - if elseif else statement
|
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
The syntax of an if...else if...else statement is as follows −
if boolean_expression_1 {
/* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
/* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
/* Executes when the boolean expression 3 is true */
} else {
/* Executes when the none of the above condition is true */
}
Suppose, our Chemical company has customers of two categories – Premium and Normal. Based on the customer type we should provide them discount and other benefits like after sales service and support. Following program shows an implementation of the same.
//Execute this code in Developer Console and see the Output
String customerName = 'Glenmarkone'; //premium customer
Decimal discountRate = 0;
Boolean premiumSupport = false;
if (customerName == 'Glenmarkone') {
discountRate = 0.1; //when condition is met this block will be executed
premiumSupport = true;
System.debug('Special Discount given as Customer is Premium');
}else if (customerName == 'Joe') {
discountRate = 0.5; //when condition is met this block will be executed
premiumSupport = false;
System.debug('Special Discount not given as Customer is not Premium');
}else {
discountRate = 0.05; //when condition is not met and customer is normal
premiumSupport = false;
System.debug('Special Discount not given as Customer is not Premium');
}
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2210,
"s": 2052,
"text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement."
},
{
"code": null,
"e": 2273,
"s": 2210,
"text": "The syntax of an if...else if...else statement is as follows −"
},
{
"code": null,
"e": 2608,
"s": 2273,
"text": "if boolean_expression_1 {\n /* Executes when the boolean expression 1 is true */\n} else if boolean_expression_2 {\n /* Executes when the boolean expression 2 is true */\n} else if boolean_expression_3 {\n /* Executes when the boolean expression 3 is true */\n} else {\n /* Executes when the none of the above condition is true */\n}\n"
},
{
"code": null,
"e": 2863,
"s": 2608,
"text": "Suppose, our Chemical company has customers of two categories – Premium and Normal. Based on the customer type we should provide them discount and other benefits like after sales service and support. Following program shows an implementation of the same."
},
{
"code": null,
"e": 3638,
"s": 2863,
"text": "//Execute this code in Developer Console and see the Output\nString customerName = 'Glenmarkone'; //premium customer\nDecimal discountRate = 0;\nBoolean premiumSupport = false;\nif (customerName == 'Glenmarkone') {\n discountRate = 0.1; //when condition is met this block will be executed\n premiumSupport = true;\n System.debug('Special Discount given as Customer is Premium');\n}else if (customerName == 'Joe') {\n discountRate = 0.5; //when condition is met this block will be executed\n premiumSupport = false;\n System.debug('Special Discount not given as Customer is not Premium');\n}else {\n discountRate = 0.05; //when condition is not met and customer is normal\n premiumSupport = false;\n System.debug('Special Discount not given as Customer is not Premium');\n}"
},
{
"code": null,
"e": 3671,
"s": 3638,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3684,
"s": 3671,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 3716,
"s": 3684,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3724,
"s": 3716,
"text": " Uplatz"
},
{
"code": null,
"e": 3757,
"s": 3724,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3782,
"s": 3757,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 3815,
"s": 3782,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3830,
"s": 3815,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 3863,
"s": 3830,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3876,
"s": 3863,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 3911,
"s": 3876,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3923,
"s": 3911,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 3930,
"s": 3923,
"text": " Print"
},
{
"code": null,
"e": 3941,
"s": 3930,
"text": " Add Notes"
}
] |
How to subset a data frame by excluding a specific text value in an R data frame?
|
To create a subset based on text value we can use rowSums function by defining the sums for the text equal to zero, this will help us to drop all the rows that contains that specific text value. For example, if we have a data frame df that contains A in many columns then all the rows of df excluding A can be selected as−
df[rowSums(df=="A")==0,,drop=FALSE]
Live Demo
Consider the below data frame −
set.seed(951)
x1<−sample(LETTERS[1:3],20,replace=TRUE)
x2<−sample(LETTERS[1:4],20,replace=TRUE)
x3<−sample(LETTERS[1:5],20,replace=TRUE)
x4<−sample(LETTERS[2:5],20,replace=TRUE)
x5<−sample(LETTERS[3:5],20,replace=TRUE)
df<−data.frame(x1,x2,x3,x4,x5)
df
x1 x2 x3 x4 x5
1 A D B C C
2 B D D D D
3 B A D D D
4 B D C D E
5 C D C C C
6 A D C D E
7 B D E B E
8 A D E D C
9 A B C E E
10 C B C B C
11 A D D B D
12 B C B D E
13 A C E E D
14 C A D C E
15 C C D B D
16 A C A D E
17 C A B C E
18 A A E E D
19 B A D D C
20 B D C D C
Subsetting rows that do not include A −
df[rowSums(df=="A")==0,,drop=FALSE]
x1 x2 x3 x4 x5
2 B D D D D
4 B D C D E
5 C D C C C
7 B D E B E
10 C B C B C
12 B C B D E
15 C C D B D
20 B D C D C
Subsetting rows that do not include B −
df[rowSums(df=="B")==0,,drop=FALSE]
x1 x2 x3 x4 x5
5 C D C C C
6 A D C D E
8 A D E D C
13 A C E E D
14 C A D C E
16 A C A D E
18 A A E E D
Subsetting rows that do not include C −
df[rowSums(df=="C")==0,,drop=FALSE]
x1 x2 x3 x4 x5
2 B D D D D
3 B A D D D
7 B D E B E
11 A D D B D
18 A A E E D
Subsetting rows that do not include D −
df[rowSums(df=="D")==0,,drop=FALSE]
x1 x2 x3 x4 x5
9 A B C E E
10 C B C B C
17 C A B C E
Subsetting rows that do not include E −
df[rowSums(df=="E")==0,,drop=FALSE]
x1 x2 x3 x4 x5
1 A D B C C
2 B D D D D
3 B A D D D
5 C D C C C
10 C B C B C
11 A D D B D
15 C C D B D
19 B A D D C
20 B D C D C
|
[
{
"code": null,
"e": 1385,
"s": 1062,
"text": "To create a subset based on text value we can use rowSums function by defining the sums for the text equal to zero, this will help us to drop all the rows that contains that specific text value. For example, if we have a data frame df that contains A in many columns then all the rows of df excluding A can be selected as−"
},
{
"code": null,
"e": 1421,
"s": 1385,
"text": "df[rowSums(df==\"A\")==0,,drop=FALSE]"
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": " Live Demo"
},
{
"code": null,
"e": 1464,
"s": 1432,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1717,
"s": 1464,
"text": "set.seed(951)\nx1<−sample(LETTERS[1:3],20,replace=TRUE)\nx2<−sample(LETTERS[1:4],20,replace=TRUE)\nx3<−sample(LETTERS[1:5],20,replace=TRUE)\nx4<−sample(LETTERS[2:5],20,replace=TRUE)\nx5<−sample(LETTERS[3:5],20,replace=TRUE)\ndf<−data.frame(x1,x2,x3,x4,x5)\ndf"
},
{
"code": null,
"e": 2054,
"s": 1717,
"text": " x1 x2 x3 x4 x5\n1 A D B C C\n2 B D D D D\n3 B A D D D\n4 B D C D E\n5 C D C C C\n6 A D C D E\n7 B D E B E\n8 A D E D C\n9 A B C E E\n10 C B C B C\n11 A D D B D\n12 B C B D E\n13 A C E E D\n14 C A D C E\n15 C C D B D\n16 A C A D E\n17 C A B C E\n18 A A E E D\n19 B A D D C\n20 B D C D C"
},
{
"code": null,
"e": 2094,
"s": 2054,
"text": "Subsetting rows that do not include A −"
},
{
"code": null,
"e": 2130,
"s": 2094,
"text": "df[rowSums(df==\"A\")==0,,drop=FALSE]"
},
{
"code": null,
"e": 2275,
"s": 2130,
"text": " x1 x2 x3 x4 x5\n2 B D D D D\n4 B D C D E\n5 C D C C C\n7 B D E B E\n10 C B C B C\n12 B C B D E\n15 C C D B D\n20 B D C D C"
},
{
"code": null,
"e": 2315,
"s": 2275,
"text": "Subsetting rows that do not include B −"
},
{
"code": null,
"e": 2351,
"s": 2315,
"text": "df[rowSums(df==\"B\")==0,,drop=FALSE]"
},
{
"code": null,
"e": 2454,
"s": 2351,
"text": "x1 x2 x3 x4 x5\n5 C D C C C\n6 A D C D E\n8 A D E D C\n13 A C E E D\n14 C A D C E\n16 A C A D E\n18 A A E E D"
},
{
"code": null,
"e": 2494,
"s": 2454,
"text": "Subsetting rows that do not include C −"
},
{
"code": null,
"e": 2530,
"s": 2494,
"text": "df[rowSums(df==\"C\")==0,,drop=FALSE]"
},
{
"code": null,
"e": 2607,
"s": 2530,
"text": "x1 x2 x3 x4 x5\n2 B D D D D\n3 B A D D D\n7 B D E B E\n11 A D D B D\n18 A A E E D"
},
{
"code": null,
"e": 2647,
"s": 2607,
"text": "Subsetting rows that do not include D −"
},
{
"code": null,
"e": 2683,
"s": 2647,
"text": "df[rowSums(df==\"D\")==0,,drop=FALSE]"
},
{
"code": null,
"e": 2748,
"s": 2683,
"text": "x1 x2 x3 x4 x5\n9 A B C E E\n10 C B C B C\n17 C A B C E"
},
{
"code": null,
"e": 2788,
"s": 2748,
"text": "Subsetting rows that do not include E −"
},
{
"code": null,
"e": 2824,
"s": 2788,
"text": "df[rowSums(df==\"E\")==0,,drop=FALSE]"
},
{
"code": null,
"e": 2975,
"s": 2824,
"text": " x1 x2 x3 x4 x5\n1 A D B C C\n2 B D D D D\n3 B A D D D\n5 C D C C C\n10 C B C B C\n11 A D D B D\n15 C C D B D\n19 B A D D C\n20 B D C D C"
}
] |
MySQL Tutorial
|
MySQL is a widely used relational database management system (RDBMS).
MySQL is free and open-source.
MySQL is ideal for both small and large applications.
With our online MySQL editor, you can edit the SQL statements, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Insert the missing statement to get all the columns from the Customers table.
* FROM Customers;
Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All SQL Examples
Test your MySQL skills at W3Schools!
Start MySQL Quiz!
At W3Schools you will find a complete reference of MySQL data types and functions:
MySQL Data Types
MySQL Functions
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 70,
"s": 0,
"text": "MySQL is a widely used relational database management system (RDBMS)."
},
{
"code": null,
"e": 101,
"s": 70,
"text": "MySQL is free and open-source."
},
{
"code": null,
"e": 155,
"s": 101,
"text": "MySQL is ideal for both small and large applications."
},
{
"code": null,
"e": 260,
"s": 155,
"text": "With our online MySQL editor, you can edit the SQL statements, and click on a button to view the result."
},
{
"code": null,
"e": 319,
"s": 260,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 397,
"s": 319,
"text": "Insert the missing statement to get all the columns from the Customers table."
},
{
"code": null,
"e": 417,
"s": 397,
"text": " * FROM Customers;\n"
},
{
"code": null,
"e": 436,
"s": 417,
"text": "Start the Exercise"
},
{
"code": null,
"e": 524,
"s": 436,
"text": "Learn by examples! This tutorial supplements all explanations with clarifying examples."
},
{
"code": null,
"e": 545,
"s": 524,
"text": "See All SQL Examples"
},
{
"code": null,
"e": 582,
"s": 545,
"text": "Test your MySQL skills at W3Schools!"
},
{
"code": null,
"e": 600,
"s": 582,
"text": "Start MySQL Quiz!"
},
{
"code": null,
"e": 683,
"s": 600,
"text": "At W3Schools you will find a complete reference of MySQL data types and functions:"
},
{
"code": null,
"e": 700,
"s": 683,
"text": "MySQL Data Types"
},
{
"code": null,
"e": 716,
"s": 700,
"text": "MySQL Functions"
},
{
"code": null,
"e": 749,
"s": 716,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 791,
"s": 749,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 898,
"s": 791,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 917,
"s": 898,
"text": "[email protected]"
}
] |
Firestore and Python | NoSQL on Google Cloud | Towards Data Science
|
Familiarity with the cloud is one of those skills that, as a data scientist, machine learning engineer, or developer — is a game-changer.
No matter which domain we work in, data is always the center of attention, closely followed by our end-users. A good cloud-based database service will cater to both of these needs.
We offload our data to a location where our end-users will be able to access it via an interface that anyone can use. This interface could be a web-app — or API for the more technical end-users.
Firestore is Google’s cloud-hosted NoSQL database service offering. There are several key benefits of the service, namely:
Flexible data storage (NoSQL)
Native libraries support most popular languages (Python)
You learn for free (surpassing the free tier limits takes a lot of data)
Everything is simple — we can spin up a database quicker than the time it takes to make coffee
Authentication (can be) handled by Google, we maximize security with minimal work
Automated scaling to meet demand
Intuitive documentation, possibly the best of the big three cloud-providers (Azure, AWS, GCP)
In this article, we will set up our Firebase project (the platform hosting Firestore), create a database using the web-UI, and create a simple Python script performing all of the essential Firestore functions. It will look like this:
In Firebase> Create a Project> Initialize Database> Get CredentialsIn Python> Install gcloud Libraries (+ venv)> Authenticate> Connect to Firestore> Get> Create> Modify> Delete> Queries
Let’s get started.
Fortunately, Google is good at making things easy. Go to the Firebase website and click the big Get started button.
We should now see the ‘Welcome to Firebase’ page above — create a project and give it a cool name (it should probably be relevant to your project too).
I’ve named this one ‘antigravity’.
You should see a window asking whether we would like to enable Google Analytics — this is entirely your choice, we won’t be using it, but it will also cost you nothing.
Our project will initialize, and on clicking Continue, we are taken to the Project Overview page of our new project.
To initialize our Firestore database, we navigate to the sidebar and click Develop > Database. Here we will see the ‘Cloud Firestore’ page above — click Create database.
Here we will be asked whether to start in production or test mode. We will be using test mode.
Next, you select your location — this is where you or your users will requesting data from, so choose the nearest option!
Finally, we have access to our Database. For this tutorial we will need a collection called ‘places’ and a document called ‘rome’ like above — simply click Start collection to add these (where_to_go is an array).
We need to pip install the firebase_admin package:
pip install firebase-admin
With any version of Python beyond 3.6, we will receive a SyntaxError when importing firebase_admin to our scripts:
The async identifier was added in Python 3.7 — breaking the firebase_admin module. We have two options here:
Modify firebase_admin and replace every instance of async with _async (or any keyword of your choice).Use Python 3.6 via a virtual environment (venv).
Modify firebase_admin and replace every instance of async with _async (or any keyword of your choice).
Use Python 3.6 via a virtual environment (venv).
Option (1) is probably a bad idea. So let’s quickly cover a venv setup using Anaconda (ask Google or me for how on other environments).
Open Anaconda prompt and create a new venv (we will call it fire36):
conda create --name fire36 python
Activate the venv and install the firebase_admin package:
conda activate fire36pip install firebase_admin
If you’re using Jupyter or Spyder, simply type jupyter|jupyter lab|spyder to write code using this venv. Both PyCharm and VSCode can use this venv too.
To access Firestore, we need lots of credentials. Google again makes this easy.
Navigate to your project in the Firebase Console.
Next to ‘Project Overview’ in the top-left, click the gear icon and select Project Settings.
Now we click the Service accounts tab where we will find instructions on authentication with the Firebase Admin SDK.
Now, we need to click Generate new private key. We download the file, rename it to serviceAccountKey.json (or anything else) and store it in an accessible location for our Python scripts.
Storing serviceAccountKey.json in the same directory for testing is okay — but keep the contents of the JSON private. Public GitHub repos are a terrible place for credentials.
On the same Firebase Admin SDK page, we can copy and paste the Python code into the top of our script. All we need to do is update the path to serviceAccountKey.json and add firestore to our imports — our script should look like this:
import firebase_adminfrom firebase_admin import credentials, firestorecred = credentials.Certificate("path/to/serviceAccountKey.json")firebase_admin.initialize_app(cred)
That is all we need for authentication. Now we (finally) move onto writing some code!
There are three layers to our connection:
Database > Collection > Document
db = firestore.client() # this connects to our Firestore databasecollection = db.collection('places') # opens 'places' collectiondoc = collection.document('rome') # specifies the 'rome' document
Each layer comes with its own set of methods that allow us to perform different operations at the database, collection, or document level.
We use the get method to retrieve data. Let’s use this method to get our rome document:
doc = collection.document('rome')res = doc.get().to_dict()print(res)[Out]: { 'lat': 41.9028, 'long': 12.4964, 'where_to_go': [ 'villa_borghese', 'trastevere', 'vatican_city' ]}
We can also perform a .get() operation on collection to return an array of all documents contained within it. If we had two documents, it would look like this:
docs = collection.get()print(docs)[Out]: [ <google.cloud.firestore_v1.document.DocumentSnapshot object ...>, <google.cloud.firestore_v1.document.DocumentSnapshot object ...>]
These documents are stored as DocumentSnapshot objects — the same object types we receive when using the .document(<doc-id>).get() method above. As with the first get example — we can use .to_dict() to convert these objects to dictionaries.
We create documents using both the .document(<doc-id>) and the .set() method on collection. The .set() method takes a dictionary containing all of the data we would like to store within our new <doc-id>, like so:
res = collection.document('barcelona').set({ 'lat': 41.3851, 'long': 2.1734, 'weather': 'great', 'landmarks': [ 'guadí park', 'gaudí church', 'gaudí everything' ]})print(res)[Out]: update_time { seconds: 1596532394 nanos: 630200000}
If the operation is successful, we will receive the update_time in our response.
By navigating back to the Firestore interface, we can see our new document data as above.
Sometimes, rather than creating a whole new document, we will need to modify an existing one. There are several ways of doing this, depending on what it is we want to change.
To update a full key-value pair, we use update:
res = collection.document('barcelona').update({ 'weather': 'sun'})
The update method works for most values, but when we simply want to add or remove a single entry in an array, it is less useful. Here we use the firestore.ArrayUnion and firestore.ArrayRemove methods for adding and removing individual array values respectively, like so:
collection.document('rome').update({ 'where_to_go': firestore.ArrayUnion(['colosseum'])})
And to remove vatican_city and trastevere:
collection.document('rome').update({ 'where_to_go': firestore.ArrayRemove( ['vatican_city', 'trastevere'])})
Other times, we may need to delete documents in their entirety. We do this with the delete method:
collection.document('rome').delete()
If we wanted to delete a single field within a document, we could use firestore.DELETE_FIELD like so:
collection.document('barcelona').update({ 'weather': firestore.DELETE_FIELD})
Taking things to the next level, we can specify what exactly it is we want.
For this example, we have added several global cities (code for adding them is here) to Firestore.
We will query for all cities within Europe — which we are defining as having a longitude of more than -9.4989° (west) and less than 33.4299° (east). We will ignore latitude for the sake of simplicity.
To query our Firestore, we use the where method on our collection object. The method has three arguments, where(fieldPath, opStr, value):
fieldPath — the field we are targeting, in this case 'long'
opStr — comparison operation string, '==' checks equality
value — the value we are comparing to
Anything true for our query will be returned. For our example, we will find documents where long > 9.4989 — which we write as:
collection.where('long', '>', 9.4989).get()
With this query, we return barcelona, rome, and brisbane — but we need to exclude anything East of Europe too. We can do this by adding another where method like so:
collection.where('long', '>', -9.4989) \ .where('long', '<', 33.4299).get()
That’s all for this introduction to Google’s Firestore. For easy, secure, and robust cloud-based databases Firestore truly is fantastic.
Of course, there’s a lot more to the cloud than data storage alone. AWS and Azure are both great too, but the ease of use with GCP’s Firebase configuration is simply unmatched to anything else out there.
With very little time, it is effortless to learn everything we need to build a full application from the front-end UI to our data storage setup.
If the cloud is somewhat new to you, don’t hesitate to jump in — it is simply too valuable a skill to miss.
If you have any suggestions or would like to talk with me about Firestore — or getting started with the cloud — feel free to reach out to me on Twitter or in the comments below.
Thanks for reading!
Interested in learning more about the other side of this? Feel free to read my introduction to Angular — a fantastic and surprisingly simple front-end framework:
|
[
{
"code": null,
"e": 309,
"s": 171,
"text": "Familiarity with the cloud is one of those skills that, as a data scientist, machine learning engineer, or developer — is a game-changer."
},
{
"code": null,
"e": 490,
"s": 309,
"text": "No matter which domain we work in, data is always the center of attention, closely followed by our end-users. A good cloud-based database service will cater to both of these needs."
},
{
"code": null,
"e": 685,
"s": 490,
"text": "We offload our data to a location where our end-users will be able to access it via an interface that anyone can use. This interface could be a web-app — or API for the more technical end-users."
},
{
"code": null,
"e": 808,
"s": 685,
"text": "Firestore is Google’s cloud-hosted NoSQL database service offering. There are several key benefits of the service, namely:"
},
{
"code": null,
"e": 838,
"s": 808,
"text": "Flexible data storage (NoSQL)"
},
{
"code": null,
"e": 895,
"s": 838,
"text": "Native libraries support most popular languages (Python)"
},
{
"code": null,
"e": 968,
"s": 895,
"text": "You learn for free (surpassing the free tier limits takes a lot of data)"
},
{
"code": null,
"e": 1063,
"s": 968,
"text": "Everything is simple — we can spin up a database quicker than the time it takes to make coffee"
},
{
"code": null,
"e": 1145,
"s": 1063,
"text": "Authentication (can be) handled by Google, we maximize security with minimal work"
},
{
"code": null,
"e": 1178,
"s": 1145,
"text": "Automated scaling to meet demand"
},
{
"code": null,
"e": 1272,
"s": 1178,
"text": "Intuitive documentation, possibly the best of the big three cloud-providers (Azure, AWS, GCP)"
},
{
"code": null,
"e": 1506,
"s": 1272,
"text": "In this article, we will set up our Firebase project (the platform hosting Firestore), create a database using the web-UI, and create a simple Python script performing all of the essential Firestore functions. It will look like this:"
},
{
"code": null,
"e": 1692,
"s": 1506,
"text": "In Firebase> Create a Project> Initialize Database> Get CredentialsIn Python> Install gcloud Libraries (+ venv)> Authenticate> Connect to Firestore> Get> Create> Modify> Delete> Queries"
},
{
"code": null,
"e": 1711,
"s": 1692,
"text": "Let’s get started."
},
{
"code": null,
"e": 1827,
"s": 1711,
"text": "Fortunately, Google is good at making things easy. Go to the Firebase website and click the big Get started button."
},
{
"code": null,
"e": 1979,
"s": 1827,
"text": "We should now see the ‘Welcome to Firebase’ page above — create a project and give it a cool name (it should probably be relevant to your project too)."
},
{
"code": null,
"e": 2014,
"s": 1979,
"text": "I’ve named this one ‘antigravity’."
},
{
"code": null,
"e": 2183,
"s": 2014,
"text": "You should see a window asking whether we would like to enable Google Analytics — this is entirely your choice, we won’t be using it, but it will also cost you nothing."
},
{
"code": null,
"e": 2300,
"s": 2183,
"text": "Our project will initialize, and on clicking Continue, we are taken to the Project Overview page of our new project."
},
{
"code": null,
"e": 2470,
"s": 2300,
"text": "To initialize our Firestore database, we navigate to the sidebar and click Develop > Database. Here we will see the ‘Cloud Firestore’ page above — click Create database."
},
{
"code": null,
"e": 2565,
"s": 2470,
"text": "Here we will be asked whether to start in production or test mode. We will be using test mode."
},
{
"code": null,
"e": 2687,
"s": 2565,
"text": "Next, you select your location — this is where you or your users will requesting data from, so choose the nearest option!"
},
{
"code": null,
"e": 2900,
"s": 2687,
"text": "Finally, we have access to our Database. For this tutorial we will need a collection called ‘places’ and a document called ‘rome’ like above — simply click Start collection to add these (where_to_go is an array)."
},
{
"code": null,
"e": 2951,
"s": 2900,
"text": "We need to pip install the firebase_admin package:"
},
{
"code": null,
"e": 2978,
"s": 2951,
"text": "pip install firebase-admin"
},
{
"code": null,
"e": 3093,
"s": 2978,
"text": "With any version of Python beyond 3.6, we will receive a SyntaxError when importing firebase_admin to our scripts:"
},
{
"code": null,
"e": 3202,
"s": 3093,
"text": "The async identifier was added in Python 3.7 — breaking the firebase_admin module. We have two options here:"
},
{
"code": null,
"e": 3353,
"s": 3202,
"text": "Modify firebase_admin and replace every instance of async with _async (or any keyword of your choice).Use Python 3.6 via a virtual environment (venv)."
},
{
"code": null,
"e": 3456,
"s": 3353,
"text": "Modify firebase_admin and replace every instance of async with _async (or any keyword of your choice)."
},
{
"code": null,
"e": 3505,
"s": 3456,
"text": "Use Python 3.6 via a virtual environment (venv)."
},
{
"code": null,
"e": 3641,
"s": 3505,
"text": "Option (1) is probably a bad idea. So let’s quickly cover a venv setup using Anaconda (ask Google or me for how on other environments)."
},
{
"code": null,
"e": 3710,
"s": 3641,
"text": "Open Anaconda prompt and create a new venv (we will call it fire36):"
},
{
"code": null,
"e": 3744,
"s": 3710,
"text": "conda create --name fire36 python"
},
{
"code": null,
"e": 3802,
"s": 3744,
"text": "Activate the venv and install the firebase_admin package:"
},
{
"code": null,
"e": 3850,
"s": 3802,
"text": "conda activate fire36pip install firebase_admin"
},
{
"code": null,
"e": 4002,
"s": 3850,
"text": "If you’re using Jupyter or Spyder, simply type jupyter|jupyter lab|spyder to write code using this venv. Both PyCharm and VSCode can use this venv too."
},
{
"code": null,
"e": 4082,
"s": 4002,
"text": "To access Firestore, we need lots of credentials. Google again makes this easy."
},
{
"code": null,
"e": 4132,
"s": 4082,
"text": "Navigate to your project in the Firebase Console."
},
{
"code": null,
"e": 4225,
"s": 4132,
"text": "Next to ‘Project Overview’ in the top-left, click the gear icon and select Project Settings."
},
{
"code": null,
"e": 4342,
"s": 4225,
"text": "Now we click the Service accounts tab where we will find instructions on authentication with the Firebase Admin SDK."
},
{
"code": null,
"e": 4530,
"s": 4342,
"text": "Now, we need to click Generate new private key. We download the file, rename it to serviceAccountKey.json (or anything else) and store it in an accessible location for our Python scripts."
},
{
"code": null,
"e": 4706,
"s": 4530,
"text": "Storing serviceAccountKey.json in the same directory for testing is okay — but keep the contents of the JSON private. Public GitHub repos are a terrible place for credentials."
},
{
"code": null,
"e": 4941,
"s": 4706,
"text": "On the same Firebase Admin SDK page, we can copy and paste the Python code into the top of our script. All we need to do is update the path to serviceAccountKey.json and add firestore to our imports — our script should look like this:"
},
{
"code": null,
"e": 5111,
"s": 4941,
"text": "import firebase_adminfrom firebase_admin import credentials, firestorecred = credentials.Certificate(\"path/to/serviceAccountKey.json\")firebase_admin.initialize_app(cred)"
},
{
"code": null,
"e": 5197,
"s": 5111,
"text": "That is all we need for authentication. Now we (finally) move onto writing some code!"
},
{
"code": null,
"e": 5239,
"s": 5197,
"text": "There are three layers to our connection:"
},
{
"code": null,
"e": 5272,
"s": 5239,
"text": "Database > Collection > Document"
},
{
"code": null,
"e": 5470,
"s": 5272,
"text": "db = firestore.client() # this connects to our Firestore databasecollection = db.collection('places') # opens 'places' collectiondoc = collection.document('rome') # specifies the 'rome' document"
},
{
"code": null,
"e": 5609,
"s": 5470,
"text": "Each layer comes with its own set of methods that allow us to perform different operations at the database, collection, or document level."
},
{
"code": null,
"e": 5697,
"s": 5609,
"text": "We use the get method to retrieve data. Let’s use this method to get our rome document:"
},
{
"code": null,
"e": 5904,
"s": 5697,
"text": "doc = collection.document('rome')res = doc.get().to_dict()print(res)[Out]: { 'lat': 41.9028, 'long': 12.4964, 'where_to_go': [ 'villa_borghese', 'trastevere', 'vatican_city' ]}"
},
{
"code": null,
"e": 6064,
"s": 5904,
"text": "We can also perform a .get() operation on collection to return an array of all documents contained within it. If we had two documents, it would look like this:"
},
{
"code": null,
"e": 6242,
"s": 6064,
"text": "docs = collection.get()print(docs)[Out]: [ <google.cloud.firestore_v1.document.DocumentSnapshot object ...>, <google.cloud.firestore_v1.document.DocumentSnapshot object ...>]"
},
{
"code": null,
"e": 6483,
"s": 6242,
"text": "These documents are stored as DocumentSnapshot objects — the same object types we receive when using the .document(<doc-id>).get() method above. As with the first get example — we can use .to_dict() to convert these objects to dictionaries."
},
{
"code": null,
"e": 6696,
"s": 6483,
"text": "We create documents using both the .document(<doc-id>) and the .set() method on collection. The .set() method takes a dictionary containing all of the data we would like to store within our new <doc-id>, like so:"
},
{
"code": null,
"e": 6971,
"s": 6696,
"text": "res = collection.document('barcelona').set({ 'lat': 41.3851, 'long': 2.1734, 'weather': 'great', 'landmarks': [ 'guadí park', 'gaudí church', 'gaudí everything' ]})print(res)[Out]: update_time { seconds: 1596532394 nanos: 630200000}"
},
{
"code": null,
"e": 7052,
"s": 6971,
"text": "If the operation is successful, we will receive the update_time in our response."
},
{
"code": null,
"e": 7142,
"s": 7052,
"text": "By navigating back to the Firestore interface, we can see our new document data as above."
},
{
"code": null,
"e": 7317,
"s": 7142,
"text": "Sometimes, rather than creating a whole new document, we will need to modify an existing one. There are several ways of doing this, depending on what it is we want to change."
},
{
"code": null,
"e": 7365,
"s": 7317,
"text": "To update a full key-value pair, we use update:"
},
{
"code": null,
"e": 7435,
"s": 7365,
"text": "res = collection.document('barcelona').update({ 'weather': 'sun'})"
},
{
"code": null,
"e": 7706,
"s": 7435,
"text": "The update method works for most values, but when we simply want to add or remove a single entry in an array, it is less useful. Here we use the firestore.ArrayUnion and firestore.ArrayRemove methods for adding and removing individual array values respectively, like so:"
},
{
"code": null,
"e": 7799,
"s": 7706,
"text": "collection.document('rome').update({ 'where_to_go': firestore.ArrayUnion(['colosseum'])})"
},
{
"code": null,
"e": 7842,
"s": 7799,
"text": "And to remove vatican_city and trastevere:"
},
{
"code": null,
"e": 7961,
"s": 7842,
"text": "collection.document('rome').update({ 'where_to_go': firestore.ArrayRemove( ['vatican_city', 'trastevere'])})"
},
{
"code": null,
"e": 8060,
"s": 7961,
"text": "Other times, we may need to delete documents in their entirety. We do this with the delete method:"
},
{
"code": null,
"e": 8097,
"s": 8060,
"text": "collection.document('rome').delete()"
},
{
"code": null,
"e": 8199,
"s": 8097,
"text": "If we wanted to delete a single field within a document, we could use firestore.DELETE_FIELD like so:"
},
{
"code": null,
"e": 8280,
"s": 8199,
"text": "collection.document('barcelona').update({ 'weather': firestore.DELETE_FIELD})"
},
{
"code": null,
"e": 8356,
"s": 8280,
"text": "Taking things to the next level, we can specify what exactly it is we want."
},
{
"code": null,
"e": 8455,
"s": 8356,
"text": "For this example, we have added several global cities (code for adding them is here) to Firestore."
},
{
"code": null,
"e": 8656,
"s": 8455,
"text": "We will query for all cities within Europe — which we are defining as having a longitude of more than -9.4989° (west) and less than 33.4299° (east). We will ignore latitude for the sake of simplicity."
},
{
"code": null,
"e": 8794,
"s": 8656,
"text": "To query our Firestore, we use the where method on our collection object. The method has three arguments, where(fieldPath, opStr, value):"
},
{
"code": null,
"e": 8854,
"s": 8794,
"text": "fieldPath — the field we are targeting, in this case 'long'"
},
{
"code": null,
"e": 8912,
"s": 8854,
"text": "opStr — comparison operation string, '==' checks equality"
},
{
"code": null,
"e": 8950,
"s": 8912,
"text": "value — the value we are comparing to"
},
{
"code": null,
"e": 9077,
"s": 8950,
"text": "Anything true for our query will be returned. For our example, we will find documents where long > 9.4989 — which we write as:"
},
{
"code": null,
"e": 9121,
"s": 9077,
"text": "collection.where('long', '>', 9.4989).get()"
},
{
"code": null,
"e": 9287,
"s": 9121,
"text": "With this query, we return barcelona, rome, and brisbane — but we need to exclude anything East of Europe too. We can do this by adding another where method like so:"
},
{
"code": null,
"e": 9372,
"s": 9287,
"text": "collection.where('long', '>', -9.4989) \\ .where('long', '<', 33.4299).get()"
},
{
"code": null,
"e": 9509,
"s": 9372,
"text": "That’s all for this introduction to Google’s Firestore. For easy, secure, and robust cloud-based databases Firestore truly is fantastic."
},
{
"code": null,
"e": 9713,
"s": 9509,
"text": "Of course, there’s a lot more to the cloud than data storage alone. AWS and Azure are both great too, but the ease of use with GCP’s Firebase configuration is simply unmatched to anything else out there."
},
{
"code": null,
"e": 9858,
"s": 9713,
"text": "With very little time, it is effortless to learn everything we need to build a full application from the front-end UI to our data storage setup."
},
{
"code": null,
"e": 9966,
"s": 9858,
"text": "If the cloud is somewhat new to you, don’t hesitate to jump in — it is simply too valuable a skill to miss."
},
{
"code": null,
"e": 10144,
"s": 9966,
"text": "If you have any suggestions or would like to talk with me about Firestore — or getting started with the cloud — feel free to reach out to me on Twitter or in the comments below."
},
{
"code": null,
"e": 10164,
"s": 10144,
"text": "Thanks for reading!"
}
] |
Compare Two Java int Arrays in Java
|
To compare two Java short arrays, use the Arrays.equals() method.
Let us first declare and initialize some int arrays.
int[] arr1 = new int[] { 33, 66, 12, 56, 99 };
int[] arr2 = new int[] { 33, 66, 12, 56, 99 };
int[] arr3 = new int[] { 33, 66, 15, 56, 90 };
Now let us compare any two of the above arrays.
Arrays.equals(arr1, arr2));
In the same way, work it for other arrays and compare them
Live Demo
import java.util.*;
public class Demo {
public static void main(String[] args) {
int[] arr1 = new int[] { 33, 66, 12, 56, 99 };
int[] arr2 = new int[] { 33, 66, 12, 56, 99 };
int[] arr3 = new int[] { 33, 66, 15, 56, 90 };
System.out.println(Arrays.equals(arr1, arr2));
System.out.println(Arrays.equals(arr2, arr3));
System.out.println(Arrays.equals(arr3, arr1));
}
}
true
false
false
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "To compare two Java short arrays, use the Arrays.equals() method."
},
{
"code": null,
"e": 1181,
"s": 1128,
"text": "Let us first declare and initialize some int arrays."
},
{
"code": null,
"e": 1322,
"s": 1181,
"text": "int[] arr1 = new int[] { 33, 66, 12, 56, 99 };\nint[] arr2 = new int[] { 33, 66, 12, 56, 99 };\nint[] arr3 = new int[] { 33, 66, 15, 56, 90 };"
},
{
"code": null,
"e": 1370,
"s": 1322,
"text": "Now let us compare any two of the above arrays."
},
{
"code": null,
"e": 1398,
"s": 1370,
"text": "Arrays.equals(arr1, arr2));"
},
{
"code": null,
"e": 1457,
"s": 1398,
"text": "In the same way, work it for other arrays and compare them"
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": " Live Demo"
},
{
"code": null,
"e": 1877,
"s": 1468,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n int[] arr1 = new int[] { 33, 66, 12, 56, 99 };\n int[] arr2 = new int[] { 33, 66, 12, 56, 99 };\n int[] arr3 = new int[] { 33, 66, 15, 56, 90 };\n System.out.println(Arrays.equals(arr1, arr2));\n System.out.println(Arrays.equals(arr2, arr3));\n System.out.println(Arrays.equals(arr3, arr1));\n }\n}"
},
{
"code": null,
"e": 1894,
"s": 1877,
"text": "true\nfalse\nfalse"
}
] |
HTML - <aside> Tag
|
The HTML <aside> tag is used to specify a section of a page aside from the related section. This tag can be used for glossary definitions, author biography, author profile etc.
<!DOCTYPE html>
<html>
<head>
<title>HTML aside Tag</title>
</head>
<body>
<aside>
<h3>Java History</h3>
<p>Java is a programming language developed by James Gosling in 1994.</p>
</aside>
</body>
</html>
This will produce the following result −
Java is a programming language developed by James Gosling in 1994.
This tag supports all the global attributes described in HTML Attribute Reference
This tag supports all the event attributes described in HTML Events Reference
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": 2551,
"s": 2374,
"text": "The HTML <aside> tag is used to specify a section of a page aside from the related section. This tag can be used for glossary definitions, author biography, author profile etc."
},
{
"code": null,
"e": 2807,
"s": 2551,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML aside Tag</title>\n </head>\n\n <body>\n <aside>\n <h3>Java History</h3> \n <p>Java is a programming language developed by James Gosling in 1994.</p>\n </aside>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2848,
"s": 2807,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2915,
"s": 2848,
"text": "Java is a programming language developed by James Gosling in 1994."
},
{
"code": null,
"e": 2997,
"s": 2915,
"text": "This tag supports all the global attributes described in HTML Attribute Reference"
},
{
"code": null,
"e": 3075,
"s": 2997,
"text": "This tag supports all the event attributes described in HTML Events Reference"
},
{
"code": null,
"e": 3108,
"s": 3075,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3122,
"s": 3108,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3157,
"s": 3122,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3171,
"s": 3157,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3206,
"s": 3171,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3223,
"s": 3206,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3258,
"s": 3223,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3289,
"s": 3258,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3322,
"s": 3289,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3353,
"s": 3322,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3388,
"s": 3353,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3419,
"s": 3388,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3426,
"s": 3419,
"text": " Print"
},
{
"code": null,
"e": 3437,
"s": 3426,
"text": " Add Notes"
}
] |
Generalized Linked List - GeeksforGeeks
|
14 Nov, 2019
A Generalized Linked List L, is defined as a finite sequence of n>=0 elements, l1, l2, l3, l4, ..., ln, such that li are either atom or the list of atoms. ThusL = (l1, l2, l3, l4, ..., ln)where n is total number of nodes in the list.To represent a list of items there are certain assumptions about the node structure.
Flag = 1 implies that down pointer exists
Flag = 0 implies that next pointer exists
Data means the atom
Down pointer is the address of node which is down of the current node
Next pointer is the address of node which is attached as the next node
Why Generalized Linked List?Generalized linked lists are used because although the efficiency of polynomial operations using linked list is good but still, the disadvantage is that the linked list is unable to use multiple variable polynomial equation efficiently. It helps us to represent multi-variable polynomial along with the list of elements.
Typical ‘C’ structure of Generalized Linked List
typedef struct node { char c; //Data int index; //Flag struct node *next, *down; //Next & Down pointer}GLL;
Example of GLL {List representation}( a, (b, c), d)When first field is 0, it indicates that the second field is variable. If first field is 1 means the second field is a down pointer, means some list is starting.
Polynomial Representation using Generalized Linked ListThe typical node structure will be:
Here Flag = 0 means variable is present
Flag = 1 means down pointer is present
Flag = 2 means coefficient and exponent is present
Example:9x5 + 7xy4 + 10xz
In the above example the head node is of variable x. The temp node shows the first field as 2 means coefficient and exponent are present.
Since temp node is attached to head node and head node is having variable x, temp node having coefficient = 9 and exponent = 5. The above two nodes can be read as 9x5.Similarly, in the above figure, the node temp1 can be read as x4.
The flag field is 1 means down pointer is there
temp2 = y
temp3 = coefficient = 7
exponent = 1
flag = 2 means the node contains coefficient and exponent values.
temp2 is attached to temp3 this means 7y1 and temp2 is also attached to temp1 means
temp1 x temp2
x4 x 7y1 = 7x4y1 value is represented by above figure
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
LinkedList in Java
Doubly Linked List | Set 1 (Introduction and Insertion)
Linked List vs Array
Implementing a Linked List in Java using Class
Merge two sorted linked lists
Queue - Linked List Implementation
Implement a stack using singly linked list
Circular Linked List | Set 1 (Introduction and Applications)
Merge Sort for Linked Lists
Remove duplicates from a sorted linked list
|
[
{
"code": null,
"e": 24512,
"s": 24484,
"text": "\n14 Nov, 2019"
},
{
"code": null,
"e": 24830,
"s": 24512,
"text": "A Generalized Linked List L, is defined as a finite sequence of n>=0 elements, l1, l2, l3, l4, ..., ln, such that li are either atom or the list of atoms. ThusL = (l1, l2, l3, l4, ..., ln)where n is total number of nodes in the list.To represent a list of items there are certain assumptions about the node structure."
},
{
"code": null,
"e": 24872,
"s": 24830,
"text": "Flag = 1 implies that down pointer exists"
},
{
"code": null,
"e": 24914,
"s": 24872,
"text": "Flag = 0 implies that next pointer exists"
},
{
"code": null,
"e": 24934,
"s": 24914,
"text": "Data means the atom"
},
{
"code": null,
"e": 25004,
"s": 24934,
"text": "Down pointer is the address of node which is down of the current node"
},
{
"code": null,
"e": 25075,
"s": 25004,
"text": "Next pointer is the address of node which is attached as the next node"
},
{
"code": null,
"e": 25424,
"s": 25075,
"text": "Why Generalized Linked List?Generalized linked lists are used because although the efficiency of polynomial operations using linked list is good but still, the disadvantage is that the linked list is unable to use multiple variable polynomial equation efficiently. It helps us to represent multi-variable polynomial along with the list of elements."
},
{
"code": null,
"e": 25473,
"s": 25424,
"text": "Typical ‘C’ structure of Generalized Linked List"
},
{
"code": "typedef struct node { char c; //Data int index; //Flag struct node *next, *down; //Next & Down pointer}GLL;",
"e": 25627,
"s": 25473,
"text": null
},
{
"code": null,
"e": 25840,
"s": 25627,
"text": "Example of GLL {List representation}( a, (b, c), d)When first field is 0, it indicates that the second field is variable. If first field is 1 means the second field is a down pointer, means some list is starting."
},
{
"code": null,
"e": 25931,
"s": 25840,
"text": "Polynomial Representation using Generalized Linked ListThe typical node structure will be:"
},
{
"code": null,
"e": 25971,
"s": 25931,
"text": "Here Flag = 0 means variable is present"
},
{
"code": null,
"e": 26010,
"s": 25971,
"text": "Flag = 1 means down pointer is present"
},
{
"code": null,
"e": 26061,
"s": 26010,
"text": "Flag = 2 means coefficient and exponent is present"
},
{
"code": null,
"e": 26087,
"s": 26061,
"text": "Example:9x5 + 7xy4 + 10xz"
},
{
"code": null,
"e": 26225,
"s": 26087,
"text": "In the above example the head node is of variable x. The temp node shows the first field as 2 means coefficient and exponent are present."
},
{
"code": null,
"e": 26458,
"s": 26225,
"text": "Since temp node is attached to head node and head node is having variable x, temp node having coefficient = 9 and exponent = 5. The above two nodes can be read as 9x5.Similarly, in the above figure, the node temp1 can be read as x4."
},
{
"code": null,
"e": 26506,
"s": 26458,
"text": "The flag field is 1 means down pointer is there"
},
{
"code": null,
"e": 26516,
"s": 26506,
"text": "temp2 = y"
},
{
"code": null,
"e": 26540,
"s": 26516,
"text": "temp3 = coefficient = 7"
},
{
"code": null,
"e": 26553,
"s": 26540,
"text": "exponent = 1"
},
{
"code": null,
"e": 26619,
"s": 26553,
"text": "flag = 2 means the node contains coefficient and exponent values."
},
{
"code": null,
"e": 26703,
"s": 26619,
"text": "temp2 is attached to temp3 this means 7y1 and temp2 is also attached to temp1 means"
},
{
"code": null,
"e": 26717,
"s": 26703,
"text": "temp1 x temp2"
},
{
"code": null,
"e": 26771,
"s": 26717,
"text": "x4 x 7y1 = 7x4y1 value is represented by above figure"
},
{
"code": null,
"e": 26783,
"s": 26771,
"text": "Linked List"
},
{
"code": null,
"e": 26795,
"s": 26783,
"text": "Linked List"
},
{
"code": null,
"e": 26893,
"s": 26795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26902,
"s": 26893,
"text": "Comments"
},
{
"code": null,
"e": 26915,
"s": 26902,
"text": "Old Comments"
},
{
"code": null,
"e": 26934,
"s": 26915,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 26990,
"s": 26934,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 27011,
"s": 26990,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 27058,
"s": 27011,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 27088,
"s": 27058,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 27123,
"s": 27088,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 27166,
"s": 27123,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 27227,
"s": 27166,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 27255,
"s": 27227,
"text": "Merge Sort for Linked Lists"
}
] |
Arduino - Water Detector / Sensor
|
Water sensor brick is designed for water detection, which can be widely used in sensing rainfall, water level, and even liquid leakage.
Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood, rain, etc. It can be used to detect the presence, the level, the volume and/or the absence of water. While this could be used to remind you to water your plants, there is a better Grove sensor for that. The sensor has an array of exposed traces, which read LOW when water is detected.
In this chapter, we will connect the water sensor to Digital Pin 8 on Arduino, and will enlist the very handy LED to help identify when the water sensor comes into contact with a source of water.
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × Water Sensor
1 × led
1 × 330 ohm resistor
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New.
#define Grove_Water_Sensor 8 // Attach Water sensor to Arduino Digital Pin 8
#define LED 9 // Attach an LED to Digital Pin 9 (or use onboard LED)
void setup() {
pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input
pinMode(LED, OUTPUT); // The LED is an Output
}
void loop() {
/* The water sensor will switch LOW when water is detected.
Get the Arduino to illuminate the LED and activate the buzzer
when water is detected, and switch both off when no water is present */
if( digitalRead(Grove_Water_Sensor) == LOW) {
digitalWrite(LED,HIGH);
}else {
digitalWrite(LED,LOW);
}
}
Water sensor has three terminals - S, Vout(+), and GND (-). Connect the sensor as follows −
Connect the +Vs to +5v on your Arduino board.
Connect S to digital pin number 8 on Arduino board.
Connect GND with GND on Arduino.
Connect LED to digital pin number 9 in Arduino board.
When the sensor detects water, pin 8 on Arduino becomes LOW and then the LED on Arduino is turned ON.
You will see the indication LED turn ON when the sensor detects water.
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3006,
"s": 2870,
"text": "Water sensor brick is designed for water detection, which can be widely used in sensing rainfall, water level, and even liquid leakage."
},
{
"code": null,
"e": 3378,
"s": 3006,
"text": "Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood, rain, etc. It can be used to detect the presence, the level, the volume and/or the absence of water. While this could be used to remind you to water your plants, there is a better Grove sensor for that. The sensor has an array of exposed traces, which read LOW when water is detected."
},
{
"code": null,
"e": 3574,
"s": 3378,
"text": "In this chapter, we will connect the water sensor to Digital Pin 8 on Arduino, and will enlist the very handy LED to help identify when the water sensor comes into contact with a source of water."
},
{
"code": null,
"e": 3615,
"s": 3574,
"text": "You will need the following components −"
},
{
"code": null,
"e": 3630,
"s": 3615,
"text": "1 × Breadboard"
},
{
"code": null,
"e": 3649,
"s": 3630,
"text": "1 × Arduino Uno R3"
},
{
"code": null,
"e": 3666,
"s": 3649,
"text": "1 × Water Sensor"
},
{
"code": null,
"e": 3674,
"s": 3666,
"text": "1 × led"
},
{
"code": null,
"e": 3695,
"s": 3674,
"text": "1 × 330 ohm resistor"
},
{
"code": null,
"e": 3802,
"s": 3695,
"text": "Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below."
},
{
"code": null,
"e": 3951,
"s": 3802,
"text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New."
},
{
"code": null,
"e": 4579,
"s": 3951,
"text": "#define Grove_Water_Sensor 8 // Attach Water sensor to Arduino Digital Pin 8\n#define LED 9 // Attach an LED to Digital Pin 9 (or use onboard LED)\n\nvoid setup() {\n pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input\n pinMode(LED, OUTPUT); // The LED is an Output\n}\n\nvoid loop() {\n /* The water sensor will switch LOW when water is detected.\n Get the Arduino to illuminate the LED and activate the buzzer\n when water is detected, and switch both off when no water is present */\n if( digitalRead(Grove_Water_Sensor) == LOW) {\n digitalWrite(LED,HIGH);\n }else {\n digitalWrite(LED,LOW);\n }\n}"
},
{
"code": null,
"e": 4671,
"s": 4579,
"text": "Water sensor has three terminals - S, Vout(+), and GND (-). Connect the sensor as follows −"
},
{
"code": null,
"e": 4717,
"s": 4671,
"text": "Connect the +Vs to +5v on your Arduino board."
},
{
"code": null,
"e": 4769,
"s": 4717,
"text": "Connect S to digital pin number 8 on Arduino board."
},
{
"code": null,
"e": 4802,
"s": 4769,
"text": "Connect GND with GND on Arduino."
},
{
"code": null,
"e": 4856,
"s": 4802,
"text": "Connect LED to digital pin number 9 in Arduino board."
},
{
"code": null,
"e": 4958,
"s": 4856,
"text": "When the sensor detects water, pin 8 on Arduino becomes LOW and then the LED on Arduino is turned ON."
},
{
"code": null,
"e": 5029,
"s": 4958,
"text": "You will see the indication LED turn ON when the sensor detects water."
},
{
"code": null,
"e": 5064,
"s": 5029,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5075,
"s": 5064,
"text": " Amit Rana"
},
{
"code": null,
"e": 5108,
"s": 5075,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5119,
"s": 5108,
"text": " Amit Rana"
},
{
"code": null,
"e": 5152,
"s": 5119,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5165,
"s": 5152,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5200,
"s": 5165,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5213,
"s": 5200,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5245,
"s": 5213,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 5258,
"s": 5245,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5289,
"s": 5258,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 5302,
"s": 5289,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5309,
"s": 5302,
"text": " Print"
},
{
"code": null,
"e": 5320,
"s": 5309,
"text": " Add Notes"
}
] |
How to loop the program after an exception is thrown in java?
|
Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again.
In the following example we have an array with 5 elements, we are accepting two integers from user representing positions in the array and performing division operation with them, if the integer entered representing the positions is more than 5 (length of the exception) an ArrayIndexOutOfBoundsException occurs and, if the position chosen for denominator is 4 which is 0 an ArithmeticException occurs.
We are reading values and calculating the result in a static method. We are catching these two exceptions in two catch blocks and in each block we are invoking the method after displaying the respective message.
import java.util.Arrays;
import java.util.Scanner;
public class LoopBack {
int[] arr = {10, 20, 30, 2, 0, 8};
public static void getInputs(int[] arr){
Scanner sc = new Scanner(System.in);
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Error: You have chosen position which is not in the array: TRY AGAIN");
getInputs(arr);
}catch(ArithmeticException e) {
System.out.println("Error: Denominator must not be zero: TRY AGAIN");
getInputs(arr);
}
}
public static void main(String [] args) {
LoopBack obj = new LoopBack();
System.out.println("Array: "+Arrays.toString(obj.arr));
getInputs(obj.arr);
}
}
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
14
24
Error: You have chosen position which is not in the array: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
3
4
Error: Denominator must not be zero: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
3
Result of 10/2: 5
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again."
},
{
"code": null,
"e": 1720,
"s": 1317,
"text": "In the following example we have an array with 5 elements, we are accepting two integers from user representing positions in the array and performing division operation with them, if the integer entered representing the positions is more than 5 (length of the exception) an ArrayIndexOutOfBoundsException occurs and, if the position chosen for denominator is 4 which is 0 an ArithmeticException occurs."
},
{
"code": null,
"e": 1932,
"s": 1720,
"text": "We are reading values and calculating the result in a static method. We are catching these two exceptions in two catch blocks and in each block we are invoking the method after displaying the respective message."
},
{
"code": null,
"e": 2931,
"s": 1932,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class LoopBack {\n int[] arr = {10, 20, 30, 2, 0, 8};\n public static void getInputs(int[] arr){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)\");\n int a = sc.nextInt();\n int b = sc.nextInt();\n try {\n int result = (arr[a])/(arr[b]);\n System.out.println(\"Result of \"+arr[a]+\"/\"+arr[b]+\": \"+result);\n }catch(ArrayIndexOutOfBoundsException e) {\n System.out.println(\"Error: You have chosen position which is not in the array: TRY AGAIN\");\n getInputs(arr);\n }catch(ArithmeticException e) {\n System.out.println(\"Error: Denominator must not be zero: TRY AGAIN\");\n getInputs(arr);\n }\n }\n public static void main(String [] args) {\n LoopBack obj = new LoopBack();\n System.out.println(\"Array: \"+Arrays.toString(obj.arr));\n getInputs(obj.arr);\n }\n}"
},
{
"code": null,
"e": 3351,
"s": 2931,
"text": "Array: [10, 20, 30, 2, 0, 8]\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n14\n24\nError: You have chosen position which is not in the array: TRY AGAIN\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n3\n4\nError: Denominator must not be zero: TRY AGAIN\nChoose numerator and denominator(not 0) from this array (enter positions 0 to 5)\n0\n3\nResult of 10/2: 5"
}
] |
Android - CheckBox Control
|
A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when presenting users with a group of selectable options that are not mutually exclusive.
Following are the important attributes related to CheckBox control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −
android:autoText
If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight
This is the drawable to be drawn to the right of the text.
android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display.
Inherited from android.view.View Class −
android:background
This is a drawable to use as the background.
android:contentDescription
This defines text that briefly describes content of the view.
android:id
This supplies an identifier name for this view.
android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.
android:visibility
This controls the initial visibility of the view.
This example will take you through simple steps to show how to create your own Android application using Linear Layout and CheckBox.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity {
CheckBox ch1,ch2;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch1=(CheckBox)findViewById(R.id.checkBox1);
ch2=(CheckBox)findViewById(R.id.checkBox2);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Thanks : ").append(ch1.isChecked());
result.append("\nThanks: ").append(ch2.isChecked());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of checkbox"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like Tutorials Point"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like android "
android:checked="false"
android:layout_above="@+id/checkBox1"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyApplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your MyApplication application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
User needs you check on either do you like android check box or do you like tutorials point check box. and press ok button, if does all process correctly, it gonna be shown toast message as Thanks. Or else do press on cancel button, if user presses cancel button it going to close the application
I will recommend to try above example with different attributes of CheckBox in Layout XML file as well at programming time to have different look and feel of the CheckBox. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple CheckBox controls in one activity.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3788,
"s": 3607,
"text": "A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when presenting users with a group of selectable options that are not mutually exclusive."
},
{
"code": null,
"e": 4012,
"s": 3788,
"text": "Following are the important attributes related to CheckBox control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time."
},
{
"code": null,
"e": 4059,
"s": 4012,
"text": "Inherited from android.widget.TextView Class −"
},
{
"code": null,
"e": 4076,
"s": 4059,
"text": "android:autoText"
},
{
"code": null,
"e": 4196,
"s": 4076,
"text": "If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors."
},
{
"code": null,
"e": 4219,
"s": 4196,
"text": "android:drawableBottom"
},
{
"code": null,
"e": 4268,
"s": 4219,
"text": "This is the drawable to be drawn below the text."
},
{
"code": null,
"e": 4290,
"s": 4268,
"text": "android:drawableRight"
},
{
"code": null,
"e": 4349,
"s": 4290,
"text": "This is the drawable to be drawn to the right of the text."
},
{
"code": null,
"e": 4366,
"s": 4349,
"text": "android:editable"
},
{
"code": null,
"e": 4424,
"s": 4366,
"text": "If set, specifies that this TextView has an input method."
},
{
"code": null,
"e": 4437,
"s": 4424,
"text": "android:text"
},
{
"code": null,
"e": 4466,
"s": 4437,
"text": "This is the Text to display."
},
{
"code": null,
"e": 4507,
"s": 4466,
"text": "Inherited from android.view.View Class −"
},
{
"code": null,
"e": 4526,
"s": 4507,
"text": "android:background"
},
{
"code": null,
"e": 4571,
"s": 4526,
"text": "This is a drawable to use as the background."
},
{
"code": null,
"e": 4598,
"s": 4571,
"text": "android:contentDescription"
},
{
"code": null,
"e": 4660,
"s": 4598,
"text": "This defines text that briefly describes content of the view."
},
{
"code": null,
"e": 4671,
"s": 4660,
"text": "android:id"
},
{
"code": null,
"e": 4719,
"s": 4671,
"text": "This supplies an identifier name for this view."
},
{
"code": null,
"e": 4735,
"s": 4719,
"text": "android:onClick"
},
{
"code": null,
"e": 4825,
"s": 4735,
"text": "This is the name of the method in this View's context to invoke when the view is clicked."
},
{
"code": null,
"e": 4844,
"s": 4825,
"text": "android:visibility"
},
{
"code": null,
"e": 4894,
"s": 4844,
"text": "This controls the initial visibility of the view."
},
{
"code": null,
"e": 5027,
"s": 4894,
"text": "This example will take you through simple steps to show how to create your own Android application using Linear Layout and CheckBox."
},
{
"code": null,
"e": 5175,
"s": 5027,
"text": "Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 6484,
"s": 5175,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.widget.Button;\n\nimport android.view.View;\nimport android.view.View.OnClickListener;\n\nimport android.widget.CheckBox;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n CheckBox ch1,ch2;\n Button b1,b2;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n ch1=(CheckBox)findViewById(R.id.checkBox1);\n ch2=(CheckBox)findViewById(R.id.checkBox2);\n \n b1=(Button)findViewById(R.id.button);\n b2=(Button)findViewById(R.id.button2);\n b2.setOnClickListener(new View.OnClickListener() {\n \n @Override\n public void onClick(View v) {\n finish();\n }\n });\n b1.setOnClickListener(new View.OnClickListener() {\n \n @Override\n public void onClick(View v) {\n StringBuffer result = new StringBuffer();\n result.append(\"Thanks : \").append(ch1.isChecked());\n result.append(\"\\nThanks: \").append(ch2.isChecked());\n Toast.makeText(MainActivity.this, result.toString(), \n Toast.LENGTH_LONG).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 6553,
"s": 6484,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 9337,
"s": 6553,
"text": "<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n \n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\">\n \n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Example of checkbox\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\" />\n \n <CheckBox\n android:id=\"@+id/checkBox1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Do you like Tutorials Point\"\n android:layout_above=\"@+id/button\"\n android:layout_centerHorizontal=\"true\" />\n \n <CheckBox\n android:id=\"@+id/checkBox2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Do you like android \"\n android:checked=\"false\"\n android:layout_above=\"@+id/checkBox1\"\n android:layout_alignLeft=\"@+id/checkBox1\"\n android:layout_alignStart=\"@+id/checkBox1\" />\n \n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignLeft=\"@+id/checkBox1\"\n android:layout_below=\"@+id/textView1\"\n android:layout_marginTop=\"39dp\"\n android:text=\"Tutorials point\"\n android:textColor=\"#ff87ff09\"\n android:textSize=\"30dp\"\n android:layout_alignRight=\"@+id/textView1\"\n android:layout_alignEnd=\"@+id/textView1\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Ok\"\n android:id=\"@+id/button\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignLeft=\"@+id/checkBox1\"\n android:layout_alignStart=\"@+id/checkBox1\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Cancel\"\n android:id=\"@+id/button2\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\" />\n \n <ImageButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageButton\"\n android:src=\"@drawable/abc\"\n android:layout_centerVertical=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 9426,
"s": 9337,
"text": "Following will be the content of res/values/strings.xml to define these new constants −"
},
{
"code": null,
"e": 9541,
"s": 9426,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">MyApplication</string>\t\n</resources>"
},
{
"code": null,
"e": 9600,
"s": 9541,
"text": "Following is the default content of AndroidManifest.xml −"
},
{
"code": null,
"e": 10312,
"s": 9600,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 10703,
"s": 10312,
"text": "Let's try to run your MyApplication application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 11000,
"s": 10703,
"text": "User needs you check on either do you like android check box or do you like tutorials point check box. and press ok button, if does all process correctly, it gonna be shown toast message as Thanks. Or else do press on cancel button, if user presses cancel button it going to close the application"
},
{
"code": null,
"e": 11352,
"s": 11000,
"text": "I will recommend to try above example with different attributes of CheckBox in Layout XML file as well at programming time to have different look and feel of the CheckBox. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple CheckBox controls in one activity."
},
{
"code": null,
"e": 11387,
"s": 11352,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11399,
"s": 11387,
"text": " Aditya Dua"
},
{
"code": null,
"e": 11434,
"s": 11399,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11448,
"s": 11434,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 11480,
"s": 11448,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11497,
"s": 11480,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11532,
"s": 11497,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11549,
"s": 11532,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11584,
"s": 11549,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11601,
"s": 11584,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11634,
"s": 11601,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11651,
"s": 11634,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11658,
"s": 11651,
"text": " Print"
},
{
"code": null,
"e": 11669,
"s": 11658,
"text": " Add Notes"
}
] |
AJAX - Browser Support
|
All the available browsers cannot support AJAX. Here is a list of major browsers that support AJAX.
Mozilla Firefox 1.0 and above.
Netscape version 7.1 and above.
Apple Safari 1.2 and above.
Microsoft Internet Explorer 5 and above.
Konqueror.
Opera 7.6 and above.
When you write your next application, do consider the browsers that do not support AJAX.
NOTE − When we say that a browser does not support AJAX, it simply means that the browser does not support the creation of Javascript object – XMLHttpRequest object.
The simplest way to make your source code compatible with a browser is to use try...catch blocks in your JavaScript.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
//-->
</script>
<form name = 'myForm'>
Name: <input type = 'text' name = 'username' /> <br />
Time: <input type = 'text' name = 'time' />
</form>
</body>
</html>
In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our first attempt −
ajaxRequest = new XMLHttpRequest();
It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make the correct object for an Internet Explorer browser with −
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
If it doesn't work, then we can use a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support AJAX.
Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server. The step-wise AJAX workflow is explained in the next chapter.
72 Lectures
4.5 hours
Frahaan Hussain
20 Lectures
1 hours
Laurence Svekis
29 Lectures
2 hours
YouAccel
20 Lectures
1.5 hours
YouAccel
18 Lectures
2.5 hours
Stone River ELearning
47 Lectures
5.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1836,
"s": 1736,
"text": "All the available browsers cannot support AJAX. Here is a list of major browsers that support AJAX."
},
{
"code": null,
"e": 1867,
"s": 1836,
"text": "Mozilla Firefox 1.0 and above."
},
{
"code": null,
"e": 1899,
"s": 1867,
"text": "Netscape version 7.1 and above."
},
{
"code": null,
"e": 1927,
"s": 1899,
"text": "Apple Safari 1.2 and above."
},
{
"code": null,
"e": 1968,
"s": 1927,
"text": "Microsoft Internet Explorer 5 and above."
},
{
"code": null,
"e": 1979,
"s": 1968,
"text": "Konqueror."
},
{
"code": null,
"e": 2000,
"s": 1979,
"text": "Opera 7.6 and above."
},
{
"code": null,
"e": 2089,
"s": 2000,
"text": "When you write your next application, do consider the browsers that do not support AJAX."
},
{
"code": null,
"e": 2255,
"s": 2089,
"text": "NOTE − When we say that a browser does not support AJAX, it simply means that the browser does not support the creation of Javascript object – XMLHttpRequest object."
},
{
"code": null,
"e": 2372,
"s": 2255,
"text": "The simplest way to make your source code compatible with a browser is to use try...catch blocks in your JavaScript."
},
{
"code": null,
"e": 3483,
"s": 2372,
"text": "<html>\n <body>\n <script language = \"javascript\" type = \"text/javascript\">\n <!-- \n //Browser Support Code\n function ajaxFunction() {\n var ajaxRequest; // The variable that makes Ajax possible!\n\n try {\n // Opera 8.0+, Firefox, Safari \n ajaxRequest = new XMLHttpRequest();\n } catch (e) {\n\n // Internet Explorer Browsers\n try {\n ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n \n try {\n ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {\n\n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n }\n }\n }\n //-->\n </script>\n \n <form name = 'myForm'>\n Name: <input type = 'text' name = 'username' /> <br />\n Time: <input type = 'text' name = 'time' />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3587,
"s": 3483,
"text": "In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our first attempt −"
},
{
"code": null,
"e": 3623,
"s": 3587,
"text": "ajaxRequest = new XMLHttpRequest();"
},
{
"code": null,
"e": 3777,
"s": 3623,
"text": "It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make the correct object for an Internet Explorer browser with −"
},
{
"code": null,
"e": 3828,
"s": 3777,
"text": "ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");"
},
{
"code": null,
"e": 3882,
"s": 3828,
"text": "ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");"
},
{
"code": null,
"e": 4021,
"s": 3882,
"text": "If it doesn't work, then we can use a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support AJAX."
},
{
"code": null,
"e": 4242,
"s": 4021,
"text": "Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server. The step-wise AJAX workflow is explained in the next chapter."
},
{
"code": null,
"e": 4277,
"s": 4242,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4294,
"s": 4277,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4327,
"s": 4294,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4344,
"s": 4327,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4377,
"s": 4344,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4387,
"s": 4377,
"text": " YouAccel"
},
{
"code": null,
"e": 4422,
"s": 4387,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4432,
"s": 4422,
"text": " YouAccel"
},
{
"code": null,
"e": 4467,
"s": 4432,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4490,
"s": 4467,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4525,
"s": 4490,
"text": "\n 47 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4543,
"s": 4525,
"text": " Packt Publishing"
},
{
"code": null,
"e": 4550,
"s": 4543,
"text": " Print"
},
{
"code": null,
"e": 4561,
"s": 4550,
"text": " Add Notes"
}
] |
Apply CSS on a table cell based on the content in SAPUI5
|
You are having one of the most common requirements in the case of the table. You can achieve the end result using formatter function exposed on the cells of a table.
Here is a code snippet for your reference which you can alter as per your use case:
cells: [
new sap.m.Text({
text: {
formatter: function(name) {
if (name == "<your value>") {
// you can add style class or do your own logic here
this.addStyleClass("Total");
}
}
}
})
]
|
[
{
"code": null,
"e": 1228,
"s": 1062,
"text": "You are having one of the most common requirements in the case of the table. You can achieve the end result using formatter function exposed on the cells of a table."
},
{
"code": null,
"e": 1312,
"s": 1228,
"text": "Here is a code snippet for your reference which you can alter as per your use case:"
},
{
"code": null,
"e": 1587,
"s": 1312,
"text": "cells: [\n new sap.m.Text({\n text: {\n formatter: function(name) {\n if (name == \"<your value>\") {\n // you can add style class or do your own logic here\n this.addStyleClass(\"Total\");\n }\n }\n }\n })\n]"
}
] |
How to Install Turbo C++ on Linux?
|
13 May, 2022
In this article, we will look into how to install Turbo C++ on Linux. Turbo C++ is the free and Open-Source Software, it is a development tool for writing programs in the C/C++ language. Turbo C++ is a compiler and IDE (Integrated development environment) originally from Borland.
To run Turbo C++ in Linux System you must have the following:
Turbo C++ Setup
DOSBox Emulator
Note: If you have it installed on your system, just go to Linux Software Center and search for DOSBox and install the emulator or use the below command in the terminal:
sudo apt-get install dosbox
Follow the below steps to install Turbo C++ on Linux:
Step 1: Download and Extract the zip file of Turbo C++.
Step 2: Move the extracted folder to your home folder
Step 3: Go to the Dosbox configuration file and change settings. Use the following command –
satyajit@satyajit:~$ gedit .dosbox/dosbox-0.74-3.conf
Then change the following key values on that configuration file –
fullscreen=true
fulldouble=true
fullresolution=1920x1080
windowresolution=1920x1080
output=opengl
Set the fullresolution and windowresolution value the same as your screen resolution.
Then at the end of the file add the following lines –
mount C: ~
C:
cd TURBOC3/bin
tc.exe
Now to run Turbo C++ go to the terminal and write –
dosbox
It will start Turbo C++
Press Alt + Enter to switch between full screen and window mode.
Press Ctrl + F10 to release and lock the mouse on DOSBox
satyajit1910
how-to-install
linux
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 337,
"s": 54,
"text": "In this article, we will look into how to install Turbo C++ on Linux. Turbo C++ is the free and Open-Source Software, it is a development tool for writing programs in the C/C++ language. Turbo C++ is a compiler and IDE (Integrated development environment) originally from Borland. "
},
{
"code": null,
"e": 399,
"s": 337,
"text": "To run Turbo C++ in Linux System you must have the following:"
},
{
"code": null,
"e": 415,
"s": 399,
"text": "Turbo C++ Setup"
},
{
"code": null,
"e": 432,
"s": 415,
"text": "DOSBox Emulator "
},
{
"code": null,
"e": 601,
"s": 432,
"text": "Note: If you have it installed on your system, just go to Linux Software Center and search for DOSBox and install the emulator or use the below command in the terminal:"
},
{
"code": null,
"e": 629,
"s": 601,
"text": "sudo apt-get install dosbox"
},
{
"code": null,
"e": 683,
"s": 629,
"text": "Follow the below steps to install Turbo C++ on Linux:"
},
{
"code": null,
"e": 739,
"s": 683,
"text": "Step 1: Download and Extract the zip file of Turbo C++."
},
{
"code": null,
"e": 793,
"s": 739,
"text": "Step 2: Move the extracted folder to your home folder"
},
{
"code": null,
"e": 886,
"s": 793,
"text": "Step 3: Go to the Dosbox configuration file and change settings. Use the following command –"
},
{
"code": null,
"e": 940,
"s": 886,
"text": "satyajit@satyajit:~$ gedit .dosbox/dosbox-0.74-3.conf"
},
{
"code": null,
"e": 1006,
"s": 940,
"text": "Then change the following key values on that configuration file –"
},
{
"code": null,
"e": 1104,
"s": 1006,
"text": "fullscreen=true\nfulldouble=true\nfullresolution=1920x1080\nwindowresolution=1920x1080\noutput=opengl"
},
{
"code": null,
"e": 1190,
"s": 1104,
"text": "Set the fullresolution and windowresolution value the same as your screen resolution."
},
{
"code": null,
"e": 1246,
"s": 1192,
"text": "Then at the end of the file add the following lines –"
},
{
"code": null,
"e": 1282,
"s": 1246,
"text": "mount C: ~\nC:\ncd TURBOC3/bin\ntc.exe"
},
{
"code": null,
"e": 1336,
"s": 1284,
"text": "Now to run Turbo C++ go to the terminal and write –"
},
{
"code": null,
"e": 1343,
"s": 1336,
"text": "dosbox"
},
{
"code": null,
"e": 1367,
"s": 1343,
"text": "It will start Turbo C++"
},
{
"code": null,
"e": 1434,
"s": 1369,
"text": "Press Alt + Enter to switch between full screen and window mode."
},
{
"code": null,
"e": 1491,
"s": 1434,
"text": "Press Ctrl + F10 to release and lock the mouse on DOSBox"
},
{
"code": null,
"e": 1504,
"s": 1491,
"text": "satyajit1910"
},
{
"code": null,
"e": 1519,
"s": 1504,
"text": "how-to-install"
},
{
"code": null,
"e": 1525,
"s": 1519,
"text": "linux"
},
{
"code": null,
"e": 1532,
"s": 1525,
"text": "Picked"
},
{
"code": null,
"e": 1539,
"s": 1532,
"text": "How To"
},
{
"code": null,
"e": 1558,
"s": 1539,
"text": "Installation Guide"
},
{
"code": null,
"e": 1569,
"s": 1558,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1667,
"s": 1569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1716,
"s": 1667,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 1755,
"s": 1716,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 1797,
"s": 1755,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 1839,
"s": 1797,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 1880,
"s": 1839,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 1913,
"s": 1880,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1948,
"s": 1913,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 1987,
"s": 1948,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2029,
"s": 1987,
"text": "How to Install Jupyter Notebook on MacOS?"
}
] |
Utopian Simplex Protocol in Computer Network
|
21 Dec, 2020
We will consider a protocol that is simple because it does not worry about the possibility of anything going wrong. Data are transmitted in one direction only. Both are transmitting and receiving network layers are always ready. Processing time can be ignored. Infinite buffer space is available. This thoroughly unrealistic protocol, which we will nickname “Utopia”, is simply to show the basic structure on which we will build. Its implementation is shown below.
A Utopian simplex Protocol :There is one direction data transmission only from sender to receiver. Here we assume the communication channel to be error-free and the receiver will infinitely quickly process the input. The sender pumps out the data onto the line as fast as it can.
typedef enum {frame_arrival} event_type;
#include"protocol.h"
void sender1(void)
{
frame s; /* buffer for an outbound frame */
packet buffer; /* buffer for an outbound packet */
while(true)
{
from_network_layer(&buffer); /* go get something to send */
s.info=buffer; /* copy it into s for transmission */
to_physical_layer(&s); /* send it on its way */
}
}
void receiver1(void)
{
frame r;
event_type event; /* filled in by wait, but not used here */
while(true)
{
wait_for_event(&event); /* only possibility is frame_arrival */
from_physical_layer(&r); /* go get the inbound frame */
to_network_layer(&r.info); /* pass the data to the network layer */
}
}
This protocol has two different procedures, a sender and a receiver. MAX_SEQ is not needed because no sequence numbers or acknowledgments are used. The only event type possible is frame_arrival (i.e. the arrival of an undamaged frame).
The sender pumps out the data in an infinite while loop as fast as it can. The loop body consists of three actions and they are –
Fetch a packet from the network layer,
Construct an outbound frame using the variable s,
Send the frame on its way.
Other fields have to do with error and flow control and there are no errors or flow control restrictions here so only the info field is used here.
The receiver is equally simple. The procedure wait_for_event returns when the frame arrives and the event set to frame_arrival. The newly arrived frame from the hardware buffer is removed by the call from_physical_layer and puts in the variable r, so that receiver can get it. The data link layer settles back to wait for the next frame when the data portion is passed on to the network layer, suspending itself until the frame arrives. It does not handle either flow control or error correction therefore it is unrealistic.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 518,
"s": 53,
"text": "We will consider a protocol that is simple because it does not worry about the possibility of anything going wrong. Data are transmitted in one direction only. Both are transmitting and receiving network layers are always ready. Processing time can be ignored. Infinite buffer space is available. This thoroughly unrealistic protocol, which we will nickname “Utopia”, is simply to show the basic structure on which we will build. Its implementation is shown below."
},
{
"code": null,
"e": 798,
"s": 518,
"text": "A Utopian simplex Protocol :There is one direction data transmission only from sender to receiver. Here we assume the communication channel to be error-free and the receiver will infinitely quickly process the input. The sender pumps out the data onto the line as fast as it can."
},
{
"code": null,
"e": 1596,
"s": 798,
"text": "typedef enum {frame_arrival} event_type;\n\n#include\"protocol.h\"\n\nvoid sender1(void)\n{\n frame s; /* buffer for an outbound frame */\n packet buffer; /* buffer for an outbound packet */\n while(true)\n {\n from_network_layer(&buffer); /* go get something to send */\n s.info=buffer; /* copy it into s for transmission */\n to_physical_layer(&s); /* send it on its way */\n } \n}\n\nvoid receiver1(void)\n{\n frame r;\n event_type event; /* filled in by wait, but not used here */\n while(true)\n {\n wait_for_event(&event); /* only possibility is frame_arrival */\n from_physical_layer(&r); /* go get the inbound frame */\n to_network_layer(&r.info); /* pass the data to the network layer */\n }\n}"
},
{
"code": null,
"e": 1832,
"s": 1596,
"text": "This protocol has two different procedures, a sender and a receiver. MAX_SEQ is not needed because no sequence numbers or acknowledgments are used. The only event type possible is frame_arrival (i.e. the arrival of an undamaged frame)."
},
{
"code": null,
"e": 1962,
"s": 1832,
"text": "The sender pumps out the data in an infinite while loop as fast as it can. The loop body consists of three actions and they are –"
},
{
"code": null,
"e": 2001,
"s": 1962,
"text": "Fetch a packet from the network layer,"
},
{
"code": null,
"e": 2051,
"s": 2001,
"text": "Construct an outbound frame using the variable s,"
},
{
"code": null,
"e": 2078,
"s": 2051,
"text": "Send the frame on its way."
},
{
"code": null,
"e": 2225,
"s": 2078,
"text": "Other fields have to do with error and flow control and there are no errors or flow control restrictions here so only the info field is used here."
},
{
"code": null,
"e": 2750,
"s": 2225,
"text": "The receiver is equally simple. The procedure wait_for_event returns when the frame arrives and the event set to frame_arrival. The newly arrived frame from the hardware buffer is removed by the call from_physical_layer and puts in the variable r, so that receiver can get it. The data link layer settles back to wait for the next frame when the data portion is passed on to the network layer, suspending itself until the frame arrives. It does not handle either flow control or error correction therefore it is unrealistic."
},
{
"code": null,
"e": 2768,
"s": 2750,
"text": "Computer Networks"
},
{
"code": null,
"e": 2786,
"s": 2768,
"text": "Computer Networks"
}
] |
How to set position of an image in CSS ?
|
13 Jul, 2021
You can easily position an image by using the object-position property. You can also use a bunch of other ways like float-property that will be discussed further in this article.
Methods:
object-position property: Specify how an image element is positioned with x, y coordinates inside its content box.
float property: Specify how an element should float and place an element on its container’s right or left side.
Method 1: Using object-position Property
Syntax:
object-position: <position>
Property values:
position: It takes 2 numerical values corresponding to the distance from the left of the content-box (x-axis) and the distance from the top of the content-box (y-axis) respectively.
Note:
We can align elements using position property with some helper property left | right | top | bottom.
You can either use string values like right, left, center, top, or you can use numerical value in pixel like 200px, 250px.
Example:
HTML
<!DOCTYPE html><html> <head> <style> #object1 { width: 500px; height: 200px; background-color: green; object-fit: none; object-position: center top; /* String value */ } #object2 { width: 500px; height: 200px; background-color: green; object-fit: none; object-position: 50px 30px; /* Numeric value */ } </style></head> <body> <center> <h2 style="color:green"> GeeksforGeeks </h2> <h4>object-position Property</h4> <img id="object1" src="https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png" /> <img id="object2" src="https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png" /> </center></body> </html>
Output:
object-position
Method 2: Using float Property
Syntax:
float: none|inherit|left|right|initial;
Note: Elements are floated only horizontally i.e. left or right
Property Value:
left: Place an element on its container’s right.
right: Place an element on its container’s left.
inherit: Element inherits floating property from it’s parent (div, table etc...) elements.
none: Element is displayed as it is (Default).
Example:
HTML
<!DOCTYPE html><html> <head> <style> #object1 { width: 300px; height: 200px; float: right; } center { width: 500px; height: 500px; background-color: green; } </style></head> <body> <center> <h2 style="color:green"> GeeksforGeeks </h2> <h4>Float Property</h4> <img id="object1" src="https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png" /> </center></body> </html>
Output:
Float property
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 233,
"s": 54,
"text": "You can easily position an image by using the object-position property. You can also use a bunch of other ways like float-property that will be discussed further in this article."
},
{
"code": null,
"e": 242,
"s": 233,
"text": "Methods:"
},
{
"code": null,
"e": 357,
"s": 242,
"text": "object-position property: Specify how an image element is positioned with x, y coordinates inside its content box."
},
{
"code": null,
"e": 469,
"s": 357,
"text": "float property: Specify how an element should float and place an element on its container’s right or left side."
},
{
"code": null,
"e": 510,
"s": 469,
"text": "Method 1: Using object-position Property"
},
{
"code": null,
"e": 518,
"s": 510,
"text": "Syntax:"
},
{
"code": null,
"e": 546,
"s": 518,
"text": "object-position: <position>"
},
{
"code": null,
"e": 565,
"s": 548,
"text": "Property values:"
},
{
"code": null,
"e": 747,
"s": 565,
"text": "position: It takes 2 numerical values corresponding to the distance from the left of the content-box (x-axis) and the distance from the top of the content-box (y-axis) respectively."
},
{
"code": null,
"e": 753,
"s": 747,
"text": "Note:"
},
{
"code": null,
"e": 854,
"s": 753,
"text": "We can align elements using position property with some helper property left | right | top | bottom."
},
{
"code": null,
"e": 977,
"s": 854,
"text": "You can either use string values like right, left, center, top, or you can use numerical value in pixel like 200px, 250px."
},
{
"code": null,
"e": 986,
"s": 977,
"text": "Example:"
},
{
"code": null,
"e": 991,
"s": 986,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #object1 { width: 500px; height: 200px; background-color: green; object-fit: none; object-position: center top; /* String value */ } #object2 { width: 500px; height: 200px; background-color: green; object-fit: none; object-position: 50px 30px; /* Numeric value */ } </style></head> <body> <center> <h2 style=\"color:green\"> GeeksforGeeks </h2> <h4>object-position Property</h4> <img id=\"object1\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png\" /> <img id=\"object2\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png\" /> </center></body> </html>",
"e": 1945,
"s": 991,
"text": null
},
{
"code": null,
"e": 1953,
"s": 1945,
"text": "Output:"
},
{
"code": null,
"e": 1969,
"s": 1953,
"text": "object-position"
},
{
"code": null,
"e": 2000,
"s": 1969,
"text": "Method 2: Using float Property"
},
{
"code": null,
"e": 2008,
"s": 2000,
"text": "Syntax:"
},
{
"code": null,
"e": 2048,
"s": 2008,
"text": "float: none|inherit|left|right|initial;"
},
{
"code": null,
"e": 2112,
"s": 2048,
"text": "Note: Elements are floated only horizontally i.e. left or right"
},
{
"code": null,
"e": 2128,
"s": 2112,
"text": "Property Value:"
},
{
"code": null,
"e": 2177,
"s": 2128,
"text": "left: Place an element on its container’s right."
},
{
"code": null,
"e": 2226,
"s": 2177,
"text": "right: Place an element on its container’s left."
},
{
"code": null,
"e": 2317,
"s": 2226,
"text": "inherit: Element inherits floating property from it’s parent (div, table etc...) elements."
},
{
"code": null,
"e": 2364,
"s": 2317,
"text": "none: Element is displayed as it is (Default)."
},
{
"code": null,
"e": 2373,
"s": 2364,
"text": "Example:"
},
{
"code": null,
"e": 2378,
"s": 2373,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #object1 { width: 300px; height: 200px; float: right; } center { width: 500px; height: 500px; background-color: green; } </style></head> <body> <center> <h2 style=\"color:green\"> GeeksforGeeks </h2> <h4>Float Property</h4> <img id=\"object1\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png\" /> </center></body> </html>",
"e": 2957,
"s": 2378,
"text": null
},
{
"code": null,
"e": 2965,
"s": 2957,
"text": "Output:"
},
{
"code": null,
"e": 2980,
"s": 2965,
"text": "Float property"
},
{
"code": null,
"e": 2995,
"s": 2980,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3009,
"s": 2995,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3016,
"s": 3009,
"text": "Picked"
},
{
"code": null,
"e": 3020,
"s": 3016,
"text": "CSS"
},
{
"code": null,
"e": 3037,
"s": 3020,
"text": "Web Technologies"
}
] |
SIP - Quick Guide
|
Session Initiation Protocol (SIP) is one of the most common protocols used in VoIP technology. It is an application layer protocol that works in conjunction with other application layer protocols to control multimedia communication sessions over the Internet.
Before moving further, let us first understand a few points about VoIP.
VOIP is a technology that allows you to deliver voice and multimedia (videos, pictures) content over the Internet. It is one of the cheapest way to communicate anytime, anywhere with the Internet’s availability.
VOIP is a technology that allows you to deliver voice and multimedia (videos, pictures) content over the Internet. It is one of the cheapest way to communicate anytime, anywhere with the Internet’s availability.
Some advantages of VOIP include −
Low cost
Portability
No extra cables
Flexibility
Video conferencing
Some advantages of VOIP include −
Low cost
Low cost
Portability
Portability
No extra cables
No extra cables
Flexibility
Flexibility
Video conferencing
Video conferencing
For a VOIP call, all that you need is a computer/laptop/mobile with internet connectivity. The following figure depicts how a VoIP call takes place.
For a VOIP call, all that you need is a computer/laptop/mobile with internet connectivity. The following figure depicts how a VoIP call takes place.
With this much fundamental, let us get back to SIP.
Given below are a few points to note about SIP −
SIP is a signalling protocol used to create, modify, and terminate a multimedia session over the Internet Protocol. A session is nothing but a simple call between two endpoints. An endpoint can be a smartphone, a laptop, or any device that can receive and send multimedia content over the Internet.
SIP is a signalling protocol used to create, modify, and terminate a multimedia session over the Internet Protocol. A session is nothing but a simple call between two endpoints. An endpoint can be a smartphone, a laptop, or any device that can receive and send multimedia content over the Internet.
SIP is an application layer protocol defined by IETF (Internet Engineering Task Force) standard. It is defined in RFC 3261.
SIP is an application layer protocol defined by IETF (Internet Engineering Task Force) standard. It is defined in RFC 3261.
SIP embodies client-server architecture and the use of URL and URI from HTTP and a text encoding scheme and a header style from SMTP.
SIP embodies client-server architecture and the use of URL and URI from HTTP and a text encoding scheme and a header style from SMTP.
SIP takes the help of SDP (Session Description Protocol) which describes a session and RTP (Real Time Transport Protocol) used for delivering voice and video over IP network.
SIP takes the help of SDP (Session Description Protocol) which describes a session and RTP (Real Time Transport Protocol) used for delivering voice and video over IP network.
SIP can be used for two-party (unicast) or multiparty (multicast) sessions.
SIP can be used for two-party (unicast) or multiparty (multicast) sessions.
Other SIP applications include file transfer, instant messaging, video conferencing, online games, and steaming multimedia distribution.
Other SIP applications include file transfer, instant messaging, video conferencing, online games, and steaming multimedia distribution.
Basically SIP is an application layer protocol. It is a simple network signalling protocol for creating and terminating sessions with one or more participants. The SIP protocol is designed to be independent of the underlying transport protocol, so SIP applications can run on TCP, UDP, or other lower-layer networking protocols.
The following illustration depicts where SIP fits in in the general scheme of things −
Typically, the SIP protocol is used for internet telephony and multimedia distribution between two or more endpoints. For example, one person can initiate a telephone call to another person using SIP, or someone may create a conference call with many participants.
The SIP protocol was designed to be very simple, with a limited set of commands. It is also text-based, so anyone can read a SIP message passed between the endpoints in a SIP session.
There are some entities that help SIP in creating its network. In SIP, every network element is identified by a SIP URI (Uniform Resource Identifier) which is like an address. Following are the network elements −
User Agent
Proxy Server
Registrar Server
Redirect Server
Location Server
It is the endpoint and one of the most important network elements of a SIP network. An endpoint can initiate, modify, or terminate a session. User agents are the most intelligent device or network element of a SIP network. It could be a softphone, a mobile, or a laptop.
User agents are logically divided into two parts −
User Agent Client (UAC) − The entity that sends a request and receives a response.
User Agent Client (UAC) − The entity that sends a request and receives a response.
User Agent Server (UAS) − The entity that receives a request and sends a response.
User Agent Server (UAS) − The entity that receives a request and sends a response.
SIP is based on client-server architecture where the caller’s phone acts as a client which initiates a call and the callee’s phone acts as a server which responds the call.
It is the network element that takes a request from a user agent and forwards it to another user.
Basically the role of a proxy server is much like a router.
Basically the role of a proxy server is much like a router.
It has some intelligence to understand a SIP request and send it ahead with the help of URI.
It has some intelligence to understand a SIP request and send it ahead with the help of URI.
A proxy server sits in between two user agents.
A proxy server sits in between two user agents.
There can be a maximum of 70 proxy servers in between a source and a destination.
There can be a maximum of 70 proxy servers in between a source and a destination.
There are two types of proxy servers −
Stateless Proxy Server − It simply forwards the message received. This type of server does not store any information of a call or a transaction.
Stateless Proxy Server − It simply forwards the message received. This type of server does not store any information of a call or a transaction.
Stateful Proxy Server − This type of proxy server keeps track of every request and response received and can use it in future if required. It can retransmit the request, if there is no response from the other side in time.
Stateful Proxy Server − This type of proxy server keeps track of every request and response received and can use it in future if required. It can retransmit the request, if there is no response from the other side in time.
The registrar server accepts registration requests from user agents. It helps users to authenticate themselves within the network. It stores the URI and the location of users in a database to help other SIP servers within the same domain.
Take a look at the following example that shows the process of a SIP Registration.
Here the caller wants to register with the TMC domain. So it sends a REGISTER request to the TMC’s Registrar server and the server returns a 200 OK response as it authorized the client.
The redirect server receives requests and looks up the intended recipient of the request in the location database created by the registrar.
The redirect server uses the database for getting location information and responds with 3xx (Redirect response) to the user. We will discuss response codes later in this tutorial.
The location server provides information about a caller's possible locations to the redirect and proxy servers.
Only a proxy server or a redirect server can contact a location server.
The following figure depicts the roles played by each of the network elements in establishing a session.
SIP is structured as a layered protocol, which means its behavior is described in terms of a set of fairly independent processing stages with only a loose coupling between each stage.
The lowest layer of SIP is its syntax and encoding. Its encoding is specified using an augmented Backus-Naur Form grammar (BNF).
The lowest layer of SIP is its syntax and encoding. Its encoding is specified using an augmented Backus-Naur Form grammar (BNF).
At the second level is the transport layer. It defines how a Client sends requests and receives responses and how a Server receives requests and sends responses over the network. All SIP elements contain a transport layer.
At the second level is the transport layer. It defines how a Client sends requests and receives responses and how a Server receives requests and sends responses over the network. All SIP elements contain a transport layer.
Next comes the transaction layer. A transaction is a request sent by a Client transaction (using the transport layer) to a Server transaction, along with all responses to that request sent from the server transaction back to the client. Any task that a user agent client (UAC) accomplishes takes place using a series of transactions. Stateless proxies do not contain a transaction layer.
Next comes the transaction layer. A transaction is a request sent by a Client transaction (using the transport layer) to a Server transaction, along with all responses to that request sent from the server transaction back to the client. Any task that a user agent client (UAC) accomplishes takes place using a series of transactions. Stateless proxies do not contain a transaction layer.
The layer above the transaction layer is called the transaction user. Each of the SIP entities, except the Stateless proxies, is a transaction user.
The layer above the transaction layer is called the transaction user. Each of the SIP entities, except the Stateless proxies, is a transaction user.
The following image shows the basic call flow of a SIP session.
Given below is a step-by-step explanation of the above call flow −
An INVITE request that is sent to a proxy server is responsible for initiating a session.
An INVITE request that is sent to a proxy server is responsible for initiating a session.
The proxy server sendsa 100 Trying response immediately to the caller (Alice) to stop the re-transmissions of the INVITE request.
The proxy server sendsa 100 Trying response immediately to the caller (Alice) to stop the re-transmissions of the INVITE request.
The proxy server searches the address of Bob in the location server. After getting the address, it forwards the INVITE request further.
The proxy server searches the address of Bob in the location server. After getting the address, it forwards the INVITE request further.
Thereafter, 180 Ringing (Provisional responses) generated by Bob is returned back to Alice.
Thereafter, 180 Ringing (Provisional responses) generated by Bob is returned back to Alice.
A 200 OK response is generated soon after Bob picks the phone up.
A 200 OK response is generated soon after Bob picks the phone up.
Bob receives an ACK from the Alice, once it gets 200 OK.
Bob receives an ACK from the Alice, once it gets 200 OK.
At the same time, the session gets established and RTP packets (conversations) start flowing from both ends.
At the same time, the session gets established and RTP packets (conversations) start flowing from both ends.
After the conversation, any participant (Alice or Bob) can send a BYE request to terminate the session.
After the conversation, any participant (Alice or Bob) can send a BYE request to terminate the session.
BYE reaches directly from Alice to Bob bypassing the proxy server.
BYE reaches directly from Alice to Bob bypassing the proxy server.
Finally, Bob sends a 200 OK response to confirm the BYE and the session is terminated.
Finally, Bob sends a 200 OK response to confirm the BYE and the session is terminated.
In the above basic call flow, three transactions are (marked as 1, 2, 3) available.
In the above basic call flow, three transactions are (marked as 1, 2, 3) available.
The complete call (from INVITE to 200 OK) is known as a Dialog.
How does a proxy help to connect one user with another? Let us find out with the help of the following diagram.
The topology shown in the diagram is known as a SIP trapezoid. The process takes place as follows −
When a caller initiates a call, an INVITE message is sent to the proxy server. Upon receiving the INVITE, the proxy server attempts to resolve the address of the callee with the help of the DNS server.
When a caller initiates a call, an INVITE message is sent to the proxy server. Upon receiving the INVITE, the proxy server attempts to resolve the address of the callee with the help of the DNS server.
After getting the next route, caller’s proxy server (Proxy 1, also known as outbound proxy server) forwards the INVITE request to the callee’s proxy server which acts as an inbound proxy server (Proxy 2) for the callee.
After getting the next route, caller’s proxy server (Proxy 1, also known as outbound proxy server) forwards the INVITE request to the callee’s proxy server which acts as an inbound proxy server (Proxy 2) for the callee.
The inbound proxy server contacts the location server to get information about the callee’s address where the user registered.
The inbound proxy server contacts the location server to get information about the callee’s address where the user registered.
After getting information from the location server, it forwards the call to its destination.
After getting information from the location server, it forwards the call to its destination.
Once the user agents get to know their address, they can bypass the call, i.e., conversations pass directly.
Once the user agents get to know their address, they can bypass the call, i.e., conversations pass directly.
SIP messages are of two types − requests and responses.
The opening line of a request contains a method that defines the request, and a Request-URI that defines where the request is to be sent.
The opening line of a request contains a method that defines the request, and a Request-URI that defines where the request is to be sent.
Similarly, the opening line of a response contains a response code.
Similarly, the opening line of a response contains a response code.
SIP requests are the codes used to establish a communication. To complement them, there are SIP responses that generally indicate whether a request succeeded or failed.
These SIP requests which are known as METHODS make SIP message workable.
METHODS can be regarded as SIP requests, since they request a specific action to be taken by another user agent or server.
METHODS can be regarded as SIP requests, since they request a specific action to be taken by another user agent or server.
METHODS are distinguished into two types −
Core Methods
Extension Methods
METHODS are distinguished into two types −
Core Methods
Core Methods
Extension Methods
Extension Methods
There are six core methods as discussed below.
INVITE is used to initiate a session with a user agent. In other words, an INVITE method is used to establish a media session between the user agents.
INVITE can contain the media information of the caller in the message body.
INVITE can contain the media information of the caller in the message body.
A session is considered established if an INVITE has received a success response(2xx) or an ACK has been sent.
A session is considered established if an INVITE has received a success response(2xx) or an ACK has been sent.
A successful INVITE request establishes a dialog between the two user agents which continues until a BYE is sent to terminate the session.
A successful INVITE request establishes a dialog between the two user agents which continues until a BYE is sent to terminate the session.
An INVITE sent within an established dialog is known as a re-INVITE.
An INVITE sent within an established dialog is known as a re-INVITE.
Re-INVITE is used to change the session characteristics or refresh the state of a dialog.
Re-INVITE is used to change the session characteristics or refresh the state of a dialog.
The following code shows how INVITE is used.
INVITE sips:[email protected] SIP/2.0
Via: SIP/2.0/TLS client.ANC.com:5061;branch = z9hG4bK74bf9
Max-Forwards: 70
From: Alice<sips:[email protected]>;tag = 1234567
To: Bob<sips:[email protected]>
Call-ID: [email protected]
CSeq: 1 INVITE
Contact: <sips:[email protected]>
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY
Supported: replaces
Content-Type: application/sdp
Content-Length: ...
v = 0
o = Alice 2890844526 2890844526 IN IP4 client.ANC.com
s = Session SDP
c = IN IP4 client.ANC.com
t = 3034423619 0
m = audio 49170 RTP/AVP 0
a = rtpmap:0 PCMU/8000
BYE is the method used to terminate an established session. This is a SIP request that can be sent by either the caller or the callee to end a session.
It cannot be sent by a proxy server.
It cannot be sent by a proxy server.
BYE request normally routes end to end, bypassing the proxy server.
BYE request normally routes end to end, bypassing the proxy server.
BYE cannot be sent to a pending an INVITE or an unestablished session.
BYE cannot be sent to a pending an INVITE or an unestablished session.
REGISTER request performs the registration of a user agent. This request is sent by a user agent to a registrar server.
The REGISTER request may be forwarded or proxied until it reaches an authoritative registrar of the specified domain.
The REGISTER request may be forwarded or proxied until it reaches an authoritative registrar of the specified domain.
It carries the AOR (Address of Record) in the To header of the user that is being registered.
It carries the AOR (Address of Record) in the To header of the user that is being registered.
REGISTER request contains the time period (3600sec).
REGISTER request contains the time period (3600sec).
One user agent can send a REGISTER request on behalf of another user agent. This is known as third-party registration. Here, the From tag contains the URI of the party submitting the registration on behalf of the party identified in the To header.
One user agent can send a REGISTER request on behalf of another user agent. This is known as third-party registration. Here, the From tag contains the URI of the party submitting the registration on behalf of the party identified in the To header.
CANCEL is used to terminate a session which is not established. User agents use this request to cancel a pending call attempt initiated earlier.
It can be sent either by a user agent or a proxy server.
It can be sent either by a user agent or a proxy server.
CANCEL is a hop by hop request, i.e., it goes through the elements between the user agent and receives the response generated by the next stateful element.
CANCEL is a hop by hop request, i.e., it goes through the elements between the user agent and receives the response generated by the next stateful element.
ACK is used to acknowledge the final responses to an INVITE method. An ACK always goes in the direction of INVITE.ACK may contain SDP body (media characteristics), if it is not available in INVITE.
ACK may not be used to modify the media description that has already been sent in the initial INVITE.
ACK may not be used to modify the media description that has already been sent in the initial INVITE.
A stateful proxy receiving an ACK must determine whether or not the ACK should be forwarded downstream to another proxy or user agent.
A stateful proxy receiving an ACK must determine whether or not the ACK should be forwarded downstream to another proxy or user agent.
For 2xx responses, ACK is end to end, but for all other final responses, it works on hop by hop basis when stateful proxies are involved.
For 2xx responses, ACK is end to end, but for all other final responses, it works on hop by hop basis when stateful proxies are involved.
OPTIONS method is used to query a user agent or a proxy server about its capabilities and discover its current availability. The response to a request lists the capabilities of the user agent or server. A proxy never generates an OPTIONS request.
SUBSCRIBE is used by user agents to establish a subscription for the purpose of getting notification about a particular event.
It contains an Expires header field that indicates the duration of a subscription.
It contains an Expires header field that indicates the duration of a subscription.
After the time period passes, the subscription will automatically terminate.
After the time period passes, the subscription will automatically terminate.
Subscription establishes a dialog between the user agents.
Subscription establishes a dialog between the user agents.
You can re-subscription again by sending another SUBSCRIBE within the dialog before the expiration time.
You can re-subscription again by sending another SUBSCRIBE within the dialog before the expiration time.
A 200 OK will be received for a subscription from User.
A 200 OK will be received for a subscription from User.
Users can unsubscribe by sending another SUBSCRIBE method with Expires value 0(zero).
Users can unsubscribe by sending another SUBSCRIBE method with Expires value 0(zero).
NOTIFY is used by user agents to get the occurrence of a particular event. Usually a NOTIFY will trigger within a dialog when a subscription exists between the subscriber and the notifier.
Every NOTIFY will get 200 OK response if it is received by notifier.
Every NOTIFY will get 200 OK response if it is received by notifier.
NOTIFY contain an Event header field indicating the event and a subscriptionstate header field indicating the current state of the subscription.
NOTIFY contain an Event header field indicating the event and a subscriptionstate header field indicating the current state of the subscription.
A NOTIFY is always sent at the start and termination of a subscription.
A NOTIFY is always sent at the start and termination of a subscription.
PUBLISH is used by a user agent to send event state information to a server.
PUBLISH is mostly useful when there are multiple sources of event information.
PUBLISH is mostly useful when there are multiple sources of event information.
A PUBLISH request is similar to a NOTIFY, except that it is not sent in a dialog.
A PUBLISH request is similar to a NOTIFY, except that it is not sent in a dialog.
A PUBLISH request must contain an Expires header field and a Min-Expires header field.
A PUBLISH request must contain an Expires header field and a Min-Expires header field.
REFER is used by a user agent to refer another user agent to access a URI for the dialog.
REFER must contain a Refer-To header. This is a mandatory header for REFER.
REFER must contain a Refer-To header. This is a mandatory header for REFER.
REFER can be sent inside or outside a dialog.
REFER can be sent inside or outside a dialog.
A 202 Accepted will trigger a REFER request which indicates that other user agent has accepted the reference.
A 202 Accepted will trigger a REFER request which indicates that other user agent has accepted the reference.
INFO is used by a user agent to send call signalling information to another user agent with which it has established a media session.
This is an end-to-end request.
This is an end-to-end request.
A proxy will always forward an INFO request.
A proxy will always forward an INFO request.
UPDATE is used to modify the state of a session if a session is not established. User could change the codec with UPDATE.
IF a session is established, a re-Invite is used to change/update the session.
PRACK is used to acknowledge the receipt of a reliable transfer of provisional response (1XX).
Generally PRACK is generated by a client when it receive a provisional response containing an RSeq reliable sequence number and a supported:100rel header.
Generally PRACK is generated by a client when it receive a provisional response containing an RSeq reliable sequence number and a supported:100rel header.
PRACK contains (RSeq + CSeq) value in the rack header.
PRACK contains (RSeq + CSeq) value in the rack header.
The PRACK method applies to all provisional responses except the 100 Trying response, which is never reliably transported.
The PRACK method applies to all provisional responses except the 100 Trying response, which is never reliably transported.
A PRACK may contain a message body; it may be used for offer/answer exchange.
A PRACK may contain a message body; it may be used for offer/answer exchange.
It is used to send an instant message using SIP. An IM usually consists of short messages exchanged in real time by participants engaged in text conversation.
MESSAGE can be sent within a dialog or outside a dialog.
MESSAGE can be sent within a dialog or outside a dialog.
The contents of a MESSAGE are carried in the message body as a MIME attachment.
The contents of a MESSAGE are carried in the message body as a MIME attachment.
A 200 OK response is normally received to indicate that the message has been delivered at its destination.
A 200 OK response is normally received to indicate that the message has been delivered at its destination.
A SIP response is a message generated by a user agent server (UAS) or SIP server to reply a request generated by a client. It could be a formal acknowledgement to prevent retransmission of requests by a UAC.
A response may contain some additional header fields of info needed by a UAC.
A response may contain some additional header fields of info needed by a UAC.
SIP has six responses.
SIP has six responses.
1xx to 5xx has been borrowed from HTTP and 6xx is introduced in SIP.
1xx to 5xx has been borrowed from HTTP and 6xx is introduced in SIP.
1xx is considered as a provisional response and the rest are final responses.
1xx is considered as a provisional response and the rest are final responses.
Informational responses are used to indicate call progress. Normally the responses are end to end (except 100 Trying).
This class of responses is meant for indicating that a request has been accepted.
Generally these class responses are sent by redirect servers in response to INVITE. They are also known as redirect class responses.
Client error responses indicate that the request cannot be fulfilled as some errors are identified from the UAC side.
This class response is used to indicate that the request cannot be processed because of an error with the server.
This response class indicates that the server knows that the request will fail wherever it is tried. As a result, the request should not be sent to other locations.
A header is a component of a SIP message that conveys information about the message. It is structured as a sequence of header fields.
SIP header fields in most cases follow the same rules as HTTP header fields. Header fields are defined as Header: field, where Header is used to represent the header field name, and field is the set of tokens that contains the information. Each field consists of a fieldname followed by a colon (":") and the field-value (i.e., field-name: field-value).
Many common SIP header fields have a compact form where the header field name is denoted by a single lower case character. Some examples are given below −
The following image shows the structure of a typical SIP header.
Headers are categorized as follows depending on their usage in SIP −
Request and Response
Request Only
Response Only
Message Body
SDP stands for Session Description Protocol. It is used to describe multimedia sessions in a format understood by the participants over a network. Depending on this description, a party decides whether to join a conference or when or how to join a conference.
The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session.
The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session.
SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP.
SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP.
SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing.
SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing.
The purpose of SDP is to convey information about media streams in multimedia sessions to help participants join or gather info of a particular session.
SDP is a short structured textual description.
SDP is a short structured textual description.
It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information.
It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information.
A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so.
A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so.
The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter.
The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter.
The general form of a SDP message is −
x = parameter1 parameter2 ... parameterN
The general form of a SDP message is −
x = parameter1 parameter2 ... parameterN
The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters.
The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters.
Session description (* denotes optional)
v = (protocol version)
o = (owner/creator and session identifier)
s = (session name)
i =* (session information)
u =* (URI of description)
e =* (email address)
p =* (phone number)
c =* (connection information - not required if included in all media)
b =* (bandwidth information)
z =* (time zone adjustments)
k =* (encryption key)
a =* (zero or more session attribute lines)
The v= field contains the SDP version number. Because the current version of SDP is 0, a valid SDP message will always begin with v = 0.
The o= field contains information about the originator of the session and session identifiers. This field is used to uniquely identify the session.
The field contains −
o=<username><session-id><version><network-type><address-type>
The field contains −
o=<username><session-id><version><network-type><address-type>
The username parameter contains the originator’s login or host.
The username parameter contains the originator’s login or host.
The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness.
The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness.
The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp.
The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp.
The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name.
The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name.
The s= field contains a name for the session. It can contain any nonzero number of characters. The optional i= field contains information about the session. It can contain any number of characters.
The optional u= field contains a uniform resource indicator (URI) with more information about the session
The optional e= field contains an e-mail address of the host of the session. The optional p= field contains a phone number.
The c= field contains information about the media connection.
The field contains −
c =<network-type><address-type><connection-address>
The field contains −
c =<network-type><address-type><connection-address>
The network-type parameter is defined as IN for the Internet.
The network-type parameter is defined as IN for the Internet.
The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses.
The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses.
The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast.
The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast.
If multicast, the connection-address field contains −
connection-address=base-multicast-address/ttl/number-of-addresses
If multicast, the connection-address field contains −
connection-address=base-multicast-address/ttl/number-of-addresses
where ttl is the time-to-live value, and number-of-addresses indicates how many contiguous multicast addresses are included starting with the base-multicast address.
The optional b= field contains information about the bandwidth required. It is of the form −
b=modifier:bandwidth − value
The t= field contains the start time and stop time of the session.
t=start-time stop-time
The optional r= field contains information about the repeat times that can be specified in either in NTP or in days (d), hours (h), or minutes (m).
The optional z= field contains information about the time zone offsets. This field is used if are occurring session spans a change from daylight savings to standard time, or vice versa.
The optional m= field contains information about the type of media session. The field contains −
m= media port transport format-list
The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number.
The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number.
The transport parameter contains the transport protocol or the RTP profile used.
The transport parameter contains the transport protocol or the RTP profile used.
The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles.
The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles.
Example:
m = audio 49430 RTP/AVP 0 6 8 99
One of these three codecs can be used for the audio media session. If the intention is to establish three audio channels, three separate media fields would be used.
The optional a= field contains attributes of the preceding media session. This field can be used to extend SDP to provide more information about the media. If not fully understood by a SDP user, the attribute field can be ignored. There can be one or more attribute fields for each media payload type listed in the media field.
Attributes in SDP can be either
session level, or
media level.
Session level means that the attribute is listed before the first media line in the SDP. If this is the case, the attribute applies to all the media lines below it.
Media level means it is listed after a media line. In this case, the attribute only applies to this particular media stream.
SDP can include both session level and media level attributes. If the same attribute appears as both, the media level attribute overrides the session level attribute for that particular media stream. Note that the connection data field can also be either session level or media level.
Given below is an example session description, taken from RFC 2327 −
v = 0
o = mhandley2890844526 2890842807 IN IP4 126.16.64.4
s = SDP Seminar
i = A Seminar on the session description protocol
u = http://www.cs.ucl.ac.uk/staff/M.Handley/sdp.03.ps
e = [email protected](Mark Handley)
c = IN IP4 224.2.17.12/127
t = 2873397496 2873404696
a = recvonly
m = audio 49170 RTP/AVP 0
m = video 51372 RTP/AVP 31
m = application 32416udp wb
a = orient:portrait
The use of SDP with SIP is given in the SDP offer answer RFC 3264. The default message body type in SIP is application/sdp.
The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK.
The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK.
The called party lists their media capabilities in the 200 OK response to the INVITE.
The called party lists their media capabilities in the 200 OK response to the INVITE.
A typical SIP use of SDP includes the following fields: version, origin, subject, time, connection, and one or more media and attribute.
The subject and time fields are not used by SIP but are included for compatibility.
The subject and time fields are not used by SIP but are included for compatibility.
In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject.
In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject.
The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs.
The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs.
The origin field has limited use with SIP.
The origin field has limited use with SIP.
The session-id is usually kept constant throughout a SIP session.
The session-id is usually kept constant throughout a SIP session.
The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same.
The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same.
As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types.
As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types.
The offer/answer specification, RFC 3264, recommends that an attribute containing a = rtpmap: be used for each media field. A media stream is declined by setting the port number to zero for the corresponding media field in the SDP response.
In the following example, the caller Tesla wants to set up an audio and video call with two possible audio codecs and a video codec in the SDP carried in the initial INVITE −
v = 0
o = John 0844526 2890844526 IN IP4 172.22.1.102
s = -
c = IN IP4 172.22.1.102
t = 0 0
m = audio 6000 RTP/AVP 97 98
a = rtpmap:97 AMR/16000/1
a = rtpmap:98 AMR-WB/8000/1
m = video 49172 RTP/AVP 32
a = rtpmap:32 MPV/90000
The codecs are referenced by the RTP/AVP profile numbers 97, 98.
The called party Marry answers the call, chooses the second codec for the first media field, and declines the second media field, only wanting AMR session.
v = 0
o = Marry 2890844526 2890844526 IN IP4 172.22.1.110
s = -
c = IN IP4 200.201.202.203
t = 0 0
m = audio 60000 RTP/AVP 8
a = rtpmap:97 AMR/16000
m = video 0 RTP/AVP 32
If this audio-only call is not acceptable, then Tom would send an ACK then a BYE to cancel the call. Otherwise, the audio session would be established and RTP packets exchanged.
As this example illustrates, unless the number and order of media fields is maintained, the calling party would not know for certain which media sessions were being accepted and declined by the called party.
The offer/answer rules are summarized in the following sections.
An SDP offer must include all required SDP fields (this includes v=, o=, s=, c=,and t=). These are mandatory fields in SDP.
It usually includes a media field (m=) but it does not have to. The media lines contain all codecs listed in preference order. The only exception to this is if the endpoint supports a huge number of codecs, the most likely to be accepted or most preferred should be listed. Different media types include audio, video, text, MSRP, BFCP, and so forth.
An SDP answer to an offer must be constructed according to the following rules −
The answer must have the same number of m= lines in the same order as the answer.
The answer must have the same number of m= lines in the same order as the answer.
Individual media streams can be declined by setting the port number to 0.
Individual media streams can be declined by setting the port number to 0.
Streams are accepted by sending a nonzero port number.
Streams are accepted by sending a nonzero port number.
The listed payloads for each media type must be a subset of the payloads listed in the offer.
The listed payloads for each media type must be a subset of the payloads listed in the offer.
For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected.
For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected.
Either party can initiate another offer/answer exchange to modify a session. When a session is modified, the following rules must be followed −
The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed.
The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed.
The offer must include all existing media lines and they must be sent in the same order.
The offer must include all existing media lines and they must be sent in the same order.
Additional media streams can be added to the end of the m= line list.
Additional media streams can be added to the end of the m= line list.
An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session.
An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session.
One party in a call can temporarily place the other on hold. This is done by sending an INVITE with an identical SDP to that of the original INVITE but with a = sendonly attribute present.
The call is made active again by sending another INVITE with the a = sendrecv attribute present. The following illustration shows the call flow of a call hold.
Personal mobility is the ability to have a constant identifier across a number of devices. SIP supports basic personal mobility using the REGISTER method, which allows a mobile device to change its IP address and point of connection to the Internet and still be able to receive incoming calls.
SIP can also support service mobility – the ability of a user to keep the same services when mobile
A device binds its Contact URI with the address of record by a simple sip registration. According to the device IP address, registration authorizes this information automatically update in sip network.
During handover, the User agent routes between different operators, where it has to register again with a Contact as an AOR with another service provider.
For example, let’s take the example of the following call flow. UA which has temporarily received a new SIP URI with a new service provider. The UA then performs a double registration −
The first registration is with the new service operator, which binds the Contact URI of the device with the new service provider’s AOR URI.
The first registration is with the new service operator, which binds the Contact URI of the device with the new service provider’s AOR URI.
The second REGISTER request is routed back to the original service provider and provides the new service provider’s AOR as the Contact URI.
The second REGISTER request is routed back to the original service provider and provides the new service provider’s AOR as the Contact URI.
As shown later in the call flow, when a request comes in to the original service provider’s network, the INVITE is redirected to the new service provider who then routes the call to the user.
For the first registration, the message containing the device URI would be −
REGISTER sip:visited.registrar1.com SIP/2.0
Via: SIP/2.0/UDP 172.22.1.102:5060;branch = z9hG4bK97a7ea349ce0fca
Max-Forwards: 70
To: Tom <sip:[email protected]>
From: Tom <sip:[email protected]>;tag = 72d65a24
Call-ID: [email protected]
CSeq: 1 REGISTER
Contact: <sip:[email protected]:5060>
Expires: 600000
Content-Length: 0
The second registration message with the roaming URI would be −
REGISTER sip:home.registrar2.in SIP/2.0
Via: SIP/2.0/UDP 172.22.1.102:5060;branch = z9hG4bKah4vn2u
Max-Forwards: 70
To: Tom <sip:[email protected]>
From: Tom <sip:[email protected]>;tag = 45375
Call-ID:[email protected]
CSeq: 6421 REGISTER
Contact: <sip:[email protected]>
Content-Length: 0
The first INVITE that is represents in the above figure would be sent to sip:registrar2.in; the second INVITE would be sent to sip: sip:[email protected], which would be forwarded to sip:[email protected]. It reaches Tom and allows the session to be established. Periodically both registrations would need to be refreshed.
User Agent may change its IP address during the session as it swaps from one network to another. Basic SIP supports this scenario, as a re-INVITE in a dialog can be used to update the Contact URI and change the media information in the SDP.
Take a look at the call flow mentioned in the figure below.
Here, Tom detects a new network,
Here, Tom detects a new network,
Uses DHCP to acquire a new IP address, and
Uses DHCP to acquire a new IP address, and
Performs a re-INVITE to allow the signalling and media flow to the new IP address.
Performs a re-INVITE to allow the signalling and media flow to the new IP address.
If the UA can receive media from both networks, the interruption is negligible. If this is not the case, a few media packets may be lost, resulting in a slight interruption to the call.
The re-INVITE would appear as follows −
INVITE sip:[email protected] SIP/2.0
Via: SIP/2.0/UDP 172.22.1.102:5060;branch = z9hG4bK918f5a84fe6bf7a
Max-Forwards: 70
To: <sip:[email protected]>
From: sip:[email protected];tag = 70133df4
Call-ID: 76d4861c19c
CSeq: 1 INVITE
Accept: application/sdp
Accept-Language: en
Allow: INVITE,ACK,CANCEL,BYE,INFO,OPTIONS,REFER,NOTIFY,SUBSCRIBE
Contact: <sip:172.22.1.102:5060>;
Content-Type: application/sdp
Content-Length: 168
v = 0
o = PPT 40467 40468 IN IP4 192.168.2.1
s = -
c = IN IP4 192.168.2.1
b = AS:49
t = 0 0
b = RR:0
b = RS:0
a = rtpmap:97 AMR/8000/1
m = audio 6000 RTP/AVP 96
a = fmtp:102 0-15
a = ptime:20
a = maxptime:240
The re-INVITE contains Bowditch’s new IP address in the Via and Contact header fields and SDP media information.
In midcall mobility, the actual route set (set of SIP proxies that the SIP messages must traverse) must change. We cannot use a re-INVITE in midcall mobility
For example, if a proxy is necessary for NAT traversal, then Contact URI must be changed — a new dialog must be created. Hence, it has to send a new INVITE with a Replaces header, which identifies the existing session.
Note − Suppose A & B both are in a call and if A gets another INVITE (let’s say from C) with a replace header (should match existing dialog), then A must accept the INVITE and terminate the session with B and transfer all resource to newly formed dialog.
The call flow is shown in the following Figure. It is similar to the previous call flow using re-INVITE except that a BYE is automatically generated to terminate the existing dialog when the INVITE with the Replaces is accepted.
Given below are the points to note in this scenario −
The existing dialog between Tom and Jerry includes the old visited proxy server.
The existing dialog between Tom and Jerry includes the old visited proxy server.
The new dialog using the new wireless network requires the inclusion of the new visited proxy server.
The new dialog using the new wireless network requires the inclusion of the new visited proxy server.
As a result, an INVITE with Replaces is sent by Tom, which creates a new dialog that includes the new visited proxy server but not the old visited proxy server.
As a result, an INVITE with Replaces is sent by Tom, which creates a new dialog that includes the new visited proxy server but not the old visited proxy server.
When Jerry accepts the INVITE, a BYE is automatically sent to terminate the old dialog that routes through the old visited proxy server that is now no longer involved in the session.
When Jerry accepts the INVITE, a BYE is automatically sent to terminate the old dialog that routes through the old visited proxy server that is now no longer involved in the session.
The resulting media session is established using Tom’s new IP address from the SDP in the INVITE.
The resulting media session is established using Tom’s new IP address from the SDP in the INVITE.
Services in SIP can be provided in either proxies or in UAs. Providing service mobility along with personal mobility can be challenging unless the user’s devices are identically configured with the same services.
SIP can easily support service mobility over the Internet. When connected to Internet, a UA configured to use a set of proxies in India can still use those proxies when roaming in Europe. It does not have any impact on the quality of the media session as the media always flows directly between the two UAs and does not traverse the SIP proxy servers.
Endpoint resident services are available only when the endpoint is connected to the Internet. A terminating service such as a call forwarding service implemented in an endpoint will fail if the endpoint has temporarily lost its Internet connection. Hence some services are implemented in the network using SIP proxy servers.
Sometime a proxy server forwards a single SIP call to multiple SIP endpoints. This process is known as forking. Here a single call can ring many endpoints at the same time.
With SIP forking, you can have your desk phone ring at the same time as your softphone or a SIP phone on your mobile, allowing you to take the call from either device easily.
Generally, in an office, suppose boss unable to pick the call or away, SIP forking allow the secretary to answer calls his extension.
Forking will be possible if there is a stateful proxy available as it needs to perform and response out of the many it receives.
We have two types of forking −
Parallel Forking
Sequential Forking
In this scenario, the proxy server will fork the INVITE to, say, two devices (UA2, UA3) at a time. Both the devices will generate 180 Ringing and whoever receives the call will generate a 200 OK. The response (suppose UA2) that reaches the Originator first will establish a session with UA2. For the other response, a CANCEL will be triggered.
If the originator receives both the responses simultaneously, then based on q-value, it will forward the response.
In this scenario, the proxy server will fork the INVITE to one device (UA2). If UA2 is unavailable or busy at that time, then the proxy will fork it to another device (UA3).
Branch IDs help proxies to match responses to forked requests. Without Branch IDs, a proxy server would not be able to understand the forked response. Branch-id will be available in Via header.
Tags are used by the UAC to distinguish multiple final responses from different UAS. A UAS cannot resolve whether the request has been forked or not. Therefore, it need to add a tag.
Proxies also can add tags if it generates a final response, they never insert tags into requests or responses they forward.
It may be possible that a single request can be forked by multiple proxy servers also. So the proxy which would fork shall add its own unique IDs to the branches it created.
A call leg refers to one to one signalling relationship between two user agents. The call ID is a unique identifier carried in SIP message that refers to the call. A call is a collection of call legs.
A UAC starts by sending an INVITE. Due to forking, it may receive multiple 200 OK from different UAs. Each corresponds to a different call leg within the same call.
A call is thus a group of call legs. A call leg refers to end-to-end connection between UAs.
The CSeq spaces in the two directions of a call leg are independent. Within a single direction, the sequence number is incremented for each transaction.
Voicemail is very common now-a-days for enterprise users. It’s a telephone application. It comes to picture when the called party is unavailable or unable to receive the call, the PBX will announce to calling party to leave a voice message.
User agent will either get a 3xx response or redirect to voicemail server if the called party’s number is unreachable. However, some kind of SIP extension is needed to indicate to the voicemail system which mailbox to use—that is, which greeting to play and where to store the recorded message. There are two ways to achieve this −
By using a SIP header field extension
By using a SIP header field extension
By using the Request-URI to signal this information
By using the Request-URI to signal this information
Suppose for the user sip:[email protected] has a voicemail system at sip:voicemail.tutorialspoint.com which is providing voicemail, the Request-URI of the INVITE when it is forwarded to the voicemail server could look like −
sip:voicemail.tutorialspoint.com;target = sip:[email protected];cause = 486
The following illustration shows how the Request-URI carries the mailbox identifier and the reason (here 486).
As we know, a proxy server can be either stateless or stateful. Here, in this chapter, we will discuss more on proxy servers and SIP routing.
A stateless proxy server simply forwards the message it receives. This kind of server does not store any information of the call or transaction.
Stateless proxies forget about the SIP request once it has been forwarded.
Transaction will be fast via stateless proxies.
A stateful proxy server keeps track of every request and response that it receives. It can use the stored information in future, if required. It can retransmit the request if it does not receive a response from the other side.
Stateful proxies remember the request after it has been forwarded, so they can use it for advance routing. Stateful proxies maintain transaction state. Transaction implies transaction state, not call state.
Stateful proxies remember the request after it has been forwarded, so they can use it for advance routing. Stateful proxies maintain transaction state. Transaction implies transaction state, not call state.
Transaction is not as fast with stateful proxies as stateless.
Transaction is not as fast with stateful proxies as stateless.
Stateful proxies can fork and retransmit if required.(e.g.: call forward busy, for example).
Stateful proxies can fork and retransmit if required.(e.g.: call forward busy, for example).
The Record-Route header is inserted into requests by proxies that wanted to be in the path of subsequent requests for the same call-id. It is then used by the user agent to route subsequent requests.
Via headers are inserted by servers into requests to detect loops and to help responses to find their way back to the client. This is helpful for only responses to reach their destination.
A UA himself generate and add its own address in a Via header field while sending request.
A UA himself generate and add its own address in a Via header field while sending request.
A proxy forwarding the request adds a Via header field containing its own address to the top of the list of Via header fields.
A proxy forwarding the request adds a Via header field containing its own address to the top of the list of Via header fields.
A proxy or UA generating a response to a request copies all the Via header fields from the request in order into the response, then sends the response to the address specified in the top Via header field.
A proxy or UA generating a response to a request copies all the Via header fields from the request in order into the response, then sends the response to the address specified in the top Via header field.
A proxy receiving a response checks the top Via header field and matches its own address. If it does not match, the response has been discarded.
A proxy receiving a response checks the top Via header field and matches its own address. If it does not match, the response has been discarded.
The top Via header field is then removed, and the response forwarded to the address specified in the next Via header field.
The top Via header field is then removed, and the response forwarded to the address specified in the next Via header field.
Via header fields contain protocolname, versionnumber, and transport (SIP/2.0/UDP, SIP/2.0/TCP, etc.) and contain portnumbers and parameters such as received, rport, branch.
A received tag is added to a Via header field if a UA or proxy receives the request from a different address than that specified in the top Via header field.
A received tag is added to a Via header field if a UA or proxy receives the request from a different address than that specified in the top Via header field.
A branch parameter is added to Via header fields by UAs and proxies, which is computed as a hash function of the Request-URI, and the To, From, Call-ID, and CSeq number.
A branch parameter is added to Via header fields by UAs and proxies, which is computed as a hash function of the Request-URI, and the To, From, Call-ID, and CSeq number.
SIP (Softphone) and PSTN (Old telephone) both are different networks and speaks different languages. So we need a translator (Gateway here) to communicate between these two networks.
Let us take an example to show how a SIP phone places a telephone call to a PSTN through PSTN gateway.
In this example, Tom (sip:[email protected]) is a sip phone and Jerry uses a global telephone number +91401234567.
The following illustration shows a call flow from SIP to PSTN through gateways.
Given below is a step-by-step explanation of all the process that takes place while placing a call from a SIP phone to PSTN.
First of all, (Tom)SIP phone dials the global number +91401234567 to reach Jerry. SIP user agent understands it as a global number and converts it into request-uri using DNS and trigger the request.
First of all, (Tom)SIP phone dials the global number +91401234567 to reach Jerry. SIP user agent understands it as a global number and converts it into request-uri using DNS and trigger the request.
The SIP phone sends the INVITE directly to gateway.
The SIP phone sends the INVITE directly to gateway.
The gateway initiates the call into the PSTN by selecting an SS7 ISUP trunk to the next telephone switch in the PSTN.
The gateway initiates the call into the PSTN by selecting an SS7 ISUP trunk to the next telephone switch in the PSTN.
The dialled digits from the INVITE are mapped into the ISUP IAM. The ISUP address complete message (ACM) is sent back by the PSTN to indicate that the trunk has been created.
The dialled digits from the INVITE are mapped into the ISUP IAM. The ISUP address complete message (ACM) is sent back by the PSTN to indicate that the trunk has been created.
The telephone generates ringtone and it goes to telephone switch. The gateway maps the ACM to the 183 Session Progress response containing an SDP indicating the RTP port that the gateway will use to bridge the audio from the PSTN.
The telephone generates ringtone and it goes to telephone switch. The gateway maps the ACM to the 183 Session Progress response containing an SDP indicating the RTP port that the gateway will use to bridge the audio from the PSTN.
Upon reception of the 183, the caller’s UAC begins receiving the RTP packets sent from the gateway and presents the audio to the caller so they know that the callee progressing in the PSTN.
Upon reception of the 183, the caller’s UAC begins receiving the RTP packets sent from the gateway and presents the audio to the caller so they know that the callee progressing in the PSTN.
The call completes when the called party answers the telephone, which causes the telephone switch to send an answer message (ANM) to the gateway.
The call completes when the called party answers the telephone, which causes the telephone switch to send an answer message (ANM) to the gateway.
The gateway then cuts the PSTN audio connection through in both directions and sends a 200 OK response to the caller. As the RTP media path is already established, the gateway replies the SDP in the 183 but causes no changes to the RTP connection.
The gateway then cuts the PSTN audio connection through in both directions and sends a 200 OK response to the caller. As the RTP media path is already established, the gateway replies the SDP in the 183 but causes no changes to the RTP connection.
The UAC sends an ACK to complete the SIP signalling exchange. As there is no equivalent message in ISUP, the gateway absorbs the ACK.
The UAC sends an ACK to complete the SIP signalling exchange. As there is no equivalent message in ISUP, the gateway absorbs the ACK.
The caller sends BYE to gateway to terminates. The gateway maps the BYE into the ISUP release message (REL).
The caller sends BYE to gateway to terminates. The gateway maps the BYE into the ISUP release message (REL).
The gateway sends the 200OK to the BYE and receives an RLC from the PSTN.
The gateway sends the 200OK to the BYE and receives an RLC from the PSTN.
A codec, short for coder-decoder, does two basic operations −
First, it converts an analog voice signal to its equivalent digital form so that it can be easily transmitted.
First, it converts an analog voice signal to its equivalent digital form so that it can be easily transmitted.
Thereafter, it converts the compressed digital signal back to its original analog form so that it can be replayed.
Thereafter, it converts the compressed digital signal back to its original analog form so that it can be replayed.
There are many codecs available in the market – some are free while others require licensing. Codecs vary in the sound quality and vary in bandwidth accordingly.
Hardware devices such as phones and gateways support several different codecs. While talking to each other, they negotiate which codec they will use.
Here, in this chapter, we will discuss a few popular SIP audio codecs that are widely used.
G.711 is a codec that was introduced by ITU in 1972 for use in digital telephony. The codec has two variants: A-Law is being used in Europe and in international telephone links, uLaw is used in the U.S.A. and Japan.
G.711 uses a logarithmic compression. It squeezes each 16-bit sample to 8 bits, thus it achieves a compression ratio of 1:2.
G.711 uses a logarithmic compression. It squeezes each 16-bit sample to 8 bits, thus it achieves a compression ratio of 1:2.
The bitrate is 64 kbit/s for one direction, so a call consumes 128 kbit/s.
The bitrate is 64 kbit/s for one direction, so a call consumes 128 kbit/s.
G.711 is the same codec used by the PSTN network, hence it provides the best voice quality. However it consumes more bandwidth than other codecs.
G.711 is the same codec used by the PSTN network, hence it provides the best voice quality. However it consumes more bandwidth than other codecs.
It works best in local area networks where we have a lot of bandwidth available.
It works best in local area networks where we have a lot of bandwidth available.
G.729 is a codec with low bandwidth requirements; it provides good audio quality.
The codec encodes audio in frames of 10 ms long. Given a sampling frequency of 8 kHz, a 10 ms frame contains 80 audio samples.
The codec encodes audio in frames of 10 ms long. Given a sampling frequency of 8 kHz, a 10 ms frame contains 80 audio samples.
The codec algorithm encodes each frame into 10 bytes, so the resulting bitrate is 8 kbit/s in one direction.
The codec algorithm encodes each frame into 10 bytes, so the resulting bitrate is 8 kbit/s in one direction.
G.729 is a licensed codec. End-users who want to use this codec should buy a hardware that implements it (be it a VoIP phone or gateway).
G.729 is a licensed codec. End-users who want to use this codec should buy a hardware that implements it (be it a VoIP phone or gateway).
A frequently used variant of G.729 is G.729a. It is wire-compatible with the original codec but has lower CPU requirements.
A frequently used variant of G.729 is G.729a. It is wire-compatible with the original codec but has lower CPU requirements.
G.723.1 is the result of a competition that ITU announced with the aim to design a codec that would allow calls over 28.8 and 33 kbit/s modem links.
We have two variants of G.723.1. They both operate on audio frames of 30 ms (i.e. 240 samples), but the algorithms differ.
We have two variants of G.723.1. They both operate on audio frames of 30 ms (i.e. 240 samples), but the algorithms differ.
The bitrate of the first variant is 6.4 kbit/s, while for the second variant, it is 5.3 kbit/s.
The bitrate of the first variant is 6.4 kbit/s, while for the second variant, it is 5.3 kbit/s.
The encoded frames for the two variants are 24 and 20 bytes long, respectively.
The encoded frames for the two variants are 24 and 20 bytes long, respectively.
GSM 06.10 is a codec designed for GSM mobile networks. It is also known as GSM Full Rate.
This variant of the GSM codec can be freely used, so you will often find it in open source VoIP applications.
This variant of the GSM codec can be freely used, so you will often find it in open source VoIP applications.
The codec operates on audio frames 20 ms long (i.e. 160 samples) and it compresses each frame to 33 bytes, so the resulting bitrate is 13 kbit/.
The codec operates on audio frames 20 ms long (i.e. 160 samples) and it compresses each frame to 33 bytes, so the resulting bitrate is 13 kbit/.
A back-to-back user agent (B2BUA) is a logical network element in SIP applications. It is a type of SIP UA that receives a SIP request, then reformulates the request, and sends it out as a new request.
Unlike a proxy server, it maintains dialog state and must participate in all requests sent on the dialogs it has established. A B2BUA breaks the end-to-end nature of SIP.
A B2BUA agent operates between two endpoints of a phone call and divides the communication channel into two call legs. B2BUA is a concatenation of UAC and UAS. It participates in all SIP signalling between both ends of the call, it has established. As B2BUA available in a dialog service provider may implement some value-added features.
In the originating call leg, the B2BUA acts as a user agent server (UAS) and processes the request as a user agent client (UAC) to the destination end, handling the signalling between end points back-to-back.
A B2BUA maintains the complete state for the calls it handles. Each side of a B2BUA operates as a standard SIP network element as specified in RFC 3261.
A B2BUA provides the following functions −
Call management (billing, automatic call disconnection, call transfer, etc.)
Call management (billing, automatic call disconnection, call transfer, etc.)
Network interworking (perhaps with protocol adaptation)
Network interworking (perhaps with protocol adaptation)
Hiding of network internals (private addresses, network topology, etc.)
Hiding of network internals (private addresses, network topology, etc.)
Often, B2BUAs are also implemented in media gateways to bridge the media streams for full control over the session.
Many private branch exchange (PBX) enterprise telephone systems incorporate B2BUA logic.
Some firewalls have built in with ALG (Application Layer Gateway) functionality, which allows a firewall to authorize SIP and media traffic while still maintaining a high level of security.
Another common type of B2BUA is known as a Session Border Controller (SBC).
|
[
{
"code": null,
"e": 2244,
"s": 1984,
"text": "Session Initiation Protocol (SIP) is one of the most common protocols used in VoIP technology. It is an application layer protocol that works in conjunction with other application layer protocols to control multimedia communication sessions over the Internet."
},
{
"code": null,
"e": 2316,
"s": 2244,
"text": "Before moving further, let us first understand a few points about VoIP."
},
{
"code": null,
"e": 2528,
"s": 2316,
"text": "VOIP is a technology that allows you to deliver voice and multimedia (videos, pictures) content over the Internet. It is one of the cheapest way to communicate anytime, anywhere with the Internet’s availability."
},
{
"code": null,
"e": 2740,
"s": 2528,
"text": "VOIP is a technology that allows you to deliver voice and multimedia (videos, pictures) content over the Internet. It is one of the cheapest way to communicate anytime, anywhere with the Internet’s availability."
},
{
"code": null,
"e": 2845,
"s": 2740,
"text": "Some advantages of VOIP include −\n\nLow cost\nPortability\nNo extra cables\nFlexibility\nVideo conferencing\n\n"
},
{
"code": null,
"e": 2879,
"s": 2845,
"text": "Some advantages of VOIP include −"
},
{
"code": null,
"e": 2888,
"s": 2879,
"text": "Low cost"
},
{
"code": null,
"e": 2897,
"s": 2888,
"text": "Low cost"
},
{
"code": null,
"e": 2909,
"s": 2897,
"text": "Portability"
},
{
"code": null,
"e": 2921,
"s": 2909,
"text": "Portability"
},
{
"code": null,
"e": 2937,
"s": 2921,
"text": "No extra cables"
},
{
"code": null,
"e": 2953,
"s": 2937,
"text": "No extra cables"
},
{
"code": null,
"e": 2965,
"s": 2953,
"text": "Flexibility"
},
{
"code": null,
"e": 2977,
"s": 2965,
"text": "Flexibility"
},
{
"code": null,
"e": 2996,
"s": 2977,
"text": "Video conferencing"
},
{
"code": null,
"e": 3015,
"s": 2996,
"text": "Video conferencing"
},
{
"code": null,
"e": 3164,
"s": 3015,
"text": "For a VOIP call, all that you need is a computer/laptop/mobile with internet connectivity. The following figure depicts how a VoIP call takes place."
},
{
"code": null,
"e": 3313,
"s": 3164,
"text": "For a VOIP call, all that you need is a computer/laptop/mobile with internet connectivity. The following figure depicts how a VoIP call takes place."
},
{
"code": null,
"e": 3365,
"s": 3313,
"text": "With this much fundamental, let us get back to SIP."
},
{
"code": null,
"e": 3414,
"s": 3365,
"text": "Given below are a few points to note about SIP −"
},
{
"code": null,
"e": 3713,
"s": 3414,
"text": "SIP is a signalling protocol used to create, modify, and terminate a multimedia session over the Internet Protocol. A session is nothing but a simple call between two endpoints. An endpoint can be a smartphone, a laptop, or any device that can receive and send multimedia content over the Internet."
},
{
"code": null,
"e": 4012,
"s": 3713,
"text": "SIP is a signalling protocol used to create, modify, and terminate a multimedia session over the Internet Protocol. A session is nothing but a simple call between two endpoints. An endpoint can be a smartphone, a laptop, or any device that can receive and send multimedia content over the Internet."
},
{
"code": null,
"e": 4136,
"s": 4012,
"text": "SIP is an application layer protocol defined by IETF (Internet Engineering Task Force) standard. It is defined in RFC 3261."
},
{
"code": null,
"e": 4260,
"s": 4136,
"text": "SIP is an application layer protocol defined by IETF (Internet Engineering Task Force) standard. It is defined in RFC 3261."
},
{
"code": null,
"e": 4394,
"s": 4260,
"text": "SIP embodies client-server architecture and the use of URL and URI from HTTP and a text encoding scheme and a header style from SMTP."
},
{
"code": null,
"e": 4528,
"s": 4394,
"text": "SIP embodies client-server architecture and the use of URL and URI from HTTP and a text encoding scheme and a header style from SMTP."
},
{
"code": null,
"e": 4703,
"s": 4528,
"text": "SIP takes the help of SDP (Session Description Protocol) which describes a session and RTP (Real Time Transport Protocol) used for delivering voice and video over IP network."
},
{
"code": null,
"e": 4878,
"s": 4703,
"text": "SIP takes the help of SDP (Session Description Protocol) which describes a session and RTP (Real Time Transport Protocol) used for delivering voice and video over IP network."
},
{
"code": null,
"e": 4954,
"s": 4878,
"text": "SIP can be used for two-party (unicast) or multiparty (multicast) sessions."
},
{
"code": null,
"e": 5030,
"s": 4954,
"text": "SIP can be used for two-party (unicast) or multiparty (multicast) sessions."
},
{
"code": null,
"e": 5167,
"s": 5030,
"text": "Other SIP applications include file transfer, instant messaging, video conferencing, online games, and steaming multimedia distribution."
},
{
"code": null,
"e": 5304,
"s": 5167,
"text": "Other SIP applications include file transfer, instant messaging, video conferencing, online games, and steaming multimedia distribution."
},
{
"code": null,
"e": 5633,
"s": 5304,
"text": "Basically SIP is an application layer protocol. It is a simple network signalling protocol for creating and terminating sessions with one or more participants. The SIP protocol is designed to be independent of the underlying transport protocol, so SIP applications can run on TCP, UDP, or other lower-layer networking protocols."
},
{
"code": null,
"e": 5720,
"s": 5633,
"text": "The following illustration depicts where SIP fits in in the general scheme of things −"
},
{
"code": null,
"e": 5985,
"s": 5720,
"text": "Typically, the SIP protocol is used for internet telephony and multimedia distribution between two or more endpoints. For example, one person can initiate a telephone call to another person using SIP, or someone may create a conference call with many participants."
},
{
"code": null,
"e": 6169,
"s": 5985,
"text": "The SIP protocol was designed to be very simple, with a limited set of commands. It is also text-based, so anyone can read a SIP message passed between the endpoints in a SIP session."
},
{
"code": null,
"e": 6382,
"s": 6169,
"text": "There are some entities that help SIP in creating its network. In SIP, every network element is identified by a SIP URI (Uniform Resource Identifier) which is like an address. Following are the network elements −"
},
{
"code": null,
"e": 6393,
"s": 6382,
"text": "User Agent"
},
{
"code": null,
"e": 6406,
"s": 6393,
"text": "Proxy Server"
},
{
"code": null,
"e": 6423,
"s": 6406,
"text": "Registrar Server"
},
{
"code": null,
"e": 6439,
"s": 6423,
"text": "Redirect Server"
},
{
"code": null,
"e": 6455,
"s": 6439,
"text": "Location Server"
},
{
"code": null,
"e": 6726,
"s": 6455,
"text": "It is the endpoint and one of the most important network elements of a SIP network. An endpoint can initiate, modify, or terminate a session. User agents are the most intelligent device or network element of a SIP network. It could be a softphone, a mobile, or a laptop."
},
{
"code": null,
"e": 6777,
"s": 6726,
"text": "User agents are logically divided into two parts −"
},
{
"code": null,
"e": 6860,
"s": 6777,
"text": "User Agent Client (UAC) − The entity that sends a request and receives a response."
},
{
"code": null,
"e": 6943,
"s": 6860,
"text": "User Agent Client (UAC) − The entity that sends a request and receives a response."
},
{
"code": null,
"e": 7026,
"s": 6943,
"text": "User Agent Server (UAS) − The entity that receives a request and sends a response."
},
{
"code": null,
"e": 7109,
"s": 7026,
"text": "User Agent Server (UAS) − The entity that receives a request and sends a response."
},
{
"code": null,
"e": 7282,
"s": 7109,
"text": "SIP is based on client-server architecture where the caller’s phone acts as a client which initiates a call and the callee’s phone acts as a server which responds the call."
},
{
"code": null,
"e": 7380,
"s": 7282,
"text": "It is the network element that takes a request from a user agent and forwards it to another user."
},
{
"code": null,
"e": 7440,
"s": 7380,
"text": "Basically the role of a proxy server is much like a router."
},
{
"code": null,
"e": 7500,
"s": 7440,
"text": "Basically the role of a proxy server is much like a router."
},
{
"code": null,
"e": 7593,
"s": 7500,
"text": "It has some intelligence to understand a SIP request and send it ahead with the help of URI."
},
{
"code": null,
"e": 7686,
"s": 7593,
"text": "It has some intelligence to understand a SIP request and send it ahead with the help of URI."
},
{
"code": null,
"e": 7734,
"s": 7686,
"text": "A proxy server sits in between two user agents."
},
{
"code": null,
"e": 7782,
"s": 7734,
"text": "A proxy server sits in between two user agents."
},
{
"code": null,
"e": 7864,
"s": 7782,
"text": "There can be a maximum of 70 proxy servers in between a source and a destination."
},
{
"code": null,
"e": 7946,
"s": 7864,
"text": "There can be a maximum of 70 proxy servers in between a source and a destination."
},
{
"code": null,
"e": 7985,
"s": 7946,
"text": "There are two types of proxy servers −"
},
{
"code": null,
"e": 8130,
"s": 7985,
"text": "Stateless Proxy Server − It simply forwards the message received. This type of server does not store any information of a call or a transaction."
},
{
"code": null,
"e": 8275,
"s": 8130,
"text": "Stateless Proxy Server − It simply forwards the message received. This type of server does not store any information of a call or a transaction."
},
{
"code": null,
"e": 8498,
"s": 8275,
"text": "Stateful Proxy Server − This type of proxy server keeps track of every request and response received and can use it in future if required. It can retransmit the request, if there is no response from the other side in time."
},
{
"code": null,
"e": 8721,
"s": 8498,
"text": "Stateful Proxy Server − This type of proxy server keeps track of every request and response received and can use it in future if required. It can retransmit the request, if there is no response from the other side in time."
},
{
"code": null,
"e": 8960,
"s": 8721,
"text": "The registrar server accepts registration requests from user agents. It helps users to authenticate themselves within the network. It stores the URI and the location of users in a database to help other SIP servers within the same domain."
},
{
"code": null,
"e": 9043,
"s": 8960,
"text": "Take a look at the following example that shows the process of a SIP Registration."
},
{
"code": null,
"e": 9229,
"s": 9043,
"text": "Here the caller wants to register with the TMC domain. So it sends a REGISTER request to the TMC’s Registrar server and the server returns a 200 OK response as it authorized the client."
},
{
"code": null,
"e": 9369,
"s": 9229,
"text": "The redirect server receives requests and looks up the intended recipient of the request in the location database created by the registrar."
},
{
"code": null,
"e": 9550,
"s": 9369,
"text": "The redirect server uses the database for getting location information and responds with 3xx (Redirect response) to the user. We will discuss response codes later in this tutorial."
},
{
"code": null,
"e": 9662,
"s": 9550,
"text": "The location server provides information about a caller's possible locations to the redirect and proxy servers."
},
{
"code": null,
"e": 9734,
"s": 9662,
"text": "Only a proxy server or a redirect server can contact a location server."
},
{
"code": null,
"e": 9839,
"s": 9734,
"text": "The following figure depicts the roles played by each of the network elements in establishing a session."
},
{
"code": null,
"e": 10023,
"s": 9839,
"text": "SIP is structured as a layered protocol, which means its behavior is described in terms of a set of fairly independent processing stages with only a loose coupling between each stage."
},
{
"code": null,
"e": 10152,
"s": 10023,
"text": "The lowest layer of SIP is its syntax and encoding. Its encoding is specified using an augmented Backus-Naur Form grammar (BNF)."
},
{
"code": null,
"e": 10281,
"s": 10152,
"text": "The lowest layer of SIP is its syntax and encoding. Its encoding is specified using an augmented Backus-Naur Form grammar (BNF)."
},
{
"code": null,
"e": 10504,
"s": 10281,
"text": "At the second level is the transport layer. It defines how a Client sends requests and receives responses and how a Server receives requests and sends responses over the network. All SIP elements contain a transport layer."
},
{
"code": null,
"e": 10727,
"s": 10504,
"text": "At the second level is the transport layer. It defines how a Client sends requests and receives responses and how a Server receives requests and sends responses over the network. All SIP elements contain a transport layer."
},
{
"code": null,
"e": 11115,
"s": 10727,
"text": "Next comes the transaction layer. A transaction is a request sent by a Client transaction (using the transport layer) to a Server transaction, along with all responses to that request sent from the server transaction back to the client. Any task that a user agent client (UAC) accomplishes takes place using a series of transactions. Stateless proxies do not contain a transaction layer."
},
{
"code": null,
"e": 11503,
"s": 11115,
"text": "Next comes the transaction layer. A transaction is a request sent by a Client transaction (using the transport layer) to a Server transaction, along with all responses to that request sent from the server transaction back to the client. Any task that a user agent client (UAC) accomplishes takes place using a series of transactions. Stateless proxies do not contain a transaction layer."
},
{
"code": null,
"e": 11652,
"s": 11503,
"text": "The layer above the transaction layer is called the transaction user. Each of the SIP entities, except the Stateless proxies, is a transaction user."
},
{
"code": null,
"e": 11801,
"s": 11652,
"text": "The layer above the transaction layer is called the transaction user. Each of the SIP entities, except the Stateless proxies, is a transaction user."
},
{
"code": null,
"e": 11865,
"s": 11801,
"text": "The following image shows the basic call flow of a SIP session."
},
{
"code": null,
"e": 11932,
"s": 11865,
"text": "Given below is a step-by-step explanation of the above call flow −"
},
{
"code": null,
"e": 12022,
"s": 11932,
"text": "An INVITE request that is sent to a proxy server is responsible for initiating a session."
},
{
"code": null,
"e": 12112,
"s": 12022,
"text": "An INVITE request that is sent to a proxy server is responsible for initiating a session."
},
{
"code": null,
"e": 12242,
"s": 12112,
"text": "The proxy server sendsa 100 Trying response immediately to the caller (Alice) to stop the re-transmissions of the INVITE request."
},
{
"code": null,
"e": 12372,
"s": 12242,
"text": "The proxy server sendsa 100 Trying response immediately to the caller (Alice) to stop the re-transmissions of the INVITE request."
},
{
"code": null,
"e": 12508,
"s": 12372,
"text": "The proxy server searches the address of Bob in the location server. After getting the address, it forwards the INVITE request further."
},
{
"code": null,
"e": 12644,
"s": 12508,
"text": "The proxy server searches the address of Bob in the location server. After getting the address, it forwards the INVITE request further."
},
{
"code": null,
"e": 12736,
"s": 12644,
"text": "Thereafter, 180 Ringing (Provisional responses) generated by Bob is returned back to Alice."
},
{
"code": null,
"e": 12828,
"s": 12736,
"text": "Thereafter, 180 Ringing (Provisional responses) generated by Bob is returned back to Alice."
},
{
"code": null,
"e": 12894,
"s": 12828,
"text": "A 200 OK response is generated soon after Bob picks the phone up."
},
{
"code": null,
"e": 12960,
"s": 12894,
"text": "A 200 OK response is generated soon after Bob picks the phone up."
},
{
"code": null,
"e": 13017,
"s": 12960,
"text": "Bob receives an ACK from the Alice, once it gets 200 OK."
},
{
"code": null,
"e": 13074,
"s": 13017,
"text": "Bob receives an ACK from the Alice, once it gets 200 OK."
},
{
"code": null,
"e": 13183,
"s": 13074,
"text": "At the same time, the session gets established and RTP packets (conversations) start flowing from both ends."
},
{
"code": null,
"e": 13292,
"s": 13183,
"text": "At the same time, the session gets established and RTP packets (conversations) start flowing from both ends."
},
{
"code": null,
"e": 13396,
"s": 13292,
"text": "After the conversation, any participant (Alice or Bob) can send a BYE request to terminate the session."
},
{
"code": null,
"e": 13500,
"s": 13396,
"text": "After the conversation, any participant (Alice or Bob) can send a BYE request to terminate the session."
},
{
"code": null,
"e": 13567,
"s": 13500,
"text": "BYE reaches directly from Alice to Bob bypassing the proxy server."
},
{
"code": null,
"e": 13634,
"s": 13567,
"text": "BYE reaches directly from Alice to Bob bypassing the proxy server."
},
{
"code": null,
"e": 13721,
"s": 13634,
"text": "Finally, Bob sends a 200 OK response to confirm the BYE and the session is terminated."
},
{
"code": null,
"e": 13808,
"s": 13721,
"text": "Finally, Bob sends a 200 OK response to confirm the BYE and the session is terminated."
},
{
"code": null,
"e": 13892,
"s": 13808,
"text": "In the above basic call flow, three transactions are (marked as 1, 2, 3) available."
},
{
"code": null,
"e": 13976,
"s": 13892,
"text": "In the above basic call flow, three transactions are (marked as 1, 2, 3) available."
},
{
"code": null,
"e": 14040,
"s": 13976,
"text": "The complete call (from INVITE to 200 OK) is known as a Dialog."
},
{
"code": null,
"e": 14152,
"s": 14040,
"text": "How does a proxy help to connect one user with another? Let us find out with the help of the following diagram."
},
{
"code": null,
"e": 14252,
"s": 14152,
"text": "The topology shown in the diagram is known as a SIP trapezoid. The process takes place as follows −"
},
{
"code": null,
"e": 14454,
"s": 14252,
"text": "When a caller initiates a call, an INVITE message is sent to the proxy server. Upon receiving the INVITE, the proxy server attempts to resolve the address of the callee with the help of the DNS server."
},
{
"code": null,
"e": 14656,
"s": 14454,
"text": "When a caller initiates a call, an INVITE message is sent to the proxy server. Upon receiving the INVITE, the proxy server attempts to resolve the address of the callee with the help of the DNS server."
},
{
"code": null,
"e": 14876,
"s": 14656,
"text": "After getting the next route, caller’s proxy server (Proxy 1, also known as outbound proxy server) forwards the INVITE request to the callee’s proxy server which acts as an inbound proxy server (Proxy 2) for the callee."
},
{
"code": null,
"e": 15096,
"s": 14876,
"text": "After getting the next route, caller’s proxy server (Proxy 1, also known as outbound proxy server) forwards the INVITE request to the callee’s proxy server which acts as an inbound proxy server (Proxy 2) for the callee."
},
{
"code": null,
"e": 15223,
"s": 15096,
"text": "The inbound proxy server contacts the location server to get information about the callee’s address where the user registered."
},
{
"code": null,
"e": 15350,
"s": 15223,
"text": "The inbound proxy server contacts the location server to get information about the callee’s address where the user registered."
},
{
"code": null,
"e": 15443,
"s": 15350,
"text": "After getting information from the location server, it forwards the call to its destination."
},
{
"code": null,
"e": 15536,
"s": 15443,
"text": "After getting information from the location server, it forwards the call to its destination."
},
{
"code": null,
"e": 15645,
"s": 15536,
"text": "Once the user agents get to know their address, they can bypass the call, i.e., conversations pass directly."
},
{
"code": null,
"e": 15754,
"s": 15645,
"text": "Once the user agents get to know their address, they can bypass the call, i.e., conversations pass directly."
},
{
"code": null,
"e": 15810,
"s": 15754,
"text": "SIP messages are of two types − requests and responses."
},
{
"code": null,
"e": 15948,
"s": 15810,
"text": "The opening line of a request contains a method that defines the request, and a Request-URI that defines where the request is to be sent."
},
{
"code": null,
"e": 16086,
"s": 15948,
"text": "The opening line of a request contains a method that defines the request, and a Request-URI that defines where the request is to be sent."
},
{
"code": null,
"e": 16154,
"s": 16086,
"text": "Similarly, the opening line of a response contains a response code."
},
{
"code": null,
"e": 16222,
"s": 16154,
"text": "Similarly, the opening line of a response contains a response code."
},
{
"code": null,
"e": 16391,
"s": 16222,
"text": "SIP requests are the codes used to establish a communication. To complement them, there are SIP responses that generally indicate whether a request succeeded or failed."
},
{
"code": null,
"e": 16464,
"s": 16391,
"text": "These SIP requests which are known as METHODS make SIP message workable."
},
{
"code": null,
"e": 16587,
"s": 16464,
"text": "METHODS can be regarded as SIP requests, since they request a specific action to be taken by another user agent or server."
},
{
"code": null,
"e": 16710,
"s": 16587,
"text": "METHODS can be regarded as SIP requests, since they request a specific action to be taken by another user agent or server."
},
{
"code": null,
"e": 16787,
"s": 16710,
"text": "METHODS are distinguished into two types −\n\nCore Methods\nExtension Methods\n\n"
},
{
"code": null,
"e": 16830,
"s": 16787,
"text": "METHODS are distinguished into two types −"
},
{
"code": null,
"e": 16843,
"s": 16830,
"text": "Core Methods"
},
{
"code": null,
"e": 16856,
"s": 16843,
"text": "Core Methods"
},
{
"code": null,
"e": 16874,
"s": 16856,
"text": "Extension Methods"
},
{
"code": null,
"e": 16892,
"s": 16874,
"text": "Extension Methods"
},
{
"code": null,
"e": 16939,
"s": 16892,
"text": "There are six core methods as discussed below."
},
{
"code": null,
"e": 17090,
"s": 16939,
"text": "INVITE is used to initiate a session with a user agent. In other words, an INVITE method is used to establish a media session between the user agents."
},
{
"code": null,
"e": 17166,
"s": 17090,
"text": "INVITE can contain the media information of the caller in the message body."
},
{
"code": null,
"e": 17242,
"s": 17166,
"text": "INVITE can contain the media information of the caller in the message body."
},
{
"code": null,
"e": 17353,
"s": 17242,
"text": "A session is considered established if an INVITE has received a success response(2xx) or an ACK has been sent."
},
{
"code": null,
"e": 17464,
"s": 17353,
"text": "A session is considered established if an INVITE has received a success response(2xx) or an ACK has been sent."
},
{
"code": null,
"e": 17603,
"s": 17464,
"text": "A successful INVITE request establishes a dialog between the two user agents which continues until a BYE is sent to terminate the session."
},
{
"code": null,
"e": 17742,
"s": 17603,
"text": "A successful INVITE request establishes a dialog between the two user agents which continues until a BYE is sent to terminate the session."
},
{
"code": null,
"e": 17811,
"s": 17742,
"text": "An INVITE sent within an established dialog is known as a re-INVITE."
},
{
"code": null,
"e": 17880,
"s": 17811,
"text": "An INVITE sent within an established dialog is known as a re-INVITE."
},
{
"code": null,
"e": 17970,
"s": 17880,
"text": "Re-INVITE is used to change the session characteristics or refresh the state of a dialog."
},
{
"code": null,
"e": 18060,
"s": 17970,
"text": "Re-INVITE is used to change the session characteristics or refresh the state of a dialog."
},
{
"code": null,
"e": 18105,
"s": 18060,
"text": "The following code shows how INVITE is used."
},
{
"code": null,
"e": 18740,
"s": 18105,
"text": "INVITE sips:[email protected] SIP/2.0 \n Via: SIP/2.0/TLS client.ANC.com:5061;branch = z9hG4bK74bf9 \n Max-Forwards: 70 \n From: Alice<sips:[email protected]>;tag = 1234567 \n To: Bob<sips:[email protected]>\n Call-ID: [email protected] \n CSeq: 1 INVITE \n Contact: <sips:[email protected]> \n Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY \n Supported: replaces \n Content-Type: application/sdp \n Content-Length: ... \n \n v = 0 \n o = Alice 2890844526 2890844526 IN IP4 client.ANC.com \n s = Session SDP \n c = IN IP4 client.ANC.com \n t = 3034423619 0 \n m = audio 49170 RTP/AVP 0 \n a = rtpmap:0 PCMU/8000 \n"
},
{
"code": null,
"e": 18892,
"s": 18740,
"text": "BYE is the method used to terminate an established session. This is a SIP request that can be sent by either the caller or the callee to end a session."
},
{
"code": null,
"e": 18929,
"s": 18892,
"text": "It cannot be sent by a proxy server."
},
{
"code": null,
"e": 18966,
"s": 18929,
"text": "It cannot be sent by a proxy server."
},
{
"code": null,
"e": 19034,
"s": 18966,
"text": "BYE request normally routes end to end, bypassing the proxy server."
},
{
"code": null,
"e": 19102,
"s": 19034,
"text": "BYE request normally routes end to end, bypassing the proxy server."
},
{
"code": null,
"e": 19173,
"s": 19102,
"text": "BYE cannot be sent to a pending an INVITE or an unestablished session."
},
{
"code": null,
"e": 19244,
"s": 19173,
"text": "BYE cannot be sent to a pending an INVITE or an unestablished session."
},
{
"code": null,
"e": 19364,
"s": 19244,
"text": "REGISTER request performs the registration of a user agent. This request is sent by a user agent to a registrar server."
},
{
"code": null,
"e": 19482,
"s": 19364,
"text": "The REGISTER request may be forwarded or proxied until it reaches an authoritative registrar of the specified domain."
},
{
"code": null,
"e": 19600,
"s": 19482,
"text": "The REGISTER request may be forwarded or proxied until it reaches an authoritative registrar of the specified domain."
},
{
"code": null,
"e": 19694,
"s": 19600,
"text": "It carries the AOR (Address of Record) in the To header of the user that is being registered."
},
{
"code": null,
"e": 19788,
"s": 19694,
"text": "It carries the AOR (Address of Record) in the To header of the user that is being registered."
},
{
"code": null,
"e": 19841,
"s": 19788,
"text": "REGISTER request contains the time period (3600sec)."
},
{
"code": null,
"e": 19894,
"s": 19841,
"text": "REGISTER request contains the time period (3600sec)."
},
{
"code": null,
"e": 20142,
"s": 19894,
"text": "One user agent can send a REGISTER request on behalf of another user agent. This is known as third-party registration. Here, the From tag contains the URI of the party submitting the registration on behalf of the party identified in the To header."
},
{
"code": null,
"e": 20390,
"s": 20142,
"text": "One user agent can send a REGISTER request on behalf of another user agent. This is known as third-party registration. Here, the From tag contains the URI of the party submitting the registration on behalf of the party identified in the To header."
},
{
"code": null,
"e": 20535,
"s": 20390,
"text": "CANCEL is used to terminate a session which is not established. User agents use this request to cancel a pending call attempt initiated earlier."
},
{
"code": null,
"e": 20592,
"s": 20535,
"text": "It can be sent either by a user agent or a proxy server."
},
{
"code": null,
"e": 20649,
"s": 20592,
"text": "It can be sent either by a user agent or a proxy server."
},
{
"code": null,
"e": 20805,
"s": 20649,
"text": "CANCEL is a hop by hop request, i.e., it goes through the elements between the user agent and receives the response generated by the next stateful element."
},
{
"code": null,
"e": 20961,
"s": 20805,
"text": "CANCEL is a hop by hop request, i.e., it goes through the elements between the user agent and receives the response generated by the next stateful element."
},
{
"code": null,
"e": 21159,
"s": 20961,
"text": "ACK is used to acknowledge the final responses to an INVITE method. An ACK always goes in the direction of INVITE.ACK may contain SDP body (media characteristics), if it is not available in INVITE."
},
{
"code": null,
"e": 21261,
"s": 21159,
"text": "ACK may not be used to modify the media description that has already been sent in the initial INVITE."
},
{
"code": null,
"e": 21363,
"s": 21261,
"text": "ACK may not be used to modify the media description that has already been sent in the initial INVITE."
},
{
"code": null,
"e": 21498,
"s": 21363,
"text": "A stateful proxy receiving an ACK must determine whether or not the ACK should be forwarded downstream to another proxy or user agent."
},
{
"code": null,
"e": 21633,
"s": 21498,
"text": "A stateful proxy receiving an ACK must determine whether or not the ACK should be forwarded downstream to another proxy or user agent."
},
{
"code": null,
"e": 21771,
"s": 21633,
"text": "For 2xx responses, ACK is end to end, but for all other final responses, it works on hop by hop basis when stateful proxies are involved."
},
{
"code": null,
"e": 21909,
"s": 21771,
"text": "For 2xx responses, ACK is end to end, but for all other final responses, it works on hop by hop basis when stateful proxies are involved."
},
{
"code": null,
"e": 22156,
"s": 21909,
"text": "OPTIONS method is used to query a user agent or a proxy server about its capabilities and discover its current availability. The response to a request lists the capabilities of the user agent or server. A proxy never generates an OPTIONS request."
},
{
"code": null,
"e": 22283,
"s": 22156,
"text": "SUBSCRIBE is used by user agents to establish a subscription for the purpose of getting notification about a particular event."
},
{
"code": null,
"e": 22366,
"s": 22283,
"text": "It contains an Expires header field that indicates the duration of a subscription."
},
{
"code": null,
"e": 22449,
"s": 22366,
"text": "It contains an Expires header field that indicates the duration of a subscription."
},
{
"code": null,
"e": 22526,
"s": 22449,
"text": "After the time period passes, the subscription will automatically terminate."
},
{
"code": null,
"e": 22603,
"s": 22526,
"text": "After the time period passes, the subscription will automatically terminate."
},
{
"code": null,
"e": 22662,
"s": 22603,
"text": "Subscription establishes a dialog between the user agents."
},
{
"code": null,
"e": 22721,
"s": 22662,
"text": "Subscription establishes a dialog between the user agents."
},
{
"code": null,
"e": 22826,
"s": 22721,
"text": "You can re-subscription again by sending another SUBSCRIBE within the dialog before the expiration time."
},
{
"code": null,
"e": 22931,
"s": 22826,
"text": "You can re-subscription again by sending another SUBSCRIBE within the dialog before the expiration time."
},
{
"code": null,
"e": 22987,
"s": 22931,
"text": "A 200 OK will be received for a subscription from User."
},
{
"code": null,
"e": 23043,
"s": 22987,
"text": "A 200 OK will be received for a subscription from User."
},
{
"code": null,
"e": 23129,
"s": 23043,
"text": "Users can unsubscribe by sending another SUBSCRIBE method with Expires value 0(zero)."
},
{
"code": null,
"e": 23215,
"s": 23129,
"text": "Users can unsubscribe by sending another SUBSCRIBE method with Expires value 0(zero)."
},
{
"code": null,
"e": 23404,
"s": 23215,
"text": "NOTIFY is used by user agents to get the occurrence of a particular event. Usually a NOTIFY will trigger within a dialog when a subscription exists between the subscriber and the notifier."
},
{
"code": null,
"e": 23473,
"s": 23404,
"text": "Every NOTIFY will get 200 OK response if it is received by notifier."
},
{
"code": null,
"e": 23542,
"s": 23473,
"text": "Every NOTIFY will get 200 OK response if it is received by notifier."
},
{
"code": null,
"e": 23687,
"s": 23542,
"text": "NOTIFY contain an Event header field indicating the event and a subscriptionstate header field indicating the current state of the subscription."
},
{
"code": null,
"e": 23832,
"s": 23687,
"text": "NOTIFY contain an Event header field indicating the event and a subscriptionstate header field indicating the current state of the subscription."
},
{
"code": null,
"e": 23904,
"s": 23832,
"text": "A NOTIFY is always sent at the start and termination of a subscription."
},
{
"code": null,
"e": 23976,
"s": 23904,
"text": "A NOTIFY is always sent at the start and termination of a subscription."
},
{
"code": null,
"e": 24053,
"s": 23976,
"text": "PUBLISH is used by a user agent to send event state information to a server."
},
{
"code": null,
"e": 24132,
"s": 24053,
"text": "PUBLISH is mostly useful when there are multiple sources of event information."
},
{
"code": null,
"e": 24211,
"s": 24132,
"text": "PUBLISH is mostly useful when there are multiple sources of event information."
},
{
"code": null,
"e": 24293,
"s": 24211,
"text": "A PUBLISH request is similar to a NOTIFY, except that it is not sent in a dialog."
},
{
"code": null,
"e": 24375,
"s": 24293,
"text": "A PUBLISH request is similar to a NOTIFY, except that it is not sent in a dialog."
},
{
"code": null,
"e": 24462,
"s": 24375,
"text": "A PUBLISH request must contain an Expires header field and a Min-Expires header field."
},
{
"code": null,
"e": 24549,
"s": 24462,
"text": "A PUBLISH request must contain an Expires header field and a Min-Expires header field."
},
{
"code": null,
"e": 24639,
"s": 24549,
"text": "REFER is used by a user agent to refer another user agent to access a URI for the dialog."
},
{
"code": null,
"e": 24715,
"s": 24639,
"text": "REFER must contain a Refer-To header. This is a mandatory header for REFER."
},
{
"code": null,
"e": 24791,
"s": 24715,
"text": "REFER must contain a Refer-To header. This is a mandatory header for REFER."
},
{
"code": null,
"e": 24837,
"s": 24791,
"text": "REFER can be sent inside or outside a dialog."
},
{
"code": null,
"e": 24883,
"s": 24837,
"text": "REFER can be sent inside or outside a dialog."
},
{
"code": null,
"e": 24993,
"s": 24883,
"text": "A 202 Accepted will trigger a REFER request which indicates that other user agent has accepted the reference."
},
{
"code": null,
"e": 25103,
"s": 24993,
"text": "A 202 Accepted will trigger a REFER request which indicates that other user agent has accepted the reference."
},
{
"code": null,
"e": 25237,
"s": 25103,
"text": "INFO is used by a user agent to send call signalling information to another user agent with which it has established a media session."
},
{
"code": null,
"e": 25268,
"s": 25237,
"text": "This is an end-to-end request."
},
{
"code": null,
"e": 25299,
"s": 25268,
"text": "This is an end-to-end request."
},
{
"code": null,
"e": 25344,
"s": 25299,
"text": "A proxy will always forward an INFO request."
},
{
"code": null,
"e": 25389,
"s": 25344,
"text": "A proxy will always forward an INFO request."
},
{
"code": null,
"e": 25511,
"s": 25389,
"text": "UPDATE is used to modify the state of a session if a session is not established. User could change the codec with UPDATE."
},
{
"code": null,
"e": 25590,
"s": 25511,
"text": "IF a session is established, a re-Invite is used to change/update the session."
},
{
"code": null,
"e": 25685,
"s": 25590,
"text": "PRACK is used to acknowledge the receipt of a reliable transfer of provisional response (1XX)."
},
{
"code": null,
"e": 25840,
"s": 25685,
"text": "Generally PRACK is generated by a client when it receive a provisional response containing an RSeq reliable sequence number and a supported:100rel header."
},
{
"code": null,
"e": 25995,
"s": 25840,
"text": "Generally PRACK is generated by a client when it receive a provisional response containing an RSeq reliable sequence number and a supported:100rel header."
},
{
"code": null,
"e": 26050,
"s": 25995,
"text": "PRACK contains (RSeq + CSeq) value in the rack header."
},
{
"code": null,
"e": 26105,
"s": 26050,
"text": "PRACK contains (RSeq + CSeq) value in the rack header."
},
{
"code": null,
"e": 26228,
"s": 26105,
"text": "The PRACK method applies to all provisional responses except the 100 Trying response, which is never reliably transported."
},
{
"code": null,
"e": 26351,
"s": 26228,
"text": "The PRACK method applies to all provisional responses except the 100 Trying response, which is never reliably transported."
},
{
"code": null,
"e": 26429,
"s": 26351,
"text": "A PRACK may contain a message body; it may be used for offer/answer exchange."
},
{
"code": null,
"e": 26507,
"s": 26429,
"text": "A PRACK may contain a message body; it may be used for offer/answer exchange."
},
{
"code": null,
"e": 26666,
"s": 26507,
"text": "It is used to send an instant message using SIP. An IM usually consists of short messages exchanged in real time by participants engaged in text conversation."
},
{
"code": null,
"e": 26723,
"s": 26666,
"text": "MESSAGE can be sent within a dialog or outside a dialog."
},
{
"code": null,
"e": 26780,
"s": 26723,
"text": "MESSAGE can be sent within a dialog or outside a dialog."
},
{
"code": null,
"e": 26860,
"s": 26780,
"text": "The contents of a MESSAGE are carried in the message body as a MIME attachment."
},
{
"code": null,
"e": 26940,
"s": 26860,
"text": "The contents of a MESSAGE are carried in the message body as a MIME attachment."
},
{
"code": null,
"e": 27047,
"s": 26940,
"text": "A 200 OK response is normally received to indicate that the message has been delivered at its destination."
},
{
"code": null,
"e": 27154,
"s": 27047,
"text": "A 200 OK response is normally received to indicate that the message has been delivered at its destination."
},
{
"code": null,
"e": 27362,
"s": 27154,
"text": "A SIP response is a message generated by a user agent server (UAS) or SIP server to reply a request generated by a client. It could be a formal acknowledgement to prevent retransmission of requests by a UAC."
},
{
"code": null,
"e": 27440,
"s": 27362,
"text": "A response may contain some additional header fields of info needed by a UAC."
},
{
"code": null,
"e": 27518,
"s": 27440,
"text": "A response may contain some additional header fields of info needed by a UAC."
},
{
"code": null,
"e": 27541,
"s": 27518,
"text": "SIP has six responses."
},
{
"code": null,
"e": 27564,
"s": 27541,
"text": "SIP has six responses."
},
{
"code": null,
"e": 27633,
"s": 27564,
"text": "1xx to 5xx has been borrowed from HTTP and 6xx is introduced in SIP."
},
{
"code": null,
"e": 27702,
"s": 27633,
"text": "1xx to 5xx has been borrowed from HTTP and 6xx is introduced in SIP."
},
{
"code": null,
"e": 27780,
"s": 27702,
"text": "1xx is considered as a provisional response and the rest are final responses."
},
{
"code": null,
"e": 27858,
"s": 27780,
"text": "1xx is considered as a provisional response and the rest are final responses."
},
{
"code": null,
"e": 27977,
"s": 27858,
"text": "Informational responses are used to indicate call progress. Normally the responses are end to end (except 100 Trying)."
},
{
"code": null,
"e": 28059,
"s": 27977,
"text": "This class of responses is meant for indicating that a request has been accepted."
},
{
"code": null,
"e": 28192,
"s": 28059,
"text": "Generally these class responses are sent by redirect servers in response to INVITE. They are also known as redirect class responses."
},
{
"code": null,
"e": 28310,
"s": 28192,
"text": "Client error responses indicate that the request cannot be fulfilled as some errors are identified from the UAC side."
},
{
"code": null,
"e": 28424,
"s": 28310,
"text": "This class response is used to indicate that the request cannot be processed because of an error with the server."
},
{
"code": null,
"e": 28589,
"s": 28424,
"text": "This response class indicates that the server knows that the request will fail wherever it is tried. As a result, the request should not be sent to other locations."
},
{
"code": null,
"e": 28723,
"s": 28589,
"text": "A header is a component of a SIP message that conveys information about the message. It is structured as a sequence of header fields."
},
{
"code": null,
"e": 29077,
"s": 28723,
"text": "SIP header fields in most cases follow the same rules as HTTP header fields. Header fields are defined as Header: field, where Header is used to represent the header field name, and field is the set of tokens that contains the information. Each field consists of a fieldname followed by a colon (\":\") and the field-value (i.e., field-name: field-value)."
},
{
"code": null,
"e": 29232,
"s": 29077,
"text": "Many common SIP header fields have a compact form where the header field name is denoted by a single lower case character. Some examples are given below −"
},
{
"code": null,
"e": 29297,
"s": 29232,
"text": "The following image shows the structure of a typical SIP header."
},
{
"code": null,
"e": 29366,
"s": 29297,
"text": "Headers are categorized as follows depending on their usage in SIP −"
},
{
"code": null,
"e": 29387,
"s": 29366,
"text": "Request and Response"
},
{
"code": null,
"e": 29400,
"s": 29387,
"text": "Request Only"
},
{
"code": null,
"e": 29414,
"s": 29400,
"text": "Response Only"
},
{
"code": null,
"e": 29427,
"s": 29414,
"text": "Message Body"
},
{
"code": null,
"e": 29687,
"s": 29427,
"text": "SDP stands for Session Description Protocol. It is used to describe multimedia sessions in a format understood by the participants over a network. Depending on this description, a party decides whether to join a conference or when or how to join a conference."
},
{
"code": null,
"e": 30016,
"s": 29687,
"text": "The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session."
},
{
"code": null,
"e": 30345,
"s": 30016,
"text": "The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session."
},
{
"code": null,
"e": 30442,
"s": 30345,
"text": "SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP."
},
{
"code": null,
"e": 30539,
"s": 30442,
"text": "SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP."
},
{
"code": null,
"e": 30739,
"s": 30539,
"text": "SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing."
},
{
"code": null,
"e": 30939,
"s": 30739,
"text": "SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing."
},
{
"code": null,
"e": 31092,
"s": 30939,
"text": "The purpose of SDP is to convey information about media streams in multimedia sessions to help participants join or gather info of a particular session."
},
{
"code": null,
"e": 31139,
"s": 31092,
"text": "SDP is a short structured textual description."
},
{
"code": null,
"e": 31186,
"s": 31139,
"text": "SDP is a short structured textual description."
},
{
"code": null,
"e": 31305,
"s": 31186,
"text": "It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information."
},
{
"code": null,
"e": 31424,
"s": 31305,
"text": "It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information."
},
{
"code": null,
"e": 31570,
"s": 31424,
"text": "A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so."
},
{
"code": null,
"e": 31716,
"s": 31570,
"text": "A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so."
},
{
"code": null,
"e": 31886,
"s": 31716,
"text": "The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter."
},
{
"code": null,
"e": 32056,
"s": 31886,
"text": "The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter."
},
{
"code": null,
"e": 32136,
"s": 32056,
"text": "The general form of a SDP message is −\nx = parameter1 parameter2 ... parameterN"
},
{
"code": null,
"e": 32175,
"s": 32136,
"text": "The general form of a SDP message is −"
},
{
"code": null,
"e": 32216,
"s": 32175,
"text": "x = parameter1 parameter2 ... parameterN"
},
{
"code": null,
"e": 32440,
"s": 32216,
"text": "The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters."
},
{
"code": null,
"e": 32664,
"s": 32440,
"text": "The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters."
},
{
"code": null,
"e": 32705,
"s": 32664,
"text": "Session description (* denotes optional)"
},
{
"code": null,
"e": 32728,
"s": 32705,
"text": "v = (protocol version)"
},
{
"code": null,
"e": 32771,
"s": 32728,
"text": "o = (owner/creator and session identifier)"
},
{
"code": null,
"e": 32790,
"s": 32771,
"text": "s = (session name)"
},
{
"code": null,
"e": 32817,
"s": 32790,
"text": "i =* (session information)"
},
{
"code": null,
"e": 32843,
"s": 32817,
"text": "u =* (URI of description)"
},
{
"code": null,
"e": 32864,
"s": 32843,
"text": "e =* (email address)"
},
{
"code": null,
"e": 32884,
"s": 32864,
"text": "p =* (phone number)"
},
{
"code": null,
"e": 32954,
"s": 32884,
"text": "c =* (connection information - not required if included in all media)"
},
{
"code": null,
"e": 32983,
"s": 32954,
"text": "b =* (bandwidth information)"
},
{
"code": null,
"e": 33012,
"s": 32983,
"text": "z =* (time zone adjustments)"
},
{
"code": null,
"e": 33034,
"s": 33012,
"text": "k =* (encryption key)"
},
{
"code": null,
"e": 33078,
"s": 33034,
"text": "a =* (zero or more session attribute lines)"
},
{
"code": null,
"e": 33215,
"s": 33078,
"text": "The v= field contains the SDP version number. Because the current version of SDP is 0, a valid SDP message will always begin with v = 0."
},
{
"code": null,
"e": 33363,
"s": 33215,
"text": "The o= field contains information about the originator of the session and session identifiers. This field is used to uniquely identify the session."
},
{
"code": null,
"e": 33446,
"s": 33363,
"text": "The field contains −\no=<username><session-id><version><network-type><address-type>"
},
{
"code": null,
"e": 33467,
"s": 33446,
"text": "The field contains −"
},
{
"code": null,
"e": 33529,
"s": 33467,
"text": "o=<username><session-id><version><network-type><address-type>"
},
{
"code": null,
"e": 33593,
"s": 33529,
"text": "The username parameter contains the originator’s login or host."
},
{
"code": null,
"e": 33657,
"s": 33593,
"text": "The username parameter contains the originator’s login or host."
},
{
"code": null,
"e": 33771,
"s": 33657,
"text": "The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness."
},
{
"code": null,
"e": 33885,
"s": 33771,
"text": "The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness."
},
{
"code": null,
"e": 34006,
"s": 33885,
"text": "The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp."
},
{
"code": null,
"e": 34127,
"s": 34006,
"text": "The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp."
},
{
"code": null,
"e": 34306,
"s": 34127,
"text": "The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name."
},
{
"code": null,
"e": 34485,
"s": 34306,
"text": "The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name."
},
{
"code": null,
"e": 34683,
"s": 34485,
"text": "The s= field contains a name for the session. It can contain any nonzero number of characters. The optional i= field contains information about the session. It can contain any number of characters."
},
{
"code": null,
"e": 34789,
"s": 34683,
"text": "The optional u= field contains a uniform resource indicator (URI) with more information about the session"
},
{
"code": null,
"e": 34913,
"s": 34789,
"text": "The optional e= field contains an e-mail address of the host of the session. The optional p= field contains a phone number."
},
{
"code": null,
"e": 34975,
"s": 34913,
"text": "The c= field contains information about the media connection."
},
{
"code": null,
"e": 35048,
"s": 34975,
"text": "The field contains −\nc =<network-type><address-type><connection-address>"
},
{
"code": null,
"e": 35069,
"s": 35048,
"text": "The field contains −"
},
{
"code": null,
"e": 35121,
"s": 35069,
"text": "c =<network-type><address-type><connection-address>"
},
{
"code": null,
"e": 35183,
"s": 35121,
"text": "The network-type parameter is defined as IN for the Internet."
},
{
"code": null,
"e": 35245,
"s": 35183,
"text": "The network-type parameter is defined as IN for the Internet."
},
{
"code": null,
"e": 35327,
"s": 35245,
"text": "The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses."
},
{
"code": null,
"e": 35409,
"s": 35327,
"text": "The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses."
},
{
"code": null,
"e": 35542,
"s": 35409,
"text": "The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast."
},
{
"code": null,
"e": 35675,
"s": 35542,
"text": "The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast."
},
{
"code": null,
"e": 35795,
"s": 35675,
"text": "If multicast, the connection-address field contains −\nconnection-address=base-multicast-address/ttl/number-of-addresses"
},
{
"code": null,
"e": 35849,
"s": 35795,
"text": "If multicast, the connection-address field contains −"
},
{
"code": null,
"e": 35915,
"s": 35849,
"text": "connection-address=base-multicast-address/ttl/number-of-addresses"
},
{
"code": null,
"e": 36081,
"s": 35915,
"text": "where ttl is the time-to-live value, and number-of-addresses indicates how many contiguous multicast addresses are included starting with the base-multicast address."
},
{
"code": null,
"e": 36174,
"s": 36081,
"text": "The optional b= field contains information about the bandwidth required. It is of the form −"
},
{
"code": null,
"e": 36203,
"s": 36174,
"text": "b=modifier:bandwidth − value"
},
{
"code": null,
"e": 36270,
"s": 36203,
"text": "The t= field contains the start time and stop time of the session."
},
{
"code": null,
"e": 36293,
"s": 36270,
"text": "t=start-time stop-time"
},
{
"code": null,
"e": 36441,
"s": 36293,
"text": "The optional r= field contains information about the repeat times that can be specified in either in NTP or in days (d), hours (h), or minutes (m)."
},
{
"code": null,
"e": 36627,
"s": 36441,
"text": "The optional z= field contains information about the time zone offsets. This field is used if are occurring session spans a change from daylight savings to standard time, or vice versa."
},
{
"code": null,
"e": 36724,
"s": 36627,
"text": "The optional m= field contains information about the type of media session. The field contains −"
},
{
"code": null,
"e": 36760,
"s": 36724,
"text": "m= media port transport format-list"
},
{
"code": null,
"e": 36896,
"s": 36760,
"text": "The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number."
},
{
"code": null,
"e": 37032,
"s": 36896,
"text": "The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number."
},
{
"code": null,
"e": 37113,
"s": 37032,
"text": "The transport parameter contains the transport protocol or the RTP profile used."
},
{
"code": null,
"e": 37194,
"s": 37113,
"text": "The transport parameter contains the transport protocol or the RTP profile used."
},
{
"code": null,
"e": 37331,
"s": 37194,
"text": "The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles."
},
{
"code": null,
"e": 37468,
"s": 37331,
"text": "The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles."
},
{
"code": null,
"e": 37511,
"s": 37468,
"text": "Example:\nm = audio 49430 RTP/AVP 0 6 8 99\n"
},
{
"code": null,
"e": 37676,
"s": 37511,
"text": "One of these three codecs can be used for the audio media session. If the intention is to establish three audio channels, three separate media fields would be used."
},
{
"code": null,
"e": 38004,
"s": 37676,
"text": "The optional a= field contains attributes of the preceding media session. This field can be used to extend SDP to provide more information about the media. If not fully understood by a SDP user, the attribute field can be ignored. There can be one or more attribute fields for each media payload type listed in the media field."
},
{
"code": null,
"e": 38036,
"s": 38004,
"text": "Attributes in SDP can be either"
},
{
"code": null,
"e": 38054,
"s": 38036,
"text": "session level, or"
},
{
"code": null,
"e": 38067,
"s": 38054,
"text": "media level."
},
{
"code": null,
"e": 38232,
"s": 38067,
"text": "Session level means that the attribute is listed before the first media line in the SDP. If this is the case, the attribute applies to all the media lines below it."
},
{
"code": null,
"e": 38357,
"s": 38232,
"text": "Media level means it is listed after a media line. In this case, the attribute only applies to this particular media stream."
},
{
"code": null,
"e": 38642,
"s": 38357,
"text": "SDP can include both session level and media level attributes. If the same attribute appears as both, the media level attribute overrides the session level attribute for that particular media stream. Note that the connection data field can also be either session level or media level."
},
{
"code": null,
"e": 38711,
"s": 38642,
"text": "Given below is an example session description, taken from RFC 2327 −"
},
{
"code": null,
"e": 39088,
"s": 38711,
"text": "v = 0\no = mhandley2890844526 2890842807 IN IP4 126.16.64.4\ns = SDP Seminar\ni = A Seminar on the session description protocol\nu = http://www.cs.ucl.ac.uk/staff/M.Handley/sdp.03.ps\ne = [email protected](Mark Handley)\nc = IN IP4 224.2.17.12/127\nt = 2873397496 2873404696\na = recvonly\nm = audio 49170 RTP/AVP 0\nm = video 51372 RTP/AVP 31\nm = application 32416udp wb\na = orient:portrait\n"
},
{
"code": null,
"e": 39212,
"s": 39088,
"text": "The use of SDP with SIP is given in the SDP offer answer RFC 3264. The default message body type in SIP is application/sdp."
},
{
"code": null,
"e": 39342,
"s": 39212,
"text": "The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK."
},
{
"code": null,
"e": 39472,
"s": 39342,
"text": "The calling party lists the media capabilities that they are willing to receive in SDP, usually in either an INVITE or in an ACK."
},
{
"code": null,
"e": 39558,
"s": 39472,
"text": "The called party lists their media capabilities in the 200 OK response to the INVITE."
},
{
"code": null,
"e": 39644,
"s": 39558,
"text": "The called party lists their media capabilities in the 200 OK response to the INVITE."
},
{
"code": null,
"e": 39781,
"s": 39644,
"text": "A typical SIP use of SDP includes the following fields: version, origin, subject, time, connection, and one or more media and attribute."
},
{
"code": null,
"e": 39865,
"s": 39781,
"text": "The subject and time fields are not used by SIP but are included for compatibility."
},
{
"code": null,
"e": 39949,
"s": 39865,
"text": "The subject and time fields are not used by SIP but are included for compatibility."
},
{
"code": null,
"e": 40093,
"s": 39949,
"text": "In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject."
},
{
"code": null,
"e": 40237,
"s": 40093,
"text": "In the SDP standard, the subject field is a required field and must contain at least one character, suggested to be s=- if there is no subject."
},
{
"code": null,
"e": 40363,
"s": 40237,
"text": "The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs."
},
{
"code": null,
"e": 40489,
"s": 40363,
"text": "The time field is usually set to t = 00. SIP uses the connection, media, and attribute fields to set up sessions between UAs."
},
{
"code": null,
"e": 40532,
"s": 40489,
"text": "The origin field has limited use with SIP."
},
{
"code": null,
"e": 40575,
"s": 40532,
"text": "The origin field has limited use with SIP."
},
{
"code": null,
"e": 40641,
"s": 40575,
"text": "The session-id is usually kept constant throughout a SIP session."
},
{
"code": null,
"e": 40707,
"s": 40641,
"text": "The session-id is usually kept constant throughout a SIP session."
},
{
"code": null,
"e": 40856,
"s": 40707,
"text": "The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same."
},
{
"code": null,
"e": 41005,
"s": 40856,
"text": "The version is incremented each time the SDP is changed. If the SDP being sent is unchanged from that sent previously, the version is kept the same."
},
{
"code": null,
"e": 41211,
"s": 41005,
"text": "As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types."
},
{
"code": null,
"e": 41417,
"s": 41211,
"text": "As the type of media session and codec to be used are part of the connection negotiation, SIP can use SDP to specify multiple alternative media types and to selectively accept or decline those media types."
},
{
"code": null,
"e": 41658,
"s": 41417,
"text": "The offer/answer specification, RFC 3264, recommends that an attribute containing a = rtpmap: be used for each media field. A media stream is declined by setting the port number to zero for the corresponding media field in the SDP response."
},
{
"code": null,
"e": 41833,
"s": 41658,
"text": "In the following example, the caller Tesla wants to set up an audio and video call with two possible audio codecs and a video codec in the SDP carried in the initial INVITE −"
},
{
"code": null,
"e": 42071,
"s": 41833,
"text": "v = 0 \no = John 0844526 2890844526 IN IP4 172.22.1.102 \ns = - \nc = IN IP4 172.22.1.102 \nt = 0 0 \nm = audio 6000 RTP/AVP 97 98 \na = rtpmap:97 AMR/16000/1 \na = rtpmap:98 AMR-WB/8000/1 \nm = video 49172 RTP/AVP 32 \na = rtpmap:32 MPV/90000 \n"
},
{
"code": null,
"e": 42136,
"s": 42071,
"text": "The codecs are referenced by the RTP/AVP profile numbers 97, 98."
},
{
"code": null,
"e": 42292,
"s": 42136,
"text": "The called party Marry answers the call, chooses the second codec for the first media field, and declines the second media field, only wanting AMR session."
},
{
"code": null,
"e": 42473,
"s": 42292,
"text": "v = 0 \no = Marry 2890844526 2890844526 IN IP4 172.22.1.110 \ns = - \nc = IN IP4 200.201.202.203 \nt = 0 0 \nm = audio 60000 RTP/AVP 8 \na = rtpmap:97 AMR/16000 \nm = video 0 RTP/AVP 32 \n"
},
{
"code": null,
"e": 42651,
"s": 42473,
"text": "If this audio-only call is not acceptable, then Tom would send an ACK then a BYE to cancel the call. Otherwise, the audio session would be established and RTP packets exchanged."
},
{
"code": null,
"e": 42859,
"s": 42651,
"text": "As this example illustrates, unless the number and order of media fields is maintained, the calling party would not know for certain which media sessions were being accepted and declined by the called party."
},
{
"code": null,
"e": 42924,
"s": 42859,
"text": "The offer/answer rules are summarized in the following sections."
},
{
"code": null,
"e": 43048,
"s": 42924,
"text": "An SDP offer must include all required SDP fields (this includes v=, o=, s=, c=,and t=). These are mandatory fields in SDP."
},
{
"code": null,
"e": 43398,
"s": 43048,
"text": "It usually includes a media field (m=) but it does not have to. The media lines contain all codecs listed in preference order. The only exception to this is if the endpoint supports a huge number of codecs, the most likely to be accepted or most preferred should be listed. Different media types include audio, video, text, MSRP, BFCP, and so forth."
},
{
"code": null,
"e": 43479,
"s": 43398,
"text": "An SDP answer to an offer must be constructed according to the following rules −"
},
{
"code": null,
"e": 43561,
"s": 43479,
"text": "The answer must have the same number of m= lines in the same order as the answer."
},
{
"code": null,
"e": 43643,
"s": 43561,
"text": "The answer must have the same number of m= lines in the same order as the answer."
},
{
"code": null,
"e": 43717,
"s": 43643,
"text": "Individual media streams can be declined by setting the port number to 0."
},
{
"code": null,
"e": 43791,
"s": 43717,
"text": "Individual media streams can be declined by setting the port number to 0."
},
{
"code": null,
"e": 43846,
"s": 43791,
"text": "Streams are accepted by sending a nonzero port number."
},
{
"code": null,
"e": 43901,
"s": 43846,
"text": "Streams are accepted by sending a nonzero port number."
},
{
"code": null,
"e": 43995,
"s": 43901,
"text": "The listed payloads for each media type must be a subset of the payloads listed in the offer."
},
{
"code": null,
"e": 44089,
"s": 43995,
"text": "The listed payloads for each media type must be a subset of the payloads listed in the offer."
},
{
"code": null,
"e": 44231,
"s": 44089,
"text": "For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected."
},
{
"code": null,
"e": 44373,
"s": 44231,
"text": "For dynamic payloads, the same dynamic payload number does not need to be used in each direction. Usually, only a single payload is selected."
},
{
"code": null,
"e": 44517,
"s": 44373,
"text": "Either party can initiate another offer/answer exchange to modify a session. When a session is modified, the following rules must be followed −"
},
{
"code": null,
"e": 44746,
"s": 44517,
"text": "The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed."
},
{
"code": null,
"e": 44975,
"s": 44746,
"text": "The origin (o=) line version number must either be the same as the last one sent, which indicates that this SDP is identical to the previous exchange, or it may be incremented by one, which indicates new SDP that must be parsed."
},
{
"code": null,
"e": 45064,
"s": 44975,
"text": "The offer must include all existing media lines and they must be sent in the same order."
},
{
"code": null,
"e": 45153,
"s": 45064,
"text": "The offer must include all existing media lines and they must be sent in the same order."
},
{
"code": null,
"e": 45223,
"s": 45153,
"text": "Additional media streams can be added to the end of the m= line list."
},
{
"code": null,
"e": 45293,
"s": 45223,
"text": "Additional media streams can be added to the end of the m= line list."
},
{
"code": null,
"e": 45461,
"s": 45293,
"text": "An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session."
},
{
"code": null,
"e": 45629,
"s": 45461,
"text": "An existing media stream can be deleted by setting the port number to 0. This media line must remain in the SDP and all future offer/answer exchanges for this session."
},
{
"code": null,
"e": 45818,
"s": 45629,
"text": "One party in a call can temporarily place the other on hold. This is done by sending an INVITE with an identical SDP to that of the original INVITE but with a = sendonly attribute present."
},
{
"code": null,
"e": 45978,
"s": 45818,
"text": "The call is made active again by sending another INVITE with the a = sendrecv attribute present. The following illustration shows the call flow of a call hold."
},
{
"code": null,
"e": 46272,
"s": 45978,
"text": "Personal mobility is the ability to have a constant identifier across a number of devices. SIP supports basic personal mobility using the REGISTER method, which allows a mobile device to change its IP address and point of connection to the Internet and still be able to receive incoming calls."
},
{
"code": null,
"e": 46372,
"s": 46272,
"text": "SIP can also support service mobility – the ability of a user to keep the same services when mobile"
},
{
"code": null,
"e": 46574,
"s": 46372,
"text": "A device binds its Contact URI with the address of record by a simple sip registration. According to the device IP address, registration authorizes this information automatically update in sip network."
},
{
"code": null,
"e": 46729,
"s": 46574,
"text": "During handover, the User agent routes between different operators, where it has to register again with a Contact as an AOR with another service provider."
},
{
"code": null,
"e": 46915,
"s": 46729,
"text": "For example, let’s take the example of the following call flow. UA which has temporarily received a new SIP URI with a new service provider. The UA then performs a double registration −"
},
{
"code": null,
"e": 47055,
"s": 46915,
"text": "The first registration is with the new service operator, which binds the Contact URI of the device with the new service provider’s AOR URI."
},
{
"code": null,
"e": 47195,
"s": 47055,
"text": "The first registration is with the new service operator, which binds the Contact URI of the device with the new service provider’s AOR URI."
},
{
"code": null,
"e": 47335,
"s": 47195,
"text": "The second REGISTER request is routed back to the original service provider and provides the new service provider’s AOR as the Contact URI."
},
{
"code": null,
"e": 47475,
"s": 47335,
"text": "The second REGISTER request is routed back to the original service provider and provides the new service provider’s AOR as the Contact URI."
},
{
"code": null,
"e": 47667,
"s": 47475,
"text": "As shown later in the call flow, when a request comes in to the original service provider’s network, the INVITE is redirected to the new service provider who then routes the call to the user."
},
{
"code": null,
"e": 47744,
"s": 47667,
"text": "For the first registration, the message containing the device URI would be −"
},
{
"code": null,
"e": 48101,
"s": 47744,
"text": "REGISTER sip:visited.registrar1.com SIP/2.0 \nVia: SIP/2.0/UDP 172.22.1.102:5060;branch = z9hG4bK97a7ea349ce0fca \nMax-Forwards: 70 \nTo: Tom <sip:[email protected]> \nFrom: Tom <sip:[email protected]>;tag = 72d65a24 \nCall-ID: [email protected] \nCSeq: 1 REGISTER \nContact: <sip:[email protected]:5060> \nExpires: 600000 \nContent-Length: 0\n"
},
{
"code": null,
"e": 48165,
"s": 48101,
"text": "The second registration message with the roaming URI would be −"
},
{
"code": null,
"e": 48468,
"s": 48165,
"text": "REGISTER sip:home.registrar2.in SIP/2.0 \nVia: SIP/2.0/UDP 172.22.1.102:5060;branch = z9hG4bKah4vn2u \nMax-Forwards: 70 \nTo: Tom <sip:[email protected]> \nFrom: Tom <sip:[email protected]>;tag = 45375 \nCall-ID:[email protected] \nCSeq: 6421 REGISTER \nContact: <sip:[email protected]> \nContent-Length: 0\n"
},
{
"code": null,
"e": 48790,
"s": 48468,
"text": "The first INVITE that is represents in the above figure would be sent to sip:registrar2.in; the second INVITE would be sent to sip: sip:[email protected], which would be forwarded to sip:[email protected]. It reaches Tom and allows the session to be established. Periodically both registrations would need to be refreshed."
},
{
"code": null,
"e": 49031,
"s": 48790,
"text": "User Agent may change its IP address during the session as it swaps from one network to another. Basic SIP supports this scenario, as a re-INVITE in a dialog can be used to update the Contact URI and change the media information in the SDP."
},
{
"code": null,
"e": 49091,
"s": 49031,
"text": "Take a look at the call flow mentioned in the figure below."
},
{
"code": null,
"e": 49124,
"s": 49091,
"text": "Here, Tom detects a new network,"
},
{
"code": null,
"e": 49157,
"s": 49124,
"text": "Here, Tom detects a new network,"
},
{
"code": null,
"e": 49200,
"s": 49157,
"text": "Uses DHCP to acquire a new IP address, and"
},
{
"code": null,
"e": 49243,
"s": 49200,
"text": "Uses DHCP to acquire a new IP address, and"
},
{
"code": null,
"e": 49326,
"s": 49243,
"text": "Performs a re-INVITE to allow the signalling and media flow to the new IP address."
},
{
"code": null,
"e": 49409,
"s": 49326,
"text": "Performs a re-INVITE to allow the signalling and media flow to the new IP address."
},
{
"code": null,
"e": 49595,
"s": 49409,
"text": "If the UA can receive media from both networks, the interruption is negligible. If this is not the case, a few media packets may be lost, resulting in a slight interruption to the call."
},
{
"code": null,
"e": 49635,
"s": 49595,
"text": "The re-INVITE would appear as follows −"
},
{
"code": null,
"e": 50281,
"s": 49635,
"text": "INVITE sip:[email protected] SIP/2.0 \nVia: SIP/2.0/UDP 172.22.1.102:5060;branch = z9hG4bK918f5a84fe6bf7a \nMax-Forwards: 70 \n\nTo: <sip:[email protected]> \n\nFrom: sip:[email protected];tag = 70133df4 \nCall-ID: 76d4861c19c \nCSeq: 1 INVITE \nAccept: application/sdp \nAccept-Language: en \n\nAllow: INVITE,ACK,CANCEL,BYE,INFO,OPTIONS,REFER,NOTIFY,SUBSCRIBE \nContact: <sip:172.22.1.102:5060>; \nContent-Type: application/sdp \nContent-Length: 168 \n\nv = 0\no = PPT 40467 40468 IN IP4 192.168.2.1 \ns = - \nc = IN IP4 192.168.2.1 \nb = AS:49 \nt = 0 0 \nb = RR:0 \nb = RS:0 \na = rtpmap:97 AMR/8000/1 \nm = audio 6000 RTP/AVP 96 \na = fmtp:102 0-15 \na = ptime:20 \na = maxptime:240\n"
},
{
"code": null,
"e": 50394,
"s": 50281,
"text": "The re-INVITE contains Bowditch’s new IP address in the Via and Contact header fields and SDP media information."
},
{
"code": null,
"e": 50552,
"s": 50394,
"text": "In midcall mobility, the actual route set (set of SIP proxies that the SIP messages must traverse) must change. We cannot use a re-INVITE in midcall mobility"
},
{
"code": null,
"e": 50771,
"s": 50552,
"text": "For example, if a proxy is necessary for NAT traversal, then Contact URI must be changed — a new dialog must be created. Hence, it has to send a new INVITE with a Replaces header, which identifies the existing session."
},
{
"code": null,
"e": 51026,
"s": 50771,
"text": "Note − Suppose A & B both are in a call and if A gets another INVITE (let’s say from C) with a replace header (should match existing dialog), then A must accept the INVITE and terminate the session with B and transfer all resource to newly formed dialog."
},
{
"code": null,
"e": 51255,
"s": 51026,
"text": "The call flow is shown in the following Figure. It is similar to the previous call flow using re-INVITE except that a BYE is automatically generated to terminate the existing dialog when the INVITE with the Replaces is accepted."
},
{
"code": null,
"e": 51309,
"s": 51255,
"text": "Given below are the points to note in this scenario −"
},
{
"code": null,
"e": 51390,
"s": 51309,
"text": "The existing dialog between Tom and Jerry includes the old visited proxy server."
},
{
"code": null,
"e": 51471,
"s": 51390,
"text": "The existing dialog between Tom and Jerry includes the old visited proxy server."
},
{
"code": null,
"e": 51573,
"s": 51471,
"text": "The new dialog using the new wireless network requires the inclusion of the new visited proxy server."
},
{
"code": null,
"e": 51675,
"s": 51573,
"text": "The new dialog using the new wireless network requires the inclusion of the new visited proxy server."
},
{
"code": null,
"e": 51836,
"s": 51675,
"text": "As a result, an INVITE with Replaces is sent by Tom, which creates a new dialog that includes the new visited proxy server but not the old visited proxy server."
},
{
"code": null,
"e": 51997,
"s": 51836,
"text": "As a result, an INVITE with Replaces is sent by Tom, which creates a new dialog that includes the new visited proxy server but not the old visited proxy server."
},
{
"code": null,
"e": 52180,
"s": 51997,
"text": "When Jerry accepts the INVITE, a BYE is automatically sent to terminate the old dialog that routes through the old visited proxy server that is now no longer involved in the session."
},
{
"code": null,
"e": 52363,
"s": 52180,
"text": "When Jerry accepts the INVITE, a BYE is automatically sent to terminate the old dialog that routes through the old visited proxy server that is now no longer involved in the session."
},
{
"code": null,
"e": 52461,
"s": 52363,
"text": "The resulting media session is established using Tom’s new IP address from the SDP in the INVITE."
},
{
"code": null,
"e": 52559,
"s": 52461,
"text": "The resulting media session is established using Tom’s new IP address from the SDP in the INVITE."
},
{
"code": null,
"e": 52772,
"s": 52559,
"text": "Services in SIP can be provided in either proxies or in UAs. Providing service mobility along with personal mobility can be challenging unless the user’s devices are identically configured with the same services."
},
{
"code": null,
"e": 53124,
"s": 52772,
"text": "SIP can easily support service mobility over the Internet. When connected to Internet, a UA configured to use a set of proxies in India can still use those proxies when roaming in Europe. It does not have any impact on the quality of the media session as the media always flows directly between the two UAs and does not traverse the SIP proxy servers."
},
{
"code": null,
"e": 53449,
"s": 53124,
"text": "Endpoint resident services are available only when the endpoint is connected to the Internet. A terminating service such as a call forwarding service implemented in an endpoint will fail if the endpoint has temporarily lost its Internet connection. Hence some services are implemented in the network using SIP proxy servers."
},
{
"code": null,
"e": 53622,
"s": 53449,
"text": "Sometime a proxy server forwards a single SIP call to multiple SIP endpoints. This process is known as forking. Here a single call can ring many endpoints at the same time."
},
{
"code": null,
"e": 53797,
"s": 53622,
"text": "With SIP forking, you can have your desk phone ring at the same time as your softphone or a SIP phone on your mobile, allowing you to take the call from either device easily."
},
{
"code": null,
"e": 53931,
"s": 53797,
"text": "Generally, in an office, suppose boss unable to pick the call or away, SIP forking allow the secretary to answer calls his extension."
},
{
"code": null,
"e": 54060,
"s": 53931,
"text": "Forking will be possible if there is a stateful proxy available as it needs to perform and response out of the many it receives."
},
{
"code": null,
"e": 54091,
"s": 54060,
"text": "We have two types of forking −"
},
{
"code": null,
"e": 54108,
"s": 54091,
"text": "Parallel Forking"
},
{
"code": null,
"e": 54127,
"s": 54108,
"text": "Sequential Forking"
},
{
"code": null,
"e": 54471,
"s": 54127,
"text": "In this scenario, the proxy server will fork the INVITE to, say, two devices (UA2, UA3) at a time. Both the devices will generate 180 Ringing and whoever receives the call will generate a 200 OK. The response (suppose UA2) that reaches the Originator first will establish a session with UA2. For the other response, a CANCEL will be triggered."
},
{
"code": null,
"e": 54586,
"s": 54471,
"text": "If the originator receives both the responses simultaneously, then based on q-value, it will forward the response."
},
{
"code": null,
"e": 54760,
"s": 54586,
"text": "In this scenario, the proxy server will fork the INVITE to one device (UA2). If UA2 is unavailable or busy at that time, then the proxy will fork it to another device (UA3)."
},
{
"code": null,
"e": 54954,
"s": 54760,
"text": "Branch IDs help proxies to match responses to forked requests. Without Branch IDs, a proxy server would not be able to understand the forked response. Branch-id will be available in Via header."
},
{
"code": null,
"e": 55137,
"s": 54954,
"text": "Tags are used by the UAC to distinguish multiple final responses from different UAS. A UAS cannot resolve whether the request has been forked or not. Therefore, it need to add a tag."
},
{
"code": null,
"e": 55261,
"s": 55137,
"text": "Proxies also can add tags if it generates a final response, they never insert tags into requests or responses they forward."
},
{
"code": null,
"e": 55435,
"s": 55261,
"text": "It may be possible that a single request can be forked by multiple proxy servers also. So the proxy which would fork shall add its own unique IDs to the branches it created."
},
{
"code": null,
"e": 55636,
"s": 55435,
"text": "A call leg refers to one to one signalling relationship between two user agents. The call ID is a unique identifier carried in SIP message that refers to the call. A call is a collection of call legs."
},
{
"code": null,
"e": 55801,
"s": 55636,
"text": "A UAC starts by sending an INVITE. Due to forking, it may receive multiple 200 OK from different UAs. Each corresponds to a different call leg within the same call."
},
{
"code": null,
"e": 55894,
"s": 55801,
"text": "A call is thus a group of call legs. A call leg refers to end-to-end connection between UAs."
},
{
"code": null,
"e": 56047,
"s": 55894,
"text": "The CSeq spaces in the two directions of a call leg are independent. Within a single direction, the sequence number is incremented for each transaction."
},
{
"code": null,
"e": 56288,
"s": 56047,
"text": "Voicemail is very common now-a-days for enterprise users. It’s a telephone application. It comes to picture when the called party is unavailable or unable to receive the call, the PBX will announce to calling party to leave a voice message."
},
{
"code": null,
"e": 56620,
"s": 56288,
"text": "User agent will either get a 3xx response or redirect to voicemail server if the called party’s number is unreachable. However, some kind of SIP extension is needed to indicate to the voicemail system which mailbox to use—that is, which greeting to play and where to store the recorded message. There are two ways to achieve this −"
},
{
"code": null,
"e": 56658,
"s": 56620,
"text": "By using a SIP header field extension"
},
{
"code": null,
"e": 56696,
"s": 56658,
"text": "By using a SIP header field extension"
},
{
"code": null,
"e": 56748,
"s": 56696,
"text": "By using the Request-URI to signal this information"
},
{
"code": null,
"e": 56800,
"s": 56748,
"text": "By using the Request-URI to signal this information"
},
{
"code": null,
"e": 57030,
"s": 56800,
"text": "Suppose for the user sip:[email protected] has a voicemail system at sip:voicemail.tutorialspoint.com which is providing voicemail, the Request-URI of the INVITE when it is forwarded to the voicemail server could look like −"
},
{
"code": null,
"e": 57112,
"s": 57030,
"text": "sip:voicemail.tutorialspoint.com;target = sip:[email protected];cause = 486\n"
},
{
"code": null,
"e": 57223,
"s": 57112,
"text": "The following illustration shows how the Request-URI carries the mailbox identifier and the reason (here 486)."
},
{
"code": null,
"e": 57365,
"s": 57223,
"text": "As we know, a proxy server can be either stateless or stateful. Here, in this chapter, we will discuss more on proxy servers and SIP routing."
},
{
"code": null,
"e": 57510,
"s": 57365,
"text": "A stateless proxy server simply forwards the message it receives. This kind of server does not store any information of the call or transaction."
},
{
"code": null,
"e": 57585,
"s": 57510,
"text": "Stateless proxies forget about the SIP request once it has been forwarded."
},
{
"code": null,
"e": 57633,
"s": 57585,
"text": "Transaction will be fast via stateless proxies."
},
{
"code": null,
"e": 57860,
"s": 57633,
"text": "A stateful proxy server keeps track of every request and response that it receives. It can use the stored information in future, if required. It can retransmit the request if it does not receive a response from the other side."
},
{
"code": null,
"e": 58068,
"s": 57860,
"text": "Stateful proxies remember the request after it has been forwarded, so they can use it for advance routing. Stateful proxies maintain transaction state. Transaction implies transaction state, not call state."
},
{
"code": null,
"e": 58276,
"s": 58068,
"text": "Stateful proxies remember the request after it has been forwarded, so they can use it for advance routing. Stateful proxies maintain transaction state. Transaction implies transaction state, not call state."
},
{
"code": null,
"e": 58339,
"s": 58276,
"text": "Transaction is not as fast with stateful proxies as stateless."
},
{
"code": null,
"e": 58402,
"s": 58339,
"text": "Transaction is not as fast with stateful proxies as stateless."
},
{
"code": null,
"e": 58495,
"s": 58402,
"text": "Stateful proxies can fork and retransmit if required.(e.g.: call forward busy, for example)."
},
{
"code": null,
"e": 58588,
"s": 58495,
"text": "Stateful proxies can fork and retransmit if required.(e.g.: call forward busy, for example)."
},
{
"code": null,
"e": 58788,
"s": 58588,
"text": "The Record-Route header is inserted into requests by proxies that wanted to be in the path of subsequent requests for the same call-id. It is then used by the user agent to route subsequent requests."
},
{
"code": null,
"e": 58977,
"s": 58788,
"text": "Via headers are inserted by servers into requests to detect loops and to help responses to find their way back to the client. This is helpful for only responses to reach their destination."
},
{
"code": null,
"e": 59068,
"s": 58977,
"text": "A UA himself generate and add its own address in a Via header field while sending request."
},
{
"code": null,
"e": 59159,
"s": 59068,
"text": "A UA himself generate and add its own address in a Via header field while sending request."
},
{
"code": null,
"e": 59286,
"s": 59159,
"text": "A proxy forwarding the request adds a Via header field containing its own address to the top of the list of Via header fields."
},
{
"code": null,
"e": 59413,
"s": 59286,
"text": "A proxy forwarding the request adds a Via header field containing its own address to the top of the list of Via header fields."
},
{
"code": null,
"e": 59618,
"s": 59413,
"text": "A proxy or UA generating a response to a request copies all the Via header fields from the request in order into the response, then sends the response to the address specified in the top Via header field."
},
{
"code": null,
"e": 59823,
"s": 59618,
"text": "A proxy or UA generating a response to a request copies all the Via header fields from the request in order into the response, then sends the response to the address specified in the top Via header field."
},
{
"code": null,
"e": 59968,
"s": 59823,
"text": "A proxy receiving a response checks the top Via header field and matches its own address. If it does not match, the response has been discarded."
},
{
"code": null,
"e": 60113,
"s": 59968,
"text": "A proxy receiving a response checks the top Via header field and matches its own address. If it does not match, the response has been discarded."
},
{
"code": null,
"e": 60237,
"s": 60113,
"text": "The top Via header field is then removed, and the response forwarded to the address specified in the next Via header field."
},
{
"code": null,
"e": 60361,
"s": 60237,
"text": "The top Via header field is then removed, and the response forwarded to the address specified in the next Via header field."
},
{
"code": null,
"e": 60535,
"s": 60361,
"text": "Via header fields contain protocolname, versionnumber, and transport (SIP/2.0/UDP, SIP/2.0/TCP, etc.) and contain portnumbers and parameters such as received, rport, branch."
},
{
"code": null,
"e": 60693,
"s": 60535,
"text": "A received tag is added to a Via header field if a UA or proxy receives the request from a different address than that specified in the top Via header field."
},
{
"code": null,
"e": 60851,
"s": 60693,
"text": "A received tag is added to a Via header field if a UA or proxy receives the request from a different address than that specified in the top Via header field."
},
{
"code": null,
"e": 61021,
"s": 60851,
"text": "A branch parameter is added to Via header fields by UAs and proxies, which is computed as a hash function of the Request-URI, and the To, From, Call-ID, and CSeq number."
},
{
"code": null,
"e": 61191,
"s": 61021,
"text": "A branch parameter is added to Via header fields by UAs and proxies, which is computed as a hash function of the Request-URI, and the To, From, Call-ID, and CSeq number."
},
{
"code": null,
"e": 61374,
"s": 61191,
"text": "SIP (Softphone) and PSTN (Old telephone) both are different networks and speaks different languages. So we need a translator (Gateway here) to communicate between these two networks."
},
{
"code": null,
"e": 61477,
"s": 61374,
"text": "Let us take an example to show how a SIP phone places a telephone call to a PSTN through PSTN gateway."
},
{
"code": null,
"e": 61597,
"s": 61477,
"text": "In this example, Tom (sip:[email protected]) is a sip phone and Jerry uses a global telephone number +91401234567."
},
{
"code": null,
"e": 61677,
"s": 61597,
"text": "The following illustration shows a call flow from SIP to PSTN through gateways."
},
{
"code": null,
"e": 61802,
"s": 61677,
"text": "Given below is a step-by-step explanation of all the process that takes place while placing a call from a SIP phone to PSTN."
},
{
"code": null,
"e": 62001,
"s": 61802,
"text": "First of all, (Tom)SIP phone dials the global number +91401234567 to reach Jerry. SIP user agent understands it as a global number and converts it into request-uri using DNS and trigger the request."
},
{
"code": null,
"e": 62200,
"s": 62001,
"text": "First of all, (Tom)SIP phone dials the global number +91401234567 to reach Jerry. SIP user agent understands it as a global number and converts it into request-uri using DNS and trigger the request."
},
{
"code": null,
"e": 62252,
"s": 62200,
"text": "The SIP phone sends the INVITE directly to gateway."
},
{
"code": null,
"e": 62304,
"s": 62252,
"text": "The SIP phone sends the INVITE directly to gateway."
},
{
"code": null,
"e": 62422,
"s": 62304,
"text": "The gateway initiates the call into the PSTN by selecting an SS7 ISUP trunk to the next telephone switch in the PSTN."
},
{
"code": null,
"e": 62540,
"s": 62422,
"text": "The gateway initiates the call into the PSTN by selecting an SS7 ISUP trunk to the next telephone switch in the PSTN."
},
{
"code": null,
"e": 62715,
"s": 62540,
"text": "The dialled digits from the INVITE are mapped into the ISUP IAM. The ISUP address complete message (ACM) is sent back by the PSTN to indicate that the trunk has been created."
},
{
"code": null,
"e": 62890,
"s": 62715,
"text": "The dialled digits from the INVITE are mapped into the ISUP IAM. The ISUP address complete message (ACM) is sent back by the PSTN to indicate that the trunk has been created."
},
{
"code": null,
"e": 63121,
"s": 62890,
"text": "The telephone generates ringtone and it goes to telephone switch. The gateway maps the ACM to the 183 Session Progress response containing an SDP indicating the RTP port that the gateway will use to bridge the audio from the PSTN."
},
{
"code": null,
"e": 63352,
"s": 63121,
"text": "The telephone generates ringtone and it goes to telephone switch. The gateway maps the ACM to the 183 Session Progress response containing an SDP indicating the RTP port that the gateway will use to bridge the audio from the PSTN."
},
{
"code": null,
"e": 63542,
"s": 63352,
"text": "Upon reception of the 183, the caller’s UAC begins receiving the RTP packets sent from the gateway and presents the audio to the caller so they know that the callee progressing in the PSTN."
},
{
"code": null,
"e": 63732,
"s": 63542,
"text": "Upon reception of the 183, the caller’s UAC begins receiving the RTP packets sent from the gateway and presents the audio to the caller so they know that the callee progressing in the PSTN."
},
{
"code": null,
"e": 63878,
"s": 63732,
"text": "The call completes when the called party answers the telephone, which causes the telephone switch to send an answer message (ANM) to the gateway."
},
{
"code": null,
"e": 64024,
"s": 63878,
"text": "The call completes when the called party answers the telephone, which causes the telephone switch to send an answer message (ANM) to the gateway."
},
{
"code": null,
"e": 64272,
"s": 64024,
"text": "The gateway then cuts the PSTN audio connection through in both directions and sends a 200 OK response to the caller. As the RTP media path is already established, the gateway replies the SDP in the 183 but causes no changes to the RTP connection."
},
{
"code": null,
"e": 64520,
"s": 64272,
"text": "The gateway then cuts the PSTN audio connection through in both directions and sends a 200 OK response to the caller. As the RTP media path is already established, the gateway replies the SDP in the 183 but causes no changes to the RTP connection."
},
{
"code": null,
"e": 64654,
"s": 64520,
"text": "The UAC sends an ACK to complete the SIP signalling exchange. As there is no equivalent message in ISUP, the gateway absorbs the ACK."
},
{
"code": null,
"e": 64788,
"s": 64654,
"text": "The UAC sends an ACK to complete the SIP signalling exchange. As there is no equivalent message in ISUP, the gateway absorbs the ACK."
},
{
"code": null,
"e": 64897,
"s": 64788,
"text": "The caller sends BYE to gateway to terminates. The gateway maps the BYE into the ISUP release message (REL)."
},
{
"code": null,
"e": 65006,
"s": 64897,
"text": "The caller sends BYE to gateway to terminates. The gateway maps the BYE into the ISUP release message (REL)."
},
{
"code": null,
"e": 65080,
"s": 65006,
"text": "The gateway sends the 200OK to the BYE and receives an RLC from the PSTN."
},
{
"code": null,
"e": 65154,
"s": 65080,
"text": "The gateway sends the 200OK to the BYE and receives an RLC from the PSTN."
},
{
"code": null,
"e": 65216,
"s": 65154,
"text": "A codec, short for coder-decoder, does two basic operations −"
},
{
"code": null,
"e": 65327,
"s": 65216,
"text": "First, it converts an analog voice signal to its equivalent digital form so that it can be easily transmitted."
},
{
"code": null,
"e": 65438,
"s": 65327,
"text": "First, it converts an analog voice signal to its equivalent digital form so that it can be easily transmitted."
},
{
"code": null,
"e": 65553,
"s": 65438,
"text": "Thereafter, it converts the compressed digital signal back to its original analog form so that it can be replayed."
},
{
"code": null,
"e": 65668,
"s": 65553,
"text": "Thereafter, it converts the compressed digital signal back to its original analog form so that it can be replayed."
},
{
"code": null,
"e": 65830,
"s": 65668,
"text": "There are many codecs available in the market – some are free while others require licensing. Codecs vary in the sound quality and vary in bandwidth accordingly."
},
{
"code": null,
"e": 65980,
"s": 65830,
"text": "Hardware devices such as phones and gateways support several different codecs. While talking to each other, they negotiate which codec they will use."
},
{
"code": null,
"e": 66072,
"s": 65980,
"text": "Here, in this chapter, we will discuss a few popular SIP audio codecs that are widely used."
},
{
"code": null,
"e": 66288,
"s": 66072,
"text": "G.711 is a codec that was introduced by ITU in 1972 for use in digital telephony. The codec has two variants: A-Law is being used in Europe and in international telephone links, uLaw is used in the U.S.A. and Japan."
},
{
"code": null,
"e": 66413,
"s": 66288,
"text": "G.711 uses a logarithmic compression. It squeezes each 16-bit sample to 8 bits, thus it achieves a compression ratio of 1:2."
},
{
"code": null,
"e": 66538,
"s": 66413,
"text": "G.711 uses a logarithmic compression. It squeezes each 16-bit sample to 8 bits, thus it achieves a compression ratio of 1:2."
},
{
"code": null,
"e": 66613,
"s": 66538,
"text": "The bitrate is 64 kbit/s for one direction, so a call consumes 128 kbit/s."
},
{
"code": null,
"e": 66688,
"s": 66613,
"text": "The bitrate is 64 kbit/s for one direction, so a call consumes 128 kbit/s."
},
{
"code": null,
"e": 66834,
"s": 66688,
"text": "G.711 is the same codec used by the PSTN network, hence it provides the best voice quality. However it consumes more bandwidth than other codecs."
},
{
"code": null,
"e": 66980,
"s": 66834,
"text": "G.711 is the same codec used by the PSTN network, hence it provides the best voice quality. However it consumes more bandwidth than other codecs."
},
{
"code": null,
"e": 67061,
"s": 66980,
"text": "It works best in local area networks where we have a lot of bandwidth available."
},
{
"code": null,
"e": 67142,
"s": 67061,
"text": "It works best in local area networks where we have a lot of bandwidth available."
},
{
"code": null,
"e": 67224,
"s": 67142,
"text": "G.729 is a codec with low bandwidth requirements; it provides good audio quality."
},
{
"code": null,
"e": 67351,
"s": 67224,
"text": "The codec encodes audio in frames of 10 ms long. Given a sampling frequency of 8 kHz, a 10 ms frame contains 80 audio samples."
},
{
"code": null,
"e": 67478,
"s": 67351,
"text": "The codec encodes audio in frames of 10 ms long. Given a sampling frequency of 8 kHz, a 10 ms frame contains 80 audio samples."
},
{
"code": null,
"e": 67587,
"s": 67478,
"text": "The codec algorithm encodes each frame into 10 bytes, so the resulting bitrate is 8 kbit/s in one direction."
},
{
"code": null,
"e": 67696,
"s": 67587,
"text": "The codec algorithm encodes each frame into 10 bytes, so the resulting bitrate is 8 kbit/s in one direction."
},
{
"code": null,
"e": 67834,
"s": 67696,
"text": "G.729 is a licensed codec. End-users who want to use this codec should buy a hardware that implements it (be it a VoIP phone or gateway)."
},
{
"code": null,
"e": 67972,
"s": 67834,
"text": "G.729 is a licensed codec. End-users who want to use this codec should buy a hardware that implements it (be it a VoIP phone or gateway)."
},
{
"code": null,
"e": 68096,
"s": 67972,
"text": "A frequently used variant of G.729 is G.729a. It is wire-compatible with the original codec but has lower CPU requirements."
},
{
"code": null,
"e": 68220,
"s": 68096,
"text": "A frequently used variant of G.729 is G.729a. It is wire-compatible with the original codec but has lower CPU requirements."
},
{
"code": null,
"e": 68369,
"s": 68220,
"text": "G.723.1 is the result of a competition that ITU announced with the aim to design a codec that would allow calls over 28.8 and 33 kbit/s modem links."
},
{
"code": null,
"e": 68492,
"s": 68369,
"text": "We have two variants of G.723.1. They both operate on audio frames of 30 ms (i.e. 240 samples), but the algorithms differ."
},
{
"code": null,
"e": 68615,
"s": 68492,
"text": "We have two variants of G.723.1. They both operate on audio frames of 30 ms (i.e. 240 samples), but the algorithms differ."
},
{
"code": null,
"e": 68711,
"s": 68615,
"text": "The bitrate of the first variant is 6.4 kbit/s, while for the second variant, it is 5.3 kbit/s."
},
{
"code": null,
"e": 68807,
"s": 68711,
"text": "The bitrate of the first variant is 6.4 kbit/s, while for the second variant, it is 5.3 kbit/s."
},
{
"code": null,
"e": 68887,
"s": 68807,
"text": "The encoded frames for the two variants are 24 and 20 bytes long, respectively."
},
{
"code": null,
"e": 68967,
"s": 68887,
"text": "The encoded frames for the two variants are 24 and 20 bytes long, respectively."
},
{
"code": null,
"e": 69057,
"s": 68967,
"text": "GSM 06.10 is a codec designed for GSM mobile networks. It is also known as GSM Full Rate."
},
{
"code": null,
"e": 69167,
"s": 69057,
"text": "This variant of the GSM codec can be freely used, so you will often find it in open source VoIP applications."
},
{
"code": null,
"e": 69277,
"s": 69167,
"text": "This variant of the GSM codec can be freely used, so you will often find it in open source VoIP applications."
},
{
"code": null,
"e": 69422,
"s": 69277,
"text": "The codec operates on audio frames 20 ms long (i.e. 160 samples) and it compresses each frame to 33 bytes, so the resulting bitrate is 13 kbit/."
},
{
"code": null,
"e": 69567,
"s": 69422,
"text": "The codec operates on audio frames 20 ms long (i.e. 160 samples) and it compresses each frame to 33 bytes, so the resulting bitrate is 13 kbit/."
},
{
"code": null,
"e": 69769,
"s": 69567,
"text": "A back-to-back user agent (B2BUA) is a logical network element in SIP applications. It is a type of SIP UA that receives a SIP request, then reformulates the request, and sends it out as a new request."
},
{
"code": null,
"e": 69940,
"s": 69769,
"text": "Unlike a proxy server, it maintains dialog state and must participate in all requests sent on the dialogs it has established. A B2BUA breaks the end-to-end nature of SIP."
},
{
"code": null,
"e": 70278,
"s": 69940,
"text": "A B2BUA agent operates between two endpoints of a phone call and divides the communication channel into two call legs. B2BUA is a concatenation of UAC and UAS. It participates in all SIP signalling between both ends of the call, it has established. As B2BUA available in a dialog service provider may implement some value-added features."
},
{
"code": null,
"e": 70487,
"s": 70278,
"text": "In the originating call leg, the B2BUA acts as a user agent server (UAS) and processes the request as a user agent client (UAC) to the destination end, handling the signalling between end points back-to-back."
},
{
"code": null,
"e": 70640,
"s": 70487,
"text": "A B2BUA maintains the complete state for the calls it handles. Each side of a B2BUA operates as a standard SIP network element as specified in RFC 3261."
},
{
"code": null,
"e": 70683,
"s": 70640,
"text": "A B2BUA provides the following functions −"
},
{
"code": null,
"e": 70760,
"s": 70683,
"text": "Call management (billing, automatic call disconnection, call transfer, etc.)"
},
{
"code": null,
"e": 70837,
"s": 70760,
"text": "Call management (billing, automatic call disconnection, call transfer, etc.)"
},
{
"code": null,
"e": 70893,
"s": 70837,
"text": "Network interworking (perhaps with protocol adaptation)"
},
{
"code": null,
"e": 70949,
"s": 70893,
"text": "Network interworking (perhaps with protocol adaptation)"
},
{
"code": null,
"e": 71021,
"s": 70949,
"text": "Hiding of network internals (private addresses, network topology, etc.)"
},
{
"code": null,
"e": 71093,
"s": 71021,
"text": "Hiding of network internals (private addresses, network topology, etc.)"
},
{
"code": null,
"e": 71209,
"s": 71093,
"text": "Often, B2BUAs are also implemented in media gateways to bridge the media streams for full control over the session."
},
{
"code": null,
"e": 71298,
"s": 71209,
"text": "Many private branch exchange (PBX) enterprise telephone systems incorporate B2BUA logic."
},
{
"code": null,
"e": 71488,
"s": 71298,
"text": "Some firewalls have built in with ALG (Application Layer Gateway) functionality, which allows a firewall to authorize SIP and media traffic while still maintaining a high level of security."
}
] |
Sum of array Elements without using loops and recursion
|
02 Nov, 2021
Given an array of N elements, the task is to find the Sum of N elements without using loops(for, while & doWhile) and recursion.Examples:
Input: arr[]={1, 2, 3, 4, 5}
Output: 15
Input: arr[]={10, 20, 30}
Output: 60
Approach: Unconditional Jump Statements can be used to solve this problem.Unconditional Jump Statements:Jump statements interrupt the sequential execution of statements, so that execution continues at a different point in the program. A jump destroys automatic variables if the jump destination is outside their scope. There are four statements that cause unconditional jumps in C: break, continue, goto, and return.To solve this particular problem, goto statement can be useful.goto Statement: The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier which indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find the sum of// N elements with goto statement #include <iostream>using namespace std; // Function to perform desired operationint operate(int array[], int N){ int sum = 0, index = 0; label: sum += array[index++]; if (index < N) { // backward jump of goto statement goto label; } // return the sum return sum;} // Driver Codeint main(){ // Get N int N = 5, sum = 0; // Input values of an array int array[] = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum cout << sum;}
// C program to find the sum of// N elements with goto statement #include <stdio.h> // Function to perform desired operationint operate(int array[], int N){ int sum = 0, index = 0; label: sum += array[index++]; if (index < N) { // backward jump of goto statement goto label; } // return the sum return sum;} // Driver Codeint main(){ // Get N int N = 5, sum = 0; // Input values of an array int array[] = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum printf("%d", sum);}
// Java program to find the sum of// N elementsclass GFG{ // Function to perform desired operation static int operate(int array[], int N) { int sum = 0, index = 0; while(true) { sum += array[index++]; if (index < N) { // backward jump of goto statement continue; } else { break; } } // return the sum return sum; } // Driver code public static void main(String[] args) { // Get N int N = 5, sum = 0; // Input values of an array int array[] = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum System.out.print(sum); }} // This code is contributed by divyeshrabaiya07
# Python3 program to find the sum of# N elements # Function to perform desired operationdef operate(array, N) : Sum, index = 0, 0 while(True) : Sum += array[index] index += 1 if index < N : # backward jump of goto statement continue else : break # return the sum return Sum # Get NN, Sum = 5, 0 # Input values of an arrayarray = [ 1, 2, 3, 4, 5 ] # Find the sumSum = operate(array, N) # Print the sumprint(Sum) # This code is contributed by divyesh072019
// C# program to find the sum of// N elements with goto statementusing System; class GFG{// Function to perform desired operationstatic int operate(int[] array, int N){ int sum = 0, index = 0; label: sum += array[index++]; if (index < N) { // backward jump of goto statement goto label; } // return the sum return sum;} // Driver Codepublic static void Main(){ // Get N int N = 5, sum = 0; // Input values of an array int[] array = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum Console.Write(sum);}} // This code is contributed// by Akanksha Rai
<?php// PHP program to find the sum of N// elements with goto statementfunction operate($array, $N){ $sum = 0; $index = 0; label: $sum += $array[$index++]; if($index < $N) { // backward jump of goto statement goto label; } // return the sum return $sum;} // Driver code$N = 5; $array = array(1, 2, 3, 4, 5); echo operate($array, $N); // This code is contributed// by Mohit kumar 29?>
<script> // Javascript program to find the sum of // N elements // Function to perform desired operation function operate(array, N) { let sum = 0, index = 0; while(true) { sum += array[index++]; if (index < N) { // backward jump of goto statement continue; } else { break; } } // return the sum return sum; } // Get N let N = 5, sum = 0; // Input values of an array let array = [ 1, 2, 3, 4, 5 ]; // Find the sum sum = operate(array, N); // Print the sum document.write(sum); // This code is contributed by suresh07.</script>
15
mohit kumar 29
Akanksha_Rai
divyeshrabadiya07
divyesh072019
suresh07
surindertarika1234
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 192,
"s": 52,
"text": "Given an array of N elements, the task is to find the Sum of N elements without using loops(for, while & doWhile) and recursion.Examples: "
},
{
"code": null,
"e": 276,
"s": 192,
"text": "Input: arr[]={1, 2, 3, 4, 5} \nOutput: 15\n\nInput: arr[]={10, 20, 30} \nOutput: 60"
},
{
"code": null,
"e": 975,
"s": 278,
"text": "Approach: Unconditional Jump Statements can be used to solve this problem.Unconditional Jump Statements:Jump statements interrupt the sequential execution of statements, so that execution continues at a different point in the program. A jump destroys automatic variables if the jump destination is outside their scope. There are four statements that cause unconditional jumps in C: break, continue, goto, and return.To solve this particular problem, goto statement can be useful.goto Statement: The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax: "
},
{
"code": null,
"e": 1167,
"s": 975,
"text": "Syntax1 | Syntax2\n----------------------------\ngoto label; | label: \n. | .\n. | .\n. | .\nlabel: | goto label;"
},
{
"code": null,
"e": 1519,
"s": 1167,
"text": "In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier which indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax. "
},
{
"code": null,
"e": 1572,
"s": 1519,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1576,
"s": 1572,
"text": "C++"
},
{
"code": null,
"e": 1578,
"s": 1576,
"text": "C"
},
{
"code": null,
"e": 1583,
"s": 1578,
"text": "Java"
},
{
"code": null,
"e": 1591,
"s": 1583,
"text": "Python3"
},
{
"code": null,
"e": 1594,
"s": 1591,
"text": "C#"
},
{
"code": null,
"e": 1598,
"s": 1594,
"text": "PHP"
},
{
"code": null,
"e": 1609,
"s": 1598,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of// N elements with goto statement #include <iostream>using namespace std; // Function to perform desired operationint operate(int array[], int N){ int sum = 0, index = 0; label: sum += array[index++]; if (index < N) { // backward jump of goto statement goto label; } // return the sum return sum;} // Driver Codeint main(){ // Get N int N = 5, sum = 0; // Input values of an array int array[] = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum cout << sum;}",
"e": 2191,
"s": 1609,
"text": null
},
{
"code": "// C program to find the sum of// N elements with goto statement #include <stdio.h> // Function to perform desired operationint operate(int array[], int N){ int sum = 0, index = 0; label: sum += array[index++]; if (index < N) { // backward jump of goto statement goto label; } // return the sum return sum;} // Driver Codeint main(){ // Get N int N = 5, sum = 0; // Input values of an array int array[] = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum printf(\"%d\", sum);}",
"e": 2756,
"s": 2191,
"text": null
},
{
"code": "// Java program to find the sum of// N elementsclass GFG{ // Function to perform desired operation static int operate(int array[], int N) { int sum = 0, index = 0; while(true) { sum += array[index++]; if (index < N) { // backward jump of goto statement continue; } else { break; } } // return the sum return sum; } // Driver code public static void main(String[] args) { // Get N int N = 5, sum = 0; // Input values of an array int array[] = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum System.out.print(sum); }} // This code is contributed by divyeshrabaiya07",
"e": 3474,
"s": 2756,
"text": null
},
{
"code": "# Python3 program to find the sum of# N elements # Function to perform desired operationdef operate(array, N) : Sum, index = 0, 0 while(True) : Sum += array[index] index += 1 if index < N : # backward jump of goto statement continue else : break # return the sum return Sum # Get NN, Sum = 5, 0 # Input values of an arrayarray = [ 1, 2, 3, 4, 5 ] # Find the sumSum = operate(array, N) # Print the sumprint(Sum) # This code is contributed by divyesh072019",
"e": 4030,
"s": 3474,
"text": null
},
{
"code": "// C# program to find the sum of// N elements with goto statementusing System; class GFG{// Function to perform desired operationstatic int operate(int[] array, int N){ int sum = 0, index = 0; label: sum += array[index++]; if (index < N) { // backward jump of goto statement goto label; } // return the sum return sum;} // Driver Codepublic static void Main(){ // Get N int N = 5, sum = 0; // Input values of an array int[] array = { 1, 2, 3, 4, 5 }; // Find the sum sum = operate(array, N); // Print the sum Console.Write(sum);}} // This code is contributed// by Akanksha Rai",
"e": 4673,
"s": 4030,
"text": null
},
{
"code": "<?php// PHP program to find the sum of N// elements with goto statementfunction operate($array, $N){ $sum = 0; $index = 0; label: $sum += $array[$index++]; if($index < $N) { // backward jump of goto statement goto label; } // return the sum return $sum;} // Driver code$N = 5; $array = array(1, 2, 3, 4, 5); echo operate($array, $N); // This code is contributed// by Mohit kumar 29?>",
"e": 5148,
"s": 4673,
"text": null
},
{
"code": "<script> // Javascript program to find the sum of // N elements // Function to perform desired operation function operate(array, N) { let sum = 0, index = 0; while(true) { sum += array[index++]; if (index < N) { // backward jump of goto statement continue; } else { break; } } // return the sum return sum; } // Get N let N = 5, sum = 0; // Input values of an array let array = [ 1, 2, 3, 4, 5 ]; // Find the sum sum = operate(array, N); // Print the sum document.write(sum); // This code is contributed by suresh07.</script>",
"e": 5860,
"s": 5148,
"text": null
},
{
"code": null,
"e": 5863,
"s": 5860,
"text": "15"
},
{
"code": null,
"e": 5880,
"s": 5865,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 5893,
"s": 5880,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5911,
"s": 5893,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 5925,
"s": 5911,
"text": "divyesh072019"
},
{
"code": null,
"e": 5934,
"s": 5925,
"text": "suresh07"
},
{
"code": null,
"e": 5953,
"s": 5934,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5964,
"s": 5953,
"text": "C Language"
},
{
"code": null,
"e": 5968,
"s": 5964,
"text": "C++"
},
{
"code": null,
"e": 5987,
"s": 5968,
"text": "School Programming"
},
{
"code": null,
"e": 5991,
"s": 5987,
"text": "CPP"
}
] |
Memory Mapping
|
The mmap() system call provides mapping in the virtual address space of the calling process that maps the files or devices into memory. This is of two types −
File mapping or File-backed mapping − This mapping maps the area of the process’ virtual memory to the files. This means reading or writing to those areas of memory causes the file to be read or written. This is the default mapping type.
Anonymous mapping − This mapping maps the area of the process’ virtual memory without backed by any file. The contents are initialized to zero. This mapping is similar to dynamic memory allocation (malloc()) and is used in some malloc() implementations for certain allocations.
The memory in one process mapping may be shared with mappings in other processes. This can be done in two ways −
When two processes map the same region of a file, they share the same pages of physical memory.
When two processes map the same region of a file, they share the same pages of physical memory.
If a child process is created, it inherits the parent’s mappings and these mappings refer to the same pages of physical memory as that of the parent. Upon any change of data in the child process, different pages would be created for the child process.
If a child process is created, it inherits the parent’s mappings and these mappings refer to the same pages of physical memory as that of the parent. Upon any change of data in the child process, different pages would be created for the child process.
When two or more processes share the same pages, each process can see the changes of the page contents made by other processes depending on the mapping type. The mapping type can be either private or shared −
Private Mapping (MAP_PRIVATE) − Modifications to the contents of this mapping are not visible to other processes and the mapping is not carried to the underlying file.
Shared Mapping (MAP_SHARED) − Modifications to the contents of this mapping are visible to other processes and mapping is carried to the underlying file.
#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
The above system call returns the starting address of the mapping on success or MAP_FAILED on error.
The virtual address addr, can be either user specified or generated by the kernel (upon passing addr as NULL). The field length indicated requires the size of mapping in bytes. The field prot indicates memory protection values such as PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC meant for regions that may not be accessed, read, write or executed respectively. This value can be single (PROT_NONE) or can be ORd with any of the three flags (last 3). The field flags indicate mapping type either or MAP_PRIVATE or MAP_SHARED. The field ‘fd’ indicates the file descriptor identifying the file to be mapped and the field ‘offset’ implies the starting point of the file, if need to map the entire file, offset should be zero.
#include <sys/mman.h>
int munmap(void *addr, size_t length);
The above system call returns 0 on success or -1 on error.
The system call munmap, performs the unmapping of the already memory mapped region. The fields addr indicates the starting address of the mapping and the length indicates the size in bytes of the mapping to be unmapped. Usually, the mapping and unmapping would be for the entire mapped regions. If this has to be different, then it should be either shrinked or cut in two parts. If the addr doesn’t have any mappings this call would have no effect and the call returns 0 (success).
Let us consider an example −
Step 1 − Writie into file Alpha Numeric characters as shown below −
Step 2 − Map the file contents into memory using mmap() system call. This would return the start address after mapped into the memory.
Step 3 − Access the file contents using array notation (can also access with pointer notation) as doesn’t read expensive read() system call. Using memory mapping, avoid multiple copying between the user space, kernel space buffers and buffer cache.
Step 4 − Repeat reading the file contents until the user enters “-1” (signifies end of access).
Step 5 − Perform clean-up activities i.e., unmapping the mapped memory region (munmap()), closing the file and removing the file.
/* Filename: mmap_test.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
void write_mmap_sample_data();
int main() {
struct stat mmapstat;
char *data;
int minbyteindex;
int maxbyteindex;
int offset;
int fd;
int unmapstatus;
write_mmap_sample_data();
if (stat("MMAP_DATA.txt", &mmapstat) == -1) {
perror("stat failure");
return 1;
}
if ((fd = open("MMAP_DATA.txt", O_RDONLY)) == -1) {
perror("open failure");
return 1;
}
data = mmap((caddr_t)0, mmapstat.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (data == (caddr_t)(-1)) {
perror("mmap failure");
return 1;
}
minbyteindex = 0;
maxbyteindex = mmapstat.st_size - 1;
do {
printf("Enter -1 to quit or ");
printf("enter a number between %d and %d: ", minbyteindex, maxbyteindex);
scanf("%d",&offset);
if ( (offset >= 0) && (offset <= maxbyteindex) )
printf("Received char at %d is %c\n", offset, data[offset]);
else if (offset != -1)
printf("Received invalid index %d\n", offset);
} while (offset != -1);
unmapstatus = munmap(data, mmapstat.st_size);
if (unmapstatus == -1) {
perror("munmap failure");
return 1;
}
close(fd);
system("rm -f MMAP_DATA.txt");
return 0;
}
void write_mmap_sample_data() {
int fd;
char ch;
struct stat textfilestat;
fd = open("MMAP_DATA.txt", O_CREAT|O_TRUNC|O_WRONLY, 0666);
if (fd == -1) {
perror("File open error ");
return;
}
// Write A to Z
ch = 'A';
while (ch <= 'Z') {
write(fd, &ch, sizeof(ch));
ch++;
}
// Write 0 to 9
ch = '0';
while (ch <= '9') {
write(fd, &ch, sizeof(ch));
ch++;
}
// Write a to z
ch = 'a';
while (ch <= 'z') {
write(fd, &ch, sizeof(ch));
ch++;
}
close(fd);
return;
}
Enter -1 to quit or enter a number between 0 and 61: 3
Received char at 3 is D
Enter -1 to quit or enter a number between 0 and 61: 28
Received char at 28 is 2
Enter -1 to quit or enter a number between 0 and 61: 38
Received char at 38 is c
Enter -1 to quit or enter a number between 0 and 61: 59
Received char at 59 is x
Enter -1 to quit or enter a number between 0 and 61: 65
Received invalid index 65
Enter -1 to quit or enter a number between 0 and 61: -99
Received invalid index -99
Enter -1 to quit or enter a number between 0 and 61: -1
|
[
{
"code": null,
"e": 2164,
"s": 2005,
"text": "The mmap() system call provides mapping in the virtual address space of the calling process that maps the files or devices into memory. This is of two types −"
},
{
"code": null,
"e": 2402,
"s": 2164,
"text": "File mapping or File-backed mapping − This mapping maps the area of the process’ virtual memory to the files. This means reading or writing to those areas of memory causes the file to be read or written. This is the default mapping type."
},
{
"code": null,
"e": 2680,
"s": 2402,
"text": "Anonymous mapping − This mapping maps the area of the process’ virtual memory without backed by any file. The contents are initialized to zero. This mapping is similar to dynamic memory allocation (malloc()) and is used in some malloc() implementations for certain allocations."
},
{
"code": null,
"e": 2793,
"s": 2680,
"text": "The memory in one process mapping may be shared with mappings in other processes. This can be done in two ways −"
},
{
"code": null,
"e": 2889,
"s": 2793,
"text": "When two processes map the same region of a file, they share the same pages of physical memory."
},
{
"code": null,
"e": 2985,
"s": 2889,
"text": "When two processes map the same region of a file, they share the same pages of physical memory."
},
{
"code": null,
"e": 3237,
"s": 2985,
"text": "If a child process is created, it inherits the parent’s mappings and these mappings refer to the same pages of physical memory as that of the parent. Upon any change of data in the child process, different pages would be created for the child process."
},
{
"code": null,
"e": 3489,
"s": 3237,
"text": "If a child process is created, it inherits the parent’s mappings and these mappings refer to the same pages of physical memory as that of the parent. Upon any change of data in the child process, different pages would be created for the child process."
},
{
"code": null,
"e": 3698,
"s": 3489,
"text": "When two or more processes share the same pages, each process can see the changes of the page contents made by other processes depending on the mapping type. The mapping type can be either private or shared −"
},
{
"code": null,
"e": 3866,
"s": 3698,
"text": "Private Mapping (MAP_PRIVATE) − Modifications to the contents of this mapping are not visible to other processes and the mapping is not carried to the underlying file."
},
{
"code": null,
"e": 4020,
"s": 3866,
"text": "Shared Mapping (MAP_SHARED) − Modifications to the contents of this mapping are visible to other processes and mapping is carried to the underlying file."
},
{
"code": null,
"e": 4125,
"s": 4020,
"text": "#include <sys/mman.h>\n\nvoid *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);"
},
{
"code": null,
"e": 4226,
"s": 4125,
"text": "The above system call returns the starting address of the mapping on success or MAP_FAILED on error."
},
{
"code": null,
"e": 4948,
"s": 4226,
"text": "The virtual address addr, can be either user specified or generated by the kernel (upon passing addr as NULL). The field length indicated requires the size of mapping in bytes. The field prot indicates memory protection values such as PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC meant for regions that may not be accessed, read, write or executed respectively. This value can be single (PROT_NONE) or can be ORd with any of the three flags (last 3). The field flags indicate mapping type either or MAP_PRIVATE or MAP_SHARED. The field ‘fd’ indicates the file descriptor identifying the file to be mapped and the field ‘offset’ implies the starting point of the file, if need to map the entire file, offset should be zero."
},
{
"code": null,
"e": 5010,
"s": 4948,
"text": "#include <sys/mman.h>\n\nint munmap(void *addr, size_t length);"
},
{
"code": null,
"e": 5069,
"s": 5010,
"text": "The above system call returns 0 on success or -1 on error."
},
{
"code": null,
"e": 5551,
"s": 5069,
"text": "The system call munmap, performs the unmapping of the already memory mapped region. The fields addr indicates the starting address of the mapping and the length indicates the size in bytes of the mapping to be unmapped. Usually, the mapping and unmapping would be for the entire mapped regions. If this has to be different, then it should be either shrinked or cut in two parts. If the addr doesn’t have any mappings this call would have no effect and the call returns 0 (success)."
},
{
"code": null,
"e": 5580,
"s": 5551,
"text": "Let us consider an example −"
},
{
"code": null,
"e": 5648,
"s": 5580,
"text": "Step 1 − Writie into file Alpha Numeric characters as shown below −"
},
{
"code": null,
"e": 5783,
"s": 5648,
"text": "Step 2 − Map the file contents into memory using mmap() system call. This would return the start address after mapped into the memory."
},
{
"code": null,
"e": 6032,
"s": 5783,
"text": "Step 3 − Access the file contents using array notation (can also access with pointer notation) as doesn’t read expensive read() system call. Using memory mapping, avoid multiple copying between the user space, kernel space buffers and buffer cache."
},
{
"code": null,
"e": 6128,
"s": 6032,
"text": "Step 4 − Repeat reading the file contents until the user enters “-1” (signifies end of access)."
},
{
"code": null,
"e": 6258,
"s": 6128,
"text": "Step 5 − Perform clean-up activities i.e., unmapping the mapped memory region (munmap()), closing the file and removing the file."
},
{
"code": null,
"e": 8229,
"s": 6258,
"text": "/* Filename: mmap_test.c */\n#include <stdio.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys/mman.h>\nvoid write_mmap_sample_data();\n\nint main() {\n struct stat mmapstat;\n char *data;\n int minbyteindex;\n int maxbyteindex;\n int offset;\n int fd;\n int unmapstatus;\n write_mmap_sample_data();\n if (stat(\"MMAP_DATA.txt\", &mmapstat) == -1) {\n perror(\"stat failure\");\n return 1;\n }\n \n if ((fd = open(\"MMAP_DATA.txt\", O_RDONLY)) == -1) {\n perror(\"open failure\");\n return 1;\n }\n data = mmap((caddr_t)0, mmapstat.st_size, PROT_READ, MAP_SHARED, fd, 0);\n \n if (data == (caddr_t)(-1)) {\n perror(\"mmap failure\");\n return 1;\n }\n minbyteindex = 0;\n maxbyteindex = mmapstat.st_size - 1;\n \n do {\n printf(\"Enter -1 to quit or \");\n printf(\"enter a number between %d and %d: \", minbyteindex, maxbyteindex);\n scanf(\"%d\",&offset);\n if ( (offset >= 0) && (offset <= maxbyteindex) )\n printf(\"Received char at %d is %c\\n\", offset, data[offset]);\n else if (offset != -1)\n printf(\"Received invalid index %d\\n\", offset);\n } while (offset != -1);\n unmapstatus = munmap(data, mmapstat.st_size);\n \n if (unmapstatus == -1) {\n perror(\"munmap failure\");\n return 1;\n }\n close(fd);\n system(\"rm -f MMAP_DATA.txt\");\n return 0;\n}\n\nvoid write_mmap_sample_data() {\n int fd;\n char ch;\n struct stat textfilestat;\n fd = open(\"MMAP_DATA.txt\", O_CREAT|O_TRUNC|O_WRONLY, 0666);\n if (fd == -1) {\n perror(\"File open error \");\n return;\n }\n // Write A to Z\n ch = 'A';\n \n while (ch <= 'Z') {\n write(fd, &ch, sizeof(ch));\n ch++;\n }\n // Write 0 to 9\n ch = '0';\n \n while (ch <= '9') {\n write(fd, &ch, sizeof(ch));\n ch++;\n }\n // Write a to z\n ch = 'a';\n \n while (ch <= 'z') {\n write(fd, &ch, sizeof(ch));\n ch++;\n }\n close(fd);\n return;\n}"
}
] |
How to select different values from same column and display them in different columns with MySQL?
|
To select different values on the basis of condition, use CASE statement. Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(40),
Score int
) ;
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(Name,Score) values('David',68);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Score) values('Robert',89);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Score) values('Bob',34);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name,Score) values('Sam',66);
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------+
| Id | Name | Score |
+----+--------+-------+
| 1 | Chris | 45 |
| 2 | David | 68 |
| 3 | Robert | 89 |
| 4 | Bob | 34 |
| 5 | Sam | 66 |
+----+--------+-------+
5 rows in set (0.00 sec)
Following is the query to select different values from same column −
mysql> select Score,
case when Score < 40 then Score end as ' Score Less than 40',
case when Score between 60 and 70 then Score end as 'Score Between 60 and 70 ',
case when Score > 80 then Score end as 'Score greater than 80'
from DemoTable;
This will produce the following output −
+-------+--------------------+--------------------------+-----------------------+
| Score | Score Less than 40 | Score Between 60 and 70 | Score greater than 80 |
+-------+--------------------+--------------------------+-----------------------+
| 45 | NULL | NULL | NULL |
| 68 | NULL | 68 | NULL |
| 89 | NULL | NULL | 89 |
| 34 | 34 | NULL | NULL |
| 66 | NULL | 66 | NULL |
+-------+--------------------+--------------------------+-----------------------+
5 rows in set, 1 warning (0.03 sec)
|
[
{
"code": null,
"e": 1291,
"s": 1187,
"text": "To select different values on the basis of condition, use CASE statement. Let us first create a table −"
},
{
"code": null,
"e": 1442,
"s": 1291,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(40),\nScore int\n) ;\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1498,
"s": 1442,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1980,
"s": 1498,
"text": "mysql> insert into DemoTable(Name,Score) values('Chris',45);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable(Name,Score) values('David',68);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(Name,Score) values('Robert',89);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable(Name,Score) values('Bob',34);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable(Name,Score) values('Sam',66);\nQuery OK, 1 row affected (0.22 sec)"
},
{
"code": null,
"e": 2040,
"s": 1980,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2071,
"s": 2040,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2112,
"s": 2071,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2353,
"s": 2112,
"text": "+----+--------+-------+\n| Id | Name | Score |\n+----+--------+-------+\n| 1 | Chris | 45 |\n| 2 | David | 68 |\n| 3 | Robert | 89 |\n| 4 | Bob | 34 |\n| 5 | Sam | 66 |\n+----+--------+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2422,
"s": 2353,
"text": "Following is the query to select different values from same column −"
},
{
"code": null,
"e": 2676,
"s": 2422,
"text": "mysql> select Score,\n case when Score < 40 then Score end as ' Score Less than 40',\n case when Score between 60 and 70 then Score end as 'Score Between 60 and 70 ',\n case when Score > 80 then Score end as 'Score greater than 80'\n from DemoTable;"
},
{
"code": null,
"e": 2717,
"s": 2676,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3491,
"s": 2717,
"text": "+-------+--------------------+--------------------------+-----------------------+\n| Score | Score Less than 40 | Score Between 60 and 70 | Score greater than 80 |\n+-------+--------------------+--------------------------+-----------------------+\n| 45 | NULL | NULL | NULL |\n| 68 | NULL | 68 | NULL |\n| 89 | NULL | NULL | 89 |\n| 34 | 34 | NULL | NULL |\n| 66 | NULL | 66 | NULL |\n+-------+--------------------+--------------------------+-----------------------+\n5 rows in set, 1 warning (0.03 sec)"
}
] |
What does the CSS rule “clear: both” do?
|
15 Feb, 2019
The clear property is used to specify that which side of floating elements are not allowed to float. It sets or returns the position of the element in relation to floating the objects.
The “clear: both” means floating the elements are not allowed to float on both sides. It is used when no need of any element float on the left and right side as related to the specified element and wanted the next element only shown below. It also indicates that no other element takes up space on the left and right side.
Syntax:
clear:both;
Example:
<!DOCTYPE html> <html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: both; } h1 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:both;</h1> <div><pre>GFG</pre></div> <p>GeeksforGeeks: A computer science portal for geeks</p> <p class="GFG">GeeksforGeeks</P> </body> </html>
Output:
Supported Browsers: The supported browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n15 Feb, 2019"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "The clear property is used to specify that which side of floating elements are not allowed to float. It sets or returns the position of the element in relation to floating the objects."
},
{
"code": null,
"e": 536,
"s": 213,
"text": "The “clear: both” means floating the elements are not allowed to float on both sides. It is used when no need of any element float on the left and right side as related to the specified element and wanted the next element only shown below. It also indicates that no other element takes up space on the left and right side."
},
{
"code": null,
"e": 544,
"s": 536,
"text": "Syntax:"
},
{
"code": null,
"e": 557,
"s": 544,
"text": "clear:both; "
},
{
"code": null,
"e": 566,
"s": 557,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: both; } h1 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:both;</h1> <div><pre>GFG</pre></div> <p>GeeksforGeeks: A computer science portal for geeks</p> <p class=\"GFG\">GeeksforGeeks</P> </body> </html> ",
"e": 1376,
"s": 566,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1376,
"text": "Output:"
},
{
"code": null,
"e": 1445,
"s": 1384,
"text": "Supported Browsers: The supported browsers are listed below:"
},
{
"code": null,
"e": 1459,
"s": 1445,
"text": "Google Chrome"
},
{
"code": null,
"e": 1477,
"s": 1459,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1485,
"s": 1477,
"text": "Firefox"
},
{
"code": null,
"e": 1491,
"s": 1485,
"text": "Opera"
},
{
"code": null,
"e": 1498,
"s": 1491,
"text": "Safari"
},
{
"code": null,
"e": 1507,
"s": 1498,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1514,
"s": 1507,
"text": "Picked"
},
{
"code": null,
"e": 1518,
"s": 1514,
"text": "CSS"
},
{
"code": null,
"e": 1535,
"s": 1518,
"text": "Web Technologies"
},
{
"code": null,
"e": 1633,
"s": 1535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1681,
"s": 1633,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1743,
"s": 1681,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1793,
"s": 1743,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1851,
"s": 1793,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 1901,
"s": 1851,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1963,
"s": 1901,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1996,
"s": 1963,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2057,
"s": 1996,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2107,
"s": 2057,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
‘crontab’ in Linux with Examples
|
22 Apr, 2022
The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. Crontab stands for “cron table, ” because it uses the job scheduler cron to execute tasks; cron itself is named after “chronos, ” the Greek word for time.cron is the system process which will automatically perform tasks for you according to a set schedule. The schedule is called the crontab, which is also the name of the program used to edit that schedule. Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Crontab Fields and Allowed Ranges (Linux Crontab Syntax)
Field Description Allowed Value
MIN Minute field 0 to 59
HOUR Hour field 0 to 23
DOM Day of Month 1-31
MON Month field 1-12
DOW Day Of Week 0-6
CMD Command Any command to be executed.
Examples of Cron jobs 1. Scheduling a Job For a Specific Time The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM. The time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/maverick/full-backup
30 – 30th Minute 08 – 08 AM 10 – 10th Day 06 – 6th Month (June) * – Every day of the week 2.To view the Crontab entries
View Current Logged-In User’s Crontab entries : To view your crontab entries type crontab -l from your unix account.
View Root Crontab entries : Login as root user (su – root) and do crontab -l.
To view crontab entries of other Linux users : Login to root and use -u {username} -l.
3.To edit Crontab Entries Edit Current Logged-In User’s Crontab entries.To edit a crontab entries, use crontab -e. By default this will edit the current logged-in users crontab. 4.To schedule a job for every minute using Cron. Ideally you may not have a requirement to schedule a job every minute. But understanding this example will help you understand the other examples.
* * * * * CMD
The * means all the possible unit — i.e every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases. When you specify */5 in minute field means every 5 minutes. When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute. Thus the above convention can be used for all the other 4 fields. 5.To schedule a job for more than one time (e.g. Twice a Day) The following script take a incremental backup twice a day every day. This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time.
00 11, 16 * * * /home/maverick/bin/incremental-backup
00 – 0th Minute (Top of the hour) 11, 16 – 11 AM and 4 PM * – Every day * – Every month * – Every day of the week 6.To schedule a job for certain range of time (e.g. Only on Weekdays) If you wanted a job to be scheduled for every hour with in a specific range of time then use the following.
Cron Job everyday during working hours : This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m
00 09-18 * * * /home/maverick/bin/check-db-status
00 – 0th Minute (Top of the hour) 09-18 – 9 am, 10 am, 11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm * – Every day * – Every month * – Every day of the week
Cron Job every weekday during working hours : This example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m.
00 09-18 * * 1-5 /home/maverick/bin/check-db-status
00 – 0th Minute (Top of the hour) 09-18 – 9 am, 10 am, 11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm * – Every day * – Every month 1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)
7.To schedule a background Cron job for every 10 minutes. Use the following, if you want to check the disk space every 10 minutes.
*/10 * * * * /home/maverick/check-disk-space
It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during certain hours or vice versa. The above examples shows how to do those things.Instead of specifying values in the 5 fields, we can specify it using a single keyword as mentioned below. There are special cases in which instead of the above 5 fields you can use @ followed by a keyword — such as reboot, midnight, yearly, hourly. Cron special keywords and its meaning
Keyword Equivalent
@yearly 0 0 1 1 *
@daily 0 0 * * *
@hourly 0 * * * *
@reboot Run at startup.
8.To schedule a job for first minute of every year using @yearly If you want a job to be executed on the first minute of every year, then you can use the @yearly cron keyword as shown below.This will execute the system annual maintenance using annual-maintenance shell script at 00:00 on Jan 1st for every year.
@yearly /home/maverick/bin/annual-maintenance
9.To schedule a Cron job beginning of every month using @monthly It is as similar as the @yearly as above. But executes the command monthly once using @monthly cron keyword.This will execute the shell script tape-backup at 00:00 on 1st of every month.
@monthly /home/maverick/bin/tape-backup
10.To schedule a background job every day using @daily Using the @daily cron keyword, this will do a daily log file cleanup using cleanup-logs shell script at 00:00 on every day.
@daily /home/maverick/bin/cleanup-logs "day started"
11.To execute a linux command after every reboot using @reboot Using the @reboot cron keyword, this will execute the specified command once after the machine got booted every time.
@reboot CMD
Reference : Linux man page for cron This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
linux-command
Linux-misc-commands
Linux-Unix
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 571,
"s": 54,
"text": "The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. Crontab stands for “cron table, ” because it uses the job scheduler cron to execute tasks; cron itself is named after “chronos, ” the Greek word for time.cron is the system process which will automatically perform tasks for you according to a set schedule. The schedule is called the crontab, which is also the name of the program used to edit that schedule. Linux Crontab Format"
},
{
"code": null,
"e": 596,
"s": 571,
"text": "MIN HOUR DOM MON DOW CMD"
},
{
"code": null,
"e": 653,
"s": 596,
"text": "Crontab Fields and Allowed Ranges (Linux Crontab Syntax)"
},
{
"code": null,
"e": 899,
"s": 653,
"text": "Field Description Allowed Value\nMIN Minute field 0 to 59\nHOUR Hour field 0 to 23\nDOM Day of Month 1-31\nMON Month field 1-12\nDOW Day Of Week 0-6\nCMD Command Any command to be executed."
},
{
"code": null,
"e": 1202,
"s": 899,
"text": "Examples of Cron jobs 1. Scheduling a Job For a Specific Time The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM. The time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20."
},
{
"code": null,
"e": 1243,
"s": 1202,
"text": "30 08 10 06 * /home/maverick/full-backup"
},
{
"code": null,
"e": 1363,
"s": 1243,
"text": "30 – 30th Minute 08 – 08 AM 10 – 10th Day 06 – 6th Month (June) * – Every day of the week 2.To view the Crontab entries"
},
{
"code": null,
"e": 1481,
"s": 1363,
"text": "View Current Logged-In User’s Crontab entries : To view your crontab entries type crontab -l from your unix account. "
},
{
"code": null,
"e": 1560,
"s": 1481,
"text": "View Root Crontab entries : Login as root user (su – root) and do crontab -l. "
},
{
"code": null,
"e": 1648,
"s": 1560,
"text": "To view crontab entries of other Linux users : Login to root and use -u {username} -l. "
},
{
"code": null,
"e": 2024,
"s": 1648,
"text": "3.To edit Crontab Entries Edit Current Logged-In User’s Crontab entries.To edit a crontab entries, use crontab -e. By default this will edit the current logged-in users crontab. 4.To schedule a job for every minute using Cron. Ideally you may not have a requirement to schedule a job every minute. But understanding this example will help you understand the other examples."
},
{
"code": null,
"e": 2038,
"s": 2024,
"text": "* * * * * CMD"
},
{
"code": null,
"e": 2790,
"s": 2038,
"text": "The * means all the possible unit — i.e every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases. When you specify */5 in minute field means every 5 minutes. When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute. Thus the above convention can be used for all the other 4 fields. 5.To schedule a job for more than one time (e.g. Twice a Day) The following script take a incremental backup twice a day every day. This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time."
},
{
"code": null,
"e": 2844,
"s": 2790,
"text": "00 11, 16 * * * /home/maverick/bin/incremental-backup"
},
{
"code": null,
"e": 3136,
"s": 2844,
"text": "00 – 0th Minute (Top of the hour) 11, 16 – 11 AM and 4 PM * – Every day * – Every month * – Every day of the week 6.To schedule a job for certain range of time (e.g. Only on Weekdays) If you wanted a job to be scheduled for every hour with in a specific range of time then use the following."
},
{
"code": null,
"e": 3293,
"s": 3136,
"text": "Cron Job everyday during working hours : This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m"
},
{
"code": null,
"e": 3343,
"s": 3293,
"text": "00 09-18 * * * /home/maverick/bin/check-db-status"
},
{
"code": null,
"e": 3503,
"s": 3343,
"text": "00 – 0th Minute (Top of the hour) 09-18 – 9 am, 10 am, 11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm * – Every day * – Every month * – Every day of the week"
},
{
"code": null,
"e": 3678,
"s": 3503,
"text": "Cron Job every weekday during working hours : This example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m."
},
{
"code": null,
"e": 3730,
"s": 3678,
"text": "00 09-18 * * 1-5 /home/maverick/bin/check-db-status"
},
{
"code": null,
"e": 3912,
"s": 3730,
"text": "00 – 0th Minute (Top of the hour) 09-18 – 9 am, 10 am, 11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm * – Every day * – Every month 1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)"
},
{
"code": null,
"e": 4043,
"s": 3912,
"text": "7.To schedule a background Cron job for every 10 minutes. Use the following, if you want to check the disk space every 10 minutes."
},
{
"code": null,
"e": 4088,
"s": 4043,
"text": "*/10 * * * * /home/maverick/check-disk-space"
},
{
"code": null,
"e": 4611,
"s": 4088,
"text": "It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during certain hours or vice versa. The above examples shows how to do those things.Instead of specifying values in the 5 fields, we can specify it using a single keyword as mentioned below. There are special cases in which instead of the above 5 fields you can use @ followed by a keyword — such as reboot, midnight, yearly, hourly. Cron special keywords and its meaning"
},
{
"code": null,
"e": 4723,
"s": 4611,
"text": "Keyword Equivalent\n@yearly 0 0 1 1 *\n@daily 0 0 * * *\n@hourly 0 * * * *\n@reboot Run at startup."
},
{
"code": null,
"e": 5035,
"s": 4723,
"text": "8.To schedule a job for first minute of every year using @yearly If you want a job to be executed on the first minute of every year, then you can use the @yearly cron keyword as shown below.This will execute the system annual maintenance using annual-maintenance shell script at 00:00 on Jan 1st for every year."
},
{
"code": null,
"e": 5081,
"s": 5035,
"text": "@yearly /home/maverick/bin/annual-maintenance"
},
{
"code": null,
"e": 5333,
"s": 5081,
"text": "9.To schedule a Cron job beginning of every month using @monthly It is as similar as the @yearly as above. But executes the command monthly once using @monthly cron keyword.This will execute the shell script tape-backup at 00:00 on 1st of every month."
},
{
"code": null,
"e": 5373,
"s": 5333,
"text": "@monthly /home/maverick/bin/tape-backup"
},
{
"code": null,
"e": 5552,
"s": 5373,
"text": "10.To schedule a background job every day using @daily Using the @daily cron keyword, this will do a daily log file cleanup using cleanup-logs shell script at 00:00 on every day."
},
{
"code": null,
"e": 5605,
"s": 5552,
"text": "@daily /home/maverick/bin/cleanup-logs \"day started\""
},
{
"code": null,
"e": 5786,
"s": 5605,
"text": "11.To execute a linux command after every reboot using @reboot Using the @reboot cron keyword, this will execute the specified command once after the machine got booted every time."
},
{
"code": null,
"e": 5798,
"s": 5786,
"text": "@reboot CMD"
},
{
"code": null,
"e": 6256,
"s": 5798,
"text": "Reference : Linux man page for cron This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6273,
"s": 6256,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6287,
"s": 6273,
"text": "linux-command"
},
{
"code": null,
"e": 6307,
"s": 6287,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 6318,
"s": 6307,
"text": "Linux-Unix"
},
{
"code": null,
"e": 6336,
"s": 6318,
"text": "Operating Systems"
},
{
"code": null,
"e": 6354,
"s": 6336,
"text": "Operating Systems"
}
] |
CSS | Layout – Horizontal & Vertical Align
|
14 Feb, 2019
The Layout in CSS is used to control the flow of element inside another element. It sets the position of element in the web page. The position of element can be set by using horizontal and vertical alignment. There are many ways to set the position of element which are listed below:
Using Position Property: Use position property to absolute to set the align left and right.
Syntax:
position: absolute;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ position: absolute; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Using text align property: Use text-align property to set the horizontal alignment of an element. The text-align property can be set to left, right or center.
Syntax:
text-align: center;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ text-align: center; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Using float property: Use float property to set the alignment of element. The float value can be set to left or right.
Syntax:
float: right;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ float: right; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Use Padding property Horizontally: Padding property is used to set the element align to Horizontally by using left and right padding.
Syntax:
padding: 0 100px;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ padding: 0 100px; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Use Padding property Vertically: Padding property is used to set the element align to Vertically by using top and bottom padding.
Syntax:
padding: 15px 0;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ padding: 15px 0; text-align: center; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Line height property: Line height is used to set the alignment vertically.
Syntax:
line-height: 40px;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { line-height: 40px; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Using margin property: Margin property is used to set auto, align horizontally a block element.
Syntax:
margin: auto;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { margin: auto; width: 300px; height: 100px; } </style> <head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Using Clearfix: If any element is taller than its parent element and it is floated then it will overflow outside of its container. Overflow is set to auto to fix this.
Syntax:
overflow: auto;
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { overflow: auto; } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
Using transform and positioning: The transform property is used to transform an element relative to its parent element along with position to absolute.
Syntax:
position: absolute;
transform: translate(X%, Y%);
Example:
<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { position: absolute; transform: translate(50%, 10%); } </style> </head> <body> <div id="content"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html>
Output:
CSS-Basics
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
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": "\n14 Feb, 2019"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "The Layout in CSS is used to control the flow of element inside another element. It sets the position of element in the web page. The position of element can be set by using horizontal and vertical alignment. There are many ways to set the position of element which are listed below:"
},
{
"code": null,
"e": 404,
"s": 312,
"text": "Using Position Property: Use position property to absolute to set the align left and right."
},
{
"code": null,
"e": 412,
"s": 404,
"text": "Syntax:"
},
{
"code": null,
"e": 432,
"s": 412,
"text": "position: absolute;"
},
{
"code": null,
"e": 441,
"s": 432,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ position: absolute; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 1020,
"s": 441,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1020,
"text": "Output:"
},
{
"code": null,
"e": 1187,
"s": 1028,
"text": "Using text align property: Use text-align property to set the horizontal alignment of an element. The text-align property can be set to left, right or center."
},
{
"code": null,
"e": 1195,
"s": 1187,
"text": "Syntax:"
},
{
"code": null,
"e": 1215,
"s": 1195,
"text": "text-align: center;"
},
{
"code": null,
"e": 1224,
"s": 1215,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ text-align: center; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 1807,
"s": 1224,
"text": null
},
{
"code": null,
"e": 1815,
"s": 1807,
"text": "Output:"
},
{
"code": null,
"e": 1934,
"s": 1815,
"text": "Using float property: Use float property to set the alignment of element. The float value can be set to left or right."
},
{
"code": null,
"e": 1942,
"s": 1934,
"text": "Syntax:"
},
{
"code": null,
"e": 1956,
"s": 1942,
"text": "float: right;"
},
{
"code": null,
"e": 1965,
"s": 1956,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ float: right; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 2526,
"s": 1965,
"text": null
},
{
"code": null,
"e": 2534,
"s": 2526,
"text": "Output:"
},
{
"code": null,
"e": 2668,
"s": 2534,
"text": "Use Padding property Horizontally: Padding property is used to set the element align to Horizontally by using left and right padding."
},
{
"code": null,
"e": 2676,
"s": 2668,
"text": "Syntax:"
},
{
"code": null,
"e": 2694,
"s": 2676,
"text": "padding: 0 100px;"
},
{
"code": null,
"e": 2703,
"s": 2694,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ padding: 0 100px; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 3267,
"s": 2703,
"text": null
},
{
"code": null,
"e": 3275,
"s": 3267,
"text": "Output:"
},
{
"code": null,
"e": 3405,
"s": 3275,
"text": "Use Padding property Vertically: Padding property is used to set the element align to Vertically by using top and bottom padding."
},
{
"code": null,
"e": 3413,
"s": 3405,
"text": "Syntax:"
},
{
"code": null,
"e": 3430,
"s": 3413,
"text": "padding: 15px 0;"
},
{
"code": null,
"e": 3439,
"s": 3430,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body{ width: 500px; height: 150px; border: 3px solid green; } #content{ padding: 15px 0; text-align: center; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 4046,
"s": 3439,
"text": null
},
{
"code": null,
"e": 4054,
"s": 4046,
"text": "Output:"
},
{
"code": null,
"e": 4129,
"s": 4054,
"text": "Line height property: Line height is used to set the alignment vertically."
},
{
"code": null,
"e": 4137,
"s": 4129,
"text": "Syntax:"
},
{
"code": null,
"e": 4156,
"s": 4137,
"text": "line-height: 40px;"
},
{
"code": null,
"e": 4165,
"s": 4156,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { line-height: 40px; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 4729,
"s": 4165,
"text": null
},
{
"code": null,
"e": 4737,
"s": 4729,
"text": "Output:"
},
{
"code": null,
"e": 4833,
"s": 4737,
"text": "Using margin property: Margin property is used to set auto, align horizontally a block element."
},
{
"code": null,
"e": 4841,
"s": 4833,
"text": "Syntax:"
},
{
"code": null,
"e": 4855,
"s": 4841,
"text": "margin: auto;"
},
{
"code": null,
"e": 4864,
"s": 4855,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { margin: auto; width: 300px; height: 100px; } </style> <head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 5486,
"s": 4864,
"text": null
},
{
"code": null,
"e": 5494,
"s": 5486,
"text": "Output:"
},
{
"code": null,
"e": 5662,
"s": 5494,
"text": "Using Clearfix: If any element is taller than its parent element and it is floated then it will overflow outside of its container. Overflow is set to auto to fix this."
},
{
"code": null,
"e": 5670,
"s": 5662,
"text": "Syntax:"
},
{
"code": null,
"e": 5686,
"s": 5670,
"text": "overflow: auto;"
},
{
"code": null,
"e": 5695,
"s": 5686,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { overflow: auto; } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 6261,
"s": 5695,
"text": null
},
{
"code": null,
"e": 6269,
"s": 6261,
"text": "Output:"
},
{
"code": null,
"e": 6421,
"s": 6269,
"text": "Using transform and positioning: The transform property is used to transform an element relative to its parent element along with position to absolute."
},
{
"code": null,
"e": 6429,
"s": 6421,
"text": "Syntax:"
},
{
"code": null,
"e": 6479,
"s": 6429,
"text": "position: absolute;\ntransform: translate(X%, Y%);"
},
{
"code": null,
"e": 6488,
"s": 6479,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Layout </title> <style> body { width: 500px; height: 150px; border: 3px solid green; } #content { position: absolute; transform: translate(50%, 10%); } </style> </head> <body> <div id=\"content\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2>CSS Layout</h2> </div> </body> </html> ",
"e": 7101,
"s": 6488,
"text": null
},
{
"code": null,
"e": 7109,
"s": 7101,
"text": "Output:"
},
{
"code": null,
"e": 7120,
"s": 7109,
"text": "CSS-Basics"
},
{
"code": null,
"e": 7127,
"s": 7120,
"text": "Picked"
},
{
"code": null,
"e": 7131,
"s": 7127,
"text": "CSS"
},
{
"code": null,
"e": 7148,
"s": 7131,
"text": "Web Technologies"
},
{
"code": null,
"e": 7246,
"s": 7148,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7294,
"s": 7246,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 7356,
"s": 7294,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7406,
"s": 7356,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7464,
"s": 7406,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 7514,
"s": 7464,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 7547,
"s": 7514,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 7609,
"s": 7547,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7670,
"s": 7609,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7720,
"s": 7670,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Extract values from HashMap in Java
|
To extract values from HashMap, let us first create a HashMap with keys and values −
HashMap<Integer, Integer>m = new HashMap<Integer, Integer>();
Now, add some elements to the HashMap −
m.put(10, 20);
m.put(30, 40);
m.put(50, 60);
m.put(70, 80);
m.put(90, 100);
m.put(110, 120);
m.put(130, 140);
m.put(150, 160);
Now, extract the values from the HashMap −
for (Integer i: m.keySet()) {
System.out.println(m.get(i));
}
Live Demo
import java.util.HashMap;
public class Demo {
public static void main(String args[]) {
HashMap<Integer, Integer>m = new HashMap<Integer, Integer>();
m.put(10, 20);
m.put(30, 40);
m.put(50, 60);
m.put(70, 80);
m.put(90, 100);
m.put(110, 120);
m.put(130, 140);
m.put(150, 160);
System.out.println("Displaying values from HashMap...");
for (Integer i: m.keySet()) {
System.out.println(m.get(i));
}
}
}
Displaying values from HashMap...
60
140
80
160
20
100
40
120
|
[
{
"code": null,
"e": 1272,
"s": 1187,
"text": "To extract values from HashMap, let us first create a HashMap with keys and values −"
},
{
"code": null,
"e": 1334,
"s": 1272,
"text": "HashMap<Integer, Integer>m = new HashMap<Integer, Integer>();"
},
{
"code": null,
"e": 1374,
"s": 1334,
"text": "Now, add some elements to the HashMap −"
},
{
"code": null,
"e": 1501,
"s": 1374,
"text": "m.put(10, 20);\nm.put(30, 40);\nm.put(50, 60);\nm.put(70, 80);\nm.put(90, 100);\nm.put(110, 120);\nm.put(130, 140);\nm.put(150, 160);"
},
{
"code": null,
"e": 1544,
"s": 1501,
"text": "Now, extract the values from the HashMap −"
},
{
"code": null,
"e": 1609,
"s": 1544,
"text": "for (Integer i: m.keySet()) {\n System.out.println(m.get(i));\n}"
},
{
"code": null,
"e": 1620,
"s": 1609,
"text": " Live Demo"
},
{
"code": null,
"e": 2106,
"s": 1620,
"text": "import java.util.HashMap;\npublic class Demo {\n public static void main(String args[]) {\n HashMap<Integer, Integer>m = new HashMap<Integer, Integer>();\n m.put(10, 20);\n m.put(30, 40);\n m.put(50, 60);\n m.put(70, 80);\n m.put(90, 100);\n m.put(110, 120);\n m.put(130, 140);\n m.put(150, 160);\n System.out.println(\"Displaying values from HashMap...\");\n for (Integer i: m.keySet()) {\n System.out.println(m.get(i));\n }\n }\n}"
},
{
"code": null,
"e": 2168,
"s": 2106,
"text": "Displaying values from HashMap...\n60\n140\n80\n160\n20\n100\n40\n120"
}
] |
List clear() method in Java with Examples
|
11 Dec, 2018
The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.
Syntax:
public void clear()
Parameter: This method accepts does not accepts any parameter.
Return Value: The return type of the function is void and it does not returns anything.
Exceptions: This method throws an UnsupportedOperationException if the clear() operation is not supported by this list.
Below programs illustrate the List.clear() method:
Program 1:
// Java code to illustrate clear() methodimport java.io.*;import java.util.*; public class ListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<String> list = new ArrayList<String>(5); // use add() method to initially // add elements in the list list.add("Geeks"); list.add("For"); list.add("Geeks"); // Remove all elements from the List list.clear(); // print the List System.out.println(list); }}
[]
Program 2:
// Java code to illustrate clear() methodimport java.io.*;import java.util.*; public class ListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<Integer> list = new ArrayList<Integer>(5); // use add() method to initially // add elements in the list list.add(10); list.add(20); list.add(30); // clear the list list.clear(); // prints all the elements available in list System.out.println(list); }}
[]
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List."
},
{
"code": null,
"e": 253,
"s": 245,
"text": "Syntax:"
},
{
"code": null,
"e": 273,
"s": 253,
"text": "public void clear()"
},
{
"code": null,
"e": 336,
"s": 273,
"text": "Parameter: This method accepts does not accepts any parameter."
},
{
"code": null,
"e": 424,
"s": 336,
"text": "Return Value: The return type of the function is void and it does not returns anything."
},
{
"code": null,
"e": 544,
"s": 424,
"text": "Exceptions: This method throws an UnsupportedOperationException if the clear() operation is not supported by this list."
},
{
"code": null,
"e": 595,
"s": 544,
"text": "Below programs illustrate the List.clear() method:"
},
{
"code": null,
"e": 606,
"s": 595,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate clear() methodimport java.io.*;import java.util.*; public class ListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<String> list = new ArrayList<String>(5); // use add() method to initially // add elements in the list list.add(\"Geeks\"); list.add(\"For\"); list.add(\"Geeks\"); // Remove all elements from the List list.clear(); // print the List System.out.println(list); }}",
"e": 1153,
"s": 606,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1153,
"text": "[]\n"
},
{
"code": null,
"e": 1168,
"s": 1157,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate clear() methodimport java.io.*;import java.util.*; public class ListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<Integer> list = new ArrayList<Integer>(5); // use add() method to initially // add elements in the list list.add(10); list.add(20); list.add(30); // clear the list list.clear(); // prints all the elements available in list System.out.println(list); }}",
"e": 1712,
"s": 1168,
"text": null
},
{
"code": null,
"e": 1716,
"s": 1712,
"text": "[]\n"
},
{
"code": null,
"e": 1797,
"s": 1716,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()"
},
{
"code": null,
"e": 1814,
"s": 1797,
"text": "Java-Collections"
},
{
"code": null,
"e": 1829,
"s": 1814,
"text": "Java-Functions"
},
{
"code": null,
"e": 1839,
"s": 1829,
"text": "java-list"
},
{
"code": null,
"e": 1844,
"s": 1839,
"text": "Java"
},
{
"code": null,
"e": 1849,
"s": 1844,
"text": "Java"
},
{
"code": null,
"e": 1866,
"s": 1849,
"text": "Java-Collections"
}
] |
ML – Gradient Boosting
|
02 Sep, 2020
Gradient Boosting is a popular boosting algorithm. In gradient boosting, each predictor corrects its predecessor’s error. In contrast to Adaboost, the weights of the training instances are not tweaked, instead, each predictor is trained using the residual errors of predecessor as labels.
There is a technique called the Gradient Boosted Trees whose base learner is CART (Classification and Regression Trees).
The below diagram explains how gradient boosted trees are trained for regression problems.
Gradient Boosted Trees for Regression
The ensemble consists of N trees. Tree1 is trained using the feature matrix X and the labels y. The predictions labelled y1(hat) are used to determine the training set residual errors r1. Tree2 is then trained using the feature matrix X and the residual errors r1 of Tree1 as labels. The predicted results r1(hat) are then used to determine the residual r2. The process is repeated until all the N trees forming the ensemble are trained.
There is an important parameter used in this technique known as Shrinkage.
Each tree predicts a label and final prediction is given by the formula,
y(pred) = y1 + (eta * r1) + (eta * r2) + ....... + (eta * rN)
The class of the gradient boosting regression in scikit-learn is GradientBoostingRegressor. A similar algorithm is used for classification known as GradientBoostingClassifier.
Code: Python code for Gradient Boosting Regressor
# Import models and utility functionsfrom sklearn.ensemble import GradientBoostingRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error as MSEfrom sklearn import datasets # Setting SEED for reproducibilitySEED = 1 # Importing the dataset bike = datasets.load_bike()X, y = bike.data, bike.target # Splitting datasettrain_X, test_X, train_y, test_y = train_test_split(X, y, test_size = 0.3, random_state = SEED) # Instantiate Gradient Boosting Regressorgbr = GradientBoostingRegressor(n_estimators = 200, max_depth = 1, random_state = SEED) # Fit to training setgbr.fit(train_X, train_y) # Predict on test setpred_y = gbr.predict(test_X) # test set RMSEtest_rmse = MSE(test_y, pred_y) ** (1 / 2) # Print rmseprint('RMSE test set: {:.2f}'.format(test_rmse))
Output:
RMSE test set: 4.01
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Support Vector Machine Algorithm
Elbow Method for optimal value of k in KMeans
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": 52,
"s": 24,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 341,
"s": 52,
"text": "Gradient Boosting is a popular boosting algorithm. In gradient boosting, each predictor corrects its predecessor’s error. In contrast to Adaboost, the weights of the training instances are not tweaked, instead, each predictor is trained using the residual errors of predecessor as labels."
},
{
"code": null,
"e": 462,
"s": 341,
"text": "There is a technique called the Gradient Boosted Trees whose base learner is CART (Classification and Regression Trees)."
},
{
"code": null,
"e": 553,
"s": 462,
"text": "The below diagram explains how gradient boosted trees are trained for regression problems."
},
{
"code": null,
"e": 591,
"s": 553,
"text": "Gradient Boosted Trees for Regression"
},
{
"code": null,
"e": 1029,
"s": 591,
"text": "The ensemble consists of N trees. Tree1 is trained using the feature matrix X and the labels y. The predictions labelled y1(hat) are used to determine the training set residual errors r1. Tree2 is then trained using the feature matrix X and the residual errors r1 of Tree1 as labels. The predicted results r1(hat) are then used to determine the residual r2. The process is repeated until all the N trees forming the ensemble are trained."
},
{
"code": null,
"e": 1104,
"s": 1029,
"text": "There is an important parameter used in this technique known as Shrinkage."
},
{
"code": null,
"e": 1177,
"s": 1104,
"text": "Each tree predicts a label and final prediction is given by the formula,"
},
{
"code": null,
"e": 1242,
"s": 1177,
"text": "y(pred) = y1 + (eta * r1) + (eta * r2) + ....... + (eta * rN)\n\n"
},
{
"code": null,
"e": 1418,
"s": 1242,
"text": "The class of the gradient boosting regression in scikit-learn is GradientBoostingRegressor. A similar algorithm is used for classification known as GradientBoostingClassifier."
},
{
"code": null,
"e": 1468,
"s": 1418,
"text": "Code: Python code for Gradient Boosting Regressor"
},
{
"code": "# Import models and utility functionsfrom sklearn.ensemble import GradientBoostingRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error as MSEfrom sklearn import datasets # Setting SEED for reproducibilitySEED = 1 # Importing the dataset bike = datasets.load_bike()X, y = bike.data, bike.target # Splitting datasettrain_X, test_X, train_y, test_y = train_test_split(X, y, test_size = 0.3, random_state = SEED) # Instantiate Gradient Boosting Regressorgbr = GradientBoostingRegressor(n_estimators = 200, max_depth = 1, random_state = SEED) # Fit to training setgbr.fit(train_X, train_y) # Predict on test setpred_y = gbr.predict(test_X) # test set RMSEtest_rmse = MSE(test_y, pred_y) ** (1 / 2) # Print rmseprint('RMSE test set: {:.2f}'.format(test_rmse))",
"e": 2285,
"s": 1468,
"text": null
},
{
"code": null,
"e": 2293,
"s": 2285,
"text": "Output:"
},
{
"code": null,
"e": 2314,
"s": 2293,
"text": "RMSE test set: 4.01\n"
},
{
"code": null,
"e": 2331,
"s": 2314,
"text": "Machine Learning"
},
{
"code": null,
"e": 2338,
"s": 2331,
"text": "Python"
},
{
"code": null,
"e": 2355,
"s": 2338,
"text": "Machine Learning"
},
{
"code": null,
"e": 2453,
"s": 2355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2476,
"s": 2453,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 2517,
"s": 2476,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 2553,
"s": 2517,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2586,
"s": 2553,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 2632,
"s": 2586,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 2660,
"s": 2632,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2710,
"s": 2660,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2732,
"s": 2710,
"text": "Python map() function"
}
] |
How to Plot a Smooth Line using ggplot2 in R ?
|
02 Jul, 2021
In this article, we will learn how to plot a smooth line using ggplot2 in R Programming Language.
We will be using the “USArrests” data set as a sample dataset for this article.
Murder Assault UrbanPop Rape
Alabama 13.2 236 58 21.2
Alaska 10.0 263 48 44.5
Arizona 8.1 294 80 31.0
Arkansas 8.8 190 50 19.5
California 9.0 276 91 40.6
Colorado 7.9 204 78 38.7
Let us first plot the regression line.
Syntax:
geom_smooth(method=lm)
We have used geom_smooth() function to add a regression line to our scatter plot by providing “method=lm” as an argument. We have set method=lm as lm stands for Linear Model, which plots a linear regression line.
But we can see in the below example that although the Linear regression line is a best-fit line however it is not a smooth line. Further in this article, we will see how we can plot a smooth line using multiple approaches.
Example:
R
library(ggplot2) plot <- ggplot(USArrests, aes(Murder,Assault)) + geom_point() plot + geom_smooth(method = lm)
Output:
We can plot a smooth line using the “loess” method of the geom_smooth() function. The only difference, in this case, is that we have passed method=loess, unlike lm in the previous case. Here, “loess” stands for “local regression fitting“. This method plots a smooth local regression line.
Syntax:
geom_smooth(method = loess)
Example:
R
library(ggplot2) plot <- ggplot(USArrests, aes(Murder,Assault)) + geom_point() plot + geom_smooth(method = loess)
Output:
We can also use the formula: y~ploy(x,3), along with the linear model method, which gives us the same smooth line as in the previous example. Pass “se” as FALSE in the argument. By default, the value of “se” remains TRUE, which results in plotting a confidence interval around the smooth line.
Syntax:
geom_smooth(method = “lm”, formula = y ~ poly(x, 3), se = FALSE)
Example:
R
library(ggplot2) plot <- ggplot(USArrests, aes(Murder,Assault)) + geom_point() plot + geom_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE)
Output:
stat_smooth() and geom_smooth() both are aliases. Both of them have the same arguments and both of them are used to plot a smooth line. We can plot a smooth line using the “loess” method of stat_smooth() function. The only difference, in this case, is that we have passed method=loess, unlike lm in the previous case. Here, “loess” stands for “local regression fitting”. This method plots a smooth local regression line.
Syntax:
stat_smooth(method = loess)
Example:
R
library(ggplot2) plot <- ggplot(USArrests, aes(Murder, Assault)) + geom_point() plot + stat_smooth(method = loess)
Output:
Spline regression is a better method as it overcomes the shortcomings of Polynomial Regression as Polynomial Regression was only able to express a particular amount of curvature. In simple words, splines are piecewise polynomial functions.
To draw a spline use the spline function when passing the dataframe for plotting.
Syntax:
spline( attributes )
Example:
R
library(ggplot2) spline.d <- as.data.frame(spline(USArrests$Murder, USArrests$Assault)) plot <- ggplot(USArrests, aes(x = Murder, y = Assault))+geom_point() +geom_line(data = spline.d, aes(x = x, y = y))plot
Output:
sudhanshublaze
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 151,
"s": 53,
"text": "In this article, we will learn how to plot a smooth line using ggplot2 in R Programming Language."
},
{
"code": null,
"e": 231,
"s": 151,
"text": "We will be using the “USArrests” data set as a sample dataset for this article."
},
{
"code": null,
"e": 501,
"s": 231,
"text": " Murder Assault UrbanPop Rape\nAlabama 13.2 236 58 21.2\nAlaska 10.0 263 48 44.5\nArizona 8.1 294 80 31.0\nArkansas 8.8 190 50 19.5\nCalifornia 9.0 276 91 40.6\nColorado 7.9 204 78 38.7"
},
{
"code": null,
"e": 540,
"s": 501,
"text": "Let us first plot the regression line."
},
{
"code": null,
"e": 549,
"s": 540,
"text": "Syntax: "
},
{
"code": null,
"e": 572,
"s": 549,
"text": "geom_smooth(method=lm)"
},
{
"code": null,
"e": 786,
"s": 572,
"text": "We have used geom_smooth() function to add a regression line to our scatter plot by providing “method=lm” as an argument. We have set method=lm as lm stands for Linear Model, which plots a linear regression line."
},
{
"code": null,
"e": 1009,
"s": 786,
"text": "But we can see in the below example that although the Linear regression line is a best-fit line however it is not a smooth line. Further in this article, we will see how we can plot a smooth line using multiple approaches."
},
{
"code": null,
"e": 1018,
"s": 1009,
"text": "Example:"
},
{
"code": null,
"e": 1020,
"s": 1018,
"text": "R"
},
{
"code": "library(ggplot2) plot <- ggplot(USArrests, aes(Murder,Assault)) + geom_point() plot + geom_smooth(method = lm)",
"e": 1131,
"s": 1020,
"text": null
},
{
"code": null,
"e": 1143,
"s": 1135,
"text": "Output:"
},
{
"code": null,
"e": 1436,
"s": 1147,
"text": "We can plot a smooth line using the “loess” method of the geom_smooth() function. The only difference, in this case, is that we have passed method=loess, unlike lm in the previous case. Here, “loess” stands for “local regression fitting“. This method plots a smooth local regression line."
},
{
"code": null,
"e": 1447,
"s": 1438,
"text": "Syntax: "
},
{
"code": null,
"e": 1477,
"s": 1449,
"text": "geom_smooth(method = loess)"
},
{
"code": null,
"e": 1488,
"s": 1479,
"text": "Example:"
},
{
"code": null,
"e": 1492,
"s": 1490,
"text": "R"
},
{
"code": "library(ggplot2) plot <- ggplot(USArrests, aes(Murder,Assault)) + geom_point() plot + geom_smooth(method = loess)",
"e": 1606,
"s": 1492,
"text": null
},
{
"code": null,
"e": 1618,
"s": 1610,
"text": "Output:"
},
{
"code": null,
"e": 1917,
"s": 1622,
"text": "We can also use the formula: y~ploy(x,3), along with the linear model method, which gives us the same smooth line as in the previous example. Pass “se” as FALSE in the argument. By default, the value of “se” remains TRUE, which results in plotting a confidence interval around the smooth line. "
},
{
"code": null,
"e": 1928,
"s": 1919,
"text": "Syntax: "
},
{
"code": null,
"e": 1995,
"s": 1930,
"text": "geom_smooth(method = “lm”, formula = y ~ poly(x, 3), se = FALSE)"
},
{
"code": null,
"e": 2006,
"s": 1997,
"text": "Example:"
},
{
"code": null,
"e": 2010,
"s": 2008,
"text": "R"
},
{
"code": "library(ggplot2) plot <- ggplot(USArrests, aes(Murder,Assault)) + geom_point() plot + geom_smooth(method = \"lm\", formula = y ~ poly(x, 3), se = FALSE)",
"e": 2161,
"s": 2010,
"text": null
},
{
"code": null,
"e": 2169,
"s": 2161,
"text": "Output:"
},
{
"code": null,
"e": 2590,
"s": 2169,
"text": "stat_smooth() and geom_smooth() both are aliases. Both of them have the same arguments and both of them are used to plot a smooth line. We can plot a smooth line using the “loess” method of stat_smooth() function. The only difference, in this case, is that we have passed method=loess, unlike lm in the previous case. Here, “loess” stands for “local regression fitting”. This method plots a smooth local regression line."
},
{
"code": null,
"e": 2599,
"s": 2590,
"text": "Syntax: "
},
{
"code": null,
"e": 2627,
"s": 2599,
"text": "stat_smooth(method = loess)"
},
{
"code": null,
"e": 2636,
"s": 2627,
"text": "Example:"
},
{
"code": null,
"e": 2638,
"s": 2636,
"text": "R"
},
{
"code": "library(ggplot2) plot <- ggplot(USArrests, aes(Murder, Assault)) + geom_point() plot + stat_smooth(method = loess)",
"e": 2753,
"s": 2638,
"text": null
},
{
"code": null,
"e": 2765,
"s": 2757,
"text": "Output:"
},
{
"code": null,
"e": 3009,
"s": 2769,
"text": "Spline regression is a better method as it overcomes the shortcomings of Polynomial Regression as Polynomial Regression was only able to express a particular amount of curvature. In simple words, splines are piecewise polynomial functions."
},
{
"code": null,
"e": 3093,
"s": 3011,
"text": "To draw a spline use the spline function when passing the dataframe for plotting."
},
{
"code": null,
"e": 3104,
"s": 3095,
"text": "Syntax: "
},
{
"code": null,
"e": 3127,
"s": 3106,
"text": "spline( attributes )"
},
{
"code": null,
"e": 3138,
"s": 3129,
"text": "Example:"
},
{
"code": null,
"e": 3142,
"s": 3140,
"text": "R"
},
{
"code": "library(ggplot2) spline.d <- as.data.frame(spline(USArrests$Murder, USArrests$Assault)) plot <- ggplot(USArrests, aes(x = Murder, y = Assault))+geom_point() +geom_line(data = spline.d, aes(x = x, y = y))plot",
"e": 3350,
"s": 3142,
"text": null
},
{
"code": null,
"e": 3358,
"s": 3350,
"text": "Output:"
},
{
"code": null,
"e": 3373,
"s": 3358,
"text": "sudhanshublaze"
},
{
"code": null,
"e": 3380,
"s": 3373,
"text": "Picked"
},
{
"code": null,
"e": 3389,
"s": 3380,
"text": "R-ggplot"
},
{
"code": null,
"e": 3400,
"s": 3389,
"text": "R Language"
}
] |
Mathematics | Introduction of Set theory
|
28 Jun, 2021
A Set is an unordered collection of objects, known as elements or members of the set.An element ‘a’ belong to a set A can be written as ‘a ∈ A’, ‘a ∉ A’ denotes that a is not an element of the set A.
Representation of a SetA set can be represented by various methods. 3 common methods used for representing set:1. Statement form.2. Roaster form or tabular form method.3. Set Builder method.
Statement formIn this representation, the well-defined description of the elements of the set is given. Below are some examples of the same.1. The set of all even number less than 10.2. The set of the number less than 10 and more than 1.
Roster formIn this representation, elements are listed within the pair of brackets {} and are separated by commas. Below are two examples.1. Let N is the set of natural numbers less than 5.N = { 1 , 2 , 3, 4 }.
2. The set of all vowels in the English alphabet.V = { a , e , i , o , u }.
Set builder formIn Set-builder set is described by a property that its member must satisfy.1. {x : x is even number divisible by 6 and less than 100}.2. {x : x is natural number less than 10}.
Equal setsTwo sets are said to be equal if both have same elements. For example A = {1, 3, 9, 7} and B = {3, 1, 7, 9} are equal sets.
NOTE: Order of elements of a set doesn’t matter.
Subset
A set A is said to be subset of another set B if and only if every element of set A is also a part of other set B.Denoted by ‘⊆‘.‘A ⊆ B ‘ denotes A is a subset of B.
To prove A is the subset of B, we need to simply show that if x belongs to A then x also belongs to B.To prove A is not a subset of B, we need to find out one element which is part of set A but not belong to set B.
‘U’ denotes the universal set.Above Venn Diagram shows that A is a subset of B.
Size of a SetSize of a set can be finite or infinite.
For example
Finite set: Set of natural numbers less than 100.
Infinite set: Set of real numbers.
Size of the set S is known as Cardinality number, denoted as |S|.
Example: Let A be a set of odd positive integers less than 10.Solution : A = {1,3,5,7,9}, Cardinality of the set is 5, i.e.,|A| = 5.
Note: Cardinality of a null set is 0.
Power SetsThe power set is the set all possible subset of the set S. Denoted by P(S).Example: What is the power set of {0,1,2}?Solution: All possible subsets{∅}, {0}, {1}, {2}, {0,1}, {0,2}, {1,2}, {0,1,2}.Note: Empty set and set itself is also the member of this set of subsets.
Cardinality of power set is
, where n is the number of elements in a set.
Cartesian ProductsLet A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered pairs (a,b), where a belong to A and b belong to B.
A × B = {(a, b) | a ∈ A ∧ b ∈ B}.
Example 1. What is Cartesian product of A = {1,2} and B = {p, q, r}.Solution : A × B ={(1, p), (1, q), (1, r), (2, p), (2, q), (2, r) };
The cardinality of A × B is N*M, where N is the Cardinality of A and M is the cardinality of B.
Note: A × B is not the same as B × A.
Below are some Gate Previous question
https://www.geeksforgeeks.org/gate-gate-cs-2015-set-2-question-28/
https://www.geeksforgeeks.org/gate-gate-cs-2015-set-1-question-26/
Set Theory continue..
References
https://en.wikipedia.org/wiki/Cartesian_product
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
stewardmailler
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Various Implicants in K-Map
Inequalities in LaTeX
Representation of Boolean Functions
Mutual exclusion in distributed system
Three address code in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Types of Operating Systems
Code Optimization in Compiler Design
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 254,
"s": 52,
"text": "A Set is an unordered collection of objects, known as elements or members of the set.An element ‘a’ belong to a set A can be written as ‘a ∈ A’, ‘a ∉ A’ denotes that a is not an element of the set A."
},
{
"code": null,
"e": 447,
"s": 256,
"text": "Representation of a SetA set can be represented by various methods. 3 common methods used for representing set:1. Statement form.2. Roaster form or tabular form method.3. Set Builder method."
},
{
"code": null,
"e": 689,
"s": 451,
"text": "Statement formIn this representation, the well-defined description of the elements of the set is given. Below are some examples of the same.1. The set of all even number less than 10.2. The set of the number less than 10 and more than 1."
},
{
"code": null,
"e": 902,
"s": 691,
"text": "Roster formIn this representation, elements are listed within the pair of brackets {} and are separated by commas. Below are two examples.1. Let N is the set of natural numbers less than 5.N = { 1 , 2 , 3, 4 }."
},
{
"code": null,
"e": 978,
"s": 902,
"text": "2. The set of all vowels in the English alphabet.V = { a , e , i , o , u }."
},
{
"code": null,
"e": 1173,
"s": 980,
"text": "Set builder formIn Set-builder set is described by a property that its member must satisfy.1. {x : x is even number divisible by 6 and less than 100}.2. {x : x is natural number less than 10}."
},
{
"code": null,
"e": 1309,
"s": 1175,
"text": "Equal setsTwo sets are said to be equal if both have same elements. For example A = {1, 3, 9, 7} and B = {3, 1, 7, 9} are equal sets."
},
{
"code": null,
"e": 1358,
"s": 1309,
"text": "NOTE: Order of elements of a set doesn’t matter."
},
{
"code": null,
"e": 1367,
"s": 1360,
"text": "Subset"
},
{
"code": null,
"e": 1533,
"s": 1367,
"text": "A set A is said to be subset of another set B if and only if every element of set A is also a part of other set B.Denoted by ‘⊆‘.‘A ⊆ B ‘ denotes A is a subset of B."
},
{
"code": null,
"e": 1748,
"s": 1533,
"text": "To prove A is the subset of B, we need to simply show that if x belongs to A then x also belongs to B.To prove A is not a subset of B, we need to find out one element which is part of set A but not belong to set B."
},
{
"code": null,
"e": 1828,
"s": 1748,
"text": "‘U’ denotes the universal set.Above Venn Diagram shows that A is a subset of B."
},
{
"code": null,
"e": 1884,
"s": 1830,
"text": "Size of a SetSize of a set can be finite or infinite."
},
{
"code": null,
"e": 1896,
"s": 1884,
"text": "For example"
},
{
"code": null,
"e": 1981,
"s": 1896,
"text": "Finite set: Set of natural numbers less than 100.\nInfinite set: Set of real numbers."
},
{
"code": null,
"e": 2047,
"s": 1981,
"text": "Size of the set S is known as Cardinality number, denoted as |S|."
},
{
"code": null,
"e": 2180,
"s": 2047,
"text": "Example: Let A be a set of odd positive integers less than 10.Solution : A = {1,3,5,7,9}, Cardinality of the set is 5, i.e.,|A| = 5."
},
{
"code": null,
"e": 2218,
"s": 2180,
"text": "Note: Cardinality of a null set is 0."
},
{
"code": null,
"e": 2500,
"s": 2220,
"text": "Power SetsThe power set is the set all possible subset of the set S. Denoted by P(S).Example: What is the power set of {0,1,2}?Solution: All possible subsets{∅}, {0}, {1}, {2}, {0,1}, {0,2}, {1,2}, {0,1,2}.Note: Empty set and set itself is also the member of this set of subsets."
},
{
"code": null,
"e": 2530,
"s": 2502,
"text": "Cardinality of power set is"
},
{
"code": null,
"e": 2576,
"s": 2530,
"text": ", where n is the number of elements in a set."
},
{
"code": null,
"e": 2749,
"s": 2578,
"text": "Cartesian ProductsLet A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered pairs (a,b), where a belong to A and b belong to B."
},
{
"code": null,
"e": 2783,
"s": 2749,
"text": "A × B = {(a, b) | a ∈ A ∧ b ∈ B}."
},
{
"code": null,
"e": 2920,
"s": 2783,
"text": "Example 1. What is Cartesian product of A = {1,2} and B = {p, q, r}.Solution : A × B ={(1, p), (1, q), (1, r), (2, p), (2, q), (2, r) };"
},
{
"code": null,
"e": 3017,
"s": 2920,
"text": "The cardinality of A × B is N*M, where N is the Cardinality of A and M is the cardinality of B."
},
{
"code": null,
"e": 3055,
"s": 3017,
"text": "Note: A × B is not the same as B × A."
},
{
"code": null,
"e": 3097,
"s": 3059,
"text": "Below are some Gate Previous question"
},
{
"code": null,
"e": 3164,
"s": 3097,
"text": "https://www.geeksforgeeks.org/gate-gate-cs-2015-set-2-question-28/"
},
{
"code": null,
"e": 3231,
"s": 3164,
"text": "https://www.geeksforgeeks.org/gate-gate-cs-2015-set-1-question-26/"
},
{
"code": null,
"e": 3255,
"s": 3233,
"text": "Set Theory continue.."
},
{
"code": null,
"e": 3266,
"s": 3255,
"text": "References"
},
{
"code": null,
"e": 3314,
"s": 3266,
"text": "https://en.wikipedia.org/wiki/Cartesian_product"
},
{
"code": null,
"e": 3438,
"s": 3314,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 3453,
"s": 3438,
"text": "stewardmailler"
},
{
"code": null,
"e": 3477,
"s": 3453,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 3485,
"s": 3477,
"text": "GATE CS"
},
{
"code": null,
"e": 3583,
"s": 3485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3642,
"s": 3583,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 3665,
"s": 3642,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 3693,
"s": 3665,
"text": "Various Implicants in K-Map"
},
{
"code": null,
"e": 3715,
"s": 3693,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 3751,
"s": 3715,
"text": "Representation of Boolean Functions"
},
{
"code": null,
"e": 3790,
"s": 3751,
"text": "Mutual exclusion in distributed system"
},
{
"code": null,
"e": 3821,
"s": 3790,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 3891,
"s": 3821,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 3918,
"s": 3891,
"text": "Types of Operating Systems"
}
] |
Ternary contours Plot using Plotly in Python
|
01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, ternary contours plot can be made by using the create_ternary_contour method of figure_factory class which helps to represent the isovalues lines which are defined inside the ternary diagram, where the sum of three variables is constant. It graphically depicts the ratios of the three variables as positions in an equilateral triangle.
Syntax: create_ternary_contour(coordinates, values, pole_labels=[‘a’, ‘b’, ‘c’],ncontours=None, interp_mode=’ilr’, showmarkers=False)
Example:
Python3
import plotly.figure_factory as ffimport numpy as np test_data = np.array([[0, 0, 1, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 1], [0.25, 0.5, 0.25, 1], [0, 1, 0, 1]]) # barycentric coords: (a,b,c)a = test_data[:, 0]b = test_data[:, 1]c = test_data[:, 2] # values is stored in the last columnv = test_data[:, -1] fig = ff.create_ternary_contour( np.array([a, b, c]), v, pole_labels=['A', 'B', 'C'],) fig.show()
Output:
Height, width, colorscale, and many other values can be customized by using the parameter provided by this function.
Example:
Python3
import plotly.figure_factory as ffimport numpy as np test_data = np.array([[0, 0, 1, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 1], [0.25, 0.5, 0.25, 1], [0, 1, 0, 1]]) # barycentric coords: (a,b,c)a = test_data[:, 0]b = test_data[:, 1]c = test_data[:, 2] # values is stored in the last columnv = test_data[:, -1] fig = ff.create_ternary_contour( np.array([a, b, c]), v, pole_labels=['A', 'B', 'C'], ncontours=20, colorscale='Greens', showscale=True, title='Ternary Contour Plot') fig.show()
Output:
Only lines can be shown by the parameter coloring and setting it to lines and data points can be shown by passing True to the showmarkers parameter.
Example:
Python3
import plotly.figure_factory as ffimport numpy as np test_data = np.array([[0, 0, 1, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 1], [0.25, 0.5, 0.25, 1], [0, 1, 0, 1]]) # barycentric coords: (a,b,c)a = test_data[:, 0]b = test_data[:, 1]c = test_data[:, 2] # values is stored in the last columnv = test_data[:, -1] fig = ff.create_ternary_contour( np.array([a, b, c]), v, pole_labels=['A', 'B', 'C'], ncontours=20, colorscale='Greens', showscale=True, title='Ternary Contour Plot', coloring='lines', showmarkers=True) fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 358,
"s": 54,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 705,
"s": 358,
"text": "In plotly, ternary contours plot can be made by using the create_ternary_contour method of figure_factory class which helps to represent the isovalues lines which are defined inside the ternary diagram, where the sum of three variables is constant. It graphically depicts the ratios of the three variables as positions in an equilateral triangle."
},
{
"code": null,
"e": 840,
"s": 705,
"text": "Syntax: create_ternary_contour(coordinates, values, pole_labels=[‘a’, ‘b’, ‘c’],ncontours=None, interp_mode=’ilr’, showmarkers=False)"
},
{
"code": null,
"e": 849,
"s": 840,
"text": "Example:"
},
{
"code": null,
"e": 857,
"s": 849,
"text": "Python3"
},
{
"code": "import plotly.figure_factory as ffimport numpy as np test_data = np.array([[0, 0, 1, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 1], [0.25, 0.5, 0.25, 1], [0, 1, 0, 1]]) # barycentric coords: (a,b,c)a = test_data[:, 0]b = test_data[:, 1]c = test_data[:, 2] # values is stored in the last columnv = test_data[:, -1] fig = ff.create_ternary_contour( np.array([a, b, c]), v, pole_labels=['A', 'B', 'C'],) fig.show()",
"e": 1408,
"s": 857,
"text": null
},
{
"code": null,
"e": 1416,
"s": 1408,
"text": "Output:"
},
{
"code": null,
"e": 1534,
"s": 1416,
"text": " Height, width, colorscale, and many other values can be customized by using the parameter provided by this function."
},
{
"code": null,
"e": 1543,
"s": 1534,
"text": "Example:"
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Python3"
},
{
"code": "import plotly.figure_factory as ffimport numpy as np test_data = np.array([[0, 0, 1, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 1], [0.25, 0.5, 0.25, 1], [0, 1, 0, 1]]) # barycentric coords: (a,b,c)a = test_data[:, 0]b = test_data[:, 1]c = test_data[:, 2] # values is stored in the last columnv = test_data[:, -1] fig = ff.create_ternary_contour( np.array([a, b, c]), v, pole_labels=['A', 'B', 'C'], ncontours=20, colorscale='Greens', showscale=True, title='Ternary Contour Plot') fig.show()",
"e": 2194,
"s": 1551,
"text": null
},
{
"code": null,
"e": 2202,
"s": 2194,
"text": "Output:"
},
{
"code": null,
"e": 2351,
"s": 2202,
"text": "Only lines can be shown by the parameter coloring and setting it to lines and data points can be shown by passing True to the showmarkers parameter."
},
{
"code": null,
"e": 2360,
"s": 2351,
"text": "Example:"
},
{
"code": null,
"e": 2368,
"s": 2360,
"text": "Python3"
},
{
"code": "import plotly.figure_factory as ffimport numpy as np test_data = np.array([[0, 0, 1, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 0], [0.25, 0.25, 0.5, 1], [0.25, 0.5, 0.25, 1], [0, 1, 0, 1]]) # barycentric coords: (a,b,c)a = test_data[:, 0]b = test_data[:, 1]c = test_data[:, 2] # values is stored in the last columnv = test_data[:, -1] fig = ff.create_ternary_contour( np.array([a, b, c]), v, pole_labels=['A', 'B', 'C'], ncontours=20, colorscale='Greens', showscale=True, title='Ternary Contour Plot', coloring='lines', showmarkers=True) fig.show()",
"e": 3053,
"s": 2368,
"text": null
},
{
"code": null,
"e": 3061,
"s": 3053,
"text": "Output:"
},
{
"code": null,
"e": 3075,
"s": 3061,
"text": "Python-Plotly"
},
{
"code": null,
"e": 3082,
"s": 3075,
"text": "Python"
},
{
"code": null,
"e": 3180,
"s": 3082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3212,
"s": 3180,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3239,
"s": 3212,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3260,
"s": 3239,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3283,
"s": 3260,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3339,
"s": 3283,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3370,
"s": 3339,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3412,
"s": 3370,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3454,
"s": 3412,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3493,
"s": 3454,
"text": "Python | Get unique values from a list"
}
] |
Python | Generate random numbers within a given range and store in a list
|
14 Jan, 2022
Given lower and upper limits, generate a given count of random numbers within a given range, starting from ‘start’ to ‘end’ and store them in list.Examples:
Input : num = 10, start = 20, end = 40
Output : [23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
The output contains 10 random numbers in
range [20, 40].
Input : num = 5, start = 10, end = 15
Output : [15, 11, 15, 12, 11]
The output contains 5 random numbers in
range [10, 15].
Python provides a random module to generate random numbers. To generate random numbers we have used the random function along with the use of the randint function. Syntax:
randint(start, end)
randint accepts two parameters: a starting point and an ending point. Both should be integers and the first value should always be less than the second.
Python3
# Python code to generate# random numbers and# append them to a listimport random # Function to generate# and append them# start = starting range,# end = ending range# num = number of# elements needs to be appendeddef Rand(start, end, num): res = [] for j in range(num): res.append(random.randint(start, end)) return res # Driver Codenum = 10start = 20end = 40print(Rand(start, end, num))
Output:
[23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
Method 2: Using numpy random.randint() method to generate random numbers.
Python3
# Python code to generate# random numbers and# append them to a listimport numpy as npdef Rand(start, end, num): res = [] for j in range(num): res.append(np.random.randint(start, end)) return res # Driver Codenum = 10start = 20end = 40print(Rand(start, end, num))
Output:
[30, 30, 38, 39, 39, 37, 24, 25, 28, 32]
pulamolusaimohan
varshagumber28
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 212,
"s": 53,
"text": "Given lower and upper limits, generate a given count of random numbers within a given range, starting from ‘start’ to ‘end’ and store them in list.Examples: "
},
{
"code": null,
"e": 483,
"s": 212,
"text": "Input : num = 10, start = 20, end = 40\nOutput : [23, 20, 30, 33, 30, 36, 37, 27, 28, 38]\nThe output contains 10 random numbers in\nrange [20, 40].\n\nInput : num = 5, start = 10, end = 15\nOutput : [15, 11, 15, 12, 11]\nThe output contains 5 random numbers in\nrange [10, 15]."
},
{
"code": null,
"e": 659,
"s": 485,
"text": "Python provides a random module to generate random numbers. To generate random numbers we have used the random function along with the use of the randint function. Syntax: "
},
{
"code": null,
"e": 679,
"s": 659,
"text": "randint(start, end)"
},
{
"code": null,
"e": 833,
"s": 679,
"text": "randint accepts two parameters: a starting point and an ending point. Both should be integers and the first value should always be less than the second. "
},
{
"code": null,
"e": 841,
"s": 833,
"text": "Python3"
},
{
"code": "# Python code to generate# random numbers and# append them to a listimport random # Function to generate# and append them# start = starting range,# end = ending range# num = number of# elements needs to be appendeddef Rand(start, end, num): res = [] for j in range(num): res.append(random.randint(start, end)) return res # Driver Codenum = 10start = 20end = 40print(Rand(start, end, num))",
"e": 1248,
"s": 841,
"text": null
},
{
"code": null,
"e": 1258,
"s": 1248,
"text": "Output: "
},
{
"code": null,
"e": 1299,
"s": 1258,
"text": "[23, 20, 30, 33, 30, 36, 37, 27, 28, 38]"
},
{
"code": null,
"e": 1374,
"s": 1299,
"text": "Method 2: Using numpy random.randint() method to generate random numbers."
},
{
"code": null,
"e": 1382,
"s": 1374,
"text": "Python3"
},
{
"code": "# Python code to generate# random numbers and# append them to a listimport numpy as npdef Rand(start, end, num): res = [] for j in range(num): res.append(np.random.randint(start, end)) return res # Driver Codenum = 10start = 20end = 40print(Rand(start, end, num))",
"e": 1665,
"s": 1382,
"text": null
},
{
"code": null,
"e": 1673,
"s": 1665,
"text": "Output:"
},
{
"code": null,
"e": 1714,
"s": 1673,
"text": "[30, 30, 38, 39, 39, 37, 24, 25, 28, 32]"
},
{
"code": null,
"e": 1731,
"s": 1714,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 1746,
"s": 1731,
"text": "varshagumber28"
},
{
"code": null,
"e": 1767,
"s": 1746,
"text": "Python list-programs"
},
{
"code": null,
"e": 1779,
"s": 1767,
"text": "python-list"
},
{
"code": null,
"e": 1786,
"s": 1779,
"text": "Python"
},
{
"code": null,
"e": 1798,
"s": 1786,
"text": "python-list"
},
{
"code": null,
"e": 1896,
"s": 1798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1914,
"s": 1896,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1956,
"s": 1914,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1978,
"s": 1956,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2013,
"s": 1978,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2045,
"s": 2013,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2074,
"s": 2045,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2101,
"s": 2074,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2131,
"s": 2101,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2152,
"s": 2131,
"text": "Python OOPs Concepts"
}
] |
Iterative approach to check if a Binary Tree is BST or not
|
22 Jun, 2021
Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print “YES”. Otherwise, print “NO”.
Examples:
Input:
9
/ \
6 10
/ \ \
4 7 11
/ \ \
3 5 8
Output: YES Explanation: Since the left subtree of each node of the tree consists of smaller valued nodes and the right subtree of each node of the tree consists of larger valued nodes. Therefore, the required is output is “YES”.
Input:
5
/ \
6 3
/ \ \
4 9 2
Output: NO
Recursive Approach: Refer to the previous post to solve this problem using recursion. Time Complexity: O(N) where N is the count of nodes in the Binary Tree. Auxiliary Space: O(N)
Iterative Approach: To solve the problem iteratively, use Stack. Follow the steps below to solve the problem:
Initialize a Stack to store the nodes along with its left subtree.
Initialize a variable, say prev, to store previous visited node of the Binary Tree.
Traverse the tree and push the root node and left subtree of each node into the stack and check if the data value of the prev node is greater than or equal to the data value of the current visited node or not. If found to be true, then print “NO”.
Otherwise, print “YES”.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of a tree nodestruct TreeNode { // Stores data value of a node int data; // Stores left subtree // of a tree node TreeNode* left; // Stores right subtree // of a tree node TreeNode* right; // Initialization of // a tree node TreeNode(int val) { // Update data data = val; // Update left and right left = right = NULL; }}; // Function to check if a binary tree// is binary search tree or notbool checkTreeIsBST(TreeNode *root){ // Stores root node and left // subtree of each node stack<TreeNode* > Stack; // Stores previous visited node TreeNode* prev = NULL; // Traverse the binary tree while (!Stack.empty() || root != NULL) { // Traverse left subtree while (root != NULL) { // Insert root into Stack Stack.push(root); // Update root root = root->left; } // Stores top element of Stack root = Stack.top(); // Remove the top element of Stack Stack.pop(); // If data value of root node less // than data value of left subtree if(prev != NULL && root->data <= prev->data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root->right; } return true;} // Driver Codeint main(){ /* 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 */ // Initialize binary tree TreeNode *root = new TreeNode(9); root->left = new TreeNode(6); root->right = new TreeNode(10); root->left->left = new TreeNode(4); root->left->right = new TreeNode(7); root->right->right = new TreeNode(11); root->left->left->left = new TreeNode(3); root->left->left->right = new TreeNode(5); root->left->right->right = new TreeNode(8); if (checkTreeIsBST(root)) { cout<<"YES"; } else { cout<<"NO"; }}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Structure of a tree nodestatic class TreeNode { // Stores data value of a node int data; // Stores left subtree // of a tree node TreeNode left; // Stores right subtree // of a tree node TreeNode right; // Initialization of // a tree node TreeNode(int val) { // Update data data = val; // Update left and right left = right = null; }}; // Function to check if a binary tree// is binary search tree or notstatic boolean checkTreeIsBST(TreeNode root){ // Stores root node and left // subtree of each node Stack<TreeNode > Stack = new Stack<TreeNode >(); // Stores previous visited node TreeNode prev = null; // Traverse the binary tree while (!Stack.isEmpty() || root != null) { // Traverse left subtree while (root != null) { // Insert root into Stack Stack.add(root); // Update root root = root.left; } // Stores top element of Stack root = Stack.peek(); // Remove the top element of Stack Stack.pop(); // If data value of root node less // than data value of left subtree if(prev != null && root.data <= prev.data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root.right; } return true;} // Driver Codepublic static void main(String[] args){ /* 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 */ // Initialize binary tree TreeNode root = new TreeNode(9); root.left = new TreeNode(6); root.right = new TreeNode(10); root.left.left = new TreeNode(4); root.left.right = new TreeNode(7); root.right.right = new TreeNode(11); root.left.left.left = new TreeNode(3); root.left.left.right = new TreeNode(5); root.left.right.right = new TreeNode(8); if (checkTreeIsBST(root)) { System.out.print("YES"); } else { System.out.print("NO"); }}}// This code is contributed by Amit Katiyar
# Python3 program to implement# the above approach # Structure of a tree nodeclass TreeNode: def __init__(self, data: int) -> None: # Stores data value of a node self.data = data # Stores left subtree # of a tree node self.left = None # Stores right subtree # of a tree node self.right = None # Function to check if a binary tree# is binary search tree or notdef checkTreeIsBST(root: TreeNode) -> bool: # Stores root node and left # subtree of each node Stack = [] # Stores previous visited node prev = None # Traverse the binary tree while (Stack or root): # Traverse left subtree while root: # Insert root into Stack Stack.append(root) # Update root root = root.left # Stores top element of Stack # Remove the top element of Stack root = Stack.pop() # If data value of root node less # than data value of left subtree if (prev and root.data <= prev.data): return False # Update prev prev = root # Traverse right subtree # of the tree root = root.right return True # Driver Codeif __name__ == "__main__": ''' 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 ''' # Initialize binary tree root = TreeNode(9) root.left = TreeNode(6) root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(7) root.right.right = TreeNode(11) root.left.left.left = TreeNode(3) root.left.left.right = TreeNode(5) root.left.right.right = TreeNode(8) if checkTreeIsBST(root): print("YES") else: print("NO") # This code is contributed by sanjeev2552
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Structure of a tree nodeclass TreeNode{ // Stores data value of a node public int data; // Stores left subtree // of a tree node public TreeNode left; // Stores right subtree // of a tree node public TreeNode right; // Initialization of // a tree node public TreeNode(int val) { // Update data data = val; // Update left and right left = right = null; }}; // Function to check if a binary tree// is binary search tree or notstatic bool checkTreeIsBST(TreeNode root){ // Stores root node and left // subtree of each node Stack<TreeNode > Stack = new Stack<TreeNode >(); // Stores previous visited node TreeNode prev = null; // Traverse the binary tree while (Stack.Count!=0 || root != null) { // Traverse left subtree while (root != null) { // Insert root into Stack Stack.Push(root); // Update root root = root.left; } // Stores top element of Stack root = Stack.Peek(); // Remove the top element of Stack Stack.Pop(); // If data value of root node less // than data value of left subtree if(prev != null && root.data <= prev.data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root.right; } return true;} // Driver Codepublic static void Main(String[] args){ /* 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 */ // Initialize binary tree TreeNode root = new TreeNode(9); root.left = new TreeNode(6); root.right = new TreeNode(10); root.left.left = new TreeNode(4); root.left.right = new TreeNode(7); root.right.right = new TreeNode(11); root.left.left.left = new TreeNode(3); root.left.left.right = new TreeNode(5); root.left.right.right = new TreeNode(8); if (checkTreeIsBST(root)) { Console.Write("YES"); } else { Console.Write("NO"); }}} // This code is contributed by shikhasingrajput
<script> // Javascript program to implement// the above approach // Structure of a tree nodeclass TreeNode{ constructor(val) { // Stores left subtree // of a tree node this.left = null; // Stores right subtree // of a tree node this.right = null; // Stores data value of a node this.data = val; }} // Function to check if a binary tree// is binary search tree or notfunction checkTreeIsBST(root){ // Stores root node and left // subtree of each node let Stack = []; // Stores previous visited node let prev = null; // Traverse the binary tree while (Stack.length > 0 || root != null) { // Traverse left subtree while (root != null) { // Insert root into Stack Stack.push(root); // Update root root = root.left; } // Stores top element of Stack root = Stack[Stack.length - 1]; // Remove the top element of Stack Stack.pop(); // If data value of root node less // than data value of left subtree if (prev != null && root.data <= prev.data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root.right; } return true;} // Driver code/* 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 */ // Initialize binary treelet root = new TreeNode(9);root.left = new TreeNode(6);root.right = new TreeNode(10);root.left.left = new TreeNode(4);root.left.right = new TreeNode(7);root.right.right = new TreeNode(11);root.left.left.left = new TreeNode(3);root.left.left.right = new TreeNode(5);root.left.right.right = new TreeNode(8); if (checkTreeIsBST(root)){ document.write("YES");}else{ document.write("NO");} // This code is contributed by divyeshrabadiya07 </script>
YES
Time Complexity: O(N), where N is count of nodes in the binary tree Auxiliary Space: O(N)
amit143katiyar
shikhasingrajput
sanjeev2552
divyeshrabadiya07
Binary Search Trees
Binary Tree
BST
Inorder Traversal
Stack
Tree
Stack
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Next Smaller Element
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print “YES”. Otherwise, print “NO”."
},
{
"code": null,
"e": 223,
"s": 213,
"text": "Examples:"
},
{
"code": null,
"e": 231,
"s": 223,
"text": "Input: "
},
{
"code": null,
"e": 350,
"s": 231,
"text": " 9\n / \\\n 6 10\n / \\ \\\n 4 7 11\n / \\ \\\n 3 5 8"
},
{
"code": null,
"e": 580,
"s": 350,
"text": "Output: YES Explanation: Since the left subtree of each node of the tree consists of smaller valued nodes and the right subtree of each node of the tree consists of larger valued nodes. Therefore, the required is output is “YES”."
},
{
"code": null,
"e": 589,
"s": 580,
"text": "Input: "
},
{
"code": null,
"e": 674,
"s": 589,
"text": " 5\n / \\\n 6 3\n / \\ \\\n 4 9 2"
},
{
"code": null,
"e": 687,
"s": 674,
"text": "Output: NO "
},
{
"code": null,
"e": 867,
"s": 687,
"text": "Recursive Approach: Refer to the previous post to solve this problem using recursion. Time Complexity: O(N) where N is the count of nodes in the Binary Tree. Auxiliary Space: O(N)"
},
{
"code": null,
"e": 977,
"s": 867,
"text": "Iterative Approach: To solve the problem iteratively, use Stack. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1044,
"s": 977,
"text": "Initialize a Stack to store the nodes along with its left subtree."
},
{
"code": null,
"e": 1128,
"s": 1044,
"text": "Initialize a variable, say prev, to store previous visited node of the Binary Tree."
},
{
"code": null,
"e": 1376,
"s": 1128,
"text": "Traverse the tree and push the root node and left subtree of each node into the stack and check if the data value of the prev node is greater than or equal to the data value of the current visited node or not. If found to be true, then print “NO”."
},
{
"code": null,
"e": 1400,
"s": 1376,
"text": "Otherwise, print “YES”."
},
{
"code": null,
"e": 1451,
"s": 1400,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1455,
"s": 1451,
"text": "C++"
},
{
"code": null,
"e": 1460,
"s": 1455,
"text": "Java"
},
{
"code": null,
"e": 1468,
"s": 1460,
"text": "Python3"
},
{
"code": null,
"e": 1471,
"s": 1468,
"text": "C#"
},
{
"code": null,
"e": 1482,
"s": 1471,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of a tree nodestruct TreeNode { // Stores data value of a node int data; // Stores left subtree // of a tree node TreeNode* left; // Stores right subtree // of a tree node TreeNode* right; // Initialization of // a tree node TreeNode(int val) { // Update data data = val; // Update left and right left = right = NULL; }}; // Function to check if a binary tree// is binary search tree or notbool checkTreeIsBST(TreeNode *root){ // Stores root node and left // subtree of each node stack<TreeNode* > Stack; // Stores previous visited node TreeNode* prev = NULL; // Traverse the binary tree while (!Stack.empty() || root != NULL) { // Traverse left subtree while (root != NULL) { // Insert root into Stack Stack.push(root); // Update root root = root->left; } // Stores top element of Stack root = Stack.top(); // Remove the top element of Stack Stack.pop(); // If data value of root node less // than data value of left subtree if(prev != NULL && root->data <= prev->data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root->right; } return true;} // Driver Codeint main(){ /* 9 / \\ 6 10 / \\ \\ 4 7 11 / \\ \\ 3 5 8 */ // Initialize binary tree TreeNode *root = new TreeNode(9); root->left = new TreeNode(6); root->right = new TreeNode(10); root->left->left = new TreeNode(4); root->left->right = new TreeNode(7); root->right->right = new TreeNode(11); root->left->left->left = new TreeNode(3); root->left->left->right = new TreeNode(5); root->left->right->right = new TreeNode(8); if (checkTreeIsBST(root)) { cout<<\"YES\"; } else { cout<<\"NO\"; }}",
"e": 3655,
"s": 1482,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Structure of a tree nodestatic class TreeNode { // Stores data value of a node int data; // Stores left subtree // of a tree node TreeNode left; // Stores right subtree // of a tree node TreeNode right; // Initialization of // a tree node TreeNode(int val) { // Update data data = val; // Update left and right left = right = null; }}; // Function to check if a binary tree// is binary search tree or notstatic boolean checkTreeIsBST(TreeNode root){ // Stores root node and left // subtree of each node Stack<TreeNode > Stack = new Stack<TreeNode >(); // Stores previous visited node TreeNode prev = null; // Traverse the binary tree while (!Stack.isEmpty() || root != null) { // Traverse left subtree while (root != null) { // Insert root into Stack Stack.add(root); // Update root root = root.left; } // Stores top element of Stack root = Stack.peek(); // Remove the top element of Stack Stack.pop(); // If data value of root node less // than data value of left subtree if(prev != null && root.data <= prev.data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root.right; } return true;} // Driver Codepublic static void main(String[] args){ /* 9 / \\ 6 10 / \\ \\ 4 7 11 / \\ \\ 3 5 8 */ // Initialize binary tree TreeNode root = new TreeNode(9); root.left = new TreeNode(6); root.right = new TreeNode(10); root.left.left = new TreeNode(4); root.left.right = new TreeNode(7); root.right.right = new TreeNode(11); root.left.left.left = new TreeNode(3); root.left.left.right = new TreeNode(5); root.left.right.right = new TreeNode(8); if (checkTreeIsBST(root)) { System.out.print(\"YES\"); } else { System.out.print(\"NO\"); }}}// This code is contributed by Amit Katiyar",
"e": 5925,
"s": 3655,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Structure of a tree nodeclass TreeNode: def __init__(self, data: int) -> None: # Stores data value of a node self.data = data # Stores left subtree # of a tree node self.left = None # Stores right subtree # of a tree node self.right = None # Function to check if a binary tree# is binary search tree or notdef checkTreeIsBST(root: TreeNode) -> bool: # Stores root node and left # subtree of each node Stack = [] # Stores previous visited node prev = None # Traverse the binary tree while (Stack or root): # Traverse left subtree while root: # Insert root into Stack Stack.append(root) # Update root root = root.left # Stores top element of Stack # Remove the top element of Stack root = Stack.pop() # If data value of root node less # than data value of left subtree if (prev and root.data <= prev.data): return False # Update prev prev = root # Traverse right subtree # of the tree root = root.right return True # Driver Codeif __name__ == \"__main__\": ''' 9 / \\ 6 10 / \\ \\ 4 7 11 / \\ \\ 3 5 8 ''' # Initialize binary tree root = TreeNode(9) root.left = TreeNode(6) root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(7) root.right.right = TreeNode(11) root.left.left.left = TreeNode(3) root.left.left.right = TreeNode(5) root.left.right.right = TreeNode(8) if checkTreeIsBST(root): print(\"YES\") else: print(\"NO\") # This code is contributed by sanjeev2552",
"e": 7782,
"s": 5925,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Structure of a tree nodeclass TreeNode{ // Stores data value of a node public int data; // Stores left subtree // of a tree node public TreeNode left; // Stores right subtree // of a tree node public TreeNode right; // Initialization of // a tree node public TreeNode(int val) { // Update data data = val; // Update left and right left = right = null; }}; // Function to check if a binary tree// is binary search tree or notstatic bool checkTreeIsBST(TreeNode root){ // Stores root node and left // subtree of each node Stack<TreeNode > Stack = new Stack<TreeNode >(); // Stores previous visited node TreeNode prev = null; // Traverse the binary tree while (Stack.Count!=0 || root != null) { // Traverse left subtree while (root != null) { // Insert root into Stack Stack.Push(root); // Update root root = root.left; } // Stores top element of Stack root = Stack.Peek(); // Remove the top element of Stack Stack.Pop(); // If data value of root node less // than data value of left subtree if(prev != null && root.data <= prev.data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root.right; } return true;} // Driver Codepublic static void Main(String[] args){ /* 9 / \\ 6 10 / \\ \\ 4 7 11 / \\ \\ 3 5 8 */ // Initialize binary tree TreeNode root = new TreeNode(9); root.left = new TreeNode(6); root.right = new TreeNode(10); root.left.left = new TreeNode(4); root.left.right = new TreeNode(7); root.right.right = new TreeNode(11); root.left.left.left = new TreeNode(3); root.left.left.right = new TreeNode(5); root.left.right.right = new TreeNode(8); if (checkTreeIsBST(root)) { Console.Write(\"YES\"); } else { Console.Write(\"NO\"); }}} // This code is contributed by shikhasingrajput",
"e": 10126,
"s": 7782,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Structure of a tree nodeclass TreeNode{ constructor(val) { // Stores left subtree // of a tree node this.left = null; // Stores right subtree // of a tree node this.right = null; // Stores data value of a node this.data = val; }} // Function to check if a binary tree// is binary search tree or notfunction checkTreeIsBST(root){ // Stores root node and left // subtree of each node let Stack = []; // Stores previous visited node let prev = null; // Traverse the binary tree while (Stack.length > 0 || root != null) { // Traverse left subtree while (root != null) { // Insert root into Stack Stack.push(root); // Update root root = root.left; } // Stores top element of Stack root = Stack[Stack.length - 1]; // Remove the top element of Stack Stack.pop(); // If data value of root node less // than data value of left subtree if (prev != null && root.data <= prev.data) { return false; } // Update prev prev = root; // Traverse right subtree // of the tree root = root.right; } return true;} // Driver code/* 9 / \\ 6 10 / \\ \\ 4 7 11 / \\ \\ 3 5 8 */ // Initialize binary treelet root = new TreeNode(9);root.left = new TreeNode(6);root.right = new TreeNode(10);root.left.left = new TreeNode(4);root.left.right = new TreeNode(7);root.right.right = new TreeNode(11);root.left.left.left = new TreeNode(3);root.left.left.right = new TreeNode(5);root.left.right.right = new TreeNode(8); if (checkTreeIsBST(root)){ document.write(\"YES\");}else{ document.write(\"NO\");} // This code is contributed by divyeshrabadiya07 </script>",
"e": 12181,
"s": 10126,
"text": null
},
{
"code": null,
"e": 12185,
"s": 12181,
"text": "YES"
},
{
"code": null,
"e": 12277,
"s": 12187,
"text": "Time Complexity: O(N), where N is count of nodes in the binary tree Auxiliary Space: O(N)"
},
{
"code": null,
"e": 12292,
"s": 12277,
"text": "amit143katiyar"
},
{
"code": null,
"e": 12309,
"s": 12292,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 12321,
"s": 12309,
"text": "sanjeev2552"
},
{
"code": null,
"e": 12339,
"s": 12321,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 12359,
"s": 12339,
"text": "Binary Search Trees"
},
{
"code": null,
"e": 12371,
"s": 12359,
"text": "Binary Tree"
},
{
"code": null,
"e": 12375,
"s": 12371,
"text": "BST"
},
{
"code": null,
"e": 12393,
"s": 12375,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 12399,
"s": 12393,
"text": "Stack"
},
{
"code": null,
"e": 12404,
"s": 12399,
"text": "Tree"
},
{
"code": null,
"e": 12410,
"s": 12404,
"text": "Stack"
},
{
"code": null,
"e": 12415,
"s": 12410,
"text": "Tree"
},
{
"code": null,
"e": 12513,
"s": 12415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12545,
"s": 12513,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 12609,
"s": 12545,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 12658,
"s": 12609,
"text": "Design a stack with operations on middle element"
},
{
"code": null,
"e": 12715,
"s": 12658,
"text": "How to efficiently implement k stacks in a single array?"
},
{
"code": null,
"e": 12736,
"s": 12715,
"text": "Next Smaller Element"
},
{
"code": null,
"e": 12786,
"s": 12736,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 12821,
"s": 12786,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 12855,
"s": 12821,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 12884,
"s": 12855,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
Double ended priority queue
|
08 Jul, 2021
A double ended priority queue supports operations of both max heap (a max priority queue) and min heap (a min priority queue). The following operations are expected from double ended priority queue.
getMax() : Returns maximum element.getMin() : Returns minimum element.deleteMax() : Deletes maximum element.deleteMin() : Deletes minimum element.size() : Returns count of elements.isEmpty() : Returns true if the queue is empty.
getMax() : Returns maximum element.
getMin() : Returns minimum element.
deleteMax() : Deletes maximum element.
deleteMin() : Deletes minimum element.
size() : Returns count of elements.
isEmpty() : Returns true if the queue is empty.
We can try different data structure like Linked List. In case of linked list, if we maintain elements in sorted order, then time complexity of all operations become O(1) except the operation insert() which takes O(n) time. We can try two heaps (min heap and max heap). We maintain a pointer of every max heap element in min heap. To get minimum element, we simply return root. To get maximum element, we return root of max heap. To insert an element, we insert in min heap and max heap both. The main idea is to maintain one to one correspondence, so that deleteMin() and deleteMax() can be done in O(Log n) time.
getMax() : O(1)getMin() : O(1)deleteMax() : O(Log n)deleteMin() : O(Log n)size() : O(1)isEmpty() : O(1)
getMax() : O(1)
getMin() : O(1)
deleteMax() : O(Log n)
deleteMin() : O(Log n)
size() : O(1)
isEmpty() : O(1)
Another solution is to use self balancing binary search tree. A self balancing BST is implemented as set in C++ and TreeSet in Java.
getMax() : O(1)getMin() : O(1)deleteMax() : O(Log n)deleteMin() : O(Log n)size() : O(1)isEmpty() : O(1)
getMax() : O(1)
getMin() : O(1)
deleteMax() : O(Log n)
deleteMin() : O(Log n)
size() : O(1)
isEmpty() : O(1)
Below is the implementation of above approach:
C++
Java
C#
Javascript
// C++ program to implement double-ended// priority queue using self balancing BST.#include <bits/stdc++.h>using namespace std; struct DblEndedPQ { set<int> s; // Returns size of the queue. Works in // O(1) time int size() { return s.size(); } // Returns true if queue is empty. Works // in O(1) time bool isEmpty() { return (s.size() == 0); } // Inserts an element. Works in O(Log n) // time void insert(int x) { s.insert(x); } // Returns minimum element. Works in O(1) // time int getMin() { return *(s.begin()); } // Returns maximum element. Works in O(1) // time int getMax() { return *(s.rbegin()); } // Deletes minimum element. Works in O(Log n) // time void deleteMin() { if (s.size() == 0) return; s.erase(s.begin()); } // Deletes maximum element. Works in O(Log n) // time void deleteMax() { if (s.size() == 0) return; auto it = s.end(); it--; s.erase(it); }}; // Driver codeint main(){ DblEndedPQ d; d.insert(10); d.insert(50); d.insert(40); d.insert(20); cout << d.getMin() << endl; cout << d.getMax() << endl; d.deleteMax(); cout << d.getMax() << endl; d.deleteMin(); cout << d.getMin() << endl; return 0;}
// Java program to implement double-ended// priority queue using self balancing BST.import java.util.*;class solution{ static class DblEndedPQ { Set<Integer> s; DblEndedPQ() { s= new HashSet<Integer>(); } // Returns size of the queue. Works in // O(1) time int size() { return s.size(); } // Returns true if queue is empty. Works // in O(1) time boolean isEmpty() { return (s.size() == 0); } // Inserts an element. Works in O(Log n) // time void insert(int x) { s.add(x); } // Returns minimum element. Works in O(1) // time int getMin() { return Collections.min(s,null); } // Returns maximum element. Works in O(1) // time int getMax() { return Collections.max(s,null); } // Deletes minimum element. Works in O(Log n) // time void deleteMin() { if (s.size() == 0) return ; s.remove(Collections.min(s,null)); } // Deletes maximum element. Works in O(Log n) // time void deleteMax() { if (s.size() == 0) return ; s.remove(Collections.max(s,null)); }}; // Driver codepublic static void main(String args[]){ DblEndedPQ d= new DblEndedPQ(); d.insert(10); d.insert(50); d.insert(40); d.insert(20); System.out.println( d.getMin() ); System.out.println(d.getMax() ); d.deleteMax(); System.out.println( d.getMax() ); d.deleteMin(); System.out.println( d.getMin() );}}//contributed by Arnab Kundu
// C# program to implement double-ended// priority queue using self balancing BST.using System;using System.Linq;using System.Collections.Generic; class GFG{ public class DblEndedPQ{ HashSet<int> s; public DblEndedPQ() { s = new HashSet<int>(); } // Returns size of the queue. Works in // O(1) time public int size() { return s.Count; } // Returns true if queue is empty. Works // in O(1) time public bool isEmpty() { return (s.Count == 0); } // Inserts an element. Works in O(Log n) // time public void insert(int x) { s.Add(x); } // Returns minimum element. Works in O(1) // time public int getMin() { return s.Min(); } // Returns maximum element. Works in O(1) // time public int getMax() { return s.Max(); } // Deletes minimum element. Works in O(Log n) // time public void deleteMin() { if (s.Count == 0) return ; s.Remove(s.Min()); } // Deletes maximum element. Works in O(Log n) // time public void deleteMax() { if (s.Count == 0) return ; s.Remove(s.Max()); }}; // Driver codepublic static void Main(String[] args){ DblEndedPQ d= new DblEndedPQ(); d.insert(10); d.insert(50); d.insert(40); d.insert(20); Console.WriteLine( d.getMin() ); Console.WriteLine(d.getMax() ); d.deleteMax(); Console.WriteLine( d.getMax() ); d.deleteMin(); Console.WriteLine( d.getMin() );}} // This code contributed by Rajput-Ji
<script> // JavaScript program to implement double-ended // priority queue using self balancing BST. class DblEndedPQ { constructor() { this.s = new Set(); } // Returns size of the queue. Works in // O(1) time size() { return this.s.size; } // Returns true if queue is empty. Works // in O(1) time isEmpty() { return this.s.size == 0; } // Inserts an element. Works in O(Log n) // time insert(x) { this.s.add(x); } // Returns minimum element. Works in O(1) // time getMin() { return Math.min(...Array.from(this.s.values())); } // Returns maximum element. Works in O(1) // time getMax() { return Math.max(...Array.from(this.s.values())); } // Deletes minimum element. Works in O(Log n) // time deleteMin() { if (this.s.size == 0) return; this.s.delete(this.getMin()); } // Deletes maximum element. Works in O(Log n) // time deleteMax() { if (this.s.size == 0) return; this.s.delete(this.getMax()); } } // Driver code var d = new DblEndedPQ(); d.insert(10); d.insert(50); d.insert(40); d.insert(20); document.write(d.getMin() + "<br>"); document.write(d.getMax() + "<br>"); d.deleteMax(); document.write(d.getMax() + "<br>"); d.deleteMin(); document.write(d.getMin() + "<br>"); // This code is contributed by rdtank. </script>
10
50
40
20
Comparison of Heap and BST solutions Heap based solution requires O(n) extra space for an extra heap. BST based solution does not require extra space. The advantage of heap based solution is cache friendly.
andrew1234
Rajput-Ji
rdtank
cpp-map
priority-queue
Self-Balancing-BST
Binary Search Tree
Heap
Binary Search Tree
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 253,
"s": 52,
"text": "A double ended priority queue supports operations of both max heap (a max priority queue) and min heap (a min priority queue). The following operations are expected from double ended priority queue. "
},
{
"code": null,
"e": 482,
"s": 253,
"text": "getMax() : Returns maximum element.getMin() : Returns minimum element.deleteMax() : Deletes maximum element.deleteMin() : Deletes minimum element.size() : Returns count of elements.isEmpty() : Returns true if the queue is empty."
},
{
"code": null,
"e": 518,
"s": 482,
"text": "getMax() : Returns maximum element."
},
{
"code": null,
"e": 554,
"s": 518,
"text": "getMin() : Returns minimum element."
},
{
"code": null,
"e": 593,
"s": 554,
"text": "deleteMax() : Deletes maximum element."
},
{
"code": null,
"e": 632,
"s": 593,
"text": "deleteMin() : Deletes minimum element."
},
{
"code": null,
"e": 668,
"s": 632,
"text": "size() : Returns count of elements."
},
{
"code": null,
"e": 716,
"s": 668,
"text": "isEmpty() : Returns true if the queue is empty."
},
{
"code": null,
"e": 1334,
"s": 718,
"text": "We can try different data structure like Linked List. In case of linked list, if we maintain elements in sorted order, then time complexity of all operations become O(1) except the operation insert() which takes O(n) time. We can try two heaps (min heap and max heap). We maintain a pointer of every max heap element in min heap. To get minimum element, we simply return root. To get maximum element, we return root of max heap. To insert an element, we insert in min heap and max heap both. The main idea is to maintain one to one correspondence, so that deleteMin() and deleteMax() can be done in O(Log n) time. "
},
{
"code": null,
"e": 1438,
"s": 1334,
"text": "getMax() : O(1)getMin() : O(1)deleteMax() : O(Log n)deleteMin() : O(Log n)size() : O(1)isEmpty() : O(1)"
},
{
"code": null,
"e": 1454,
"s": 1438,
"text": "getMax() : O(1)"
},
{
"code": null,
"e": 1470,
"s": 1454,
"text": "getMin() : O(1)"
},
{
"code": null,
"e": 1493,
"s": 1470,
"text": "deleteMax() : O(Log n)"
},
{
"code": null,
"e": 1516,
"s": 1493,
"text": "deleteMin() : O(Log n)"
},
{
"code": null,
"e": 1530,
"s": 1516,
"text": "size() : O(1)"
},
{
"code": null,
"e": 1547,
"s": 1530,
"text": "isEmpty() : O(1)"
},
{
"code": null,
"e": 1681,
"s": 1547,
"text": "Another solution is to use self balancing binary search tree. A self balancing BST is implemented as set in C++ and TreeSet in Java. "
},
{
"code": null,
"e": 1785,
"s": 1681,
"text": "getMax() : O(1)getMin() : O(1)deleteMax() : O(Log n)deleteMin() : O(Log n)size() : O(1)isEmpty() : O(1)"
},
{
"code": null,
"e": 1801,
"s": 1785,
"text": "getMax() : O(1)"
},
{
"code": null,
"e": 1817,
"s": 1801,
"text": "getMin() : O(1)"
},
{
"code": null,
"e": 1840,
"s": 1817,
"text": "deleteMax() : O(Log n)"
},
{
"code": null,
"e": 1863,
"s": 1840,
"text": "deleteMin() : O(Log n)"
},
{
"code": null,
"e": 1877,
"s": 1863,
"text": "size() : O(1)"
},
{
"code": null,
"e": 1894,
"s": 1877,
"text": "isEmpty() : O(1)"
},
{
"code": null,
"e": 1943,
"s": 1894,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1947,
"s": 1943,
"text": "C++"
},
{
"code": null,
"e": 1952,
"s": 1947,
"text": "Java"
},
{
"code": null,
"e": 1955,
"s": 1952,
"text": "C#"
},
{
"code": null,
"e": 1966,
"s": 1955,
"text": "Javascript"
},
{
"code": "// C++ program to implement double-ended// priority queue using self balancing BST.#include <bits/stdc++.h>using namespace std; struct DblEndedPQ { set<int> s; // Returns size of the queue. Works in // O(1) time int size() { return s.size(); } // Returns true if queue is empty. Works // in O(1) time bool isEmpty() { return (s.size() == 0); } // Inserts an element. Works in O(Log n) // time void insert(int x) { s.insert(x); } // Returns minimum element. Works in O(1) // time int getMin() { return *(s.begin()); } // Returns maximum element. Works in O(1) // time int getMax() { return *(s.rbegin()); } // Deletes minimum element. Works in O(Log n) // time void deleteMin() { if (s.size() == 0) return; s.erase(s.begin()); } // Deletes maximum element. Works in O(Log n) // time void deleteMax() { if (s.size() == 0) return; auto it = s.end(); it--; s.erase(it); }}; // Driver codeint main(){ DblEndedPQ d; d.insert(10); d.insert(50); d.insert(40); d.insert(20); cout << d.getMin() << endl; cout << d.getMax() << endl; d.deleteMax(); cout << d.getMax() << endl; d.deleteMin(); cout << d.getMin() << endl; return 0;}",
"e": 3337,
"s": 1966,
"text": null
},
{
"code": "// Java program to implement double-ended// priority queue using self balancing BST.import java.util.*;class solution{ static class DblEndedPQ { Set<Integer> s; DblEndedPQ() { s= new HashSet<Integer>(); } // Returns size of the queue. Works in // O(1) time int size() { return s.size(); } // Returns true if queue is empty. Works // in O(1) time boolean isEmpty() { return (s.size() == 0); } // Inserts an element. Works in O(Log n) // time void insert(int x) { s.add(x); } // Returns minimum element. Works in O(1) // time int getMin() { return Collections.min(s,null); } // Returns maximum element. Works in O(1) // time int getMax() { return Collections.max(s,null); } // Deletes minimum element. Works in O(Log n) // time void deleteMin() { if (s.size() == 0) return ; s.remove(Collections.min(s,null)); } // Deletes maximum element. Works in O(Log n) // time void deleteMax() { if (s.size() == 0) return ; s.remove(Collections.max(s,null)); }}; // Driver codepublic static void main(String args[]){ DblEndedPQ d= new DblEndedPQ(); d.insert(10); d.insert(50); d.insert(40); d.insert(20); System.out.println( d.getMin() ); System.out.println(d.getMax() ); d.deleteMax(); System.out.println( d.getMax() ); d.deleteMin(); System.out.println( d.getMin() );}}//contributed by Arnab Kundu",
"e": 4895,
"s": 3337,
"text": null
},
{
"code": "// C# program to implement double-ended// priority queue using self balancing BST.using System;using System.Linq;using System.Collections.Generic; class GFG{ public class DblEndedPQ{ HashSet<int> s; public DblEndedPQ() { s = new HashSet<int>(); } // Returns size of the queue. Works in // O(1) time public int size() { return s.Count; } // Returns true if queue is empty. Works // in O(1) time public bool isEmpty() { return (s.Count == 0); } // Inserts an element. Works in O(Log n) // time public void insert(int x) { s.Add(x); } // Returns minimum element. Works in O(1) // time public int getMin() { return s.Min(); } // Returns maximum element. Works in O(1) // time public int getMax() { return s.Max(); } // Deletes minimum element. Works in O(Log n) // time public void deleteMin() { if (s.Count == 0) return ; s.Remove(s.Min()); } // Deletes maximum element. Works in O(Log n) // time public void deleteMax() { if (s.Count == 0) return ; s.Remove(s.Max()); }}; // Driver codepublic static void Main(String[] args){ DblEndedPQ d= new DblEndedPQ(); d.insert(10); d.insert(50); d.insert(40); d.insert(20); Console.WriteLine( d.getMin() ); Console.WriteLine(d.getMax() ); d.deleteMax(); Console.WriteLine( d.getMax() ); d.deleteMin(); Console.WriteLine( d.getMin() );}} // This code contributed by Rajput-Ji",
"e": 6492,
"s": 4895,
"text": null
},
{
"code": "<script> // JavaScript program to implement double-ended // priority queue using self balancing BST. class DblEndedPQ { constructor() { this.s = new Set(); } // Returns size of the queue. Works in // O(1) time size() { return this.s.size; } // Returns true if queue is empty. Works // in O(1) time isEmpty() { return this.s.size == 0; } // Inserts an element. Works in O(Log n) // time insert(x) { this.s.add(x); } // Returns minimum element. Works in O(1) // time getMin() { return Math.min(...Array.from(this.s.values())); } // Returns maximum element. Works in O(1) // time getMax() { return Math.max(...Array.from(this.s.values())); } // Deletes minimum element. Works in O(Log n) // time deleteMin() { if (this.s.size == 0) return; this.s.delete(this.getMin()); } // Deletes maximum element. Works in O(Log n) // time deleteMax() { if (this.s.size == 0) return; this.s.delete(this.getMax()); } } // Driver code var d = new DblEndedPQ(); d.insert(10); d.insert(50); d.insert(40); d.insert(20); document.write(d.getMin() + \"<br>\"); document.write(d.getMax() + \"<br>\"); d.deleteMax(); document.write(d.getMax() + \"<br>\"); d.deleteMin(); document.write(d.getMin() + \"<br>\"); // This code is contributed by rdtank. </script>",
"e": 8120,
"s": 6492,
"text": null
},
{
"code": null,
"e": 8132,
"s": 8120,
"text": "10\n50\n40\n20"
},
{
"code": null,
"e": 8342,
"s": 8134,
"text": "Comparison of Heap and BST solutions Heap based solution requires O(n) extra space for an extra heap. BST based solution does not require extra space. The advantage of heap based solution is cache friendly. "
},
{
"code": null,
"e": 8353,
"s": 8342,
"text": "andrew1234"
},
{
"code": null,
"e": 8363,
"s": 8353,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8370,
"s": 8363,
"text": "rdtank"
},
{
"code": null,
"e": 8378,
"s": 8370,
"text": "cpp-map"
},
{
"code": null,
"e": 8393,
"s": 8378,
"text": "priority-queue"
},
{
"code": null,
"e": 8412,
"s": 8393,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 8431,
"s": 8412,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 8436,
"s": 8431,
"text": "Heap"
},
{
"code": null,
"e": 8455,
"s": 8436,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 8460,
"s": 8455,
"text": "Heap"
},
{
"code": null,
"e": 8475,
"s": 8460,
"text": "priority-queue"
}
] |
Multiples of 4 (An Interesting Method)
|
31 May, 2022
Given a number n, the task is to check whether this number is a multiple of 4 or not without using +, -, * ,/ and % operators.Examples :
Input: n = 4 Output - Yes
n = 20 Output - Yes
n = 19 Output - No
Method 1 (Using XOR) An interesting fact for n > 1 is, we do XOR of all numbers from 1 to n and if the result is equal to n, then n is a multiple of 4 else not.
C++
Java
Python 3
C#
PHP
Javascript
// An interesting XOR based method to check if// a number is multiple of 4.#include<bits/stdc++.h>using namespace std; // Returns true if n is a multiple of 4.bool isMultipleOf4(int n){ if (n == 1) return false; // Find XOR of all numbers from 1 to n int XOR = 0; for (int i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then return true return (XOR == n);} // Driver code to print multiples of 4int main(){ // Printing multiples of 4 using above method for (int n=0; n<=42; n++) if (isMultipleOf4(n)) cout << n << " "; return 0;}
// An interesting XOR based method to check if// a number is multiple of 4. class Test{ // Returns true if n is a multiple of 4. static boolean isMultipleOf4(int n) { if (n == 1) return false; // Find XOR of all numbers from 1 to n int XOR = 0; for (int i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then return true return (XOR == n); } // Driver method public static void main(String[] args) { // Printing multiples of 4 using above method for (int n=0; n<=42; n++) System.out.print(isMultipleOf4(n) ? n : " "); }}
# An interesting XOR based# method to check if a# number is multiple of 4. # Returns true if n is a# multiple of 4.def isMultipleOf4(n): if (n == 1): return False # Find XOR of all numbers # from 1 to n XOR = 0 for i in range(1, n + 1): XOR = XOR ^ i # If XOR is equal n, then # return true return (XOR == n) # Driver code to print# multiples of 4 Printing# multiples of 4 using# above methodfor n in range(0, 43): if (isMultipleOf4(n)): print(n, end = " ") # This code is contributed# by Smitha
// An interesting XOR based method// to check if a number is multiple// of 4.using System;class GFG { // Returns true if n is a // multiple of 4. static bool isMultipleOf4(int n) { if (n == 1) return false; // Find XOR of all numbers // from 1 to n int XOR = 0; for (int i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then // return true return (XOR == n); } // Driver method public static void Main() { // Printing multiples of 4 // using above method for (int n = 0; n <= 42; n++) { if (isMultipleOf4(n)) Console.Write(n+" "); } }} // This code is contributed by Smitha.
<?php// PHP program to check if// a number is multiple of 4. // Returns true if n is// a multiple of 4.function isMultipleOf4($n){ if ($n == 1) return false; // Find XOR of all // numbers from 1 to n $XOR = 0; for ($i = 1; $i <= $n; $i++) $XOR = $XOR ^ $i; // If XOR is equal n, // then return true return ($XOR == $n);} // Driver Code // Printing multiples of 4// using above methodfor ($n = 0; $n <= 42; $n++)if (isMultipleOf4($n)) echo $n, " "; // This code is contributed by Ajit?>
<script> // Javascript program of interesting XOR based method to check if// a number is multiple of 4. // Returns true if n is a multiple of 4. function isMultipleOf4(n) { if (n == 1) return false; // Find XOR of all numbers from 1 to n let XOR = 0; for (let i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then return true return (XOR == n); } // Driver Code // Printing multiples of 4 using above method for (let n = 0; n <= 42; n++) document.write(isMultipleOf4(n) ? n : " "); // This code is contributed by avijitmondal1998.</script>
Output :
0 4 8 12 16 20 24 28 32 36 40
Time Complexity: O(n)
Auxiliary Space: O(1)
How does this work? When we do XOR of numbers, we get 0 as XOR value just before a multiple of 4. This keeps repeating before every multiple of 4.
Number Binary-Repr XOR-from-1-to-n
1 1 [0001]
2 10 [0011]
3 11 [0000]
Method 2 (Using Bitwise Shift Operators) The idea is to remove last two bits using >>, then multiply with 4 using <<. If final result is same as n, then last two bits were 0, hence number was a multiple of four.
C++
Java
Python3
C#
PHP
Javascript
// An interesting XOR based method to check if// a number is multiple of 4.#include<bits/stdc++.h>using namespace std; // Returns true if n is a multiple of 4.bool isMultipleOf4(long long n){ if (n==0) return true; return (((n>>2)<<2) == n);} // Driver code to print multiples of 4int main(){ // Printing multiples of 4 using above method for (int n=0; n<=42; n++) if (isMultipleOf4(n)) cout << n << " "; return 0;}
// An interesting XOR based method to check if// a number is multiple of 4. class Test{ // Returns true if n is a multiple of 4. static boolean isMultipleOf4(long n) { if (n==0) return true; return (((n>>2)<<2) == n); } // Driver method public static void main(String[] args) { // Printing multiples of 4 using above method for (int n=0; n<=42; n++) System.out.print(isMultipleOf4(n) ? n : " "); }}
# Python3 code to implement an interesting XOR# based method to check if a number is multiple of 4. # Returns true if n is a multiple of 4.def isMultipleOf4(n): if (n == 0): return True return (((n>>2)<<2) == n) # Driver code to print multiples of 4#Printing multiples of 4 using above methodfor n in range(43): if isMultipleOf4(n): print(n, end = " ") # This codeis contributed by phasing17
// An interesting XOR based method to// check if a number is multiple of 4.using System; class GFG { // Returns true if n is a multiple // of 4. static bool isMultipleOf4(int n) { if (n == 0) return true; return (((n >> 2) << 2) == n); } // Driver code to print multiples // of 4 static void Main() { // Printing multiples of 4 using // above method for (int n = 0; n <= 42; n++) if (isMultipleOf4(n)) Console.Write(n + " "); }} // This code is contributed by Anuj_67
<?php// PHP program to check if// a number is multiple of 4. // Returns true if n is// a multiple of 4.function isMultipleOf4($n){ if ($n == 0) return true; return ((($n >> 2) << 2) == $n);} // Driver Code // Printing multiples of 4// using above methodfor ($n = 0; $n <= 42; $n++) if (isMultipleOf4($n)) echo $n , " "; // This code is contributed by anuj_67.?>
<script> // An interesting XOR based method to // check if a number is multiple of 4. // Returns true if n is a multiple // of 4. function isMultipleOf4(n) { if (n == 0) return true; return (((n >> 2) << 2) == n); } // Printing multiples of 4 using // above method for (let n = 0; n <= 42; n++) if (isMultipleOf4(n)) document.write(n + " "); </script>
Output :
0 4 8 12 16 20 24 28 32 36 40
Time Complexity: O(1)
Auxiliary Space: O(1)
As we can see that the main idea to find multiplicity of 4 is to check the least two significant bits of the given number. We know that for any even number, the least significant bit is always ZERO (i.e. 0). Similarly, for any number which is multiple of 4 will have least two significant bits as ZERO. And with the same logic, for any number to be multiple of 8, least three significant bits will be ZERO. That’s why we can use AND operator (&) as well with other operand as 0x3 to find multiplicity of 4. This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
Smitha Dinesh Semwal
avijitmondal1998
divyesh072019
surinderdawra388
subhammahato348
phasing17
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Builtin functions of GCC compiler
Calculate XOR from 1 to n.
Find two numbers from their sum and XOR
Calculate square of a number without using *, / and pow()
Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
Reverse actual bits of the given number
Google Online Challenge 2020
Equal Sum and XOR of three Numbers
Unique element in an array where all elements occur k times except one
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 193,
"s": 54,
"text": "Given a number n, the task is to check whether this number is a multiple of 4 or not without using +, -, * ,/ and % operators.Examples : "
},
{
"code": null,
"e": 273,
"s": 193,
"text": "Input: n = 4 Output - Yes\n n = 20 Output - Yes\n n = 19 Output - No"
},
{
"code": null,
"e": 438,
"s": 275,
"text": "Method 1 (Using XOR) An interesting fact for n > 1 is, we do XOR of all numbers from 1 to n and if the result is equal to n, then n is a multiple of 4 else not. "
},
{
"code": null,
"e": 442,
"s": 438,
"text": "C++"
},
{
"code": null,
"e": 447,
"s": 442,
"text": "Java"
},
{
"code": null,
"e": 456,
"s": 447,
"text": "Python 3"
},
{
"code": null,
"e": 459,
"s": 456,
"text": "C#"
},
{
"code": null,
"e": 463,
"s": 459,
"text": "PHP"
},
{
"code": null,
"e": 474,
"s": 463,
"text": "Javascript"
},
{
"code": "// An interesting XOR based method to check if// a number is multiple of 4.#include<bits/stdc++.h>using namespace std; // Returns true if n is a multiple of 4.bool isMultipleOf4(int n){ if (n == 1) return false; // Find XOR of all numbers from 1 to n int XOR = 0; for (int i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then return true return (XOR == n);} // Driver code to print multiples of 4int main(){ // Printing multiples of 4 using above method for (int n=0; n<=42; n++) if (isMultipleOf4(n)) cout << n << \" \"; return 0;}",
"e": 1070,
"s": 474,
"text": null
},
{
"code": "// An interesting XOR based method to check if// a number is multiple of 4. class Test{ // Returns true if n is a multiple of 4. static boolean isMultipleOf4(int n) { if (n == 1) return false; // Find XOR of all numbers from 1 to n int XOR = 0; for (int i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then return true return (XOR == n); } // Driver method public static void main(String[] args) { // Printing multiples of 4 using above method for (int n=0; n<=42; n++) System.out.print(isMultipleOf4(n) ? n : \" \"); }}",
"e": 1726,
"s": 1070,
"text": null
},
{
"code": "# An interesting XOR based# method to check if a# number is multiple of 4. # Returns true if n is a# multiple of 4.def isMultipleOf4(n): if (n == 1): return False # Find XOR of all numbers # from 1 to n XOR = 0 for i in range(1, n + 1): XOR = XOR ^ i # If XOR is equal n, then # return true return (XOR == n) # Driver code to print# multiples of 4 Printing# multiples of 4 using# above methodfor n in range(0, 43): if (isMultipleOf4(n)): print(n, end = \" \") # This code is contributed# by Smitha",
"e": 2273,
"s": 1726,
"text": null
},
{
"code": "// An interesting XOR based method// to check if a number is multiple// of 4.using System;class GFG { // Returns true if n is a // multiple of 4. static bool isMultipleOf4(int n) { if (n == 1) return false; // Find XOR of all numbers // from 1 to n int XOR = 0; for (int i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then // return true return (XOR == n); } // Driver method public static void Main() { // Printing multiples of 4 // using above method for (int n = 0; n <= 42; n++) { if (isMultipleOf4(n)) Console.Write(n+\" \"); } }} // This code is contributed by Smitha.",
"e": 3047,
"s": 2273,
"text": null
},
{
"code": "<?php// PHP program to check if// a number is multiple of 4. // Returns true if n is// a multiple of 4.function isMultipleOf4($n){ if ($n == 1) return false; // Find XOR of all // numbers from 1 to n $XOR = 0; for ($i = 1; $i <= $n; $i++) $XOR = $XOR ^ $i; // If XOR is equal n, // then return true return ($XOR == $n);} // Driver Code // Printing multiples of 4// using above methodfor ($n = 0; $n <= 42; $n++)if (isMultipleOf4($n)) echo $n, \" \"; // This code is contributed by Ajit?>",
"e": 3572,
"s": 3047,
"text": null
},
{
"code": "<script> // Javascript program of interesting XOR based method to check if// a number is multiple of 4. // Returns true if n is a multiple of 4. function isMultipleOf4(n) { if (n == 1) return false; // Find XOR of all numbers from 1 to n let XOR = 0; for (let i = 1; i <= n; i++) XOR = XOR ^ i; // If XOR is equal n, then return true return (XOR == n); } // Driver Code // Printing multiples of 4 using above method for (let n = 0; n <= 42; n++) document.write(isMultipleOf4(n) ? n : \" \"); // This code is contributed by avijitmondal1998.</script>",
"e": 4261,
"s": 3572,
"text": null
},
{
"code": null,
"e": 4272,
"s": 4261,
"text": "Output : "
},
{
"code": null,
"e": 4303,
"s": 4272,
"text": "0 4 8 12 16 20 24 28 32 36 40 "
},
{
"code": null,
"e": 4325,
"s": 4303,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4347,
"s": 4325,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4496,
"s": 4347,
"text": "How does this work? When we do XOR of numbers, we get 0 as XOR value just before a multiple of 4. This keeps repeating before every multiple of 4. "
},
{
"code": null,
"e": 4619,
"s": 4496,
"text": "Number Binary-Repr XOR-from-1-to-n\n1 1 [0001]\n2 10 [0011]\n3 11 [0000]"
},
{
"code": null,
"e": 4834,
"s": 4619,
"text": " Method 2 (Using Bitwise Shift Operators) The idea is to remove last two bits using >>, then multiply with 4 using <<. If final result is same as n, then last two bits were 0, hence number was a multiple of four. "
},
{
"code": null,
"e": 4838,
"s": 4834,
"text": "C++"
},
{
"code": null,
"e": 4843,
"s": 4838,
"text": "Java"
},
{
"code": null,
"e": 4851,
"s": 4843,
"text": "Python3"
},
{
"code": null,
"e": 4854,
"s": 4851,
"text": "C#"
},
{
"code": null,
"e": 4858,
"s": 4854,
"text": "PHP"
},
{
"code": null,
"e": 4869,
"s": 4858,
"text": "Javascript"
},
{
"code": "// An interesting XOR based method to check if// a number is multiple of 4.#include<bits/stdc++.h>using namespace std; // Returns true if n is a multiple of 4.bool isMultipleOf4(long long n){ if (n==0) return true; return (((n>>2)<<2) == n);} // Driver code to print multiples of 4int main(){ // Printing multiples of 4 using above method for (int n=0; n<=42; n++) if (isMultipleOf4(n)) cout << n << \" \"; return 0;}",
"e": 5326,
"s": 4869,
"text": null
},
{
"code": "// An interesting XOR based method to check if// a number is multiple of 4. class Test{ // Returns true if n is a multiple of 4. static boolean isMultipleOf4(long n) { if (n==0) return true; return (((n>>2)<<2) == n); } // Driver method public static void main(String[] args) { // Printing multiples of 4 using above method for (int n=0; n<=42; n++) System.out.print(isMultipleOf4(n) ? n : \" \"); }}",
"e": 5809,
"s": 5326,
"text": null
},
{
"code": "# Python3 code to implement an interesting XOR# based method to check if a number is multiple of 4. # Returns true if n is a multiple of 4.def isMultipleOf4(n): if (n == 0): return True return (((n>>2)<<2) == n) # Driver code to print multiples of 4#Printing multiples of 4 using above methodfor n in range(43): if isMultipleOf4(n): print(n, end = \" \") # This codeis contributed by phasing17",
"e": 6225,
"s": 5809,
"text": null
},
{
"code": "// An interesting XOR based method to// check if a number is multiple of 4.using System; class GFG { // Returns true if n is a multiple // of 4. static bool isMultipleOf4(int n) { if (n == 0) return true; return (((n >> 2) << 2) == n); } // Driver code to print multiples // of 4 static void Main() { // Printing multiples of 4 using // above method for (int n = 0; n <= 42; n++) if (isMultipleOf4(n)) Console.Write(n + \" \"); }} // This code is contributed by Anuj_67",
"e": 6819,
"s": 6225,
"text": null
},
{
"code": "<?php// PHP program to check if// a number is multiple of 4. // Returns true if n is// a multiple of 4.function isMultipleOf4($n){ if ($n == 0) return true; return ((($n >> 2) << 2) == $n);} // Driver Code // Printing multiples of 4// using above methodfor ($n = 0; $n <= 42; $n++) if (isMultipleOf4($n)) echo $n , \" \"; // This code is contributed by anuj_67.?>",
"e": 7213,
"s": 6819,
"text": null
},
{
"code": "<script> // An interesting XOR based method to // check if a number is multiple of 4. // Returns true if n is a multiple // of 4. function isMultipleOf4(n) { if (n == 0) return true; return (((n >> 2) << 2) == n); } // Printing multiples of 4 using // above method for (let n = 0; n <= 42; n++) if (isMultipleOf4(n)) document.write(n + \" \"); </script>",
"e": 7657,
"s": 7213,
"text": null
},
{
"code": null,
"e": 7668,
"s": 7657,
"text": "Output : "
},
{
"code": null,
"e": 7699,
"s": 7668,
"text": "0 4 8 12 16 20 24 28 32 36 40 "
},
{
"code": null,
"e": 7721,
"s": 7699,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 7743,
"s": 7721,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8680,
"s": 7743,
"text": "As we can see that the main idea to find multiplicity of 4 is to check the least two significant bits of the given number. We know that for any even number, the least significant bit is always ZERO (i.e. 0). Similarly, for any number which is multiple of 4 will have least two significant bits as ZERO. And with the same logic, for any number to be multiple of 8, least three significant bits will be ZERO. That’s why we can use AND operator (&) as well with other operand as 0x3 to find multiplicity of 4. This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8685,
"s": 8680,
"text": "vt_m"
},
{
"code": null,
"e": 8691,
"s": 8685,
"text": "jit_t"
},
{
"code": null,
"e": 8712,
"s": 8691,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 8729,
"s": 8712,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 8743,
"s": 8729,
"text": "divyesh072019"
},
{
"code": null,
"e": 8760,
"s": 8743,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8776,
"s": 8760,
"text": "subhammahato348"
},
{
"code": null,
"e": 8786,
"s": 8776,
"text": "phasing17"
},
{
"code": null,
"e": 8798,
"s": 8786,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 8808,
"s": 8798,
"text": "Bit Magic"
},
{
"code": null,
"e": 8818,
"s": 8808,
"text": "Bit Magic"
},
{
"code": null,
"e": 8916,
"s": 8818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8967,
"s": 8916,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 9001,
"s": 8967,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 9028,
"s": 9001,
"text": "Calculate XOR from 1 to n."
},
{
"code": null,
"e": 9068,
"s": 9028,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 9126,
"s": 9068,
"text": "Calculate square of a number without using *, / and pow()"
},
{
"code": null,
"e": 9220,
"s": 9126,
"text": "Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal"
},
{
"code": null,
"e": 9260,
"s": 9220,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 9289,
"s": 9260,
"text": "Google Online Challenge 2020"
},
{
"code": null,
"e": 9324,
"s": 9289,
"text": "Equal Sum and XOR of three Numbers"
}
] |
Next Larger element in n-ary tree
|
08 Jul, 2021
Given a generic tree and a integer x. Find and return the node with next larger element in the tree i.e. find a node just greater than x. Return NULL if no node is present with value greater than x. For example, in the given tree
x = 10, just greater node value is 12
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.
The idea is maintain a node pointer res, which will contain the final resultant node. Traverse the tree and check if root data is greater than x. If so, then compare the root data with res data. If root data is greater than n and less than res data update res.
C++
Java
Python3
C#
Javascript
// CPP program to find next larger element// in an n-ary tree.#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node { int key; vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; return temp;} void nextLargerElementUtil(Node* root, int x, Node** res){ if (root == NULL) return; // if root is less than res but greater than // x update res if (root->key > x) if (!(*res) || (*res)->key > root->key) *res = root; // Number of children of root int numChildren = root->child.size(); // Recur calling for every child for (int i = 0; i < numChildren; i++) nextLargerElementUtil(root->child[i], x, res); return;} // Function to find next Greater element of x in treeNode* nextLargerElement(Node* root, int x){ // resultant node Node* res = NULL; // calling helper function nextLargerElementUtil(root, x, &res); return res;} // Driver programint main(){ /* Let us create below tree * 5 * / | \ * 1 2 3 * / / \ \ * 15 4 5 6 */ Node* root = newNode(5); (root->child).push_back(newNode(1)); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(3)); (root->child[0]->child).push_back(newNode(15)); (root->child[1]->child).push_back(newNode(4)); (root->child[1]->child).push_back(newNode(5)); (root->child[2]->child).push_back(newNode(6)); int x = 5; cout << "Next larger element of " << x << " is "; cout << nextLargerElement(root, x)->key << endl; return 0;}
// Java program to find next larger element// in an n-ary tree.import java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{ int key; Vector<Node> child;};static Node res; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new Vector<>(); return temp;} static void nextLargerElementUtil(Node root, int x){ if (root == null) return; // if root is less than res but // greater than x, update res if (root.key > x) if ((res == null || (res).key > root.key)) res = root; // Number of children of root int numChildren = root.child.size(); // Recur calling for every child for (int i = 0; i < numChildren; i++) nextLargerElementUtil(root.child.get(i), x); return;} // Function to find next Greater element// of x in treestatic Node nextLargerElement(Node root, int x){ // resultant node res = null; // calling helper function nextLargerElementUtil(root, x); return res;} // Driver Codepublic static void main(String[] args){ /* Let us create below tree * 5 * / | \ * 1 2 3 * / / \ \ * 15 4 5 6 */ Node root = newNode(5); (root.child).add(newNode(1)); (root.child).add(newNode(2)); (root.child).add(newNode(3)); (root.child.get(0).child).add(newNode(15)); (root.child.get(1).child).add(newNode(4)); (root.child.get(1).child).add(newNode(5)); (root.child.get(2).child).add(newNode(6)); int x = 5; System.out.print("Next larger element of " + x + " is "); System.out.print(nextLargerElement(root, x).key + "\n"); }} // This code is contributed by 29AjayKumar
# Python program to find next larger element# in an n-ary tree.class Node: # Structure of a node of an n-ary tree def __init__(self): self.key = 0 self.child = [] # Utility function to create a new tree nodedef newNode(key): temp = Node() temp.key = key temp.child = [] return temp res = None; def nextLargerElementUtil(root,x): global res if (root == None): return; # if root is less than res but # greater than x, update res if (root.key > x): if ((res == None or (res).key > root.key)): res = root; # Number of children of root numChildren = len(root.child) # Recur calling for every child for i in range(numChildren): nextLargerElementUtil(root.child[i], x) return # Function to find next Greater element# of x in treedef nextLargerElement(root,x): # resultant node global res res=None # Calling helper function nextLargerElementUtil(root, x) return res # Driver coderoot = newNode(5)(root.child).append(newNode(1))(root.child).append(newNode(2))(root.child).append(newNode(3))(root.child[0].child).append(newNode(15))(root.child[1].child).append(newNode(4))(root.child[1].child).append(newNode(5))(root.child[2].child).append(newNode(6)) x = 5print("Next larger element of " , x , " is ",end='')print(nextLargerElement(root, x).key) # This code is contributed by rag2127.
// C# program to find next larger element// in an n-ary tree.using System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treeclass Node{ public int key; public List<Node> child;};static Node res; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new List<Node>(); return temp;} static void nextLargerElementUtil(Node root, int x){ if (root == null) return; // if root is less than res but // greater than x, update res if (root.key > x) if ((res == null || (res).key > root.key)) res = root; // Number of children of root int numChildren = root.child.Count; // Recur calling for every child for (int i = 0; i < numChildren; i++) nextLargerElementUtil(root.child[i], x); return;} // Function to find next Greater element// of x in treestatic Node nextLargerElement(Node root, int x){ // resultant node res = null; // calling helper function nextLargerElementUtil(root, x); return res;} // Driver Codepublic static void Main(String[] args){ /* Let us create below tree * 5 * / | \ * 1 2 3 * / / \ \ * 15 4 5 6 */ Node root = newNode(5); (root.child).Add(newNode(1)); (root.child).Add(newNode(2)); (root.child).Add(newNode(3)); (root.child[0].child).Add(newNode(15)); (root.child[1].child).Add(newNode(4)); (root.child[1].child).Add(newNode(5)); (root.child[2].child).Add(newNode(6)); int x = 5; Console.Write("Next larger element of " + x + " is "); Console.Write(nextLargerElement(root, x).key + "\n");}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find next larger element// in an n-ary tree. // Structure of a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; var res = null; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.child = []; return temp;} function nextLargerElementUtil(root, x){ if (root == null) return; // if root is less than res but // greater than x, update res if (root.key > x) if ((res == null || (res).key > root.key)) res = root; // Number of children of root var numChildren = root.child.length; // Recur calling for every child for (var i = 0; i < numChildren; i++) nextLargerElementUtil(root.child[i], x); return;} // Function to find next Greater element// of x in treefunction nextLargerElement(root, x){ // resultant node res = null; // calling helper function nextLargerElementUtil(root, x); return res;} // Driver Code/* Let us create below tree* 5* / | \* 1 2 3* / / \ \* 15 4 5 6*/var root = newNode(5);(root.child).push(newNode(1));(root.child).push(newNode(2));(root.child).push(newNode(3));(root.child[0].child).push(newNode(15));(root.child[1].child).push(newNode(4));(root.child[1].child).push(newNode(5));(root.child[2].child).push(newNode(6));var x = 5;document.write("Next larger element of " + x + " is ");document.write(nextLargerElement(root, x).key + "<br>"); </script>
Output:
Next larger element of 5 is 6
Next Larger element in n-ary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersNext Larger element in n-ary tree | 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 / 4:06•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=MB665oPA7SE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
princiraj1992
rrrtnx
rag2127
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 3 (Types of Binary Tree)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 285,
"s": 54,
"text": "Given a generic tree and a integer x. Find and return the node with next larger element in the tree i.e. find a node just greater than x. Return NULL if no node is present with value greater than x. For example, in the given tree "
},
{
"code": null,
"e": 325,
"s": 287,
"text": "x = 10, just greater node value is 12"
},
{
"code": null,
"e": 336,
"s": 327,
"text": "Chapters"
},
{
"code": null,
"e": 363,
"s": 336,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 413,
"s": 363,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 436,
"s": 413,
"text": "captions off, selected"
},
{
"code": null,
"e": 444,
"s": 436,
"text": "English"
},
{
"code": null,
"e": 468,
"s": 444,
"text": "This is a modal window."
},
{
"code": null,
"e": 537,
"s": 468,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 559,
"s": 537,
"text": "End of dialog window."
},
{
"code": null,
"e": 821,
"s": 559,
"text": "The idea is maintain a node pointer res, which will contain the final resultant node. Traverse the tree and check if root data is greater than x. If so, then compare the root data with res data. If root data is greater than n and less than res data update res. "
},
{
"code": null,
"e": 825,
"s": 821,
"text": "C++"
},
{
"code": null,
"e": 830,
"s": 825,
"text": "Java"
},
{
"code": null,
"e": 838,
"s": 830,
"text": "Python3"
},
{
"code": null,
"e": 841,
"s": 838,
"text": "C#"
},
{
"code": null,
"e": 852,
"s": 841,
"text": "Javascript"
},
{
"code": "// CPP program to find next larger element// in an n-ary tree.#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node { int key; vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; return temp;} void nextLargerElementUtil(Node* root, int x, Node** res){ if (root == NULL) return; // if root is less than res but greater than // x update res if (root->key > x) if (!(*res) || (*res)->key > root->key) *res = root; // Number of children of root int numChildren = root->child.size(); // Recur calling for every child for (int i = 0; i < numChildren; i++) nextLargerElementUtil(root->child[i], x, res); return;} // Function to find next Greater element of x in treeNode* nextLargerElement(Node* root, int x){ // resultant node Node* res = NULL; // calling helper function nextLargerElementUtil(root, x, &res); return res;} // Driver programint main(){ /* Let us create below tree * 5 * / | \\ * 1 2 3 * / / \\ \\ * 15 4 5 6 */ Node* root = newNode(5); (root->child).push_back(newNode(1)); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(3)); (root->child[0]->child).push_back(newNode(15)); (root->child[1]->child).push_back(newNode(4)); (root->child[1]->child).push_back(newNode(5)); (root->child[2]->child).push_back(newNode(6)); int x = 5; cout << \"Next larger element of \" << x << \" is \"; cout << nextLargerElement(root, x)->key << endl; return 0;}",
"e": 2550,
"s": 852,
"text": null
},
{
"code": "// Java program to find next larger element// in an n-ary tree.import java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{ int key; Vector<Node> child;};static Node res; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new Vector<>(); return temp;} static void nextLargerElementUtil(Node root, int x){ if (root == null) return; // if root is less than res but // greater than x, update res if (root.key > x) if ((res == null || (res).key > root.key)) res = root; // Number of children of root int numChildren = root.child.size(); // Recur calling for every child for (int i = 0; i < numChildren; i++) nextLargerElementUtil(root.child.get(i), x); return;} // Function to find next Greater element// of x in treestatic Node nextLargerElement(Node root, int x){ // resultant node res = null; // calling helper function nextLargerElementUtil(root, x); return res;} // Driver Codepublic static void main(String[] args){ /* Let us create below tree * 5 * / | \\ * 1 2 3 * / / \\ \\ * 15 4 5 6 */ Node root = newNode(5); (root.child).add(newNode(1)); (root.child).add(newNode(2)); (root.child).add(newNode(3)); (root.child.get(0).child).add(newNode(15)); (root.child.get(1).child).add(newNode(4)); (root.child.get(1).child).add(newNode(5)); (root.child.get(2).child).add(newNode(6)); int x = 5; System.out.print(\"Next larger element of \" + x + \" is \"); System.out.print(nextLargerElement(root, x).key + \"\\n\"); }} // This code is contributed by 29AjayKumar",
"e": 4329,
"s": 2550,
"text": null
},
{
"code": "# Python program to find next larger element# in an n-ary tree.class Node: # Structure of a node of an n-ary tree def __init__(self): self.key = 0 self.child = [] # Utility function to create a new tree nodedef newNode(key): temp = Node() temp.key = key temp.child = [] return temp res = None; def nextLargerElementUtil(root,x): global res if (root == None): return; # if root is less than res but # greater than x, update res if (root.key > x): if ((res == None or (res).key > root.key)): res = root; # Number of children of root numChildren = len(root.child) # Recur calling for every child for i in range(numChildren): nextLargerElementUtil(root.child[i], x) return # Function to find next Greater element# of x in treedef nextLargerElement(root,x): # resultant node global res res=None # Calling helper function nextLargerElementUtil(root, x) return res # Driver coderoot = newNode(5)(root.child).append(newNode(1))(root.child).append(newNode(2))(root.child).append(newNode(3))(root.child[0].child).append(newNode(15))(root.child[1].child).append(newNode(4))(root.child[1].child).append(newNode(5))(root.child[2].child).append(newNode(6)) x = 5print(\"Next larger element of \" , x , \" is \",end='')print(nextLargerElement(root, x).key) # This code is contributed by rag2127.",
"e": 5765,
"s": 4329,
"text": null
},
{
"code": "// C# program to find next larger element// in an n-ary tree.using System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treeclass Node{ public int key; public List<Node> child;};static Node res; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new List<Node>(); return temp;} static void nextLargerElementUtil(Node root, int x){ if (root == null) return; // if root is less than res but // greater than x, update res if (root.key > x) if ((res == null || (res).key > root.key)) res = root; // Number of children of root int numChildren = root.child.Count; // Recur calling for every child for (int i = 0; i < numChildren; i++) nextLargerElementUtil(root.child[i], x); return;} // Function to find next Greater element// of x in treestatic Node nextLargerElement(Node root, int x){ // resultant node res = null; // calling helper function nextLargerElementUtil(root, x); return res;} // Driver Codepublic static void Main(String[] args){ /* Let us create below tree * 5 * / | \\ * 1 2 3 * / / \\ \\ * 15 4 5 6 */ Node root = newNode(5); (root.child).Add(newNode(1)); (root.child).Add(newNode(2)); (root.child).Add(newNode(3)); (root.child[0].child).Add(newNode(15)); (root.child[1].child).Add(newNode(4)); (root.child[1].child).Add(newNode(5)); (root.child[2].child).Add(newNode(6)); int x = 5; Console.Write(\"Next larger element of \" + x + \" is \"); Console.Write(nextLargerElement(root, x).key + \"\\n\");}} // This code is contributed by PrinciRaj1992",
"e": 7627,
"s": 5765,
"text": null
},
{
"code": "<script> // JavaScript program to find next larger element// in an n-ary tree. // Structure of a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; var res = null; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.child = []; return temp;} function nextLargerElementUtil(root, x){ if (root == null) return; // if root is less than res but // greater than x, update res if (root.key > x) if ((res == null || (res).key > root.key)) res = root; // Number of children of root var numChildren = root.child.length; // Recur calling for every child for (var i = 0; i < numChildren; i++) nextLargerElementUtil(root.child[i], x); return;} // Function to find next Greater element// of x in treefunction nextLargerElement(root, x){ // resultant node res = null; // calling helper function nextLargerElementUtil(root, x); return res;} // Driver Code/* Let us create below tree* 5* / | \\* 1 2 3* / / \\ \\* 15 4 5 6*/var root = newNode(5);(root.child).push(newNode(1));(root.child).push(newNode(2));(root.child).push(newNode(3));(root.child[0].child).push(newNode(15));(root.child[1].child).push(newNode(4));(root.child[1].child).push(newNode(5));(root.child[2].child).push(newNode(6));var x = 5;document.write(\"Next larger element of \" + x + \" is \");document.write(nextLargerElement(root, x).key + \"<br>\"); </script>",
"e": 9218,
"s": 7627,
"text": null
},
{
"code": null,
"e": 9228,
"s": 9218,
"text": "Output: "
},
{
"code": null,
"e": 9258,
"s": 9228,
"text": "Next larger element of 5 is 6"
},
{
"code": null,
"e": 10144,
"s": 9260,
"text": "Next Larger element in n-ary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersNext Larger element in n-ary tree | 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 / 4:06•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=MB665oPA7SE\" 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": 10559,
"s": 10144,
"text": "This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10571,
"s": 10559,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10585,
"s": 10571,
"text": "princiraj1992"
},
{
"code": null,
"e": 10592,
"s": 10585,
"text": "rrrtnx"
},
{
"code": null,
"e": 10600,
"s": 10592,
"text": "rag2127"
},
{
"code": null,
"e": 10611,
"s": 10600,
"text": "n-ary-tree"
},
{
"code": null,
"e": 10616,
"s": 10611,
"text": "Tree"
},
{
"code": null,
"e": 10621,
"s": 10616,
"text": "Tree"
},
{
"code": null,
"e": 10719,
"s": 10621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10769,
"s": 10719,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 10804,
"s": 10769,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 10838,
"s": 10804,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 10867,
"s": 10838,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 10899,
"s": 10867,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10935,
"s": 10899,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 10976,
"s": 10935,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 11040,
"s": 10976,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 11102,
"s": 11040,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
}
] |
Static Dropdown verification with Cypress
|
Cypress handles static dropdowns with the help of its in built commands. For a
static dropdown, the tagname of the element should be <select> and its child
elements should have the tagname <option>.
The command used is select(). This command needs to be chained with a command
that gives DOM elements having tagname as select. The various usage of select commands are listed below −
select(value) − The select() command with argument value selects the option
with that value. The get method should have the css selector of the static dropdown when chained with select().
select(value) − The select() command with argument value selects the option
with that value. The get method should have the css selector of the static dropdown when chained with select().
cy.get('select').select('value1')
select(text) − The select() command with argument text selects the option
with that text content. The get method should have the css selector of the static dropdown when chained with select().
select(text) − The select() command with argument text selects the option
with that text content. The get method should have the css selector of the static dropdown when chained with select().
cy.get('select').select('text')
select('Value1', 'Value2') − The select() command with arguments selects the
array of options with those values or text contents. The get method should have the css selector of the static dropdown when chained with select().
select('Value1', 'Value2') − The select() command with arguments selects the
array of options with those values or text contents. The get method should have the css selector of the static dropdown when chained with select().
cy.get('select').select(['Tutorialspoint', 'Cypress'])
select({ force: true }) − The select() command with option as argument
changes the default behavior of static dropdown. There can be three types of options − log, force and timeout having default values as true, false and
defaultCommandTimeout (4000 milliseconds) respectively.
select({ force: true }) − The select() command with option as argument
changes the default behavior of static dropdown. There can be three types of options − log, force and timeout having default values as true, false and
defaultCommandTimeout (4000 milliseconds) respectively.
cy.get('select').select('Cypress', { force: true})
The option force is used by Cypress to interact with hidden elements and
then forces to select an option from the dropdown internally.
We can apply assertions with the select() command in Cypress.
cy.get('select').select('Cypress').should('have.value', 'Cypress')
Code Implementation with select().
describe('Tutorialspoint Test', function () {
// test case
it('Test Case2', function (){
cy.visit("https://www.tutorialspoint.com/selenium /selenium_automation_practice.htm");
// checking by values
cy.get('input[type="checkbox"]')
.check(['Manual Tester','Automation Tester']);
// selecting a value from static dropdown
cy.get('select[name="continents"]').select('Europe')
// asserting the option selected
.should('have.text', 'Europe')
});
});
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "Cypress handles static dropdowns with the help of its in built commands. For a\nstatic dropdown, the tagname of the element should be <select> and its child\nelements should have the tagname <option>."
},
{
"code": null,
"e": 1445,
"s": 1261,
"text": "The command used is select(). This command needs to be chained with a command\nthat gives DOM elements having tagname as select. The various usage of select commands are listed below −"
},
{
"code": null,
"e": 1633,
"s": 1445,
"text": "select(value) − The select() command with argument value selects the option\nwith that value. The get method should have the css selector of the static dropdown when chained with select()."
},
{
"code": null,
"e": 1821,
"s": 1633,
"text": "select(value) − The select() command with argument value selects the option\nwith that value. The get method should have the css selector of the static dropdown when chained with select()."
},
{
"code": null,
"e": 1855,
"s": 1821,
"text": "cy.get('select').select('value1')"
},
{
"code": null,
"e": 2048,
"s": 1855,
"text": "select(text) − The select() command with argument text selects the option\nwith that text content. The get method should have the css selector of the static dropdown when chained with select()."
},
{
"code": null,
"e": 2241,
"s": 2048,
"text": "select(text) − The select() command with argument text selects the option\nwith that text content. The get method should have the css selector of the static dropdown when chained with select()."
},
{
"code": null,
"e": 2273,
"s": 2241,
"text": "cy.get('select').select('text')"
},
{
"code": null,
"e": 2498,
"s": 2273,
"text": "select('Value1', 'Value2') − The select() command with arguments selects the\narray of options with those values or text contents. The get method should have the css selector of the static dropdown when chained with select()."
},
{
"code": null,
"e": 2723,
"s": 2498,
"text": "select('Value1', 'Value2') − The select() command with arguments selects the\narray of options with those values or text contents. The get method should have the css selector of the static dropdown when chained with select()."
},
{
"code": null,
"e": 2778,
"s": 2723,
"text": "cy.get('select').select(['Tutorialspoint', 'Cypress'])"
},
{
"code": null,
"e": 3056,
"s": 2778,
"text": "select({ force: true }) − The select() command with option as argument\nchanges the default behavior of static dropdown. There can be three types of options − log, force and timeout having default values as true, false and\ndefaultCommandTimeout (4000 milliseconds) respectively."
},
{
"code": null,
"e": 3334,
"s": 3056,
"text": "select({ force: true }) − The select() command with option as argument\nchanges the default behavior of static dropdown. There can be three types of options − log, force and timeout having default values as true, false and\ndefaultCommandTimeout (4000 milliseconds) respectively."
},
{
"code": null,
"e": 3385,
"s": 3334,
"text": "cy.get('select').select('Cypress', { force: true})"
},
{
"code": null,
"e": 3520,
"s": 3385,
"text": "The option force is used by Cypress to interact with hidden elements and\nthen forces to select an option from the dropdown internally."
},
{
"code": null,
"e": 3582,
"s": 3520,
"text": "We can apply assertions with the select() command in Cypress."
},
{
"code": null,
"e": 3649,
"s": 3582,
"text": "cy.get('select').select('Cypress').should('have.value', 'Cypress')"
},
{
"code": null,
"e": 3684,
"s": 3649,
"text": "Code Implementation with select()."
},
{
"code": null,
"e": 4186,
"s": 3684,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Test Case2', function (){\n cy.visit(\"https://www.tutorialspoint.com/selenium /selenium_automation_practice.htm\");\n // checking by values\n cy.get('input[type=\"checkbox\"]')\n .check(['Manual Tester','Automation Tester']);\n // selecting a value from static dropdown\n cy.get('select[name=\"continents\"]').select('Europe')\n // asserting the option selected\n .should('have.text', 'Europe')\n });\n});"
}
] |
Tokenizing a String in Java
|
We have the following string −
String str = "This is demo text, and demo line!";
To tokenize the string, let us split them after every period (.) and comma (,)
String str = "This is demo text, and demo line!";
The following is the complete example.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = "This is demo text, and demo line!";
String[] res = str.split("[, .]", 0);
for(String myStr: res) {
System.out.println(myStr);
}
}
}
This
is
demo
text
and
demo
line!
|
[
{
"code": null,
"e": 1093,
"s": 1062,
"text": "We have the following string −"
},
{
"code": null,
"e": 1143,
"s": 1093,
"text": "String str = \"This is demo text, and demo line!\";"
},
{
"code": null,
"e": 1222,
"s": 1143,
"text": "To tokenize the string, let us split them after every period (.) and comma (,)"
},
{
"code": null,
"e": 1272,
"s": 1222,
"text": "String str = \"This is demo text, and demo line!\";"
},
{
"code": null,
"e": 1311,
"s": 1272,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": " Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1322,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = \"This is demo text, and demo line!\";\n String[] res = str.split(\"[, .]\", 0);\n for(String myStr: res) {\n System.out.println(myStr);\n }\n }\n}"
},
{
"code": null,
"e": 1609,
"s": 1575,
"text": "This\nis\ndemo\ntext\n\nand\ndemo\nline!"
}
] |
C++ Overloading (Operator and Function)
|
C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types −
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below −
#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Following is the list of operators which can be overloaded −
Following is the list of operators, which can not be overloaded −
Here are various operator overloading examples to help you in understanding the concept.
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": 2499,
"s": 2318,
"text": "C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively."
},
{
"code": null,
"e": 2742,
"s": 2499,
"text": "An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation)."
},
{
"code": null,
"e": 3099,
"s": 2742,
"text": "When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution."
},
{
"code": null,
"e": 3379,
"s": 3099,
"text": "You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type."
},
{
"code": null,
"e": 3478,
"s": 3379,
"text": "Following is the example where same function print() is being used to print different data types −"
},
{
"code": null,
"e": 4038,
"s": 3478,
"text": "#include <iostream>\nusing namespace std;\n \nclass printData {\n public:\n void print(int i) {\n cout << \"Printing int: \" << i << endl;\n }\n void print(double f) {\n cout << \"Printing float: \" << f << endl;\n }\n void print(char* c) {\n cout << \"Printing character: \" << c << endl;\n }\n};\n\nint main(void) {\n printData pd;\n \n // Call print to print integer\n pd.print(5);\n \n // Call print to print float\n pd.print(500.263);\n \n // Call print to print character\n pd.print(\"Hello C++\");\n \n return 0;\n}"
},
{
"code": null,
"e": 4119,
"s": 4038,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4190,
"s": 4119,
"text": "Printing int: 5\nPrinting float: 500.263\nPrinting character: Hello C++\n"
},
{
"code": null,
"e": 4338,
"s": 4190,
"text": "You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well."
},
{
"code": null,
"e": 4559,
"s": 4338,
"text": "Overloaded operators are functions with special names: the keyword \"operator\" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list."
},
{
"code": null,
"e": 4587,
"s": 4559,
"text": "Box operator+(const Box&);\n"
},
{
"code": null,
"e": 4930,
"s": 4587,
"text": "declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows −"
},
{
"code": null,
"e": 4970,
"s": 4930,
"text": "Box operator+(const Box&, const Box&);\n"
},
{
"code": null,
"e": 5256,
"s": 4970,
"text": "Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below −"
},
{
"code": null,
"e": 6921,
"s": 5256,
"text": "#include <iostream>\nusing namespace std;\n\nclass Box {\n public:\n double getVolume(void) {\n return length * breadth * height;\n }\n void setLength( double len ) {\n length = len;\n }\n void setBreadth( double bre ) {\n breadth = bre;\n }\n void setHeight( double hei ) {\n height = hei;\n }\n \n // Overload + operator to add two Box objects.\n Box operator+(const Box& b) {\n Box box;\n box.length = this->length + b.length;\n box.breadth = this->breadth + b.breadth;\n box.height = this->height + b.height;\n return box;\n }\n \n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n\n// Main function for the program\nint main() {\n Box Box1; // Declare Box1 of type Box\n Box Box2; // Declare Box2 of type Box\n Box Box3; // Declare Box3 of type Box\n double volume = 0.0; // Store the volume of a box here\n \n // box 1 specification\n Box1.setLength(6.0); \n Box1.setBreadth(7.0); \n Box1.setHeight(5.0);\n \n // box 2 specification\n Box2.setLength(12.0); \n Box2.setBreadth(13.0); \n Box2.setHeight(10.0);\n \n // volume of box 1\n volume = Box1.getVolume();\n cout << \"Volume of Box1 : \" << volume <<endl;\n \n // volume of box 2\n volume = Box2.getVolume();\n cout << \"Volume of Box2 : \" << volume <<endl;\n\n // Add two object as follows:\n Box3 = Box1 + Box2;\n\n // volume of box 3\n volume = Box3.getVolume();\n cout << \"Volume of Box3 : \" << volume <<endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 7002,
"s": 6921,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7068,
"s": 7002,
"text": "Volume of Box1 : 210\nVolume of Box2 : 1560\nVolume of Box3 : 5400\n"
},
{
"code": null,
"e": 7129,
"s": 7068,
"text": "Following is the list of operators which can be overloaded −"
},
{
"code": null,
"e": 7195,
"s": 7129,
"text": "Following is the list of operators, which can not be overloaded −"
},
{
"code": null,
"e": 7284,
"s": 7195,
"text": "Here are various operator overloading examples to help you in understanding the concept."
},
{
"code": null,
"e": 7321,
"s": 7284,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 7340,
"s": 7321,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7372,
"s": 7340,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 7395,
"s": 7372,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 7431,
"s": 7395,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 7448,
"s": 7431,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7483,
"s": 7448,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7500,
"s": 7483,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7535,
"s": 7500,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7552,
"s": 7535,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7587,
"s": 7552,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7604,
"s": 7587,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7611,
"s": 7604,
"text": " Print"
},
{
"code": null,
"e": 7622,
"s": 7611,
"text": " Add Notes"
}
] |
Market Response Models. Predicting incremental gains of... | by Barış Karaman | Towards Data Science
|
This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning.
I will cover all the topics in the following nine articles:
1- Know Your Metrics
2- Customer Segmentation
3- Customer Lifetime Value Prediction
4- Churn Prediction
5- Predicting Next Purchase Day
6- Predicting Sales
7- Market Response Models
8- Uplift Modeling
9- A/B Testing Design and Execution
Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:
Sometimes you gotta run before you can walk — Tony Stark
As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only.
Alright, let’s start.
By using the models we have built in the previous articles, we can easily segment the customers and predict their lifetime value (LTV) for targeting purposes. As a side note, we also know what will be our sales numbers. But how we can increase our sales? If we do a discount today, how many incremental transactions should we expect?
Segmenting customers and doing A/B tests enable us to try lots of different ideas for generating incremental sales. This is one of the building blocks of Growth Hacking. You need to ideate and experiment continuously to find growth opportunities.
Splitting the customers who we are going to send the offer into test and control groups helps us to calculate incremental gains.
Let’s see the example below:
In this setup, the target group was divided into three groups to find an answer to the questions below:
1- Does giving an offer increase conversion?
2- If yes, what kind of offer performs best? Discount or Buy One Get One?
Assuming the results are statistically significant, Discount (Group A) looks the best as it’s increased the conversion by 3% compared to the Control group and brought 1% more conversion against Buy One Get One.
Of course in the real world, it is much more complicated. Some offers perform better on specific segments. So you need to create a portfolio of offers for selected segments. Moreover, you can’t count on conversion as the only criterion of success. There is always a cost trade-off. Generally, while conversion rates go up, cost increases too. That’s why sometimes you need to select an offer that is cost-friendly but brings less conversion.
Now we know which offer performed well compared to others thanks to the experiment. But what about predicting it? If we predict the effect of giving an offer, we can easily maximize our transactions and have a forecast of the cost. Market Response Models help us building this framework. But there is more than one way of doing it. We can group them into two:
1- If you don’t have a control group (imagine you did an open promotion to everyone and announced it on social media), then you cannot calculate the incrementality. For this kind of situation, better to build a regression model that predicts overall sales. The prior assumption will be that the model will provide higher sales numbers for the promo days.
To build this kind of model, your dataset should include promo & non-promo days sales numbers so that the machine learning model can calculate the incrementality.
2- If you have a control group, you can build the response model based on segment or individual level. For both of them, the assumption is the same. Giving an offer should increase the probability of conversion. The uptick in the individuals’ conversion probability will bring us the incremental conversion.
Let’s jump into coding and see how we can build an individual level response model. In this example, we will be using the marketing dataset here. But I’ve done some alterations to make it more relevant to our case (which you can find here.)
Let’s import the libraries we need and import our data:
First 10 rows of our data:
Our first 8 columns are providing individual-level data and conversion column is our label to predict:
recency: months since last purchase
history: $value of the historical purchases
used_discount/used_bogo: indicates if the customer used a discount or buy one get one before
zip_code: class of the zip code as Suburban/Urban/Rural
is_referral: indicates if the customer was acquired from referral channel
channel: channels that the customer using, Phone/Web/Multichannel
offer: the offers sent to the customers, Discount/But One Get One/No Offer
We will be building a binary classification model for scoring the conversion probability of all customers. For doing that, we are going to follow the steps below:
Building the uplift formula
Exploratory Data Analysis (EDA) & Feature Engineering
Scoring the conversion probabilities
Observing the results on the test set
First off, we need to build a function that calculates our uplift. To keep it simple, we will assume every conversion means 1 order and the average order value is 25$.
We are going to calculate three types of uplift:
Conversion Uplift: Conversion rate of test group - conversion rate of control group
Order Uplift: Conversion uplift * # converted customer in test group
Revenue Uplift: Order Uplift * Average order $ value
Let’s build our calc_uplift function:
def calc_uplift(df): #assigning 25$ to the average order value avg_order_value = 25 #calculate conversions for each offer type base_conv = df[df.offer == 'No Offer']['conversion'].mean() disc_conv = df[df.offer == 'Discount']['conversion'].mean() bogo_conv = df[df.offer == 'Buy One Get One']['conversion'].mean() #calculate conversion uplift for discount and bogo disc_conv_uplift = disc_conv - base_conv bogo_conv_uplift = bogo_conv - base_conv #calculate order uplift disc_order_uplift = disc_conv_uplift * len(df[df.offer == 'Discount']['conversion']) bogo_order_uplift = bogo_conv_uplift * len(df[df.offer == 'Buy One Get One']['conversion']) #calculate revenue uplift disc_rev_uplift = disc_order_uplift * avg_order_value bogo_rev_uplift = bogo_order_uplift * avg_order_value print('Discount Conversion Uplift: {0}%'.format(np.round(disc_conv_uplift*100,2))) print('Discount Order Uplift: {0}'.format(np.round(disc_order_uplift,2))) print('Discount Revenue Uplift: ${0}\n'.format(np.round(disc_rev_uplift,2))) print('-------------- \n')print('BOGO Conversion Uplift: {0}%'.format(np.round(bogo_conv_uplift*100,2))) print('BOGO Order Uplift: {0}'.format(np.round(bogo_order_uplift,2))) print('BOGO Revenue Uplift: ${0}'.format(np.round(bogo_rev_uplift,2)))
If we apply this function to our dataframe, we will see the results below:
Discount looks like a better option if we want to get more conversion. It brings 7.6% uptick compared to the customers who didn’t receive any offer. BOGO (Buy One Get One) has 4.5% uptick as well.
Let’s start exploring which factors are the drivers of this incremental change.
We check every feature one by one to find out their impact on conversion
1- Recency
Ideally, the conversion should go down while recency goes up since inactive customers are less likely to buy again:
df_plot = df_data.groupby('recency').conversion.mean().reset_index()plot_data = [ go.Bar( x=df_plot['recency'], y=df_plot['conversion'], )]plot_layout = go.Layout( xaxis={"type": "category"}, title='Recency vs Conversion', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)
It goes as expected until 11 months of recency. Then it increases. It can be due to many reasons like having less number of customers in those buckets or the effect of the given offers.
2- History
We will create a history cluster and observe its impact. Let’s apply k-means clustering to define the significant groups in history:
kmeans = KMeans(n_clusters=5)kmeans.fit(df_data[['history']])df_data['history_cluster'] = kmeans.predict(df_data[['history']])#order the cluster numbers df_data = order_cluster('history_cluster', 'history',df_data,True)#print how the clusters look likedf_data.groupby('history_cluster').agg({'history':['mean','min','max'], 'conversion':['count', 'mean']})#plot the conversion by each clusterdf_plot = df_data.groupby('history_cluster').conversion.mean().reset_index()plot_data = [ go.Bar( x=df_plot['history_cluster'], y=df_plot['conversion'], )]plot_layout = go.Layout( xaxis={"type": "category"}, title='History vs Conversion', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)
Overview of the clusters and the plot vs. conversion:
Customers with higher $ value of history are more likely to convert.
3- Used Discount & BOGO
We will check these two features together with the following code line:
df_data.groupby(['used_discount','used_bogo','offer']).agg({'conversion':'mean'})
Output:
Customers, who used both of the offers before, have the highest conversion rate.
4- Zip Code
Rural shows better conversion compared to others:
df_plot = df_data.groupby('zip_code').conversion.mean().reset_index()plot_data = [ go.Bar( x=df_plot['zip_code'], y=df_plot['conversion'], marker=dict( color=['green', 'blue', 'orange']) )]plot_layout = go.Layout( xaxis={"type": "category"}, title='Zip Code vs Conversion', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)
5- Referral
As we see below, customers from referral channel have less conversion rate:
They show almost 5% less conversion.
6- Channel
Multichannel shows higher conversion rate as we expected. Using more than one channel is an indicator of high engagement.
7- Offer Type
Customers who get discount offers show ~18% conversion whereas it is ~15% for BOGO. If customers don’t get an offer, their conversion rate drops by ~4%.
Feature Engineering of this data will be pretty simple. We will apply .get_dummies() to convert categorical columns to numerical ones:
df_model = df_data.copy()df_model = pd.get_dummies(df_model)
It is time to build our machine learning model to score conversion probabilities.
To build our model, we need to follow the steps we mentioned earlier in the articles.
Let’s start with splitting features and the label:
#create feature set and labelsX = df_model.drop(['conversion'],axis=1)y = df_model.conversion
Creating training and test sets:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=56)
We will fit the model and get the conversion probabilities. predit_proba() function of our model assigns probability for each row:
xgb_model = xgb.XGBClassifier().fit(X_train, y_train)X_test['proba'] = xgb_model.predict_proba(X_test)[:,1]
Let’s see how our probability column looks like:
From the above, we can see that our model assigned the probability of conversion (from 0 to 1) for each customer.
Finally, we need to understand if our model works well or not.
Now we assume, the difference in the probability of discount, bogo and control group should be similar to conversion differences between them.
We need to use our test set to find it out.
Let’s calculate predicted and real order upticks for discount:
real_disc_uptick = len(X_test)*(X_test[X_test['offer_Discount'] == 1].conversion.mean() - X_test[X_test['offer_No Offer'] == 1].conversion.mean())pred_disc_uptick = len(X_test)*(X_test[X_test['offer_Discount'] == 1].proba.mean() - X_test[X_test['offer_No Offer'] == 1].proba.mean())
For real uptick calculation, we used the conversion column. For the predicted one, we replaced it with proba.
The results are pretty good. The real order uptick was 966 and the model predicted it as 948 (1.8% error).
Revenue uptick prediction comparison: 24150 vs 23700.
We need to check if the results are good for BOGO as well:
real_bogo_uptick = len(X_test)*(X_test[X_test['offer_Buy One Get One'] == 1].conversion.mean() - X_test[X_test['offer_No Offer'] == 1].conversion.mean())pred_bogo_uptick = len(X_test)*(X_test[X_test['offer_Buy One Get One'] == 1].proba.mean() - X_test[X_test['offer_No Offer'] == 1].proba.mean())
Promising results for BOGO:
Order uptick - real vs predicted: 563 vs 595
Revenue uptick — real vs predicted: 14075 vs 14875
The error rate is around 5.6%. The model can benefit from improving the prediction scores on BOGO offer type.
Calculating conversion probabilities help us a lot in different areas as well. We have predicted the return of the different types of offers but it can help us to find out who to target for maximizing the uplift as well. In the next article, we will build our own uplift model.
You can find the Jupyter Notebook for this article here.
To discuss growth marketing & data science, go ahead and book a free session with me here.
|
[
{
"code": null,
"e": 423,
"s": 172,
"text": "This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning."
},
{
"code": null,
"e": 483,
"s": 423,
"text": "I will cover all the topics in the following nine articles:"
},
{
"code": null,
"e": 504,
"s": 483,
"text": "1- Know Your Metrics"
},
{
"code": null,
"e": 529,
"s": 504,
"text": "2- Customer Segmentation"
},
{
"code": null,
"e": 567,
"s": 529,
"text": "3- Customer Lifetime Value Prediction"
},
{
"code": null,
"e": 587,
"s": 567,
"text": "4- Churn Prediction"
},
{
"code": null,
"e": 619,
"s": 587,
"text": "5- Predicting Next Purchase Day"
},
{
"code": null,
"e": 639,
"s": 619,
"text": "6- Predicting Sales"
},
{
"code": null,
"e": 665,
"s": 639,
"text": "7- Market Response Models"
},
{
"code": null,
"e": 684,
"s": 665,
"text": "8- Uplift Modeling"
},
{
"code": null,
"e": 720,
"s": 684,
"text": "9- A/B Testing Design and Execution"
},
{
"code": null,
"e": 1070,
"s": 720,
"text": "Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:"
},
{
"code": null,
"e": 1127,
"s": 1070,
"text": "Sometimes you gotta run before you can walk — Tony Stark"
},
{
"code": null,
"e": 1268,
"s": 1127,
"text": "As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only."
},
{
"code": null,
"e": 1290,
"s": 1268,
"text": "Alright, let’s start."
},
{
"code": null,
"e": 1624,
"s": 1290,
"text": "By using the models we have built in the previous articles, we can easily segment the customers and predict their lifetime value (LTV) for targeting purposes. As a side note, we also know what will be our sales numbers. But how we can increase our sales? If we do a discount today, how many incremental transactions should we expect?"
},
{
"code": null,
"e": 1871,
"s": 1624,
"text": "Segmenting customers and doing A/B tests enable us to try lots of different ideas for generating incremental sales. This is one of the building blocks of Growth Hacking. You need to ideate and experiment continuously to find growth opportunities."
},
{
"code": null,
"e": 2000,
"s": 1871,
"text": "Splitting the customers who we are going to send the offer into test and control groups helps us to calculate incremental gains."
},
{
"code": null,
"e": 2029,
"s": 2000,
"text": "Let’s see the example below:"
},
{
"code": null,
"e": 2133,
"s": 2029,
"text": "In this setup, the target group was divided into three groups to find an answer to the questions below:"
},
{
"code": null,
"e": 2178,
"s": 2133,
"text": "1- Does giving an offer increase conversion?"
},
{
"code": null,
"e": 2252,
"s": 2178,
"text": "2- If yes, what kind of offer performs best? Discount or Buy One Get One?"
},
{
"code": null,
"e": 2463,
"s": 2252,
"text": "Assuming the results are statistically significant, Discount (Group A) looks the best as it’s increased the conversion by 3% compared to the Control group and brought 1% more conversion against Buy One Get One."
},
{
"code": null,
"e": 2905,
"s": 2463,
"text": "Of course in the real world, it is much more complicated. Some offers perform better on specific segments. So you need to create a portfolio of offers for selected segments. Moreover, you can’t count on conversion as the only criterion of success. There is always a cost trade-off. Generally, while conversion rates go up, cost increases too. That’s why sometimes you need to select an offer that is cost-friendly but brings less conversion."
},
{
"code": null,
"e": 3265,
"s": 2905,
"text": "Now we know which offer performed well compared to others thanks to the experiment. But what about predicting it? If we predict the effect of giving an offer, we can easily maximize our transactions and have a forecast of the cost. Market Response Models help us building this framework. But there is more than one way of doing it. We can group them into two:"
},
{
"code": null,
"e": 3620,
"s": 3265,
"text": "1- If you don’t have a control group (imagine you did an open promotion to everyone and announced it on social media), then you cannot calculate the incrementality. For this kind of situation, better to build a regression model that predicts overall sales. The prior assumption will be that the model will provide higher sales numbers for the promo days."
},
{
"code": null,
"e": 3783,
"s": 3620,
"text": "To build this kind of model, your dataset should include promo & non-promo days sales numbers so that the machine learning model can calculate the incrementality."
},
{
"code": null,
"e": 4091,
"s": 3783,
"text": "2- If you have a control group, you can build the response model based on segment or individual level. For both of them, the assumption is the same. Giving an offer should increase the probability of conversion. The uptick in the individuals’ conversion probability will bring us the incremental conversion."
},
{
"code": null,
"e": 4332,
"s": 4091,
"text": "Let’s jump into coding and see how we can build an individual level response model. In this example, we will be using the marketing dataset here. But I’ve done some alterations to make it more relevant to our case (which you can find here.)"
},
{
"code": null,
"e": 4388,
"s": 4332,
"text": "Let’s import the libraries we need and import our data:"
},
{
"code": null,
"e": 4415,
"s": 4388,
"text": "First 10 rows of our data:"
},
{
"code": null,
"e": 4518,
"s": 4415,
"text": "Our first 8 columns are providing individual-level data and conversion column is our label to predict:"
},
{
"code": null,
"e": 4554,
"s": 4518,
"text": "recency: months since last purchase"
},
{
"code": null,
"e": 4598,
"s": 4554,
"text": "history: $value of the historical purchases"
},
{
"code": null,
"e": 4691,
"s": 4598,
"text": "used_discount/used_bogo: indicates if the customer used a discount or buy one get one before"
},
{
"code": null,
"e": 4747,
"s": 4691,
"text": "zip_code: class of the zip code as Suburban/Urban/Rural"
},
{
"code": null,
"e": 4821,
"s": 4747,
"text": "is_referral: indicates if the customer was acquired from referral channel"
},
{
"code": null,
"e": 4887,
"s": 4821,
"text": "channel: channels that the customer using, Phone/Web/Multichannel"
},
{
"code": null,
"e": 4962,
"s": 4887,
"text": "offer: the offers sent to the customers, Discount/But One Get One/No Offer"
},
{
"code": null,
"e": 5125,
"s": 4962,
"text": "We will be building a binary classification model for scoring the conversion probability of all customers. For doing that, we are going to follow the steps below:"
},
{
"code": null,
"e": 5153,
"s": 5125,
"text": "Building the uplift formula"
},
{
"code": null,
"e": 5207,
"s": 5153,
"text": "Exploratory Data Analysis (EDA) & Feature Engineering"
},
{
"code": null,
"e": 5244,
"s": 5207,
"text": "Scoring the conversion probabilities"
},
{
"code": null,
"e": 5282,
"s": 5244,
"text": "Observing the results on the test set"
},
{
"code": null,
"e": 5450,
"s": 5282,
"text": "First off, we need to build a function that calculates our uplift. To keep it simple, we will assume every conversion means 1 order and the average order value is 25$."
},
{
"code": null,
"e": 5499,
"s": 5450,
"text": "We are going to calculate three types of uplift:"
},
{
"code": null,
"e": 5583,
"s": 5499,
"text": "Conversion Uplift: Conversion rate of test group - conversion rate of control group"
},
{
"code": null,
"e": 5652,
"s": 5583,
"text": "Order Uplift: Conversion uplift * # converted customer in test group"
},
{
"code": null,
"e": 5705,
"s": 5652,
"text": "Revenue Uplift: Order Uplift * Average order $ value"
},
{
"code": null,
"e": 5743,
"s": 5705,
"text": "Let’s build our calc_uplift function:"
},
{
"code": null,
"e": 7102,
"s": 5743,
"text": "def calc_uplift(df): #assigning 25$ to the average order value avg_order_value = 25 #calculate conversions for each offer type base_conv = df[df.offer == 'No Offer']['conversion'].mean() disc_conv = df[df.offer == 'Discount']['conversion'].mean() bogo_conv = df[df.offer == 'Buy One Get One']['conversion'].mean() #calculate conversion uplift for discount and bogo disc_conv_uplift = disc_conv - base_conv bogo_conv_uplift = bogo_conv - base_conv #calculate order uplift disc_order_uplift = disc_conv_uplift * len(df[df.offer == 'Discount']['conversion']) bogo_order_uplift = bogo_conv_uplift * len(df[df.offer == 'Buy One Get One']['conversion']) #calculate revenue uplift disc_rev_uplift = disc_order_uplift * avg_order_value bogo_rev_uplift = bogo_order_uplift * avg_order_value print('Discount Conversion Uplift: {0}%'.format(np.round(disc_conv_uplift*100,2))) print('Discount Order Uplift: {0}'.format(np.round(disc_order_uplift,2))) print('Discount Revenue Uplift: ${0}\\n'.format(np.round(disc_rev_uplift,2))) print('-------------- \\n')print('BOGO Conversion Uplift: {0}%'.format(np.round(bogo_conv_uplift*100,2))) print('BOGO Order Uplift: {0}'.format(np.round(bogo_order_uplift,2))) print('BOGO Revenue Uplift: ${0}'.format(np.round(bogo_rev_uplift,2)))"
},
{
"code": null,
"e": 7177,
"s": 7102,
"text": "If we apply this function to our dataframe, we will see the results below:"
},
{
"code": null,
"e": 7374,
"s": 7177,
"text": "Discount looks like a better option if we want to get more conversion. It brings 7.6% uptick compared to the customers who didn’t receive any offer. BOGO (Buy One Get One) has 4.5% uptick as well."
},
{
"code": null,
"e": 7454,
"s": 7374,
"text": "Let’s start exploring which factors are the drivers of this incremental change."
},
{
"code": null,
"e": 7527,
"s": 7454,
"text": "We check every feature one by one to find out their impact on conversion"
},
{
"code": null,
"e": 7538,
"s": 7527,
"text": "1- Recency"
},
{
"code": null,
"e": 7654,
"s": 7538,
"text": "Ideally, the conversion should go down while recency goes up since inactive customers are less likely to buy again:"
},
{
"code": null,
"e": 8070,
"s": 7654,
"text": "df_plot = df_data.groupby('recency').conversion.mean().reset_index()plot_data = [ go.Bar( x=df_plot['recency'], y=df_plot['conversion'], )]plot_layout = go.Layout( xaxis={\"type\": \"category\"}, title='Recency vs Conversion', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)"
},
{
"code": null,
"e": 8256,
"s": 8070,
"text": "It goes as expected until 11 months of recency. Then it increases. It can be due to many reasons like having less number of customers in those buckets or the effect of the given offers."
},
{
"code": null,
"e": 8267,
"s": 8256,
"text": "2- History"
},
{
"code": null,
"e": 8400,
"s": 8267,
"text": "We will create a history cluster and observe its impact. Let’s apply k-means clustering to define the significant groups in history:"
},
{
"code": null,
"e": 9224,
"s": 8400,
"text": "kmeans = KMeans(n_clusters=5)kmeans.fit(df_data[['history']])df_data['history_cluster'] = kmeans.predict(df_data[['history']])#order the cluster numbers df_data = order_cluster('history_cluster', 'history',df_data,True)#print how the clusters look likedf_data.groupby('history_cluster').agg({'history':['mean','min','max'], 'conversion':['count', 'mean']})#plot the conversion by each clusterdf_plot = df_data.groupby('history_cluster').conversion.mean().reset_index()plot_data = [ go.Bar( x=df_plot['history_cluster'], y=df_plot['conversion'], )]plot_layout = go.Layout( xaxis={\"type\": \"category\"}, title='History vs Conversion', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)"
},
{
"code": null,
"e": 9278,
"s": 9224,
"text": "Overview of the clusters and the plot vs. conversion:"
},
{
"code": null,
"e": 9347,
"s": 9278,
"text": "Customers with higher $ value of history are more likely to convert."
},
{
"code": null,
"e": 9371,
"s": 9347,
"text": "3- Used Discount & BOGO"
},
{
"code": null,
"e": 9443,
"s": 9371,
"text": "We will check these two features together with the following code line:"
},
{
"code": null,
"e": 9525,
"s": 9443,
"text": "df_data.groupby(['used_discount','used_bogo','offer']).agg({'conversion':'mean'})"
},
{
"code": null,
"e": 9533,
"s": 9525,
"text": "Output:"
},
{
"code": null,
"e": 9614,
"s": 9533,
"text": "Customers, who used both of the offers before, have the highest conversion rate."
},
{
"code": null,
"e": 9626,
"s": 9614,
"text": "4- Zip Code"
},
{
"code": null,
"e": 9676,
"s": 9626,
"text": "Rural shows better conversion compared to others:"
},
{
"code": null,
"e": 10157,
"s": 9676,
"text": "df_plot = df_data.groupby('zip_code').conversion.mean().reset_index()plot_data = [ go.Bar( x=df_plot['zip_code'], y=df_plot['conversion'], marker=dict( color=['green', 'blue', 'orange']) )]plot_layout = go.Layout( xaxis={\"type\": \"category\"}, title='Zip Code vs Conversion', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)"
},
{
"code": null,
"e": 10169,
"s": 10157,
"text": "5- Referral"
},
{
"code": null,
"e": 10245,
"s": 10169,
"text": "As we see below, customers from referral channel have less conversion rate:"
},
{
"code": null,
"e": 10282,
"s": 10245,
"text": "They show almost 5% less conversion."
},
{
"code": null,
"e": 10293,
"s": 10282,
"text": "6- Channel"
},
{
"code": null,
"e": 10415,
"s": 10293,
"text": "Multichannel shows higher conversion rate as we expected. Using more than one channel is an indicator of high engagement."
},
{
"code": null,
"e": 10429,
"s": 10415,
"text": "7- Offer Type"
},
{
"code": null,
"e": 10582,
"s": 10429,
"text": "Customers who get discount offers show ~18% conversion whereas it is ~15% for BOGO. If customers don’t get an offer, their conversion rate drops by ~4%."
},
{
"code": null,
"e": 10717,
"s": 10582,
"text": "Feature Engineering of this data will be pretty simple. We will apply .get_dummies() to convert categorical columns to numerical ones:"
},
{
"code": null,
"e": 10778,
"s": 10717,
"text": "df_model = df_data.copy()df_model = pd.get_dummies(df_model)"
},
{
"code": null,
"e": 10860,
"s": 10778,
"text": "It is time to build our machine learning model to score conversion probabilities."
},
{
"code": null,
"e": 10946,
"s": 10860,
"text": "To build our model, we need to follow the steps we mentioned earlier in the articles."
},
{
"code": null,
"e": 10997,
"s": 10946,
"text": "Let’s start with splitting features and the label:"
},
{
"code": null,
"e": 11091,
"s": 10997,
"text": "#create feature set and labelsX = df_model.drop(['conversion'],axis=1)y = df_model.conversion"
},
{
"code": null,
"e": 11124,
"s": 11091,
"text": "Creating training and test sets:"
},
{
"code": null,
"e": 11214,
"s": 11124,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=56)"
},
{
"code": null,
"e": 11345,
"s": 11214,
"text": "We will fit the model and get the conversion probabilities. predit_proba() function of our model assigns probability for each row:"
},
{
"code": null,
"e": 11453,
"s": 11345,
"text": "xgb_model = xgb.XGBClassifier().fit(X_train, y_train)X_test['proba'] = xgb_model.predict_proba(X_test)[:,1]"
},
{
"code": null,
"e": 11502,
"s": 11453,
"text": "Let’s see how our probability column looks like:"
},
{
"code": null,
"e": 11616,
"s": 11502,
"text": "From the above, we can see that our model assigned the probability of conversion (from 0 to 1) for each customer."
},
{
"code": null,
"e": 11679,
"s": 11616,
"text": "Finally, we need to understand if our model works well or not."
},
{
"code": null,
"e": 11822,
"s": 11679,
"text": "Now we assume, the difference in the probability of discount, bogo and control group should be similar to conversion differences between them."
},
{
"code": null,
"e": 11866,
"s": 11822,
"text": "We need to use our test set to find it out."
},
{
"code": null,
"e": 11929,
"s": 11866,
"text": "Let’s calculate predicted and real order upticks for discount:"
},
{
"code": null,
"e": 12212,
"s": 11929,
"text": "real_disc_uptick = len(X_test)*(X_test[X_test['offer_Discount'] == 1].conversion.mean() - X_test[X_test['offer_No Offer'] == 1].conversion.mean())pred_disc_uptick = len(X_test)*(X_test[X_test['offer_Discount'] == 1].proba.mean() - X_test[X_test['offer_No Offer'] == 1].proba.mean())"
},
{
"code": null,
"e": 12322,
"s": 12212,
"text": "For real uptick calculation, we used the conversion column. For the predicted one, we replaced it with proba."
},
{
"code": null,
"e": 12429,
"s": 12322,
"text": "The results are pretty good. The real order uptick was 966 and the model predicted it as 948 (1.8% error)."
},
{
"code": null,
"e": 12483,
"s": 12429,
"text": "Revenue uptick prediction comparison: 24150 vs 23700."
},
{
"code": null,
"e": 12542,
"s": 12483,
"text": "We need to check if the results are good for BOGO as well:"
},
{
"code": null,
"e": 12839,
"s": 12542,
"text": "real_bogo_uptick = len(X_test)*(X_test[X_test['offer_Buy One Get One'] == 1].conversion.mean() - X_test[X_test['offer_No Offer'] == 1].conversion.mean())pred_bogo_uptick = len(X_test)*(X_test[X_test['offer_Buy One Get One'] == 1].proba.mean() - X_test[X_test['offer_No Offer'] == 1].proba.mean())"
},
{
"code": null,
"e": 12867,
"s": 12839,
"text": "Promising results for BOGO:"
},
{
"code": null,
"e": 12912,
"s": 12867,
"text": "Order uptick - real vs predicted: 563 vs 595"
},
{
"code": null,
"e": 12963,
"s": 12912,
"text": "Revenue uptick — real vs predicted: 14075 vs 14875"
},
{
"code": null,
"e": 13073,
"s": 12963,
"text": "The error rate is around 5.6%. The model can benefit from improving the prediction scores on BOGO offer type."
},
{
"code": null,
"e": 13351,
"s": 13073,
"text": "Calculating conversion probabilities help us a lot in different areas as well. We have predicted the return of the different types of offers but it can help us to find out who to target for maximizing the uplift as well. In the next article, we will build our own uplift model."
},
{
"code": null,
"e": 13408,
"s": 13351,
"text": "You can find the Jupyter Notebook for this article here."
}
] |
Perform NAND/NOR operations in MySQL
|
Let us first see how we can perform NAND/NOR operations in MySQL. The concept is as follows −
NAND= NOT( yourColumnName1 AND yourColumnName2)
NOR=NOT( yourColumnName1 OR yourColumnName2)
Let us first create a table −
mysql> create table DemoTable
(
Value1 boolean ,
Value2 boolean
);
Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(true,true);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(false,false);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(false,true);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(true,false);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 1 | 1 |
| 0 | 0 |
| 0 | 1 |
| 1 | 0 |
+--------+--------+
4 rows in set (0.00 sec)
Following is the query to perform NAND/NOR operations −
mysql> select Value1,Value2, NOT(Value1 AND Value2) AS NAND_Result,NOT(Value1 OR Value2) AS NOR_Result from DemoTable;
This will produce the following output −
+--------+--------+-------------+------------+
| Value1 | Value2 | NAND_Result | NOR_Result |
+--------+--------+-------------+------------+
| 1 | 1 | 0 | 0 |
| 0 | 0 | 1 | 1 |
| 0 | 1 | 1 | 0 |
| 1 | 0 | 1 | 0 |
+--------+--------+-------------+------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "Let us first see how we can perform NAND/NOR operations in MySQL. The concept is as follows −"
},
{
"code": null,
"e": 1249,
"s": 1156,
"text": "NAND= NOT( yourColumnName1 AND yourColumnName2)\nNOR=NOT( yourColumnName1 OR yourColumnName2)"
},
{
"code": null,
"e": 1279,
"s": 1249,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1389,
"s": 1279,
"text": "mysql> create table DemoTable\n(\n Value1 boolean ,\n Value2 boolean\n);\nQuery OK, 0 rows affected (0.72 sec)"
},
{
"code": null,
"e": 1445,
"s": 1389,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1785,
"s": 1445,
"text": "mysql> insert into DemoTable values(true,true);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(false,false);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(false,true);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(true,false);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1845,
"s": 1785,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1876,
"s": 1845,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1917,
"s": 1876,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2102,
"s": 1917,
"text": "+--------+--------+\n| Value1 | Value2 |\n+--------+--------+\n| 1 | 1 |\n| 0 | 0 |\n| 0 | 1 |\n| 1 | 0 |\n+--------+--------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2158,
"s": 2102,
"text": "Following is the query to perform NAND/NOR operations −"
},
{
"code": null,
"e": 2277,
"s": 2158,
"text": "mysql> select Value1,Value2, NOT(Value1 AND Value2) AS NAND_Result,NOT(Value1 OR Value2) AS NOR_Result from DemoTable;"
},
{
"code": null,
"e": 2318,
"s": 2277,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2719,
"s": 2318,
"text": "+--------+--------+-------------+------------+\n| Value1 | Value2 | NAND_Result | NOR_Result |\n+--------+--------+-------------+------------+\n| 1 | 1 | 0 | 0 |\n| 0 | 0 | 1 | 1 |\n| 0 | 1 | 1 | 0 |\n| 1 | 0 | 1 | 0 |\n+--------+--------+-------------+------------+\n4 rows in set (0.00 sec)"
}
] |
ASP Server.MapPath Method - GeeksforGeeks
|
02 Mar, 2021
The MapPath method is used to define a relative virtual path for a physical directory on the server.
Note: This method cannot be used in Session.OnEnd and Application.OnEnd.
Syntax:
Server.MapPath(path)
Parameter Value:
path: It stores a string value that defines the relative or virtual path to map to a physical directory. If the path starts with either a forward slash(/) or backward slash(\) the MapPath Method returns a path as if the path is a full virtual path. If the path doesn’t start with a slash, the MapPath Method returns a path relative to a directory of the .asp file being processed.
Example Code: Below code that demonstrates the use of the Server.MapPath Method.
<%
response.write(Server.MapPath("test.asp") & "<br>")
response.write(Server.MapPath("script/test.asp") & "<br>")
response.write(Server.MapPath("/script/test.asp") & "<br>")
response.write(Server.MapPath("\script") & "<br>")
response.write(Server.MapPath("/") & "<br>")
response.write(Server.MapPath("\") & "<br>")
%>
Output
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script\script\test.asp
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script
c:\inetpub\wwwroot
c:\inetpub\wwwroot
ASP-Methods
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
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
Differences between Functional Components and Class Components in React
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?
How to execute PHP code using command line ?
REST API (Introduction)
|
[
{
"code": null,
"e": 24525,
"s": 24497,
"text": "\n02 Mar, 2021"
},
{
"code": null,
"e": 24633,
"s": 24525,
"text": "The MapPath method is used to define a relative virtual path for a physical directory on the server. "
},
{
"code": null,
"e": 24706,
"s": 24633,
"text": "Note: This method cannot be used in Session.OnEnd and Application.OnEnd."
},
{
"code": null,
"e": 24714,
"s": 24706,
"text": "Syntax:"
},
{
"code": null,
"e": 24798,
"s": 24714,
"text": "Server.MapPath(path) "
},
{
"code": null,
"e": 24817,
"s": 24798,
"text": " Parameter Value:"
},
{
"code": null,
"e": 25198,
"s": 24817,
"text": "path: It stores a string value that defines the relative or virtual path to map to a physical directory. If the path starts with either a forward slash(/) or backward slash(\\) the MapPath Method returns a path as if the path is a full virtual path. If the path doesn’t start with a slash, the MapPath Method returns a path relative to a directory of the .asp file being processed."
},
{
"code": null,
"e": 25279,
"s": 25198,
"text": "Example Code: Below code that demonstrates the use of the Server.MapPath Method."
},
{
"code": null,
"e": 25597,
"s": 25279,
"text": "<%\nresponse.write(Server.MapPath(\"test.asp\") & \"<br>\")\nresponse.write(Server.MapPath(\"script/test.asp\") & \"<br>\")\nresponse.write(Server.MapPath(\"/script/test.asp\") & \"<br>\")\nresponse.write(Server.MapPath(\"\\script\") & \"<br>\")\nresponse.write(Server.MapPath(\"/\") & \"<br>\")\nresponse.write(Server.MapPath(\"\\\") & \"<br>\")\n%>"
},
{
"code": null,
"e": 25606,
"s": 25597,
"text": "Output "
},
{
"code": null,
"e": 25782,
"s": 25606,
"text": "c:\\inetpub\\wwwroot\\script\\test.asp\nc:\\inetpub\\wwwroot\\script\\script\\test.asp\nc:\\inetpub\\wwwroot\\script\\test.asp\nc:\\inetpub\\wwwroot\\script\nc:\\inetpub\\wwwroot\nc:\\inetpub\\wwwroot"
},
{
"code": null,
"e": 25794,
"s": 25782,
"text": "ASP-Methods"
},
{
"code": null,
"e": 25811,
"s": 25794,
"text": "Web Technologies"
},
{
"code": null,
"e": 25909,
"s": 25811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25918,
"s": 25909,
"text": "Comments"
},
{
"code": null,
"e": 25931,
"s": 25918,
"text": "Old Comments"
},
{
"code": null,
"e": 25987,
"s": 25931,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26030,
"s": 25987,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26091,
"s": 26030,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26136,
"s": 26091,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26208,
"s": 26136,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26253,
"s": 26208,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 26303,
"s": 26253,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26368,
"s": 26303,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 26413,
"s": 26368,
"text": "How to execute PHP code using command line ?"
}
] |
How to Fix: SyntaxError: positional argument follows keyword argument in Python - GeeksforGeeks
|
28 Nov, 2021
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python
An argument is a value provided to a function when you call that function. For example, look at the below program –
Python
# functiondef calculate_square(num): return num * num # call the functionresult = calculate_square(10)print(result)
100
The calculate_square() function takes in an argument num which is an integer or decimal input, calculates the square of the number and returns the value.
There are two kind of arguments, namely, keyword and positional. As the name suggests, the keyword argument is identified by a function based on some key whereas the positional argument is identified based on its position in the function definition. Let us have a look at this with an example.
Python
# functiondef foo(a, b, c=10): print('a =', a) print('b =', b) print('c =', c) # call the functionsprint("Function Call 1")foo(2, 3, 8)print("Function Call 2")foo(2, 3)print("Function Call 3")foo(a=2, c=3, b=10)
Output:
Function Call 1
a = 2
b = 3
c = 8
Function Call 2
a = 2
b = 3
c = 10
Function Call 3
a = 2
b = 10
c = 3
Explanation:
During the first function call, we provided 3 arguments with any keyword. Python interpreted in order of how they have been defined in the function that is considering position of these keywords.In the second function call, we provided 2 arguments, but still the output is shown because of we provided 2 positional argument and the function has a default value for the final argument c. So, it takes the default value into account for the final argument.In the third function call, three keyword arguments are provided. The benefit of providing this keyword argument is that you need not remember the positions but just the keywords that are required for the function call. These keywords can be provided in any order but function will take these as key-value pairs and not in the order which they are being passed.
During the first function call, we provided 3 arguments with any keyword. Python interpreted in order of how they have been defined in the function that is considering position of these keywords.
In the second function call, we provided 2 arguments, but still the output is shown because of we provided 2 positional argument and the function has a default value for the final argument c. So, it takes the default value into account for the final argument.
In the third function call, three keyword arguments are provided. The benefit of providing this keyword argument is that you need not remember the positions but just the keywords that are required for the function call. These keywords can be provided in any order but function will take these as key-value pairs and not in the order which they are being passed.
In the above 3 cases, we have seen how python can interpret the argument values that are being passed during a function call. Now, let us consider the below example which leads to a SyntaxError.
Python
# function definitiondef foo(a, b, c=10): print('a =', a) print('b =', b) print('c =', c) # call the functionprint("Function Call 4")foo(a=2, c=3, 9)
Output:
File "<ipython-input-40-982df054f26b>", line 7
foo(a=2, c=3, 9)
^
SyntaxError: positional argument follows keyword argument
Explanation:
In this example, the error occurred because of the way we have passed the arguments during the function call. The error positional argument follows keyword argument means that the if any keyword argument is used in the function call then it should always be followed by keyword arguments. Positional arguments can be written in the beginning before any keyword argument is passed. Here, a=2 and c=3 are keyword argument. The 3rd argument 9 is a positional argument. This can not be interpreted by the python as to which key holds what value. The way python works in this regards is that, it will first map the positional argument and then any keyword argument if present.
Picked
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24025,
"s": 23901,
"text": "In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 24141,
"s": 24025,
"text": "An argument is a value provided to a function when you call that function. For example, look at the below program –"
},
{
"code": null,
"e": 24148,
"s": 24141,
"text": "Python"
},
{
"code": "# functiondef calculate_square(num): return num * num # call the functionresult = calculate_square(10)print(result)",
"e": 24270,
"s": 24148,
"text": null
},
{
"code": null,
"e": 24275,
"s": 24270,
"text": "100\n"
},
{
"code": null,
"e": 24429,
"s": 24275,
"text": "The calculate_square() function takes in an argument num which is an integer or decimal input, calculates the square of the number and returns the value."
},
{
"code": null,
"e": 24723,
"s": 24429,
"text": "There are two kind of arguments, namely, keyword and positional. As the name suggests, the keyword argument is identified by a function based on some key whereas the positional argument is identified based on its position in the function definition. Let us have a look at this with an example."
},
{
"code": null,
"e": 24730,
"s": 24723,
"text": "Python"
},
{
"code": "# functiondef foo(a, b, c=10): print('a =', a) print('b =', b) print('c =', c) # call the functionsprint(\"Function Call 1\")foo(2, 3, 8)print(\"Function Call 2\")foo(2, 3)print(\"Function Call 3\")foo(a=2, c=3, b=10)",
"e": 24954,
"s": 24730,
"text": null
},
{
"code": null,
"e": 24962,
"s": 24954,
"text": "Output:"
},
{
"code": null,
"e": 25066,
"s": 24962,
"text": "Function Call 1\na = 2\nb = 3\nc = 8\nFunction Call 2\na = 2\nb = 3\nc = 10\nFunction Call 3\na = 2\nb = 10\nc = 3"
},
{
"code": null,
"e": 25079,
"s": 25066,
"text": "Explanation:"
},
{
"code": null,
"e": 25895,
"s": 25079,
"text": "During the first function call, we provided 3 arguments with any keyword. Python interpreted in order of how they have been defined in the function that is considering position of these keywords.In the second function call, we provided 2 arguments, but still the output is shown because of we provided 2 positional argument and the function has a default value for the final argument c. So, it takes the default value into account for the final argument.In the third function call, three keyword arguments are provided. The benefit of providing this keyword argument is that you need not remember the positions but just the keywords that are required for the function call. These keywords can be provided in any order but function will take these as key-value pairs and not in the order which they are being passed."
},
{
"code": null,
"e": 26091,
"s": 25895,
"text": "During the first function call, we provided 3 arguments with any keyword. Python interpreted in order of how they have been defined in the function that is considering position of these keywords."
},
{
"code": null,
"e": 26351,
"s": 26091,
"text": "In the second function call, we provided 2 arguments, but still the output is shown because of we provided 2 positional argument and the function has a default value for the final argument c. So, it takes the default value into account for the final argument."
},
{
"code": null,
"e": 26713,
"s": 26351,
"text": "In the third function call, three keyword arguments are provided. The benefit of providing this keyword argument is that you need not remember the positions but just the keywords that are required for the function call. These keywords can be provided in any order but function will take these as key-value pairs and not in the order which they are being passed."
},
{
"code": null,
"e": 26908,
"s": 26713,
"text": "In the above 3 cases, we have seen how python can interpret the argument values that are being passed during a function call. Now, let us consider the below example which leads to a SyntaxError."
},
{
"code": null,
"e": 26915,
"s": 26908,
"text": "Python"
},
{
"code": "# function definitiondef foo(a, b, c=10): print('a =', a) print('b =', b) print('c =', c) # call the functionprint(\"Function Call 4\")foo(a=2, c=3, 9)",
"e": 27079,
"s": 26915,
"text": null
},
{
"code": null,
"e": 27087,
"s": 27079,
"text": "Output:"
},
{
"code": null,
"e": 27232,
"s": 27087,
"text": "File \"<ipython-input-40-982df054f26b>\", line 7\n foo(a=2, c=3, 9)\n ^\nSyntaxError: positional argument follows keyword argument"
},
{
"code": null,
"e": 27245,
"s": 27232,
"text": "Explanation:"
},
{
"code": null,
"e": 27917,
"s": 27245,
"text": "In this example, the error occurred because of the way we have passed the arguments during the function call. The error positional argument follows keyword argument means that the if any keyword argument is used in the function call then it should always be followed by keyword arguments. Positional arguments can be written in the beginning before any keyword argument is passed. Here, a=2 and c=3 are keyword argument. The 3rd argument 9 is a positional argument. This can not be interpreted by the python as to which key holds what value. The way python works in this regards is that, it will first map the positional argument and then any keyword argument if present."
},
{
"code": null,
"e": 27924,
"s": 27917,
"text": "Picked"
},
{
"code": null,
"e": 27942,
"s": 27924,
"text": "Python-exceptions"
},
{
"code": null,
"e": 27949,
"s": 27942,
"text": "Python"
},
{
"code": null,
"e": 28047,
"s": 27949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28056,
"s": 28047,
"text": "Comments"
},
{
"code": null,
"e": 28069,
"s": 28056,
"text": "Old Comments"
},
{
"code": null,
"e": 28101,
"s": 28069,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28157,
"s": 28101,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28199,
"s": 28157,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28241,
"s": 28199,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28277,
"s": 28241,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28299,
"s": 28277,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28338,
"s": 28299,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28365,
"s": 28338,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28396,
"s": 28365,
"text": "Python | os.path.join() method"
}
] |
Python PIL | Image.frombytes() Method - GeeksforGeeks
|
07 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
PIL.Image.frombytes() Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data).
Syntax: PIL.Image.frombytes(mode, size, data, decoder_name=’raw’, *args)
Parameters:mode – The image mode. See: Modes.size – The image size.data – A byte buffer containing raw data for the given mode.decoder_name – What decoder to use.args – Additional parameters for the given decoder.
Returns: An Image object.
# importing image object from PILfrom PIL import Image # using tobytes data as raw for frombyte functiontobytes = b'xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1'img = Image.frombytes("L", (3, 2), tobytes) # creating list img1 = list(img.getdata())print(img1)
Output:
[120, 100, 56, 225, 183, 235]
Another Example: Here we use different raw in tobytes.
# importing image object from PILfrom PIL import Image # using tobytes data as raw for frombyte functiontobytes = b'\xbf\x8cd\xba\x7f\xe0\xf0\xb8t\xfe'img = Image.frombytes("L", (3, 2), tobytes) # creating list img1 = list(img.getdata())print(img1)
Output:
[191, 140, 100, 186, 127, 224]
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n07 Aug, 2019"
},
{
"code": null,
"e": 25864,
"s": 25537,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."
},
{
"code": null,
"e": 26046,
"s": 25864,
"text": "PIL.Image.frombytes() Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data)."
},
{
"code": null,
"e": 26119,
"s": 26046,
"text": "Syntax: PIL.Image.frombytes(mode, size, data, decoder_name=’raw’, *args)"
},
{
"code": null,
"e": 26333,
"s": 26119,
"text": "Parameters:mode – The image mode. See: Modes.size – The image size.data – A byte buffer containing raw data for the given mode.decoder_name – What decoder to use.args – Additional parameters for the given decoder."
},
{
"code": null,
"e": 26359,
"s": 26333,
"text": "Returns: An Image object."
},
{
"code": " # importing image object from PILfrom PIL import Image # using tobytes data as raw for frombyte functiontobytes = b'xd8\\xe1\\xb7\\xeb\\xa8\\xe5 \\xd2\\xb7\\xe1'img = Image.frombytes(\"L\", (3, 2), tobytes) # creating list img1 = list(img.getdata())print(img1)",
"e": 26617,
"s": 26359,
"text": null
},
{
"code": null,
"e": 26625,
"s": 26617,
"text": "Output:"
},
{
"code": null,
"e": 26656,
"s": 26625,
"text": "[120, 100, 56, 225, 183, 235]\n"
},
{
"code": null,
"e": 26711,
"s": 26656,
"text": "Another Example: Here we use different raw in tobytes."
},
{
"code": " # importing image object from PILfrom PIL import Image # using tobytes data as raw for frombyte functiontobytes = b'\\xbf\\x8cd\\xba\\x7f\\xe0\\xf0\\xb8t\\xfe'img = Image.frombytes(\"L\", (3, 2), tobytes) # creating list img1 = list(img.getdata())print(img1)",
"e": 26967,
"s": 26711,
"text": null
},
{
"code": null,
"e": 26975,
"s": 26967,
"text": "Output:"
},
{
"code": null,
"e": 27007,
"s": 26975,
"text": "[191, 140, 100, 186, 127, 224]\n"
},
{
"code": null,
"e": 27018,
"s": 27007,
"text": "Python-pil"
},
{
"code": null,
"e": 27025,
"s": 27018,
"text": "Python"
},
{
"code": null,
"e": 27123,
"s": 27025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27155,
"s": 27123,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27197,
"s": 27155,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27239,
"s": 27197,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27295,
"s": 27239,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27322,
"s": 27295,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27353,
"s": 27322,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27392,
"s": 27353,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27421,
"s": 27392,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27443,
"s": 27421,
"text": "Defaultdict in Python"
}
] |
How to use spectrum colorpicker get color with transparency ? - GeeksforGeeks
|
01 Aug, 2021
Spectrum is the distribution of colors produced when light is dispersed by a prism. Using spectrum, one can select easily the required color from the dialog. Spectrum can be used by clicking and dragging your cursor inside the picker area to highlight color. In a development field, as it plays a vital role & facilitate choosing the color with a wide range from the spectrum.
Spectrum provides an attribute named showAlpha which is used to get transparency in color. showAlpha is an attribute of Query plugin Spectrum which can be set true to get transparency in the color, otherwise set false to avoid transparency.
Syntax:
$("#colorpicker").spectrum({
showAlpha: boolean
});
Approach: For building the spectrum colorpicker, we have to follow certain points:
Add the necessary library files from the jquery & spectrum CDN in the Html file.Declare a <div> tag with id as output & input tag as colorpicker which is declared outside of the <div> tag.Declare a function for spectrum that will facilitate the choosing the color & set the value for showAlpha as true.
Add the necessary library files from the jquery & spectrum CDN in the Html file.
Declare a <div> tag with id as output & input tag as colorpicker which is declared outside of the <div> tag.
Declare a function for spectrum that will facilitate the choosing the color & set the value for showAlpha as true.
Implementing Spectrum with color transparency attribute
Step 1: Include Spectrum JQuery CDN in your HTML file.<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
Step 1: Include Spectrum JQuery CDN in your HTML file.
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
Step 2: Include Spectrum CDN in your HTML file.<script src=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js”></script><link rel=”stylesheet” type=”text/css” href=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css”>
Step 2: Include Spectrum CDN in your HTML file.
<script src=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js”></script><link rel=”stylesheet” type=”text/css” href=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css”>
Step3: Add a colorpicker and output div to <body> of your HTML file.<div id=”output” style=”height:200px;width:200px;”><h2>GeeksforGeeks<h2></div><input type=”text” id=”colorPicker”/>
Step3: Add a colorpicker and output div to <body> of your HTML file.
<div id=”output” style=”height:200px;width:200px;”><h2>GeeksforGeeks<h2></div><input type=”text” id=”colorPicker”/>
Step 4: Add Sprectrum JQuery to <script>$(document).ready(function(){
$('#colorPicker').spectrum({
color: '#fff',
showAlpha: true,
move: function(color){
$('#output').css(
'background-color', color.toRgbString());
}
});
});
Step 4: Add Sprectrum JQuery to <script>
$(document).ready(function(){
$('#colorPicker').spectrum({
color: '#fff',
showAlpha: true,
move: function(color){
$('#output').css(
'background-color', color.toRgbString());
}
});
});
Example: You are now ready to use a spectrum colorpicker with transparency.
HTML
<!DOCTYPE html><html> <head> <title>Spectrum Sample</title> <!-- Include JQuery and Spectrum CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js"> </script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css" /></head> <body> <!-- Output div to show output color --> <div id="output" style="height: 200px; width: 200px"> <h2>GeeksforGeeks</h2> </div> <!-- Spectrum colorpicker --> <input type="text" id="colorPicker" /> <script> // jQuery to show selected color in // the ouput of body tag. $(document).ready(function () { $("#colorPicker").spectrum({ color: "#fff", // showApla set true to get // transparency slider in // the spectrum. showAlpha: true, move: function (color) { $("#output").css( "background-color", color.toRgbString()); }, }); }); </script></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
jQuery-Questions
jQuery-Selectors
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
|
[
{
"code": null,
"e": 26202,
"s": 26174,
"text": "\n01 Aug, 2021"
},
{
"code": null,
"e": 26580,
"s": 26202,
"text": "Spectrum is the distribution of colors produced when light is dispersed by a prism. Using spectrum, one can select easily the required color from the dialog. Spectrum can be used by clicking and dragging your cursor inside the picker area to highlight color. In a development field, as it plays a vital role & facilitate choosing the color with a wide range from the spectrum. "
},
{
"code": null,
"e": 26821,
"s": 26580,
"text": "Spectrum provides an attribute named showAlpha which is used to get transparency in color. showAlpha is an attribute of Query plugin Spectrum which can be set true to get transparency in the color, otherwise set false to avoid transparency."
},
{
"code": null,
"e": 26829,
"s": 26821,
"text": "Syntax:"
},
{
"code": null,
"e": 26885,
"s": 26829,
"text": "$(\"#colorpicker\").spectrum({\n showAlpha: boolean\n}); "
},
{
"code": null,
"e": 26968,
"s": 26885,
"text": "Approach: For building the spectrum colorpicker, we have to follow certain points:"
},
{
"code": null,
"e": 27272,
"s": 26968,
"text": "Add the necessary library files from the jquery & spectrum CDN in the Html file.Declare a <div> tag with id as output & input tag as colorpicker which is declared outside of the <div> tag.Declare a function for spectrum that will facilitate the choosing the color & set the value for showAlpha as true. "
},
{
"code": null,
"e": 27353,
"s": 27272,
"text": "Add the necessary library files from the jquery & spectrum CDN in the Html file."
},
{
"code": null,
"e": 27462,
"s": 27353,
"text": "Declare a <div> tag with id as output & input tag as colorpicker which is declared outside of the <div> tag."
},
{
"code": null,
"e": 27578,
"s": 27462,
"text": "Declare a function for spectrum that will facilitate the choosing the color & set the value for showAlpha as true. "
},
{
"code": null,
"e": 27636,
"s": 27580,
"text": "Implementing Spectrum with color transparency attribute"
},
{
"code": null,
"e": 27779,
"s": 27636,
"text": "Step 1: Include Spectrum JQuery CDN in your HTML file.<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>"
},
{
"code": null,
"e": 27834,
"s": 27779,
"text": "Step 1: Include Spectrum JQuery CDN in your HTML file."
},
{
"code": null,
"e": 27923,
"s": 27834,
"text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>"
},
{
"code": null,
"e": 28181,
"s": 27923,
"text": "Step 2: Include Spectrum CDN in your HTML file.<script src=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js”></script><link rel=”stylesheet” type=”text/css” href=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css”>"
},
{
"code": null,
"e": 28229,
"s": 28181,
"text": "Step 2: Include Spectrum CDN in your HTML file."
},
{
"code": null,
"e": 28440,
"s": 28229,
"text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js”></script><link rel=”stylesheet” type=”text/css” href=”https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css”>"
},
{
"code": null,
"e": 28624,
"s": 28440,
"text": "Step3: Add a colorpicker and output div to <body> of your HTML file.<div id=”output” style=”height:200px;width:200px;”><h2>GeeksforGeeks<h2></div><input type=”text” id=”colorPicker”/>"
},
{
"code": null,
"e": 28693,
"s": 28624,
"text": "Step3: Add a colorpicker and output div to <body> of your HTML file."
},
{
"code": null,
"e": 28809,
"s": 28693,
"text": "<div id=”output” style=”height:200px;width:200px;”><h2>GeeksforGeeks<h2></div><input type=”text” id=”colorPicker”/>"
},
{
"code": null,
"e": 29101,
"s": 28809,
"text": "Step 4: Add Sprectrum JQuery to <script>$(document).ready(function(){\n $('#colorPicker').spectrum({\n color: '#fff',\n showAlpha: true,\n move: function(color){\n $('#output').css(\n 'background-color', color.toRgbString());\n }\n });\n});"
},
{
"code": null,
"e": 29142,
"s": 29101,
"text": "Step 4: Add Sprectrum JQuery to <script>"
},
{
"code": null,
"e": 29394,
"s": 29142,
"text": "$(document).ready(function(){\n $('#colorPicker').spectrum({\n color: '#fff',\n showAlpha: true,\n move: function(color){\n $('#output').css(\n 'background-color', color.toRgbString());\n }\n });\n});"
},
{
"code": null,
"e": 29470,
"s": 29394,
"text": "Example: You are now ready to use a spectrum colorpicker with transparency."
},
{
"code": null,
"e": 29475,
"s": 29470,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Spectrum Sample</title> <!-- Include JQuery and Spectrum CDN --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js\"> </script> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css\" /></head> <body> <!-- Output div to show output color --> <div id=\"output\" style=\"height: 200px; width: 200px\"> <h2>GeeksforGeeks</h2> </div> <!-- Spectrum colorpicker --> <input type=\"text\" id=\"colorPicker\" /> <script> // jQuery to show selected color in // the ouput of body tag. $(document).ready(function () { $(\"#colorPicker\").spectrum({ color: \"#fff\", // showApla set true to get // transparency slider in // the spectrum. showAlpha: true, move: function (color) { $(\"#output\").css( \"background-color\", color.toRgbString()); }, }); }); </script></body> </html>",
"e": 30742,
"s": 29475,
"text": null
},
{
"code": null,
"e": 30750,
"s": 30742,
"text": "Output:"
},
{
"code": null,
"e": 30887,
"s": 30750,
"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": 30904,
"s": 30887,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 30921,
"s": 30904,
"text": "jQuery-Selectors"
},
{
"code": null,
"e": 30928,
"s": 30921,
"text": "Picked"
},
{
"code": null,
"e": 30933,
"s": 30928,
"text": "HTML"
},
{
"code": null,
"e": 30940,
"s": 30933,
"text": "JQuery"
},
{
"code": null,
"e": 30957,
"s": 30940,
"text": "Web Technologies"
},
{
"code": null,
"e": 30962,
"s": 30957,
"text": "HTML"
},
{
"code": null,
"e": 31060,
"s": 30962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31084,
"s": 31060,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 31125,
"s": 31084,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 31162,
"s": 31125,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31191,
"s": 31162,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31211,
"s": 31191,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31257,
"s": 31211,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 31286,
"s": 31257,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31349,
"s": 31286,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 31426,
"s": 31349,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Maximum length of subarray such that all elements are equal in the subarray - GeeksforGeeks
|
16 Apr, 2021
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements.Examples:
Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements.Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical element subarray are {1}, {2}, {3}, and {4} which is of length 1.
Approach: The idea is to traverse the array store the maximum length and current length of the subarray which has the same elements. Below are the steps:
Traverse the array and check if the current element is equal to the next element then increase the value of the current length variable.Now, compare the current length with max length to update the maximum length of the subarray.If the current element is not equal to the next element then reset the length to 1 and continue this for all the elements of the array.
Traverse the array and check if the current element is equal to the next element then increase the value of the current length variable.
Now, compare the current length with max length to update the maximum length of the subarray.
If the current element is not equal to the next element then reset the length to 1 and continue this for all the elements of the array.
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 longest// subarray with same elementint longest_subarray(int arr[], int d){ int i = 0, j = 1, e = 0; for (i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << longest_subarray(arr, N);}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the longest// subarray with same elementstatic int longest_subarray(int arr[], int d){ int i = 0, j = 1, e = 0; for(i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int N = arr.length; // Function Call System.out.print(longest_subarray(arr, N));}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the longest# subarray with same elementdef longest_subarray(arr, d): (i, j, e) = (0, 1, 0) for i in range(d - 1): # Check if the elements # are same then we can # increment the length if arr[i] == arr[i + 1]: j += 1 else: # Reinitialize j j = 1 # Compare the maximum # length e with j if e < j: e = j # Return max length return e # Driver code # Given list arr[]arr = [ 1, 2, 3, 4 ]N = len(arr) # Function callprint(longest_subarray(arr, N)) # This code is contributed by rutvik_56
// C# program for the above approachusing System; class GFG{ // Function to find the longest// subarray with same elementstatic int longest_subarray(int []arr, int d){ int i = 0, j = 1, e = 0; for(i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 1, 2, 3, 4 }; int N = arr.Length; // Function Call Console.Write(longest_subarray(arr, N));}} // This code is contributed by 29AjayKumar
<script>// javascript program for the above approach // Function to find the longest // subarray with same element function longest_subarray(arr , d) { var i = 0, j = 1, e = 0; for (i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e; } // Driver Code // Given array arr var arr = [ 1, 2, 3, 4 ]; var N = arr.length; // Function Call document.write(longest_subarray(arr, N)); // This code is contributed by todaysgaurav</script>
1
Time Complexity: O(N) Auxiliary Space: O(1)
29AjayKumar
ukasp
rutvik_56
todaysgaurav
subarray
Algorithms
Analysis
Arrays
Mathematical
Arrays
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Understanding Time Complexity with Simple Examples
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Time Complexity and Space Complexity
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
|
[
{
"code": null,
"e": 26472,
"s": 26444,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 26599,
"s": 26472,
"text": "Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements.Examples: "
},
{
"code": null,
"e": 26884,
"s": 26599,
"text": "Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements.Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical element subarray are {1}, {2}, {3}, and {4} which is of length 1. "
},
{
"code": null,
"e": 27042,
"s": 26886,
"text": "Approach: The idea is to traverse the array store the maximum length and current length of the subarray which has the same elements. Below are the steps: "
},
{
"code": null,
"e": 27407,
"s": 27042,
"text": "Traverse the array and check if the current element is equal to the next element then increase the value of the current length variable.Now, compare the current length with max length to update the maximum length of the subarray.If the current element is not equal to the next element then reset the length to 1 and continue this for all the elements of the array."
},
{
"code": null,
"e": 27544,
"s": 27407,
"text": "Traverse the array and check if the current element is equal to the next element then increase the value of the current length variable."
},
{
"code": null,
"e": 27638,
"s": 27544,
"text": "Now, compare the current length with max length to update the maximum length of the subarray."
},
{
"code": null,
"e": 27774,
"s": 27638,
"text": "If the current element is not equal to the next element then reset the length to 1 and continue this for all the elements of the array."
},
{
"code": null,
"e": 27827,
"s": 27774,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27831,
"s": 27827,
"text": "C++"
},
{
"code": null,
"e": 27836,
"s": 27831,
"text": "Java"
},
{
"code": null,
"e": 27844,
"s": 27836,
"text": "Python3"
},
{
"code": null,
"e": 27847,
"s": 27844,
"text": "C#"
},
{
"code": null,
"e": 27858,
"s": 27847,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to find the longest// subarray with same elementint longest_subarray(int arr[], int d){ int i = 0, j = 1, e = 0; for (i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << longest_subarray(arr, N);}",
"e": 28661,
"s": 27858,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the longest// subarray with same elementstatic int longest_subarray(int arr[], int d){ int i = 0, j = 1, e = 0; for(i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int N = arr.length; // Function Call System.out.print(longest_subarray(arr, N));}} // This code is contributed by 29AjayKumar",
"e": 29560,
"s": 28661,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the longest# subarray with same elementdef longest_subarray(arr, d): (i, j, e) = (0, 1, 0) for i in range(d - 1): # Check if the elements # are same then we can # increment the length if arr[i] == arr[i + 1]: j += 1 else: # Reinitialize j j = 1 # Compare the maximum # length e with j if e < j: e = j # Return max length return e # Driver code # Given list arr[]arr = [ 1, 2, 3, 4 ]N = len(arr) # Function callprint(longest_subarray(arr, N)) # This code is contributed by rutvik_56",
"e": 30260,
"s": 29560,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the longest// subarray with same elementstatic int longest_subarray(int []arr, int d){ int i = 0, j = 1, e = 0; for(i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 1, 2, 3, 4 }; int N = arr.Length; // Function Call Console.Write(longest_subarray(arr, N));}} // This code is contributed by 29AjayKumar",
"e": 31157,
"s": 30260,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to find the longest // subarray with same element function longest_subarray(arr , d) { var i = 0, j = 1, e = 0; for (i = 0; i < d - 1; i++) { // Check if the elements // are same then we can // increment the length if (arr[i] == arr[i + 1]) { j = j + 1; } else { // Reinitialize j j = 1; } // Compare the maximum // length e with j if (e < j) { e = j; } } // Return max length return e; } // Driver Code // Given array arr var arr = [ 1, 2, 3, 4 ]; var N = arr.length; // Function Call document.write(longest_subarray(arr, N)); // This code is contributed by todaysgaurav</script>",
"e": 32114,
"s": 31157,
"text": null
},
{
"code": null,
"e": 32116,
"s": 32114,
"text": "1"
},
{
"code": null,
"e": 32163,
"s": 32118,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32175,
"s": 32163,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32181,
"s": 32175,
"text": "ukasp"
},
{
"code": null,
"e": 32191,
"s": 32181,
"text": "rutvik_56"
},
{
"code": null,
"e": 32204,
"s": 32191,
"text": "todaysgaurav"
},
{
"code": null,
"e": 32213,
"s": 32204,
"text": "subarray"
},
{
"code": null,
"e": 32224,
"s": 32213,
"text": "Algorithms"
},
{
"code": null,
"e": 32233,
"s": 32224,
"text": "Analysis"
},
{
"code": null,
"e": 32240,
"s": 32233,
"text": "Arrays"
},
{
"code": null,
"e": 32253,
"s": 32240,
"text": "Mathematical"
},
{
"code": null,
"e": 32260,
"s": 32253,
"text": "Arrays"
},
{
"code": null,
"e": 32273,
"s": 32260,
"text": "Mathematical"
},
{
"code": null,
"e": 32284,
"s": 32273,
"text": "Algorithms"
},
{
"code": null,
"e": 32382,
"s": 32284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32431,
"s": 32382,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32456,
"s": 32431,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32484,
"s": 32456,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 32535,
"s": 32484,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 32562,
"s": 32535,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 32615,
"s": 32562,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 32666,
"s": 32615,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 32720,
"s": 32666,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 32757,
"s": 32720,
"text": "Time Complexity and Space Complexity"
}
] |
Wand scale() function - Python - GeeksforGeeks
|
10 Aug, 2021
The scale() function is an inbuilt function in the Python Wand ImageMagick library which is used to change the image size by scaling each pixel value by given columns and rows.
Syntax:
scale(columns, rows)
Parameters: This function accepts two parameters as mentioned above and defined below:
columns: This parameter stores the number of columns to scale the image horizontally. It is in pixels.
rows: This parameter stores the number of columns to scale the image vertically. It is in pixels.
Return Value: This function returns the Wand ImageMagick object.
Original Image:
Example 1:
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as scale: # Invoke scale function with threshold as 0.8 scale.scale(200, 100) # Save the image scale.save(filename ='scale1.jpg')
Output:
Example 2:
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke scale function method with threshold 0.6 pic.scale(50, 100) # Save the image pic.save(filename ='scale2.jpg')
Output:
sagartomar9927
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 25715,
"s": 25537,
"text": "The scale() function is an inbuilt function in the Python Wand ImageMagick library which is used to change the image size by scaling each pixel value by given columns and rows. "
},
{
"code": null,
"e": 25724,
"s": 25715,
"text": "Syntax: "
},
{
"code": null,
"e": 25745,
"s": 25724,
"text": "scale(columns, rows)"
},
{
"code": null,
"e": 25834,
"s": 25745,
"text": "Parameters: This function accepts two parameters as mentioned above and defined below: "
},
{
"code": null,
"e": 25937,
"s": 25834,
"text": "columns: This parameter stores the number of columns to scale the image horizontally. It is in pixels."
},
{
"code": null,
"e": 26035,
"s": 25937,
"text": "rows: This parameter stores the number of columns to scale the image vertically. It is in pixels."
},
{
"code": null,
"e": 26100,
"s": 26035,
"text": "Return Value: This function returns the Wand ImageMagick object."
},
{
"code": null,
"e": 26118,
"s": 26100,
"text": "Original Image: "
},
{
"code": null,
"e": 26131,
"s": 26118,
"text": "Example 1: "
},
{
"code": null,
"e": 26139,
"s": 26131,
"text": "Python3"
},
{
"code": "# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as scale: # Invoke scale function with threshold as 0.8 scale.scale(200, 100) # Save the image scale.save(filename ='scale1.jpg')",
"e": 26489,
"s": 26139,
"text": null
},
{
"code": null,
"e": 26498,
"s": 26489,
"text": "Output: "
},
{
"code": null,
"e": 26510,
"s": 26498,
"text": "Example 2: "
},
{
"code": null,
"e": 26518,
"s": 26510,
"text": "Python3"
},
{
"code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke scale function method with threshold 0.6 pic.scale(50, 100) # Save the image pic.save(filename ='scale2.jpg')",
"e": 27533,
"s": 26518,
"text": null
},
{
"code": null,
"e": 27543,
"s": 27533,
"text": "Output: "
},
{
"code": null,
"e": 27560,
"s": 27545,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27577,
"s": 27560,
"text": "Image-Processing"
},
{
"code": null,
"e": 27589,
"s": 27577,
"text": "Python-wand"
},
{
"code": null,
"e": 27596,
"s": 27589,
"text": "Python"
},
{
"code": null,
"e": 27694,
"s": 27596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27726,
"s": 27694,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27768,
"s": 27726,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27810,
"s": 27768,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27837,
"s": 27810,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27893,
"s": 27837,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27915,
"s": 27893,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27954,
"s": 27915,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27985,
"s": 27954,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28014,
"s": 27985,
"text": "Create a directory in Python"
}
] |
How to fix auto keyword error in Dev-C++ - GeeksforGeeks
|
15 Jul, 2020
The auto keyword in C++ specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.
// C++ program to illustrate the auto// keyword in DevC++ compiler#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Initialize vector vector<int> v = { 1, 2, 3, 4, 5 }; // Traverse vector using auto for (auto x : v) { // Print elements of vector cout << x << " "; }}
1 2 3 4 5
If you want to traverse a vector using an auto keyword (as shown in the above code), then it will show error as:
The auto keyword introduces in C++ 11, and it is allowed to the user to leave the type deduction to the compiler itself. But while running a program in Dev-C++ then it will be showing error, because in Dev-C++ inbuilt C++98 compiler so that’s by that error occurs.
Below are the steps to solve the error:
Open Dev C++ go to ->tools.Click on ->compiler options(1st option).A new window will open and in that window click on -> settings:Go to -> code generation:In language standard column(std) choose ->ISO C++11:Click on OK and After that the code will execute and will give no error.
Open Dev C++ go to ->tools.
Click on ->compiler options(1st option).
A new window will open and in that window click on -> settings:
Go to -> code generation:
In language standard column(std) choose ->ISO C++11:
Click on OK and After that the code will execute and will give no error.
Now the code works fine and prints the expected output.
C++
C++ Programs
How To
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 25600,
"s": 25343,
"text": "The auto keyword in C++ specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime."
},
{
"code": "// C++ program to illustrate the auto// keyword in DevC++ compiler#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Initialize vector vector<int> v = { 1, 2, 3, 4, 5 }; // Traverse vector using auto for (auto x : v) { // Print elements of vector cout << x << \" \"; }}",
"e": 25925,
"s": 25600,
"text": null
},
{
"code": null,
"e": 25936,
"s": 25925,
"text": "1 2 3 4 5\n"
},
{
"code": null,
"e": 26049,
"s": 25936,
"text": "If you want to traverse a vector using an auto keyword (as shown in the above code), then it will show error as:"
},
{
"code": null,
"e": 26314,
"s": 26049,
"text": "The auto keyword introduces in C++ 11, and it is allowed to the user to leave the type deduction to the compiler itself. But while running a program in Dev-C++ then it will be showing error, because in Dev-C++ inbuilt C++98 compiler so that’s by that error occurs."
},
{
"code": null,
"e": 26354,
"s": 26314,
"text": "Below are the steps to solve the error:"
},
{
"code": null,
"e": 26634,
"s": 26354,
"text": "Open Dev C++ go to ->tools.Click on ->compiler options(1st option).A new window will open and in that window click on -> settings:Go to -> code generation:In language standard column(std) choose ->ISO C++11:Click on OK and After that the code will execute and will give no error."
},
{
"code": null,
"e": 26662,
"s": 26634,
"text": "Open Dev C++ go to ->tools."
},
{
"code": null,
"e": 26703,
"s": 26662,
"text": "Click on ->compiler options(1st option)."
},
{
"code": null,
"e": 26767,
"s": 26703,
"text": "A new window will open and in that window click on -> settings:"
},
{
"code": null,
"e": 26793,
"s": 26767,
"text": "Go to -> code generation:"
},
{
"code": null,
"e": 26846,
"s": 26793,
"text": "In language standard column(std) choose ->ISO C++11:"
},
{
"code": null,
"e": 26919,
"s": 26846,
"text": "Click on OK and After that the code will execute and will give no error."
},
{
"code": null,
"e": 26975,
"s": 26919,
"text": "Now the code works fine and prints the expected output."
},
{
"code": null,
"e": 26979,
"s": 26975,
"text": "C++"
},
{
"code": null,
"e": 26992,
"s": 26979,
"text": "C++ Programs"
},
{
"code": null,
"e": 26999,
"s": 26992,
"text": "How To"
},
{
"code": null,
"e": 27003,
"s": 26999,
"text": "CPP"
},
{
"code": null,
"e": 27101,
"s": 27003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27129,
"s": 27101,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27149,
"s": 27129,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27182,
"s": 27149,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27206,
"s": 27182,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27231,
"s": 27206,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27266,
"s": 27231,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27310,
"s": 27266,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 27369,
"s": 27310,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27395,
"s": 27369,
"text": "C++ Program for QuickSort"
}
] |
Text portrait using CSS - GeeksforGeeks
|
28 Jul, 2021
In this article, we will learn to create a text portrait using CSS in a few simple steps. If you want to know, then keep reading this article. We have specified all the steps you need to take. So let’s start designing the text portrait.
Text portrait using CSS
Approach: Here are the steps required to get the desired text portrait.
Create an HTML document with a bunch of “GeeksforGeeks” text, for repeating the particular word, we use the JavaScript repeat() function as shown below HTML code.To darken the background in order to make the portrait appealing, use the background property along with setting the background-image using the url() function in CSS. To avoid the repetition of the image, set the background-repeat as no-repeat by placing the image at the center. For better visualization, reduce the space between the lines.In order to print the background with the foreground text, we need to clip the text & add some styling properties such as background-size, font, etc.
Create an HTML document with a bunch of “GeeksforGeeks” text, for repeating the particular word, we use the JavaScript repeat() function as shown below HTML code.
To darken the background in order to make the portrait appealing, use the background property along with setting the background-image using the url() function in CSS. To avoid the repetition of the image, set the background-repeat as no-repeat by placing the image at the center. For better visualization, reduce the space between the lines.
In order to print the background with the foreground text, we need to clip the text & add some styling properties such as background-size, font, etc.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Text Portrait using CSS</title> <style> body { background: rgb(236, 236, 236); overflow: hidden; font-family: "Segoe UI", sans-serif; } p { line-height: 14px; background: url("https://media.geeksforgeeks.org/wp-content/uploads/20210628182253/gfglogo.png"); -webkit-background-clip: text; background-attachment: fixed; background-repeat: no-repeat; -webkit-text-fill-color: rgba(255, 255, 255, 0); background-size: 80vh; background-position: center; } </style></head> <body> <p id="text"></p> <script> let str = "GeeksForGeeks "; document.getElementById("text").innerHTML = str.repeat(500); </script></body> </html>
Output:
Final output
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26645,
"s": 26617,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 26882,
"s": 26645,
"text": "In this article, we will learn to create a text portrait using CSS in a few simple steps. If you want to know, then keep reading this article. We have specified all the steps you need to take. So let’s start designing the text portrait."
},
{
"code": null,
"e": 26906,
"s": 26882,
"text": "Text portrait using CSS"
},
{
"code": null,
"e": 26978,
"s": 26906,
"text": "Approach: Here are the steps required to get the desired text portrait."
},
{
"code": null,
"e": 27631,
"s": 26978,
"text": "Create an HTML document with a bunch of “GeeksforGeeks” text, for repeating the particular word, we use the JavaScript repeat() function as shown below HTML code.To darken the background in order to make the portrait appealing, use the background property along with setting the background-image using the url() function in CSS. To avoid the repetition of the image, set the background-repeat as no-repeat by placing the image at the center. For better visualization, reduce the space between the lines.In order to print the background with the foreground text, we need to clip the text & add some styling properties such as background-size, font, etc."
},
{
"code": null,
"e": 27794,
"s": 27631,
"text": "Create an HTML document with a bunch of “GeeksforGeeks” text, for repeating the particular word, we use the JavaScript repeat() function as shown below HTML code."
},
{
"code": null,
"e": 28136,
"s": 27794,
"text": "To darken the background in order to make the portrait appealing, use the background property along with setting the background-image using the url() function in CSS. To avoid the repetition of the image, set the background-repeat as no-repeat by placing the image at the center. For better visualization, reduce the space between the lines."
},
{
"code": null,
"e": 28286,
"s": 28136,
"text": "In order to print the background with the foreground text, we need to clip the text & add some styling properties such as background-size, font, etc."
},
{
"code": null,
"e": 28295,
"s": 28286,
"text": "Example:"
},
{
"code": null,
"e": 28300,
"s": 28295,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Text Portrait using CSS</title> <style> body { background: rgb(236, 236, 236); overflow: hidden; font-family: \"Segoe UI\", sans-serif; } p { line-height: 14px; background: url(\"https://media.geeksforgeeks.org/wp-content/uploads/20210628182253/gfglogo.png\"); -webkit-background-clip: text; background-attachment: fixed; background-repeat: no-repeat; -webkit-text-fill-color: rgba(255, 255, 255, 0); background-size: 80vh; background-position: center; } </style></head> <body> <p id=\"text\"></p> <script> let str = \"GeeksForGeeks \"; document.getElementById(\"text\").innerHTML = str.repeat(500); </script></body> </html>",
"e": 29151,
"s": 28300,
"text": null
},
{
"code": null,
"e": 29159,
"s": 29151,
"text": "Output:"
},
{
"code": null,
"e": 29172,
"s": 29159,
"text": "Final output"
},
{
"code": null,
"e": 29309,
"s": 29172,
"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": 29324,
"s": 29309,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29338,
"s": 29324,
"text": "CSS-Questions"
},
{
"code": null,
"e": 29342,
"s": 29338,
"text": "CSS"
},
{
"code": null,
"e": 29347,
"s": 29342,
"text": "HTML"
},
{
"code": null,
"e": 29364,
"s": 29347,
"text": "Web Technologies"
},
{
"code": null,
"e": 29369,
"s": 29364,
"text": "HTML"
},
{
"code": null,
"e": 29467,
"s": 29369,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29504,
"s": 29467,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29543,
"s": 29504,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29572,
"s": 29543,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29614,
"s": 29572,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29649,
"s": 29614,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 29709,
"s": 29649,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29762,
"s": 29709,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29823,
"s": 29762,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29847,
"s": 29823,
"text": "REST API (Introduction)"
}
] |
How can we sort a Map by both key and value using lambda in Java?
|
A Map interface implements the Collection interface that provides the functionality of the map data structure. A Map doesn't contain any duplicate keys and each key is associated with a single value. We can able to access and modify values using the keys associated with them.
In the below two examples, we can able to sort a Map by both key and value with the help of lambda expression.
import java.util.*;
import java.util.stream.*;
public class MapSortUsingKeyTest {
public static void main(String args[]) {
// Sort a Map by their key
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(2, "India");
map.put(5, "Australia");
map.put(3, "England");
map.put(1, "Newzealand");
map.put(4, "Scotland");
Map<Integer, String> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
}
}
Sorted Map: [1=Newzealand, 2=India, 3=England, 4=Scotland, 5=Australia]
import java.util.*;
import java.util.stream.*;
public class MapSortUsingValueTest {
public static void main(String args[]) {
//Sort a Map by their Value
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Jaidev");
map.put(2, "Adithya");
map.put(3, "Vamsi");
map.put(4, "Krishna");
map.put(5, "Chaitanya");
Map<Integer, String> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
}
}
Sorted Map: [2=Adithya, 5=Chaitanya, 1=Jaidev, 4=Krishna, 3=Vamsi]
|
[
{
"code": null,
"e": 1339,
"s": 1062,
"text": "A Map interface implements the Collection interface that provides the functionality of the map data structure. A Map doesn't contain any duplicate keys and each key is associated with a single value. We can able to access and modify values using the keys associated with them."
},
{
"code": null,
"e": 1450,
"s": 1339,
"text": "In the below two examples, we can able to sort a Map by both key and value with the help of lambda expression."
},
{
"code": null,
"e": 2228,
"s": 1450,
"text": "import java.util.*;\nimport java.util.stream.*;\n\npublic class MapSortUsingKeyTest {\n public static void main(String args[]) {\n \n // Sort a Map by their key\n Map<Integer, String> map = new HashMap<Integer, String>();\n\n map.put(2, \"India\");\n map.put(5, \"Australia\");\n map.put(3, \"England\");\n map.put(1, \"Newzealand\");\n map.put(4, \"Scotland\");\n\n Map<Integer, String> sortedMap = map.entrySet().stream()\n .sorted(Map.Entry.comparingByKey())\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,\n (e1, e2) -> e2, LinkedHashMap::new));\n System.out.println(\"Sorted Map: \" + Arrays.toString(sortedMap.entrySet().toArray()));\n }\n}\n"
},
{
"code": null,
"e": 2300,
"s": 2228,
"text": "Sorted Map: [1=Newzealand, 2=India, 3=England, 4=Scotland, 5=Australia]"
},
{
"code": null,
"e": 3077,
"s": 2300,
"text": "import java.util.*;\nimport java.util.stream.*;\n\npublic class MapSortUsingValueTest {\n public static void main(String args[]) {\n \n //Sort a Map by their Value\n Map<Integer, String> map = new HashMap<Integer, String>();\n\n map.put(1, \"Jaidev\");\n map.put(2, \"Adithya\");\n map.put(3, \"Vamsi\");\n map.put(4, \"Krishna\");\n map.put(5, \"Chaitanya\");\n\n Map<Integer, String> sortedMap = map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue())\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,\n (e1, e2) -> e2, LinkedHashMap::new));\n System.out.println(\"Sorted Map: \" + Arrays.toString(sortedMap.entrySet().toArray()));\n }\n}"
},
{
"code": null,
"e": 3144,
"s": 3077,
"text": "Sorted Map: [2=Adithya, 5=Chaitanya, 1=Jaidev, 4=Krishna, 3=Vamsi]"
}
] |
Selection Sort program in C#
|
Selection Sort is a sorting algorithm that finds the minimum value in the array for each iteration of the loop. Then this minimum value is swapped with the current array element. This procedure is followed until the array is sorted.
A program that demonstrates selection sort in C# is given as follows.
Live Demo
using System;
public class Example {
static void Main(string[] args) {
int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
int temp, smallest;
for (int i = 0; i < n - 1; i++) {
smallest = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[smallest]) {
smallest = j;
}
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
Console.WriteLine();
Console.Write("Sorted array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
}
}
The output of the above program is as follows.
Selection sort
Initial array is: 56 1 99 67 89 23 44 12 78 34
Sorted array is: 1 12 23 34 44 56 67 78 89 99
Now, let us understand the above program.
First the array is initialized and its value is printed using a for loop. This can be seen in the following code snippet.
int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
A nested for loop is used for the actual sorting process. In each pass of the outer for loop, the smallest element in the array is found and replaced by the current element. This process continues until the array is sorted. This can be seen in the following code snippet.
for (int i = 0; i < n - 1; i++) {
smallest = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[smallest]) {
smallest = j;
}
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
Finally the sorted array is displayed. This can be seen in the following code snippet.
Console.Write("Sorted array is: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "Selection Sort is a sorting algorithm that finds the minimum value in the array for each iteration of the loop. Then this minimum value is swapped with the current array element. This procedure is followed until the array is sorted."
},
{
"code": null,
"e": 1365,
"s": 1295,
"text": "A program that demonstrates selection sort in C# is given as follows."
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": " Live Demo"
},
{
"code": null,
"e": 2191,
"s": 1376,
"text": "using System;\npublic class Example {\n static void Main(string[] args) {\n int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };\n int n = 10;\n Console.WriteLine(\"Selection sort\");\n Console.Write(\"Initial array is: \");\n for (int i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n }\n int temp, smallest;\n for (int i = 0; i < n - 1; i++) {\n smallest = i;\n for (int j = i + 1; j < n; j++) {\n if (arr[j] < arr[smallest]) {\n smallest = j;\n }\n }\n temp = arr[smallest];\n arr[smallest] = arr[i];\n arr[i] = temp;\n }\n Console.WriteLine();\n Console.Write(\"Sorted array is: \");\n for (int i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 2238,
"s": 2191,
"text": "The output of the above program is as follows."
},
{
"code": null,
"e": 2346,
"s": 2238,
"text": "Selection sort\nInitial array is: 56 1 99 67 89 23 44 12 78 34\nSorted array is: 1 12 23 34 44 56 67 78 89 99"
},
{
"code": null,
"e": 2388,
"s": 2346,
"text": "Now, let us understand the above program."
},
{
"code": null,
"e": 2510,
"s": 2388,
"text": "First the array is initialized and its value is printed using a for loop. This can be seen in the following code snippet."
},
{
"code": null,
"e": 2727,
"s": 2510,
"text": "int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };\nint n = 10;\nConsole.WriteLine(\"Selection sort\");\nConsole.Write(\"Initial array is: \");\nfor (int i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n}"
},
{
"code": null,
"e": 2999,
"s": 2727,
"text": "A nested for loop is used for the actual sorting process. In each pass of the outer for loop, the smallest element in the array is found and replaced by the current element. This process continues until the array is sorted. This can be seen in the following code snippet."
},
{
"code": null,
"e": 3231,
"s": 2999,
"text": "for (int i = 0; i < n - 1; i++) {\n smallest = i;\n for (int j = i + 1; j < n; j++) {\n if (arr[j] < arr[smallest]) {\n smallest = j;\n }\n }\n temp = arr[smallest];\n arr[smallest] = arr[i];\n arr[i] = temp;\n}"
},
{
"code": null,
"e": 3318,
"s": 3231,
"text": "Finally the sorted array is displayed. This can be seen in the following code snippet."
},
{
"code": null,
"e": 3418,
"s": 3318,
"text": "Console.Write(\"Sorted array is: \");\nfor (int i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n}"
}
] |
C++ Program For Finding Intersection Of Two Sorted Linked Lists - GeeksforGeeks
|
15 Dec, 2021
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
Example:
Input:
First linked list: 1->2->3->4->6
Second linked list be 2->4->6->8,
Output: 2->4->6.
The elements 2, 4, 6 are common in
both the list so they appear in the
intersection list.
Input:
First linked list: 1->2->3->4->5
Second linked list be 2->3->4,
Output: 2->3->4
The elements 2, 3, 4 are common in
both the list so they appear in the
intersection list.
Method 1: Using Dummy Node. Approach: The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’ and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>using namespace std; // Link list node struct Node { int data; Node* next;}; void push(Node** head_ref, int new_data); /* This solution uses the temporary dummy to build up the result list */Node* sortedIntersect(Node* a, Node* b){ Node dummy; Node* tail = &dummy; dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } // Advance the smaller list else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next);} // UTILITY FUNCTIONS /* Function to insert a node at the beginning of the linked list */void push(Node** head_ref, int new_data){ // Allocate node Node* new_node = (Node*)malloc(sizeof(Node)); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data <<" "; node = node->next; }} // Driver codeint main(){ // Start with the empty lists Node* a = NULL; Node* b = NULL; Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list. Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); // Find the intersection two linked lists intersect = sortedIntersect(a, b); cout << "Linked list containing common items of a & b "; printList(intersect);}
Output:
Linked list containing common items of a & b
2 4 6
Complexity Analysis:
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed.
Auxiliary Space: O(min(m, n)). The output list can store at most min(m,n) nodes .
Method 2: Recursive Solution. Approach: The recursive approach is very similar to the the above two approaches. Build a recursive function that takes two nodes and returns a linked list node. Compare the first element of both the lists.
If they are similar then call the recursive function with the next node of both the lists. Create a node with the data of the current node and put the returned node from the recursive function to the next pointer of the node created. Return the node created.
If the values are not equal then remove the smaller node of both the lists and call the recursive function.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Link list node struct Node { int data; struct Node* next;}; struct Node* sortedIntersect(struct Node* a, struct Node* b){ // Base case if (a == NULL || b == NULL) return NULL; // If both lists are non-empty /* Advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = a->data; // Advance both lists and call recursively temp->next = sortedIntersect(a->next, b->next); return temp;} // UTILITY FUNCTIONS /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { cout << " " << node->data; node = node->next; }} // Driver codeint main(){ // Start with the empty lists struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list. Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); // Find the intersection two linked lists intersect = sortedIntersect(a, b); cout << "Linked list containing " << "common items of a & b "; printList(intersect); return 0;}// This code is contributed by shivanisinghss2110
Output:
Linked list containing common items of a & b
2 4 6
Complexity Analysis:
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed.
Auxiliary Space: O(max(m, n)). The output list can store at most m+n nodes.
Please refer complete article on Intersection of two Sorted Linked Lists for more details!
Amazon
D-E-Shaw
Linked Lists
Microsoft
Zopper
C++
C++ Programs
Linked List
Sorting
Amazon
Microsoft
D-E-Shaw
Zopper
Linked List
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25531,
"s": 25503,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25745,
"s": 25531,
"text": "Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. "
},
{
"code": null,
"e": 25755,
"s": 25745,
"text": "Example: "
},
{
"code": null,
"e": 26123,
"s": 25755,
"text": "Input: \nFirst linked list: 1->2->3->4->6\nSecond linked list be 2->4->6->8, \nOutput: 2->4->6.\nThe elements 2, 4, 6 are common in \nboth the list so they appear in the \nintersection list. \n\nInput: \nFirst linked list: 1->2->3->4->5\nSecond linked list be 2->3->4, \nOutput: 2->3->4\nThe elements 2, 3, 4 are common in \nboth the list so they appear in the \nintersection list."
},
{
"code": null,
"e": 26846,
"s": 26123,
"text": "Method 1: Using Dummy Node. Approach: The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’ and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists. "
},
{
"code": null,
"e": 26897,
"s": 26846,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26901,
"s": 26897,
"text": "C++"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // Link list node struct Node { int data; Node* next;}; void push(Node** head_ref, int new_data); /* This solution uses the temporary dummy to build up the result list */Node* sortedIntersect(Node* a, Node* b){ Node dummy; Node* tail = &dummy; dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } // Advance the smaller list else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next);} // UTILITY FUNCTIONS /* Function to insert a node at the beginning of the linked list */void push(Node** head_ref, int new_data){ // Allocate node Node* new_node = (Node*)malloc(sizeof(Node)); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data <<\" \"; node = node->next; }} // Driver codeint main(){ // Start with the empty lists Node* a = NULL; Node* b = NULL; Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list. Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); // Find the intersection two linked lists intersect = sortedIntersect(a, b); cout << \"Linked list containing common items of a & b \"; printList(intersect);}",
"e": 29005,
"s": 26901,
"text": null
},
{
"code": null,
"e": 29013,
"s": 29005,
"text": "Output:"
},
{
"code": null,
"e": 29066,
"s": 29013,
"text": "Linked list containing common items of a & b \n2 4 6 "
},
{
"code": null,
"e": 29088,
"s": 29066,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 29237,
"s": 29088,
"text": "Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed."
},
{
"code": null,
"e": 29319,
"s": 29237,
"text": "Auxiliary Space: O(min(m, n)). The output list can store at most min(m,n) nodes ."
},
{
"code": null,
"e": 29557,
"s": 29319,
"text": "Method 2: Recursive Solution. Approach: The recursive approach is very similar to the the above two approaches. Build a recursive function that takes two nodes and returns a linked list node. Compare the first element of both the lists. "
},
{
"code": null,
"e": 29816,
"s": 29557,
"text": "If they are similar then call the recursive function with the next node of both the lists. Create a node with the data of the current node and put the returned node from the recursive function to the next pointer of the node created. Return the node created."
},
{
"code": null,
"e": 29924,
"s": 29816,
"text": "If the values are not equal then remove the smaller node of both the lists and call the recursive function."
},
{
"code": null,
"e": 29975,
"s": 29924,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 29979,
"s": 29975,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Link list node struct Node { int data; struct Node* next;}; struct Node* sortedIntersect(struct Node* a, struct Node* b){ // Base case if (a == NULL || b == NULL) return NULL; // If both lists are non-empty /* Advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = a->data; // Advance both lists and call recursively temp->next = sortedIntersect(a->next, b->next); return temp;} // UTILITY FUNCTIONS /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { cout << \" \" << node->data; node = node->next; }} // Driver codeint main(){ // Start with the empty lists struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list. Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); // Find the intersection two linked lists intersect = sortedIntersect(a, b); cout << \"Linked list containing \" << \"common items of a & b \"; printList(intersect); return 0;}// This code is contributed by shivanisinghss2110",
"e": 32345,
"s": 29979,
"text": null
},
{
"code": null,
"e": 32353,
"s": 32345,
"text": "Output:"
},
{
"code": null,
"e": 32405,
"s": 32353,
"text": "Linked list containing common items of a & b \n2 4 6"
},
{
"code": null,
"e": 32427,
"s": 32405,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32576,
"s": 32427,
"text": "Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively. Only one traversal of the lists are needed."
},
{
"code": null,
"e": 32652,
"s": 32576,
"text": "Auxiliary Space: O(max(m, n)). The output list can store at most m+n nodes."
},
{
"code": null,
"e": 32743,
"s": 32652,
"text": "Please refer complete article on Intersection of two Sorted Linked Lists for more details!"
},
{
"code": null,
"e": 32750,
"s": 32743,
"text": "Amazon"
},
{
"code": null,
"e": 32759,
"s": 32750,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 32772,
"s": 32759,
"text": "Linked Lists"
},
{
"code": null,
"e": 32782,
"s": 32772,
"text": "Microsoft"
},
{
"code": null,
"e": 32789,
"s": 32782,
"text": "Zopper"
},
{
"code": null,
"e": 32793,
"s": 32789,
"text": "C++"
},
{
"code": null,
"e": 32806,
"s": 32793,
"text": "C++ Programs"
},
{
"code": null,
"e": 32818,
"s": 32806,
"text": "Linked List"
},
{
"code": null,
"e": 32826,
"s": 32818,
"text": "Sorting"
},
{
"code": null,
"e": 32833,
"s": 32826,
"text": "Amazon"
},
{
"code": null,
"e": 32843,
"s": 32833,
"text": "Microsoft"
},
{
"code": null,
"e": 32852,
"s": 32843,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 32859,
"s": 32852,
"text": "Zopper"
},
{
"code": null,
"e": 32871,
"s": 32859,
"text": "Linked List"
},
{
"code": null,
"e": 32879,
"s": 32871,
"text": "Sorting"
},
{
"code": null,
"e": 32883,
"s": 32879,
"text": "CPP"
},
{
"code": null,
"e": 32981,
"s": 32883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33009,
"s": 32981,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 33029,
"s": 33009,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 33062,
"s": 33029,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 33086,
"s": 33062,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 33111,
"s": 33086,
"text": "std::string class in C++"
},
{
"code": null,
"e": 33146,
"s": 33111,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 33190,
"s": 33146,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 33216,
"s": 33190,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 33275,
"s": 33216,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Simulation Structures and Modelling in SimPy | Towards Data Science
|
Python is famous for its simple syntax and numerous libraries which make this language capable of doing almost anything. Python’s range of operations varies from moderately easy tasks like developing web and desktop applications to complex tasks like building machine learning and artificial intelligence projects.
We see systems everywhere, from an embedded system in a digital alarm clock to big systems like airports and railway stations. To run these systems efficiently and optimally, we need simulations as they provide us with readings to rely on. Engagement with surroundings and randomness are two crucial factors of systems and simulations. This article will focus on such functions of python libraries so that we can simulate a scenario as per our requirements. To achieve this goal and create the algorithm, we will use the following two built-in libraries of Python:
SimPy
Random
Scenario: To follow social distancing, as a station master you have to design a plan to minimize the number of people on the platform and keep the maximum people out in their vehicles or waiting rooms (Let’s assume that the rooms have proper measures to keep the travelers safe).
Plan: We will start by assigning arrival and departure times to the trains. A booth should be made to distribute platform tickets to passengers boarding the next arriving train.
I am assuming that you already have Python installed and have a basic knowledge. If you haven’t worked with Python before, you might want to check out this tutorial.
I prefer running the program in the shell. You can use Jupyter Notebooks as well. The first step is to install and import the required libraries. Open the Command Prompt and write:
pip install SimPypip install random
After successful installation, import the libraries using the import function:
import SimPyimport random
Before you start coding the main algorithm, it is necessary to make a clear image of how should your simulation look like. This step is most important for making a good simulation model. One should spend maximum time brainstorming, structuring, and collecting data for this step. Collecting statistical data from a trustworthy source for every uncertain moment in simulation is important. If this is compromised, the frequency of occurrence of one or more events can increase or decrease. This can result in generating false values. According to our plan, the simulation must run in the following manner:
Passenger arrives at the Railway Station and heads to the platform ticket counter. — If he is boarding the next arriving train, he gets a platform ticket. — Else, he is requested to wait in the lounge.
Passenger arrives at the Railway Station and heads to the platform ticket counter. — If he is boarding the next arriving train, he gets a platform ticket. — Else, he is requested to wait in the lounge.
2. The train arrives at the platform, passengers board the train and it departs after 10 minutes. There is also a probability that the train will delay by some minutes.
3. Passengers waiting in the lounge head to the ticket counter and the eligible ones head to the platform. Meanwhile, more passengers arrive at the station.In this way, we can minimize the number of passengers on the platform.
We will start by defining the main class which will contain a blueprint of simulation and the procedures carried out at the railway station. This class will contain some functions that will generate the required environment. This class is named as Station.
class Station(object): def __init__(self, env, num_worker): self.env = env self.worker = simpy.Resource(env, num_worker)
In this code, __init__() is a reserved method in python classes. It is called when an object is created from the class. This method allows us to define the attributes of a class. We proceed by creating some SimPy resources essential for our simulation. The variable ‘env’ is predefined and helps us to generate a virtual environment for simulation. Now think it this way, there are some resources that are provided by the station to the passengers. In this situation, it’s the workers present in the ticket counter. The number of workers will be denoted by num_worker variable.
Before proceeding, we need to learn about some more functions of SimPy and Random library. The first one being:
random.randint(a,b)
This function helps us generate a random integer between two integers a and b (both included). This will aid us in simulating random events in our process. You can use it with conditional statements by specifying a trigger condition for events.
p = random.randint(1,8)if p == 3 : print('Event Triggered') #Probability = 0.125
The second function is:
yield self.env.timeout(a)
This is used to run a process (env in this case) for a duration of a minute(s). We can further use this with the randint function to run the environment for any random integral value of time between a and b.
yield self.env.timeout(random.randint(a,b))
Now you are ready to code the function that will classify the passengers and sell platform tickets accordingly. It will also generate the schedule of trains, delay them (if needed), and print the number of passengers on the platform and in the lounge. The task will be accomplished by using the above functions with conditional statements and loops as per requirement. SimPy will help in generating and running the environment.
The first step is to define the function and its arguments. After that, all the necessary variables that govern the arrival, departure (after 10 minutes of arrival), and delay of trains will be declared.
def ticket(self, passenger): sch_train = random.randint(0,45) dep_train = sch_train + 10 print('Next train arriving after',sch_train,'minutes')
Note: The function ticket takes self and passenger as its attributes. The passenger attribute will be defined later in the run_station function.
The next task is to set a condition to delay the train. In this case, the train will delay for all even possibilities between 0 and 10.
del_ = random.randint(0,10)del_f = del_%2if del_f == 0: del_t = random.randint(5,20) print('Train is delayed by',del_t,'minutes') sch_train = sch_train + del_t dep_train = sch_train + 10 print('Train will arrive after',sch_train,'minutes\n') else: print('No delay\n')
The variable del_ generates required cases and del_f is the remainder after those case values are divided by 2. To be an even number, the value of del_f must be zero. When it is equal to zero, the train is delayed by del_t minutes which is again a random amount of time between 5 and 20 minutes. Consequently, the value of arrival and departure time is increased. If the difference between the current time and delayed arrival time (new arrival time after the delay is announced) is less than 10, the platform ticket will not be generated (This will be coded in the next step).
num_pass = 0 for i in range(passenger): time = random.randint(5,60) #time after which passenger's train is scheduled if time<=dep_train: yield self.env.timeout(random.randint(1,3)) print('Platform ticket generated') num_pass +=1 else: print('Cannot generate platform ticket')print('\nPassengers on platorm:', num_pass) p = passenger - num_pass print('Passengers in waiting lounge:', p,'\n')
Initially, num_pass (number of passengers on the platform) is equal to 0. The variable time stores random values of time in minutes after which the train is scheduled. A conditional ‘if’ statement checks whether the passenger is eligible for a platform ticket or not. The time a worker takes to complete this process is between 1 and 3 minutes. Subsequently, the platform ticket is generated, num_pass is incremented by 1, and the value of num_pass is printed.The process of ticket generation is completed. Now we will code a function which schedules the arrival of passengers in the station.
def station_arrival(env, passenger, station): arrival_time = env.now with station.worker.request() as req: yield req yield env.process(station.ticket(passenger))
Note: This function calls out for another function in the main class. This gives a hint that it will be called again somewhere as a substitute to avoid calling too many functions at once.
The variable arrival_time stores the value of the current time of the environment generated by env.now command. The next line requests the main class (Station) to let the simulation use its resource (num_worker). The last line of this request yields triggers the function of ticket generation (env.process(station.ticket(passenger)) defined in the main class. The last thing we require is a function that calls all other functions in order and generates value for passenger variable in a ‘for’ loop as it is an attribute for both functions defined above.
def run_station(env, num_worker): station = Station(env, num_worker) a = 5 for passenger in range(20,40): env.process(station_arrival(env, passenger, station))while a > 0: yield env.timeout(0.7) passenger += 1 env.process(station_arrival(env, passenger, station))
The station_arrival function is called in a ‘for’ loop that asks the environment for a resource and then initiates the ticket generation process after the conditions are fulfilled. Finally, a ‘while’ loop executes the whole process and increments the passenger in every step. In order to run the simulation, we just need to call the run_station function.
With this, the simulation structure is ready to be executed in the main function that will assign the env variable as a SimPy environment and defines the simulation time (env.run(until=200)).
def main(): random.seed(30) n = input('Enter no. of workers: ') num_worker = int(n) env = simpy.Environment() env.process(run_station(env, num_worker)) env.run(until=200)if __name__ == "__main__": main()
The effectiveness of the simulation depends on how well the program is structured and how accurate are the probability determining factors. It requires a lot of brainstorming. In this case, all the numbers generated using randint give a rough estimate. We can structure them accurately based on studies/surveys conducted on the same topic an then determine the correct probability of an event. This field has great potential to become a research topic.
For more assistance, download the source code from GitHub.
This is a self-made scenario of maintaining social distancing on platforms. The solution provided to the issue might not be the best but the main motive of framing this situation was to describe basic functions of SimPy library, need for simulations, and demonstrate the coding procedure behind the simple simulation cases.
With the help of the SimPy framework, we can understand a lot about structuring programs and processes. We can now simulate various systems and their subprocesses by defining and scheduling various functions in an environment. This helps us understand the randomness in daily life processes. Now we have a clear understanding of the system and how basic probabilities govern the complexity and accuracy of a simulation.
These simulations can help individuals in making various decisions by calculating costs and other factors. Simulations are an effective way of generating useful and accurate data if they are structured correctly. Moreover, they can also be used in data prediction with the help of data analytics.
|
[
{
"code": null,
"e": 486,
"s": 171,
"text": "Python is famous for its simple syntax and numerous libraries which make this language capable of doing almost anything. Python’s range of operations varies from moderately easy tasks like developing web and desktop applications to complex tasks like building machine learning and artificial intelligence projects."
},
{
"code": null,
"e": 1051,
"s": 486,
"text": "We see systems everywhere, from an embedded system in a digital alarm clock to big systems like airports and railway stations. To run these systems efficiently and optimally, we need simulations as they provide us with readings to rely on. Engagement with surroundings and randomness are two crucial factors of systems and simulations. This article will focus on such functions of python libraries so that we can simulate a scenario as per our requirements. To achieve this goal and create the algorithm, we will use the following two built-in libraries of Python:"
},
{
"code": null,
"e": 1057,
"s": 1051,
"text": "SimPy"
},
{
"code": null,
"e": 1064,
"s": 1057,
"text": "Random"
},
{
"code": null,
"e": 1344,
"s": 1064,
"text": "Scenario: To follow social distancing, as a station master you have to design a plan to minimize the number of people on the platform and keep the maximum people out in their vehicles or waiting rooms (Let’s assume that the rooms have proper measures to keep the travelers safe)."
},
{
"code": null,
"e": 1522,
"s": 1344,
"text": "Plan: We will start by assigning arrival and departure times to the trains. A booth should be made to distribute platform tickets to passengers boarding the next arriving train."
},
{
"code": null,
"e": 1688,
"s": 1522,
"text": "I am assuming that you already have Python installed and have a basic knowledge. If you haven’t worked with Python before, you might want to check out this tutorial."
},
{
"code": null,
"e": 1869,
"s": 1688,
"text": "I prefer running the program in the shell. You can use Jupyter Notebooks as well. The first step is to install and import the required libraries. Open the Command Prompt and write:"
},
{
"code": null,
"e": 1905,
"s": 1869,
"text": "pip install SimPypip install random"
},
{
"code": null,
"e": 1984,
"s": 1905,
"text": "After successful installation, import the libraries using the import function:"
},
{
"code": null,
"e": 2010,
"s": 1984,
"text": "import SimPyimport random"
},
{
"code": null,
"e": 2615,
"s": 2010,
"text": "Before you start coding the main algorithm, it is necessary to make a clear image of how should your simulation look like. This step is most important for making a good simulation model. One should spend maximum time brainstorming, structuring, and collecting data for this step. Collecting statistical data from a trustworthy source for every uncertain moment in simulation is important. If this is compromised, the frequency of occurrence of one or more events can increase or decrease. This can result in generating false values. According to our plan, the simulation must run in the following manner:"
},
{
"code": null,
"e": 2817,
"s": 2615,
"text": "Passenger arrives at the Railway Station and heads to the platform ticket counter. — If he is boarding the next arriving train, he gets a platform ticket. — Else, he is requested to wait in the lounge."
},
{
"code": null,
"e": 3019,
"s": 2817,
"text": "Passenger arrives at the Railway Station and heads to the platform ticket counter. — If he is boarding the next arriving train, he gets a platform ticket. — Else, he is requested to wait in the lounge."
},
{
"code": null,
"e": 3188,
"s": 3019,
"text": "2. The train arrives at the platform, passengers board the train and it departs after 10 minutes. There is also a probability that the train will delay by some minutes."
},
{
"code": null,
"e": 3415,
"s": 3188,
"text": "3. Passengers waiting in the lounge head to the ticket counter and the eligible ones head to the platform. Meanwhile, more passengers arrive at the station.In this way, we can minimize the number of passengers on the platform."
},
{
"code": null,
"e": 3672,
"s": 3415,
"text": "We will start by defining the main class which will contain a blueprint of simulation and the procedures carried out at the railway station. This class will contain some functions that will generate the required environment. This class is named as Station."
},
{
"code": null,
"e": 3810,
"s": 3672,
"text": "class Station(object): def __init__(self, env, num_worker): self.env = env self.worker = simpy.Resource(env, num_worker)"
},
{
"code": null,
"e": 4388,
"s": 3810,
"text": "In this code, __init__() is a reserved method in python classes. It is called when an object is created from the class. This method allows us to define the attributes of a class. We proceed by creating some SimPy resources essential for our simulation. The variable ‘env’ is predefined and helps us to generate a virtual environment for simulation. Now think it this way, there are some resources that are provided by the station to the passengers. In this situation, it’s the workers present in the ticket counter. The number of workers will be denoted by num_worker variable."
},
{
"code": null,
"e": 4500,
"s": 4388,
"text": "Before proceeding, we need to learn about some more functions of SimPy and Random library. The first one being:"
},
{
"code": null,
"e": 4520,
"s": 4500,
"text": "random.randint(a,b)"
},
{
"code": null,
"e": 4765,
"s": 4520,
"text": "This function helps us generate a random integer between two integers a and b (both included). This will aid us in simulating random events in our process. You can use it with conditional statements by specifying a trigger condition for events."
},
{
"code": null,
"e": 4852,
"s": 4765,
"text": "p = random.randint(1,8)if p == 3 : print('Event Triggered') #Probability = 0.125"
},
{
"code": null,
"e": 4876,
"s": 4852,
"text": "The second function is:"
},
{
"code": null,
"e": 4902,
"s": 4876,
"text": "yield self.env.timeout(a)"
},
{
"code": null,
"e": 5110,
"s": 4902,
"text": "This is used to run a process (env in this case) for a duration of a minute(s). We can further use this with the randint function to run the environment for any random integral value of time between a and b."
},
{
"code": null,
"e": 5154,
"s": 5110,
"text": "yield self.env.timeout(random.randint(a,b))"
},
{
"code": null,
"e": 5582,
"s": 5154,
"text": "Now you are ready to code the function that will classify the passengers and sell platform tickets accordingly. It will also generate the schedule of trains, delay them (if needed), and print the number of passengers on the platform and in the lounge. The task will be accomplished by using the above functions with conditional statements and loops as per requirement. SimPy will help in generating and running the environment."
},
{
"code": null,
"e": 5786,
"s": 5582,
"text": "The first step is to define the function and its arguments. After that, all the necessary variables that govern the arrival, departure (after 10 minutes of arrival), and delay of trains will be declared."
},
{
"code": null,
"e": 5941,
"s": 5786,
"text": "def ticket(self, passenger): sch_train = random.randint(0,45) dep_train = sch_train + 10 print('Next train arriving after',sch_train,'minutes')"
},
{
"code": null,
"e": 6086,
"s": 5941,
"text": "Note: The function ticket takes self and passenger as its attributes. The passenger attribute will be defined later in the run_station function."
},
{
"code": null,
"e": 6222,
"s": 6086,
"text": "The next task is to set a condition to delay the train. In this case, the train will delay for all even possibilities between 0 and 10."
},
{
"code": null,
"e": 6563,
"s": 6222,
"text": "del_ = random.randint(0,10)del_f = del_%2if del_f == 0: del_t = random.randint(5,20) print('Train is delayed by',del_t,'minutes') sch_train = sch_train + del_t dep_train = sch_train + 10 print('Train will arrive after',sch_train,'minutes\\n') else: print('No delay\\n')"
},
{
"code": null,
"e": 7141,
"s": 6563,
"text": "The variable del_ generates required cases and del_f is the remainder after those case values are divided by 2. To be an even number, the value of del_f must be zero. When it is equal to zero, the train is delayed by del_t minutes which is again a random amount of time between 5 and 20 minutes. Consequently, the value of arrival and departure time is increased. If the difference between the current time and delayed arrival time (new arrival time after the delay is announced) is less than 10, the platform ticket will not be generated (This will be coded in the next step)."
},
{
"code": null,
"e": 7650,
"s": 7141,
"text": "num_pass = 0 for i in range(passenger): time = random.randint(5,60) #time after which passenger's train is scheduled if time<=dep_train: yield self.env.timeout(random.randint(1,3)) print('Platform ticket generated') num_pass +=1 else: print('Cannot generate platform ticket')print('\\nPassengers on platorm:', num_pass) p = passenger - num_pass print('Passengers in waiting lounge:', p,'\\n')"
},
{
"code": null,
"e": 8243,
"s": 7650,
"text": "Initially, num_pass (number of passengers on the platform) is equal to 0. The variable time stores random values of time in minutes after which the train is scheduled. A conditional ‘if’ statement checks whether the passenger is eligible for a platform ticket or not. The time a worker takes to complete this process is between 1 and 3 minutes. Subsequently, the platform ticket is generated, num_pass is incremented by 1, and the value of num_pass is printed.The process of ticket generation is completed. Now we will code a function which schedules the arrival of passengers in the station."
},
{
"code": null,
"e": 8425,
"s": 8243,
"text": "def station_arrival(env, passenger, station): arrival_time = env.now with station.worker.request() as req: yield req yield env.process(station.ticket(passenger))"
},
{
"code": null,
"e": 8613,
"s": 8425,
"text": "Note: This function calls out for another function in the main class. This gives a hint that it will be called again somewhere as a substitute to avoid calling too many functions at once."
},
{
"code": null,
"e": 9168,
"s": 8613,
"text": "The variable arrival_time stores the value of the current time of the environment generated by env.now command. The next line requests the main class (Station) to let the simulation use its resource (num_worker). The last line of this request yields triggers the function of ticket generation (env.process(station.ticket(passenger)) defined in the main class. The last thing we require is a function that calls all other functions in order and generates value for passenger variable in a ‘for’ loop as it is an attribute for both functions defined above."
},
{
"code": null,
"e": 9469,
"s": 9168,
"text": "def run_station(env, num_worker): station = Station(env, num_worker) a = 5 for passenger in range(20,40): env.process(station_arrival(env, passenger, station))while a > 0: yield env.timeout(0.7) passenger += 1 env.process(station_arrival(env, passenger, station))"
},
{
"code": null,
"e": 9824,
"s": 9469,
"text": "The station_arrival function is called in a ‘for’ loop that asks the environment for a resource and then initiates the ticket generation process after the conditions are fulfilled. Finally, a ‘while’ loop executes the whole process and increments the passenger in every step. In order to run the simulation, we just need to call the run_station function."
},
{
"code": null,
"e": 10016,
"s": 9824,
"text": "With this, the simulation structure is ready to be executed in the main function that will assign the env variable as a SimPy environment and defines the simulation time (env.run(until=200))."
},
{
"code": null,
"e": 10241,
"s": 10016,
"text": "def main(): random.seed(30) n = input('Enter no. of workers: ') num_worker = int(n) env = simpy.Environment() env.process(run_station(env, num_worker)) env.run(until=200)if __name__ == \"__main__\": main()"
},
{
"code": null,
"e": 10694,
"s": 10241,
"text": "The effectiveness of the simulation depends on how well the program is structured and how accurate are the probability determining factors. It requires a lot of brainstorming. In this case, all the numbers generated using randint give a rough estimate. We can structure them accurately based on studies/surveys conducted on the same topic an then determine the correct probability of an event. This field has great potential to become a research topic."
},
{
"code": null,
"e": 10753,
"s": 10694,
"text": "For more assistance, download the source code from GitHub."
},
{
"code": null,
"e": 11077,
"s": 10753,
"text": "This is a self-made scenario of maintaining social distancing on platforms. The solution provided to the issue might not be the best but the main motive of framing this situation was to describe basic functions of SimPy library, need for simulations, and demonstrate the coding procedure behind the simple simulation cases."
},
{
"code": null,
"e": 11497,
"s": 11077,
"text": "With the help of the SimPy framework, we can understand a lot about structuring programs and processes. We can now simulate various systems and their subprocesses by defining and scheduling various functions in an environment. This helps us understand the randomness in daily life processes. Now we have a clear understanding of the system and how basic probabilities govern the complexity and accuracy of a simulation."
}
] |
Java Program to Insert Details in a Table using JDBC - GeeksforGeeks
|
13 Jul, 2021
Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgress, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data).
Algorithm: Search/ Insert/ Delete/ Update in JDBC
In order to deal with JDBC standard 7 steps are supposed to be followed:
Import the database
Load and register drivers
Create a connection
Create a statement
Execute the query
Process the results
Close the connection
Import the database
Load and register drivers
Create a connection
Create a statement
Execute the query
Process the results
Close the connection
Procedure:
Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named “hotelman” and table names are “cuslogin” & “adminlogin”.
Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating a class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.
Inserting details in a table using JDBC in the input sample image with parameters as follows
“cuslogin” table has columns namely –
name
password
email
address
phone
id
Need is to insert new details inside the “cuslogin” table.
Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named “hotelman” and table names are “cuslogin” & “adminlogin”.
Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating a class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.
Inserting details in a table using JDBC in the input sample image with parameters as follows
“cuslogin” table has columns namely –
name
password
email
address
phone
id
Need is to insert new details inside the “cuslogin” table.
“cuslogin” table has columns namely –
name
password
email
address
phone
id
name
password
email
address
phone
id
Need is to insert new details inside the “cuslogin” table.
Input sample Image:
3.1: Initialize a string with the SQL query as follows
String sql=”insert into cuslogin values(‘geeksforgeeks’,’gfg’,’[email protected]’,’flat 1′,’1239087474′,10)”;
3.2: Initialize the below objects of Connection class, PreparedStatement class(needed for JDBC ) and connect with the database as follows
Connection con=null;
PreparedStatement p=null;
con=connection.connectDB();
3.3: Now, add the SQL query of step 3.1 inside PrepareStatement and execute it as follows
p =con.prepareStatement(sql);
p.execute();
3.4: Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for inserting the details of the customer in table “cuslogin”.
Note: Both the file’s viz result.java and connection.java should be inside the same package, else the program won’t give the desired output.
Implementation :
Example 1 is Connection class of JDBC
Example 2 is App(Main) class where connection class is used as calling object of Connection class in main class.
Example 1: Connection class
Java
// Java Program to Insert Details in a Table using JDBC
// Connections class
// Importing all SQL classes
import java.sql.*;
public class connection {
// object of Connection class
// initially assigned NULL
Connection con = null;
public static Connection connectDB()
{
try {
// Step 2 is involved among 7 in Connection
// class i.e Load and register drivers
// 2(a) Loading drivers using forName() method
// name of database here is mysql
Class.forName("com.mysql.jdbc.Driver");
// 2(b) Registering drivers using DriverManager
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hotelman",
"root", "1234");
// For DB here (custom sets)
// root is the username, and
// 1234 is the password
// returning the object of Connection class
// to be used in main class (Example2)
return con;
}
// Catch block to handle the exceptions
catch (SQLException | ClassNotFoundException e) {
// Print the exceptions
System.out.println(e);
return null;
}
}
}
Example 2: App/Main Class where the program is compiled and run calling the above connection class object
Java
// Java Program to Insert Details in a Table using JDBC
// Main class
// Step 1: Importing DB classes
// DB is SQL here
import java.sql.*;
// Main/App class of above Connection class
public class GFG {
// MAin driver method
public static void main(String[] args)
{
// Step 2: Showing above Connection class i.e
// loading and registering drivers
// Initially assigning NULL parameters
// to object of Connection class
Connection con = null;
PreparedStatement ps = null;
// Step 3: Establish the connection
con = connection.connectDB();
// Try block to check if exception/s occurs
try {
// Step 4: Create a statement
String sql = "insert into cuslogin values('geeksforgeeks','gfg','[email protected]','flat 1','1239087474',10)";
// Step 5: Execute the query
ps = con.prepareStatement(sql);
// Step 6: Process the results
ps.execute();
}
// Optional but recommended
// Step 7: Close the connection
// Catch block to handle the exception/s
catch (Exception e) {
// Print the exception
System.out.println(e);
}
}
}
Output:
Details added here: “geeksforgeeks” named customer details have been added.
simmytarika5
gabaa406
simranarora5sos
JDBC
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
ArrayList in Java
Convert a String to Character array in Java
Java Programming Examples
Initializing a List in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 24429,
"s": 24398,
"text": " \n13 Jul, 2021\n"
},
{
"code": null,
"e": 24702,
"s": 24429,
"text": "Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgress, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data)."
},
{
"code": null,
"e": 24752,
"s": 24702,
"text": "Algorithm: Search/ Insert/ Delete/ Update in JDBC"
},
{
"code": null,
"e": 24825,
"s": 24752,
"text": "In order to deal with JDBC standard 7 steps are supposed to be followed:"
},
{
"code": null,
"e": 24971,
"s": 24825,
"text": "\nImport the database\nLoad and register drivers\nCreate a connection\nCreate a statement\nExecute the query\nProcess the results\nClose the connection\n"
},
{
"code": null,
"e": 24991,
"s": 24971,
"text": "Import the database"
},
{
"code": null,
"e": 25017,
"s": 24991,
"text": "Load and register drivers"
},
{
"code": null,
"e": 25037,
"s": 25017,
"text": "Create a connection"
},
{
"code": null,
"e": 25056,
"s": 25037,
"text": "Create a statement"
},
{
"code": null,
"e": 25074,
"s": 25056,
"text": "Execute the query"
},
{
"code": null,
"e": 25094,
"s": 25074,
"text": "Process the results"
},
{
"code": null,
"e": 25115,
"s": 25094,
"text": "Close the connection"
},
{
"code": null,
"e": 25126,
"s": 25115,
"text": "Procedure:"
},
{
"code": null,
"e": 25930,
"s": 25126,
"text": "\nCreating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named “hotelman” and table names are “cuslogin” & “adminlogin”.\nCreate a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating a class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.\nInserting details in a table using JDBC in the input sample image with parameters as follows\n\n“cuslogin” table has columns namely –\n\nname\npassword\nemail\naddress\nphone\nid\n\n\nNeed is to insert new details inside the “cuslogin” table.\n\n\n"
},
{
"code": null,
"e": 26209,
"s": 25930,
"text": "Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named “hotelman” and table names are “cuslogin” & “adminlogin”."
},
{
"code": null,
"e": 26499,
"s": 26209,
"text": "Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating a class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java."
},
{
"code": null,
"e": 26732,
"s": 26499,
"text": "Inserting details in a table using JDBC in the input sample image with parameters as follows\n\n“cuslogin” table has columns namely –\n\nname\npassword\nemail\naddress\nphone\nid\n\n\nNeed is to insert new details inside the “cuslogin” table.\n\n"
},
{
"code": null,
"e": 26810,
"s": 26732,
"text": "“cuslogin” table has columns namely –\n\nname\npassword\nemail\naddress\nphone\nid\n\n"
},
{
"code": null,
"e": 26815,
"s": 26810,
"text": "name"
},
{
"code": null,
"e": 26824,
"s": 26815,
"text": "password"
},
{
"code": null,
"e": 26830,
"s": 26824,
"text": "email"
},
{
"code": null,
"e": 26838,
"s": 26830,
"text": "address"
},
{
"code": null,
"e": 26844,
"s": 26838,
"text": "phone"
},
{
"code": null,
"e": 26847,
"s": 26844,
"text": "id"
},
{
"code": null,
"e": 26906,
"s": 26847,
"text": "Need is to insert new details inside the “cuslogin” table."
},
{
"code": null,
"e": 26927,
"s": 26906,
"text": "Input sample Image: "
},
{
"code": null,
"e": 26982,
"s": 26927,
"text": "3.1: Initialize a string with the SQL query as follows"
},
{
"code": null,
"e": 27091,
"s": 26982,
"text": "String sql=”insert into cuslogin values(‘geeksforgeeks’,’gfg’,’[email protected]’,’flat 1′,’1239087474′,10)”;"
},
{
"code": null,
"e": 27229,
"s": 27091,
"text": "3.2: Initialize the below objects of Connection class, PreparedStatement class(needed for JDBC ) and connect with the database as follows"
},
{
"code": null,
"e": 27304,
"s": 27229,
"text": "Connection con=null;\nPreparedStatement p=null;\ncon=connection.connectDB();"
},
{
"code": null,
"e": 27394,
"s": 27304,
"text": "3.3: Now, add the SQL query of step 3.1 inside PrepareStatement and execute it as follows"
},
{
"code": null,
"e": 27437,
"s": 27394,
"text": "p =con.prepareStatement(sql);\np.execute();"
},
{
"code": null,
"e": 27611,
"s": 27437,
"text": "3.4: Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for inserting the details of the customer in table “cuslogin”."
},
{
"code": null,
"e": 27752,
"s": 27611,
"text": "Note: Both the file’s viz result.java and connection.java should be inside the same package, else the program won’t give the desired output."
},
{
"code": null,
"e": 27770,
"s": 27752,
"text": "Implementation : "
},
{
"code": null,
"e": 27808,
"s": 27770,
"text": "Example 1 is Connection class of JDBC"
},
{
"code": null,
"e": 27921,
"s": 27808,
"text": "Example 2 is App(Main) class where connection class is used as calling object of Connection class in main class."
},
{
"code": null,
"e": 27949,
"s": 27921,
"text": "Example 1: Connection class"
},
{
"code": null,
"e": 27954,
"s": 27949,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to Insert Details in a Table using JDBC\n// Connections class\n \n// Importing all SQL classes\nimport java.sql.*;\n \npublic class connection {\n \n // object of Connection class\n // initially assigned NULL\n Connection con = null;\n \n public static Connection connectDB()\n \n {\n \n try {\n \n // Step 2 is involved among 7 in Connection\n // class i.e Load and register drivers\n \n // 2(a) Loading drivers using forName() method\n // name of database here is mysql\n Class.forName(\"com.mysql.jdbc.Driver\");\n \n // 2(b) Registering drivers using DriverManager\n Connection con = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/hotelman\",\n \"root\", \"1234\");\n // For DB here (custom sets)\n // root is the username, and\n // 1234 is the password\n \n // returning the object of Connection class\n // to be used in main class (Example2)\n return con;\n }\n \n // Catch block to handle the exceptions\n catch (SQLException | ClassNotFoundException e) {\n \n // Print the exceptions\n System.out.println(e);\n \n return null;\n }\n }\n}\n\n\n\n\n\n",
"e": 29257,
"s": 27964,
"text": null
},
{
"code": null,
"e": 29366,
"s": 29260,
"text": "Example 2: App/Main Class where the program is compiled and run calling the above connection class object"
},
{
"code": null,
"e": 29373,
"s": 29368,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to Insert Details in a Table using JDBC\n// Main class\n \n// Step 1: Importing DB classes\n// DB is SQL here\nimport java.sql.*;\n \n// Main/App class of above Connection class\npublic class GFG {\n \n // MAin driver method\n public static void main(String[] args)\n {\n // Step 2: Showing above Connection class i.e\n // loading and registering drivers\n \n // Initially assigning NULL parameters\n // to object of Connection class\n Connection con = null;\n PreparedStatement ps = null;\n \n // Step 3: Establish the connection\n con = connection.connectDB();\n \n // Try block to check if exception/s occurs\n try {\n \n // Step 4: Create a statement\n String sql = \"insert into cuslogin values('geeksforgeeks','gfg','[email protected]','flat 1','1239087474',10)\";\n \n // Step 5: Execute the query\n ps = con.prepareStatement(sql);\n \n // Step 6: Process the results\n ps.execute();\n }\n \n // Optional but recommended\n // Step 7: Close the connection\n \n // Catch block to handle the exception/s\n catch (Exception e) {\n \n // Print the exception\n System.out.println(e);\n }\n }\n}\n\n\n\n\n\n",
"e": 30670,
"s": 29383,
"text": null
},
{
"code": null,
"e": 30681,
"s": 30673,
"text": "Output:"
},
{
"code": null,
"e": 30759,
"s": 30683,
"text": "Details added here: “geeksforgeeks” named customer details have been added."
},
{
"code": null,
"e": 30774,
"s": 30761,
"text": "simmytarika5"
},
{
"code": null,
"e": 30783,
"s": 30774,
"text": "gabaa406"
},
{
"code": null,
"e": 30799,
"s": 30783,
"text": "simranarora5sos"
},
{
"code": null,
"e": 30806,
"s": 30799,
"text": "\nJDBC\n"
},
{
"code": null,
"e": 30832,
"s": 30806,
"text": "\nTechnical Scripter 2020\n"
},
{
"code": null,
"e": 30839,
"s": 30832,
"text": "\nJava\n"
},
{
"code": null,
"e": 30855,
"s": 30839,
"text": "\nJava Programs\n"
},
{
"code": null,
"e": 30876,
"s": 30855,
"text": "\nTechnical Scripter\n"
},
{
"code": null,
"e": 31081,
"s": 30876,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 31113,
"s": 31081,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31132,
"s": 31113,
"text": "Overriding in Java"
},
{
"code": null,
"e": 31164,
"s": 31132,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31183,
"s": 31164,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 31201,
"s": 31183,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31245,
"s": 31201,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 31271,
"s": 31245,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31299,
"s": 31271,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 31346,
"s": 31299,
"text": "Implementing a Linked List in Java using Class"
}
] |
Java AWS - How to read messages from SQS - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see how to read messages from AWS SQS using Java SDK.
You may be wonder that what is the use of this article while we have a provision to add subscriptions or triggers to the SQS directly that can automatically trigger SNS or lambda accordingly whenever a message sent to the SQS. Generally, we call this kind of design a push service.
The intention of this approach is for pulling the messages from the SQS whenever we need them, which we call on-demand pulling.
Make sure you have an AWS account and valid credentials to access the resources.
Better you install the AWS CLI on your machine for troubleshooting.
Configure AWS credentials on your local machine.
Java 14
AWS SDK 2.16.29
As part of this example, we are going to send messages to the SQS queue, messages can be sent to the SQS queue in two ways; single message and sending a bulk of messages at a time.
Add software.amazon.awssdk dependency into your pom.xml.
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sqs</artifactId>
</dependency>
The Amazon AWS SDK for Java is used to interact with AWS resources from a Java application.
Run the maven clean install command to download the dependencies.
% mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------< AWS_EXample:java-aws-examples >--------------------
[INFO] Building java-aws-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
...
..
I am suspecting you have already messages in the SQS because it doesn’t make any sense to read the messages without having them. If you are interested in sending messages to SQS, I have written an article on it please go through it.
I have a FIFO queue and 2 messages in it. let’s try to read them.
package com.otp;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;
import java.util.List;
public class SQS_Example {
public static void main(String[] args) {
SqsClient sqsClient = SqsClient.builder()
.region(Region.US_WEST_2)
.build();
String queue = "https://sqs.us-west-2.amazonaws.com/12345/My-FIFO-Queue.fifo";
readMessages(sqsClient, queue);
sqsClient.close();
}
public static void readMessages(SqsClient sqsClient, String queueUrl) {
try {
ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
.queueUrl(queueUrl)
.maxNumberOfMessages(5)
.build();
List<Message> messages = sqsClient.receiveMessage(receiveMessageRequest).messages();
messages.forEach(message -> System.out.println(message.body()));
} catch (SqsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
Output:
Hello world from Java!
Hello 1
AWS SQS developer guide
Send messages to SQS
Happy Learning 🙂
Java AWS – How to Send Messages to SQS Queues
Java AWS – How to Create SQS Standard and FIFO Queues
How to install AWS CLI on Windows 10
Python – AWS SAM Lambda Example
Javascript – How to listObjects from AWS S3
How to Copy Local Files to AWS EC2 instance Manually ?
How set AWS Access Keys in Windows or Mac Environment
How to connect AWS EC2 Instance using PuTTY
[Fixed] – Malformed Lambda proxy response – status 502
Python – How to read environment variables ?
Spring Boot RabbitMQ Consumer Messages Example
How add files to S3 Bucket using Shell Script
Python raw_input read input from keyboard
Python How to read input from keyboard
Spring Boot Kafka Consume JSON Messages Example
Java AWS – How to Send Messages to SQS Queues
Java AWS – How to Create SQS Standard and FIFO Queues
How to install AWS CLI on Windows 10
Python – AWS SAM Lambda Example
Javascript – How to listObjects from AWS S3
How to Copy Local Files to AWS EC2 instance Manually ?
How set AWS Access Keys in Windows or Mac Environment
How to connect AWS EC2 Instance using PuTTY
[Fixed] – Malformed Lambda proxy response – status 502
Python – How to read environment variables ?
Spring Boot RabbitMQ Consumer Messages Example
How add files to S3 Bucket using Shell Script
Python raw_input read input from keyboard
Python How to read input from keyboard
Spring Boot Kafka Consume JSON Messages Example
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 486,
"s": 398,
"text": "In this tutorial, we are going to see how to read messages from AWS SQS using Java SDK."
},
{
"code": null,
"e": 769,
"s": 486,
"text": "You may be wonder that what is the use of this article while we have a provision to add subscriptions or triggers to the SQS directly that can automatically trigger SNS or lambda accordingly whenever a message sent to the SQS. Generally, we call this kind of design a push service."
},
{
"code": null,
"e": 897,
"s": 769,
"text": "The intention of this approach is for pulling the messages from the SQS whenever we need them, which we call on-demand pulling."
},
{
"code": null,
"e": 978,
"s": 897,
"text": "Make sure you have an AWS account and valid credentials to access the resources."
},
{
"code": null,
"e": 1046,
"s": 978,
"text": "Better you install the AWS CLI on your machine for troubleshooting."
},
{
"code": null,
"e": 1095,
"s": 1046,
"text": "Configure AWS credentials on your local machine."
},
{
"code": null,
"e": 1103,
"s": 1095,
"text": "Java 14"
},
{
"code": null,
"e": 1119,
"s": 1103,
"text": "AWS SDK 2.16.29"
},
{
"code": null,
"e": 1300,
"s": 1119,
"text": "As part of this example, we are going to send messages to the SQS queue, messages can be sent to the SQS queue in two ways; single message and sending a bulk of messages at a time."
},
{
"code": null,
"e": 1357,
"s": 1300,
"text": "Add software.amazon.awssdk dependency into your pom.xml."
},
{
"code": null,
"e": 1463,
"s": 1357,
"text": "<dependency>\n <groupId>software.amazon.awssdk</groupId>\n <artifactId>sqs</artifactId>\n</dependency>"
},
{
"code": null,
"e": 1555,
"s": 1463,
"text": "The Amazon AWS SDK for Java is used to interact with AWS resources from a Java application."
},
{
"code": null,
"e": 1621,
"s": 1555,
"text": "Run the maven clean install command to download the dependencies."
},
{
"code": null,
"e": 1904,
"s": 1621,
"text": " % mvn clean install\n[INFO] Scanning for projects...\n[INFO] \n[INFO] -------------------< AWS_EXample:java-aws-examples >--------------------\n[INFO] Building java-aws-examples 1.0-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO] \n...\n.."
},
{
"code": null,
"e": 2137,
"s": 1904,
"text": "I am suspecting you have already messages in the SQS because it doesn’t make any sense to read the messages without having them. If you are interested in sending messages to SQS, I have written an article on it please go through it."
},
{
"code": null,
"e": 2203,
"s": 2137,
"text": "I have a FIFO queue and 2 messages in it. let’s try to read them."
},
{
"code": null,
"e": 3367,
"s": 2203,
"text": "package com.otp;\n\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\nimport java.util.List;\n\npublic class SQS_Example {\n\n public static void main(String[] args) {\n SqsClient sqsClient = SqsClient.builder()\n .region(Region.US_WEST_2)\n .build();\n String queue = \"https://sqs.us-west-2.amazonaws.com/12345/My-FIFO-Queue.fifo\";\n readMessages(sqsClient, queue);\n sqsClient.close();\n }\n\n public static void readMessages(SqsClient sqsClient, String queueUrl) {\n try {\n ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()\n .queueUrl(queueUrl)\n .maxNumberOfMessages(5)\n .build();\n List<Message> messages = sqsClient.receiveMessage(receiveMessageRequest).messages();\n messages.forEach(message -> System.out.println(message.body()));\n } catch (SqsException e) {\n System.err.println(e.awsErrorDetails().errorMessage());\n System.exit(1);\n }\n }\n}\n"
},
{
"code": null,
"e": 3375,
"s": 3367,
"text": "Output:"
},
{
"code": null,
"e": 3406,
"s": 3375,
"text": "Hello world from Java!\nHello 1"
},
{
"code": null,
"e": 3430,
"s": 3406,
"text": "AWS SQS developer guide"
},
{
"code": null,
"e": 3451,
"s": 3430,
"text": "Send messages to SQS"
},
{
"code": null,
"e": 3468,
"s": 3451,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4159,
"s": 3468,
"text": "\nJava AWS – How to Send Messages to SQS Queues\nJava AWS – How to Create SQS Standard and FIFO Queues\nHow to install AWS CLI on Windows 10\nPython – AWS SAM Lambda Example\nJavascript – How to listObjects from AWS S3\nHow to Copy Local Files to AWS EC2 instance Manually ?\nHow set AWS Access Keys in Windows or Mac Environment\nHow to connect AWS EC2 Instance using PuTTY\n[Fixed] – Malformed Lambda proxy response – status 502\nPython – How to read environment variables ?\nSpring Boot RabbitMQ Consumer Messages Example\nHow add files to S3 Bucket using Shell Script\nPython raw_input read input from keyboard\nPython How to read input from keyboard\nSpring Boot Kafka Consume JSON Messages Example\n"
},
{
"code": null,
"e": 4205,
"s": 4159,
"text": "Java AWS – How to Send Messages to SQS Queues"
},
{
"code": null,
"e": 4259,
"s": 4205,
"text": "Java AWS – How to Create SQS Standard and FIFO Queues"
},
{
"code": null,
"e": 4296,
"s": 4259,
"text": "How to install AWS CLI on Windows 10"
},
{
"code": null,
"e": 4328,
"s": 4296,
"text": "Python – AWS SAM Lambda Example"
},
{
"code": null,
"e": 4372,
"s": 4328,
"text": "Javascript – How to listObjects from AWS S3"
},
{
"code": null,
"e": 4427,
"s": 4372,
"text": "How to Copy Local Files to AWS EC2 instance Manually ?"
},
{
"code": null,
"e": 4481,
"s": 4427,
"text": "How set AWS Access Keys in Windows or Mac Environment"
},
{
"code": null,
"e": 4525,
"s": 4481,
"text": "How to connect AWS EC2 Instance using PuTTY"
},
{
"code": null,
"e": 4581,
"s": 4525,
"text": "[Fixed] – Malformed Lambda proxy response – status 502"
},
{
"code": null,
"e": 4626,
"s": 4581,
"text": "Python – How to read environment variables ?"
},
{
"code": null,
"e": 4673,
"s": 4626,
"text": "Spring Boot RabbitMQ Consumer Messages Example"
},
{
"code": null,
"e": 4719,
"s": 4673,
"text": "How add files to S3 Bucket using Shell Script"
},
{
"code": null,
"e": 4761,
"s": 4719,
"text": "Python raw_input read input from keyboard"
},
{
"code": null,
"e": 4800,
"s": 4761,
"text": "Python How to read input from keyboard"
},
{
"code": null,
"e": 4848,
"s": 4800,
"text": "Spring Boot Kafka Consume JSON Messages Example"
},
{
"code": null,
"e": 4854,
"s": 4852,
"text": "Δ"
},
{
"code": null,
"e": 4878,
"s": 4854,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 4906,
"s": 4878,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 4935,
"s": 4906,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 4970,
"s": 4935,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 4997,
"s": 4970,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 5024,
"s": 4997,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 5053,
"s": 5024,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 5079,
"s": 5053,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 5105,
"s": 5079,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 5141,
"s": 5105,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 5175,
"s": 5141,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 5201,
"s": 5175,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 5226,
"s": 5201,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 5260,
"s": 5226,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 5295,
"s": 5260,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 5319,
"s": 5295,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 5348,
"s": 5319,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 5380,
"s": 5348,
"text": " Install Apache Kafka on Ubuntu"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.