title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
ARIMA vs. Prophet: Forecasting Air Passenger Numbers | by Michael Grogan | Towards Data Science
This is a follow-up to my prior article: Time Series Analysis with Prophet: Air Passenger Data In this example, an ARIMA (Autoregressive Integrated Moving Average) model is built using R to forecast air passenger numbers using the San Francisco International Airport Report on Monthly Passenger Traffic Statistics by Airline. Specifically, adjusted passenger numbers for the airline KLM (enplaned) are filtered as the time series for analysis from the period May 2005 to March 2016. The results will be compared to those obtained by Prophet to see how ARIMA performs relative to this model. The model is trained on 90% of the time series (training set), with the latter 10% of the series being used to compare to the predictions (test set). An ARIMA model consists of coordinates (p, d, q): p stands for the number of autoregressive terms, i.e. the number of observations from past time values used to forecast future values. e.g. if the value of p is 2, then this means that two previous time observations in the series are being used to forecast the future trend. d denotes the number of differences needed to make the time series stationary (i.e. one with a constant mean, variance, and autocorrelation). For instance, if d = 1, then it means that a first-difference of the series must be obtained to transform it into a stationary one. q represents the moving average of the previous forecast errors in our model, or the lagged values of the error term. As an example, if q has a value of 1, then this means that we have one lagged value of the error term in the model. When it comes to forecasting, a key assumption for time series data is that of stationarity. This is where the mean, variance, and autocorrelation of a series are constant. The reason for this assumption is that if the mean, variance and autocorrelation of a series are not constant over time — then it makes it a lot harder to use forecasting models to make predictions. However, as we have noted above, the d parameter in the ARIMA model denotes the number of differences needed to make the series stationary. When using the auto.arima feature in R, the p, d, and q values are selected automatically. Stationarity can usually be indicated visually through a visual inspection of the data. Let’s have a look at the time series again. We can see that — on the whole — the time series demonstrates a zig-zag pattern with little to no change in the overall trend over time. However, this can formally be tested for using the Dickey-Fuller test. The null hypothesis is that the series has a unit root present (non-stationarity), with the alternative hypothesis being stationarity or trend stationarity. The test for a unit root is as follows: When running the test on the series, a p-value of 0.01 is obtained, meaning that the null hypothesis is rejected at the 5% level of significance — indicating stationarity is present in the series. > adf.test(passengernumbers)Augmented Dickey-Fuller Testdata: passengernumbersDickey-Fuller = -8.061, Lag order = 4, p-value = 0.01alternative hypothesis: stationary The p parameter in ARIMA accounts for the number of autoregressive terms in the model — which allows the model to handle autocorrelation. Autocorrelation is a situation where correlation exists between the error terms across different observations in the time series, and this can also skew forecasts. Here is the ACF (autocorrelation function) plot for the time series (maximum lags of 20 are set): We see that autocorrelations persist for two months after lag 0, with positive and negative correlations persisting at the 6-month and 12-month period. In this instance, the lags are monthly — hence the 6-month period is indicated as 0.5, while the 12-month period is indicated as 1.0. The partial autocorrelation function seeks to remove indirect correlations that result from inherent linear functions that exist between each observation. Here is the partial autocorrelation plot for the series: We see that the partial autocorrelation function still shows correlations (albeit negative) persisting two months after lag 0. Therefore, the ARIMA model will need to be configured in such a way so as to account for the correct number of autoregressive terms. Here is a general overview of the components for the time series trend: > components <- decompose(passengernumbers)> components When looking at the series, significant seasonality patterns are observed roughly every six to eight months. With that in mind, the ARIMA model will need to account for such seasonality in its forecasts. Given the visual indication of autocorrelation as well as seasonality, auto.arima is used to automatically generate many ARIMA models with differing p, d, and q coordinates — the best model is then selected based on the one with the lowest BIC (Bayesian Information Criterion). > # ARIMA> fitpassengers<-auto.arima(passengernumbers, trace=TRUE, test="kpss", ic="bic")ARIMA(2,0,2)(1,1,1)[12] with drift : 1693.37 ARIMA(0,0,0)(0,1,0)[12] with drift : 1779.685 ARIMA(1,0,0)(1,1,0)[12] with drift : 1682.899 ARIMA(0,0,1)(0,1,1)[12] with drift : 1724.722 ARIMA(0,0,0)(0,1,0)[12] : 1775.932 ARIMA(1,0,0)(0,1,0)[12] with drift : 1702.397 ARIMA(1,0,0)(2,1,0)[12] with drift : 1685.158 ARIMA(1,0,0)(1,1,1)[12] with drift : 1684.594 ARIMA(1,0,0)(0,1,1)[12] with drift : 1680.905 ARIMA(1,0,0)(0,1,2)[12] with drift : 1684.211 ARIMA(1,0,0)(1,1,2)[12] with drift : Inf ARIMA(0,0,0)(0,1,1)[12] with drift : 1772.299 ARIMA(2,0,0)(0,1,1)[12] with drift : 1684.965 ARIMA(1,0,1)(0,1,1)[12] with drift : 1685.149 ARIMA(2,0,1)(0,1,1)[12] with drift : 1688.428 ARIMA(1,0,0)(0,1,1)[12] : 1676.443 ARIMA(1,0,0)(0,1,0)[12] : 1697.822 ARIMA(1,0,0)(1,1,1)[12] : 1680.163 ARIMA(1,0,0)(0,1,2)[12] : 1679.795 ARIMA(1,0,0)(1,1,0)[12] : 1678.467 ARIMA(1,0,0)(1,1,2)[12] : Inf ARIMA(0,0,0)(0,1,1)[12] : 1768.607 ARIMA(2,0,0)(0,1,1)[12] : 1680.489 ARIMA(1,0,1)(0,1,1)[12] : 1680.677 ARIMA(0,0,1)(0,1,1)[12] : 1720.732 ARIMA(2,0,1)(0,1,1)[12] : 1683.954Best model: ARIMA(1,0,0)(0,1,1)[12] The best model configuration is indicated as ARIMA(1,0,0)(0,1,1)[12]. The coefficients for this model are as follows: > fitpassengersSeries: passengernumbers ARIMA(1,0,0)(0,1,1)[12]Coefficients: ar1 sma1 0.7794 -0.5001s.e. 0.0609 0.0840sigma^2 estimated as 585834: log likelihood=-831.27AIC=1668.54 AICc=1668.78 BIC=1676.44 The ARIMA model generates the following forecasts: The RMSE (root mean squared error) and MFE (mean forecast error) are as follows: RMSE: 698 MFE: -115 > # Errors> library(Metrics)> rmse(df$`Actual Passenger Numbers`, df$`Forecasted Passenger Numbers`)[1] 698.6527> ## Forecast Error> forecast_error=(df$`Actual Passenger Numbers`-df$`Forecasted Passenger Numbers`)> forecast_error [1] -415.8149 -982.0972 -273.1147 -539.5008 -520.7138 -845.2062 -824.7485 [8] -212.4401 -454.4602 1387.1299 962.7507 153.2876 257.2238 687.3703> mean(forecast_error)[1] -115.7381 One key difference between ARIMA and Prophet is that the Prophet model accounts for “change points”, or specific shifts in trend in the time series. While it is technically possible to do this with ARIMA in R — it requires use of a separate package called AEDForecasting. Prophet works through use of an additive model whereby the non-linear trends in the series are fitted with the appropriate seasonality (whether daily, weekly, or yearly). In this particular dataset, a shift in trend came after 2009 — when we saw a reversal of growth in the overall trend for passenger demand: A standard Prophet model was fitted to the dataset, without any manual specifications for seasonality: prophet_basic = Prophet()prophet_basic.fit(train_dataset) Through trial and error, 4 change points were shown to minimise the RMSE and MFE and therefore were defined as the appropriate number of change points in the model: pro_change= Prophet(n_changepoints=4)forecast = pro_change.fit(train_dataset).predict(future)fig= pro_change.plot(forecast);a = add_changepoints_to_plot(fig.gca(), pro_change, forecast) The RMSE and MAE are calculated as follows: >>> from sklearn.metrics import mean_squared_error>>> from math import sqrt>>> mse = mean_squared_error(passenger_test, yhat14)>>> rmse = sqrt(mse)>>> print('RMSE: %f' % rmse)RMSE: 524.263928>>> forecast_error = (passenger_test-yhat14)>>> forecast_error>>> mean_forecast_error = np.mean(forecast_error)>>> mean_forecast_error71.58326743881493 With an RMSE and MFE of 524 and 71 obtained with Prophet respectively, the errors are significantly lower than the errors of 698 and -115 obtained with ARIMA. From this standpoint, while ARIMA has accounted for patterns such as seasonality and autocorrelation in the time series — Prophet has excelled at correctly identifying the relevant change point in the series — and this appears to have boosted the forecast accuracy for the model. It may be possible that ARIMA would excel when forecasting data with a more clearly defined trend or one that does not particularly exhibit seasonality — we saw very clear signs of this for the dataset in question. However, other cases where seasonality is not present may not be suitable for use with Prophet. In this example, we have seen: How to configure an ARIMA model The relevance of change points in a time series Comparison of ARIMA and Prophet in calculating forecast accuracy Many thanks for reading, and questions or feedback are always welcome. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. Analytics Vidhya: SARIMA — Forecasting Seasonal Data with Python and R CRAN — Package AEDForecasting data.world: Air Traffic Passenger Data (Original Source: San Francisco Open Data) GitHub: facebook/prophet Machine Learning Mastery: A Gentle Introduction to Autocorrelation and Partial Autocorrelation
[ { "code": null, "e": 266, "s": 171, "text": "This is a follow-up to my prior article: Time Series Analysis with Prophet: Air Passenger Data" }, { "code": null, "e": 497, "s": 266, "text": "In this example, an ARIMA (Autoregressive Integrated Moving Average) model is built using R to forecast air passenger numbers using the San Francisco International Airport Report on Monthly Passenger Traffic Statistics by Airline." }, { "code": null, "e": 654, "s": 497, "text": "Specifically, adjusted passenger numbers for the airline KLM (enplaned) are filtered as the time series for analysis from the period May 2005 to March 2016." }, { "code": null, "e": 762, "s": 654, "text": "The results will be compared to those obtained by Prophet to see how ARIMA performs relative to this model." }, { "code": null, "e": 912, "s": 762, "text": "The model is trained on 90% of the time series (training set), with the latter 10% of the series being used to compare to the predictions (test set)." }, { "code": null, "e": 962, "s": 912, "text": "An ARIMA model consists of coordinates (p, d, q):" }, { "code": null, "e": 1237, "s": 962, "text": "p stands for the number of autoregressive terms, i.e. the number of observations from past time values used to forecast future values. e.g. if the value of p is 2, then this means that two previous time observations in the series are being used to forecast the future trend." }, { "code": null, "e": 1511, "s": 1237, "text": "d denotes the number of differences needed to make the time series stationary (i.e. one with a constant mean, variance, and autocorrelation). For instance, if d = 1, then it means that a first-difference of the series must be obtained to transform it into a stationary one." }, { "code": null, "e": 1745, "s": 1511, "text": "q represents the moving average of the previous forecast errors in our model, or the lagged values of the error term. As an example, if q has a value of 1, then this means that we have one lagged value of the error term in the model." }, { "code": null, "e": 1918, "s": 1745, "text": "When it comes to forecasting, a key assumption for time series data is that of stationarity. This is where the mean, variance, and autocorrelation of a series are constant." }, { "code": null, "e": 2117, "s": 1918, "text": "The reason for this assumption is that if the mean, variance and autocorrelation of a series are not constant over time — then it makes it a lot harder to use forecasting models to make predictions." }, { "code": null, "e": 2348, "s": 2117, "text": "However, as we have noted above, the d parameter in the ARIMA model denotes the number of differences needed to make the series stationary. When using the auto.arima feature in R, the p, d, and q values are selected automatically." }, { "code": null, "e": 2436, "s": 2348, "text": "Stationarity can usually be indicated visually through a visual inspection of the data." }, { "code": null, "e": 2480, "s": 2436, "text": "Let’s have a look at the time series again." }, { "code": null, "e": 2617, "s": 2480, "text": "We can see that — on the whole — the time series demonstrates a zig-zag pattern with little to no change in the overall trend over time." }, { "code": null, "e": 2845, "s": 2617, "text": "However, this can formally be tested for using the Dickey-Fuller test. The null hypothesis is that the series has a unit root present (non-stationarity), with the alternative hypothesis being stationarity or trend stationarity." }, { "code": null, "e": 2885, "s": 2845, "text": "The test for a unit root is as follows:" }, { "code": null, "e": 3082, "s": 2885, "text": "When running the test on the series, a p-value of 0.01 is obtained, meaning that the null hypothesis is rejected at the 5% level of significance — indicating stationarity is present in the series." }, { "code": null, "e": 3249, "s": 3082, "text": "> adf.test(passengernumbers)Augmented Dickey-Fuller Testdata: passengernumbersDickey-Fuller = -8.061, Lag order = 4, p-value = 0.01alternative hypothesis: stationary" }, { "code": null, "e": 3551, "s": 3249, "text": "The p parameter in ARIMA accounts for the number of autoregressive terms in the model — which allows the model to handle autocorrelation. Autocorrelation is a situation where correlation exists between the error terms across different observations in the time series, and this can also skew forecasts." }, { "code": null, "e": 3649, "s": 3551, "text": "Here is the ACF (autocorrelation function) plot for the time series (maximum lags of 20 are set):" }, { "code": null, "e": 3935, "s": 3649, "text": "We see that autocorrelations persist for two months after lag 0, with positive and negative correlations persisting at the 6-month and 12-month period. In this instance, the lags are monthly — hence the 6-month period is indicated as 0.5, while the 12-month period is indicated as 1.0." }, { "code": null, "e": 4090, "s": 3935, "text": "The partial autocorrelation function seeks to remove indirect correlations that result from inherent linear functions that exist between each observation." }, { "code": null, "e": 4147, "s": 4090, "text": "Here is the partial autocorrelation plot for the series:" }, { "code": null, "e": 4407, "s": 4147, "text": "We see that the partial autocorrelation function still shows correlations (albeit negative) persisting two months after lag 0. Therefore, the ARIMA model will need to be configured in such a way so as to account for the correct number of autoregressive terms." }, { "code": null, "e": 4479, "s": 4407, "text": "Here is a general overview of the components for the time series trend:" }, { "code": null, "e": 4535, "s": 4479, "text": "> components <- decompose(passengernumbers)> components" }, { "code": null, "e": 4739, "s": 4535, "text": "When looking at the series, significant seasonality patterns are observed roughly every six to eight months. With that in mind, the ARIMA model will need to account for such seasonality in its forecasts." }, { "code": null, "e": 5017, "s": 4739, "text": "Given the visual indication of autocorrelation as well as seasonality, auto.arima is used to automatically generate many ARIMA models with differing p, d, and q coordinates — the best model is then selected based on the one with the lowest BIC (Bayesian Information Criterion)." }, { "code": null, "e": 6534, "s": 5017, "text": "> # ARIMA> fitpassengers<-auto.arima(passengernumbers, trace=TRUE, test=\"kpss\", ic=\"bic\")ARIMA(2,0,2)(1,1,1)[12] with drift : 1693.37 ARIMA(0,0,0)(0,1,0)[12] with drift : 1779.685 ARIMA(1,0,0)(1,1,0)[12] with drift : 1682.899 ARIMA(0,0,1)(0,1,1)[12] with drift : 1724.722 ARIMA(0,0,0)(0,1,0)[12] : 1775.932 ARIMA(1,0,0)(0,1,0)[12] with drift : 1702.397 ARIMA(1,0,0)(2,1,0)[12] with drift : 1685.158 ARIMA(1,0,0)(1,1,1)[12] with drift : 1684.594 ARIMA(1,0,0)(0,1,1)[12] with drift : 1680.905 ARIMA(1,0,0)(0,1,2)[12] with drift : 1684.211 ARIMA(1,0,0)(1,1,2)[12] with drift : Inf ARIMA(0,0,0)(0,1,1)[12] with drift : 1772.299 ARIMA(2,0,0)(0,1,1)[12] with drift : 1684.965 ARIMA(1,0,1)(0,1,1)[12] with drift : 1685.149 ARIMA(2,0,1)(0,1,1)[12] with drift : 1688.428 ARIMA(1,0,0)(0,1,1)[12] : 1676.443 ARIMA(1,0,0)(0,1,0)[12] : 1697.822 ARIMA(1,0,0)(1,1,1)[12] : 1680.163 ARIMA(1,0,0)(0,1,2)[12] : 1679.795 ARIMA(1,0,0)(1,1,0)[12] : 1678.467 ARIMA(1,0,0)(1,1,2)[12] : Inf ARIMA(0,0,0)(0,1,1)[12] : 1768.607 ARIMA(2,0,0)(0,1,1)[12] : 1680.489 ARIMA(1,0,1)(0,1,1)[12] : 1680.677 ARIMA(0,0,1)(0,1,1)[12] : 1720.732 ARIMA(2,0,1)(0,1,1)[12] : 1683.954Best model: ARIMA(1,0,0)(0,1,1)[12]" }, { "code": null, "e": 6604, "s": 6534, "text": "The best model configuration is indicated as ARIMA(1,0,0)(0,1,1)[12]." }, { "code": null, "e": 6652, "s": 6604, "text": "The coefficients for this model are as follows:" }, { "code": null, "e": 6884, "s": 6652, "text": "> fitpassengersSeries: passengernumbers ARIMA(1,0,0)(0,1,1)[12]Coefficients: ar1 sma1 0.7794 -0.5001s.e. 0.0609 0.0840sigma^2 estimated as 585834: log likelihood=-831.27AIC=1668.54 AICc=1668.78 BIC=1676.44" }, { "code": null, "e": 6935, "s": 6884, "text": "The ARIMA model generates the following forecasts:" }, { "code": null, "e": 7016, "s": 6935, "text": "The RMSE (root mean squared error) and MFE (mean forecast error) are as follows:" }, { "code": null, "e": 7026, "s": 7016, "text": "RMSE: 698" }, { "code": null, "e": 7036, "s": 7026, "text": "MFE: -115" }, { "code": null, "e": 7449, "s": 7036, "text": "> # Errors> library(Metrics)> rmse(df$`Actual Passenger Numbers`, df$`Forecasted Passenger Numbers`)[1] 698.6527> ## Forecast Error> forecast_error=(df$`Actual Passenger Numbers`-df$`Forecasted Passenger Numbers`)> forecast_error [1] -415.8149 -982.0972 -273.1147 -539.5008 -520.7138 -845.2062 -824.7485 [8] -212.4401 -454.4602 1387.1299 962.7507 153.2876 257.2238 687.3703> mean(forecast_error)[1] -115.7381" }, { "code": null, "e": 7721, "s": 7449, "text": "One key difference between ARIMA and Prophet is that the Prophet model accounts for “change points”, or specific shifts in trend in the time series. While it is technically possible to do this with ARIMA in R — it requires use of a separate package called AEDForecasting." }, { "code": null, "e": 7892, "s": 7721, "text": "Prophet works through use of an additive model whereby the non-linear trends in the series are fitted with the appropriate seasonality (whether daily, weekly, or yearly)." }, { "code": null, "e": 8031, "s": 7892, "text": "In this particular dataset, a shift in trend came after 2009 — when we saw a reversal of growth in the overall trend for passenger demand:" }, { "code": null, "e": 8134, "s": 8031, "text": "A standard Prophet model was fitted to the dataset, without any manual specifications for seasonality:" }, { "code": null, "e": 8192, "s": 8134, "text": "prophet_basic = Prophet()prophet_basic.fit(train_dataset)" }, { "code": null, "e": 8357, "s": 8192, "text": "Through trial and error, 4 change points were shown to minimise the RMSE and MFE and therefore were defined as the appropriate number of change points in the model:" }, { "code": null, "e": 8543, "s": 8357, "text": "pro_change= Prophet(n_changepoints=4)forecast = pro_change.fit(train_dataset).predict(future)fig= pro_change.plot(forecast);a = add_changepoints_to_plot(fig.gca(), pro_change, forecast)" }, { "code": null, "e": 8587, "s": 8543, "text": "The RMSE and MAE are calculated as follows:" }, { "code": null, "e": 8930, "s": 8587, "text": ">>> from sklearn.metrics import mean_squared_error>>> from math import sqrt>>> mse = mean_squared_error(passenger_test, yhat14)>>> rmse = sqrt(mse)>>> print('RMSE: %f' % rmse)RMSE: 524.263928>>> forecast_error = (passenger_test-yhat14)>>> forecast_error>>> mean_forecast_error = np.mean(forecast_error)>>> mean_forecast_error71.58326743881493" }, { "code": null, "e": 9089, "s": 8930, "text": "With an RMSE and MFE of 524 and 71 obtained with Prophet respectively, the errors are significantly lower than the errors of 698 and -115 obtained with ARIMA." }, { "code": null, "e": 9369, "s": 9089, "text": "From this standpoint, while ARIMA has accounted for patterns such as seasonality and autocorrelation in the time series — Prophet has excelled at correctly identifying the relevant change point in the series — and this appears to have boosted the forecast accuracy for the model." }, { "code": null, "e": 9680, "s": 9369, "text": "It may be possible that ARIMA would excel when forecasting data with a more clearly defined trend or one that does not particularly exhibit seasonality — we saw very clear signs of this for the dataset in question. However, other cases where seasonality is not present may not be suitable for use with Prophet." }, { "code": null, "e": 9711, "s": 9680, "text": "In this example, we have seen:" }, { "code": null, "e": 9743, "s": 9711, "text": "How to configure an ARIMA model" }, { "code": null, "e": 9791, "s": 9743, "text": "The relevance of change points in a time series" }, { "code": null, "e": 9856, "s": 9791, "text": "Comparison of ARIMA and Prophet in calculating forecast accuracy" }, { "code": null, "e": 9927, "s": 9856, "text": "Many thanks for reading, and questions or feedback are always welcome." }, { "code": null, "e": 10155, "s": 9927, "text": "Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way." }, { "code": null, "e": 10226, "s": 10155, "text": "Analytics Vidhya: SARIMA — Forecasting Seasonal Data with Python and R" }, { "code": null, "e": 10256, "s": 10226, "text": "CRAN — Package AEDForecasting" }, { "code": null, "e": 10338, "s": 10256, "text": "data.world: Air Traffic Passenger Data (Original Source: San Francisco Open Data)" }, { "code": null, "e": 10363, "s": 10338, "text": "GitHub: facebook/prophet" } ]
How to submit a form by clicking a link in JavaScript ? - GeeksforGeeks
14 Aug, 2021 In this article, we have submitted a form using JavaScript by clicking a link. In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked. When we click on the link, the function submitForm() will get executed. This function will get the element object using DOM getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method. Example: Create a form and submit it using the above approach. It is required for the form structure where the user will provide his/her details. HTML <!DOCTYPE html><html> <body> <h2 style="color:green">GeeksforGeeks</h2> <b>Submit form details</b> <form id="form__submit" action="form.php" method="post"> <label>NAME: </label><br /> <input type="text" name="name" /><br /> <label>AGE: </label><br /> <input type="number" name="age" /><br /> <label>CITY: </label><br /> <input type="text" name="city" /><br /><br /> <a href="#" onclick="submitForm()">Submit Here</a> </form> <script> function submitForm() { let form = document.getElementById("form__submit"); form.submit(); } </script></body> </html> Note: The given HTML code will redirect the form data to the site or file which is mentioned in the action attribute. PHP Code: Create a PHP file to get the user entered form data, rename this PHP file as “form.php”. This code displays the user form data. PHP <?php $name=$_POST['name']; $age=$_POST['age']; $city=$_POST['city']; echo "NAME-SUBMITTED : $name <br>"; echo "AGE-SUBMITTED : $age <br>"; echo "CITY-SUBMITTED: $city";?> Output: user form data PHP is a client-side language. So it requires a server. Please refer PHP tutorial for a better understanding. HTML-Questions JavaScript-Questions PHP-basics Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery DOM (Document Object Model) Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ?
[ { "code": null, "e": 24894, "s": 24866, "text": "\n14 Aug, 2021" }, { "code": null, "e": 25448, "s": 24894, "text": "In this article, we have submitted a form using JavaScript by clicking a link. In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked. When we click on the link, the function submitForm() will get executed. This function will get the element object using DOM getElementById() method by passing the form id to this method, then the form will be submitted by using submit() method." }, { "code": null, "e": 25594, "s": 25448, "text": "Example: Create a form and submit it using the above approach. It is required for the form structure where the user will provide his/her details." }, { "code": null, "e": 25599, "s": 25594, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2 style=\"color:green\">GeeksforGeeks</h2> <b>Submit form details</b> <form id=\"form__submit\" action=\"form.php\" method=\"post\"> <label>NAME: </label><br /> <input type=\"text\" name=\"name\" /><br /> <label>AGE: </label><br /> <input type=\"number\" name=\"age\" /><br /> <label>CITY: </label><br /> <input type=\"text\" name=\"city\" /><br /><br /> <a href=\"#\" onclick=\"submitForm()\">Submit Here</a> </form> <script> function submitForm() { let form = document.getElementById(\"form__submit\"); form.submit(); } </script></body> </html>", "e": 26260, "s": 25599, "text": null }, { "code": null, "e": 26378, "s": 26260, "text": "Note: The given HTML code will redirect the form data to the site or file which is mentioned in the action attribute." }, { "code": null, "e": 26516, "s": 26378, "text": "PHP Code: Create a PHP file to get the user entered form data, rename this PHP file as “form.php”. This code displays the user form data." }, { "code": null, "e": 26520, "s": 26516, "text": "PHP" }, { "code": "<?php $name=$_POST['name']; $age=$_POST['age']; $city=$_POST['city']; echo \"NAME-SUBMITTED : $name <br>\"; echo \"AGE-SUBMITTED : $age <br>\"; echo \"CITY-SUBMITTED: $city\";?>", "e": 26718, "s": 26520, "text": null }, { "code": null, "e": 26726, "s": 26718, "text": "Output:" }, { "code": null, "e": 26741, "s": 26726, "text": "user form data" }, { "code": null, "e": 26851, "s": 26741, "text": "PHP is a client-side language. So it requires a server. Please refer PHP tutorial for a better understanding." }, { "code": null, "e": 26866, "s": 26851, "text": "HTML-Questions" }, { "code": null, "e": 26887, "s": 26866, "text": "JavaScript-Questions" }, { "code": null, "e": 26898, "s": 26887, "text": "PHP-basics" }, { "code": null, "e": 26905, "s": 26898, "text": "Picked" }, { "code": null, "e": 26910, "s": 26905, "text": "HTML" }, { "code": null, "e": 26921, "s": 26910, "text": "JavaScript" }, { "code": null, "e": 26938, "s": 26921, "text": "Web Technologies" }, { "code": null, "e": 26943, "s": 26938, "text": "HTML" }, { "code": null, "e": 27041, "s": 26943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27065, "s": 27041, "text": "REST API (Introduction)" }, { "code": null, "e": 27102, "s": 27065, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27122, "s": 27102, "text": "Angular File Upload" }, { "code": null, "e": 27151, "s": 27122, "text": "Form validation using jQuery" }, { "code": null, "e": 27179, "s": 27151, "text": "DOM (Document Object Model)" }, { "code": null, "e": 27224, "s": 27179, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27285, "s": 27224, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27354, "s": 27285, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 27426, "s": 27354, "text": "Differences between Functional Components and Class Components in React" } ]
How to print % using printf()?
Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use ‘%%’. Neither single % will print anything nor it will show any error or warning. Here is an example to print % in printf() in C language, Live Demo #include<stdio.h> int main() { printf("%"); printf("%%"); getchar(); return 0; } % There are some other ways to print % in the text message as in the following example, Live Demo #include<stdio.h> #include<string.h> int main() { printf("welcome%\n"); printf("%%\n"); printf("%c\n",'%'); printf("%s\n","%"); char a[5]; strcpy(a, "%%"); printf("This is a's value: %s\n", a); return 0; } welcome% % 37 % % This is a's value: %%
[ { "code": null, "e": 1287, "s": 1062, "text": "Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use ‘%%’. Neither single % will print anything nor it will show any error or warning." }, { "code": null, "e": 1344, "s": 1287, "text": "Here is an example to print % in printf() in C language," }, { "code": null, "e": 1355, "s": 1344, "text": " Live Demo" }, { "code": null, "e": 1448, "s": 1355, "text": "#include<stdio.h>\nint main() {\n printf(\"%\");\n printf(\"%%\");\n getchar();\n return 0;\n}" }, { "code": null, "e": 1450, "s": 1448, "text": "%" }, { "code": null, "e": 1536, "s": 1450, "text": "There are some other ways to print % in the text message as in the following example," }, { "code": null, "e": 1547, "s": 1536, "text": " Live Demo" }, { "code": null, "e": 1777, "s": 1547, "text": "#include<stdio.h>\n#include<string.h>\nint main() {\n printf(\"welcome%\\n\");\n printf(\"%%\\n\");\n printf(\"%c\\n\",'%');\n printf(\"%s\\n\",\"%\");\n char a[5];\n strcpy(a, \"%%\");\n printf(\"This is a's value: %s\\n\", a);\n return 0;\n}" }, { "code": null, "e": 1817, "s": 1777, "text": "welcome%\n%\n37\n%\n%\nThis is a's value: %%" } ]
5 Wrong Use Cases Of Python List Comprehensions | by Anupam Chugh | Towards Data Science
List comprehensions are unarguably the most powerful feature of Python. They are pythonic, powerful, and provide readability. But that easily opens up the door for misusing them. Or rather abusing in various forms. In doing so, your code only gets non-pythonic and hard to decipher by peers. In the following section, we’ll look at a few incorrect ways of using Python list comprehensions with their replacements. A lot of programmers when starting out with Python, begin using list comprehensions where it isn’t really needed. For instance, in the following examples, using list comprehensions isn’t the best idea as we aren’t doing anything with the list. vehicles = [ car, bike, truck ][ v.setLights(true) for v in vehicles ]names = [ "A", "B", "C" ][ print(i) for n in names ] In such cases, it’s better to use the classic for loops as it’ll prevent the creation of an unnecessary list. List comprehensions aren’t meant to specify commands or set states on the elements. You might want to transform characters of a string or simply add a bunch of numbers. In either of the cases, picking list comprehensions just because it’s fancy doesn’t mean it’s pythonic too. Let’s consider the following example: total = 0listOne = [1,2,3][total := total + x for x in listOne] While the Python 3.8 assignment operator := lets us do a sum of list elements using list comprehensions, why reinvent a wheel when Python provides a built-in sum() function? The above list comprehension can be done away with a remarkably short piece of code: sum(listOne) Similarly, when you’re only splitting a string into characters(or transforming them), using list comprehension is overkill and not necessary at all: str = "Fred"chars = [x for x in str]#use this instead:chars = list(str) List comprehensions however good they are can become a pain when they’re nested. Readability issues are only further aggravated when the logic is lengthy. Python list comprehensions should best be reserved for concise logic in order to adhere to pythonic code. This means it’s okay to let go of nested list comprehensions in favor of nested loops if need be. The following example only showcases, how nested loops can be easier to comprehend and at times are a good substitute for long nested comprehensions. list = [[1,2,3],[-1,-5,6]]flatten = [item for sublist in list for item in sublist if item > 0]#using loopsflatten1 = []for rows in list: for sublist in rows: if sublist > 0: flatten1.append(sublist) List comprehensions let you create lists easily but they occupy memory for the whole time. This makes them very inefficient especially when dealing with large datasets. Consider the below example where you’d easily run into out of memory errors. sum([i * i for i in range(1000)]) Using a generator expression instead is recommended as it yields value one at a time: sum(i* i for i in range(1000)) Another example where storing the list in memory is a bad idea is when you’re only looking for a single element based on a certain condition. The following list comprehension one-liner is inefficient. first = [x for x in list if x.get("id")=="12"] We can substitute this with not only a generator expression but also set the next function in order to return when the first element matches a given condition: first = next((x for x in list if x.get("id")=="12"), None) Using itertools functions alongwith generator expression are an effective way to exit rather than using list comprehension which doesn’t support break or continue. Again, you’ll be surprised to know how easy to get bogged down with list comprehensions and use it for unzipping tuples. The below example just reinstates another incorrect use case where we’re splitting the tuple values into nested lists: myList = [('A', 1), ('B', 2), ('C', 3)]result = [[ i for i, j in myList ], [ j for i, j in myList ]] Python already provides us with a specific built-in tool that lets us unzip tuples. Simply use the unpacking operator * to destructure the tuple and pass it to the zip function for creating separate lists. result = list(zip(*myList))# [['A', 'B', 'C'], [1, 2, 3]] Python List Comprehensions are powerful but they can be easily overused thereby making the code non-pythonic. I hope the above incorrect approaches help you make a better judgment of when not to use list comprehensions. That’s it for this one. Thanks for reading.
[ { "code": null, "e": 297, "s": 171, "text": "List comprehensions are unarguably the most powerful feature of Python. They are pythonic, powerful, and provide readability." }, { "code": null, "e": 463, "s": 297, "text": "But that easily opens up the door for misusing them. Or rather abusing in various forms. In doing so, your code only gets non-pythonic and hard to decipher by peers." }, { "code": null, "e": 585, "s": 463, "text": "In the following section, we’ll look at a few incorrect ways of using Python list comprehensions with their replacements." }, { "code": null, "e": 699, "s": 585, "text": "A lot of programmers when starting out with Python, begin using list comprehensions where it isn’t really needed." }, { "code": null, "e": 829, "s": 699, "text": "For instance, in the following examples, using list comprehensions isn’t the best idea as we aren’t doing anything with the list." }, { "code": null, "e": 952, "s": 829, "text": "vehicles = [ car, bike, truck ][ v.setLights(true) for v in vehicles ]names = [ \"A\", \"B\", \"C\" ][ print(i) for n in names ]" }, { "code": null, "e": 1146, "s": 952, "text": "In such cases, it’s better to use the classic for loops as it’ll prevent the creation of an unnecessary list. List comprehensions aren’t meant to specify commands or set states on the elements." }, { "code": null, "e": 1339, "s": 1146, "text": "You might want to transform characters of a string or simply add a bunch of numbers. In either of the cases, picking list comprehensions just because it’s fancy doesn’t mean it’s pythonic too." }, { "code": null, "e": 1377, "s": 1339, "text": "Let’s consider the following example:" }, { "code": null, "e": 1441, "s": 1377, "text": "total = 0listOne = [1,2,3][total := total + x for x in listOne]" }, { "code": null, "e": 1700, "s": 1441, "text": "While the Python 3.8 assignment operator := lets us do a sum of list elements using list comprehensions, why reinvent a wheel when Python provides a built-in sum() function? The above list comprehension can be done away with a remarkably short piece of code:" }, { "code": null, "e": 1713, "s": 1700, "text": "sum(listOne)" }, { "code": null, "e": 1862, "s": 1713, "text": "Similarly, when you’re only splitting a string into characters(or transforming them), using list comprehension is overkill and not necessary at all:" }, { "code": null, "e": 1934, "s": 1862, "text": "str = \"Fred\"chars = [x for x in str]#use this instead:chars = list(str)" }, { "code": null, "e": 2089, "s": 1934, "text": "List comprehensions however good they are can become a pain when they’re nested. Readability issues are only further aggravated when the logic is lengthy." }, { "code": null, "e": 2293, "s": 2089, "text": "Python list comprehensions should best be reserved for concise logic in order to adhere to pythonic code. This means it’s okay to let go of nested list comprehensions in favor of nested loops if need be." }, { "code": null, "e": 2443, "s": 2293, "text": "The following example only showcases, how nested loops can be easier to comprehend and at times are a good substitute for long nested comprehensions." }, { "code": null, "e": 2692, "s": 2443, "text": "list = [[1,2,3],[-1,-5,6]]flatten = [item for sublist in list for item in sublist if item > 0]#using loopsflatten1 = []for rows in list: for sublist in rows: if sublist > 0: flatten1.append(sublist)" }, { "code": null, "e": 2861, "s": 2692, "text": "List comprehensions let you create lists easily but they occupy memory for the whole time. This makes them very inefficient especially when dealing with large datasets." }, { "code": null, "e": 2938, "s": 2861, "text": "Consider the below example where you’d easily run into out of memory errors." }, { "code": null, "e": 2972, "s": 2938, "text": "sum([i * i for i in range(1000)])" }, { "code": null, "e": 3058, "s": 2972, "text": "Using a generator expression instead is recommended as it yields value one at a time:" }, { "code": null, "e": 3089, "s": 3058, "text": "sum(i* i for i in range(1000))" }, { "code": null, "e": 3290, "s": 3089, "text": "Another example where storing the list in memory is a bad idea is when you’re only looking for a single element based on a certain condition. The following list comprehension one-liner is inefficient." }, { "code": null, "e": 3346, "s": 3290, "text": "first = [x for x in list if x.get(\"id\")==\"12\"]" }, { "code": null, "e": 3506, "s": 3346, "text": "We can substitute this with not only a generator expression but also set the next function in order to return when the first element matches a given condition:" }, { "code": null, "e": 3565, "s": 3506, "text": "first = next((x for x in list if x.get(\"id\")==\"12\"), None)" }, { "code": null, "e": 3729, "s": 3565, "text": "Using itertools functions alongwith generator expression are an effective way to exit rather than using list comprehension which doesn’t support break or continue." }, { "code": null, "e": 3850, "s": 3729, "text": "Again, you’ll be surprised to know how easy to get bogged down with list comprehensions and use it for unzipping tuples." }, { "code": null, "e": 3969, "s": 3850, "text": "The below example just reinstates another incorrect use case where we’re splitting the tuple values into nested lists:" }, { "code": null, "e": 4076, "s": 3969, "text": "myList = [('A', 1), ('B', 2), ('C', 3)]result = [[ i for i, j in myList ], [ j for i, j in myList ]]" }, { "code": null, "e": 4282, "s": 4076, "text": "Python already provides us with a specific built-in tool that lets us unzip tuples. Simply use the unpacking operator * to destructure the tuple and pass it to the zip function for creating separate lists." }, { "code": null, "e": 4340, "s": 4282, "text": "result = list(zip(*myList))# [['A', 'B', 'C'], [1, 2, 3]]" }, { "code": null, "e": 4450, "s": 4340, "text": "Python List Comprehensions are powerful but they can be easily overused thereby making the code non-pythonic." }, { "code": null, "e": 4560, "s": 4450, "text": "I hope the above incorrect approaches help you make a better judgment of when not to use list comprehensions." } ]
Python - Display True for infinite values in a Pandas DataFrame
Use the isin() method to display True for infinite values. At first, let us import the required libraries with their respective aliases − import pandas as pd import numpy as np Create a dictionary of list. We have set the infinity values using the Numpy np.inf − d = { "Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf] } Creating DataFrame from the above dictionary of list − dataFrame = pd.DataFrame(d) Display True for infinite values − res = dataFrame.isin([np.inf, -np.inf]) Following is the code − import pandas as pd import numpy as np # dictionary of list d = { "Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf] } # creating dataframe from the above dictionary of list dataFrame = pd.DataFrame(d) print"DataFrame...\n",dataFrame # checking for infinite values and displaying the count count = np.isinf(dataFrame).values.sum() print"\nInfinity values count...\n ",count # Displaying TRUE for infinite values res = dataFrame.isin([np.inf, -np.inf]) print"\n Updated DataFrame...\n",res This will produce the following output − DataFrame... Reg_Price 0 7000.505700 1 inf 2 5000.000000 3 inf 4 9000.757680 5 6000.000000 6 900.000000 7 inf Infinity values count... 3 Updated DataFrame... Reg_Price 0 False 1 True 2 False 3 True 4 False 5 False 6 False 7 True
[ { "code": null, "e": 1200, "s": 1062, "text": "Use the isin() method to display True for infinite values. At first, let us import the required libraries with their respective aliases −" }, { "code": null, "e": 1239, "s": 1200, "text": "import pandas as pd\nimport numpy as np" }, { "code": null, "e": 1325, "s": 1239, "text": "Create a dictionary of list. We have set the infinity values using the Numpy np.inf −" }, { "code": null, "e": 1412, "s": 1325, "text": "d = { \"Reg_Price\": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf] }\n" }, { "code": null, "e": 1467, "s": 1412, "text": "Creating DataFrame from the above dictionary of list −" }, { "code": null, "e": 1495, "s": 1467, "text": "dataFrame = pd.DataFrame(d)" }, { "code": null, "e": 1530, "s": 1495, "text": "Display True for infinite values −" }, { "code": null, "e": 1571, "s": 1530, "text": "res = dataFrame.isin([np.inf, -np.inf])\n" }, { "code": null, "e": 1595, "s": 1571, "text": "Following is the code −" }, { "code": null, "e": 2115, "s": 1595, "text": "import pandas as pd\nimport numpy as np\n\n# dictionary of list\nd = { \"Reg_Price\": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf] }\n\n# creating dataframe from the above dictionary of list\ndataFrame = pd.DataFrame(d)\nprint\"DataFrame...\\n\",dataFrame\n\n# checking for infinite values and displaying the count\ncount = np.isinf(dataFrame).values.sum()\nprint\"\\nInfinity values count...\\n \",count\n\n# Displaying TRUE for infinite values\nres = dataFrame.isin([np.inf, -np.inf])\nprint\"\\n Updated DataFrame...\\n\",res" }, { "code": null, "e": 2156, "s": 2115, "text": "This will produce the following output −" }, { "code": null, "e": 2483, "s": 2156, "text": "DataFrame...\n Reg_Price\n0 7000.505700\n1 inf\n2 5000.000000\n3 inf\n4 9000.757680\n5 6000.000000\n6 900.000000\n7 inf\n\nInfinity values count...\n 3\n\nUpdated DataFrame...\n Reg_Price\n0 False\n1 True\n2 False\n3 True\n4 False\n5 False\n6 False\n7 True" } ]
Supervised Learning Algorithms: Explanaition and Simple code | by Felipe Sanchez Garzón | Towards Data Science
A supervised learning algorithm takes a known set of input data (the learning set) and known responses to the data (the output), and forms a model to generate reasonable predictions for the response to the new input data. Use supervised learning if you have existing data for the output you are trying to predict. They can be for Classification or Regression. In this post I will show some example of each one. 1) Import the Classifier from sklearn.neighbors import KNeighborsClassifier2) Create arrays for the features and the response variable y = df['target'].values X = df.drop('target', axis=1).values 3) Create a k-NN classifier with 6 neighbors knn = KNeighborsClassifier(n_neighbors = 6) 4) Fit the classifier to the data knn.fit(X,y) 5) make predictionsnew_prediction = knn.predict(X_new) 1) Setup arrays to store train and test accuraciesneighbors = np.arange(1, 9)train_accuracy = np.empty(len(neighbors))test_accuracy = np.empty(len(neighbors))2) Loop over different values of kfor i, k in enumerate(neighbors): 3) Setup a k-NN Classifier with k neighbors knn = KNeighborsClassifier(n_neighbors=k) 4) Fit the classifier to the training data knn.fit(X_train, y_train) 5) Compute accuracy on the training set train_accuracy[i] = knn.score(X_train, y_train) 6) Compute accuracy on the testing set test_accuracy[i] = knn.score(X_test, y_test)7) Generate plotplt.title('k-NN: Varying Number of Neighbors')plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')plt.legend()plt.xlabel('Number of Neighbors')plt.ylabel('Accuracy') 1) Import the Classifierfrom sklearn.ensemble import RandomForestClassifier2) input data as np arrayy = df[‘target'].valuesX = df.drop(‘target', axis=1).values3) import model and fit(train) datarfc = RandomForestClassifier(n_estimators=100)rfc.fit(X, y)4) make predictionspred_rfc = rfc.predict(X_test) 1) Import the necessary modules from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, classification_report 2) Create training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state=42) 3) Create the classifier: logreg = LogisticRegression() 4) Fit the classifier to the training data logreg.fit(X_train,y_train) 5) Predict the labels of the test set y_pred = logreg.predict(X_test) THE ROC Curve for the Logisti Regression ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied. The ROC curve is created by plotting the true positive rate against the false positive rate at various threshold settings. The true-positive rate is also known as sensitivity, recall or probability of detection. The false-positive rate is also known as probability of false alarm 1) Import the necessary modules from sklearn.metrics import roc_curve 2) Compute predicted probabilities y_pred_prob = logreg.predict_proba(X_test)[:,1] 3) Generate ROC curve values fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob) 4) Plot ROC curve plt.plot([0, 1], [0, 1], 'k--') plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.show() The larger the area under the ROC curve, the better the model. 1) Import LinearRegression from sklearn import linear_model from sklearn.linear_model import LinearRegression2) Create the regressor reg = linear_model.LinearRegression()3) Create the prediction space prediction_space = np.linspace(min(X_fertility),max(X_fertility)).reshape(-1,1)4) Fit the model to the data reg.fit(X_fertility,y)5) Compute predictions y_pred = reg.predict(prediction_space)6) Plot regression line plt.plot(prediction_space, y_pred, color='black', linewidth=3) plt.show() 1) Import Decision Tree Regressorfrom sklearn.tree import DecisionTreeRegressor2) Create a decision tree regression model decision_tree = DecisionTreeRegressor() 3) Fit the model to the training features and targets decision_tree.fit(train_features,train_targets) 4) Check the score on train and test print(decision_tree.score(train_features, train_targets)) print(decision_tree.score(test_features,test_targets)) Finally, two more regression algorithms: If you like to continue reading stories like this one you can suscribe here ! If you want to see how these algorithms performs in a dataset from the real world, I suggest you to read the next post: towardsdatascience.com Or to read this project, where I am working with the data from my reasearch:
[ { "code": null, "e": 486, "s": 172, "text": "A supervised learning algorithm takes a known set of input data (the learning set) and known responses to the data (the output), and forms a model to generate reasonable predictions for the response to the new input data. Use supervised learning if you have existing data for the output you are trying to predict." }, { "code": null, "e": 583, "s": 486, "text": "They can be for Classification or Regression. In this post I will show some example of each one." }, { "code": null, "e": 1042, "s": 583, "text": "1) Import the Classifier from sklearn.neighbors import KNeighborsClassifier2) Create arrays for the features and the response variable y = df['target'].values X = df.drop('target', axis=1).values 3) Create a k-NN classifier with 6 neighbors knn = KNeighborsClassifier(n_neighbors = 6) 4) Fit the classifier to the data knn.fit(X,y) 5) make predictionsnew_prediction = knn.predict(X_new)" }, { "code": null, "e": 1866, "s": 1042, "text": "1) Setup arrays to store train and test accuraciesneighbors = np.arange(1, 9)train_accuracy = np.empty(len(neighbors))test_accuracy = np.empty(len(neighbors))2) Loop over different values of kfor i, k in enumerate(neighbors): 3) Setup a k-NN Classifier with k neighbors knn = KNeighborsClassifier(n_neighbors=k) 4) Fit the classifier to the training data knn.fit(X_train, y_train) 5) Compute accuracy on the training set train_accuracy[i] = knn.score(X_train, y_train) 6) Compute accuracy on the testing set test_accuracy[i] = knn.score(X_test, y_test)7) Generate plotplt.title('k-NN: Varying Number of Neighbors')plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')plt.legend()plt.xlabel('Number of Neighbors')plt.ylabel('Accuracy')" }, { "code": null, "e": 2169, "s": 1866, "text": "1) Import the Classifierfrom sklearn.ensemble import RandomForestClassifier2) input data as np arrayy = df[‘target'].valuesX = df.drop(‘target', axis=1).values3) import model and fit(train) datarfc = RandomForestClassifier(n_estimators=100)rfc.fit(X, y)4) make predictionspred_rfc = rfc.predict(X_test)" }, { "code": null, "e": 2722, "s": 2169, "text": "1) Import the necessary modules from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, classification_report 2) Create training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state=42) 3) Create the classifier: logreg = LogisticRegression() 4) Fit the classifier to the training data logreg.fit(X_train,y_train) 5) Predict the labels of the test set y_pred = logreg.predict(X_test)" }, { "code": null, "e": 2763, "s": 2722, "text": "THE ROC Curve for the Logisti Regression" }, { "code": null, "e": 3187, "s": 2763, "text": "ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied. The ROC curve is created by plotting the true positive rate against the false positive rate at various threshold settings. The true-positive rate is also known as sensitivity, recall or probability of detection. The false-positive rate is also known as probability of false alarm" }, { "code": null, "e": 3669, "s": 3187, "text": "1) Import the necessary modules from sklearn.metrics import roc_curve 2) Compute predicted probabilities y_pred_prob = logreg.predict_proba(X_test)[:,1] 3) Generate ROC curve values fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob) 4) Plot ROC curve plt.plot([0, 1], [0, 1], 'k--') plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.show()" }, { "code": null, "e": 3732, "s": 3669, "text": "The larger the area under the ROC curve, the better the model." }, { "code": null, "e": 4266, "s": 3732, "text": "1) Import LinearRegression from sklearn import linear_model from sklearn.linear_model import LinearRegression2) Create the regressor reg = linear_model.LinearRegression()3) Create the prediction space prediction_space = np.linspace(min(X_fertility),max(X_fertility)).reshape(-1,1)4) Fit the model to the data reg.fit(X_fertility,y)5) Compute predictions y_pred = reg.predict(prediction_space)6) Plot regression line plt.plot(prediction_space, y_pred, color='black', linewidth=3) plt.show()" }, { "code": null, "e": 4731, "s": 4266, "text": "1) Import Decision Tree Regressorfrom sklearn.tree import DecisionTreeRegressor2) Create a decision tree regression model decision_tree = DecisionTreeRegressor() 3) Fit the model to the training features and targets decision_tree.fit(train_features,train_targets) 4) Check the score on train and test print(decision_tree.score(train_features, train_targets)) print(decision_tree.score(test_features,test_targets))" }, { "code": null, "e": 4772, "s": 4731, "text": "Finally, two more regression algorithms:" }, { "code": null, "e": 4850, "s": 4772, "text": "If you like to continue reading stories like this one you can suscribe here !" }, { "code": null, "e": 4970, "s": 4850, "text": "If you want to see how these algorithms performs in a dataset from the real world, I suggest you to read the next post:" }, { "code": null, "e": 4993, "s": 4970, "text": "towardsdatascience.com" } ]
PHP | getcwd( ) Function - GeeksforGeeks
11 Jul, 2018 The getcwd() function in PHP is an inbuilt function which is used to return the current working directory. This function does not accepts any parameter and returns the current working directory on successful function call or FALSE on failure. Syntax: getcwd() Parameters: This function does not accept any parameter. Return Value: It returns the current working directory on successful function call or FALSE on failure. Errors And Exceptions: getcwd() returns FALSE on some Unix variants if any one of the parent directories does not have the readable or search mode set.If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link. getcwd() returns FALSE on some Unix variants if any one of the parent directories does not have the readable or search mode set. If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link. Below programs illustrate the getcwd() function: Program 1: <?php //current directory$cur_dir = getcwd(); // displaying current directoryecho $cur_dir ; ?> Output: user/home/gfg Program 2: <?php//current directory $cur_dir = getcwd(); echo("Current Directory is " . $cur_dir); echo "<br>" ; //changing current directory$flag = chdir("user/home/articles"); if($flag == true) { $cur_dir = getcwd();echo("Directory Has Been Successfully Changed to " . $cur_dir);}else{echo("Failed to Change Directory.");}?> Output: Current Directory Location is user/home/gfg Directory Has Been Successfully Changed to user/home/articles Reference: http://php.net/manual/en/function.getcwd.php PHP-file-handling PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? PHP in_array() Function How to convert array to string in PHP ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 40503, "s": 40475, "text": "\n11 Jul, 2018" }, { "code": null, "e": 40746, "s": 40503, "text": "The getcwd() function in PHP is an inbuilt function which is used to return the current working directory. This function does not accepts any parameter and returns the current working directory on successful function call or FALSE on failure." }, { "code": null, "e": 40754, "s": 40746, "text": "Syntax:" }, { "code": null, "e": 40763, "s": 40754, "text": "getcwd()" }, { "code": null, "e": 40820, "s": 40763, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 40924, "s": 40820, "text": "Return Value: It returns the current working directory on successful function call or FALSE on failure." }, { "code": null, "e": 40947, "s": 40924, "text": "Errors And Exceptions:" }, { "code": null, "e": 41186, "s": 40947, "text": "getcwd() returns FALSE on some Unix variants if any one of the parent directories does not have the readable or search mode set.If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link." }, { "code": null, "e": 41315, "s": 41186, "text": "getcwd() returns FALSE on some Unix variants if any one of the parent directories does not have the readable or search mode set." }, { "code": null, "e": 41426, "s": 41315, "text": "If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link." }, { "code": null, "e": 41475, "s": 41426, "text": "Below programs illustrate the getcwd() function:" }, { "code": null, "e": 41486, "s": 41475, "text": "Program 1:" }, { "code": "<?php //current directory$cur_dir = getcwd(); // displaying current directoryecho $cur_dir ; ?>", "e": 41584, "s": 41486, "text": null }, { "code": null, "e": 41592, "s": 41584, "text": "Output:" }, { "code": null, "e": 41607, "s": 41592, "text": "user/home/gfg\n" }, { "code": null, "e": 41618, "s": 41607, "text": "Program 2:" }, { "code": "<?php//current directory $cur_dir = getcwd(); echo(\"Current Directory is \" . $cur_dir); echo \"<br>\" ; //changing current directory$flag = chdir(\"user/home/articles\"); if($flag == true) { $cur_dir = getcwd();echo(\"Directory Has Been Successfully Changed to \" . $cur_dir);}else{echo(\"Failed to Change Directory.\");}?>", "e": 41938, "s": 41618, "text": null }, { "code": null, "e": 41946, "s": 41938, "text": "Output:" }, { "code": null, "e": 42053, "s": 41946, "text": "Current Directory Location is user/home/gfg\nDirectory Has Been Successfully Changed to user/home/articles\n" }, { "code": null, "e": 42109, "s": 42053, "text": "Reference: http://php.net/manual/en/function.getcwd.php" }, { "code": null, "e": 42127, "s": 42109, "text": "PHP-file-handling" }, { "code": null, "e": 42140, "s": 42127, "text": "PHP-function" }, { "code": null, "e": 42144, "s": 42140, "text": "PHP" }, { "code": null, "e": 42161, "s": 42144, "text": "Web Technologies" }, { "code": null, "e": 42165, "s": 42161, "text": "PHP" }, { "code": null, "e": 42263, "s": 42165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42272, "s": 42263, "text": "Comments" }, { "code": null, "e": 42285, "s": 42272, "text": "Old Comments" }, { "code": null, "e": 42335, "s": 42285, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 42380, "s": 42335, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 42424, "s": 42380, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 42448, "s": 42424, "text": "PHP in_array() Function" }, { "code": null, "e": 42488, "s": 42448, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 42544, "s": 42488, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 42577, "s": 42544, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42639, "s": 42577, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42682, "s": 42639, "text": "How to fetch data from an API in ReactJS ?" } ]
How to show a window that was hidden using the "withdraw" method in Tkinter?
Tkinter withdraw method hides the window without destroying it internally. It is similar to the iconify method that turns a window into a small icon. Let us suppose we want to reveal the hidden window during the execution of an application then we can use deiconify() method. It can be invoked with the window or frame of a widget in the application. In this example, we will define a button in a Toplevel window (Popup Window) which can be the trigger to reveal the main window. #Import the library from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame win= Tk() #Set the window geometry win.geometry("750x200") #Create a Label Label(win, text= "Tkinter is a GUI Library in Python", font=('Helvetica 15 bold')).pack(pady=20) #Define a function to show the Main window def show_win(): win.deiconify() #Create another Toplevel Window new_win= Toplevel(win) new_win.geometry("700x250") new_win.title("NEW WINDOW") #Hide the Main Window win.withdraw() #Create a Button to Hide/ Reveal the Main Window button= ttk.Button(new_win, text="Show" ,command= show_win) button.pack(pady=50) win.mainloop() Running the above code will show the output as, When we click the button "Show", it will display the Main window.
[ { "code": null, "e": 1413, "s": 1062, "text": "Tkinter withdraw method hides the window without destroying it internally. It is similar to the iconify method that turns a window into a small icon. Let us suppose we want to reveal the hidden window during the execution of an application then we can use deiconify() method. It can be invoked with the window or frame of a widget in the application." }, { "code": null, "e": 1542, "s": 1413, "text": "In this example, we will define a button in a Toplevel window (Popup Window) which can be the trigger to reveal the main window." }, { "code": null, "e": 2196, "s": 1542, "text": "#Import the library\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter frame\nwin= Tk()\n\n#Set the window geometry\nwin.geometry(\"750x200\")\n\n#Create a Label\nLabel(win, text= \"Tkinter is a GUI Library in Python\", font=('Helvetica 15 bold')).pack(pady=20)\n\n#Define a function to show the Main window\ndef show_win():\n win.deiconify()\n\n#Create another Toplevel Window\nnew_win= Toplevel(win)\nnew_win.geometry(\"700x250\")\nnew_win.title(\"NEW WINDOW\")\n\n#Hide the Main Window\nwin.withdraw()\n\n#Create a Button to Hide/ Reveal the Main Window\nbutton= ttk.Button(new_win, text=\"Show\" ,command= show_win)\nbutton.pack(pady=50)\n\nwin.mainloop()" }, { "code": null, "e": 2244, "s": 2196, "text": "Running the above code will show the output as," }, { "code": null, "e": 2310, "s": 2244, "text": "When we click the button \"Show\", it will display the Main window." } ]
How to maximize the browser window in Selenium WebDriver using C#?
We can maximize the browser window with Selenium webdriver in C#. This can be done with the help of the Maximize method. We shall launch the browser and then apply this method on the driver object. driver.Manage().Window.Maximize(); For implementation we shall be using the NUnit framework. using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using System; namespace NUnitTestProject1{ public class Tests{ String u = "https://www.tutorialspoint.com/index.htm"; IWebDriver d; [SetUp] public void Setup(){ //creating object of FirefoxDriver d = new FirefoxDriver(); } [Test] public void Test1(){ //launching URL d.Navigate().GoToUrl(u); //maximizing browser d.Manage().Window.Maximize(); Console.WriteLine("Browser Maximized"); } [TearDown] public void close_Browser(){ d.Quit(); } } } Click on Run All Tests − Then, click on Open additional output for this result link
[ { "code": null, "e": 1260, "s": 1062, "text": "We can maximize the browser window with Selenium webdriver in C#. This can be done with the help of the Maximize method. We shall launch the browser and then apply this method on the driver object." }, { "code": null, "e": 1295, "s": 1260, "text": "driver.Manage().Window.Maximize();" }, { "code": null, "e": 1353, "s": 1295, "text": "For implementation we shall be using the NUnit framework." }, { "code": null, "e": 2015, "s": 1353, "text": "using NUnit.Framework;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing System;\nnamespace NUnitTestProject1{\n public class Tests{\n String u = \"https://www.tutorialspoint.com/index.htm\";\n IWebDriver d;\n [SetUp]\n public void Setup(){\n //creating object of FirefoxDriver\n d = new FirefoxDriver();\n }\n [Test]\n public void Test1(){\n //launching URL\n d.Navigate().GoToUrl(u);\n //maximizing browser\n d.Manage().Window.Maximize();\n Console.WriteLine(\"Browser Maximized\");\n }\n [TearDown]\n public void close_Browser(){\n d.Quit();\n }\n }\n}" }, { "code": null, "e": 2040, "s": 2015, "text": "Click on Run All Tests −" }, { "code": null, "e": 2099, "s": 2040, "text": "Then, click on Open additional output for this result link" } ]
Compilation and execution of Java Program
Let us look at a simple code first that will print the words Hello World. Live Demo public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } } Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps − Open notepad and add the code as above. Open notepad and add the code as above. Save the file as: MyFirstJavaProgram.java. Save the file as: MyFirstJavaProgram.java. Open a command prompt window and go to the directory where you saved the class. Assume it's C:\. Open a command prompt window and go to the directory where you saved the class. Assume it's C:\. Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program. Now, type ' java MyFirstJavaProgram ' to run your program. You will be able to see ' Hello World ' printed on the window. You will be able to see ' Hello World ' printed on the window. C:\> javac MyFirstJavaProgram.java C:\> java MyFirstJavaProgram Hello World About Java programs, it is very important to keep in mind the following points. Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a different meaning in Java. Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a different meaning in Java. Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.Example: class MyFirstJavaClass Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example: class MyFirstJavaClass Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.Example: public void myMethodName() Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example: public void myMethodName() Program File Name − Name of the program file should exactly match the class name.When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' Program File Name − Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program. public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.
[ { "code": null, "e": 1136, "s": 1062, "text": "Let us look at a simple code first that will print the words Hello World." }, { "code": null, "e": 1146, "s": 1136, "text": "Live Demo" }, { "code": null, "e": 1396, "s": 1146, "text": "public class MyFirstJavaProgram {\n\n /* This is my first java program. \n * This will print 'Hello World' as the output \n */\n\n public static void main(String []args) {\n System.out.println(\"Hello World\"); // prints Hello World\n }\n}" }, { "code": null, "e": 1499, "s": 1396, "text": "Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −" }, { "code": null, "e": 1539, "s": 1499, "text": "Open notepad and add the code as above." }, { "code": null, "e": 1579, "s": 1539, "text": "Open notepad and add the code as above." }, { "code": null, "e": 1622, "s": 1579, "text": "Save the file as: MyFirstJavaProgram.java." }, { "code": null, "e": 1665, "s": 1622, "text": "Save the file as: MyFirstJavaProgram.java." }, { "code": null, "e": 1762, "s": 1665, "text": "Open a command prompt window and go to the directory where you saved the class. Assume it's C:\\." }, { "code": null, "e": 1859, "s": 1762, "text": "Open a command prompt window and go to the directory where you saved the class. Assume it's C:\\." }, { "code": null, "e": 2061, "s": 1859, "text": "Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set)." }, { "code": null, "e": 2263, "s": 2061, "text": "Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set)." }, { "code": null, "e": 2322, "s": 2263, "text": "Now, type ' java MyFirstJavaProgram ' to run your program." }, { "code": null, "e": 2381, "s": 2322, "text": "Now, type ' java MyFirstJavaProgram ' to run your program." }, { "code": null, "e": 2444, "s": 2381, "text": "You will be able to see ' Hello World ' printed on the window." }, { "code": null, "e": 2507, "s": 2444, "text": "You will be able to see ' Hello World ' printed on the window." }, { "code": null, "e": 2585, "s": 2507, "text": "C:\\> javac MyFirstJavaProgram.java\nC:\\> java MyFirstJavaProgram \nHello World" }, { "code": null, "e": 2665, "s": 2585, "text": "About Java programs, it is very important to keep in mind the following points." }, { "code": null, "e": 2787, "s": 2665, "text": "Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a different meaning in Java." }, { "code": null, "e": 2909, "s": 2787, "text": "Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a different meaning in Java." }, { "code": null, "e": 3128, "s": 2909, "text": "Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.Example: class MyFirstJavaClass" }, { "code": null, "e": 3316, "s": 3128, "text": "Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case." }, { "code": null, "e": 3348, "s": 3316, "text": "Example: class MyFirstJavaClass" }, { "code": null, "e": 3573, "s": 3348, "text": "Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.Example: public void myMethodName()" }, { "code": null, "e": 3763, "s": 3573, "text": "Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case." }, { "code": null, "e": 3799, "s": 3763, "text": "Example: public void myMethodName()" }, { "code": null, "e": 4215, "s": 3799, "text": "Program File Name − Name of the program file should exactly match the class name.When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'" }, { "code": null, "e": 4297, "s": 4215, "text": "Program File Name − Name of the program file should exactly match the class name." }, { "code": null, "e": 4518, "s": 4297, "text": "When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile)." }, { "code": null, "e": 4633, "s": 4518, "text": "Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'" }, { "code": null, "e": 4777, "s": 4633, "text": "public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program." }, { "code": null, "e": 4921, "s": 4777, "text": "public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program." } ]
MySQL query to find a list of city names that do not start with vowels?
You can use DISTINCT with RLIKE operator to find a list of city names that do not start with vowels. The syntax is as follows − SELECT DISTINCT yourCityColumnName FROM yourTableName WHERE yourCityColumnName NOT RLIKE ‘ ^[AEIOUaeiou].*$’; To understand the above syntax, let us create a table. Here, we have a column for city names. The query to create a table is as follows − mysql> create table Employee_Information -> ( -> Id int NOT NULL AUTO_INCREMENT, -> EmployeeName varchar(20), -> CityName varchar(20), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.76 sec) Insert some records in the table using INSERT command. The query is as follows − mysql> insert into Employee_Information(EmployeeName,CityName) values('Larry','New York'); Query OK, 1 row affected (0.12 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('Sam','Indianapolis'); Query OK, 1 row affected (0.15 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('Carol','El Paso'); Query OK, 1 row affected (0.16 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('John','Austin'); Query OK, 1 row affected (0.07 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('Mike','Denver'); Query OK, 1 row affected (0.06 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('David','Las Vegas'); Query OK, 1 row affected (0.11 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('James','Albuquerque'); Query OK, 1 row affected (0.13 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('Robert','Portland'); Query OK, 1 row affected (0.28 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('Richard','Irvine'); Query OK, 1 row affected (0.10 sec) mysql> insert into Employee_Information(EmployeeName,CityName) values('Michael',' Garland'); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from Employee_Information; The following is the output − +----+--------------+--------------+ | Id | EmployeeName | CityName | +----+--------------+--------------+ | 1 | Larry | New York | | 2 | Sam | Indianapolis | | 3 | Carol | El Paso | | 4 | John | Austin | | 5 | Mike | Denver | | 6 | David | Las Vegas | | 7 | James | Albuquerque | | 8 | Robert | Portland | | 9 | Richard | Irvine | | 10 | Michael | Garland | +----+--------------+--------------+ 10 rows in set (0.00 sec) Here is the query to find a list of city names that do not start with vowel. This means first letter of city name must not start with A,E,I,O,U or a,e,i,o,u − mysql> SELECT DISTINCT CityName FROM Employee_Information -> WHERE CityName NOT RLIKE '^[AEIOUaeiou].*$'; The following is the output − +-----------+ | CityName | +-----------+ | New York | | Denver | | Las Vegas | | Portland | | Garland | +-----------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1163, "s": 1062, "text": "You can use DISTINCT with RLIKE operator to find a list of city names that do not start with vowels." }, { "code": null, "e": 1190, "s": 1163, "text": "The syntax is as follows −" }, { "code": null, "e": 1300, "s": 1190, "text": "SELECT DISTINCT yourCityColumnName FROM yourTableName WHERE\nyourCityColumnName NOT RLIKE ‘ ^[AEIOUaeiou].*$’;" }, { "code": null, "e": 1394, "s": 1300, "text": "To understand the above syntax, let us create a table. Here, we have a column for city names." }, { "code": null, "e": 1438, "s": 1394, "text": "The query to create a table is as follows −" }, { "code": null, "e": 1653, "s": 1438, "text": "mysql> create table Employee_Information\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> EmployeeName varchar(20),\n -> CityName varchar(20),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.76 sec)" }, { "code": null, "e": 1734, "s": 1653, "text": "Insert some records in the table using INSERT command. The query is as follows −" }, { "code": null, "e": 3015, "s": 1734, "text": "mysql> insert into Employee_Information(EmployeeName,CityName) values('Larry','New York');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('Sam','Indianapolis');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('Carol','El Paso');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('John','Austin');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('Mike','Denver');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('David','Las Vegas');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('James','Albuquerque');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('Robert','Portland');\nQuery OK, 1 row affected (0.28 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('Richard','Irvine');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into Employee_Information(EmployeeName,CityName) values('Michael',' Garland');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 3100, "s": 3015, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 3142, "s": 3100, "text": "mysql> select *from Employee_Information;" }, { "code": null, "e": 3172, "s": 3142, "text": "The following is the output −" }, { "code": null, "e": 3716, "s": 3172, "text": "+----+--------------+--------------+\n| Id | EmployeeName | CityName |\n+----+--------------+--------------+\n| 1 | Larry | New York |\n| 2 | Sam | Indianapolis |\n| 3 | Carol | El Paso |\n| 4 | John | Austin |\n| 5 | Mike | Denver |\n| 6 | David | Las Vegas |\n| 7 | James | Albuquerque |\n| 8 | Robert | Portland |\n| 9 | Richard | Irvine |\n| 10 | Michael | Garland |\n+----+--------------+--------------+\n10 rows in set (0.00 sec)" }, { "code": null, "e": 3875, "s": 3716, "text": "Here is the query to find a list of city names that do not start with vowel. This means first letter of city name must not start with A,E,I,O,U or a,e,i,o,u −" }, { "code": null, "e": 3984, "s": 3875, "text": "mysql> SELECT DISTINCT CityName FROM Employee_Information\n -> WHERE CityName NOT RLIKE '^[AEIOUaeiou].*$';" }, { "code": null, "e": 4014, "s": 3984, "text": "The following is the output −" }, { "code": null, "e": 4165, "s": 4014, "text": "+-----------+\n| CityName |\n+-----------+\n| New York |\n| Denver |\n| Las Vegas |\n| Portland |\n| Garland |\n+-----------+\n5 rows in set (0.00 sec)" } ]
How To Concatenate Two or More Pandas DataFrames? - GeeksforGeeks
05 Jun, 2021 Let’s understand how we can concatenate two or more Data Frames. A concatenation of two or more data frames can be done using pandas.concat() method. concat() in pandas works by combining Data Frames across rows or columns. We can concat two or more data frames either along rows (axis=0) or along columns (axis=1) Step 1: Import numpy and pandas libraries. Python3 import pandas as pdimport numpy as np Step 2: Create two Data Frames which we will be concatenating now. For creating Data frames we will be using numpy and pandas. Python3 df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)), index=["1", "2", "3", "4"], columns=["A", "B", "C", "D"]) df2 = pd.DataFrame(np.random.randint(25, size=(6, 4)), index=["5", "6", "7", "8", "9", "10"], columns=["A", "B", "C", "D"]) df3 = pd.DataFrame(np.random.randint(25, size=(4, 4)), columns=["A", "B", "C", "D"]) df4 = pd.DataFrame(np.random.randint(25, size=(4, 4)), columns=["E", "F", "G", "H"]) display(df1, df2, df3, df4) Output: Step 3: Now we need to pass the two data frames to the contact() method in the form of a list and mention in which axis you want to concat. Python3 # concatenating df1 and df2 along rowsvertical_concat = pd.concat([df1, df2], axis=0) # concatenating df3 and df4 along columnshorizontal_concat = pd.concat([df3, df4], axis=1) display(vertical_concat, horizontal_concat) Output: anikaseth98 Python pandas-dataFrame Python Pandas-exercise Python-pandas Technical Scripter 2020 Python Technical Scripter 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() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23926, "s": 23898, "text": "\n05 Jun, 2021" }, { "code": null, "e": 24242, "s": 23926, "text": "Let’s understand how we can concatenate two or more Data Frames. A concatenation of two or more data frames can be done using pandas.concat() method. concat() in pandas works by combining Data Frames across rows or columns. We can concat two or more data frames either along rows (axis=0) or along columns (axis=1)" }, { "code": null, "e": 24285, "s": 24242, "text": "Step 1: Import numpy and pandas libraries." }, { "code": null, "e": 24293, "s": 24285, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np", "e": 24331, "s": 24293, "text": null }, { "code": null, "e": 24458, "s": 24331, "text": "Step 2: Create two Data Frames which we will be concatenating now. For creating Data frames we will be using numpy and pandas." }, { "code": null, "e": 24466, "s": 24458, "text": "Python3" }, { "code": "df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)), index=[\"1\", \"2\", \"3\", \"4\"], columns=[\"A\", \"B\", \"C\", \"D\"]) df2 = pd.DataFrame(np.random.randint(25, size=(6, 4)), index=[\"5\", \"6\", \"7\", \"8\", \"9\", \"10\"], columns=[\"A\", \"B\", \"C\", \"D\"]) df3 = pd.DataFrame(np.random.randint(25, size=(4, 4)), columns=[\"A\", \"B\", \"C\", \"D\"]) df4 = pd.DataFrame(np.random.randint(25, size=(4, 4)), columns=[\"E\", \"F\", \"G\", \"H\"]) display(df1, df2, df3, df4)", "e": 25009, "s": 24466, "text": null }, { "code": null, "e": 25021, "s": 25013, "text": "Output:" }, { "code": null, "e": 25165, "s": 25025, "text": "Step 3: Now we need to pass the two data frames to the contact() method in the form of a list and mention in which axis you want to concat." }, { "code": null, "e": 25175, "s": 25167, "text": "Python3" }, { "code": "# concatenating df1 and df2 along rowsvertical_concat = pd.concat([df1, df2], axis=0) # concatenating df3 and df4 along columnshorizontal_concat = pd.concat([df3, df4], axis=1) display(vertical_concat, horizontal_concat)", "e": 25396, "s": 25175, "text": null }, { "code": null, "e": 25408, "s": 25400, "text": "Output:" }, { "code": null, "e": 25424, "s": 25412, "text": "anikaseth98" }, { "code": null, "e": 25448, "s": 25424, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25471, "s": 25448, "text": "Python Pandas-exercise" }, { "code": null, "e": 25485, "s": 25471, "text": "Python-pandas" }, { "code": null, "e": 25509, "s": 25485, "text": "Technical Scripter 2020" }, { "code": null, "e": 25516, "s": 25509, "text": "Python" }, { "code": null, "e": 25535, "s": 25516, "text": "Technical Scripter" }, { "code": null, "e": 25633, "s": 25535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25642, "s": 25633, "text": "Comments" }, { "code": null, "e": 25655, "s": 25642, "text": "Old Comments" }, { "code": null, "e": 25687, "s": 25655, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25743, "s": 25687, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25785, "s": 25743, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25827, "s": 25785, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25863, "s": 25827, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25902, "s": 25863, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25924, "s": 25902, "text": "Defaultdict in Python" }, { "code": null, "e": 25955, "s": 25924, "text": "Python | os.path.join() method" }, { "code": null, "e": 25982, "s": 25955, "text": "Python Classes and Objects" } ]
Prophet vs. NeuralProphet. A side-by-side comparison of the famous... | by Michael Berk | Towards Data Science
Prophet models are effective, interpretable, and easy to use. But which one is better? In this post we will explore the implementation differences of Prophet and Neural Prophet and run a quick case study. Here’s the code. But before we start coding, let’s quickly cover some background information, more of which can be found here. Prophet (2017) is the predecessor to NeuralProphet (2020) — the latter incorporates some autoregressive deep learning. Theoretically, NeuralProphet should always have equal or better performance than Prophet, so today we’re going to put that claim to the test. Let’s dive in. We’re going to be using a daily time series of California’s energy demand (figure 2). As you can see above, there is very strong yearly seasonality with peaks in the summers, probably due to increased air conditioning use. While less apparent from this chart, we’d also expect to see weekly seasonality — our hypothesis is that electricity consumption would differ between the weekend and weekdays. With a traditional time series model like ARIMA, all this seasonality would require us to specify orders (look back indices) that corresponds to whatever level of seasonality we observe. The prophet models, on the other hand, automatically encapsulate this sinusoidal motion with Fourier Series’, so both Prophet models should effectively leverage the above seasonality. Finally, taking one more observation about the data, you’ll notice that the axis names are y and ds. We’ve stored our time series in a pandas DataFrame that’s been restructured to fit Prophet’s specifications. The exact code that was used is the following... df = read_data() # helper funcdf = df[['Local date','D']]df.columns = ['ds','y'] If you want to follow along, the data were downloaded from the source: U.S. Energy Information Administration (December 2021) and are available here as well. Here’s the copyright info. Our metric of interest will be RMSE (figure 3). To fairly compare our two models, we will leverage cross validation (CV). Note that traditional CV assumes that our data are exchangeable i.e. any ordering of our sample is equally likely to occur. With time series data, there’s a temporal component so unfortunately full randomization cannot be applied. Instead, we try many different date cutoffs, training on all prior data and testing with the next n periods. This is called a rolling origin backtest. By iteratively training and determining out-of-sample accuracy, we can derive a more robust estimate of model accuracy. In our case, we start our iterations at 2017–12–22 and, in increments of 180 days, end near 2021–12–06. Our first competitor is Facebook Prophet. It is an open-source algorithm that has seen tremendous popularity since its inception in 2017. It’s main selling points are that it’s easy to use, interpretable, and easily interacts with a subject matter expert. With introductions out of the way, let’s get coding. First we are going to create our model and fit our restructured data. m = Prophet()m.fit(df) Pretty complex, right? Next we’re going to develop a forecast and derive some key plots. # create forecastfuture = m.make_future_dataframe(periods=365)forecast = m.predict(future)# create plotspred_plot = plot_plotly(m, forecast)comp_plot = plot_components_plotly(m, forecast) First, we create a data frame that is 365 periods into the future, in our case, 365 days. We then forecast accordingly and store predicted values along with prediction intervals in the variable, forecast. Finally, we create a prediction plot and component plot. Let’s take a look at each one in turn. First we have our prediction plot in figure 4. As you can see around 2022, our data stop and our forecast begins, as indicated by the lack of observations (black dots). Ok this is a pretty picture, but it doesn’t tell us a ton about what’s going on behind the scenes. For that we’ll turn to a component plot (figure 5). In the above plot, we have three charts, all of which provide useful conclusions about our data. First, we can see that in our top plot, trend is pretty unstable throughout the duration of our data. Starting in the middle of 2017, we saw a decrease in electricity demand, but the overall magnitude of the drop isn’t enormous. Second, according to the second chart, electricity demand is highest during the summer months and lowest in spring. These observations are consistent with our intuitions. Third, it seems that consumption on the weekends is significantly lower than on the week days. Again, this aligns with our expectations. Talk about an interpretable model! Prophet’s component plots are a tremendously useful window into what’s going on behind the scenes — no more black boxes. And note that NeuralProphet has the same functionality. But, a model is only as good as its accuracy, so let’s take a look at accuracy. Using the built in cross validation methods, the RMSE observed for a 365 forecast is 48810.12. Our y value is in the hundreds of thousands, somewhere between 600k and 1.2M, so an RMSE of 48k seems to be pretty low. Let’s see if we can beat this with some deep learning. Our next model is the second iteration of Prophet. It incorporates deep learning terms to our equation which are fit on autoregressed (lagged) data. Theoretically and empirically, NeuralProphet is a superior model. But let’s see if this superiority holds for our energy demand dataset. Let’s get coding. First, as with Prophet, we need to create and fit a model. And note that syntax is very similar between the two iterations of Prophet. m = NeuralProphet()metrics = m.fit(df, freq="D") Now that we’ve created our model, let’s create a forecast and get some key plots. We will be using the default parameters in NeuralProphet, which do not incorporate deep learning. # create forecastdf_future = m.make_future_dataframe(df, periods=365)forecast = m.predict(df_future)# create plotsfig_forecast = m.plot(forecast)fig_components = m.plot_components(forecast)fig_model = m.plot_parameters() As in the values above, let’s take a look at our forecast plot (figure 6). The values shown above are zoomed in much more than the prior forecast, but both have the same structure. Overall, they seem to have nearly identical values as well, which is expected because they’re both using Prophet without deep learning. Finally, the built-in accuracy measure using default parameters for NeuralProphet is an RMSE of 62162.133594. After some digging, it turns out that the two libraries use different backtesting functions, so we will create a custom function that allows for a fair comparison. And, we’ll break out the deep learning. Ok now that we have a feel for both libraries, let’s execute our competition. First, we define our custom rolling backtest function. The key concept is that we create many train/test splits, as shown below. train_test_split_indices = list(range(365*2, len(df.index) - 365, 180))train_test_splits = [(df.iloc[:i, :], df.iloc[i:(i+365), :]) for i in train_test_split_indices] From here, we can iterate over train_test_splits, train both models, and compare the results. With our data set up, we are ready to break out the deep learning in NeuralProphet... neural_params = dict( n_forecasts=365, n_lags=30, yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=True, batch_size=64, epochs=200, learning_rate=0.03) As shown above, we have activated the autoregression functionality through the n_lags parameter. We’ve also added some other potentially useful parameters, such as setting the number of epochs, seasonality types, and the learning rate. And finally, we’ve set our forecasting horizon to be 365 days. After running both models through our rolling origin backtest, we get the following RMSE’s. Note that we also included Mean Absolute Percent Error (MAPE) for interpretation purposes. The results are pretty surprising. When trained on 730 days, NeuralProphet far out-performs Prophet. However, with 910 and 1090 days of training data, NeuralProphet beats Prophet by a slim margin. And finally, with 1270 days or more of training data, Prophet surpasses NeuralProphet in accuracy. Here, NeuralProphet is better on smaller datasets, but Prophet is better with lots of training data. Now we wouldn’t expect this outcome prior to running the models, but retrospectively, this sort of makes sense. One reason deep learning methods are so effective is they can fit extremely complex data. However, if too much noisy data is provided, they can overfit which makes simpler and “smoother” models perform better. One possible explanation is that with enough training data, Prophet is more effective on very cyclical data. If the majority of the motion is sinusoidal due to seasonality (which appears to be the case), it will be hard to improve upon a Fourier-Series-based model. If you’re curious to reproduce the results, check out the code here. Also, if there is incorrect implementation, please leave a comment here or on the repo. Finally, we’re going to end on a fun note. Each day the EIA publishes a day-ahead forecast. Curious to see how our annual models compared, I quickly calculated the RMSE and MAPE for the government’s forecast. The values were 28432.85 and 0.0242 respectively. Comparing these numbers with the numbers in the above table, our Prophet models has roughly double the error, but for a 365 day forecast horizon. The government is looking just one day ahead. A cool and easy follow up would be to try to beat the government using either Prophet model. Shouldn’t be too hard, right? Thanks for reading! I’ll be writing 24 more posts that bring academic research to the DS industry. Check out my comment for links to the main source for this post and some useful resources.
[ { "code": null, "e": 259, "s": 172, "text": "Prophet models are effective, interpretable, and easy to use. But which one is better?" }, { "code": null, "e": 394, "s": 259, "text": "In this post we will explore the implementation differences of Prophet and Neural Prophet and run a quick case study. Here’s the code." }, { "code": null, "e": 504, "s": 394, "text": "But before we start coding, let’s quickly cover some background information, more of which can be found here." }, { "code": null, "e": 765, "s": 504, "text": "Prophet (2017) is the predecessor to NeuralProphet (2020) — the latter incorporates some autoregressive deep learning. Theoretically, NeuralProphet should always have equal or better performance than Prophet, so today we’re going to put that claim to the test." }, { "code": null, "e": 780, "s": 765, "text": "Let’s dive in." }, { "code": null, "e": 866, "s": 780, "text": "We’re going to be using a daily time series of California’s energy demand (figure 2)." }, { "code": null, "e": 1179, "s": 866, "text": "As you can see above, there is very strong yearly seasonality with peaks in the summers, probably due to increased air conditioning use. While less apparent from this chart, we’d also expect to see weekly seasonality — our hypothesis is that electricity consumption would differ between the weekend and weekdays." }, { "code": null, "e": 1550, "s": 1179, "text": "With a traditional time series model like ARIMA, all this seasonality would require us to specify orders (look back indices) that corresponds to whatever level of seasonality we observe. The prophet models, on the other hand, automatically encapsulate this sinusoidal motion with Fourier Series’, so both Prophet models should effectively leverage the above seasonality." }, { "code": null, "e": 1809, "s": 1550, "text": "Finally, taking one more observation about the data, you’ll notice that the axis names are y and ds. We’ve stored our time series in a pandas DataFrame that’s been restructured to fit Prophet’s specifications. The exact code that was used is the following..." }, { "code": null, "e": 1890, "s": 1809, "text": "df = read_data() # helper funcdf = df[['Local date','D']]df.columns = ['ds','y']" }, { "code": null, "e": 2075, "s": 1890, "text": "If you want to follow along, the data were downloaded from the source: U.S. Energy Information Administration (December 2021) and are available here as well. Here’s the copyright info." }, { "code": null, "e": 2123, "s": 2075, "text": "Our metric of interest will be RMSE (figure 3)." }, { "code": null, "e": 2428, "s": 2123, "text": "To fairly compare our two models, we will leverage cross validation (CV). Note that traditional CV assumes that our data are exchangeable i.e. any ordering of our sample is equally likely to occur. With time series data, there’s a temporal component so unfortunately full randomization cannot be applied." }, { "code": null, "e": 2699, "s": 2428, "text": "Instead, we try many different date cutoffs, training on all prior data and testing with the next n periods. This is called a rolling origin backtest. By iteratively training and determining out-of-sample accuracy, we can derive a more robust estimate of model accuracy." }, { "code": null, "e": 2803, "s": 2699, "text": "In our case, we start our iterations at 2017–12–22 and, in increments of 180 days, end near 2021–12–06." }, { "code": null, "e": 3059, "s": 2803, "text": "Our first competitor is Facebook Prophet. It is an open-source algorithm that has seen tremendous popularity since its inception in 2017. It’s main selling points are that it’s easy to use, interpretable, and easily interacts with a subject matter expert." }, { "code": null, "e": 3112, "s": 3059, "text": "With introductions out of the way, let’s get coding." }, { "code": null, "e": 3182, "s": 3112, "text": "First we are going to create our model and fit our restructured data." }, { "code": null, "e": 3205, "s": 3182, "text": "m = Prophet()m.fit(df)" }, { "code": null, "e": 3294, "s": 3205, "text": "Pretty complex, right? Next we’re going to develop a forecast and derive some key plots." }, { "code": null, "e": 3482, "s": 3294, "text": "# create forecastfuture = m.make_future_dataframe(periods=365)forecast = m.predict(future)# create plotspred_plot = plot_plotly(m, forecast)comp_plot = plot_components_plotly(m, forecast)" }, { "code": null, "e": 3783, "s": 3482, "text": "First, we create a data frame that is 365 periods into the future, in our case, 365 days. We then forecast accordingly and store predicted values along with prediction intervals in the variable, forecast. Finally, we create a prediction plot and component plot. Let’s take a look at each one in turn." }, { "code": null, "e": 3830, "s": 3783, "text": "First we have our prediction plot in figure 4." }, { "code": null, "e": 3952, "s": 3830, "text": "As you can see around 2022, our data stop and our forecast begins, as indicated by the lack of observations (black dots)." }, { "code": null, "e": 4103, "s": 3952, "text": "Ok this is a pretty picture, but it doesn’t tell us a ton about what’s going on behind the scenes. For that we’ll turn to a component plot (figure 5)." }, { "code": null, "e": 4737, "s": 4103, "text": "In the above plot, we have three charts, all of which provide useful conclusions about our data. First, we can see that in our top plot, trend is pretty unstable throughout the duration of our data. Starting in the middle of 2017, we saw a decrease in electricity demand, but the overall magnitude of the drop isn’t enormous. Second, according to the second chart, electricity demand is highest during the summer months and lowest in spring. These observations are consistent with our intuitions. Third, it seems that consumption on the weekends is significantly lower than on the week days. Again, this aligns with our expectations." }, { "code": null, "e": 4772, "s": 4737, "text": "Talk about an interpretable model!" }, { "code": null, "e": 4949, "s": 4772, "text": "Prophet’s component plots are a tremendously useful window into what’s going on behind the scenes — no more black boxes. And note that NeuralProphet has the same functionality." }, { "code": null, "e": 5029, "s": 4949, "text": "But, a model is only as good as its accuracy, so let’s take a look at accuracy." }, { "code": null, "e": 5244, "s": 5029, "text": "Using the built in cross validation methods, the RMSE observed for a 365 forecast is 48810.12. Our y value is in the hundreds of thousands, somewhere between 600k and 1.2M, so an RMSE of 48k seems to be pretty low." }, { "code": null, "e": 5299, "s": 5244, "text": "Let’s see if we can beat this with some deep learning." }, { "code": null, "e": 5585, "s": 5299, "text": "Our next model is the second iteration of Prophet. It incorporates deep learning terms to our equation which are fit on autoregressed (lagged) data. Theoretically and empirically, NeuralProphet is a superior model. But let’s see if this superiority holds for our energy demand dataset." }, { "code": null, "e": 5603, "s": 5585, "text": "Let’s get coding." }, { "code": null, "e": 5738, "s": 5603, "text": "First, as with Prophet, we need to create and fit a model. And note that syntax is very similar between the two iterations of Prophet." }, { "code": null, "e": 5787, "s": 5738, "text": "m = NeuralProphet()metrics = m.fit(df, freq=\"D\")" }, { "code": null, "e": 5967, "s": 5787, "text": "Now that we’ve created our model, let’s create a forecast and get some key plots. We will be using the default parameters in NeuralProphet, which do not incorporate deep learning." }, { "code": null, "e": 6188, "s": 5967, "text": "# create forecastdf_future = m.make_future_dataframe(df, periods=365)forecast = m.predict(df_future)# create plotsfig_forecast = m.plot(forecast)fig_components = m.plot_components(forecast)fig_model = m.plot_parameters()" }, { "code": null, "e": 6263, "s": 6188, "text": "As in the values above, let’s take a look at our forecast plot (figure 6)." }, { "code": null, "e": 6505, "s": 6263, "text": "The values shown above are zoomed in much more than the prior forecast, but both have the same structure. Overall, they seem to have nearly identical values as well, which is expected because they’re both using Prophet without deep learning." }, { "code": null, "e": 6819, "s": 6505, "text": "Finally, the built-in accuracy measure using default parameters for NeuralProphet is an RMSE of 62162.133594. After some digging, it turns out that the two libraries use different backtesting functions, so we will create a custom function that allows for a fair comparison. And, we’ll break out the deep learning." }, { "code": null, "e": 6897, "s": 6819, "text": "Ok now that we have a feel for both libraries, let’s execute our competition." }, { "code": null, "e": 7026, "s": 6897, "text": "First, we define our custom rolling backtest function. The key concept is that we create many train/test splits, as shown below." }, { "code": null, "e": 7214, "s": 7026, "text": "train_test_split_indices = list(range(365*2, len(df.index) - 365, 180))train_test_splits = [(df.iloc[:i, :], df.iloc[i:(i+365), :]) for i in train_test_split_indices]" }, { "code": null, "e": 7308, "s": 7214, "text": "From here, we can iterate over train_test_splits, train both models, and compare the results." }, { "code": null, "e": 7394, "s": 7308, "text": "With our data set up, we are ready to break out the deep learning in NeuralProphet..." }, { "code": null, "e": 7590, "s": 7394, "text": "neural_params = dict( n_forecasts=365, n_lags=30, yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=True, batch_size=64, epochs=200, learning_rate=0.03)" }, { "code": null, "e": 7889, "s": 7590, "text": "As shown above, we have activated the autoregression functionality through the n_lags parameter. We’ve also added some other potentially useful parameters, such as setting the number of epochs, seasonality types, and the learning rate. And finally, we’ve set our forecasting horizon to be 365 days." }, { "code": null, "e": 8072, "s": 7889, "text": "After running both models through our rolling origin backtest, we get the following RMSE’s. Note that we also included Mean Absolute Percent Error (MAPE) for interpretation purposes." }, { "code": null, "e": 8107, "s": 8072, "text": "The results are pretty surprising." }, { "code": null, "e": 8368, "s": 8107, "text": "When trained on 730 days, NeuralProphet far out-performs Prophet. However, with 910 and 1090 days of training data, NeuralProphet beats Prophet by a slim margin. And finally, with 1270 days or more of training data, Prophet surpasses NeuralProphet in accuracy." }, { "code": null, "e": 8469, "s": 8368, "text": "Here, NeuralProphet is better on smaller datasets, but Prophet is better with lots of training data." }, { "code": null, "e": 8791, "s": 8469, "text": "Now we wouldn’t expect this outcome prior to running the models, but retrospectively, this sort of makes sense. One reason deep learning methods are so effective is they can fit extremely complex data. However, if too much noisy data is provided, they can overfit which makes simpler and “smoother” models perform better." }, { "code": null, "e": 9057, "s": 8791, "text": "One possible explanation is that with enough training data, Prophet is more effective on very cyclical data. If the majority of the motion is sinusoidal due to seasonality (which appears to be the case), it will be hard to improve upon a Fourier-Series-based model." }, { "code": null, "e": 9214, "s": 9057, "text": "If you’re curious to reproduce the results, check out the code here. Also, if there is incorrect implementation, please leave a comment here or on the repo." }, { "code": null, "e": 9257, "s": 9214, "text": "Finally, we’re going to end on a fun note." }, { "code": null, "e": 9473, "s": 9257, "text": "Each day the EIA publishes a day-ahead forecast. Curious to see how our annual models compared, I quickly calculated the RMSE and MAPE for the government’s forecast. The values were 28432.85 and 0.0242 respectively." }, { "code": null, "e": 9665, "s": 9473, "text": "Comparing these numbers with the numbers in the above table, our Prophet models has roughly double the error, but for a 365 day forecast horizon. The government is looking just one day ahead." }, { "code": null, "e": 9788, "s": 9665, "text": "A cool and easy follow up would be to try to beat the government using either Prophet model. Shouldn’t be too hard, right?" } ]
QlikView - Star Schema
A start schema model is a type of data model in which multiple dimensions are linked to a single fact table. Of course, in bigger models there can be multiple facts tables linked to multiple dimensions and other fact tables. The usefulness of this model lies in performing fast queries with minimal joins among various tables. The fact table contains data, which are measures and have numeric values. Calculations are applied on the fields in the fact table. The unique keys of the dimension tables are used in linking it to the fat table, which also has a key usually with the same field name. Therefore, the Fact table contains the keys from the entire dimension table and forms a concatenated primary key used in various queries. Given below is a list of tables, which contain the data for different products from various suppliers and regions. Also the supply happens at different time intervals, which are captured in the Time dimension table. It contains the Product Category and Product Names. The Product ID field is the unique Key. ProductID,ProductCategory,ProductName 1,Outdoor Recreation,Winter Sports & Activities 2,Clothing,Uniforms 3,Lawn & Garden Power, Equipment 4,Athletics,Rugby 5,Personal Care,Shaver 6,Arts & Entertainment,Crafting Materials 7,Hardware,Power Tool Batteries It contains the Region Names where the suppliers are based. The RegionID field is the unique Key. RegionID,Continent,Country 3,North America, USA 7,South America, Brazil 12,Asia,China 2,Asia,Japan 5,Europe,Belgium It contains the Supplier Names, which supply the above products. The SupplierID field is the unique Key. SupplierID,SupplierName 3S12,Supre Suppliers 4A15,ABC Suppliers 4S66,Max Sports 5F244,Nice Foods 8A45,Artistic angle It contains the Time periods when the supply of the above products occur. The TimeID field is the unique Key. TimeID,Year,Month 1,2012,Feb 2,2012,May 3,2012,Sep 4,2013,Aug 5,2014,Jan 6,2014,Nov It contains the values for the quantities supplied and percentage of defects in them. It joins to each of the above dimensions through keys with same name. ProductID,RegionID,TimeID,SupplierID,Quantity, DefectPercentage 1,3,3,5F244,8452,12 2,3,1,4S66,5124,8.25 3,7,1,8A45,5841,7.66 4,12,2,4A15,5123,1.25 5,5,3,4S66,7452,8.11 6,2,5,4A15,5142,3.66 7,2,1,4S66,452,2.06 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory. Below is the script which appears after each of the above file is read. LOAD ProductID, ProductCategory, ProductName FROM [C:\Qlikview\images\StarSchema\Product_dimension.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD TimeID, Year, Month FROM [C:\Qlikview\images\StarSchema\Time.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD SupplierID, SupplierName FROM [C:\Qlikview\images\StarSchema\Suppliers.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD RegionID, Continent, Country FROM [C:\Qlikview\images\StarSchema\Regions.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD ProductID, RegionID, TimeID, SupplierID, Quantity, DefectPercentage FROM [C:\Qlikview\images\StarSchema\Supplier_quantity.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); After reading the above data into QlikView memory, we can look at the data model, which shows all the tables, fields, and relationship in form of a star schema. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3653, "s": 2920, "text": "A start schema model is a type of data model in which multiple dimensions are linked to a single fact table. Of course, in bigger models there can be multiple facts tables linked to multiple dimensions and other fact tables. The usefulness of this model lies in performing fast queries with minimal joins among various tables. The fact table contains data, which are measures and have numeric values. Calculations are applied on the fields in the fact table. The unique keys of the dimension tables are used in linking it to the fat table, which also has a key usually with the same field name. Therefore, the Fact table contains the keys from the entire dimension table and forms a concatenated primary key used in various queries." }, { "code": null, "e": 3869, "s": 3653, "text": "Given below is a list of tables, which contain the data for different products from various suppliers and regions. Also the supply happens at different time intervals, which are captured in the Time dimension table." }, { "code": null, "e": 3961, "s": 3869, "text": "It contains the Product Category and Product Names. The Product ID field is the unique Key." }, { "code": null, "e": 4216, "s": 3961, "text": "ProductID,ProductCategory,ProductName\n1,Outdoor Recreation,Winter Sports & Activities\n2,Clothing,Uniforms\n3,Lawn & Garden\tPower, Equipment\n4,Athletics,Rugby\n5,Personal Care,Shaver\n6,Arts & Entertainment,Crafting Materials\n7,Hardware,Power Tool Batteries\n" }, { "code": null, "e": 4314, "s": 4216, "text": "It contains the Region Names where the suppliers are based. The RegionID field is the unique Key." }, { "code": null, "e": 4431, "s": 4314, "text": "RegionID,Continent,Country\n3,North America, USA\n7,South America, Brazil\n12,Asia,China\n2,Asia,Japan\n5,Europe,Belgium\n" }, { "code": null, "e": 4536, "s": 4431, "text": "It contains the Supplier Names, which supply the above products. The SupplierID field is the unique Key." }, { "code": null, "e": 4654, "s": 4536, "text": "SupplierID,SupplierName\n3S12,Supre Suppliers\n4A15,ABC Suppliers\n4S66,Max Sports\n5F244,Nice Foods\n8A45,Artistic angle\n" }, { "code": null, "e": 4764, "s": 4654, "text": "It contains the Time periods when the supply of the above products occur. The TimeID field is the unique Key." }, { "code": null, "e": 4849, "s": 4764, "text": "TimeID,Year,Month\n1,2012,Feb\n2,2012,May\n3,2012,Sep\n4,2013,Aug\n5,2014,Jan\n6,2014,Nov\n" }, { "code": null, "e": 5005, "s": 4849, "text": "It contains the values for the quantities supplied and percentage of defects in them. It joins to each of the above dimensions through keys with same name." }, { "code": null, "e": 5216, "s": 5005, "text": "ProductID,RegionID,TimeID,SupplierID,Quantity, DefectPercentage\n1,3,3,5F244,8452,12\n2,3,1,4S66,5124,8.25\n3,7,1,8A45,5841,7.66\n4,12,2,4A15,5123,1.25\n5,5,3,4S66,7452,8.11\n6,2,5,4A15,5142,3.66\n7,2,1,4S66,452,2.06\n" }, { "code": null, "e": 5602, "s": 5216, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory. Below is the script which appears after each of the above file is read." }, { "code": null, "e": 6474, "s": 5602, "text": "LOAD ProductID, \n ProductCategory, \n ProductName\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Product_dimension.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD TimeID, \n Year, \n Month\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Time.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD SupplierID, \n SupplierName\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Suppliers.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD RegionID, \n Continent, \n Country\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Regions.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD ProductID, \n RegionID, \n TimeID, \n SupplierID, \n Quantity, \n DefectPercentage\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Supplier_quantity.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 6635, "s": 6474, "text": "After reading the above data into QlikView memory, we can look at the data model, which shows all the tables, fields, and relationship in form of a star schema." }, { "code": null, "e": 6668, "s": 6635, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 6681, "s": 6668, "text": " Arthur Fong" }, { "code": null, "e": 6688, "s": 6681, "text": " Print" }, { "code": null, "e": 6699, "s": 6688, "text": " Add Notes" } ]
Override date filter in Power BI. Overriding standard date filtering in... | by Nikola Ilic | Towards Data Science
Recently, a friend of mine came across with an interesting request he got from his client. They needed to see values for the specified period in the past, based on dates selection. For example, if they select March 31st, 2020, they need to see values for the previous 12 months, so starting from April 1st, 2019. Additionally, they need an option to choose a specific date and see values from the beginning of the year for the selected date. Again, if they select March 31st, 2020, they need to see values starting from January 1st, 2020. Visuals would be adjusted to dynamically change based on user selection. That being said, Edit Interactions, as a way to remove the filter from specific visual, was not an option, since it would completely deny a user from selecting any specific value for filtering. The trickiest thing here is establishing a proper relationship between the Date dimension and the fact table. Because, if you rely on the “normal” relationship between the Date dimension and fact table, data will be filtered based on dates selection which serves as a relationship between these two tables. Let’s head over to Power BI Desktop and see if something can be done. As you see in the Model view above, DimDate and FactOnlineSales are connected with the DateKey column. So, as long as I’m selecting dates in the slicer, my bar chart shows only those values filtered by slicer selection, as you see in the following screenshot. The main question here is: how can we “override” values passed from Date slicer. The key thing here is to disconnect the “regular” relationship between the Date dimension and the fact table. We need an independent, disconnected Dates table, which will serve to define the time frame we need for displaying values in bar chart visual. Therefore, I will create a new table with the following definition: Dates = DISTINCT(FactOnlineSales[DateKey]) This will include all the dates from our fact table. This table stays disconnected from our fact table, as you can see in the Model view: Now, let’s create a new measure, which will calculate sales amount within dates we specify: Sales Amt = VAR MaxDate = MAX(Dates[DatesDateKey]) VAR MinDate = CALCULATE(MIN(Dates[DatesDateKey]), ALLEXCEPT(Dates,Dates[DatesDateKey]) ) VAR SalesAmt = CALCULATE(SUM(FactOnlineSales[SalesAmount]), FILTER(FactOnlineSales,FactOnlineSales[DateKey] >= MinDate && FactOnlineSales[DateKey] <= MaxDate)) RETURN SalesAmt What we are basically doing here is the following: we are defining a variable that will select the last selected date (MaxDate). Then, we are defining our starting point: in this case, it will find the first date in the Dates table, overriding the existing filter context with ALLEXCEPT function. Finally, we are calculating SalesAmt value using the FILTER function, in order to limit the time frame based on dates set in variables. After we drag the new measure to the bar chart visual, we are getting the following result: So, if I select quarter 4 of the 2008 year, I will see all values from the beginning (first date value in our fact table), up until the selected period. If I had selected quarter 3 of 2009, I would have got the following values: Pretty cool, ha? However, what if we need to see only those values since the beginning of the year for the date selected, or 12 months prior to the selected date. The disconnected table stays in place, because, don’t forget, it is the key ingredient to solve this. We will just slightly change our measure for calculating Sales Amt. If you want to see all values from the beginning of the year, you can adjust measure like this: Sales Amt StartYear = VAR MaxDate = MAX('Dates'[DatesDateKey]) VAR MinDate = STARTOFYEAR('Dates'[DatesDateKey]) VAR Result = CALCULATE( SUM(FactOnlineSales[SalesAmount]), FILTER(FactOnlineSales, FactOnlineSales[DateKey] >=MinDate && FactOnlineSales[DateKey]<=MaxDate) ) RETURN Result So, the only difference is in the MinDate variable definition. Here, we use DAX function STARTOFYEAR to get the first date of the year for the date which was selected. Another option enables you to see trailing periods you define based on your needs: following example shows the last 12 months, but you can easily modify this: Sales Amt -12 Months = VAR MaxDate = MAX('Dates'[DatesDateKey]) VAR MinDate = DATE(YEAR(MaxDate),MONTH(MaxDate)-12,DAY(MaxDate)) VAR Result = CALCULATE( SUM(FactOnlineSales[SalesAmount]), FILTER(FactOnlineSales, FactOnlineSales[DateKey] >=MinDate && FactOnlineSales[DateKey]<=MaxDate) ) RETURN Result Again, the only difference is in the starting point definition. With a combination of DATE and MONTH functions, we are telling our measure how far in the past we want to calculate. In this case, it’s -12 months, but you can also use years, quarters, days as criteria. As you saw, we can override the regular behavior of filters using some non-standard techniques, like creating custom disconnected tables. Thanks for reading! Become a member and read every story on Medium!
[ { "code": null, "e": 352, "s": 171, "text": "Recently, a friend of mine came across with an interesting request he got from his client. They needed to see values for the specified period in the past, based on dates selection." }, { "code": null, "e": 783, "s": 352, "text": "For example, if they select March 31st, 2020, they need to see values for the previous 12 months, so starting from April 1st, 2019. Additionally, they need an option to choose a specific date and see values from the beginning of the year for the selected date. Again, if they select March 31st, 2020, they need to see values starting from January 1st, 2020. Visuals would be adjusted to dynamically change based on user selection." }, { "code": null, "e": 977, "s": 783, "text": "That being said, Edit Interactions, as a way to remove the filter from specific visual, was not an option, since it would completely deny a user from selecting any specific value for filtering." }, { "code": null, "e": 1284, "s": 977, "text": "The trickiest thing here is establishing a proper relationship between the Date dimension and the fact table. Because, if you rely on the “normal” relationship between the Date dimension and fact table, data will be filtered based on dates selection which serves as a relationship between these two tables." }, { "code": null, "e": 1354, "s": 1284, "text": "Let’s head over to Power BI Desktop and see if something can be done." }, { "code": null, "e": 1614, "s": 1354, "text": "As you see in the Model view above, DimDate and FactOnlineSales are connected with the DateKey column. So, as long as I’m selecting dates in the slicer, my bar chart shows only those values filtered by slicer selection, as you see in the following screenshot." }, { "code": null, "e": 1695, "s": 1614, "text": "The main question here is: how can we “override” values passed from Date slicer." }, { "code": null, "e": 1948, "s": 1695, "text": "The key thing here is to disconnect the “regular” relationship between the Date dimension and the fact table. We need an independent, disconnected Dates table, which will serve to define the time frame we need for displaying values in bar chart visual." }, { "code": null, "e": 2016, "s": 1948, "text": "Therefore, I will create a new table with the following definition:" }, { "code": null, "e": 2059, "s": 2016, "text": "Dates = DISTINCT(FactOnlineSales[DateKey])" }, { "code": null, "e": 2197, "s": 2059, "text": "This will include all the dates from our fact table. This table stays disconnected from our fact table, as you can see in the Model view:" }, { "code": null, "e": 2289, "s": 2197, "text": "Now, let’s create a new measure, which will calculate sales amount within dates we specify:" }, { "code": null, "e": 2746, "s": 2289, "text": "Sales Amt = VAR MaxDate = MAX(Dates[DatesDateKey]) VAR MinDate = CALCULATE(MIN(Dates[DatesDateKey]), ALLEXCEPT(Dates,Dates[DatesDateKey]) ) VAR SalesAmt = CALCULATE(SUM(FactOnlineSales[SalesAmount]), FILTER(FactOnlineSales,FactOnlineSales[DateKey] >= MinDate && FactOnlineSales[DateKey] <= MaxDate)) RETURN SalesAmt" }, { "code": null, "e": 3271, "s": 2746, "text": "What we are basically doing here is the following: we are defining a variable that will select the last selected date (MaxDate). Then, we are defining our starting point: in this case, it will find the first date in the Dates table, overriding the existing filter context with ALLEXCEPT function. Finally, we are calculating SalesAmt value using the FILTER function, in order to limit the time frame based on dates set in variables. After we drag the new measure to the bar chart visual, we are getting the following result:" }, { "code": null, "e": 3500, "s": 3271, "text": "So, if I select quarter 4 of the 2008 year, I will see all values from the beginning (first date value in our fact table), up until the selected period. If I had selected quarter 3 of 2009, I would have got the following values:" }, { "code": null, "e": 3517, "s": 3500, "text": "Pretty cool, ha?" }, { "code": null, "e": 3663, "s": 3517, "text": "However, what if we need to see only those values since the beginning of the year for the date selected, or 12 months prior to the selected date." }, { "code": null, "e": 3833, "s": 3663, "text": "The disconnected table stays in place, because, don’t forget, it is the key ingredient to solve this. We will just slightly change our measure for calculating Sales Amt." }, { "code": null, "e": 3929, "s": 3833, "text": "If you want to see all values from the beginning of the year, you can adjust measure like this:" }, { "code": null, "e": 4341, "s": 3929, "text": "Sales Amt StartYear = VAR MaxDate = MAX('Dates'[DatesDateKey]) VAR MinDate = STARTOFYEAR('Dates'[DatesDateKey]) VAR Result = CALCULATE( SUM(FactOnlineSales[SalesAmount]), FILTER(FactOnlineSales, FactOnlineSales[DateKey] >=MinDate && FactOnlineSales[DateKey]<=MaxDate) ) RETURN Result" }, { "code": null, "e": 4509, "s": 4341, "text": "So, the only difference is in the MinDate variable definition. Here, we use DAX function STARTOFYEAR to get the first date of the year for the date which was selected." }, { "code": null, "e": 4668, "s": 4509, "text": "Another option enables you to see trailing periods you define based on your needs: following example shows the last 12 months, but you can easily modify this:" }, { "code": null, "e": 5097, "s": 4668, "text": "Sales Amt -12 Months = VAR MaxDate = MAX('Dates'[DatesDateKey]) VAR MinDate = DATE(YEAR(MaxDate),MONTH(MaxDate)-12,DAY(MaxDate)) VAR Result = CALCULATE( SUM(FactOnlineSales[SalesAmount]), FILTER(FactOnlineSales, FactOnlineSales[DateKey] >=MinDate && FactOnlineSales[DateKey]<=MaxDate) ) RETURN Result" }, { "code": null, "e": 5365, "s": 5097, "text": "Again, the only difference is in the starting point definition. With a combination of DATE and MONTH functions, we are telling our measure how far in the past we want to calculate. In this case, it’s -12 months, but you can also use years, quarters, days as criteria." }, { "code": null, "e": 5503, "s": 5365, "text": "As you saw, we can override the regular behavior of filters using some non-standard techniques, like creating custom disconnected tables." }, { "code": null, "e": 5523, "s": 5503, "text": "Thanks for reading!" } ]
HTML | colspan Attribute - GeeksforGeeks
13 Dec, 2021 The colspan attribute in HTML specifies the number of columns a cell should span. It allows the single table cell to span the width of more than one cell or column. It provides the same functionality as “merge cell” in a spreadsheet program like Excel.Usage: It can be used with <td> and <th> element while creating an HTML Table. Attribute Values: It contains a value i.e number Which specify the number of columns that a cell should span. Note: colspan=”0′′ tells the browser to span the cell to the last column of the column group (colgroup). <td>: The colspan attribute when used with <td> tag determines the number of standard cells it should span. Syntax: <td colspan = "value">table content...</td> The value specifies the number of columns that the cell fills. The value must be an integer. Example: html <!DOCTYPE html><html> <head> <title>HTML colspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; text-align:center; } </style></head> <body> <center> <h1 style="color: green;">GeeksforGeeks</h1> <h2>HTML colspan Attribute</h2> <table> <tr> <th>Name</th> <th>Expense</th> </tr> <tr> <td>Arun</td> <td>$10</td> </tr> <tr> <td>Priya</td> <td>$8</td> </tr> <!-- The last row --> <tr> <!-- This td will span two columns, that is a single column will take up the space of 2 --> <td colspan="2">Sum: $18</td> </tr> </table> </center></body> </html> Output: <th>: The colspan attribute when used with <th> tag determines the number of header cells it should span. Syntax: <th colspan = "value">table content...</th> The value specifies the number of columns that the cell fills. The value must be a integer. Example: html <!DOCTYPE html><html> <head> <title>HTML colspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; text-align: center; } </style></head> <body> <center> <h1 style="color: green;">GeeksforGeeks</h1> <h2>HTML colspan Attribute</h2> <table> <tr> <th colspan="2">Expense</th> </tr> <tr> <td>Arun</td> <td>$10</td> </tr> <tr> <td>Priya</td> <td>$8</td> </tr> </table> </center></body> </html> Output: Supported Browsers: The browser supported by colspan attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24932, "s": 24904, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25264, "s": 24932, "text": "The colspan attribute in HTML specifies the number of columns a cell should span. It allows the single table cell to span the width of more than one cell or column. It provides the same functionality as “merge cell” in a spreadsheet program like Excel.Usage: It can be used with <td> and <th> element while creating an HTML Table. " }, { "code": null, "e": 25375, "s": 25264, "text": "Attribute Values: It contains a value i.e number Which specify the number of columns that a cell should span. " }, { "code": null, "e": 25481, "s": 25375, "text": "Note: colspan=”0′′ tells the browser to span the cell to the last column of the column group (colgroup). " }, { "code": null, "e": 25597, "s": 25481, "text": "<td>: The colspan attribute when used with <td> tag determines the number of standard cells it should span. Syntax:" }, { "code": null, "e": 25641, "s": 25597, "text": "<td colspan = \"value\">table content...</td>" }, { "code": null, "e": 25745, "s": 25641, "text": "The value specifies the number of columns that the cell fills. The value must be an integer. Example: " }, { "code": null, "e": 25750, "s": 25745, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML colspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; text-align:center; } </style></head> <body> <center> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h2>HTML colspan Attribute</h2> <table> <tr> <th>Name</th> <th>Expense</th> </tr> <tr> <td>Arun</td> <td>$10</td> </tr> <tr> <td>Priya</td> <td>$8</td> </tr> <!-- The last row --> <tr> <!-- This td will span two columns, that is a single column will take up the space of 2 --> <td colspan=\"2\">Sum: $18</td> </tr> </table> </center></body> </html> ", "e": 26710, "s": 25750, "text": null }, { "code": null, "e": 26720, "s": 26710, "text": "Output: " }, { "code": null, "e": 26834, "s": 26720, "text": "<th>: The colspan attribute when used with <th> tag determines the number of header cells it should span. Syntax:" }, { "code": null, "e": 26878, "s": 26834, "text": "<th colspan = \"value\">table content...</th>" }, { "code": null, "e": 26980, "s": 26878, "text": "The value specifies the number of columns that the cell fills. The value must be a integer. Example: " }, { "code": null, "e": 26985, "s": 26980, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML colspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; text-align: center; } </style></head> <body> <center> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h2>HTML colspan Attribute</h2> <table> <tr> <th colspan=\"2\">Expense</th> </tr> <tr> <td>Arun</td> <td>$10</td> </tr> <tr> <td>Priya</td> <td>$8</td> </tr> </table> </center></body> </html> ", "e": 27694, "s": 26985, "text": null }, { "code": null, "e": 27703, "s": 27694, "text": "Output: " }, { "code": null, "e": 27786, "s": 27703, "text": "Supported Browsers: The browser supported by colspan attribute are listed below: " }, { "code": null, "e": 27800, "s": 27786, "text": "Google Chrome" }, { "code": null, "e": 27818, "s": 27800, "text": "Internet Explorer" }, { "code": null, "e": 27826, "s": 27818, "text": "Firefox" }, { "code": null, "e": 27832, "s": 27826, "text": "Opera" }, { "code": null, "e": 27839, "s": 27832, "text": "Safari" }, { "code": null, "e": 28035, "s": 27841, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 28172, "s": 28035, "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": 28192, "s": 28172, "text": "hritikbhatnagar2182" }, { "code": null, "e": 28206, "s": 28192, "text": "ManasChhabra2" }, { "code": null, "e": 28222, "s": 28206, "text": "HTML-Attributes" }, { "code": null, "e": 28227, "s": 28222, "text": "HTML" }, { "code": null, "e": 28244, "s": 28227, "text": "Web Technologies" }, { "code": null, "e": 28249, "s": 28244, "text": "HTML" }, { "code": null, "e": 28347, "s": 28249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28397, "s": 28347, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28459, "s": 28397, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28507, "s": 28459, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28567, "s": 28507, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28620, "s": 28567, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28660, "s": 28620, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28693, "s": 28660, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28738, "s": 28693, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28781, "s": 28738, "text": "How to fetch data from an API in ReactJS ?" } ]
Why does canvas.toDataURL() throws a security exception? - GeeksforGeeks
02 Jun, 2020 Canvas.toDataURL(): The canvas.toDataURL() method returns the URI(Uniform Resource Identifier) of the web resource. It consists of an image depicted in the format specified by the type parameter whose default value is PNG. Syntax: Canvas.toDataURL(type, encoderOptions); type: It is an optional attribute that contains DOMString commenting about the image format. Its default value is PNG. encoderOptions : It consists of a numeric value between 0 and 1 used to indicate the quality of the image to be used for the various image formats. Its default value is 0.92. Security Exceptions: The security exceptions are thrown if the canvas element is not origin clean i.e. if its origin-clean flag is not set. (False). In other words, if the canvas element consists of foreign content then the security is on stake and SECURITY_ERR exception occurs. The moment the canvas is used for drawing data not following the rules related to the origin and without using the CORS (Cross-origin resource sharing) mechanism, it becomes tainted. Tainted canvas is not considered secure. Trials to retrieve image data from the canvas will lead to failure indicated by security exceptions. Along with toDataURL(), calling methods such as toBlob() and getImageData() will also lead to similar kinds of errors. These exceptions are used to safeguard the users from getting their private data being exposed without their prior permission. Since images can be used to capture information from websites, the use of exceptions is a must. Example: Canvas element producing the exception. Javascript function getBase64FromImageUrl(URL) { var img = new Image(); img.src = URL; img.onload = function () { var canvas = document.createElement("canvas"); canvas.width = this.width; canvas.height = this.height; var ctx = canvas.getContext("2d"); ctx.drawImage(this, 0, 0); var dataURL = canvas.toDataURL("image/png"); alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, "")); };} Output: These kinds of security errors occur when a trial is made to manipulate an image on canvas that is not authorized to be handled in the code. These errors are caused by the Access-Control-Allow-Origin header of a request, which the server has approved. Since the image belongs to another domain, most browsers show abnormalities in accessing them leading to a major security breach. Uncaught Security Error: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: tainted canvases may not be exported. Solution for the above problem: An image has an attribute known as crossorigin which is specified in HTML and by combining it with a suitable CORS header, it can be loaded from foreign origins to be used in the canvas behaving like belonging to the current origin. If The CORS approval is not taken, the canvas turns tainted, and there is no provision left to pull back data out of the canvas. Therefore methods like toBlob(), toDataURL(), or getImageData() cannot be used without throwing security errors. These errors can be prevented by setting the crossorigin attribute of the image using Javascript or HTML Example: HTML: <img src="otherdomain.com"/> JavaScript: var image = new Image(); image.crossOrigin = "Anonymous"; ... Note: this approach can work only when the server response has the following Access-Control-Allow-Origin header on it. Otherwise, the image from origin ‘otherdomain.com’ will get blocked from being loaded by the Cross-Origin Resource Sharing policy. Since the problem is that image does not belong to the current domain, a proxy with the server language can be created similar to displaying HTTP contents on HTTPS contents providing it a secure environment. HTML-Misc JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26655, "s": 26627, "text": "\n02 Jun, 2020" }, { "code": null, "e": 26879, "s": 26655, "text": "Canvas.toDataURL(): The canvas.toDataURL() method returns the URI(Uniform Resource Identifier) of the web resource. It consists of an image depicted in the format specified by the type parameter whose default value is PNG. " }, { "code": null, "e": 26888, "s": 26879, "text": "Syntax: " }, { "code": null, "e": 26929, "s": 26888, "text": "Canvas.toDataURL(type, encoderOptions);\n" }, { "code": null, "e": 27050, "s": 26929, "text": "type: It is an optional attribute that contains DOMString commenting about the image format. Its default value is PNG. " }, { "code": null, "e": 27227, "s": 27050, "text": "encoderOptions : It consists of a numeric value between 0 and 1 used to indicate the quality of the image to be used for the various image formats. Its default value is 0.92. " }, { "code": null, "e": 28176, "s": 27227, "text": "Security Exceptions: The security exceptions are thrown if the canvas element is not origin clean i.e. if its origin-clean flag is not set. (False). In other words, if the canvas element consists of foreign content then the security is on stake and SECURITY_ERR exception occurs. The moment the canvas is used for drawing data not following the rules related to the origin and without using the CORS (Cross-origin resource sharing) mechanism, it becomes tainted. Tainted canvas is not considered secure. Trials to retrieve image data from the canvas will lead to failure indicated by security exceptions. Along with toDataURL(), calling methods such as toBlob() and getImageData() will also lead to similar kinds of errors. These exceptions are used to safeguard the users from getting their private data being exposed without their prior permission. Since images can be used to capture information from websites, the use of exceptions is a must. " }, { "code": null, "e": 28225, "s": 28176, "text": "Example: Canvas element producing the exception." }, { "code": null, "e": 28236, "s": 28225, "text": "Javascript" }, { "code": "function getBase64FromImageUrl(URL) { var img = new Image(); img.src = URL; img.onload = function () { var canvas = document.createElement(\"canvas\"); canvas.width = this.width; canvas.height = this.height; var ctx = canvas.getContext(\"2d\"); ctx.drawImage(this, 0, 0); var dataURL = canvas.toDataURL(\"image/png\"); alert(dataURL.replace(/^data:image\\/(png|jpg);base64,/, \"\")); };}", "e": 28687, "s": 28236, "text": null }, { "code": null, "e": 29078, "s": 28687, "text": "Output: These kinds of security errors occur when a trial is made to manipulate an image on canvas that is not authorized to be handled in the code. These errors are caused by the Access-Control-Allow-Origin header of a request, which the server has approved. Since the image belongs to another domain, most browsers show abnormalities in accessing them leading to a major security breach. " }, { "code": null, "e": 29197, "s": 29078, "text": "Uncaught Security Error: Failed to execute ‘toDataURL’ on \n‘HTMLCanvasElement’: tainted canvases may not be exported.\n" }, { "code": null, "e": 29811, "s": 29197, "text": "Solution for the above problem: An image has an attribute known as crossorigin which is specified in HTML and by combining it with a suitable CORS header, it can be loaded from foreign origins to be used in the canvas behaving like belonging to the current origin. If The CORS approval is not taken, the canvas turns tainted, and there is no provision left to pull back data out of the canvas. Therefore methods like toBlob(), toDataURL(), or getImageData() cannot be used without throwing security errors. These errors can be prevented by setting the crossorigin attribute of the image using Javascript or HTML " }, { "code": null, "e": 29821, "s": 29811, "text": "Example: " }, { "code": null, "e": 29827, "s": 29821, "text": "HTML:" }, { "code": null, "e": 29857, "s": 29827, "text": "<img src=\"otherdomain.com\"/>\n" }, { "code": null, "e": 29870, "s": 29857, "text": "JavaScript: " }, { "code": null, "e": 29939, "s": 29870, "text": " var image = new Image();\n image.crossOrigin = \"Anonymous\";\n ...\n" }, { "code": null, "e": 30190, "s": 29939, "text": "Note: this approach can work only when the server response has the following Access-Control-Allow-Origin header on it. Otherwise, the image from origin ‘otherdomain.com’ will get blocked from being loaded by the Cross-Origin Resource Sharing policy. " }, { "code": null, "e": 30400, "s": 30190, "text": "Since the problem is that image does not belong to the current domain, a proxy with the server language can be created similar to displaying HTTP contents on HTTPS contents providing it a secure environment. " }, { "code": null, "e": 30410, "s": 30400, "text": "HTML-Misc" }, { "code": null, "e": 30426, "s": 30410, "text": "JavaScript-Misc" }, { "code": null, "e": 30433, "s": 30426, "text": "Picked" }, { "code": null, "e": 30444, "s": 30433, "text": "JavaScript" }, { "code": null, "e": 30461, "s": 30444, "text": "Web Technologies" }, { "code": null, "e": 30559, "s": 30461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30599, "s": 30559, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30660, "s": 30599, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30701, "s": 30660, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30723, "s": 30701, "text": "JavaScript | Promises" }, { "code": null, "e": 30771, "s": 30723, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30811, "s": 30771, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30844, "s": 30811, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30887, "s": 30844, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30937, "s": 30887, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Hive - Drop Table
This chapter describes how to drop a table in Hive. When you drop a table from Hive Metastore, it removes the table/column data and their metadata. It can be a normal table (stored in Metastore) or an external table (stored in local file system); Hive treats both in the same manner, irrespective of their types. The syntax is as follows: DROP TABLE [IF EXISTS] table_name; The following query drops a table named employee: hive> DROP TABLE IF EXISTS employee; On successful execution of the query, you get to see the following response: OK Time taken: 5.3 seconds hive> The following JDBC program drops the employee table. import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveDropTable { private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver"; public static void main(String[] args) throws SQLException { // Register driver and create driver instance Class.forName(driverName); // get connection Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", ""); // create statement Statement stmt = con.createStatement(); // execute statement stmt.executeQuery("DROP TABLE IF EXISTS employee;"); System.out.println("Drop table successful."); con.close(); } } Save the program in a file named HiveDropTable.java. Use the following commands to compile and execute this program. $ javac HiveDropTable.java $ java HiveDropTable Drop table successful The following query is used to verify the list of tables: hive> SHOW TABLES; emp ok Time taken: 2.1 seconds hive> 50 Lectures 4 hours Navdeep Kaur 67 Lectures 4 hours Bigdata Engineer 109 Lectures 2 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2263, "s": 1950, "text": "This chapter describes how to drop a table in Hive. When you drop a table from Hive Metastore, it removes the table/column data and their metadata. It can be a normal table (stored in Metastore) or an external table (stored in local file system); Hive treats both in the same manner, irrespective of their types." }, { "code": null, "e": 2289, "s": 2263, "text": "The syntax is as follows:" }, { "code": null, "e": 2324, "s": 2289, "text": "DROP TABLE [IF EXISTS] table_name;" }, { "code": null, "e": 2374, "s": 2324, "text": "The following query drops a table named employee:" }, { "code": null, "e": 2411, "s": 2374, "text": "hive> DROP TABLE IF EXISTS employee;" }, { "code": null, "e": 2488, "s": 2411, "text": "On successful execution of the query, you get to see the following response:" }, { "code": null, "e": 2521, "s": 2488, "text": "OK\nTime taken: 5.3 seconds\nhive>" }, { "code": null, "e": 2574, "s": 2521, "text": "The following JDBC program drops the employee table." }, { "code": null, "e": 3353, "s": 2574, "text": "import java.sql.SQLException;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.sql.DriverManager;\n\npublic class HiveDropTable {\n\n private static String driverName = \"org.apache.hadoop.hive.jdbc.HiveDriver\";\n \n public static void main(String[] args) throws SQLException {\n \n // Register driver and create driver instance\n Class.forName(driverName);\n\n // get connection\n Connection con = DriverManager.getConnection(\"jdbc:hive://localhost:10000/userdb\", \"\", \"\");\n\n // create statement\n Statement stmt = con.createStatement();\n\n // execute statement\n stmt.executeQuery(\"DROP TABLE IF EXISTS employee;\");\n System.out.println(\"Drop table successful.\");\n \n con.close();\n }\n}" }, { "code": null, "e": 3470, "s": 3353, "text": "Save the program in a file named HiveDropTable.java. Use the following commands to compile and execute this program." }, { "code": null, "e": 3518, "s": 3470, "text": "$ javac HiveDropTable.java\n$ java HiveDropTable" }, { "code": null, "e": 3541, "s": 3518, "text": "Drop table successful\n" }, { "code": null, "e": 3599, "s": 3541, "text": "The following query is used to verify the list of tables:" }, { "code": null, "e": 3655, "s": 3599, "text": "hive> SHOW TABLES;\nemp\nok\nTime taken: 2.1 seconds\nhive>" }, { "code": null, "e": 3688, "s": 3655, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 3702, "s": 3688, "text": " Navdeep Kaur" }, { "code": null, "e": 3735, "s": 3702, "text": "\n 67 Lectures \n 4 hours \n" }, { "code": null, "e": 3753, "s": 3735, "text": " Bigdata Engineer" }, { "code": null, "e": 3787, "s": 3753, "text": "\n 109 Lectures \n 2 hours \n" }, { "code": null, "e": 3805, "s": 3787, "text": " Bigdata Engineer" }, { "code": null, "e": 3812, "s": 3805, "text": " Print" }, { "code": null, "e": 3823, "s": 3812, "text": " Add Notes" } ]
What is the lifetime of JavaScript variables?
The lifetime of a JavaScript variable begins when it is declared − var rank; A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.The completion of a function deletes the local variable. A global variable has a global scope which means it can be defined anywhere in your JavaScript code. Global variables delete when the web browser is closed. However if a new page is loaded in the same browser window, then it remains. Here’s the usage of global variables − You can try to run the following code to learn how to work with a scope of variables in JavaScript Live Demo <html> <body onload = checkscope();> <script> <!-- var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); } //--> </script> </body> </html>
[ { "code": null, "e": 1129, "s": 1062, "text": "The lifetime of a JavaScript variable begins when it is declared −" }, { "code": null, "e": 1139, "s": 1129, "text": "var rank;" }, { "code": null, "e": 1327, "s": 1139, "text": "A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.The completion of a function deletes the local variable." }, { "code": null, "e": 1561, "s": 1327, "text": "A global variable has a global scope which means it can be defined anywhere in your JavaScript code. Global variables delete when the web browser is closed. However if a new page is loaded in the same browser window, then it remains." }, { "code": null, "e": 1600, "s": 1561, "text": "Here’s the usage of global variables −" }, { "code": null, "e": 1699, "s": 1600, "text": "You can try to run the following code to learn how to work with a scope of variables in JavaScript" }, { "code": null, "e": 1709, "s": 1699, "text": "Live Demo" }, { "code": null, "e": 2031, "s": 1709, "text": "<html>\n <body onload = checkscope();>\n <script>\n <!--\n var myVar = \"global\"; // Declare a global variable\n function checkscope( ) {\n var myVar = \"local\"; // Declare a local variable\n document.write(myVar);\n }\n //-->\n </script>\n </body>\n</html>" } ]
Difference between alert box and prompt box in JavaScript - GeeksforGeeks
19 Apr, 2022 1. Alert box : An alert box is one type of popup boxes in JavaScript which is often used to make sure that information have come through the user. So, the user will have to click “OK” to proceed when an alert box pops up on the window. Syntax : window.alert("message"); Another syntax to use alert box is : alert("message"); 2. Prompt box : It is also one of the type of popup boxes in JavaScript which is often to take input a value before entering a page from the user. To proceed after entering an input value in the prompt, the user will have to click either “OK” or “Cancel”. Syntax : window.prompt("some message"); Another syntax to use alert box is : prompt("some message"); Below example illustrates the differences between alert box and prompt box : Example : HTML <!DOCTYPE HTML><html> <head> <title> Alert Box vs Prompt Box </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <button onclick="alertBox()"> Show Alert Box </button> <button onclick="promptBox()"> Show Prompt Box </button> <script> function alertBox(){ alert("GeeksforGeeks: This" + " is an Alert Box."); } function promptBox(){ prompt("Enter your Name:"); } </script></body> </html> Output: Before clicking the button : After clicking the Show Alert Box button : After clicking the Show Prompt Box button : Supported Browsers: The list of browser supported by prompt() and alert() box are listed below : Google Chrome Internet Explorer Firefox Opera Safari Let us see the differences in a tabular form -: Its syntax is -: window.alert(“sometext”); Its syntax is -: window.prompt(“sometext”,”defaultText”); Difference Between JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Internal and External fragmentation Difference between Prim's and Kruskal's algorithm for MST Differences and Applications of List, Tuple, Set and Dictionary in Python Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript File uploading in React.js
[ { "code": null, "e": 24778, "s": 24750, "text": "\n19 Apr, 2022" }, { "code": null, "e": 25015, "s": 24778, "text": "1. Alert box : An alert box is one type of popup boxes in JavaScript which is often used to make sure that information have come through the user. So, the user will have to click “OK” to proceed when an alert box pops up on the window. " }, { "code": null, "e": 25024, "s": 25015, "text": "Syntax :" }, { "code": null, "e": 25049, "s": 25024, "text": "window.alert(\"message\");" }, { "code": null, "e": 25086, "s": 25049, "text": "Another syntax to use alert box is :" }, { "code": null, "e": 25104, "s": 25086, "text": "alert(\"message\");" }, { "code": null, "e": 25361, "s": 25104, "text": "2. Prompt box : It is also one of the type of popup boxes in JavaScript which is often to take input a value before entering a page from the user. To proceed after entering an input value in the prompt, the user will have to click either “OK” or “Cancel”. " }, { "code": null, "e": 25370, "s": 25361, "text": "Syntax :" }, { "code": null, "e": 25401, "s": 25370, "text": "window.prompt(\"some message\");" }, { "code": null, "e": 25438, "s": 25401, "text": "Another syntax to use alert box is :" }, { "code": null, "e": 25462, "s": 25438, "text": "prompt(\"some message\");" }, { "code": null, "e": 25550, "s": 25462, "text": "Below example illustrates the differences between alert box and prompt box : Example : " }, { "code": null, "e": 25555, "s": 25550, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Alert Box vs Prompt Box </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <button onclick=\"alertBox()\"> Show Alert Box </button> <button onclick=\"promptBox()\"> Show Prompt Box </button> <script> function alertBox(){ alert(\"GeeksforGeeks: This\" + \" is an Alert Box.\"); } function promptBox(){ prompt(\"Enter your Name:\"); } </script></body> </html> ", "e": 26154, "s": 25555, "text": null }, { "code": null, "e": 26163, "s": 26154, "text": "Output: " }, { "code": null, "e": 26192, "s": 26163, "text": "Before clicking the button :" }, { "code": null, "e": 26238, "s": 26195, "text": "After clicking the Show Alert Box button :" }, { "code": null, "e": 26286, "s": 26241, "text": "After clicking the Show Prompt Box button : " }, { "code": null, "e": 26385, "s": 26288, "text": "Supported Browsers: The list of browser supported by prompt() and alert() box are listed below :" }, { "code": null, "e": 26399, "s": 26385, "text": "Google Chrome" }, { "code": null, "e": 26417, "s": 26399, "text": "Internet Explorer" }, { "code": null, "e": 26425, "s": 26417, "text": "Firefox" }, { "code": null, "e": 26431, "s": 26425, "text": "Opera" }, { "code": null, "e": 26438, "s": 26431, "text": "Safari" }, { "code": null, "e": 26487, "s": 26438, "text": "Let us see the differences in a tabular form -: " }, { "code": null, "e": 26504, "s": 26487, "text": "Its syntax is -:" }, { "code": null, "e": 26530, "s": 26504, "text": "window.alert(“sometext”);" }, { "code": null, "e": 26547, "s": 26530, "text": "Its syntax is -:" }, { "code": null, "e": 26588, "s": 26547, "text": "window.prompt(“sometext”,”defaultText”);" }, { "code": null, "e": 26607, "s": 26588, "text": "Difference Between" }, { "code": null, "e": 26618, "s": 26607, "text": "JavaScript" }, { "code": null, "e": 26716, "s": 26618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26725, "s": 26716, "text": "Comments" }, { "code": null, "e": 26738, "s": 26725, "text": "Old Comments" }, { "code": null, "e": 26799, "s": 26738, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26867, "s": 26799, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 26922, "s": 26867, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 26980, "s": 26922, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27054, "s": 26980, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 27115, "s": 27054, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27184, "s": 27115, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 27256, "s": 27184, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27301, "s": 27256, "text": "Convert a string to an integer in JavaScript" } ]
Python program to convert XML to Dictionary
14 Sep, 2021 In this article, we will discuss how to convert an XML to a dictionary using Python. xmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module. Syntax: pip install xmltodict pprint: The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way. Import necessary module to working space. Open the XML File in Read-only mode and read the contents using file.read() and store it in a variable. Syntax: with open('filename', 'r', encoding='utf-8') as file: my_xml = file.read() Use xmltodict.parse() to parse the content from the variable and convert it into Dictionary. Syntax : xmltodict.parse(xml_input, encoding=’utf-8′, expat=expat, process_namespaces=False, namespace_separator=’:’, **kwargs) Use pprint(pretty print) to print the dictionary in well-formatted and readable way. Syntax : pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) Example: Converting XML to dictionary File Used: Python3 # Import the required modulesimport xmltodictimport pprint # Open the file and read the contentswith open('example.xml', 'r', encoding='utf-8') as file: my_xml = file.read() # Use xmltodict to parse and convert # the XML documentmy_dict = xmltodict.parse(my_xml) # Print the dictionarypprint.pprint(my_dict, indent=2) Output: Example 2: Converting XML to dictionary File Used: Python3 # Import the required modulesimport xmltodictimport pprint # Open the file and read the contentswith open('example_2.xml', 'r', encoding='utf-8') as file: my_xml = file.read() # Use xmltodict to parse and convert the # XML documentmy_dict = xmltodict.parse(my_xml) # Print the dictionarypprint.pprint(my_dict, indent=2) Output: Blogathon-2021 Picked Python-XML Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 113, "s": 28, "text": "In this article, we will discuss how to convert an XML to a dictionary using Python." }, { "code": null, "e": 278, "s": 113, "text": "xmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module." }, { "code": null, "e": 286, "s": 278, "text": "Syntax:" }, { "code": null, "e": 308, "s": 286, "text": "pip install xmltodict" }, { "code": null, "e": 450, "s": 308, "text": "pprint: The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way." }, { "code": null, "e": 492, "s": 450, "text": "Import necessary module to working space." }, { "code": null, "e": 596, "s": 492, "text": "Open the XML File in Read-only mode and read the contents using file.read() and store it in a variable." }, { "code": null, "e": 604, "s": 596, "text": "Syntax:" }, { "code": null, "e": 683, "s": 604, "text": "with open('filename', 'r', encoding='utf-8') as file:\n my_xml = file.read()" }, { "code": null, "e": 776, "s": 683, "text": "Use xmltodict.parse() to parse the content from the variable and convert it into Dictionary." }, { "code": null, "e": 786, "s": 776, "text": "Syntax : " }, { "code": null, "e": 906, "s": 786, "text": "xmltodict.parse(xml_input, encoding=’utf-8′, expat=expat, process_namespaces=False, namespace_separator=’:’, **kwargs) " }, { "code": null, "e": 991, "s": 906, "text": "Use pprint(pretty print) to print the dictionary in well-formatted and readable way." }, { "code": null, "e": 1001, "s": 991, "text": "Syntax : " }, { "code": null, "e": 1103, "s": 1001, "text": "pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)" }, { "code": null, "e": 1141, "s": 1103, "text": "Example: Converting XML to dictionary" }, { "code": null, "e": 1152, "s": 1141, "text": "File Used:" }, { "code": null, "e": 1160, "s": 1152, "text": "Python3" }, { "code": "# Import the required modulesimport xmltodictimport pprint # Open the file and read the contentswith open('example.xml', 'r', encoding='utf-8') as file: my_xml = file.read() # Use xmltodict to parse and convert # the XML documentmy_dict = xmltodict.parse(my_xml) # Print the dictionarypprint.pprint(my_dict, indent=2)", "e": 1484, "s": 1160, "text": null }, { "code": null, "e": 1492, "s": 1484, "text": "Output:" }, { "code": null, "e": 1532, "s": 1492, "text": "Example 2: Converting XML to dictionary" }, { "code": null, "e": 1543, "s": 1532, "text": "File Used:" }, { "code": null, "e": 1551, "s": 1543, "text": "Python3" }, { "code": "# Import the required modulesimport xmltodictimport pprint # Open the file and read the contentswith open('example_2.xml', 'r', encoding='utf-8') as file: my_xml = file.read() # Use xmltodict to parse and convert the # XML documentmy_dict = xmltodict.parse(my_xml) # Print the dictionarypprint.pprint(my_dict, indent=2)", "e": 1877, "s": 1551, "text": null }, { "code": null, "e": 1885, "s": 1877, "text": "Output:" }, { "code": null, "e": 1900, "s": 1885, "text": "Blogathon-2021" }, { "code": null, "e": 1907, "s": 1900, "text": "Picked" }, { "code": null, "e": 1918, "s": 1907, "text": "Python-XML" }, { "code": null, "e": 1928, "s": 1918, "text": "Blogathon" }, { "code": null, "e": 1935, "s": 1928, "text": "Python" } ]
C program to Compare Two Strings without using strcmp() function
06 Sep, 2021 Given two strings s1 and s2, the task is to write C program compare the two strings without using strcmp() function. If string are equal then print “Equal strings” else print “Unequal strings”. Examples: Input: s1 = “geeksforgeeks”, s2 = “geeks”Output: Unequal Strings Input: s1 = “geeksforgeeks”, s2 = “geeksforgeeks”Output: Equal Strings Approach: There are three possible cases occur when we compare two strings: Both the strings are the same means difference of ASCII value between both the strings is 0.Both the strings are different means ASCII value of first not matching character in the first string is less than the second string then the difference between both the strings is (<0).Both the strings are different means ASCII value of first not matching character in the first string is greater than the second string then the difference between both the strings is (>0). Both the strings are the same means difference of ASCII value between both the strings is 0. Both the strings are different means ASCII value of first not matching character in the first string is less than the second string then the difference between both the strings is (<0). Both the strings are different means ASCII value of first not matching character in the first string is greater than the second string then the difference between both the strings is (>0). Based on the above three conditions, the idea is to compare each character of the given strings one by one whenever condition 2 or 3 occurs then print “Unequal strings” else print “Equal strings”. Below is the implementation of the above approach: C // C program to compare the two strings// without using strcmp() function#include <stdio.h> // Function that compares the two stringvoid compareStrings(char* x, char* y){ int flag = 0; // Iterate a loop till the end // of both the strings while (*x != '\0' || *y != '\0') { if (*x == *y) { x++; y++; } // If two characters are not same // print the difference and exit else if ((*x == '\0' && *y != '\0') || (*x != '\0' && *y == '\0') || *x != *y) { flag = 1; printf("Unequal Strings\n"); break; } } // If two strings are exactly same if (flag == 0) { printf("Equal Strings\n"); }} // Driver Codeint main(void){ // Given strings s1 and s2 char s1[20] = "python"; char s2[20] = "dsa"; // Function Call compareStrings(s1, s2); return 0;} Unequal Strings Time Complexity: O(N)Auxiliary Space: O(1) varshagumber28 C Programs Greedy Mathematical School Programming Strings Strings Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Sep, 2021" }, { "code": null, "e": 246, "s": 52, "text": "Given two strings s1 and s2, the task is to write C program compare the two strings without using strcmp() function. If string are equal then print “Equal strings” else print “Unequal strings”." }, { "code": null, "e": 256, "s": 246, "text": "Examples:" }, { "code": null, "e": 321, "s": 256, "text": "Input: s1 = “geeksforgeeks”, s2 = “geeks”Output: Unequal Strings" }, { "code": null, "e": 392, "s": 321, "text": "Input: s1 = “geeksforgeeks”, s2 = “geeksforgeeks”Output: Equal Strings" }, { "code": null, "e": 468, "s": 392, "text": "Approach: There are three possible cases occur when we compare two strings:" }, { "code": null, "e": 934, "s": 468, "text": "Both the strings are the same means difference of ASCII value between both the strings is 0.Both the strings are different means ASCII value of first not matching character in the first string is less than the second string then the difference between both the strings is (<0).Both the strings are different means ASCII value of first not matching character in the first string is greater than the second string then the difference between both the strings is (>0)." }, { "code": null, "e": 1027, "s": 934, "text": "Both the strings are the same means difference of ASCII value between both the strings is 0." }, { "code": null, "e": 1213, "s": 1027, "text": "Both the strings are different means ASCII value of first not matching character in the first string is less than the second string then the difference between both the strings is (<0)." }, { "code": null, "e": 1402, "s": 1213, "text": "Both the strings are different means ASCII value of first not matching character in the first string is greater than the second string then the difference between both the strings is (>0)." }, { "code": null, "e": 1599, "s": 1402, "text": "Based on the above three conditions, the idea is to compare each character of the given strings one by one whenever condition 2 or 3 occurs then print “Unequal strings” else print “Equal strings”." }, { "code": null, "e": 1650, "s": 1599, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1652, "s": 1650, "text": "C" }, { "code": "// C program to compare the two strings// without using strcmp() function#include <stdio.h> // Function that compares the two stringvoid compareStrings(char* x, char* y){ int flag = 0; // Iterate a loop till the end // of both the strings while (*x != '\\0' || *y != '\\0') { if (*x == *y) { x++; y++; } // If two characters are not same // print the difference and exit else if ((*x == '\\0' && *y != '\\0') || (*x != '\\0' && *y == '\\0') || *x != *y) { flag = 1; printf(\"Unequal Strings\\n\"); break; } } // If two strings are exactly same if (flag == 0) { printf(\"Equal Strings\\n\"); }} // Driver Codeint main(void){ // Given strings s1 and s2 char s1[20] = \"python\"; char s2[20] = \"dsa\"; // Function Call compareStrings(s1, s2); return 0;}", "e": 2570, "s": 1652, "text": null }, { "code": null, "e": 2586, "s": 2570, "text": "Unequal Strings" }, { "code": null, "e": 2629, "s": 2586, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 2644, "s": 2629, "text": "varshagumber28" }, { "code": null, "e": 2655, "s": 2644, "text": "C Programs" }, { "code": null, "e": 2662, "s": 2655, "text": "Greedy" }, { "code": null, "e": 2675, "s": 2662, "text": "Mathematical" }, { "code": null, "e": 2694, "s": 2675, "text": "School Programming" }, { "code": null, "e": 2702, "s": 2694, "text": "Strings" }, { "code": null, "e": 2710, "s": 2702, "text": "Strings" }, { "code": null, "e": 2717, "s": 2710, "text": "Greedy" }, { "code": null, "e": 2730, "s": 2717, "text": "Mathematical" } ]
Python | Pandas Series.get_values()
13 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.get_values() function return an ndarray containing the underlying data of the given series object. Syntax: Series.get_values() Parameter : None Returns : ndarray Example #1: Use Series.get_values() function to return an array containing the underlying data of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.get_values() function to return the underlying data of the given series object as an array. # return an arrayresult = sr.get_values() # Print the resultprint(result) Output : As we can see in the output, the Series.get_values() function has returned the given series object as an array. Example #2 : Use Series.get_values() function to return an array containing the underlying data of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.get_values() function to return the underlying data of the given series object as an array. # return an arrayresult = sr.get_values() # Print the resultprint(result) Output :As we can see in the output, the Series.get_values() function has returned the given series object as an array. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 398, "s": 285, "text": "Pandas Series.get_values() function return an ndarray containing the underlying data of the given series object." }, { "code": null, "e": 426, "s": 398, "text": "Syntax: Series.get_values()" }, { "code": null, "e": 443, "s": 426, "text": "Parameter : None" }, { "code": null, "e": 461, "s": 443, "text": "Returns : ndarray" }, { "code": null, "e": 584, "s": 461, "text": "Example #1: Use Series.get_values() function to return an array containing the underlying data of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 840, "s": 584, "text": null }, { "code": null, "e": 849, "s": 840, "text": "Output :" }, { "code": null, "e": 964, "s": 849, "text": "Now we will use Series.get_values() function to return the underlying data of the given series object as an array." }, { "code": "# return an arrayresult = sr.get_values() # Print the resultprint(result)", "e": 1039, "s": 964, "text": null }, { "code": null, "e": 1048, "s": 1039, "text": "Output :" }, { "code": null, "e": 1284, "s": 1048, "text": "As we can see in the output, the Series.get_values() function has returned the given series object as an array. Example #2 : Use Series.get_values() function to return an array containing the underlying data of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1553, "s": 1284, "text": null }, { "code": null, "e": 1562, "s": 1553, "text": "Output :" }, { "code": null, "e": 1677, "s": 1562, "text": "Now we will use Series.get_values() function to return the underlying data of the given series object as an array." }, { "code": "# return an arrayresult = sr.get_values() # Print the resultprint(result)", "e": 1752, "s": 1677, "text": null }, { "code": null, "e": 1872, "s": 1752, "text": "Output :As we can see in the output, the Series.get_values() function has returned the given series object as an array." }, { "code": null, "e": 1893, "s": 1872, "text": "Python pandas-series" }, { "code": null, "e": 1922, "s": 1893, "text": "Python pandas-series-methods" }, { "code": null, "e": 1936, "s": 1922, "text": "Python-pandas" }, { "code": null, "e": 1943, "s": 1936, "text": "Python" } ]
Sum of bit differences | Practice | GeeksforGeeks
Given an integer array of N integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y. For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 (first and last bits differ in two numbers). Note: (x, y) and (y, x) are considered two separate pairs. Example 1: Input: N = 2 arr[] = {1, 2} Output: 4 Explanation: All pairs in array are (1, 1) (1, 2), 2, 1), (2, 2) Sum of bit differences = 0 + 2 + 2 + 0 = 4 Example 2: Input: N = 3 arr[] = {1, 3, 5} Output: 8 Explanation: All pairs in array are (1, 1), (1, 3), (1, 5), (3, 1), (3, 3) (3, 5),(5, 1), (5, 3), (5, 5) Sum of bit differences = 0 + 1 + 1 + 1 + 0 + 2 + 1 + 2 + 0 = 8 Your Task: You don't need to read input or print anything. Your task is to complete the function sumBitDifferences() which takes the array arr[] and n as inputs and returns an integer denoting the answer. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 105 1 <= arr[i] <= 105 0 guptatushar110412 weeks ago C++ solution:- long long sumBitDifferences(int arr[], int n) { // code here long long ans=0; for(int i=0;i<31;i++) { long long count=0; for(int j=0;j<n;j++) { if(arr[j] & (1<<i)) count++; } ans=(ans+count*(n-count)*2); } return ans; } 0 keshavkumarshivanshu31 month ago idea is very simple. for each position of every number check count of ones and zeros. so total ones*zeros combination of pair is possible so that it has difference. at last return double of answer because you have consider (a,b) and (b,a) differently long long sumBitDifferences(int arr[], int n) { long long ans = 0; for(int i=0;i<32;i++){ long long ones = 0; for(int j=0;j<n;j++){ if(arr[j]&(1<<i)) ones++; } ans += (ones)*(n-ones); } return 2*ans; } 0 tiwariravikant20012 months ago long long sumBitDifferences(int a[], int n) { long long int mask,i,k,unset,set=0,diff,res; long long int ans=0; for(i=0;i<32;i++) { mask=1<<i; for(k=0;k<n;k++) { res=a[k]&mask; if(res!=0) ++set; } unset=n-set; diff=2*unset*set; ans=(ans+diff); set=0; } return ans;} 0 kake13375 months ago int m=log2(*max_element(arr,arr+n)); vector<int> b(m+1,0); for(int i=0;i<n;i++) { for(int j=0;j<=m;j++) { int x=(1<<j); if((arr[i]&x)==x) b[j]++; } } long long r=0; for(int i=0;i<n;i++) { int x=1; for(int j=0;j<=m;j++) { if((arr[i]&x)==x) r+=(n-1)-(b[j]-1); else r+=b[j]; x*=2; } } return r; 0 chessnoobdj7 months ago C++ long long sumBitDifferences(int arr[], int n) { long long int ans = 0; for(int j=0; j<32; j++){ int cnt = 0; for(int i=0; i<n; i++) cnt += 1&(arr[i]>>j); ans += (cnt)*(n-cnt); } return 2*ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 610, "s": 238, "text": "Given an integer array of N integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y.\nFor example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 (first and last bits differ in two numbers)." }, { "code": null, "e": 669, "s": 610, "text": "Note: (x, y) and (y, x) are considered two separate pairs." }, { "code": null, "e": 680, "s": 669, "text": "Example 1:" }, { "code": null, "e": 850, "s": 680, "text": "Input: \nN = 2\narr[] = {1, 2}\nOutput: 4\nExplanation: All pairs in array are (1, 1)\n(1, 2), 2, 1), (2, 2)\nSum of bit differences = 0 + 2 + 2 + 0\n = 4" }, { "code": null, "e": 861, "s": 850, "text": "Example 2:" }, { "code": null, "e": 1149, "s": 861, "text": "Input:\nN = 3 \narr[] = {1, 3, 5}\nOutput: 8\nExplanation: \nAll pairs in array are (1, 1), (1, 3),\n(1, 5), (3, 1), (3, 3) (3, 5),(5, 1),\n(5, 3), (5, 5)\nSum of bit differences = 0 + 1 + 1 +\n 1 + 0 + 2 +\n 1 + 2 + 0 \n = 8" }, { "code": null, "e": 1466, "s": 1149, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function sumBitDifferences() which takes the array arr[] and n as inputs and returns an integer denoting the answer.\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= N <= 105\n1 <= arr[i] <= 105" }, { "code": null, "e": 1470, "s": 1468, "text": "0" }, { "code": null, "e": 1498, "s": 1470, "text": "guptatushar110412 weeks ago" }, { "code": null, "e": 1513, "s": 1498, "text": "C++ solution:-" }, { "code": null, "e": 1860, "s": 1513, "text": "long long sumBitDifferences(int arr[], int n) {\n\t // code here\n\t \n\t long long ans=0;\n\t for(int i=0;i<31;i++)\n\t {\n\t long long count=0;\n\t for(int j=0;j<n;j++)\n\t {\n\t if(arr[j] & (1<<i))\n\t \n\t count++;\n\t }\n\t ans=(ans+count*(n-count)*2);\n\t }\n\t return ans;\n\t}" }, { "code": null, "e": 1862, "s": 1860, "text": "0" }, { "code": null, "e": 1895, "s": 1862, "text": "keshavkumarshivanshu31 month ago" }, { "code": null, "e": 2062, "s": 1895, "text": "idea is very simple. for each position of every number check count of ones and zeros. so total ones*zeros combination of pair is possible so that it has difference. " }, { "code": null, "e": 2150, "s": 2064, "text": "at last return double of answer because you have consider (a,b) and (b,a) differently" }, { "code": null, "e": 2425, "s": 2152, "text": "\tlong long sumBitDifferences(int arr[], int n) {\n\t long long ans = 0;\n\t for(int i=0;i<32;i++){\n\t long long ones = 0;\n\t for(int j=0;j<n;j++){\n\t if(arr[j]&(1<<i)) ones++;\n\t }\n\t ans += (ones)*(n-ones);\n\t }\n\t return 2*ans;\n\t}" }, { "code": null, "e": 2427, "s": 2425, "text": "0" }, { "code": null, "e": 2458, "s": 2427, "text": "tiwariravikant20012 months ago" }, { "code": null, "e": 2880, "s": 2458, "text": " long long sumBitDifferences(int a[], int n) { long long int mask,i,k,unset,set=0,diff,res; long long int ans=0; for(i=0;i<32;i++) { mask=1<<i; for(k=0;k<n;k++) { res=a[k]&mask; if(res!=0) ++set; } unset=n-set; diff=2*unset*set; ans=(ans+diff); set=0; } return ans;}" }, { "code": null, "e": 2882, "s": 2880, "text": "0" }, { "code": null, "e": 2903, "s": 2882, "text": "kake13375 months ago" }, { "code": null, "e": 3387, "s": 2903, "text": " int m=log2(*max_element(arr,arr+n));\n vector<int> b(m+1,0);\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<=m;j++)\n {\n int x=(1<<j);\n if((arr[i]&x)==x)\n b[j]++;\n }\n }\n long long r=0;\n for(int i=0;i<n;i++)\n {\n int x=1;\n for(int j=0;j<=m;j++)\n {\n if((arr[i]&x)==x)\n r+=(n-1)-(b[j]-1);\n else\n r+=b[j];\n x*=2;\n }\n }\n return r;" }, { "code": null, "e": 3389, "s": 3387, "text": "0" }, { "code": null, "e": 3413, "s": 3389, "text": "chessnoobdj7 months ago" }, { "code": null, "e": 3417, "s": 3413, "text": "C++" }, { "code": null, "e": 3672, "s": 3417, "text": "long long sumBitDifferences(int arr[], int n) {\n\t long long int ans = 0;\n\t for(int j=0; j<32; j++){\n\t int cnt = 0;\n\t for(int i=0; i<n; i++)\n\t cnt += 1&(arr[i]>>j);\n\t ans += (cnt)*(n-cnt);\n\t }\n\t return 2*ans;\n\t}" }, { "code": null, "e": 3818, "s": 3672, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3854, "s": 3818, "text": " Login to access your submissions. " }, { "code": null, "e": 3864, "s": 3854, "text": "\nProblem\n" }, { "code": null, "e": 3874, "s": 3864, "text": "\nContest\n" }, { "code": null, "e": 3937, "s": 3874, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4122, "s": 3937, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4406, "s": 4122, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 4552, "s": 4406, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 4629, "s": 4552, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 4670, "s": 4629, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 4698, "s": 4670, "text": "Disable browser extensions." }, { "code": null, "e": 4769, "s": 4698, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 4956, "s": 4769, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to transform Vector into String?
06 Jul, 2017 Vectors: Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. C++ program to transform vector into string.String: C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string. std::ostringstream: It is an Output stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str. // C++ program transform a vector into// a string.#include <vector>#include <string>#include <algorithm>#include <sstream>#include <iterator>#include <iostream> int main(){ std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); vec.push_back(6); std::ostringstream vts; if (!vec.empty()) { // Convert all but the last element to avoid a trailing "," std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<int>(vts, ", ")); // Now add the last element with no delimiter vts << vec.back(); } std::cout << vts.str() << std::endl;} Output: 1, 2, 3, 4, 5, 6 This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-algorithm-library cpp-strings-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2017" }, { "code": null, "e": 429, "s": 54, "text": "Vectors: Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. C++ program to transform vector into string.String: C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string." }, { "code": null, "e": 674, "s": 429, "text": "std::ostringstream: It is an Output stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str." }, { "code": "// C++ program transform a vector into// a string.#include <vector>#include <string>#include <algorithm>#include <sstream>#include <iterator>#include <iostream> int main(){ std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); vec.push_back(6); std::ostringstream vts; if (!vec.empty()) { // Convert all but the last element to avoid a trailing \",\" std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<int>(vts, \", \")); // Now add the last element with no delimiter vts << vec.back(); } std::cout << vts.str() << std::endl;}", "e": 1302, "s": 674, "text": null }, { "code": null, "e": 1310, "s": 1302, "text": "Output:" }, { "code": null, "e": 1328, "s": 1310, "text": "1, 2, 3, 4, 5, 6\n" }, { "code": null, "e": 1627, "s": 1328, "text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1752, "s": 1627, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1774, "s": 1752, "text": "cpp-algorithm-library" }, { "code": null, "e": 1794, "s": 1774, "text": "cpp-strings-library" }, { "code": null, "e": 1798, "s": 1794, "text": "STL" }, { "code": null, "e": 1802, "s": 1798, "text": "C++" }, { "code": null, "e": 1806, "s": 1802, "text": "STL" }, { "code": null, "e": 1810, "s": 1806, "text": "CPP" } ]
C# | Predicate Delegate
04 Apr, 2019 A Predicate delegate is an in-built generic type delegate. This delegate is defined under System namespace. It works with those methods which contain some set of criteria and determine whether the passed parameter fulfill the given criteria or not. This delegate takes only one input and returns the value in the form of true or false. Now, first of all, we see how custom delegates work in this situation. As shown in the below example. Syntax: public delegate bool Predicate <in P>(P obj); Here, P is the type of the object and obj is the object which is going to compare against the criteria defined within the method represented by Predicate delegate. Example: // C# program to illustrate delegatesusing System; class GFG { // Declaring the delegate public delegate bool my_delegate(string mystring); // Method public static bool myfun(string mystring) { if (mystring.Length < 7) { return true; } else { return false; } } // Main method static public void Main() { // Creating object of my_delegate my_delegate obj = myfun; Console.WriteLine(obj("Hello")); }} True Now, we use the same above program with Predicate delegate as shown below. Example: In the below example, we use a predicate delegate instead of a custom delegate. It reduces the size of the code and makes the program more readable. Here, the Predicate delegate contains a single input parameter and return output in boolean type. And here, we directly assign a myfun method to the Predicate delegate. // C# program to illustrate Predicate delegatesusing System; class GFG { // Method public static bool myfun(string mystring) { if (mystring.Length < 7) { return true; } else { return false; } } // Main method static public void Main() { // Using predicate delegate // here, this delegate takes // only one parameter Predicate<string> val = myfun; Console.WriteLine(val("GeeksforGeeks")); }} False Important Points: You can also use a Predicate delegate with an anonymous method as shown in the below example:Example:Predicate<string> val = delegate(string str){ if (mystring.Length < 7) { return true; } else { return false; }; val("Geeks"); Example: Predicate<string> val = delegate(string str){ if (mystring.Length < 7) { return true; } else { return false; }; val("Geeks"); You can also use a Predicate delegate with the lambda expressions as shown in the below example:Example:Predicate<string> val = str = > str.Equals(str.ToLower());val("Geeks"); Example: Predicate<string> val = str = > str.Equals(str.ToLower());val("Geeks"); CSharp-Delegates C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object C# | Constructors C# | Arrays C# | Encapsulation C# | Replace() Method Difference between Ref and Out keywords in C#
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Apr, 2019" }, { "code": null, "e": 492, "s": 54, "text": "A Predicate delegate is an in-built generic type delegate. This delegate is defined under System namespace. It works with those methods which contain some set of criteria and determine whether the passed parameter fulfill the given criteria or not. This delegate takes only one input and returns the value in the form of true or false. Now, first of all, we see how custom delegates work in this situation. As shown in the below example." }, { "code": null, "e": 500, "s": 492, "text": "Syntax:" }, { "code": null, "e": 546, "s": 500, "text": "public delegate bool Predicate <in P>(P obj);" }, { "code": null, "e": 710, "s": 546, "text": "Here, P is the type of the object and obj is the object which is going to compare against the criteria defined within the method represented by Predicate delegate." }, { "code": null, "e": 719, "s": 710, "text": "Example:" }, { "code": "// C# program to illustrate delegatesusing System; class GFG { // Declaring the delegate public delegate bool my_delegate(string mystring); // Method public static bool myfun(string mystring) { if (mystring.Length < 7) { return true; } else { return false; } } // Main method static public void Main() { // Creating object of my_delegate my_delegate obj = myfun; Console.WriteLine(obj(\"Hello\")); }}", "e": 1245, "s": 719, "text": null }, { "code": null, "e": 1251, "s": 1245, "text": "True\n" }, { "code": null, "e": 1326, "s": 1251, "text": "Now, we use the same above program with Predicate delegate as shown below." }, { "code": null, "e": 1653, "s": 1326, "text": "Example: In the below example, we use a predicate delegate instead of a custom delegate. It reduces the size of the code and makes the program more readable. Here, the Predicate delegate contains a single input parameter and return output in boolean type. And here, we directly assign a myfun method to the Predicate delegate." }, { "code": "// C# program to illustrate Predicate delegatesusing System; class GFG { // Method public static bool myfun(string mystring) { if (mystring.Length < 7) { return true; } else { return false; } } // Main method static public void Main() { // Using predicate delegate // here, this delegate takes // only one parameter Predicate<string> val = myfun; Console.WriteLine(val(\"GeeksforGeeks\")); }}", "e": 2175, "s": 1653, "text": null }, { "code": null, "e": 2182, "s": 2175, "text": "False\n" }, { "code": null, "e": 2200, "s": 2182, "text": "Important Points:" }, { "code": null, "e": 2463, "s": 2200, "text": "You can also use a Predicate delegate with an anonymous method as shown in the below example:Example:Predicate<string> val = delegate(string str){ if (mystring.Length < 7) { return true; } else { return false; }; val(\"Geeks\");" }, { "code": null, "e": 2472, "s": 2463, "text": "Example:" }, { "code": "Predicate<string> val = delegate(string str){ if (mystring.Length < 7) { return true; } else { return false; }; val(\"Geeks\");", "e": 2634, "s": 2472, "text": null }, { "code": null, "e": 2810, "s": 2634, "text": "You can also use a Predicate delegate with the lambda expressions as shown in the below example:Example:Predicate<string> val = str = > str.Equals(str.ToLower());val(\"Geeks\");" }, { "code": null, "e": 2819, "s": 2810, "text": "Example:" }, { "code": "Predicate<string> val = str = > str.Equals(str.ToLower());val(\"Geeks\");", "e": 2891, "s": 2819, "text": null }, { "code": null, "e": 2908, "s": 2891, "text": "CSharp-Delegates" }, { "code": null, "e": 2911, "s": 2908, "text": "C#" }, { "code": null, "e": 3009, "s": 2911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3052, "s": 3009, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3083, "s": 3052, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3132, "s": 3083, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3172, "s": 3132, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 3194, "s": 3172, "text": "C# | Class and Object" }, { "code": null, "e": 3212, "s": 3194, "text": "C# | Constructors" }, { "code": null, "e": 3224, "s": 3212, "text": "C# | Arrays" }, { "code": null, "e": 3243, "s": 3224, "text": "C# | Encapsulation" }, { "code": null, "e": 3265, "s": 3243, "text": "C# | Replace() Method" } ]
Understanding “volatile” qualifier in C | Set 1 (Introduction)
15 Jun, 2022 In spite of tons of literature on C language, “volatile” keyword is somehow not understood well (even by experienced C programmers). We think that the main reason for this is due to not having real-world use-case of a ‘volatile‘ variable in typical C programs that are written in high level language. Basically, unless you’re doing some low level hardware programming in C, you probably won’t use a variable while is qualified as “volatile“. By low level programming, we mean a piece of C code which is dealing with peripheral devices, IO ports (mainly memory mapped IO ports), Interrupt Service Routines (ISRs) which interact with Hardware. That’s why it’s not so straight forward to have a sample working C program which can easily show-case the exact effect of “volatile” keyword. In fact, in this article, if we could explain the meaning and purpose of ‘volatile‘, it would serve as basic groundwork for further study and use of ‘volatile’ in C. To understand ‘volatile’, we first need to have some background about what a compiler does to a C program. At high level, we know that a compiler converts C code to Machine code so that the executable can be run without having actual source code. Similar to other technologies, compiler technology had also evolved a lot. While translating Source code to Machine code, compilers typically try to optimize the output so that lesser Machine code needs to be executed finally. One such optimization is removing unnecessary Machine code for accessing variable which is not changing from Compiler’s perspective. Suppose we have the following code: CPP uint32 status = 0; while (status == 0){ /*Let us assume that status isn't being changed in this while loop or may be in our whole program*/ /*So long as status (which could be reflecting status of some IO port) is ZERO, do something*/} An optimizing Compiler would see that status isn’t being changed by while loop. So there’s no need to access status variable again and again after each iteration of loop. So the Compiler would convert this loop to a infinite loop i.e. while (1) so that the Machine code to read status isn’t needed. Please note that compiler isn’t aware of that status is a special variable which can be changed from outside the current program at any point of time e.g. some IO operation happened on a peripheral device for which device IO port was memory mapped to this variable. So in reality, we want compiler to access status variable after every loop iteration even though it isn’t modified by our program which is being compiled by Compiler.One can argue that we can turn-off all the compiler optimizations for such programs so that we don’t run into this situation. This is not an option due to multiple reasons such as A) Each compiler implementation is different so it’s not a portable solution B) Just because of one variable, we don’t want to turn of all the other optimizations which compiler does at other portions of our program. C) By turning off all the optimizations, our low level program couldn’t work as expected e.g. too much increase in size or delayed execution.That’s where “volatile” comes in picture. Basically, we need to instruct Compiler that status is special variable so that no such optimization are allowed on this variable. With this, we would define our variable as follows: CPP volatile uint32 status = 0; For simplicity of explanation purpose, we choose the above example. But in general, volatile is used with pointers such as follows: CPP volatile uint32 * statusPtr = 0xF1230000 Here, statusPtr is pointing to a memory location (e.g. for some IO port) at which the content can change at any point of time from some peripheral device. Please note that our program might not have any control or knowledge about when that memory would change. So we would make it “volatile” so that compiler doesn’t perform optimization for the volatile variable which is pointed by statusPtr.In the context of our discussion about “volatile“, we quote C language standard i.e. ISO/IEC 9899 C11 – clause 6.7.3 “An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects.” “A volatile declaration may be used to describe an object corresponding to a memory-mapped input/output port or an object accessed by an asynchronously interrupting function. Actions on objects so declared shall not be ‘‘optimized out’’ by an implementation or reordered except as permitted by the rules for evaluating expressions.”Basically, C standard says that “volatile” variables can change from outside the program and that’s why compilers aren’t supposed to optimize their access. Now, you can guess that having too many ‘volatile‘ variables in your program would also result in lesser & lesser compiler optimization. We hope it gives you enough background about meaning and purpose of “volatile”.From this article, we would like you to take-away the concept of “volatile variable –> don’t do compiler optimization for that variable“!The following article explains volatile through more examples. Understanding “volatile” qualifier in C | Set 2 (Examples)If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anikakapoor sagartomar9927 C-Storage Classes and Type Qualifiers C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ TCP Server-Client implementation in C Smart Pointers in C++ and How to Use Them 'this' pointer in C++ Ways to copy a vector in C++ Storage Classes in C Understanding "extern" keyword in C
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2022" }, { "code": null, "e": 1648, "s": 54, "text": "In spite of tons of literature on C language, “volatile” keyword is somehow not understood well (even by experienced C programmers). We think that the main reason for this is due to not having real-world use-case of a ‘volatile‘ variable in typical C programs that are written in high level language. Basically, unless you’re doing some low level hardware programming in C, you probably won’t use a variable while is qualified as “volatile“. By low level programming, we mean a piece of C code which is dealing with peripheral devices, IO ports (mainly memory mapped IO ports), Interrupt Service Routines (ISRs) which interact with Hardware. That’s why it’s not so straight forward to have a sample working C program which can easily show-case the exact effect of “volatile” keyword. In fact, in this article, if we could explain the meaning and purpose of ‘volatile‘, it would serve as basic groundwork for further study and use of ‘volatile’ in C. To understand ‘volatile’, we first need to have some background about what a compiler does to a C program. At high level, we know that a compiler converts C code to Machine code so that the executable can be run without having actual source code. Similar to other technologies, compiler technology had also evolved a lot. While translating Source code to Machine code, compilers typically try to optimize the output so that lesser Machine code needs to be executed finally. One such optimization is removing unnecessary Machine code for accessing variable which is not changing from Compiler’s perspective. Suppose we have the following code: " }, { "code": null, "e": 1652, "s": 1648, "text": "CPP" }, { "code": "uint32 status = 0; while (status == 0){ /*Let us assume that status isn't being changed in this while loop or may be in our whole program*/ /*So long as status (which could be reflecting status of some IO port) is ZERO, do something*/}", "e": 1893, "s": 1652, "text": null }, { "code": null, "e": 3388, "s": 1893, "text": "An optimizing Compiler would see that status isn’t being changed by while loop. So there’s no need to access status variable again and again after each iteration of loop. So the Compiler would convert this loop to a infinite loop i.e. while (1) so that the Machine code to read status isn’t needed. Please note that compiler isn’t aware of that status is a special variable which can be changed from outside the current program at any point of time e.g. some IO operation happened on a peripheral device for which device IO port was memory mapped to this variable. So in reality, we want compiler to access status variable after every loop iteration even though it isn’t modified by our program which is being compiled by Compiler.One can argue that we can turn-off all the compiler optimizations for such programs so that we don’t run into this situation. This is not an option due to multiple reasons such as A) Each compiler implementation is different so it’s not a portable solution B) Just because of one variable, we don’t want to turn of all the other optimizations which compiler does at other portions of our program. C) By turning off all the optimizations, our low level program couldn’t work as expected e.g. too much increase in size or delayed execution.That’s where “volatile” comes in picture. Basically, we need to instruct Compiler that status is special variable so that no such optimization are allowed on this variable. With this, we would define our variable as follows: " }, { "code": null, "e": 3392, "s": 3388, "text": "CPP" }, { "code": "volatile uint32 status = 0;", "e": 3420, "s": 3392, "text": null }, { "code": null, "e": 3553, "s": 3420, "text": "For simplicity of explanation purpose, we choose the above example. But in general, volatile is used with pointers such as follows: " }, { "code": null, "e": 3557, "s": 3553, "text": "CPP" }, { "code": "volatile uint32 * statusPtr = 0xF1230000", "e": 3598, "s": 3557, "text": null }, { "code": null, "e": 5582, "s": 3598, "text": "Here, statusPtr is pointing to a memory location (e.g. for some IO port) at which the content can change at any point of time from some peripheral device. Please note that our program might not have any control or knowledge about when that memory would change. So we would make it “volatile” so that compiler doesn’t perform optimization for the volatile variable which is pointed by statusPtr.In the context of our discussion about “volatile“, we quote C language standard i.e. ISO/IEC 9899 C11 – clause 6.7.3 “An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects.” “A volatile declaration may be used to describe an object corresponding to a memory-mapped input/output port or an object accessed by an asynchronously interrupting function. Actions on objects so declared shall not be ‘‘optimized out’’ by an implementation or reordered except as permitted by the rules for evaluating expressions.”Basically, C standard says that “volatile” variables can change from outside the program and that’s why compilers aren’t supposed to optimize their access. Now, you can guess that having too many ‘volatile‘ variables in your program would also result in lesser & lesser compiler optimization. We hope it gives you enough background about meaning and purpose of “volatile”.From this article, we would like you to take-away the concept of “volatile variable –> don’t do compiler optimization for that variable“!The following article explains volatile through more examples. Understanding “volatile” qualifier in C | Set 2 (Examples)If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5594, "s": 5582, "text": "anikakapoor" }, { "code": null, "e": 5609, "s": 5594, "text": "sagartomar9927" }, { "code": null, "e": 5647, "s": 5609, "text": "C-Storage Classes and Type Qualifiers" }, { "code": null, "e": 5658, "s": 5647, "text": "C Language" }, { "code": null, "e": 5756, "s": 5658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5804, "s": 5756, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 5849, "s": 5804, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 5870, "s": 5849, "text": "Operators in C / C++" }, { "code": null, "e": 5896, "s": 5870, "text": "Exception Handling in C++" }, { "code": null, "e": 5934, "s": 5896, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 5976, "s": 5934, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 5998, "s": 5976, "text": "'this' pointer in C++" }, { "code": null, "e": 6027, "s": 5998, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 6048, "s": 6027, "text": "Storage Classes in C" } ]
How do I plot multiple X or Y axes in Matplotlib?
To plot multiple X or Y axis, we can use twinx() or twiny() methods, we can take the following Steps − Using subplots() method, create a figure and a set of subplots. Using subplots() method, create a figure and a set of subplots. Plot [1, 2, 3, 4, 5] data points on the left Y-axis scales. Plot [1, 2, 3, 4, 5] data points on the left Y-axis scales. Using twinx() method, create a twin of Axes with a shared X-axis but independent Y-axis, ax2. Using twinx() method, create a twin of Axes with a shared X-axis but independent Y-axis, ax2. Plot [11, 12, 31, 41, 15] data points on the right Y-axis scale, with blue color. Plot [11, 12, 31, 41, 15] data points on the right Y-axis scale, with blue color. Using tight_layout() method, adjust the padding between and around the subplots. Using tight_layout() method, adjust the padding between and around the subplots. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax1 = plt.subplots() ax1.plot([1, 2, 3, 4, 5], color='red') ax2 = ax1.twinx() ax2.plot([11, 12, 31, 41, 15], color='blue') fig.tight_layout() plt.show()
[ { "code": null, "e": 1165, "s": 1062, "text": "To plot multiple X or Y axis, we can use twinx() or twiny() methods, we can take the following Steps −" }, { "code": null, "e": 1229, "s": 1165, "text": "Using subplots() method, create a figure and a set of subplots." }, { "code": null, "e": 1293, "s": 1229, "text": "Using subplots() method, create a figure and a set of subplots." }, { "code": null, "e": 1353, "s": 1293, "text": "Plot [1, 2, 3, 4, 5] data points on the left Y-axis scales." }, { "code": null, "e": 1413, "s": 1353, "text": "Plot [1, 2, 3, 4, 5] data points on the left Y-axis scales." }, { "code": null, "e": 1507, "s": 1413, "text": "Using twinx() method, create a twin of Axes with a shared X-axis but independent Y-axis, ax2." }, { "code": null, "e": 1601, "s": 1507, "text": "Using twinx() method, create a twin of Axes with a shared X-axis but independent Y-axis, ax2." }, { "code": null, "e": 1683, "s": 1601, "text": "Plot [11, 12, 31, 41, 15] data points on the right Y-axis scale, with blue color." }, { "code": null, "e": 1765, "s": 1683, "text": "Plot [11, 12, 31, 41, 15] data points on the right Y-axis scale, with blue color." }, { "code": null, "e": 1846, "s": 1765, "text": "Using tight_layout() method, adjust the padding between and around the subplots." }, { "code": null, "e": 1927, "s": 1846, "text": "Using tight_layout() method, adjust the padding between and around the subplots." }, { "code": null, "e": 1969, "s": 1927, "text": "To display the figure, use show() method." }, { "code": null, "e": 2011, "s": 1969, "text": "To display the figure, use show() method." }, { "code": null, "e": 2288, "s": 2011, "text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig, ax1 = plt.subplots()\nax1.plot([1, 2, 3, 4, 5], color='red')\nax2 = ax1.twinx()\nax2.plot([11, 12, 31, 41, 15], color='blue')\nfig.tight_layout()\nplt.show()" } ]
Node.js prompt.get() Method - GeeksforGeeks
15 Oct, 2020 The prompt.get() method is an asynchronous function. This method takes strings representing property names in addition to objects for complex property validation (and more). This function is used for I/O operations. Syntax: prompt.get([object]/[properties name], callbackfunction) Parameters: This method takes two parameters as shown below: [object]/[properties name]: This parameter holds the property of the input value or predefined object.callbackfunction: This parameter holds the callback function to make this function an asynchronous function. [object]/[properties name]: This parameter holds the property of the input value or predefined object. callbackfunction: This parameter holds the callback function to make this function an asynchronous function. Installation Module: You can visit the link to Install this module. You can install this package by using this command.npm install prompt After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install this module. You can install this package by using this command.npm install prompt npm install prompt After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Filename: Index.js var prompt = require('prompt'); // Function callprompt.start(); // Reading two properties from user ie. name & classprompt.get(['Name', 'class'], function (err, result) { // Printing the result console.log('Command-line input received:'); console.log('Name: ' + result.name); console.log('class: ' + result.class);}) Project Structure: Run the index.js file using the following command: node index.js Output: prompt: name: some-user prompt: class: 12th Command-line input received: name: some-user class: 12th Node.js-Methods Node.js Web Technologies Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24555, "s": 24527, "text": "\n15 Oct, 2020" }, { "code": null, "e": 24771, "s": 24555, "text": "The prompt.get() method is an asynchronous function. This method takes strings representing property names in addition to objects for complex property validation (and more). This function is used for I/O operations." }, { "code": null, "e": 24779, "s": 24771, "text": "Syntax:" }, { "code": null, "e": 24837, "s": 24779, "text": "prompt.get([object]/[properties name], callbackfunction)\n" }, { "code": null, "e": 24898, "s": 24837, "text": "Parameters: This method takes two parameters as shown below:" }, { "code": null, "e": 25109, "s": 24898, "text": "[object]/[properties name]: This parameter holds the property of the input value or predefined object.callbackfunction: This parameter holds the callback function to make this function an asynchronous function." }, { "code": null, "e": 25212, "s": 25109, "text": "[object]/[properties name]: This parameter holds the property of the input value or predefined object." }, { "code": null, "e": 25321, "s": 25212, "text": "callbackfunction: This parameter holds the callback function to make this function an asynchronous function." }, { "code": null, "e": 25342, "s": 25321, "text": "Installation Module:" }, { "code": null, "e": 25608, "s": 25342, "text": "You can visit the link to Install this module. You can install this package by using this command.npm install prompt\nAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js\n" }, { "code": null, "e": 25726, "s": 25608, "text": "You can visit the link to Install this module. You can install this package by using this command.npm install prompt\n" }, { "code": null, "e": 25746, "s": 25726, "text": "npm install prompt\n" }, { "code": null, "e": 25895, "s": 25746, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js\n" }, { "code": null, "e": 25910, "s": 25895, "text": "node index.js\n" }, { "code": null, "e": 25929, "s": 25910, "text": "Filename: Index.js" }, { "code": "var prompt = require('prompt'); // Function callprompt.start(); // Reading two properties from user ie. name & classprompt.get(['Name', 'class'], function (err, result) { // Printing the result console.log('Command-line input received:'); console.log('Name: ' + result.name); console.log('class: ' + result.class);})", "e": 26260, "s": 25929, "text": null }, { "code": null, "e": 26279, "s": 26260, "text": "Project Structure:" }, { "code": null, "e": 26330, "s": 26279, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 26344, "s": 26330, "text": "node index.js" }, { "code": null, "e": 26352, "s": 26344, "text": "Output:" }, { "code": null, "e": 26454, "s": 26352, "text": "prompt: name: some-user\nprompt: class: 12th\nCommand-line input received:\nname: some-user\nclass: 12th\n" }, { "code": null, "e": 26470, "s": 26454, "text": "Node.js-Methods" }, { "code": null, "e": 26478, "s": 26470, "text": "Node.js" }, { "code": null, "e": 26495, "s": 26478, "text": "Web Technologies" }, { "code": null, "e": 26511, "s": 26495, "text": "Write From Home" }, { "code": null, "e": 26609, "s": 26511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26618, "s": 26609, "text": "Comments" }, { "code": null, "e": 26631, "s": 26618, "text": "Old Comments" }, { "code": null, "e": 26688, "s": 26631, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 26727, "s": 26688, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 26754, "s": 26727, "text": "Mongoose Populate() Method" }, { "code": null, "e": 26785, "s": 26754, "text": "Express.js req.params Property" }, { "code": null, "e": 26810, "s": 26785, "text": "Mongoose find() Function" }, { "code": null, "e": 26866, "s": 26810, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26928, "s": 26866, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26971, "s": 26928, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27021, "s": 26971, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java.lang.System class in Java - GeeksforGeeks
18 Nov, 2021 Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. It extends class Object. Fields: public static final InputStream in: The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.public static final PrintStream out: The “standard” output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.public static final PrintStream err: The “standard” error output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored. public static final InputStream in: The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user. public static final PrintStream out: The “standard” output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. public static final PrintStream err: The “standard” error output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored. Methods: 1. static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size): Copies an array. The array to be copied is passed in source, and the index at which point the copy will begin within source is passed in sourceStart. The array that will receive the copy is passed in target, and the index which point the copy will begin within the target is passed in targetStart. Size is the number of elements that are copied. Syntax: public static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size) Returns: NA. Exception: IndexOutOfBoundsException - if copying would cause access of data outside array bounds. ArrayStoreException - if an element in the source array could not be stored into the target array because of a type mismatch. NullPointerException - if either source or target is null. Java // Java code illustrating arraycopy() methodimport java.lang.*;import java.util.Arrays;class SystemDemo{ public static void main(String args[]) { int[] a = {1, 2, 3, 4, 5}; int[] b = {6, 7, 8, 9, 10}; System.arraycopy(a, 0, b, 2, 2); // array b after arraycopy operation System.out.println(Arrays.toString(b)); }} Output: [6, 7, 1, 2, 10] 2. static String clearProperty(String key): Removes the system property indicated by the specified key. Syntax: public static String clearProperty(String key) Returns: the previous string value of the system property, or null if there was no property with that key. Exception: SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property. NullPointerException - if key is null. IllegalArgumentException - if key is empty. 3. static String getProperty(String key): Gets the system property indicated by the specified key. Syntax: public static String getProperty(String key) Returns: the string value of the system property, or null if there is no property with that key. Exception: SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property. NullPointerException - if key is null. IllegalArgumentException - if key is empty. 4. static String getProperty(String key, String def): Gets the system property indicated by the specified key. Syntax: public static String getProperty(String key, String def) Returns: the string value of the system property, or the default value if there is no property with that key. Exception: SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property. NullPointerException - if key is null. IllegalArgumentException - if key is empty. 5. static String setProperty(String key, String value): Sets the system property indicated by the specified key. Syntax: public static String setProperty(String key, String value) Returns: the previous value of the system property, or null if it did not have one. Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow setting of the specified property. NullPointerException - if key or value is null. IllegalArgumentException - if key is empty. Java // Java code illustrating clearProperty(), getProperty()// and setProperty() methodsimport java.lang.*;import static java.lang.System.clearProperty;import static java.lang.System.setProperty;import java.util.Arrays;class SystemDemo{ public static void main(String args[]) { // checking specific property System.out.println(System.getProperty("user.home")); // clearing this property clearProperty("user.home"); System.out.println(System.getProperty("user.home")); // setting specific property setProperty("user.country", "US"); // checking property System.out.println(System.getProperty("user.country")); // checking property other than system property // illustrating getProperty(String key, String def) System.out.println(System.getProperty("user.password", "none of your business")); }} Output: /Users/abhishekverma null US none of your business 6. static Console console(): Returns the unique Console object associated with the current Java virtual machine, if any. Syntax: public static Console console() Returns: The system console, if any, otherwise null. Exception: NA Java // Java code illustrating console() methodimport java.io.Console;import java.lang.*;import java.util.Currency;import java.util.Locale;class SystemDemo{ public static void main(String args[]) throws NullPointerException { Console c = System.console(); if(c != null) { Currency currency = Currency.getInstance(Locale.ITALY); c.printf(currency.getSymbol()); c.flush(); } else System.out.println("No console attached"); }} Output: No console attached 7. static long currentTimeMillis(): Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds. Syntax: public static long currentTimeMillis() Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. Exception: NA. 8. static long nanoTime(): Returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds. Syntax: public static long nanoTime() Returns: the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds Exception: NA Java // Java code illustrating currentTimeMillis() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) throws NullPointerException { System.out.println("difference between the " + "current time and midnight," + " January 1, 1970 UTC is: " + System.currentTimeMillis()); System.out.println("current time in " + "nano sec: " + System.nanoTime()); }} Output: difference between the current time and midnight, January 1, 1970 UTC is: 1499520649545 current time in nano sec: 29976939759226 9. static void exit(int status): Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates an abnormal termination. This method calls the exit method in class Runtime. This method never returns normally. The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n) Syntax: public static void exit(int status) Returns: NA Exception: SecurityException - if a security manager exists and its checkExit method doesn't allow exit with the specified status. Java // Java code illustrating exit() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) throws NullPointerException { System.gc(); System.out.println("Garbage collector executed "); System.out.println(System.getProperty("os.name")); System.exit(1); // this line will not execute as JVM terminated System.out.println("JVM terminated"); }} Output: Garbage collector executed Mac OS X 10. static void gc(): Runs the garbage collector. Calling the gc method suggests that the Java Virtual Machine expand effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. Syntax: public static void gc() Returns: NA Exception: NA Java // Java code illustrating gc() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) { Runtime gfg = Runtime.getRuntime(); long memory1, memory2; Integer integer[] = new Integer[1000]; // checking the total memory System.out.println("Total memory is: " + gfg.totalMemory()); // checking free memory memory1 = gfg.freeMemory(); System.out.println("Initial free memory: " + memory1); // calling the garbage collector on demand System.gc(); memory1 = gfg.freeMemory(); System.out.println("Free memory after garbage " + "collection: " + memory1); // allocating integers for (int i = 0; i < 1000; i++) integer[i] = new Integer(i); memory2 = gfg.freeMemory(); System.out.println("Free memory after allocation: " + memory2); System.out.println("Memory used by allocation: " + (memory1 - memory2)); // discard integers for (int i = 0; i < 1000; i++) integer[i] = null; System.gc(); memory2 = gfg.freeMemory(); System.out.println("Free memory after " + "collecting discarded Integers: " + memory2); }} Output: Total memory is: 128974848 Initial free memory: 126929976 Free memory after garbage collection: 128632160 Free memory after allocation: 127950520 Memory used by allocation: 681640 Free memory after collecting discarded Integers: 128643472 11. static Map getenv(): Returns an unmodifiable string map view of the current system environment. The environment is a system-dependent mapping from names to values which is passed from parent to child processes. If the system does not support environment variables, an empty map is returned. Syntax: public static Map getenv() Returns: the environment as a map of variable names to values. Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow access to the process environment 12. static String getenv(String name): Gets the value of the specified environment variable. An environment variable is a system-dependent external named value. System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH). Syntax: public static String getenv(String name) Returns: the string value of the variable, or null if the variable is not defined in the system environment. Exception: NullPointerException - if name is null SecurityException - if a security manager exists and its checkPermission method doesn't allow access to the environment variable name. Java // Java code illustrating getenv() methodimport java.lang.*;import java.util.Map;import java.util.Set;class SystemDemo{ public static void main(String args[]) { Map<String, String> gfg = System.getenv(); Set<String> keySet = gfg.keySet(); for(String key : keySet) { System.out.println("key= " + key); } // checking specific environment variable System.out.println(System.getenv("PATH")); }} Output: key= JAVA_MAIN_CLASS_5396 key= PATH key= J2D_PIXMAPS key= SHELL key= USER key= TMPDIR key= SSH_AUTH_SOCK key= XPC_FLAGS key= LD_LIBRARY_PATH key= __CF_USER_TEXT_ENCODING key= Apple_PubSub_Socket_Render key= LOGNAME key= LC_CTYPE key= XPC_SERVICE_NAME key= PWD key= JAVA_MAIN_CLASS_2336 key= SHLVL key= HOME key= _ /usr/bin:/bin:/usr/sbin:/sbin 13. static Properties getProperties(): Determines the current system properties. Syntax: public static Properties getProperties() Returns: the system properties. Exception: SecurityException - if a security manager exists and its checkPropertiesAccess method doesn't allow access to the system properties. Java // Java code illustrating getProperties() methodimport java.lang.*;import java.util.Properties;import java.util.Set;class SystemDemo{ public static void main(String args[]) { Properties gfg = System.getProperties(); Set<Object> keySet = gfg.keySet(); for(Object key : keySet) { System.out.println("key= " + key); } }} Output: key= java.runtime.name key= sun.boot.library.path key= java.vm.version key= user.country.format key= gopherProxySet key= java.vm.vendor key= java.vendor.url key= path.separator key= java.vm.name key= file.encoding.pkg key= user.country key= sun.java.launcher key= sun.os.patch.level key= java.vm.specification.name key= user.dir key= java.runtime.version key= java.awt.graphicsenv key= java.endorsed.dirs key= os.arch key= java.io.tmpdir key= line.separator key= java.vm.specification.vendor key= os.name key= sun.jnu.encoding key= java.library.path key= java.specification.name key= java.class.version key= sun.management.compiler key= os.version key= http.nonProxyHosts key= user.home key= user.timezone key= java.awt.printerjob key= file.encoding key= java.specification.version key= java.class.path key= user.name key= java.vm.specification.version key= sun.java.command key= java.home key= sun.arch.data.model key= user.language key= java.specification.vendor key= awt.toolkit key= java.vm.info key= java.version key= java.ext.dirs key= sun.boot.class.path key= java.vendor key= file.separator key= java.vendor.url.bug key= sun.io.unicode.encoding key= sun.cpu.endian key= socksNonProxyHosts key= ftp.nonProxyHosts key= sun.cpu.isalist 14. static SecurityManager getSecurityManager(): Gets the system security interface. Syntax: static SecurityManager getSecurityManager() Returns: if a security manager has already been established for the current application, then that security manager is returned; otherwise, null is returned. Exception: NA 15. static void setSecurityManager(SecurityManager s): Sets the System security. Syntax: public static void setSecurityManager(SecurityManager s) Returns: NA. Exception: SecurityException - if the security manager has already been set and its checkPermission method doesn't allow it to be replaced. Java // Java code illustrating setSecurityManager()// and getSecurityManager() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) { SecurityManager gfg = new SecurityManager(); // setting the security manager System.setSecurityManager(gfg); gfg = System.getSecurityManager(); if(gfg != null) System.out.println("Security manager is configured"); }} Output: Security manager is configured 16. static void setErr(PrintStream err): Reassigns the “standard” error output stream. Syntax: public static void setErr(PrintStream err) Returns: NA Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard error output stream. 17. static void setIn(InputStream in): Reassigns the “standard” input stream. Syntax: public static void setIn(InputStream in) Returns: NA. Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard input stream. 18. static void setOut(PrintStream out): Reassigns the “standard” output stream. Syntax: public void setOut(PrintStream out) Returns: NA Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard output stream. Java // Java code illustrating setOut(), setIn() and setErr() methodimport java.lang.*;import java.util.Properties;import java.io.*;class SystemDemo{ public static void main(String args[]) throws IOException { FileInputStream IN = new FileInputStream("input.txt"); FileOutputStream OUT = new FileOutputStream("system.txt"); // set input stream System.setIn(IN); char c = (char) System.in.read(); System.out.print(c); // set output stream System.setOut(new PrintStream(OUT)); System.out.write("Hi Abhishek\n".getBytes()); // set error stream System.setErr(new PrintStream(OUT)); System.err.write("Exception message\n".getBytes()); }} Output: Output of above java code depends on content in “input.txt” file. Create your own “input.txt” then run the code and check the output. 19. static void load(String filename): Loads a code file with the specified filename from the local file system as a dynamic library. The filename argument must be a complete path name. Syntax: public static void load(String filename) Returns: NA Exception: SecurityException - if a security manager exists and its checkLink method doesn't allow loading of the specified dynamic library UnsatisfiedLinkError - if the file does not exist. NullPointerException - if filename is null 20. static void loadLibrary(String libname): Loads the system library specified by the libname argument. The manner in which a library name is mapped to the actual system library is system dependent. Syntax: public static void loadLibrary(String libname) Returns: NA Exception: SecurityException - if a security manager exists and its checkLink method doesn't allow loading of the specified dynamic library UnsatisfiedLinkError - if the library does not exist. NullPointerException - if libname is null 21. static String mapLibraryName(String libname): Maps a library name into a platform-specific string representing a native library. Syntax: public static String mapLibraryName(String libname) Returns: a platform-dependent native library name. Exception: NullPointerException - if libname is null 22. static void runFinalization(): Runs the finalization methods of any objects pending finalization. Calling this method suggests that the Java Virtual Machine expand effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations. Syntax: public static void runFinalization() Returns: NA Exception: NA. Java // Java code illustrating runFinalization(), load()// loadLibrary() and mapLibraryName() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) throws NullPointerException { // map library name String libName = System.mapLibraryName("os.name"); System.out.println("os.name library= " + libName); //load external libraries System.load("lixXYZ.so"); System.loadLibrary("libos.name.dylib"); //run finalization System.runFinalization(); }} Output: os.name library= libos.name.dylib 23. static int identityHashCode(Object x): Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode(). The hash code for the null reference is zero. Syntax: public static int identityHashCode(Object x) Returns: the hashCode. Exception: NA. 24. static Channel inheritedChannel(): Returns the channel inherited from the entity that created this Java virtual machine. Syntax: public static Channel inheritedChannel(). Returns: inherited channel, if any, otherwise null. Exception: IOException - If an I/O error occurs SecurityException - If a security manager is present and it does not permit access to the channel. 25. static String lineSeparator(): Returns the system-dependent line separator string. It always returns the same value – the initial value of the system property line separator. Syntax: public static String lineSeparator() Returns: On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n". Exception: NA Java // Java code illustrating lineSeparator(), inherentChannel()// and identityHashCode() methodimport java.io.IOException;import java.lang.*;import java.nio.channels.Channel;class SystemDemo{ public static void main(String args[]) throws NullPointerException, IOException { Integer x = 400; System.out.println(System.identityHashCode(x)); Channel ch = System.inheritedChannel(); System.out.println(ch); System.out.println(System.lineSeparator()); }} Output: 1735600054 null "\r\n" This article is contributed by Abhishek 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sweetyty arorakashish0911 sagar0719kumar Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24577, "s": 24549, "text": "\n18 Nov, 2021" }, { "code": null, "e": 24887, "s": 24577, "text": "Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. It extends class Object. " }, { "code": null, "e": 24896, "s": 24887, "text": "Fields: " }, { "code": null, "e": 25958, "s": 24896, "text": "public static final InputStream in: The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.public static final PrintStream out: The “standard” output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.public static final PrintStream err: The “standard” error output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored." }, { "code": null, "e": 26202, "s": 25958, "text": "public static final InputStream in: The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user." }, { "code": null, "e": 26455, "s": 26202, "text": "public static final PrintStream out: The “standard” output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user." }, { "code": null, "e": 27022, "s": 26455, "text": "public static final PrintStream err: The “standard” error output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored." }, { "code": null, "e": 27033, "s": 27022, "text": "Methods: " }, { "code": null, "e": 27480, "s": 27033, "text": "1. static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size): Copies an array. The array to be copied is passed in source, and the index at which point the copy will begin within source is passed in sourceStart. The array that will receive the copy is passed in target, and the index which point the copy will begin within the target is passed in targetStart. Size is the number of elements that are copied. " }, { "code": null, "e": 27892, "s": 27480, "text": "Syntax: public static void arraycopy(Object source, \nint sourceStart, Object Target, int targetStart, int size)\nReturns: NA.\nException: \nIndexOutOfBoundsException - if copying would cause access of data \noutside array bounds.\nArrayStoreException - if an element in the source array could not \nbe stored into the target array because of a type mismatch.\nNullPointerException - if either source or target is null." }, { "code": null, "e": 27897, "s": 27892, "text": "Java" }, { "code": "// Java code illustrating arraycopy() methodimport java.lang.*;import java.util.Arrays;class SystemDemo{ public static void main(String args[]) { int[] a = {1, 2, 3, 4, 5}; int[] b = {6, 7, 8, 9, 10}; System.arraycopy(a, 0, b, 2, 2); // array b after arraycopy operation System.out.println(Arrays.toString(b)); }}", "e": 28282, "s": 27897, "text": null }, { "code": null, "e": 28291, "s": 28282, "text": "Output: " }, { "code": null, "e": 28308, "s": 28291, "text": "[6, 7, 1, 2, 10]" }, { "code": null, "e": 28413, "s": 28308, "text": "2. static String clearProperty(String key): Removes the system property indicated by the specified key. " }, { "code": null, "e": 28813, "s": 28413, "text": "Syntax: public static String clearProperty(String key)\nReturns: the previous string value \nof the system property, or null if there was no property \nwith that key.\nException: \nSecurityException - if a security manager exists and its \ncheckPropertyAccess method doesn't allow \naccess to the specified system property.\nNullPointerException - if key is null.\nIllegalArgumentException - if key is empty." }, { "code": null, "e": 28913, "s": 28813, "text": "3. static String getProperty(String key): Gets the system property indicated by the specified key. " }, { "code": null, "e": 29300, "s": 28913, "text": "Syntax: public static String getProperty(String key)\nReturns: the string value of the system \nproperty, or null if there is no property with that key.\nException: \nSecurityException - if a security manager exists and its \ncheckPropertyAccess method doesn't allow access to the \nspecified system property.\nNullPointerException - if key is null.\nIllegalArgumentException - if key is empty." }, { "code": null, "e": 29412, "s": 29300, "text": "4. static String getProperty(String key, String def): Gets the system property indicated by the specified key. " }, { "code": null, "e": 29824, "s": 29412, "text": "Syntax: public static String getProperty(String key, String def)\nReturns: the string value of the system property,\n or the default value if there is no property with that key.\nException: \nSecurityException - if a security manager exists and its \ncheckPropertyAccess method doesn't allow access to the \nspecified system property.\nNullPointerException - if key is null.\nIllegalArgumentException - if key is empty." }, { "code": null, "e": 29938, "s": 29824, "text": "5. static String setProperty(String key, String value): Sets the system property indicated by the specified key. " }, { "code": null, "e": 30324, "s": 29938, "text": "Syntax: public static String setProperty(String key, String value)\nReturns: the previous value of the system \nproperty, or null if it did not have one.\nException: \nSecurityException - if a security manager exists and its checkPermission \nmethod doesn't allow setting of the specified property.\nNullPointerException - if key or value is null.\nIllegalArgumentException - if key is empty." }, { "code": null, "e": 30329, "s": 30324, "text": "Java" }, { "code": "// Java code illustrating clearProperty(), getProperty()// and setProperty() methodsimport java.lang.*;import static java.lang.System.clearProperty;import static java.lang.System.setProperty;import java.util.Arrays;class SystemDemo{ public static void main(String args[]) { // checking specific property System.out.println(System.getProperty(\"user.home\")); // clearing this property clearProperty(\"user.home\"); System.out.println(System.getProperty(\"user.home\")); // setting specific property setProperty(\"user.country\", \"US\"); // checking property System.out.println(System.getProperty(\"user.country\")); // checking property other than system property // illustrating getProperty(String key, String def) System.out.println(System.getProperty(\"user.password\", \"none of your business\")); }}", "e": 31270, "s": 30329, "text": null }, { "code": null, "e": 31279, "s": 31270, "text": "Output: " }, { "code": null, "e": 31330, "s": 31279, "text": "/Users/abhishekverma\nnull\nUS\nnone of your business" }, { "code": null, "e": 31452, "s": 31330, "text": "6. static Console console(): Returns the unique Console object associated with the current Java virtual machine, if any. " }, { "code": null, "e": 31559, "s": 31452, "text": "Syntax: public static Console console()\nReturns: The system console, if any, otherwise null.\nException: NA" }, { "code": null, "e": 31564, "s": 31559, "text": "Java" }, { "code": "// Java code illustrating console() methodimport java.io.Console;import java.lang.*;import java.util.Currency;import java.util.Locale;class SystemDemo{ public static void main(String args[]) throws NullPointerException { Console c = System.console(); if(c != null) { Currency currency = Currency.getInstance(Locale.ITALY); c.printf(currency.getSymbol()); c.flush(); } else System.out.println(\"No console attached\"); }}", "e": 32078, "s": 31564, "text": null }, { "code": null, "e": 32087, "s": 32078, "text": "Output: " }, { "code": null, "e": 32107, "s": 32087, "text": "No console attached" }, { "code": null, "e": 32431, "s": 32107, "text": "7. static long currentTimeMillis(): Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds. " }, { "code": null, "e": 32605, "s": 32431, "text": "Syntax: public static long currentTimeMillis()\nReturns: the difference, measured in milliseconds,\n between the current time and midnight, January 1, 1970 UTC.\nException: NA." }, { "code": null, "e": 32742, "s": 32605, "text": "8. static long nanoTime(): Returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds. " }, { "code": null, "e": 32904, "s": 32742, "text": "Syntax: public static long nanoTime()\nReturns: the current value of the running Java\n Virtual Machine's high-resolution time source, in nanoseconds\nException: NA" }, { "code": null, "e": 32909, "s": 32904, "text": "Java" }, { "code": "// Java code illustrating currentTimeMillis() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) throws NullPointerException { System.out.println(\"difference between the \" + \"current time and midnight,\" + \" January 1, 1970 UTC is: \" + System.currentTimeMillis()); System.out.println(\"current time in \" + \"nano sec: \" + System.nanoTime()); }}", "e": 33380, "s": 32909, "text": null }, { "code": null, "e": 33389, "s": 33380, "text": "Output: " }, { "code": null, "e": 33520, "s": 33389, "text": "difference between the current time \nand midnight, January 1, 1970 UTC is: \n1499520649545\ncurrent time in nano sec: 29976939759226" }, { "code": null, "e": 33899, "s": 33520, "text": "9. static void exit(int status): Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates an abnormal termination. This method calls the exit method in class Runtime. This method never returns normally. The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n) " }, { "code": null, "e": 34088, "s": 33899, "text": "Syntax: public static void exit(int status)\nReturns: NA\nException: \nSecurityException - if a security manager exists and its \ncheckExit method doesn't allow exit with the specified status." }, { "code": null, "e": 34093, "s": 34088, "text": "Java" }, { "code": "// Java code illustrating exit() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) throws NullPointerException { System.gc(); System.out.println(\"Garbage collector executed \"); System.out.println(System.getProperty(\"os.name\")); System.exit(1); // this line will not execute as JVM terminated System.out.println(\"JVM terminated\"); }}", "e": 34536, "s": 34093, "text": null }, { "code": null, "e": 34545, "s": 34536, "text": "Output: " }, { "code": null, "e": 34582, "s": 34545, "text": "Garbage collector executed \nMac OS X" }, { "code": null, "e": 34953, "s": 34582, "text": "10. static void gc(): Runs the garbage collector. Calling the gc method suggests that the Java Virtual Machine expand effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. " }, { "code": null, "e": 35011, "s": 34953, "text": "Syntax: public static void gc()\nReturns: NA\nException: NA" }, { "code": null, "e": 35016, "s": 35011, "text": "Java" }, { "code": "// Java code illustrating gc() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) { Runtime gfg = Runtime.getRuntime(); long memory1, memory2; Integer integer[] = new Integer[1000]; // checking the total memory System.out.println(\"Total memory is: \" + gfg.totalMemory()); // checking free memory memory1 = gfg.freeMemory(); System.out.println(\"Initial free memory: \" + memory1); // calling the garbage collector on demand System.gc(); memory1 = gfg.freeMemory(); System.out.println(\"Free memory after garbage \" + \"collection: \" + memory1); // allocating integers for (int i = 0; i < 1000; i++) integer[i] = new Integer(i); memory2 = gfg.freeMemory(); System.out.println(\"Free memory after allocation: \" + memory2); System.out.println(\"Memory used by allocation: \" + (memory1 - memory2)); // discard integers for (int i = 0; i < 1000; i++) integer[i] = null; System.gc(); memory2 = gfg.freeMemory(); System.out.println(\"Free memory after \" + \"collecting discarded Integers: \" + memory2); }}", "e": 36406, "s": 35016, "text": null }, { "code": null, "e": 36415, "s": 36406, "text": "Output: " }, { "code": null, "e": 36655, "s": 36415, "text": "Total memory is: 128974848\nInitial free memory: 126929976\nFree memory after garbage collection: 128632160\nFree memory after allocation: 127950520\nMemory used by allocation: 681640\nFree memory after collecting discarded Integers: 128643472" }, { "code": null, "e": 36951, "s": 36655, "text": "11. static Map getenv(): Returns an unmodifiable string map view of the current system environment. The environment is a system-dependent mapping from names to values which is passed from parent to child processes. If the system does not support environment variables, an empty map is returned. " }, { "code": null, "e": 37191, "s": 36951, "text": "Syntax: public static Map getenv()\nReturns: the environment as a map of variable names to values.\nException: \nSecurityException - if a security manager exists and its \ncheckPermission method doesn't allow access to the process \nenvironment" }, { "code": null, "e": 38102, "s": 37191, "text": "12. static String getenv(String name): Gets the value of the specified environment variable. An environment variable is a system-dependent external named value. System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH). " }, { "code": null, "e": 38449, "s": 38102, "text": "Syntax: public static String getenv(String name)\nReturns: the string value of the variable,\n or null if the variable is not defined in the system environment.\nException: \nNullPointerException - if name is null\nSecurityException - if a security manager exists and \nits checkPermission method doesn't allow access to the\n environment variable name." }, { "code": null, "e": 38454, "s": 38449, "text": "Java" }, { "code": "// Java code illustrating getenv() methodimport java.lang.*;import java.util.Map;import java.util.Set;class SystemDemo{ public static void main(String args[]) { Map<String, String> gfg = System.getenv(); Set<String> keySet = gfg.keySet(); for(String key : keySet) { System.out.println(\"key= \" + key); } // checking specific environment variable System.out.println(System.getenv(\"PATH\")); }}", "e": 38923, "s": 38454, "text": null }, { "code": null, "e": 38932, "s": 38923, "text": "Output: " }, { "code": null, "e": 39276, "s": 38932, "text": "key= JAVA_MAIN_CLASS_5396\nkey= PATH\nkey= J2D_PIXMAPS\nkey= SHELL\nkey= USER\nkey= TMPDIR\nkey= SSH_AUTH_SOCK\nkey= XPC_FLAGS\nkey= LD_LIBRARY_PATH\nkey= __CF_USER_TEXT_ENCODING\nkey= Apple_PubSub_Socket_Render\nkey= LOGNAME\nkey= LC_CTYPE\nkey= XPC_SERVICE_NAME\nkey= PWD\nkey= JAVA_MAIN_CLASS_2336\nkey= SHLVL\nkey= HOME\nkey= _\n/usr/bin:/bin:/usr/sbin:/sbin" }, { "code": null, "e": 39358, "s": 39276, "text": "13. static Properties getProperties(): Determines the current system properties. " }, { "code": null, "e": 39586, "s": 39358, "text": "Syntax: public static Properties getProperties()\nReturns: the system properties.\nException: \nSecurityException - if a security manager exists and \nits checkPropertiesAccess method doesn't allow access \nto the system properties." }, { "code": null, "e": 39591, "s": 39586, "text": "Java" }, { "code": "// Java code illustrating getProperties() methodimport java.lang.*;import java.util.Properties;import java.util.Set;class SystemDemo{ public static void main(String args[]) { Properties gfg = System.getProperties(); Set<Object> keySet = gfg.keySet(); for(Object key : keySet) { System.out.println(\"key= \" + key); } }}", "e": 39964, "s": 39591, "text": null }, { "code": null, "e": 39973, "s": 39964, "text": "Output: " }, { "code": null, "e": 41214, "s": 39973, "text": "key= java.runtime.name\nkey= sun.boot.library.path\nkey= java.vm.version\nkey= user.country.format\nkey= gopherProxySet\nkey= java.vm.vendor\nkey= java.vendor.url\nkey= path.separator\nkey= java.vm.name\nkey= file.encoding.pkg\nkey= user.country\nkey= sun.java.launcher\nkey= sun.os.patch.level\nkey= java.vm.specification.name\nkey= user.dir\nkey= java.runtime.version\nkey= java.awt.graphicsenv\nkey= java.endorsed.dirs\nkey= os.arch\nkey= java.io.tmpdir\nkey= line.separator\nkey= java.vm.specification.vendor\nkey= os.name\nkey= sun.jnu.encoding\nkey= java.library.path\nkey= java.specification.name\nkey= java.class.version\nkey= sun.management.compiler\nkey= os.version\nkey= http.nonProxyHosts\nkey= user.home\nkey= user.timezone\nkey= java.awt.printerjob\nkey= file.encoding\nkey= java.specification.version\nkey= java.class.path\nkey= user.name\nkey= java.vm.specification.version\nkey= sun.java.command\nkey= java.home\nkey= sun.arch.data.model\nkey= user.language\nkey= java.specification.vendor\nkey= awt.toolkit\nkey= java.vm.info\nkey= java.version\nkey= java.ext.dirs\nkey= sun.boot.class.path\nkey= java.vendor\nkey= file.separator\nkey= java.vendor.url.bug\nkey= sun.io.unicode.encoding\nkey= sun.cpu.endian\nkey= socksNonProxyHosts\nkey= ftp.nonProxyHosts\nkey= sun.cpu.isalist" }, { "code": null, "e": 41300, "s": 41214, "text": "14. static SecurityManager getSecurityManager(): Gets the system security interface. " }, { "code": null, "e": 41527, "s": 41300, "text": "Syntax: static SecurityManager getSecurityManager()\nReturns: if a security manager has \nalready been established for the current application,\n then that security manager is returned; otherwise, \nnull is returned.\nException: NA" }, { "code": null, "e": 41609, "s": 41527, "text": "15. static void setSecurityManager(SecurityManager s): Sets the System security. " }, { "code": null, "e": 41830, "s": 41609, "text": "Syntax: public static void setSecurityManager(SecurityManager s)\nReturns: NA.\nException: \nSecurityException - if the security manager has \nalready been set and its checkPermission method \ndoesn't allow it to be replaced." }, { "code": null, "e": 41835, "s": 41830, "text": "Java" }, { "code": "// Java code illustrating setSecurityManager()// and getSecurityManager() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) { SecurityManager gfg = new SecurityManager(); // setting the security manager System.setSecurityManager(gfg); gfg = System.getSecurityManager(); if(gfg != null) System.out.println(\"Security manager is configured\"); }}", "e": 42283, "s": 41835, "text": null }, { "code": null, "e": 42292, "s": 42283, "text": "Output: " }, { "code": null, "e": 42323, "s": 42292, "text": "Security manager is configured" }, { "code": null, "e": 42411, "s": 42323, "text": "16. static void setErr(PrintStream err): Reassigns the “standard” error output stream. " }, { "code": null, "e": 42631, "s": 42411, "text": "Syntax: public static void setErr(PrintStream err)\nReturns: NA\nException: \nSecurityException - if a security manager exists and its\n checkPermission method doesn't allow reassigning of the\n standard error output stream." }, { "code": null, "e": 42710, "s": 42631, "text": "17. static void setIn(InputStream in): Reassigns the “standard” input stream. " }, { "code": null, "e": 42922, "s": 42710, "text": "Syntax: public static void setIn(InputStream in)\nReturns: NA.\nException: \nSecurityException - if a security manager exists and its\n checkPermission method doesn't allow reassigning of the\n standard input stream." }, { "code": null, "e": 43004, "s": 42922, "text": "18. static void setOut(PrintStream out): Reassigns the “standard” output stream. " }, { "code": null, "e": 43211, "s": 43004, "text": "Syntax: public void setOut(PrintStream out)\nReturns: NA\nException: \nSecurityException - if a security manager exists and its\n checkPermission method doesn't allow reassigning of the\n standard output stream." }, { "code": null, "e": 43216, "s": 43211, "text": "Java" }, { "code": "// Java code illustrating setOut(), setIn() and setErr() methodimport java.lang.*;import java.util.Properties;import java.io.*;class SystemDemo{ public static void main(String args[]) throws IOException { FileInputStream IN = new FileInputStream(\"input.txt\"); FileOutputStream OUT = new FileOutputStream(\"system.txt\"); // set input stream System.setIn(IN); char c = (char) System.in.read(); System.out.print(c); // set output stream System.setOut(new PrintStream(OUT)); System.out.write(\"Hi Abhishek\\n\".getBytes()); // set error stream System.setErr(new PrintStream(OUT)); System.err.write(\"Exception message\\n\".getBytes()); }}", "e": 43966, "s": 43216, "text": null }, { "code": null, "e": 44110, "s": 43966, "text": "Output: Output of above java code depends on content in “input.txt” file. Create your own “input.txt” then run the code and check the output. " }, { "code": null, "e": 44297, "s": 44110, "text": "19. static void load(String filename): Loads a code file with the specified filename from the local file system as a dynamic library. The filename argument must be a complete path name. " }, { "code": null, "e": 44595, "s": 44297, "text": "Syntax: public static void load(String filename)\nReturns: NA\nException: \nSecurityException - if a security manager exists and\n its checkLink method doesn't allow loading of the specified\n dynamic library\nUnsatisfiedLinkError - if the file does not exist.\nNullPointerException - if filename is null" }, { "code": null, "e": 44796, "s": 44595, "text": "20. static void loadLibrary(String libname): Loads the system library specified by the libname argument. The manner in which a library name is mapped to the actual system library is system dependent. " }, { "code": null, "e": 45102, "s": 44796, "text": "Syntax: public static void loadLibrary(String libname)\nReturns: NA\nException: \nSecurityException - if a security manager exists and its \ncheckLink method doesn't allow loading of the specified dynamic\n library\nUnsatisfiedLinkError - if the library does not exist.\nNullPointerException - if libname is null" }, { "code": null, "e": 45236, "s": 45102, "text": "21. static String mapLibraryName(String libname): Maps a library name into a platform-specific string representing a native library. " }, { "code": null, "e": 45400, "s": 45236, "text": "Syntax: public static String mapLibraryName(String libname)\nReturns: a platform-dependent native library name.\nException: NullPointerException - if libname is null" }, { "code": null, "e": 45844, "s": 45400, "text": "22. static void runFinalization(): Runs the finalization methods of any objects pending finalization. Calling this method suggests that the Java Virtual Machine expand effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations. " }, { "code": null, "e": 45916, "s": 45844, "text": "Syntax: public static void runFinalization()\nReturns: NA\nException: NA." }, { "code": null, "e": 45921, "s": 45916, "text": "Java" }, { "code": "// Java code illustrating runFinalization(), load()// loadLibrary() and mapLibraryName() methodimport java.lang.*;class SystemDemo{ public static void main(String args[]) throws NullPointerException { // map library name String libName = System.mapLibraryName(\"os.name\"); System.out.println(\"os.name library= \" + libName); //load external libraries System.load(\"lixXYZ.so\"); System.loadLibrary(\"libos.name.dylib\"); //run finalization System.runFinalization(); }}", "e": 46458, "s": 45921, "text": null }, { "code": null, "e": 46467, "s": 46458, "text": "Output: " }, { "code": null, "e": 46501, "s": 46467, "text": "os.name library= libos.name.dylib" }, { "code": null, "e": 46756, "s": 46501, "text": "23. static int identityHashCode(Object x): Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode(). The hash code for the null reference is zero. " }, { "code": null, "e": 46847, "s": 46756, "text": "Syntax: public static int identityHashCode(Object x)\nReturns: the hashCode.\nException: NA." }, { "code": null, "e": 46973, "s": 46847, "text": "24. static Channel inheritedChannel(): Returns the channel inherited from the entity that created this Java virtual machine. " }, { "code": null, "e": 47225, "s": 46973, "text": "Syntax: public static Channel inheritedChannel().\nReturns: inherited channel, if any, otherwise null.\nException: \nIOException - If an I/O error occurs\nSecurityException - If a security manager is present and\n it does not permit access to the channel." }, { "code": null, "e": 47405, "s": 47225, "text": "25. static String lineSeparator(): Returns the system-dependent line separator string. It always returns the same value – the initial value of the system property line separator. " }, { "code": null, "e": 47556, "s": 47405, "text": "Syntax: public static String lineSeparator()\nReturns: On UNIX systems, it returns \"\\n\";\n on Microsoft Windows systems it returns \"\\r\\n\".\nException: NA" }, { "code": null, "e": 47561, "s": 47556, "text": "Java" }, { "code": "// Java code illustrating lineSeparator(), inherentChannel()// and identityHashCode() methodimport java.io.IOException;import java.lang.*;import java.nio.channels.Channel;class SystemDemo{ public static void main(String args[]) throws NullPointerException, IOException { Integer x = 400; System.out.println(System.identityHashCode(x)); Channel ch = System.inheritedChannel(); System.out.println(ch); System.out.println(System.lineSeparator()); }}", "e": 48103, "s": 47561, "text": null }, { "code": null, "e": 48112, "s": 48103, "text": "Output: " }, { "code": null, "e": 48135, "s": 48112, "text": "1735600054\nnull\n\"\\r\\n\"" }, { "code": null, "e": 48558, "s": 48135, "text": "This article is contributed by Abhishek 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 48567, "s": 48558, "text": "sweetyty" }, { "code": null, "e": 48584, "s": 48567, "text": "arorakashish0911" }, { "code": null, "e": 48599, "s": 48584, "text": "sagar0719kumar" }, { "code": null, "e": 48617, "s": 48599, "text": "Java-lang package" }, { "code": null, "e": 48622, "s": 48617, "text": "Java" }, { "code": null, "e": 48627, "s": 48622, "text": "Java" }, { "code": null, "e": 48725, "s": 48627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48734, "s": 48725, "text": "Comments" }, { "code": null, "e": 48747, "s": 48734, "text": "Old Comments" }, { "code": null, "e": 48798, "s": 48747, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 48828, "s": 48798, "text": "HashMap in Java with Examples" }, { "code": null, "e": 48859, "s": 48828, "text": "How to iterate any Map in Java" }, { "code": null, "e": 48878, "s": 48859, "text": "Interfaces in Java" }, { "code": null, "e": 48910, "s": 48878, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 48928, "s": 48910, "text": "ArrayList in Java" }, { "code": null, "e": 48948, "s": 48928, "text": "Stack Class in Java" }, { "code": null, "e": 48980, "s": 48948, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 49004, "s": 48980, "text": "Singleton Class in Java" } ]
Spring Boot Security MySQL Database Integration Example
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 show how to secure spring boot rest services with MySQL database integration. In the previous example, we have discussed spring boot in-memory security where the user validation happened at in-memory, as part of this Spring Boot Security MySQL Database Integration the user validation takes place in the MySQL database. Spring Boot 2.0.6 Spring Boot WEB Spring Security 2.0.6 Spring Boot Data JPA MySQL 5.1.47 Java 8 As part of this example, I am going to create a simple spring boot rest service which provides two different rest endpoints, one is – to say hello to you and another one is secured rest endpoint which provides all item details. Here we need 3 different tables such as USER, ROLE and USER_ROLE. The relationship between USER and ROLE is many to many because one USER can have multiple ROLES and one ROLE can be assigned to multiple USERS. USER: CREATE TABLE `user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `active` int(11) DEFAULT NULL, `lastname` varchar(255) NOT NULL, `firstname` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 ROLE: CREATE TABLE `role` ( `role_id` int(11) NOT NULL AUTO_INCREMENT, `role_name` varchar(255) DEFAULT NULL, PRIMARY KEY (`role_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 USER_ROLE: As per the normalization we need to have this intermediate table to represent the many to many relationships. CREATE TABLE `user_role` ( `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, PRIMARY KEY (`user_id`,`role_id`), UNIQUE KEY `UK_it77eq964jhfqtu54081ebtio` (`role_id`), CONSTRAINT `FK859n2jvi8ivhui0rl0esws6o` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`), CONSTRAINT `FKa68196081fvovjhkek5m97n3y` FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Insert Data: -- creating user insert into OTP.USER values(1,1,'shekhar','chandra','12345'); -- creating ADMIN role insert into OTP.ROLE values(1,'ADMIN'); -- Mapping ADMIN role id (1) to shekhar user userid (1) insert into OTP.USER_ROLE values(1,1); <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.onlinetutorialspoint</groupId> <artifactId>SpringBoot-Security-Mysql-Example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBoot-Security-Mysql-Example</name> <description>Spring Boot Security MySQL Database Integration Example</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Database configuration properties. server.port=8080 spring.datasource.driver-class-name: com.mysql.jdbc.Driver spring.datasource.url: jdbc:mysql://localhost:3306/otp spring.datasource.username: root spring.datasource.password: 12345 spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true Item Model: Carrying Items. package com.onlinetutorialspoint.model; import java.io.Serializable; public class Item implements Serializable { private Integer id; private String name; private String category; public Item() { } public Item(Integer id, String name, String category) { this.id = id; this.name = name; this.category = category; } // Getters and Setters } Creating JPA Entities: User.java representing USER table. package com.onlinetutorialspoint.model; import javax.persistence.*; import java.util.Set; @Entity @Table(name="user") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="user_id") private int id; @Column(name="firstname") private String firstName; @Column(name="lastname") private String lastName; private String password; @Column(name="active") private int isActive; @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) @JoinTable(name="user_role",joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set roles; public User() { } public User(User user) { this.id = user.getId(); this.firstName = user.getFirstName(); this.lastName = user.getLastName(); this.password = user.getPassword(); this.isActive = user.getIsActive(); this.roles = user.getRoles(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getIsActive() { return isActive; } public void setIsActive(int isActive) { this.isActive = isActive; } public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } Role.java representing ROLE table. package com.onlinetutorialspoint.model; import javax.persistence.*; @Entity @Table(name="role") public class Role { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "role_id") private int id; @Column(name = "role_name") private String roleName; public Role() { } public Role(int id, String roleName) { this.id = id; this.roleName = roleName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } } Creating JPA Repository. package com.onlinetutorialspoint.repos; import com.onlinetutorialspoint.model.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface UsersRepository extends JpaRepository<User, Integer> { Optional<User> findByFirstName(String firstname); } Spring Security UserdetailService Implementation. package com.onlinetutorialspoint.service; import com.onlinetutorialspoint.model.User; import com.onlinetutorialspoint.model.UserDetailsImpl; import com.onlinetutorialspoint.repos.UsersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UsersRepository usersRepository; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { Optional<User> optionalUser = usersRepository.findByFirstName(userName); return Optional.ofNullable(optionalUser).orElseThrow(()->new UsernameNotFoundException("Username Not Found")) .map(UserDetailsImpl::new).get(); } } Spring Security UserDetails implementation. package com.onlinetutorialspoint.model; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.stream.Collectors; public class UserDetailsImpl extends User implements UserDetails { public UserDetailsImpl(User user) { super(user); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return getRoles() .stream() .map(role-> new SimpleGrantedAuthority("ROLE_"+role.getRoleName())) .collect(Collectors.toList()); } @Override public String getPassword() { return super.getPassword(); } @Override public String getUsername() { return super.getFirstName(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } Spring Security Configuration package com.onlinetutorialspoint.configuration; import com.onlinetutorialspoint.repos.UsersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; @EnableGlobalMethodSecurity(prePostEnabled = true) @Configuration @EnableWebSecurity @EnableJpaRepositories(basePackageClasses = UsersRepository.class) public class SecureConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(getPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers("**/getAllItems").authenticated() .anyRequest().permitAll() .and().formLogin().permitAll(); } private PasswordEncoder getPasswordEncoder() { return new PasswordEncoder() { @Override public String encode(CharSequence charSequence) { return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return true; } }; } } Creating the Rest Controller to provide /hello and /getAllItems rest endpoints. package com.onlinetutorialspoint.controller; import com.onlinetutorialspoint.model.Item; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @RestController public class ItemController { @Autowired ItemController itemService; public static List<Item> items; static{ items = new ArrayList<>(Arrays.asList(new Item(1,"Spring Boot in Action","Books"), new Item(2,"Java 8 in Action","Books"), new Item(3,"Data Structures","Books"), new Item(4,"Spring Boot Security","Books"))); } @PreAuthorize("hasAnyRole('ADMIN')") @RequestMapping("/getAllItems") @ResponseBody public ResponseEntity<List<Item>> getAllItems() { //Reading all items (ADMIN only can access this) List<Item> items = this.items; System.out.println("Reading items: "+items); return new ResponseEntity<List<Item>>(items, HttpStatus.OK); } @RequestMapping("/hello") public String sayHello(){ return "Hello User!"; } } Main class. package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootSecurityMysqlExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSecurityMysqlExampleApplication.class, args); } } mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.6.RELEASE) 2018-10-28 12:52:26.892 INFO 13656 --- [ main] pringBootSecurityMysqlExampleApplication : Starting SpringBootSecurityMysqlExampleApplication on DESKTOP-RN4SMHT with PID 13656 (E:\work\SpringBoot-Security-Mysql-Example\target\classes started by Lenovo in E:\work\SpringBoot-Security-Mysql-Example) 2018-10-28 12:52:26.911 INFO 13656 --- [ main] pringBootSecurityMysqlExampleApplication : No active profile set, falling back to default profiles: default 2018-10-28 12:52:27.142 INFO 13656 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@14dd7b39: startup date [Sun Oct 28 12:52:27 IST 2018]; root of context hierarchy ..... ..... Accessing /hello (unsecured) endpoint Accessing /getAllItems secured endpoint — An ADMIN can access this endpoint with valid user credentials. As soon as we access the localhost:8080/getAllItems endpoint, the spring automatically redirects our request to the login page as it is a secured service. Here we have to provide our valid user credentials then only it will allow us to access the /getAllItems endpoint. Note: We haven’t created this login form at all. Spring has given us to provide the login details. Let’s provide invalid user credentials and see what will happen. Here I provided invalid username like shekhar123 and click on Login button, as a result, we should get the below error response saying login attempt was not successful. Let’s provide valid user credentials and see the result. Now we can able to see all items provided by rest endpoint. Spring Security Docs Spring Boot JPA MySql Integration Hibernate Many to Many Relationship Happy Learning 🙂 SpringBoot-Security-Mysql-Example File size: 108 KB Downloads: 2086 Spring Boot Environment Properties reading based on activeprofile Spring Boot In Memory Basic Authentication Security How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path Spring Boot How to change the Tomcat to Jetty Server Spring Boot JPA Integration Example Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot Hibernate Integration Example Spring Boot PDF iText integration with String Template Spring Boot Batch Example Csv to Database Spring Boot H2 Database + JDBC Template Example Spring Boot Actuator Database Health Check How to connect MySQL Database in Eclipse Spring Boot Multiple Data Sources Example Spring Boot Basic Authentication Example Spring Boot Environment Properties reading based on activeprofile Spring Boot In Memory Basic Authentication Security How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path Spring Boot How to change the Tomcat to Jetty Server Spring Boot JPA Integration Example Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot Hibernate Integration Example Spring Boot PDF iText integration with String Template Spring Boot Batch Example Csv to Database Spring Boot H2 Database + JDBC Template Example Spring Boot Actuator Database Health Check How to connect MySQL Database in Eclipse Spring Boot Multiple Data Sources Example Spring Boot Basic Authentication Example W. Wallace January 15, 2019 at 10:25 am - Reply nice one. One question how can i make it “@PreAuthorize(“hasAnyRole(‘ADMIN’)”) ” generic ? @PreAuthorize(“hasAnyRole(‘< LIST OF GROUPS FROM DATABASE')") chandrashekhar January 15, 2019 at 11:26 am - Reply You can define the SQL query logic like the following.. @Component("app_roles") public class Roles{ @Value("${role.roleNames}") private String[] roles; public String[] getRoles() { // SQL goes here.. //this.roles = results; return this.roles; } } call the getRoles() method as below. @PreAuthorize("hasAnyRole(@app_roles.getRoles())") public ResponseEntity> getAllItems() {} It may help you. Thanks, Chandra Shekhar G himanshu June 27, 2019 at 1:20 am - Reply this is the least complex example of such type i could find. Thanks. I couldn’t understand the hashes you provided in the sql queries `UK_it77eq964jhfqtu54081ebtio` , can you please explain or point to right resource. himanshu June 27, 2019 at 1:37 am - Reply also how did you integrate or create login page? or does it come automatically when you chose formlogin in secureconfig Abdullah-Al Tareq August 10, 2019 at 4:02 pm - Reply Please fix the User.java file. chandrashekhar August 14, 2019 at 5:24 pm - Reply Thanks Abdullah, updated the source.. Cheers! Chandra Shekhar G John September 18, 2019 at 8:25 pm - Reply Getting error: Your login attempt was not successful, try again. Reason: No value present Ramees June 12, 2020 at 12:28 pm - Reply Password is not checking W. Wallace January 15, 2019 at 10:25 am - Reply nice one. One question how can i make it “@PreAuthorize(“hasAnyRole(‘ADMIN’)”) ” generic ? @PreAuthorize(“hasAnyRole(‘< LIST OF GROUPS FROM DATABASE')") chandrashekhar January 15, 2019 at 11:26 am - Reply You can define the SQL query logic like the following.. @Component("app_roles") public class Roles{ @Value("${role.roleNames}") private String[] roles; public String[] getRoles() { // SQL goes here.. //this.roles = results; return this.roles; } } call the getRoles() method as below. @PreAuthorize("hasAnyRole(@app_roles.getRoles())") public ResponseEntity> getAllItems() {} It may help you. Thanks, Chandra Shekhar G nice one. One question how can i make it “@PreAuthorize(“hasAnyRole(‘ADMIN’)”) ” generic ? @PreAuthorize(“hasAnyRole(‘< LIST OF GROUPS FROM DATABASE')") chandrashekhar January 15, 2019 at 11:26 am - Reply You can define the SQL query logic like the following.. @Component("app_roles") public class Roles{ @Value("${role.roleNames}") private String[] roles; public String[] getRoles() { // SQL goes here.. //this.roles = results; return this.roles; } } call the getRoles() method as below. @PreAuthorize("hasAnyRole(@app_roles.getRoles())") public ResponseEntity> getAllItems() {} It may help you. Thanks, Chandra Shekhar G You can define the SQL query logic like the following.. @Component("app_roles") public class Roles{ @Value("${role.roleNames}") private String[] roles; public String[] getRoles() { // SQL goes here.. //this.roles = results; return this.roles; } } call the getRoles() method as below. @PreAuthorize("hasAnyRole(@app_roles.getRoles())") public ResponseEntity> getAllItems() {} It may help you. Thanks, Chandra Shekhar G himanshu June 27, 2019 at 1:20 am - Reply this is the least complex example of such type i could find. Thanks. I couldn’t understand the hashes you provided in the sql queries `UK_it77eq964jhfqtu54081ebtio` , can you please explain or point to right resource. this is the least complex example of such type i could find. Thanks. I couldn’t understand the hashes you provided in the sql queries `UK_it77eq964jhfqtu54081ebtio` , can you please explain or point to right resource. himanshu June 27, 2019 at 1:37 am - Reply also how did you integrate or create login page? or does it come automatically when you chose formlogin in secureconfig also how did you integrate or create login page? or does it come automatically when you chose formlogin in secureconfig Abdullah-Al Tareq August 10, 2019 at 4:02 pm - Reply Please fix the User.java file. chandrashekhar August 14, 2019 at 5:24 pm - Reply Thanks Abdullah, updated the source.. Cheers! Chandra Shekhar G Please fix the User.java file. chandrashekhar August 14, 2019 at 5:24 pm - Reply Thanks Abdullah, updated the source.. Cheers! Chandra Shekhar G Thanks Abdullah, updated the source.. Cheers! Chandra Shekhar G John September 18, 2019 at 8:25 pm - Reply Getting error: Your login attempt was not successful, try again. Reason: No value present Getting error: Your login attempt was not successful, try again. Reason: No value present Ramees June 12, 2020 at 12:28 pm - Reply Password is not checking Password is not checking Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "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": 510, "s": 398, "text": "In this tutorial, we are going to show how to secure spring boot rest services with MySQL database integration." }, { "code": null, "e": 752, "s": 510, "text": "In the previous example, we have discussed spring boot in-memory security where the user validation happened at in-memory, as part of this Spring Boot Security MySQL Database Integration the user validation takes place in the MySQL database." }, { "code": null, "e": 770, "s": 752, "text": "Spring Boot 2.0.6" }, { "code": null, "e": 786, "s": 770, "text": "Spring Boot WEB" }, { "code": null, "e": 808, "s": 786, "text": "Spring Security 2.0.6" }, { "code": null, "e": 829, "s": 808, "text": "Spring Boot Data JPA" }, { "code": null, "e": 842, "s": 829, "text": "MySQL 5.1.47" }, { "code": null, "e": 849, "s": 842, "text": "Java 8" }, { "code": null, "e": 1077, "s": 849, "text": "As part of this example, I am going to create a simple spring boot rest service which provides two different rest endpoints, one is – to say hello to you and another one is secured rest endpoint which provides all item details." }, { "code": null, "e": 1287, "s": 1077, "text": "Here we need 3 different tables such as USER, ROLE and USER_ROLE. The relationship between USER and ROLE is many to many because one USER can have multiple ROLES and one ROLE can be assigned to multiple USERS." }, { "code": null, "e": 1293, "s": 1287, "text": "USER:" }, { "code": null, "e": 1584, "s": 1293, "text": "CREATE TABLE `user` (\n `user_id` int(11) NOT NULL AUTO_INCREMENT,\n `active` int(11) DEFAULT NULL,\n `lastname` varchar(255) NOT NULL,\n `firstname` varchar(255) NOT NULL,\n `password` varchar(255) NOT NULL,\n PRIMARY KEY (`user_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1" }, { "code": null, "e": 1590, "s": 1584, "text": "ROLE:" }, { "code": null, "e": 1780, "s": 1590, "text": "CREATE TABLE `role` (\n `role_id` int(11) NOT NULL AUTO_INCREMENT,\n `role_name` varchar(255) DEFAULT NULL,\n PRIMARY KEY (`role_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1" }, { "code": null, "e": 1791, "s": 1780, "text": "USER_ROLE:" }, { "code": null, "e": 1901, "s": 1791, "text": "As per the normalization we need to have this intermediate table to represent the many to many relationships." }, { "code": null, "e": 2315, "s": 1901, "text": "CREATE TABLE `user_role` (\n `user_id` int(11) NOT NULL,\n `role_id` int(11) NOT NULL,\n PRIMARY KEY (`user_id`,`role_id`),\n UNIQUE KEY `UK_it77eq964jhfqtu54081ebtio` (`role_id`),\n CONSTRAINT `FK859n2jvi8ivhui0rl0esws6o` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`),\n CONSTRAINT `FKa68196081fvovjhkek5m97n3y` FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1" }, { "code": null, "e": 2328, "s": 2315, "text": "Insert Data:" }, { "code": null, "e": 2565, "s": 2328, "text": "-- creating user\ninsert into OTP.USER values(1,1,'shekhar','chandra','12345');\n-- creating ADMIN role\ninsert into OTP.ROLE values(1,'ADMIN');\n-- Mapping ADMIN role id (1) to shekhar user userid (1)\ninsert into OTP.USER_ROLE values(1,1);" }, { "code": null, "e": 4749, "s": 2565, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringBoot-Security-Mysql-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>SpringBoot-Security-Mysql-Example</name>\n <description>Spring Boot Security MySQL Database Integration Example</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.6.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-jpa</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-security</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>org.springframework.security</groupId>\n <artifactId>spring-security-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n" }, { "code": null, "e": 4784, "s": 4749, "text": "Database configuration properties." }, { "code": null, "e": 5056, "s": 4784, "text": "server.port=8080\nspring.datasource.driver-class-name: com.mysql.jdbc.Driver\nspring.datasource.url: jdbc:mysql://localhost:3306/otp\nspring.datasource.username: root\nspring.datasource.password: 12345\n\nspring.jpa.show-sql=true\nspring.jpa.properties.hibernate.format_sql=true" }, { "code": null, "e": 5084, "s": 5056, "text": "Item Model: Carrying Items." }, { "code": null, "e": 5483, "s": 5084, "text": "package com.onlinetutorialspoint.model;\n\nimport java.io.Serializable;\n\npublic class Item implements Serializable {\n private Integer id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(Integer id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n // Getters and Setters\n}\n" }, { "code": null, "e": 5506, "s": 5483, "text": "Creating JPA Entities:" }, { "code": null, "e": 5541, "s": 5506, "text": "User.java representing USER table." }, { "code": null, "e": 7386, "s": 5541, "text": "package com.onlinetutorialspoint.model;\n\nimport javax.persistence.*;\nimport java.util.Set;\n\n@Entity\n@Table(name=\"user\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name=\"user_id\")\n private int id;\n\n @Column(name=\"firstname\")\n private String firstName;\n\n @Column(name=\"lastname\")\n private String lastName;\n\n private String password;\n @Column(name=\"active\")\n private int isActive;\n\n @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)\n @JoinTable(name=\"user_role\",joinColumns = @JoinColumn(name = \"user_id\"), inverseJoinColumns = @JoinColumn(name = \"role_id\"))\n private Set roles;\n\n public User() {\n }\n\n public User(User user) {\n this.id = user.getId();\n this.firstName = user.getFirstName();\n this.lastName = user.getLastName();\n this.password = user.getPassword();\n this.isActive = user.getIsActive();\n this.roles = user.getRoles();\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public int getIsActive() {\n return isActive;\n }\n\n public void setIsActive(int isActive) {\n this.isActive = isActive;\n }\n\n public Set getRoles() {\n return roles;\n }\n\n public void setRoles(Set roles) {\n this.roles = roles;\n }\n" }, { "code": null, "e": 7421, "s": 7386, "text": "Role.java representing ROLE table." }, { "code": null, "e": 8114, "s": 7421, "text": "package com.onlinetutorialspoint.model;\n\nimport javax.persistence.*;\n\n@Entity\n@Table(name=\"role\")\npublic class Role {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"role_id\")\n private int id;\n\n @Column(name = \"role_name\")\n private String roleName;\n\n public Role() {\n }\n\n public Role(int id, String roleName) {\n this.id = id;\n this.roleName = roleName;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getRoleName() {\n return roleName;\n }\n\n public void setRoleName(String roleName) {\n this.roleName = roleName;\n }\n}\n" }, { "code": null, "e": 8139, "s": 8114, "text": "Creating JPA Repository." }, { "code": null, "e": 8444, "s": 8139, "text": "package com.onlinetutorialspoint.repos;\n\nimport com.onlinetutorialspoint.model.User;\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport java.util.Optional;\n\npublic interface UsersRepository extends JpaRepository<User, Integer> {\n Optional<User> findByFirstName(String firstname);\n}\n" }, { "code": null, "e": 8494, "s": 8444, "text": "Spring Security UserdetailService Implementation." }, { "code": null, "e": 9552, "s": 8494, "text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.model.User;\nimport com.onlinetutorialspoint.model.UserDetailsImpl;\nimport com.onlinetutorialspoint.repos.UsersRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.stereotype.Service;\n\nimport java.util.Optional;\n\n@Service\npublic class UserDetailsServiceImpl implements UserDetailsService {\n\n @Autowired\n private UsersRepository usersRepository;\n @Override\n public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {\n Optional<User> optionalUser = usersRepository.findByFirstName(userName);\n return Optional.ofNullable(optionalUser).orElseThrow(()->new UsernameNotFoundException(\"Username Not Found\"))\n .map(UserDetailsImpl::new).get();\n }\n}\n" }, { "code": null, "e": 9596, "s": 9552, "text": "Spring Security UserDetails implementation." }, { "code": null, "e": 10831, "s": 9596, "text": "package com.onlinetutorialspoint.model;\n\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.authority.SimpleGrantedAuthority;\nimport org.springframework.security.core.userdetails.UserDetails;\n\nimport java.util.Collection;\nimport java.util.stream.Collectors;\n\npublic class UserDetailsImpl extends User implements UserDetails {\n\n public UserDetailsImpl(User user) {\n super(user);\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return getRoles()\n .stream()\n .map(role-> new SimpleGrantedAuthority(\"ROLE_\"+role.getRoleName()))\n .collect(Collectors.toList());\n }\n\n @Override\n public String getPassword() {\n return super.getPassword();\n }\n\n @Override\n public String getUsername() {\n return super.getFirstName();\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}\n" }, { "code": null, "e": 10861, "s": 10831, "text": "Spring Security Configuration" }, { "code": null, "e": 12984, "s": 10861, "text": "package com.onlinetutorialspoint.configuration;\n\nimport com.onlinetutorialspoint.repos.UsersRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.data.jpa.repository.config.EnableJpaRepositories;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.crypto.password.PasswordEncoder;\n\n@EnableGlobalMethodSecurity(prePostEnabled = true)\n@Configuration\n@EnableWebSecurity\n@EnableJpaRepositories(basePackageClasses = UsersRepository.class)\npublic class SecureConfig extends WebSecurityConfigurerAdapter {\n\n @Autowired\n UserDetailsService userDetailsService;\n @Override\n protected void configure(AuthenticationManagerBuilder auth) throws Exception {\n auth.userDetailsService(userDetailsService)\n .passwordEncoder(getPasswordEncoder());\n }\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n\n http.csrf().disable();\n http.authorizeRequests()\n .antMatchers(\"**/getAllItems\").authenticated()\n .anyRequest().permitAll()\n .and().formLogin().permitAll();\n }\n\n private PasswordEncoder getPasswordEncoder() {\n return new PasswordEncoder() {\n @Override\n public String encode(CharSequence charSequence) {\n return charSequence.toString();\n }\n\n @Override\n public boolean matches(CharSequence charSequence, String s) {\n return true;\n }\n };\n }\n}\n" }, { "code": null, "e": 13064, "s": 12984, "text": "Creating the Rest Controller to provide /hello and /getAllItems rest endpoints." }, { "code": null, "e": 14493, "s": 13064, "text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.util.UriComponentsBuilder;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n@RestController\npublic class ItemController {\n\n @Autowired\n ItemController itemService;\n\n public static List<Item> items;\n static{\n items = new ArrayList<>(Arrays.asList(new Item(1,\"Spring Boot in Action\",\"Books\"),\n new Item(2,\"Java 8 in Action\",\"Books\"),\n new Item(3,\"Data Structures\",\"Books\"),\n new Item(4,\"Spring Boot Security\",\"Books\")));\n }\n\n @PreAuthorize(\"hasAnyRole('ADMIN')\")\n @RequestMapping(\"/getAllItems\")\n @ResponseBody\n public ResponseEntity<List<Item>> getAllItems() {\n //Reading all items (ADMIN only can access this)\n List<Item> items = this.items;\n System.out.println(\"Reading items: \"+items);\n return new ResponseEntity<List<Item>>(items, HttpStatus.OK);\n }\n\n @RequestMapping(\"/hello\")\n public String sayHello(){\n return \"Hello User!\";\n }\n\n}\n" }, { "code": null, "e": 14505, "s": 14493, "text": "Main class." }, { "code": null, "e": 14871, "s": 14505, "text": "\npackage com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootSecurityMysqlExampleApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringBootSecurityMysqlExampleApplication.class, args);\n\t}\n}\n" }, { "code": null, "e": 15960, "s": 14871, "text": "mvn spring-boot:run\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.0.6.RELEASE)\n\n2018-10-28 12:52:26.892 INFO 13656 --- [ main] pringBootSecurityMysqlExampleApplication : Starting SpringBootSecurityMysqlExampleApplication on DESKTOP-RN4SMHT with PID 13656 (E:\\work\\SpringBoot-Security-Mysql-Example\\target\\classes started by Lenovo in E:\\work\\SpringBoot-Security-Mysql-Example)\n2018-10-28 12:52:26.911 INFO 13656 --- [ main] pringBootSecurityMysqlExampleApplication : No active profile set, falling back to default profiles: default\n2018-10-28 12:52:27.142 INFO 13656 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@14dd7b39: startup date [Sun Oct 28 12:52:27 IST 2018]; root of context hierarchy\n.....\n....." }, { "code": null, "e": 15998, "s": 15960, "text": "Accessing /hello (unsecured) endpoint" }, { "code": null, "e": 16103, "s": 15998, "text": "Accessing /getAllItems secured endpoint — An ADMIN can access this endpoint with valid user credentials." }, { "code": null, "e": 16373, "s": 16103, "text": "As soon as we access the localhost:8080/getAllItems endpoint, the spring automatically redirects our request to the login page as it is a secured service. Here we have to provide our valid user credentials then only it will allow us to access the /getAllItems endpoint." }, { "code": null, "e": 16472, "s": 16373, "text": "Note: We haven’t created this login form at all. Spring has given us to provide the login details." }, { "code": null, "e": 16537, "s": 16472, "text": "Let’s provide invalid user credentials and see what will happen." }, { "code": null, "e": 16706, "s": 16537, "text": "Here I provided invalid username like shekhar123 and click on Login button, as a result, we should get the below error response saying login attempt was not successful." }, { "code": null, "e": 16763, "s": 16706, "text": "Let’s provide valid user credentials and see the result." }, { "code": null, "e": 16823, "s": 16763, "text": "Now we can able to see all items provided by rest endpoint." }, { "code": null, "e": 16844, "s": 16823, "text": "Spring Security Docs" }, { "code": null, "e": 16878, "s": 16844, "text": "Spring Boot JPA MySql Integration" }, { "code": null, "e": 16915, "s": 16878, "text": "Hibernate Many to Many Relationship " }, { "code": null, "e": 16932, "s": 16915, "text": "Happy Learning 🙂" }, { "code": null, "e": 17004, "s": 16932, "text": "\n\nSpringBoot-Security-Mysql-Example\n\nFile size: 108 KB\nDownloads: 2086\n" }, { "code": null, "e": 17698, "s": 17004, "text": "\nSpring Boot Environment Properties reading based on activeprofile\nSpring Boot In Memory Basic Authentication Security\nHow to change Spring Boot Tomcat Port Number\nHow To Change Spring Boot Context Path\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot JPA Integration Example\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot Hibernate Integration Example\nSpring Boot PDF iText integration with String Template\nSpring Boot Batch Example Csv to Database\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot Actuator Database Health Check\nHow to connect MySQL Database in Eclipse\nSpring Boot Multiple Data Sources Example\nSpring Boot Basic Authentication Example\n" }, { "code": null, "e": 17764, "s": 17698, "text": "Spring Boot Environment Properties reading based on activeprofile" }, { "code": null, "e": 17816, "s": 17764, "text": "Spring Boot In Memory Basic Authentication Security" }, { "code": null, "e": 17861, "s": 17816, "text": "How to change Spring Boot Tomcat Port Number" }, { "code": null, "e": 17900, "s": 17861, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 17953, "s": 17900, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 17989, "s": 17953, "text": "Spring Boot JPA Integration Example" }, { "code": null, "e": 18036, "s": 17989, "text": "Spring Boot JdbcTemplate CRUD Operations Mysql" }, { "code": null, "e": 18078, "s": 18036, "text": "Spring Boot Hibernate Integration Example" }, { "code": null, "e": 18133, "s": 18078, "text": "Spring Boot PDF iText integration with String Template" }, { "code": null, "e": 18175, "s": 18133, "text": "Spring Boot Batch Example Csv to Database" }, { "code": null, "e": 18223, "s": 18175, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 18266, "s": 18223, "text": "Spring Boot Actuator Database Health Check" }, { "code": null, "e": 18307, "s": 18266, "text": "How to connect MySQL Database in Eclipse" }, { "code": null, "e": 18349, "s": 18307, "text": "Spring Boot Multiple Data Sources Example" }, { "code": null, "e": 18390, "s": 18349, "text": "Spring Boot Basic Authentication Example" }, { "code": null, "e": 19975, "s": 18390, "text": "\n\n\n\n\n\nW. Wallace\nJanuary 15, 2019 at 10:25 am - Reply \n\nnice one. One question how can i make it “@PreAuthorize(“hasAnyRole(‘ADMIN’)”) ” generic ? @PreAuthorize(“hasAnyRole(‘< LIST OF GROUPS FROM DATABASE')\")\n\n\n\n\n\n\n\n\n\nchandrashekhar\nJanuary 15, 2019 at 11:26 am - Reply \n\nYou can define the SQL query logic like the following..\n@Component(\"app_roles\")\npublic class Roles{\n@Value(\"${role.roleNames}\")\nprivate String[] roles;\npublic String[] getRoles() {\n// SQL goes here..\n//this.roles = results;\nreturn this.roles;\n}\n}\ncall the getRoles() method as below.\n@PreAuthorize(\"hasAnyRole(@app_roles.getRoles())\")\npublic ResponseEntity> getAllItems() {}\nIt may help you.\nThanks,\nChandra Shekhar G\n\n\n\n\n\n\n\n\n\n\n\nhimanshu\nJune 27, 2019 at 1:20 am - Reply \n\nthis is the least complex example of such type i could find. Thanks.\nI couldn’t understand the hashes you provided in the sql queries `UK_it77eq964jhfqtu54081ebtio` , can you please explain or point to right resource.\n\n\n\n\n\n\n\n\n\nhimanshu\nJune 27, 2019 at 1:37 am - Reply \n\nalso how did you integrate or create login page? or does it come automatically when you chose formlogin in secureconfig\n\n\n\n\n\n\n\n\n\nAbdullah-Al Tareq\nAugust 10, 2019 at 4:02 pm - Reply \n\nPlease fix the User.java file.\n\n\n\n\n\n\n\n\n\nchandrashekhar\nAugust 14, 2019 at 5:24 pm - Reply \n\nThanks Abdullah, updated the source..\nCheers!\nChandra Shekhar G\n\n\n\n\n\n\n\n\n\n\n\nJohn\nSeptember 18, 2019 at 8:25 pm - Reply \n\nGetting error:\nYour login attempt was not successful, try again.\nReason: No value present\n\n\n\n\n\n\n\n\n\nRamees\nJune 12, 2020 at 12:28 pm - Reply \n\nPassword is not checking\n\n\n\n\n" }, { "code": null, "e": 20671, "s": 19975, "text": "\n\n\n\n\nW. Wallace\nJanuary 15, 2019 at 10:25 am - Reply \n\nnice one. One question how can i make it “@PreAuthorize(“hasAnyRole(‘ADMIN’)”) ” generic ? @PreAuthorize(“hasAnyRole(‘< LIST OF GROUPS FROM DATABASE')\")\n\n\n\n\n\n\n\n\n\nchandrashekhar\nJanuary 15, 2019 at 11:26 am - Reply \n\nYou can define the SQL query logic like the following..\n@Component(\"app_roles\")\npublic class Roles{\n@Value(\"${role.roleNames}\")\nprivate String[] roles;\npublic String[] getRoles() {\n// SQL goes here..\n//this.roles = results;\nreturn this.roles;\n}\n}\ncall the getRoles() method as below.\n@PreAuthorize(\"hasAnyRole(@app_roles.getRoles())\")\npublic ResponseEntity> getAllItems() {}\nIt may help you.\nThanks,\nChandra Shekhar G\n\n\n\n\n\n" }, { "code": null, "e": 20825, "s": 20671, "text": "nice one. One question how can i make it “@PreAuthorize(“hasAnyRole(‘ADMIN’)”) ” generic ? @PreAuthorize(“hasAnyRole(‘< LIST OF GROUPS FROM DATABASE')\")" }, { "code": null, "e": 21306, "s": 20825, "text": "\n\n\n\n\nchandrashekhar\nJanuary 15, 2019 at 11:26 am - Reply \n\nYou can define the SQL query logic like the following..\n@Component(\"app_roles\")\npublic class Roles{\n@Value(\"${role.roleNames}\")\nprivate String[] roles;\npublic String[] getRoles() {\n// SQL goes here..\n//this.roles = results;\nreturn this.roles;\n}\n}\ncall the getRoles() method as below.\n@PreAuthorize(\"hasAnyRole(@app_roles.getRoles())\")\npublic ResponseEntity> getAllItems() {}\nIt may help you.\nThanks,\nChandra Shekhar G\n\n\n\n" }, { "code": null, "e": 21553, "s": 21306, "text": "You can define the SQL query logic like the following..\n@Component(\"app_roles\")\npublic class Roles{\n@Value(\"${role.roleNames}\")\nprivate String[] roles;\npublic String[] getRoles() {\n// SQL goes here..\n//this.roles = results;\nreturn this.roles;\n}\n}" }, { "code": null, "e": 21681, "s": 21553, "text": "call the getRoles() method as below.\n@PreAuthorize(\"hasAnyRole(@app_roles.getRoles())\")\npublic ResponseEntity> getAllItems() {}" }, { "code": null, "e": 21698, "s": 21681, "text": "It may help you." }, { "code": null, "e": 21724, "s": 21698, "text": "Thanks,\nChandra Shekhar G" }, { "code": null, "e": 21995, "s": 21724, "text": "\n\n\n\n\nhimanshu\nJune 27, 2019 at 1:20 am - Reply \n\nthis is the least complex example of such type i could find. Thanks.\nI couldn’t understand the hashes you provided in the sql queries `UK_it77eq964jhfqtu54081ebtio` , can you please explain or point to right resource.\n\n\n\n" }, { "code": null, "e": 22064, "s": 21995, "text": "this is the least complex example of such type i could find. Thanks." }, { "code": null, "e": 22213, "s": 22064, "text": "I couldn’t understand the hashes you provided in the sql queries `UK_it77eq964jhfqtu54081ebtio` , can you please explain or point to right resource." }, { "code": null, "e": 22386, "s": 22213, "text": "\n\n\n\n\nhimanshu\nJune 27, 2019 at 1:37 am - Reply \n\nalso how did you integrate or create login page? or does it come automatically when you chose formlogin in secureconfig\n\n\n\n" }, { "code": null, "e": 22506, "s": 22386, "text": "also how did you integrate or create login page? or does it come automatically when you chose formlogin in secureconfig" }, { "code": null, "e": 22728, "s": 22506, "text": "\n\n\n\n\nAbdullah-Al Tareq\nAugust 10, 2019 at 4:02 pm - Reply \n\nPlease fix the User.java file.\n\n\n\n\n\n\n\n\n\nchandrashekhar\nAugust 14, 2019 at 5:24 pm - Reply \n\nThanks Abdullah, updated the source..\nCheers!\nChandra Shekhar G\n\n\n\n\n\n" }, { "code": null, "e": 22759, "s": 22728, "text": "Please fix the User.java file." }, { "code": null, "e": 22884, "s": 22759, "text": "\n\n\n\n\nchandrashekhar\nAugust 14, 2019 at 5:24 pm - Reply \n\nThanks Abdullah, updated the source..\nCheers!\nChandra Shekhar G\n\n\n\n" }, { "code": null, "e": 22922, "s": 22884, "text": "Thanks Abdullah, updated the source.." }, { "code": null, "e": 22948, "s": 22922, "text": "Cheers!\nChandra Shekhar G" }, { "code": null, "e": 23092, "s": 22948, "text": "\n\n\n\n\nJohn\nSeptember 18, 2019 at 8:25 pm - Reply \n\nGetting error:\nYour login attempt was not successful, try again.\nReason: No value present\n\n\n\n" }, { "code": null, "e": 23107, "s": 23092, "text": "Getting error:" }, { "code": null, "e": 23157, "s": 23107, "text": "Your login attempt was not successful, try again." }, { "code": null, "e": 23182, "s": 23157, "text": "Reason: No value present" }, { "code": null, "e": 23259, "s": 23182, "text": "\n\n\n\n\nRamees\nJune 12, 2020 at 12:28 pm - Reply \n\nPassword is not checking\n\n\n\n" }, { "code": null, "e": 23284, "s": 23259, "text": "Password is not checking" }, { "code": null, "e": 23290, "s": 23288, "text": "Δ" }, { "code": null, "e": 23317, "s": 23290, "text": " Spring Boot – Hello World" }, { "code": null, "e": 23344, "s": 23317, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 23378, "s": 23344, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 23419, "s": 23378, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 23464, "s": 23419, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 23502, "s": 23464, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 23536, "s": 23502, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 23567, "s": 23536, "text": " Spring Boot – Properties File" }, { "code": null, "e": 23601, "s": 23567, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 23634, "s": 23601, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 23667, "s": 23634, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 23707, "s": 23667, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 23732, "s": 23707, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 23763, "s": 23732, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 23787, "s": 23763, "text": " Spring Boot – Actuator" }, { "code": null, "e": 23833, "s": 23787, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 23856, "s": 23833, "text": " Spring Boot – Swagger" }, { "code": null, "e": 23883, "s": 23856, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 23929, "s": 23883, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 23969, "s": 23929, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 23998, "s": 23969, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 24032, "s": 23998, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 24062, "s": 24032, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 24098, "s": 24062, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 24131, "s": 24098, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 24164, "s": 24131, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 24208, "s": 24164, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 24242, "s": 24208, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 24274, "s": 24242, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 24302, "s": 24274, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 24333, "s": 24302, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 24374, "s": 24333, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 24408, "s": 24374, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 24433, "s": 24408, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 24467, "s": 24433, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 24503, "s": 24467, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 24549, "s": 24503, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 24600, "s": 24549, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 24642, "s": 24600, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 24673, "s": 24642, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 24696, "s": 24673, "text": " Spring Boot – EhCache" }, { "code": null, "e": 24726, "s": 24696, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 24756, "s": 24726, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 24805, "s": 24756, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 24839, "s": 24805, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 24872, "s": 24839, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 24901, "s": 24872, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 24933, "s": 24901, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 24970, "s": 24933, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 24999, "s": 24970, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 25028, "s": 24999, "text": " Spring Boot – MockMvc JUnit" } ]
C | Pointer Basics | Question 1 - GeeksforGeeks
04 Feb, 2013 What is the output of following program? # include <stdio.h>void fun(int x){ x = 30;} int main(){ int y = 20; fun(y); printf("%d", y); return 0;} (A) 30(B) 20(C) Compiler Error(D) Runtime ErrorAnswer: (B)Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using the function fun(). So how do we modify the value of a local variable of a function inside another function. Pointer is the solution to such problems. Using pointers, we can modify a local variable of a function inside another function. See the next question.Note that everything is passed by value in C. We only get the effect of pass by reference using pointers. C-Pointers Pointers C Language C Quiz Pointers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | Structure & Union | Question 10 Output of C programs | Set 64 (Pointers) C | Misc | Question 7
[ { "code": null, "e": 24232, "s": 24204, "text": "\n04 Feb, 2013" }, { "code": null, "e": 24273, "s": 24232, "text": "What is the output of following program?" }, { "code": "# include <stdio.h>void fun(int x){ x = 30;} int main(){ int y = 20; fun(y); printf(\"%d\", y); return 0;}", "e": 24386, "s": 24273, "text": null }, { "code": null, "e": 24929, "s": 24386, "text": "(A) 30(B) 20(C) Compiler Error(D) Runtime ErrorAnswer: (B)Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using the function fun(). So how do we modify the value of a local variable of a function inside another function. Pointer is the solution to such problems. Using pointers, we can modify a local variable of a function inside another function. See the next question.Note that everything is passed by value in C. We only get the effect of pass by reference using pointers." }, { "code": null, "e": 24940, "s": 24929, "text": "C-Pointers" }, { "code": null, "e": 24949, "s": 24940, "text": "Pointers" }, { "code": null, "e": 24960, "s": 24949, "text": "C Language" }, { "code": null, "e": 24967, "s": 24960, "text": "C Quiz" }, { "code": null, "e": 24976, "s": 24967, "text": "Pointers" }, { "code": null, "e": 25074, "s": 24976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25112, "s": 25074, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25132, "s": 25112, "text": "Multithreading in C" }, { "code": null, "e": 25158, "s": 25132, "text": "Exception Handling in C++" }, { "code": null, "e": 25199, "s": 25158, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25221, "s": 25199, "text": "'this' pointer in C++" }, { "code": null, "e": 25263, "s": 25221, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25306, "s": 25263, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25342, "s": 25306, "text": "C | Structure & Union | Question 10" }, { "code": null, "e": 25383, "s": 25342, "text": "Output of C programs | Set 64 (Pointers)" } ]
Bootstrap 4 | Pagination - GeeksforGeeks
10 Jun, 2019 Pagination is used to enable navigation between pages in a website. The pagination used in Bootstrap has a large block of connected links that are hard to miss and are easily scalable. Basic Pagination: The basic pagination can be specified using the following classes. The .pagination class is used to specify pagination on a list group. The .page-item class is used to specify each pagination item in the group. The .page-link class is used to specify the link in the pagination item. Example: <!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container"> <h1>Bootstrap 4 | Basic Pagination</h1> <!-- Declare the pagination class --> <ul class="pagination"> <!-- Declare the item in the group --> <li class="page-item"> <!-- Declare the link of the item --> <a class="page-link" href="#">Previous</a> </li> <!-- Rest of the pagination items --> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </div></body></html> Output: Disabled State: The pagination links could be styled to make them appear unclickable by using the .disabled class. This may be used for disabling the ‘Previous’ or ‘Next’ button. The .disabled class internally makes use of ‘pointer-events: none’ to make the link unclickable, however, as this specification is not always implemented, it is preferred to make it not possible to be navigated to by setting the ‘tabindex’ property to -1. This property controls whether an element can be navigated using the tab key. Example: <!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container"> <h1>Bootstrap 4 | Pagination Disabled State</h1> <!-- Declare the pagination class --> <ul class="pagination"> <!-- Specify the disabled class to style this item disabled --> <li class="page-item disabled"> <!-- Specify tabindex to make the link non navigatable --> <a class="page-link" href="#" tabindex="-1">Previous</a> </li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </div></body></html> Output: Active State: The pagination links could be styled to highlight them as the current active page by using the .active class on the pagination item. Example: <!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container"> <h1>Bootstrap 4 | Pagination Active State</h1> <!-- Declare the pagination class --> <ul class="pagination"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <!-- Specify the active class to style this item active --> <li class="page-item active"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </div></body></html> Output: Sizing the pagination group: The pagination group could be made larger or smaller by using additional classes. There are 3 possible sizes of input groups. The .pagination-sm class is used for a smaller size. The .pagination-lg class is used for a larger size. The .pagination class is the default size. Example: <!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container"> <h1>Bootstrap 4 | Pagination Sizing</h1> <b>Large Pagination</b> <!-- Specify pagination-lg for large pagination group --> <ul class="pagination pagination-lg"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> <b>Small Pagination</b> <!-- Specify pagination-sm for small pagination group --> <ul class="pagination pagination-sm"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> <b>Normal Pagination</b> <!-- Normal size pagination --> <ul class="pagination"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </div></body></html> Output: Alignment of the pagination group: The pagination group could be aligned to the right or center by using the flexbox utility classes. The .justify-content-center class is used to align the group to the center. The .justify-content-end class is used to align the group to the right. Example: <!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <div class="container"> <h1>Bootstrap 4 | Pagination Alignment</h1> <b>Align to the center</b> <!-- Specify justify-content-center to align to the center --> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> <b>Align to the right</b> <!-- Specify justify-content-end to align to the right --> <ul class="pagination justify-content-end"> <li class="page-item"> <a class="page-link" href="#">Previous</a> </li> <li class="page-item"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </div></body></html> Output: Bootstrap-4 Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 28440, "s": 28412, "text": "\n10 Jun, 2019" }, { "code": null, "e": 28625, "s": 28440, "text": "Pagination is used to enable navigation between pages in a website. The pagination used in Bootstrap has a large block of connected links that are hard to miss and are easily scalable." }, { "code": null, "e": 28643, "s": 28625, "text": "Basic Pagination:" }, { "code": null, "e": 28710, "s": 28643, "text": "The basic pagination can be specified using the following classes." }, { "code": null, "e": 28779, "s": 28710, "text": "The .pagination class is used to specify pagination on a list group." }, { "code": null, "e": 28854, "s": 28779, "text": "The .page-item class is used to specify each pagination item in the group." }, { "code": null, "e": 28927, "s": 28854, "text": "The .page-link class is used to specify the link in the pagination item." }, { "code": null, "e": 28936, "s": 28927, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container\"> <h1>Bootstrap 4 | Basic Pagination</h1> <!-- Declare the pagination class --> <ul class=\"pagination\"> <!-- Declare the item in the group --> <li class=\"page-item\"> <!-- Declare the link of the item --> <a class=\"page-link\" href=\"#\">Previous</a> </li> <!-- Rest of the pagination items --> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </div></body></html>", "e": 30442, "s": 28936, "text": null }, { "code": null, "e": 30450, "s": 30442, "text": "Output:" }, { "code": null, "e": 30466, "s": 30450, "text": "Disabled State:" }, { "code": null, "e": 30629, "s": 30466, "text": "The pagination links could be styled to make them appear unclickable by using the .disabled class. This may be used for disabling the ‘Previous’ or ‘Next’ button." }, { "code": null, "e": 30963, "s": 30629, "text": "The .disabled class internally makes use of ‘pointer-events: none’ to make the link unclickable, however, as this specification is not always implemented, it is preferred to make it not possible to be navigated to by setting the ‘tabindex’ property to -1. This property controls whether an element can be navigated using the tab key." }, { "code": null, "e": 30972, "s": 30963, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container\"> <h1>Bootstrap 4 | Pagination Disabled State</h1> <!-- Declare the pagination class --> <ul class=\"pagination\"> <!-- Specify the disabled class to style this item disabled --> <li class=\"page-item disabled\"> <!-- Specify tabindex to make the link non navigatable --> <a class=\"page-link\" href=\"#\" tabindex=\"-1\">Previous</a> </li> <li class=\"page-item\"><a class=\"page-link\" href=\"#\">1</a></li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"><a class=\"page-link\" href=\"#\">3</a></li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </div></body></html>", "e": 32405, "s": 30972, "text": null }, { "code": null, "e": 32413, "s": 32405, "text": "Output:" }, { "code": null, "e": 32427, "s": 32413, "text": "Active State:" }, { "code": null, "e": 32560, "s": 32427, "text": "The pagination links could be styled to highlight them as the current active page by using the .active class on the pagination item." }, { "code": null, "e": 32569, "s": 32560, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container\"> <h1>Bootstrap 4 | Pagination Active State</h1> <!-- Declare the pagination class --> <ul class=\"pagination\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"><a class=\"page-link\" href=\"#\">1</a></li> <li class=\"page-item\"><a class=\"page-link\" href=\"#\">2</a></li> <!-- Specify the active class to style this item active --> <li class=\"page-item active\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </div></body></html>", "e": 33920, "s": 32569, "text": null }, { "code": null, "e": 33928, "s": 33920, "text": "Output:" }, { "code": null, "e": 33957, "s": 33928, "text": "Sizing the pagination group:" }, { "code": null, "e": 34083, "s": 33957, "text": "The pagination group could be made larger or smaller by using additional classes. There are 3 possible sizes of input groups." }, { "code": null, "e": 34136, "s": 34083, "text": "The .pagination-sm class is used for a smaller size." }, { "code": null, "e": 34188, "s": 34136, "text": "The .pagination-lg class is used for a larger size." }, { "code": null, "e": 34231, "s": 34188, "text": "The .pagination class is the default size." }, { "code": null, "e": 34240, "s": 34231, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container\"> <h1>Bootstrap 4 | Pagination Sizing</h1> <b>Large Pagination</b> <!-- Specify pagination-lg for large pagination group --> <ul class=\"pagination pagination-lg\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> <b>Small Pagination</b> <!-- Specify pagination-sm for small pagination group --> <ul class=\"pagination pagination-sm\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> <b>Normal Pagination</b> <!-- Normal size pagination --> <ul class=\"pagination\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </div></body></html>", "e": 36927, "s": 34240, "text": null }, { "code": null, "e": 36935, "s": 36927, "text": "Output:" }, { "code": null, "e": 36970, "s": 36935, "text": "Alignment of the pagination group:" }, { "code": null, "e": 37069, "s": 36970, "text": "The pagination group could be aligned to the right or center by using the flexbox utility classes." }, { "code": null, "e": 37145, "s": 37069, "text": "The .justify-content-center class is used to align the group to the center." }, { "code": null, "e": 37217, "s": 37145, "text": "The .justify-content-end class is used to align the group to the right." }, { "code": null, "e": 37226, "s": 37217, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap 4 | Pagination</title><meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <div class=\"container\"> <h1>Bootstrap 4 | Pagination Alignment</h1> <b>Align to the center</b> <!-- Specify justify-content-center to align to the center --> <ul class=\"pagination justify-content-center\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> <b>Align to the right</b> <!-- Specify justify-content-end to align to the right --> <ul class=\"pagination justify-content-end\"> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Previous</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">1</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">2</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">3</a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"#\">Next</a> </li> </ul> </div></body></html>", "e": 39301, "s": 37226, "text": null }, { "code": null, "e": 39309, "s": 39301, "text": "Output:" }, { "code": null, "e": 39321, "s": 39309, "text": "Bootstrap-4" }, { "code": null, "e": 39328, "s": 39321, "text": "Picked" }, { "code": null, "e": 39338, "s": 39328, "text": "Bootstrap" }, { "code": null, "e": 39355, "s": 39338, "text": "Web Technologies" }, { "code": null, "e": 39453, "s": 39355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39503, "s": 39453, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 39532, "s": 39503, "text": "Form validation using jQuery" }, { "code": null, "e": 39588, "s": 39532, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 39629, "s": 39588, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 39670, "s": 39629, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 39712, "s": 39670, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39745, "s": 39712, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39788, "s": 39745, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 39838, "s": 39788, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to find length of a string without string.h and loop in C? - GeeksforGeeks
26 Oct, 2020 Find the length of a string without using any loops and string.h in C. Your program is supposed to behave in following way: Enter a string: GeeksforGeeks (Say user enters GeeksforGeeks) Entered string is: GeeksforGeeks Length is: 13 You may assume that the length of entered string is always less than 100.The following is the solution. C #include <stdio.h>int main(){ // entered string char ch[50] = "GeeksforGeeks"; // printing entered string printf("Entered String is:"); // returns length of string // along printing string int len = printf("%s\n", ch); printf("Length is:"); // printing length printf("%d", len - 1);} Entered String is:GeeksforGeeks Length is:13 The idea is to use return values of printf(). printf() returns the number of characters successfully written on output.In the above program we just use the property of printf() as it returns the number of characters entered in the array string. Another way of finding the length of a string without using string.h or loops is Recursion. The following program does the work of finding a length of a string using recursion. C // C program for the above approach#include <stdio.h> void LengthofString(int n,char *string){ if(string[n] == '\0') { printf("%i",n); return; } LengthofString(n+1,string); //printf("%c",string[n]);} int main(){ char string[100]; printf("Give a string : \n"); scanf("%s",string); printf("Entered string is:%s\n", string); LengthofString(0,string); return 0;} Give a string : Entered string is:0 1 The Function LengthofString calls itself until the character of string is’nt a null character it calls itself, when it calls itself it increases the value of the variable ‘n’ which stores number of times the function has been called and when it encounters the null character the function prints the value of ‘n’ and returns back in the same direction in which it was executed.This article is contributed by Sumit Singh Chauhan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Zeeking99 sc047108 C-String C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ UDP Server-Client implementation in C Understanding "extern" keyword in C Smart Pointers in C++ and How to Use Them Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second) Multiple Inheritance in C++
[ { "code": null, "e": 24232, "s": 24204, "text": "\n26 Oct, 2020" }, { "code": null, "e": 24357, "s": 24232, "text": "Find the length of a string without using any loops and string.h in C. Your program is supposed to behave in following way: " }, { "code": null, "e": 24468, "s": 24357, "text": "Enter a string: GeeksforGeeks (Say user enters GeeksforGeeks)\nEntered string is: GeeksforGeeks\nLength is: 13\n\n" }, { "code": null, "e": 24573, "s": 24468, "text": "You may assume that the length of entered string is always less than 100.The following is the solution. " }, { "code": null, "e": 24575, "s": 24573, "text": "C" }, { "code": "#include <stdio.h>int main(){ // entered string char ch[50] = \"GeeksforGeeks\"; // printing entered string printf(\"Entered String is:\"); // returns length of string // along printing string int len = printf(\"%s\\n\", ch); printf(\"Length is:\"); // printing length printf(\"%d\", len - 1);}", "e": 24913, "s": 24575, "text": null }, { "code": null, "e": 24959, "s": 24913, "text": "Entered String is:GeeksforGeeks\nLength is:13\n" }, { "code": null, "e": 25206, "s": 24959, "text": "The idea is to use return values of printf(). printf() returns the number of characters successfully written on output.In the above program we just use the property of printf() as it returns the number of characters entered in the array string. " }, { "code": null, "e": 25385, "s": 25206, "text": "Another way of finding the length of a string without using string.h or loops is Recursion. The following program does the work of finding a length of a string using recursion. " }, { "code": null, "e": 25387, "s": 25385, "text": "C" }, { "code": "// C program for the above approach#include <stdio.h> void LengthofString(int n,char *string){ if(string[n] == '\\0') { printf(\"%i\",n); return; } LengthofString(n+1,string); //printf(\"%c\",string[n]);} int main(){ char string[100]; printf(\"Give a string : \\n\"); scanf(\"%s\",string); printf(\"Entered string is:%s\\n\", string); LengthofString(0,string); return 0;}", "e": 25803, "s": 25387, "text": null }, { "code": null, "e": 25843, "s": 25803, "text": "Give a string : \nEntered string is:0\n1\n" }, { "code": null, "e": 26396, "s": 25843, "text": "The Function LengthofString calls itself until the character of string is’nt a null character it calls itself, when it calls itself it increases the value of the variable ‘n’ which stores number of times the function has been called and when it encounters the null character the function prints the value of ‘n’ and returns back in the same direction in which it was executed.This article is contributed by Sumit Singh Chauhan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26406, "s": 26396, "text": "Zeeking99" }, { "code": null, "e": 26415, "s": 26406, "text": "sc047108" }, { "code": null, "e": 26424, "s": 26415, "text": "C-String" }, { "code": null, "e": 26435, "s": 26424, "text": "C Language" }, { "code": null, "e": 26533, "s": 26435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26571, "s": 26533, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26591, "s": 26571, "text": "Multithreading in C" }, { "code": null, "e": 26617, "s": 26591, "text": "Exception Handling in C++" }, { "code": null, "e": 26658, "s": 26617, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26680, "s": 26658, "text": "'this' pointer in C++" }, { "code": null, "e": 26718, "s": 26680, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26754, "s": 26718, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26796, "s": 26754, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26862, "s": 26796, "text": "Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)" } ]
How to plot two Pandas time series on the same plot with legends and secondary Y-axis in Matplotlib?
To plot two Pandas time series on the sameplot with legends and secondary Y-axis, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a one-dimensional ndarray with axis labels (including time series). Create a one-dimensional ndarray with axis labels (including time series). Make a dataframe with some column list. Make a dataframe with some column list. Plot columns A and B using dataframe plot() method. Plot columns A and B using dataframe plot() method. Return the handles and labels for the legend using get_legend_handles_labels() method. Return the handles and labels for the legend using get_legend_handles_labels() method. Place a legend on the figure using legend() method. Place a legend on the figure using legend() method. To display the figure, use show() method. To display the figure, use show() method. import pandas as pd from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True ts = pd.Series(np.random.randn(10), index=pd.date_range('2021-04-10', periods=10)) df = pd.DataFrame(np.random.randn(10, 4), index=ts.index, columns=list('ABCD')) ax1 = df.A.plot(color='red', label='Count') ax2 = df.B.plot(color='yellow', secondary_y=True, label='Sum') h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() plt.legend(h1+h2, l1+l2, loc=2) plt.show()
[ { "code": null, "e": 1178, "s": 1062, "text": "To plot two Pandas time series on the sameplot with legends and secondary Y-axis, we can take the following steps −" }, { "code": null, "e": 1254, "s": 1178, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1330, "s": 1254, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1405, "s": 1330, "text": "Create a one-dimensional ndarray with axis labels (including time series)." }, { "code": null, "e": 1480, "s": 1405, "text": "Create a one-dimensional ndarray with axis labels (including time series)." }, { "code": null, "e": 1520, "s": 1480, "text": "Make a dataframe with some column list." }, { "code": null, "e": 1560, "s": 1520, "text": "Make a dataframe with some column list." }, { "code": null, "e": 1612, "s": 1560, "text": "Plot columns A and B using dataframe plot() method." }, { "code": null, "e": 1664, "s": 1612, "text": "Plot columns A and B using dataframe plot() method." }, { "code": null, "e": 1751, "s": 1664, "text": "Return the handles and labels for the legend using get_legend_handles_labels() method." }, { "code": null, "e": 1838, "s": 1751, "text": "Return the handles and labels for the legend using get_legend_handles_labels() method." }, { "code": null, "e": 1890, "s": 1838, "text": "Place a legend on the figure using legend() method." }, { "code": null, "e": 1942, "s": 1890, "text": "Place a legend on the figure using legend() method." }, { "code": null, "e": 1984, "s": 1942, "text": "To display the figure, use show() method." }, { "code": null, "e": 2026, "s": 1984, "text": "To display the figure, use show() method." }, { "code": null, "e": 2591, "s": 2026, "text": "import pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nts = pd.Series(np.random.randn(10), index=pd.date_range('2021-04-10', periods=10))\n\ndf = pd.DataFrame(np.random.randn(10, 4), index=ts.index, columns=list('ABCD'))\n\nax1 = df.A.plot(color='red', label='Count')\nax2 = df.B.plot(color='yellow', secondary_y=True, label='Sum')\n\nh1, l1 = ax1.get_legend_handles_labels()\nh2, l2 = ax2.get_legend_handles_labels()\n\nplt.legend(h1+h2, l1+l2, loc=2)\n\nplt.show()" } ]
Construct Binary Tree from given Parent Array representation - GeeksforGeeks
20 Jan, 2022 Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation.Examples: Input: parent[] = {1, 5, 5, 2, 2, -1, 3} Output: root of below tree 5 / \ 1 2 / / \ 0 3 4 / 6 Explanation: Index of -1 is 5. So 5 is root. 5 is present at indexes 1 and 2. So 1 and 2 are children of 5. 1 is present at index 0, so 0 is child of 1. 2 is present at indexes 3 and 4. So 3 and 4 are children of 2. 3 is present at index 6, so 6 is child of 3. Input: parent[] = {-1, 0, 0, 1, 1, 3, 5}; Output: root of below tree 0 / \ 1 2 / \ 3 4 / 5 / 6 Expected time complexity is O(n) where n is number of elements in given array. We strongly recommend to minimize your browser and try this yourself first.A Simple Solution to recursively construct by first searching the current root, then recurring for the found indexes (there can be at most two indexes) and making them left and right subtrees of root. This solution takes O(n2) as we have to linearly search for every node.An Efficient Solution can solve the above problem in O(n) time. The idea is to use extra space. An array created[0..n-1] is used to keep track of created nodes. createTree(parent[], n) Create an array of pointers say created[0..n-1]. The value of created[i] is NULL if node for index i is not created, else value is pointer to the created node.Do following for every index i of given array createNode(parent, i, created) Create an array of pointers say created[0..n-1]. The value of created[i] is NULL if node for index i is not created, else value is pointer to the created node. Do following for every index i of given array createNode(parent, i, created) createNode(parent[], i, created[]) If created[i] is not NULL, then node is already created. So return.Create a new node with value ‘i’.If parent[i] is -1 (i is root), make created node as root and return.Check if parent of ‘i’ is created (We can check this by checking if created[parent[i]] is NULL or not.If parent is not created, recur for parent and create the parent first.Let the pointer to parent be p. If p->left is NULL, then make the new node as left child. Else make the new node as right child of parent. If created[i] is not NULL, then node is already created. So return. Create a new node with value ‘i’. If parent[i] is -1 (i is root), make created node as root and return. Check if parent of ‘i’ is created (We can check this by checking if created[parent[i]] is NULL or not. If parent is not created, recur for parent and create the parent first. Let the pointer to parent be p. If p->left is NULL, then make the new node as left child. Else make the new node as right child of parent. Following is C++ implementation of above idea. C++ Java Python3 C# Javascript // C++ program to construct a Binary Tree from parent array#include<bits/stdc++.h>using namespace std; // A tree nodestruct Node{ int key; struct Node *left, *right;}; // Utility function to create new NodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Creates a node with key as 'i'. If i is root, then it changes// root. If parent of i is not created, then it creates parent firstvoid createNode(int parent[], int i, Node *created[], Node **root){ // If this node is already created if (created[i] != NULL) return; // Create a new node and set created[i] created[i] = newNode(i); // If 'i' is root, change root pointer and return if (parent[i] == -1) { *root = created[i]; return; } // If parent is not created, then create parent first if (created[parent[i]] == NULL) createNode(parent, parent[i], created, root); // Find parent pointer Node *p = created[parent[i]]; // If this is first child of parent if (p->left == NULL) p->left = created[i]; else // If second child p->right = created[i];} // Creates tree from parent[0..n-1] and returns root of the created treeNode *createTree(int parent[], int n){ // Create an array created[] to keep track // of created nodes, initialize all entries // as NULL Node *created[n]; for (int i=0; i<n; i++) created[i] = NULL; Node *root = NULL; for (int i=0; i<n; i++) createNode(parent, i, created, &root); return root;} //For adding new line in a programinline void newLine(){ cout << "\n";} // Utility function to do inorder traversalvoid inorder(Node *root){ if (root != NULL) { inorder(root->left); cout << root->key << " "; inorder(root->right); }} // Driver methodint main(){ int parent[] = {-1, 0, 0, 1, 1, 3, 5}; int n = sizeof parent / sizeof parent[0]; Node *root = createTree(parent, n); cout << "Inorder Traversal of constructed tree\n"; inorder(root); newLine();} // Java program to construct a binary tree from parent array // A binary tree nodeclass Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; // Creates a node with key as 'i'. If i is root, then it changes // root. If parent of i is not created, then it creates parent first void createNode(int parent[], int i, Node created[]) { // If this node is already created if (created[i] != null) return; // Create a new node and set created[i] created[i] = new Node(i); // If 'i' is root, change root pointer and return if (parent[i] == -1) { root = created[i]; return; } // If parent is not created, then create parent first if (created[parent[i]] == null) createNode(parent, parent[i], created); // Find parent pointer Node p = created[parent[i]]; // If this is first child of parent if (p.left == null) p.left = created[i]; else // If second child p.right = created[i]; } /* Creates tree from parent[0..n-1] and returns root of the created tree */ Node createTree(int parent[], int n) { // Create an array created[] to keep track // of created nodes, initialize all entries // as NULL Node[] created = new Node[n]; for (int i = 0; i < n; i++) created[i] = null; for (int i = 0; i < n; i++) createNode(parent, i, created); return root; } //For adding new line in a program void newLine() { System.out.println(""); } // Utility function to do inorder traversal void inorder(Node node) { if (node != null) { inorder(node.left); System.out.print(node.key + " "); inorder(node.right); } } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5}; int n = parent.length; Node node = tree.createTree(parent, n); System.out.println("Inorder traversal of constructed tree "); tree.inorder(node); tree.newLine(); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python implementation to construct a Binary Tree from# parent array # A node structureclass Node: # A utility function to create a new node def __init__(self, key): self.key = key self.left = None self.right = None """ Creates a node with key as 'i'. If i is root,then it changes root. If parent of i is not created, then it creates parent first"""def createNode(parent, i, created, root): # If this node is already created if created[i] is not None: return # Create a new node and set created[i] created[i] = Node(i) # If 'i' is root, change root pointer and return if parent[i] == -1: root[0] = created[i] # root[0] denotes root of the tree return # If parent is not created, then create parent first if created[parent[i]] is None: createNode(parent, parent[i], created, root ) # Find parent pointer p = created[parent[i]] # If this is first child of parent if p.left is None: p.left = created[i] # If second child else: p.right = created[i] # Creates tree from parent[0..n-1] and returns root of the# created treedef createTree(parent): n = len(parent) # Create and array created[] to keep track # of created nodes, initialize all entries as None created = [None for i in range(n+1)] root = [None] for i in range(n): createNode(parent, i, created, root) return root[0] #Inorder traversal of treedef inorder(root): if root is not None: inorder(root.left) print (root.key,end=" ") inorder(root.right) # Driver Methodparent = [-1, 0, 0, 1, 1, 3, 5]root = createTree(parent)print ("Inorder Traversal of constructed tree")inorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to construct a binary// tree from parent arrayusing System; // A binary tree nodepublic class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} class GFG{public Node root; // Creates a node with key as 'i'.// If i is root, then it changes// root. If parent of i is not created,// then it creates parent firstpublic virtual void createNode(int[] parent, int i, Node[] created){ // If this node is already created if (created[i] != null) { return; } // Create a new node and set created[i] created[i] = new Node(i); // If 'i' is root, change root // pointer and return if (parent[i] == -1) { root = created[i]; return; } // If parent is not created, then // create parent first if (created[parent[i]] == null) { createNode(parent, parent[i], created); } // Find parent pointer Node p = created[parent[i]]; // If this is first child of parent if (p.left == null) { p.left = created[i]; } else // If second child { p.right = created[i]; }} /* Creates tree from parent[0..n-1]and returns root of the created tree */public virtual Node createTree(int[] parent, int n){ // Create an array created[] to // keep track of created nodes, // initialize all entries as NULL Node[] created = new Node[n]; for (int i = 0; i < n; i++) { created[i] = null; } for (int i = 0; i < n; i++) { createNode(parent, i, created); } return root;} // For adding new line in a programpublic virtual void newLine(){ Console.WriteLine("");} // Utility function to do inorder traversalpublic virtual void inorder(Node node){ if (node != null) { inorder(node.left); Console.Write(node.key + " "); inorder(node.right); }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); int[] parent = new int[]{-1, 0, 0, 1, 1, 3, 5}; int n = parent.Length; Node node = tree.createTree(parent, n); Console.WriteLine("Inorder traversal of " + "constructed tree "); tree.inorder(node); tree.newLine();}} // This code is contributed by Shrikant13 <script> // Javascript program to construct a binary// tree from parent array // A binary tree nodeclass Node{ constructor(key) { this.key = key; this.left = null; this.right = null; }} var root = null; // Creates a node with key as 'i'.// If i is root, then it changes// root. If parent of i is not created,// then it creates parent firstfunction createNode(parent, i, created){ // If this node is already created if (created[i] != null) { return; } // Create a new node and set created[i] created[i] = new Node(i); // If 'i' is root, change root // pointer and return if (parent[i] == -1) { root = created[i]; return; } // If parent is not created, then // create parent first if (created[parent[i]] == null) { createNode(parent, parent[i], created); } // Find parent pointer var p = created[parent[i]]; // If this is first child of parent if (p.left == null) { p.left = created[i]; } else // If second child { p.right = created[i]; }} /* Creates tree from parent[0..n-1]and returns root of the created tree */function createTree(parent, n){ // Create an array created[] to // keep track of created nodes, // initialize all entries as NULL var created = Array(n); for (var i = 0; i < n; i++) { created[i] = null; } for (var i = 0; i < n; i++) { createNode(parent, i, created); } return root;} // For adding new line in a programfunction newLine(){ document.write("");} // Utility function to do inorder traversalfunction inorder(node){ if (node != null) { inorder(node.left); document.write(node.key + " "); inorder(node.right); }} // Driver Codevar parent = [-1, 0, 0, 1, 1, 3, 5];var n = parent.length;var node = createTree(parent, n);document.write("Inorder traversal of " + "constructed tree<br>");inorder(node);newLine(); // This code is contributed by rrrtnx. </script> Output: Inorder Traversal of constructed tree 6 5 3 1 4 0 2 Similar Problem: Find Height of Binary Tree represented by Parent arrayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 rrrtnx kapoorsagar226 amartyaghoshgfg Amazon Microsoft Snapdeal Tree Amazon Microsoft Snapdeal Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 2 (Properties) Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree Sorted Array to Balanced BST Expression Tree Binary Tree (Array implementation) Relationship between number of nodes and height of binary tree
[ { "code": null, "e": 25104, "s": 25076, "text": "\n20 Jan, 2022" }, { "code": null, "e": 25467, "s": 25104, "text": "Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation.Examples: " }, { "code": null, "e": 26041, "s": 25467, "text": "Input: parent[] = {1, 5, 5, 2, 2, -1, 3}\nOutput: root of below tree\n 5\n / \\\n 1 2\n / / \\\n 0 3 4\n /\n 6 \nExplanation: \nIndex of -1 is 5. So 5 is root. \n5 is present at indexes 1 and 2. So 1 and 2 are\nchildren of 5. \n1 is present at index 0, so 0 is child of 1.\n2 is present at indexes 3 and 4. So 3 and 4 are\nchildren of 2. \n3 is present at index 6, so 6 is child of 3.\n\n\nInput: parent[] = {-1, 0, 0, 1, 1, 3, 5};\nOutput: root of below tree\n 0\n / \\\n 1 2\n / \\\n 3 4\n /\n 5 \n /\n6" }, { "code": null, "e": 26121, "s": 26041, "text": "Expected time complexity is O(n) where n is number of elements in given array. " }, { "code": null, "e": 26655, "s": 26121, "text": "We strongly recommend to minimize your browser and try this yourself first.A Simple Solution to recursively construct by first searching the current root, then recurring for the found indexes (there can be at most two indexes) and making them left and right subtrees of root. This solution takes O(n2) as we have to linearly search for every node.An Efficient Solution can solve the above problem in O(n) time. The idea is to use extra space. An array created[0..n-1] is used to keep track of created nodes. createTree(parent[], n) " }, { "code": null, "e": 26891, "s": 26655, "text": "Create an array of pointers say created[0..n-1]. The value of created[i] is NULL if node for index i is not created, else value is pointer to the created node.Do following for every index i of given array createNode(parent, i, created)" }, { "code": null, "e": 27051, "s": 26891, "text": "Create an array of pointers say created[0..n-1]. The value of created[i] is NULL if node for index i is not created, else value is pointer to the created node." }, { "code": null, "e": 27128, "s": 27051, "text": "Do following for every index i of given array createNode(parent, i, created)" }, { "code": null, "e": 27165, "s": 27128, "text": "createNode(parent[], i, created[]) " }, { "code": null, "e": 27646, "s": 27165, "text": "If created[i] is not NULL, then node is already created. So return.Create a new node with value ‘i’.If parent[i] is -1 (i is root), make created node as root and return.Check if parent of ‘i’ is created (We can check this by checking if created[parent[i]] is NULL or not.If parent is not created, recur for parent and create the parent first.Let the pointer to parent be p. If p->left is NULL, then make the new node as left child. Else make the new node as right child of parent." }, { "code": null, "e": 27714, "s": 27646, "text": "If created[i] is not NULL, then node is already created. So return." }, { "code": null, "e": 27748, "s": 27714, "text": "Create a new node with value ‘i’." }, { "code": null, "e": 27818, "s": 27748, "text": "If parent[i] is -1 (i is root), make created node as root and return." }, { "code": null, "e": 27921, "s": 27818, "text": "Check if parent of ‘i’ is created (We can check this by checking if created[parent[i]] is NULL or not." }, { "code": null, "e": 27993, "s": 27921, "text": "If parent is not created, recur for parent and create the parent first." }, { "code": null, "e": 28132, "s": 27993, "text": "Let the pointer to parent be p. If p->left is NULL, then make the new node as left child. Else make the new node as right child of parent." }, { "code": null, "e": 28181, "s": 28132, "text": "Following is C++ implementation of above idea. " }, { "code": null, "e": 28185, "s": 28181, "text": "C++" }, { "code": null, "e": 28190, "s": 28185, "text": "Java" }, { "code": null, "e": 28198, "s": 28190, "text": "Python3" }, { "code": null, "e": 28201, "s": 28198, "text": "C#" }, { "code": null, "e": 28212, "s": 28201, "text": "Javascript" }, { "code": "// C++ program to construct a Binary Tree from parent array#include<bits/stdc++.h>using namespace std; // A tree nodestruct Node{ int key; struct Node *left, *right;}; // Utility function to create new NodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Creates a node with key as 'i'. If i is root, then it changes// root. If parent of i is not created, then it creates parent firstvoid createNode(int parent[], int i, Node *created[], Node **root){ // If this node is already created if (created[i] != NULL) return; // Create a new node and set created[i] created[i] = newNode(i); // If 'i' is root, change root pointer and return if (parent[i] == -1) { *root = created[i]; return; } // If parent is not created, then create parent first if (created[parent[i]] == NULL) createNode(parent, parent[i], created, root); // Find parent pointer Node *p = created[parent[i]]; // If this is first child of parent if (p->left == NULL) p->left = created[i]; else // If second child p->right = created[i];} // Creates tree from parent[0..n-1] and returns root of the created treeNode *createTree(int parent[], int n){ // Create an array created[] to keep track // of created nodes, initialize all entries // as NULL Node *created[n]; for (int i=0; i<n; i++) created[i] = NULL; Node *root = NULL; for (int i=0; i<n; i++) createNode(parent, i, created, &root); return root;} //For adding new line in a programinline void newLine(){ cout << \"\\n\";} // Utility function to do inorder traversalvoid inorder(Node *root){ if (root != NULL) { inorder(root->left); cout << root->key << \" \"; inorder(root->right); }} // Driver methodint main(){ int parent[] = {-1, 0, 0, 1, 1, 3, 5}; int n = sizeof parent / sizeof parent[0]; Node *root = createTree(parent, n); cout << \"Inorder Traversal of constructed tree\\n\"; inorder(root); newLine();}", "e": 30306, "s": 28212, "text": null }, { "code": "// Java program to construct a binary tree from parent array // A binary tree nodeclass Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; // Creates a node with key as 'i'. If i is root, then it changes // root. If parent of i is not created, then it creates parent first void createNode(int parent[], int i, Node created[]) { // If this node is already created if (created[i] != null) return; // Create a new node and set created[i] created[i] = new Node(i); // If 'i' is root, change root pointer and return if (parent[i] == -1) { root = created[i]; return; } // If parent is not created, then create parent first if (created[parent[i]] == null) createNode(parent, parent[i], created); // Find parent pointer Node p = created[parent[i]]; // If this is first child of parent if (p.left == null) p.left = created[i]; else // If second child p.right = created[i]; } /* Creates tree from parent[0..n-1] and returns root of the created tree */ Node createTree(int parent[], int n) { // Create an array created[] to keep track // of created nodes, initialize all entries // as NULL Node[] created = new Node[n]; for (int i = 0; i < n; i++) created[i] = null; for (int i = 0; i < n; i++) createNode(parent, i, created); return root; } //For adding new line in a program void newLine() { System.out.println(\"\"); } // Utility function to do inorder traversal void inorder(Node node) { if (node != null) { inorder(node.left); System.out.print(node.key + \" \"); inorder(node.right); } } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5}; int n = parent.length; Node node = tree.createTree(parent, n); System.out.println(\"Inorder traversal of constructed tree \"); tree.inorder(node); tree.newLine(); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 32726, "s": 30306, "text": null }, { "code": "# Python implementation to construct a Binary Tree from# parent array # A node structureclass Node: # A utility function to create a new node def __init__(self, key): self.key = key self.left = None self.right = None \"\"\" Creates a node with key as 'i'. If i is root,then it changes root. If parent of i is not created, then it creates parent first\"\"\"def createNode(parent, i, created, root): # If this node is already created if created[i] is not None: return # Create a new node and set created[i] created[i] = Node(i) # If 'i' is root, change root pointer and return if parent[i] == -1: root[0] = created[i] # root[0] denotes root of the tree return # If parent is not created, then create parent first if created[parent[i]] is None: createNode(parent, parent[i], created, root ) # Find parent pointer p = created[parent[i]] # If this is first child of parent if p.left is None: p.left = created[i] # If second child else: p.right = created[i] # Creates tree from parent[0..n-1] and returns root of the# created treedef createTree(parent): n = len(parent) # Create and array created[] to keep track # of created nodes, initialize all entries as None created = [None for i in range(n+1)] root = [None] for i in range(n): createNode(parent, i, created, root) return root[0] #Inorder traversal of treedef inorder(root): if root is not None: inorder(root.left) print (root.key,end=\" \") inorder(root.right) # Driver Methodparent = [-1, 0, 0, 1, 1, 3, 5]root = createTree(parent)print (\"Inorder Traversal of constructed tree\")inorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 34512, "s": 32726, "text": null }, { "code": "// C# program to construct a binary// tree from parent arrayusing System; // A binary tree nodepublic class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} class GFG{public Node root; // Creates a node with key as 'i'.// If i is root, then it changes// root. If parent of i is not created,// then it creates parent firstpublic virtual void createNode(int[] parent, int i, Node[] created){ // If this node is already created if (created[i] != null) { return; } // Create a new node and set created[i] created[i] = new Node(i); // If 'i' is root, change root // pointer and return if (parent[i] == -1) { root = created[i]; return; } // If parent is not created, then // create parent first if (created[parent[i]] == null) { createNode(parent, parent[i], created); } // Find parent pointer Node p = created[parent[i]]; // If this is first child of parent if (p.left == null) { p.left = created[i]; } else // If second child { p.right = created[i]; }} /* Creates tree from parent[0..n-1]and returns root of the created tree */public virtual Node createTree(int[] parent, int n){ // Create an array created[] to // keep track of created nodes, // initialize all entries as NULL Node[] created = new Node[n]; for (int i = 0; i < n; i++) { created[i] = null; } for (int i = 0; i < n; i++) { createNode(parent, i, created); } return root;} // For adding new line in a programpublic virtual void newLine(){ Console.WriteLine(\"\");} // Utility function to do inorder traversalpublic virtual void inorder(Node node){ if (node != null) { inorder(node.left); Console.Write(node.key + \" \"); inorder(node.right); }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); int[] parent = new int[]{-1, 0, 0, 1, 1, 3, 5}; int n = parent.Length; Node node = tree.createTree(parent, n); Console.WriteLine(\"Inorder traversal of \" + \"constructed tree \"); tree.inorder(node); tree.newLine();}} // This code is contributed by Shrikant13", "e": 36818, "s": 34512, "text": null }, { "code": "<script> // Javascript program to construct a binary// tree from parent array // A binary tree nodeclass Node{ constructor(key) { this.key = key; this.left = null; this.right = null; }} var root = null; // Creates a node with key as 'i'.// If i is root, then it changes// root. If parent of i is not created,// then it creates parent firstfunction createNode(parent, i, created){ // If this node is already created if (created[i] != null) { return; } // Create a new node and set created[i] created[i] = new Node(i); // If 'i' is root, change root // pointer and return if (parent[i] == -1) { root = created[i]; return; } // If parent is not created, then // create parent first if (created[parent[i]] == null) { createNode(parent, parent[i], created); } // Find parent pointer var p = created[parent[i]]; // If this is first child of parent if (p.left == null) { p.left = created[i]; } else // If second child { p.right = created[i]; }} /* Creates tree from parent[0..n-1]and returns root of the created tree */function createTree(parent, n){ // Create an array created[] to // keep track of created nodes, // initialize all entries as NULL var created = Array(n); for (var i = 0; i < n; i++) { created[i] = null; } for (var i = 0; i < n; i++) { createNode(parent, i, created); } return root;} // For adding new line in a programfunction newLine(){ document.write(\"\");} // Utility function to do inorder traversalfunction inorder(node){ if (node != null) { inorder(node.left); document.write(node.key + \" \"); inorder(node.right); }} // Driver Codevar parent = [-1, 0, 0, 1, 1, 3, 5];var n = parent.length;var node = createTree(parent, n);document.write(\"Inorder traversal of \" + \"constructed tree<br>\");inorder(node);newLine(); // This code is contributed by rrrtnx. </script>", "e": 38836, "s": 36818, "text": null }, { "code": null, "e": 38844, "s": 38836, "text": "Output:" }, { "code": null, "e": 38896, "s": 38844, "text": "Inorder Traversal of constructed tree\n6 5 3 1 4 0 2" }, { "code": null, "e": 39092, "s": 38896, "text": "Similar Problem: Find Height of Binary Tree represented by Parent arrayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 39104, "s": 39092, "text": "shrikanth13" }, { "code": null, "e": 39111, "s": 39104, "text": "rrrtnx" }, { "code": null, "e": 39126, "s": 39111, "text": "kapoorsagar226" }, { "code": null, "e": 39142, "s": 39126, "text": "amartyaghoshgfg" }, { "code": null, "e": 39149, "s": 39142, "text": "Amazon" }, { "code": null, "e": 39159, "s": 39149, "text": "Microsoft" }, { "code": null, "e": 39168, "s": 39159, "text": "Snapdeal" }, { "code": null, "e": 39173, "s": 39168, "text": "Tree" }, { "code": null, "e": 39180, "s": 39173, "text": "Amazon" }, { "code": null, "e": 39190, "s": 39180, "text": "Microsoft" }, { "code": null, "e": 39199, "s": 39190, "text": "Snapdeal" }, { "code": null, "e": 39204, "s": 39199, "text": "Tree" }, { "code": null, "e": 39302, "s": 39204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39335, "s": 39302, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 39349, "s": 39335, "text": "Decision Tree" }, { "code": null, "e": 39432, "s": 39349, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 39468, "s": 39432, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 39516, "s": 39468, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 39543, "s": 39516, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 39572, "s": 39543, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 39588, "s": 39572, "text": "Expression Tree" }, { "code": null, "e": 39623, "s": 39588, "text": "Binary Tree (Array implementation)" } ]
How to retrieve GET parameters from JavaScript ? - GeeksforGeeks
31 Dec, 2020 In order to know the parameters, those are passed by the “GET” method, like sometimes we pass the Email-id, Password, and other details. For that purpose, We are using the following snippet of code. When you visit any website, ever thought what the question mark ‘?’ is doing in the address bar. Let’s find out what is the use of this question mark ‘?’. What is the ‘?’: The question mark acts like a separator and what follows after is a query string which is in the form of key value pairs. Multiple key value pairs are separated by the ‘&’ symbol. Example: geeksforgeeks.org/web-development?page=2&name=gfg The above picture shows the address. The content followed by the ‘?’ is the query string which has two key-value pairs which are shown below : Pair 1: page = 2 Pair 2: name = gfg Our task is to get the respective values from each pair which are also known as GET parameters. Method 1: Using the keys specified in the address: The class URLSearchParams takes in the address of the website and searches for value associated with the key provided. Here is the code for the above approach: Javascript // Arrow function to get the parameter// of the specified keygetParameter = (key) => { // Address of the current window address = window.location.search // Returns a URLSearchParams object instance parameterList = new URLSearchParams(address) // Returning the respected value associated // with the provided key return parameterList.get(key)} // Gets the value associated with the key "ie"console.log(getParameter("ie")) Output: 2 Method 2: Using the forEach property of the URLSearchParams class to retrieve all the GET parameters. Javascript // Arrow function to get all the GET parametersgetParameters = () => { // Address of the current window address = window.location.search // Returns a URLSearchParams object instance parameterList = new URLSearchParams(address) // Created a map which holds key value pairs let map = new Map() // Storing every key value pair in the map parameterList.forEach((value, key) => { map.set(key, value) }) // Returning the map of GET parameters return map} // Gets all the getParametersconsole.log(getParameters()) Output: {"page" => "2", "name" => "gfg"} JavaScript-Misc Picked Technical Scripter 2020 JavaScript Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n31 Dec, 2020" }, { "code": null, "e": 25108, "s": 24909, "text": "In order to know the parameters, those are passed by the “GET” method, like sometimes we pass the Email-id, Password, and other details. For that purpose, We are using the following snippet of code." }, { "code": null, "e": 25263, "s": 25108, "text": "When you visit any website, ever thought what the question mark ‘?’ is doing in the address bar. Let’s find out what is the use of this question mark ‘?’." }, { "code": null, "e": 25280, "s": 25263, "text": "What is the ‘?’:" }, { "code": null, "e": 25460, "s": 25280, "text": "The question mark acts like a separator and what follows after is a query string which is in the form of key value pairs. Multiple key value pairs are separated by the ‘&’ symbol." }, { "code": null, "e": 25469, "s": 25460, "text": "Example:" }, { "code": null, "e": 25519, "s": 25469, "text": "geeksforgeeks.org/web-development?page=2&name=gfg" }, { "code": null, "e": 25662, "s": 25519, "text": "The above picture shows the address. The content followed by the ‘?’ is the query string which has two key-value pairs which are shown below :" }, { "code": null, "e": 25679, "s": 25662, "text": "Pair 1: page = 2" }, { "code": null, "e": 25698, "s": 25679, "text": "Pair 2: name = gfg" }, { "code": null, "e": 25794, "s": 25698, "text": "Our task is to get the respective values from each pair which are also known as GET parameters." }, { "code": null, "e": 25964, "s": 25794, "text": "Method 1: Using the keys specified in the address: The class URLSearchParams takes in the address of the website and searches for value associated with the key provided." }, { "code": null, "e": 26005, "s": 25964, "text": "Here is the code for the above approach:" }, { "code": null, "e": 26016, "s": 26005, "text": "Javascript" }, { "code": "// Arrow function to get the parameter// of the specified keygetParameter = (key) => { // Address of the current window address = window.location.search // Returns a URLSearchParams object instance parameterList = new URLSearchParams(address) // Returning the respected value associated // with the provided key return parameterList.get(key)} // Gets the value associated with the key \"ie\"console.log(getParameter(\"ie\"))", "e": 26465, "s": 26016, "text": null }, { "code": null, "e": 26473, "s": 26465, "text": "Output:" }, { "code": null, "e": 26475, "s": 26473, "text": "2" }, { "code": null, "e": 26577, "s": 26475, "text": "Method 2: Using the forEach property of the URLSearchParams class to retrieve all the GET parameters." }, { "code": null, "e": 26588, "s": 26577, "text": "Javascript" }, { "code": "// Arrow function to get all the GET parametersgetParameters = () => { // Address of the current window address = window.location.search // Returns a URLSearchParams object instance parameterList = new URLSearchParams(address) // Created a map which holds key value pairs let map = new Map() // Storing every key value pair in the map parameterList.forEach((value, key) => { map.set(key, value) }) // Returning the map of GET parameters return map} // Gets all the getParametersconsole.log(getParameters())", "e": 27146, "s": 26588, "text": null }, { "code": null, "e": 27154, "s": 27146, "text": "Output:" }, { "code": null, "e": 27187, "s": 27154, "text": "{\"page\" => \"2\", \"name\" => \"gfg\"}" }, { "code": null, "e": 27203, "s": 27187, "text": "JavaScript-Misc" }, { "code": null, "e": 27210, "s": 27203, "text": "Picked" }, { "code": null, "e": 27234, "s": 27210, "text": "Technical Scripter 2020" }, { "code": null, "e": 27245, "s": 27234, "text": "JavaScript" }, { "code": null, "e": 27264, "s": 27245, "text": "Technical Scripter" }, { "code": null, "e": 27281, "s": 27264, "text": "Web Technologies" }, { "code": null, "e": 27308, "s": 27281, "text": "Web technologies Questions" }, { "code": null, "e": 27406, "s": 27308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27415, "s": 27406, "text": "Comments" }, { "code": null, "e": 27428, "s": 27415, "text": "Old Comments" }, { "code": null, "e": 27489, "s": 27428, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27530, "s": 27489, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27584, "s": 27530, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27624, "s": 27584, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27686, "s": 27624, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27742, "s": 27686, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27775, "s": 27742, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27837, "s": 27775, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27880, "s": 27837, "text": "How to fetch data from an API in ReactJS ?" } ]
List down the name of the Web drivers supported by Selenium.
The name of the web drivers supported by Selenium are listed below − Google Chrome Driver [ ChromeDriver() supports chrome ] Google Chrome Driver [ ChromeDriver() supports chrome ] HTML Unit Driver [ WebClient() supports chrome, firefox and IE ] HTML Unit Driver [ WebClient() supports chrome, firefox and IE ] Safari Driver [ SafariDriver() supports Safari ] Safari Driver [ SafariDriver() supports Safari ] IOS Driver [ IOSDriver() supports ios ] IOS Driver [ IOSDriver() supports ios ] Android Driver [ AndroidDriver() supports Android ] Android Driver [ AndroidDriver() supports Android ] OperaChromium Driver [ ChromeDriver() supports opera ] OperaChromium Driver [ ChromeDriver() supports opera ] Gecko Driver [ FirefoxDriver() supports firefox ] Gecko Driver [ FirefoxDriver() supports firefox ] Microsoft WebDriver [ InternetExplorerDriver() supports IE ] Microsoft WebDriver [ InternetExplorerDriver() supports IE ] EventFiring WebDriver [ EventFiring Driver() supports majority of browsers ] EventFiring WebDriver [ EventFiring Driver() supports majority of browsers ] Code Implementation with Firefox driver import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class BrowserDriverScript { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); // working with Firefox driver WebDriver driver = new FirefoxDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); System.out.println("Launching the url"); driver.quit(); } }
[ { "code": null, "e": 1131, "s": 1062, "text": "The name of the web drivers supported by Selenium are listed below −" }, { "code": null, "e": 1187, "s": 1131, "text": "Google Chrome Driver [ ChromeDriver() supports chrome ]" }, { "code": null, "e": 1243, "s": 1187, "text": "Google Chrome Driver [ ChromeDriver() supports chrome ]" }, { "code": null, "e": 1308, "s": 1243, "text": "HTML Unit Driver [ WebClient() supports chrome, firefox and IE ]" }, { "code": null, "e": 1373, "s": 1308, "text": "HTML Unit Driver [ WebClient() supports chrome, firefox and IE ]" }, { "code": null, "e": 1422, "s": 1373, "text": "Safari Driver [ SafariDriver() supports Safari ]" }, { "code": null, "e": 1471, "s": 1422, "text": "Safari Driver [ SafariDriver() supports Safari ]" }, { "code": null, "e": 1511, "s": 1471, "text": "IOS Driver [ IOSDriver() supports ios ]" }, { "code": null, "e": 1551, "s": 1511, "text": "IOS Driver [ IOSDriver() supports ios ]" }, { "code": null, "e": 1603, "s": 1551, "text": "Android Driver [ AndroidDriver() supports Android ]" }, { "code": null, "e": 1655, "s": 1603, "text": "Android Driver [ AndroidDriver() supports Android ]" }, { "code": null, "e": 1710, "s": 1655, "text": "OperaChromium Driver [ ChromeDriver() supports opera ]" }, { "code": null, "e": 1765, "s": 1710, "text": "OperaChromium Driver [ ChromeDriver() supports opera ]" }, { "code": null, "e": 1815, "s": 1765, "text": "Gecko Driver [ FirefoxDriver() supports firefox ]" }, { "code": null, "e": 1865, "s": 1815, "text": "Gecko Driver [ FirefoxDriver() supports firefox ]" }, { "code": null, "e": 1926, "s": 1865, "text": "Microsoft WebDriver [ InternetExplorerDriver() supports IE ]" }, { "code": null, "e": 1987, "s": 1926, "text": "Microsoft WebDriver [ InternetExplorerDriver() supports IE ]" }, { "code": null, "e": 2064, "s": 1987, "text": "EventFiring WebDriver [ EventFiring Driver() supports majority of browsers ]" }, { "code": null, "e": 2141, "s": 2064, "text": "EventFiring WebDriver [ EventFiring Driver() supports majority of browsers ]" }, { "code": null, "e": 2181, "s": 2141, "text": "Code Implementation with Firefox driver" }, { "code": null, "e": 2916, "s": 2181, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class BrowserDriverScript {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n // working with Firefox driver\n WebDriver driver = new FirefoxDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);\n System.out.println(\"Launching the url\");\n driver.quit();\n }\n}" } ]
Tables - Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Tables. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Answer the question given below using the table below: Percent profit made by 6 different companies in 6 years Q 1 - Which company has made the highest amount of profit in the year 2005 ? A - P B - S C - P and U D - can not be determined To get the amount of profit we need income and expenditure of individual company which are not given. Answer the question given below using the table below: Percentage of marks obtained by 7 students in 6 different subjects Q 2 - What is the average percentage of marks obtained by all the students in subject B? A - 76.36 B - 78.14 C - 72.11 D - 89.92 Average percentage of marks in subject B = 1/7(84+76+89+77+66+72+83)=547/7 = 78.14 Answer the question given below using the table below: Number of student passed and failed in 5 classes of a school over the year Q 3 - What is the average number of failed students from class VII for the given years ? A - 27.5 B - 28 C - 26.5 D - 24.5 Average number of failed students from class VII =1/6(14+22+19+25+29+38) = 147/6 =24.5 Answer the question given below using the table below: Number of applications for 6 different specialist posts by six different banks in a year Q 4 - Which bank has received the lowest number of application for all the specialists post together ? A - D B - A C - C D - E total number of applications received by different banks = A =(195.3*100)=19530, B=(215.2*100)=21520, C =(190.1*100)= 19010, D =(196.2*100)=19620, E =(186.8*100)=18680, f =(198*100)= 19800 Clearly, E received the lowest number of application. Answer the question given below using the table below: Number of cars of different models and colors sold in two metro cities in a year Q 5 - The difference between the white coloured cars sold in two metros of which of the following models is the minimum ? A - A B - C C - D D - none of these difference between white car sold in two metros. A =(75-60)*1000=15000, B =(81-80)*1000= 1000, C = (90-85)*1000= 5000, D =(90-86)*1000= 4000 , E = (77-60)*1000= 17000, F = (87-75)*1000= 12000 Answer the question given below using the table below: Number of working days of various companies over the years Q 6 - Which company has the maximum number of working days over the year ? A - B B - A C - D D - C total number of working days in 6 years are maximum in case of company D Answer the question given below using the table below: Number of working days of various companies over the years Q 7 - What is the difference between the average number of students playing cricket from all the schools and the average number of students playing tennis from all the schools ? A - 31 B - 26 C - 29 D - 33 average number of students playing cricket from all the schools =1/5 (250+200+225+215+200) =1090/5 = 218 Average number of student playing tennis from all the school =1/5 (240+210+200+130+165) =189 Required difference = (218-189) =29 Answer the question given below using the table below: Distribution of malnutrition in children in percentage in various years Q 8 - In which of the following year there was most improvement in degree of malnutrition in comparison of previous year ? A - 2000 B - 2001 C - 2002 D - 2003 improvement in malnutrition in general category : In 1999 = (3.8+3.0)% = 0.8% in 2000 = (3.4-3.8)% =-0.4% . in 2001 =(10.6-3.4)% =7.2% , in 2002 =(14.3 -10.6)% =3.7% , in 2003 =(14.8-14.3)% =0.5% , in 2004 =(16.5-14.8)% =1.7% It is maximum in the year 2001. Answer the question given below using the table below: Distribution of malnutrition in children in percentage in various years Q 9 - What was the percentage of defective articles over the number of articles manufactured by all units together in the year 2005 ? A - 42% B - 40% C - 37% D - 36% number of defective articles =(123+90+152+136+80)*1000= 581000 Number of article manufactured =(311+321+353+329+282) =1596000 Required % = 581000/ 1596000*100 = 8300/228 = 36% 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4212, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Tables. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4267, "s": 4212, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 4324, "s": 4267, "text": "Percent profit made by 6 different companies in 6 years" }, { "code": null, "e": 4401, "s": 4324, "text": "Q 1 - Which company has made the highest amount of profit in the year 2005 ?" }, { "code": null, "e": 4407, "s": 4401, "text": "A - P" }, { "code": null, "e": 4413, "s": 4407, "text": "B - S" }, { "code": null, "e": 4425, "s": 4413, "text": "C - P and U" }, { "code": null, "e": 4451, "s": 4425, "text": "D - can not be determined" }, { "code": null, "e": 4553, "s": 4451, "text": "To get the amount of profit we need income and expenditure of individual company which are not given." }, { "code": null, "e": 4608, "s": 4553, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 4676, "s": 4608, "text": "Percentage of marks obtained by 7 students in 6 different subjects " }, { "code": null, "e": 4766, "s": 4676, "text": "Q 2 - What is the average percentage of marks obtained by all the students in subject B?" }, { "code": null, "e": 4776, "s": 4766, "text": "A - 76.36" }, { "code": null, "e": 4786, "s": 4776, "text": "B - 78.14" }, { "code": null, "e": 4796, "s": 4786, "text": "C - 72.11" }, { "code": null, "e": 4806, "s": 4796, "text": "D - 89.92" }, { "code": null, "e": 4889, "s": 4806, "text": "Average percentage of marks in subject B = 1/7(84+76+89+77+66+72+83)=547/7 = 78.14" }, { "code": null, "e": 4944, "s": 4889, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 5019, "s": 4944, "text": "Number of student passed and failed in 5 classes of a school over the year" }, { "code": null, "e": 5109, "s": 5019, "text": "Q 3 - What is the average number of failed students from class VII for the given years ?" }, { "code": null, "e": 5118, "s": 5109, "text": "A - 27.5" }, { "code": null, "e": 5125, "s": 5118, "text": "B - 28" }, { "code": null, "e": 5134, "s": 5125, "text": "C - 26.5" }, { "code": null, "e": 5143, "s": 5134, "text": "D - 24.5" }, { "code": null, "e": 5233, "s": 5143, "text": "Average number of failed students from class VII =1/6(14+22+19+25+29+38)\n= 147/6 =24.5 " }, { "code": null, "e": 5288, "s": 5233, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 5377, "s": 5288, "text": "Number of applications for 6 different specialist posts by six different banks in a year" }, { "code": null, "e": 5480, "s": 5377, "text": "Q 4 - Which bank has received the lowest number of application for all the specialists post together ?" }, { "code": null, "e": 5486, "s": 5480, "text": "A - D" }, { "code": null, "e": 5492, "s": 5486, "text": "B - A" }, { "code": null, "e": 5498, "s": 5492, "text": "C - C" }, { "code": null, "e": 5504, "s": 5498, "text": "D - E" }, { "code": null, "e": 5748, "s": 5504, "text": "total number of applications received by different banks = A\n=(195.3*100)=19530, B=(215.2*100)=21520, C =(190.1*100)= 19010, D =(196.2*100)=19620, E =(186.8*100)=18680, f\n =(198*100)= 19800\nClearly, E received the lowest number of application." }, { "code": null, "e": 5803, "s": 5748, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 5884, "s": 5803, "text": "Number of cars of different models and colors sold in two metro cities in a year" }, { "code": null, "e": 6007, "s": 5884, "text": "Q 5 - The difference between the white coloured cars sold in two metros of which of the following models is the minimum ?" }, { "code": null, "e": 6013, "s": 6007, "text": "A - A" }, { "code": null, "e": 6019, "s": 6013, "text": "B - C" }, { "code": null, "e": 6025, "s": 6019, "text": "C - D" }, { "code": null, "e": 6043, "s": 6025, "text": "D - none of these" }, { "code": null, "e": 6240, "s": 6043, "text": "difference between white car sold in two metros.\nA =(75-60)*1000=15000, \nB =(81-80)*1000= 1000,\nC = (90-85)*1000= 5000, \nD =(90-86)*1000= 4000 , \nE = (77-60)*1000= 17000, \nF = (87-75)*1000= 12000" }, { "code": null, "e": 6295, "s": 6240, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 6355, "s": 6295, "text": "Number of working days of various companies over the years" }, { "code": null, "e": 6430, "s": 6355, "text": "Q 6 - Which company has the maximum number of working days over the year ?" }, { "code": null, "e": 6436, "s": 6430, "text": "A - B" }, { "code": null, "e": 6442, "s": 6436, "text": "B - A" }, { "code": null, "e": 6448, "s": 6442, "text": "C - D" }, { "code": null, "e": 6454, "s": 6448, "text": "D - C" }, { "code": null, "e": 6527, "s": 6454, "text": "total number of working days in 6 years are maximum in case of company D" }, { "code": null, "e": 6582, "s": 6527, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 6642, "s": 6582, "text": "Number of working days of various companies over the years" }, { "code": null, "e": 6821, "s": 6642, "text": "Q 7 - What is the difference between the average number of students playing cricket from all the schools and the average number of students playing tennis from all the schools ?" }, { "code": null, "e": 6828, "s": 6821, "text": "A - 31" }, { "code": null, "e": 6835, "s": 6828, "text": "B - 26" }, { "code": null, "e": 6842, "s": 6835, "text": "C - 29" }, { "code": null, "e": 6849, "s": 6842, "text": "D - 33" }, { "code": null, "e": 7083, "s": 6849, "text": "average number of students playing cricket from all the schools =1/5\n(250+200+225+215+200) =1090/5 = 218\nAverage number of student playing tennis from all the school =1/5 (240+210+200+130+165) =189\nRequired difference = (218-189) =29" }, { "code": null, "e": 7138, "s": 7083, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 7210, "s": 7138, "text": "Distribution of malnutrition in children in percentage in various years" }, { "code": null, "e": 7333, "s": 7210, "text": "Q 8 - In which of the following year there was most improvement in degree of malnutrition in comparison of previous year ?" }, { "code": null, "e": 7342, "s": 7333, "text": "A - 2000" }, { "code": null, "e": 7351, "s": 7342, "text": "B - 2001" }, { "code": null, "e": 7360, "s": 7351, "text": "C - 2002" }, { "code": null, "e": 7369, "s": 7360, "text": "D - 2003" }, { "code": null, "e": 7629, "s": 7369, "text": "improvement in malnutrition in general category :\nIn 1999 = (3.8+3.0)% = 0.8% in 2000 = (3.4-3.8)% =-0.4% . in 2001 =(10.6-3.4)% =7.2% , in 2002 =(14.3 -10.6)% =3.7%\n , in 2003 =(14.8-14.3)% =0.5% , in 2004 =(16.5-14.8)% =1.7%\nIt is maximum in the year 2001." }, { "code": null, "e": 7684, "s": 7629, "text": "Answer the question given below using the table below:" }, { "code": null, "e": 7756, "s": 7684, "text": "Distribution of malnutrition in children in percentage in various years" }, { "code": null, "e": 7891, "s": 7756, "text": "Q 9 - What was the percentage of defective articles over the number of articles manufactured by all units together in the year 2005 ?" }, { "code": null, "e": 7899, "s": 7891, "text": "A - 42%" }, { "code": null, "e": 7907, "s": 7899, "text": "B - 40%" }, { "code": null, "e": 7915, "s": 7907, "text": "C - 37%" }, { "code": null, "e": 7923, "s": 7915, "text": "D - 36%" }, { "code": null, "e": 8101, "s": 7923, "text": "number of defective articles =(123+90+152+136+80)*1000= 581000\nNumber of article manufactured =(311+321+353+329+282) =1596000\nRequired % = 581000/ 1596000*100 = 8300/228 = 36% " }, { "code": null, "e": 8137, "s": 8101, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 8155, "s": 8137, "text": " Programming Line" }, { "code": null, "e": 8162, "s": 8155, "text": " Print" }, { "code": null, "e": 8173, "s": 8162, "text": " Add Notes" } ]
Conditional Probabilities, Seattle Rain, And Tricky Friends | by Tony Yiu | Towards Data Science
My least favorite kind of data science interview question is probability. It’s just not something that I think about everyday, so the probability muscles always feel super rusty whenever I am forced to exercise them. But if you are hunting for a data job, it’s inevitable that you will run into one at some point — so let’s keep our probability skills fresh with some practice. As usual, we will use simulation (and Python code) to better visualize what’s going on. You’re headed to Seattle. You want to know if you should bring an umbrella so you call 3 random friends who live there and ask each independently whether it’s raining or not. Each friend has a 2/3 chance of telling you the truth and a 1/3 chance of lying (so mean!). All 3 friends tell you “Yes, it’s raining”. What is the probability that it’s actually raining in Seattle? The first time I saw this problem, I thought “only if all 3 of my friends lied to me then it would mean it’s not raining in Seattle”. Because as long as one of my friends was not lying, then one of the yeses would be true (implying rain). probability rain = 1 - probability all lying= 1 - (1/3)^3 = 0.963 But then I thought this seems too simple. How could this question gain such notoriety if it was this simple. Sadly my instincts were right and this question is more complicated than meets the eye. My previous approach ignored the given condition. What condition you ask? The interviewer told us that all 3 of our friends answered yes. That’s relevant information that needs to be factored into our solution. To see why, imagine that it’s raining in Seattle. Our friends answered [yes, yes, yes] when we asked them whether it was raining. Let’s think through the possible outcomes in this state of the world. If they all told the truth, then that is consistent with the world state that we’re in (because it IS raining in Seattle). What if they all lied? That’s impossible. In a state of the world where it is raining, our friends can’t have answered “yes” and lied (to lie, they would have had to have replied “no”). Is it possible that just one of them lied? That’s not possible either — all of them said “yes” and to lie in the state of the world where it’s raining requires a “no”. So the only possible result if it IS raining in Seattle is that our friends are all telling the truth. Now imagine that it’s sunny in Seattle. We can perform the same exercise to figure out what’s possible in this world state. If it’s sunny, then that must mean all 3 of our friends lied to us. That’s the only possibility! Because in the sunny state of the world, our friends would have had to respond “no, it’s not raining” in order to be telling the truth. And none of them said that. So there are only two possibilities: World state = it is raining:[yes,yes,yes] = [truth,truth,truth] = raining [lie,lie,lie] = impossible [lie,lie,truth] = impossible [lie,truth,truth] = impossible [lie,truth,lie] = impossible [truth,truth,lie] = impossible [truth,lie,lie] = impossible [truth,lie,truth] = impossibleWorld state = it is not raining:[yes,yes,yes] = [truth,truth,truth] = impossible [lie,lie,lie] = not raining [lie,lie,truth] = impossible [lie,truth,truth] = impossible [lie,truth,lie] = impossible [truth,truth,lie] = impossible [truth,lie,lie] = impossible [truth,lie,truth] = impossible Basically, if it’s raining, they must all be telling the truth. And if it’s not, they must all be lying. These are the only possibilities given the condition that all 3 of our friends said yes. Thus, we are estimating a conditional probability: Prob(rain | [yes,yes,yes])Which is read as probability of rain given that the responses were yes, yes, and yes]. We could bust out Bayes’ Theorem here, but I prefer a more intuitive and in depth approach so that we can truly grasp what’s going on. Let’s write up some code to simulate this brainteaser. I’ve put some comments in the code to describe how it works and my thought process. But let’s quickly run through it as well. We will run 100,000 simulations. We also need to specify the probability of rain. That seems odd, right? Aren’t we trying to estimate the probability of rain? No, actually we’re estimating the probability of rain given that our friends all said “yes, it’s raining”. And in order to do that, we need to model the two possible states of the world (raining or not raining). We can do so with a coin flip like random variable (uniform distribution between 0 and 1) — if the random variable, rain, is less than prob_rain, then it is raining in our simulation. Next we simulate the responses of our 3 friends in the same way — if any of the 3 random variables in responses is greater than 2/3, then that specific friend lied to us (since they have 2/3 chance of telling the truth and 1/3 of lying). We have 3 counter variables to keep track of the outcomes that we care about: times_rained_3yes keeps track of the number of times it rained and our friends all told the truth and said “yes, it’s raining”.times_dry_3yes keeps track of the number of times it did not rain and our friends all lied and said “yes, it’s raining”.times_rained keeps track of the number of times in our simulation that it rained (roughly 50% of the time since we set prob_rain = 0.5). times_rained_3yes keeps track of the number of times it rained and our friends all told the truth and said “yes, it’s raining”. times_dry_3yes keeps track of the number of times it did not rain and our friends all lied and said “yes, it’s raining”. times_rained keeps track of the number of times in our simulation that it rained (roughly 50% of the time since we set prob_rain = 0.5). # Inputssims = 100000prob_rain = 0.50# Counter variables to tally the simulation outcomestimes_rained_3yes = 0times_dry_3yes = 0times_rained = 0# Loop that runs the simulationsfor i in range(sims): # Random variable to simulte whether it rains or not rain = np.random.random() # Raining Case if rain < prob_rain: # If it is raining, increment counter times_rained += 1 # Random variables to simulate whether friends lie responses = [np.random.random(), np.random.random(), np.random.random()] # Tally the number of lies lies = sum([1 for i in responses if i > 2/3]) # If sum(lies) == 0, then all truth if lies == 0: # This is outcome we are looking for, where the # world state = RAINING and all friends tell truth times_rained_3yes += 1 # Not Raining Case else: # Random variables to simulate whether friends lie responses = [np.random.random(), np.random.random(), np.random.random()] # Tally the number of lies lies = sum([1 for i in responses if i > 2/3]) # If sum(lies) == 3, then all lies if lies == 3: # This is outcome we are looking for, where the # world state = DRY and all friends lie times_dry_3yes += 1 After running the simulation, we can use our counter variables to calculate the probabilities we are interested in. sims = 100,000times_rained = 49,990times_rained_3yes = 14,852times_dry_3yes = 1,889 So it rains around 50% of the time (since we set it up that way). And when it does rain, our friends tell the truth about 29% (14,852/49,990) of the time — (2/3)3 = 0.295. And when it’s not raining, all 3 of our friends lie to us 3.77% (1,889/50,010) of the time — (1/3)3 = 0.037, slight difference due to simulation noise. We now have all the numbers we need to solve the problem! Can you see how? Let’s think back to our problem — we want to know the probability that it is raining when all 3 of our friends say “yes, it’s raining”. So the numerator of our probability calculation should be a count of the times it rained and all said yes. And the denominator should be the number of times that all of our friends replied yes in all states of the world (there are only 2 states — rain and not rain). Numerator = times_rained_3yes = 14,852Denominator = number of times our friends said 3 yeses = times_rained_3yes + times_dry_3yes = 14,852 + 1,889 = 16,741The Answer = 14,852 / 16,741 = 0.888 So given the responses of our friends, there is an 89% chance that it’s raining in Seattle (definitely bring an umbrella). We can also solve for this analytically as follows: The numerator is the joint probability of 3 yeses and rain. Since they are independent events, we can just multiply the probability of 3 truths (since answering yes when it’s raining equals to telling the truth) with the probability of rain. The denominator is the probability of 3 yeses. We can calculate this by recognizing that 3 yeses can only result from 2 cases: either 3 truths when it’s raining or 3 lies when it’s not raining. We already have the first probability (it’s our numerator). We can calculate the second one (3 lies when it’s not raining) in the same way — by multiplying the probability of 3 lies with the probability of not raining. Finally we sum the probabilities of our 2 cases to get the probability of 3 yeses. Numerator = Prob. 3 Truths * Prob. Rain = (2/3)^3 * (1/2)Denominator = Prob. 3 Yeses = (Prob. 3 Truths * Prob. Rain) + (Prob. 3 Lies * (1 - Prob. Rain)) = (2/3)^3 * (1/2) + (1/3)^3 * (1/2)Plugging into Python:(2/3)**3*(1/2) /((2/3)**3*(1/2) + (1/3)**3*(1/2))We get:0.888 Finally, it’s important to note that the answer varies based on our estimate of the probability of rain (which we previously set to 0.5). This makes sense — regardless of our friend’s responses, our prior assumption of the probability of rain is still important. Our friends’ responses modify our starting prior assumption but they do not override it. For example, if we were heading to Las Vegas instead of Seattle, even with 3 “yes, it’s raining” responses, we could probably get away with not bringing an umbrella. The following plot shows how our assumption about the probability of rain (the prob_rain variable in my code) changes our answer: And that’s all for today folks! Good luck with interviews and all things data science. Cheers!
[ { "code": null, "e": 638, "s": 172, "text": "My least favorite kind of data science interview question is probability. It’s just not something that I think about everyday, so the probability muscles always feel super rusty whenever I am forced to exercise them. But if you are hunting for a data job, it’s inevitable that you will run into one at some point — so let’s keep our probability skills fresh with some practice. As usual, we will use simulation (and Python code) to better visualize what’s going on." }, { "code": null, "e": 1012, "s": 638, "text": "You’re headed to Seattle. You want to know if you should bring an umbrella so you call 3 random friends who live there and ask each independently whether it’s raining or not. Each friend has a 2/3 chance of telling you the truth and a 1/3 chance of lying (so mean!). All 3 friends tell you “Yes, it’s raining”. What is the probability that it’s actually raining in Seattle?" }, { "code": null, "e": 1251, "s": 1012, "text": "The first time I saw this problem, I thought “only if all 3 of my friends lied to me then it would mean it’s not raining in Seattle”. Because as long as one of my friends was not lying, then one of the yeses would be true (implying rain)." }, { "code": null, "e": 1317, "s": 1251, "text": "probability rain = 1 - probability all lying= 1 - (1/3)^3 = 0.963" }, { "code": null, "e": 1514, "s": 1317, "text": "But then I thought this seems too simple. How could this question gain such notoriety if it was this simple. Sadly my instincts were right and this question is more complicated than meets the eye." }, { "code": null, "e": 1725, "s": 1514, "text": "My previous approach ignored the given condition. What condition you ask? The interviewer told us that all 3 of our friends answered yes. That’s relevant information that needs to be factored into our solution." }, { "code": null, "e": 2048, "s": 1725, "text": "To see why, imagine that it’s raining in Seattle. Our friends answered [yes, yes, yes] when we asked them whether it was raining. Let’s think through the possible outcomes in this state of the world. If they all told the truth, then that is consistent with the world state that we’re in (because it IS raining in Seattle)." }, { "code": null, "e": 2505, "s": 2048, "text": "What if they all lied? That’s impossible. In a state of the world where it is raining, our friends can’t have answered “yes” and lied (to lie, they would have had to have replied “no”). Is it possible that just one of them lied? That’s not possible either — all of them said “yes” and to lie in the state of the world where it’s raining requires a “no”. So the only possible result if it IS raining in Seattle is that our friends are all telling the truth." }, { "code": null, "e": 2890, "s": 2505, "text": "Now imagine that it’s sunny in Seattle. We can perform the same exercise to figure out what’s possible in this world state. If it’s sunny, then that must mean all 3 of our friends lied to us. That’s the only possibility! Because in the sunny state of the world, our friends would have had to respond “no, it’s not raining” in order to be telling the truth. And none of them said that." }, { "code": null, "e": 2927, "s": 2890, "text": "So there are only two possibilities:" }, { "code": null, "e": 3706, "s": 2927, "text": "World state = it is raining:[yes,yes,yes] = [truth,truth,truth] = raining [lie,lie,lie] = impossible [lie,lie,truth] = impossible [lie,truth,truth] = impossible [lie,truth,lie] = impossible [truth,truth,lie] = impossible [truth,lie,lie] = impossible [truth,lie,truth] = impossibleWorld state = it is not raining:[yes,yes,yes] = [truth,truth,truth] = impossible [lie,lie,lie] = not raining [lie,lie,truth] = impossible [lie,truth,truth] = impossible [lie,truth,lie] = impossible [truth,truth,lie] = impossible [truth,lie,lie] = impossible [truth,lie,truth] = impossible" }, { "code": null, "e": 3900, "s": 3706, "text": "Basically, if it’s raining, they must all be telling the truth. And if it’s not, they must all be lying. These are the only possibilities given the condition that all 3 of our friends said yes." }, { "code": null, "e": 3951, "s": 3900, "text": "Thus, we are estimating a conditional probability:" }, { "code": null, "e": 4064, "s": 3951, "text": "Prob(rain | [yes,yes,yes])Which is read as probability of rain given that the responses were yes, yes, and yes]." }, { "code": null, "e": 4199, "s": 4064, "text": "We could bust out Bayes’ Theorem here, but I prefer a more intuitive and in depth approach so that we can truly grasp what’s going on." }, { "code": null, "e": 4380, "s": 4199, "text": "Let’s write up some code to simulate this brainteaser. I’ve put some comments in the code to describe how it works and my thought process. But let’s quickly run through it as well." }, { "code": null, "e": 4935, "s": 4380, "text": "We will run 100,000 simulations. We also need to specify the probability of rain. That seems odd, right? Aren’t we trying to estimate the probability of rain? No, actually we’re estimating the probability of rain given that our friends all said “yes, it’s raining”. And in order to do that, we need to model the two possible states of the world (raining or not raining). We can do so with a coin flip like random variable (uniform distribution between 0 and 1) — if the random variable, rain, is less than prob_rain, then it is raining in our simulation." }, { "code": null, "e": 5173, "s": 4935, "text": "Next we simulate the responses of our 3 friends in the same way — if any of the 3 random variables in responses is greater than 2/3, then that specific friend lied to us (since they have 2/3 chance of telling the truth and 1/3 of lying)." }, { "code": null, "e": 5251, "s": 5173, "text": "We have 3 counter variables to keep track of the outcomes that we care about:" }, { "code": null, "e": 5635, "s": 5251, "text": "times_rained_3yes keeps track of the number of times it rained and our friends all told the truth and said “yes, it’s raining”.times_dry_3yes keeps track of the number of times it did not rain and our friends all lied and said “yes, it’s raining”.times_rained keeps track of the number of times in our simulation that it rained (roughly 50% of the time since we set prob_rain = 0.5)." }, { "code": null, "e": 5763, "s": 5635, "text": "times_rained_3yes keeps track of the number of times it rained and our friends all told the truth and said “yes, it’s raining”." }, { "code": null, "e": 5884, "s": 5763, "text": "times_dry_3yes keeps track of the number of times it did not rain and our friends all lied and said “yes, it’s raining”." }, { "code": null, "e": 6021, "s": 5884, "text": "times_rained keeps track of the number of times in our simulation that it rained (roughly 50% of the time since we set prob_rain = 0.5)." }, { "code": null, "e": 7431, "s": 6021, "text": "# Inputssims = 100000prob_rain = 0.50# Counter variables to tally the simulation outcomestimes_rained_3yes = 0times_dry_3yes = 0times_rained = 0# Loop that runs the simulationsfor i in range(sims): # Random variable to simulte whether it rains or not rain = np.random.random() # Raining Case if rain < prob_rain: # If it is raining, increment counter times_rained += 1 # Random variables to simulate whether friends lie responses = [np.random.random(), np.random.random(), np.random.random()] # Tally the number of lies lies = sum([1 for i in responses if i > 2/3]) # If sum(lies) == 0, then all truth if lies == 0: # This is outcome we are looking for, where the # world state = RAINING and all friends tell truth times_rained_3yes += 1 # Not Raining Case else: # Random variables to simulate whether friends lie responses = [np.random.random(), np.random.random(), np.random.random()] # Tally the number of lies lies = sum([1 for i in responses if i > 2/3]) # If sum(lies) == 3, then all lies if lies == 3: # This is outcome we are looking for, where the # world state = DRY and all friends lie times_dry_3yes += 1" }, { "code": null, "e": 7547, "s": 7431, "text": "After running the simulation, we can use our counter variables to calculate the probabilities we are interested in." }, { "code": null, "e": 7631, "s": 7547, "text": "sims = 100,000times_rained = 49,990times_rained_3yes = 14,852times_dry_3yes = 1,889" }, { "code": null, "e": 7955, "s": 7631, "text": "So it rains around 50% of the time (since we set it up that way). And when it does rain, our friends tell the truth about 29% (14,852/49,990) of the time — (2/3)3 = 0.295. And when it’s not raining, all 3 of our friends lie to us 3.77% (1,889/50,010) of the time — (1/3)3 = 0.037, slight difference due to simulation noise." }, { "code": null, "e": 8433, "s": 7955, "text": "We now have all the numbers we need to solve the problem! Can you see how? Let’s think back to our problem — we want to know the probability that it is raining when all 3 of our friends say “yes, it’s raining”. So the numerator of our probability calculation should be a count of the times it rained and all said yes. And the denominator should be the number of times that all of our friends replied yes in all states of the world (there are only 2 states — rain and not rain)." }, { "code": null, "e": 8647, "s": 8433, "text": "Numerator = times_rained_3yes = 14,852Denominator = number of times our friends said 3 yeses = times_rained_3yes + times_dry_3yes = 14,852 + 1,889 = 16,741The Answer = 14,852 / 16,741 = 0.888" }, { "code": null, "e": 8770, "s": 8647, "text": "So given the responses of our friends, there is an 89% chance that it’s raining in Seattle (definitely bring an umbrella)." }, { "code": null, "e": 8822, "s": 8770, "text": "We can also solve for this analytically as follows:" }, { "code": null, "e": 9064, "s": 8822, "text": "The numerator is the joint probability of 3 yeses and rain. Since they are independent events, we can just multiply the probability of 3 truths (since answering yes when it’s raining equals to telling the truth) with the probability of rain." }, { "code": null, "e": 9560, "s": 9064, "text": "The denominator is the probability of 3 yeses. We can calculate this by recognizing that 3 yeses can only result from 2 cases: either 3 truths when it’s raining or 3 lies when it’s not raining. We already have the first probability (it’s our numerator). We can calculate the second one (3 lies when it’s not raining) in the same way — by multiplying the probability of 3 lies with the probability of not raining. Finally we sum the probabilities of our 2 cases to get the probability of 3 yeses." }, { "code": null, "e": 9832, "s": 9560, "text": "Numerator = Prob. 3 Truths * Prob. Rain = (2/3)^3 * (1/2)Denominator = Prob. 3 Yeses = (Prob. 3 Truths * Prob. Rain) + (Prob. 3 Lies * (1 - Prob. Rain)) = (2/3)^3 * (1/2) + (1/3)^3 * (1/2)Plugging into Python:(2/3)**3*(1/2) /((2/3)**3*(1/2) + (1/3)**3*(1/2))We get:0.888" }, { "code": null, "e": 10480, "s": 9832, "text": "Finally, it’s important to note that the answer varies based on our estimate of the probability of rain (which we previously set to 0.5). This makes sense — regardless of our friend’s responses, our prior assumption of the probability of rain is still important. Our friends’ responses modify our starting prior assumption but they do not override it. For example, if we were heading to Las Vegas instead of Seattle, even with 3 “yes, it’s raining” responses, we could probably get away with not bringing an umbrella. The following plot shows how our assumption about the probability of rain (the prob_rain variable in my code) changes our answer:" } ]
Generate square or circular thumbnail image with Python - Pillow - GeeksforGeeks
17 Mar, 2021 Prerequisites: Pillow, Numpy In the word “THUMBNAIL” the word THUMB means short. A thumbnail is the compressed preview image of the original image or a Thumbnail is the smaller version of an image. In simple words, the thumbnail is the smaller image that represents the larger/original image. Usually, the shape of the thumbnail is dependent on the original image, but in this article, we are going to generate the circular and square thumbnail image using Pillow Library in Python. Installation: For installing pillow and NumPy libraries, write the following command on your command prompt. pip install pillow pip install numpy Example 1: Opening image using Pillow Library. Python # importing necessary librariesfrom PIL import Image # opening the image from the storage using # Image.open() functionorig_img=Image.open('Geekwork/sebastian-molina.jpg') # showing the image using show() functionorig_img.show() Output: Example 2: Generating circular thumbnail image using Pillow Library. Approach: Convert the image into NumPy array using NumPy library. Now create a new mask image using PIL.Image.new() function by pass the mode, image size, and color, then draw the image using PIL.Image.Draw.Draw() function by passing the size of the new mask image and let be stored in the variable named “draw”. Make the circle on the mask image using ImageDraw.Draw.peislice() function by passing four points to define a boundary, starting angle=0, ending angle=360 this creates the circle on the mask image and with them pass fill parameter for filling the color in an image. Convert the mask image to numpy array then stack the array depth-wise along with the third axis using numpy.dstack() function and pass the original image array and mask image array as we had converted in above steps to get the circular image, and let it be stored in the variable named as “npImage”. As this “npImage” is in array format we have to convert this array into an image, this is done with the help of PIL.Image.fromarray() function into this pass npImage as a parameter and let it be stored in the variable named as “final_image”. As we had generated the circular image. Below is the full implementation: Python # importing necessary librariesfrom PIL import Image, ImageDrawimport numpy as np # opening the image from# the storage using Image.open() functionorig_img=Image.open('sebastian-molina.jpg') # getting height and width of # an image using size() functionheight,width=orig_img.size # converting image to numpy arraynpImage=np.array(orig_img) # Creating mask image in L mode with same image sizenew_img = Image.new('L', orig_img.size,0) # drawing on mask created image using Draw() functiondraw = ImageDraw.Draw(new_img) # making circle on mask image using pieslice() functiondraw.pieslice([0,0,height,width],0,360,fill=255) # Converting the mask Image to numpy arraynp_new=np.array(new_img) # stack the array sequence# (original image array with mask image) depth wisenpImage=np.dstack((npImage,np_new)) # converting array to an image using fromarray() functionfinal_img = Image.fromarray(npImage) # making thumbnail using thumbnail() # function by passing the size in itfinal_img.thumbnail((500,500)) # saving the circular thumbnail Imagefinal_img.save('Circular_thumbnail.png') Output: Example 3: Generating square thumbnail image using Pillow Library. Approach: Check the three conditions if height==width or height>width or width>height if the dimension of the image falls in any of the last two conditions. Then we have to create the new mask image using new() function with the longest side/dimension of the image. Then paste the original image on the new mask image by using paste() function and pass the original image with calculated dimensions which we will discuss in the explanation of the example. Now we will get the square image by following the above steps. Now we have to generate the thumbnail image, we can do this by using PIL.Image.thumbnail() method by passing the size as a parameter, then save this using PIL.Image.save() method and pass the name of the image with standard image format. Below is the full implementation: Python # importing necessary librariesfrom PIL import Image, ImageDrawimport numpy as np # function to generate squared imagedef square_thumb(thum_img,width,height): # checking if height and width are # are equal then return image as it is if height == width: return thum_img # checking if height is greater than width elif height > width: # creating the new mask image of size i,e height of Image square_img = Image.new(thum_img.mode, (height, height)) # pasting the original image on mask image # using paste() function to make it square square_img.paste(thum_img, ((height - width) // 2,0)) # returning the generated square image return square_img # if width is greater than height else: # creating the new mask image of size i,e width of Image square_img = Image.new(thum_img.mode, (width, width)) # pasting the original image on mask image using paste() # function to make it square square_img.paste(thum_img, (0, (width - height) // 2)) # returning the generated square image return square_img # main function if __name__ == "__main__": # opening the image from the storage # using Image.open() function orig_img=Image.open('sebastian-molina.jpg') # extracting width and height of an # image from the image size w,h = orig_img.size # calling the function by passing # image width and height as a parameter sq_img = square_thumb(orig_img,w,h) # generating square thumbnail of # required size using thumbnail() function sq_img.thumbnail((400,400)) # saving the thumbnail using save function sq_img.save('Square_thumbnail.jpg') Output: Explanation: We had created the function to generate a square image by passing the image, it’s width and height as a parameter. In the function we had checked three conditions on the basis of that we had generated the square image. In the first condition, we had checked if the height of the image is equal to the width or not if True then we had returned the image as it is because when height and width are equal images is already in the square shape. In the second condition, if the height of an image is greater than the width, then we created the new mask image using Image.new() function by passing the mode of an image and size as it’s the height (i.e, height, height) and paste the original image on the created mask image using paste() function by passing original image and dimension at which original image is pasted on mask image i.e, from calculated dimension (subtracting the height of original image with a width of the original image and then divide it by 2) to 0, so that original image can be perfectly pasted on the mask image. In the third condition, if the width of an image is greater than the height, then we did the same process as we had done in the second condition, but the only change is we had created the mask image of size as it’s the width (i.e, width, width) and in case of pasting we had to pass original image and dimension i.e, from 0 to the calculated dimension (by subtracting the width of the original image with a height of the original image and then divide it by 2 ) so that original image can be perfectly pasted on the mask image. Picked Python-pil Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n17 Mar, 2021" }, { "code": null, "e": 24241, "s": 24212, "text": "Prerequisites: Pillow, Numpy" }, { "code": null, "e": 24506, "s": 24241, "text": "In the word “THUMBNAIL” the word THUMB means short. A thumbnail is the compressed preview image of the original image or a Thumbnail is the smaller version of an image. In simple words, the thumbnail is the smaller image that represents the larger/original image. " }, { "code": null, "e": 24696, "s": 24506, "text": "Usually, the shape of the thumbnail is dependent on the original image, but in this article, we are going to generate the circular and square thumbnail image using Pillow Library in Python." }, { "code": null, "e": 24710, "s": 24696, "text": "Installation:" }, { "code": null, "e": 24805, "s": 24710, "text": "For installing pillow and NumPy libraries, write the following command on your command prompt." }, { "code": null, "e": 24842, "s": 24805, "text": "pip install pillow\npip install numpy" }, { "code": null, "e": 24889, "s": 24842, "text": "Example 1: Opening image using Pillow Library." }, { "code": null, "e": 24896, "s": 24889, "text": "Python" }, { "code": "# importing necessary librariesfrom PIL import Image # opening the image from the storage using # Image.open() functionorig_img=Image.open('Geekwork/sebastian-molina.jpg') # showing the image using show() functionorig_img.show()", "e": 25127, "s": 24896, "text": null }, { "code": null, "e": 25135, "s": 25127, "text": "Output:" }, { "code": null, "e": 25204, "s": 25135, "text": "Example 2: Generating circular thumbnail image using Pillow Library." }, { "code": null, "e": 25214, "s": 25204, "text": "Approach:" }, { "code": null, "e": 25270, "s": 25214, "text": "Convert the image into NumPy array using NumPy library." }, { "code": null, "e": 25517, "s": 25270, "text": "Now create a new mask image using PIL.Image.new() function by pass the mode, image size, and color, then draw the image using PIL.Image.Draw.Draw() function by passing the size of the new mask image and let be stored in the variable named “draw”." }, { "code": null, "e": 25783, "s": 25517, "text": "Make the circle on the mask image using ImageDraw.Draw.peislice() function by passing four points to define a boundary, starting angle=0, ending angle=360 this creates the circle on the mask image and with them pass fill parameter for filling the color in an image." }, { "code": null, "e": 26083, "s": 25783, "text": "Convert the mask image to numpy array then stack the array depth-wise along with the third axis using numpy.dstack() function and pass the original image array and mask image array as we had converted in above steps to get the circular image, and let it be stored in the variable named as “npImage”." }, { "code": null, "e": 26325, "s": 26083, "text": "As this “npImage” is in array format we have to convert this array into an image, this is done with the help of PIL.Image.fromarray() function into this pass npImage as a parameter and let it be stored in the variable named as “final_image”." }, { "code": null, "e": 26365, "s": 26325, "text": "As we had generated the circular image." }, { "code": null, "e": 26399, "s": 26365, "text": "Below is the full implementation:" }, { "code": null, "e": 26406, "s": 26399, "text": "Python" }, { "code": "# importing necessary librariesfrom PIL import Image, ImageDrawimport numpy as np # opening the image from# the storage using Image.open() functionorig_img=Image.open('sebastian-molina.jpg') # getting height and width of # an image using size() functionheight,width=orig_img.size # converting image to numpy arraynpImage=np.array(orig_img) # Creating mask image in L mode with same image sizenew_img = Image.new('L', orig_img.size,0) # drawing on mask created image using Draw() functiondraw = ImageDraw.Draw(new_img) # making circle on mask image using pieslice() functiondraw.pieslice([0,0,height,width],0,360,fill=255) # Converting the mask Image to numpy arraynp_new=np.array(new_img) # stack the array sequence# (original image array with mask image) depth wisenpImage=np.dstack((npImage,np_new)) # converting array to an image using fromarray() functionfinal_img = Image.fromarray(npImage) # making thumbnail using thumbnail() # function by passing the size in itfinal_img.thumbnail((500,500)) # saving the circular thumbnail Imagefinal_img.save('Circular_thumbnail.png')", "e": 27495, "s": 26406, "text": null }, { "code": null, "e": 27503, "s": 27495, "text": "Output:" }, { "code": null, "e": 27570, "s": 27503, "text": "Example 3: Generating square thumbnail image using Pillow Library." }, { "code": null, "e": 27580, "s": 27570, "text": "Approach:" }, { "code": null, "e": 27727, "s": 27580, "text": "Check the three conditions if height==width or height>width or width>height if the dimension of the image falls in any of the last two conditions." }, { "code": null, "e": 27836, "s": 27727, "text": "Then we have to create the new mask image using new() function with the longest side/dimension of the image." }, { "code": null, "e": 28026, "s": 27836, "text": "Then paste the original image on the new mask image by using paste() function and pass the original image with calculated dimensions which we will discuss in the explanation of the example." }, { "code": null, "e": 28089, "s": 28026, "text": "Now we will get the square image by following the above steps." }, { "code": null, "e": 28327, "s": 28089, "text": "Now we have to generate the thumbnail image, we can do this by using PIL.Image.thumbnail() method by passing the size as a parameter, then save this using PIL.Image.save() method and pass the name of the image with standard image format." }, { "code": null, "e": 28361, "s": 28327, "text": "Below is the full implementation:" }, { "code": null, "e": 28368, "s": 28361, "text": "Python" }, { "code": "# importing necessary librariesfrom PIL import Image, ImageDrawimport numpy as np # function to generate squared imagedef square_thumb(thum_img,width,height): # checking if height and width are # are equal then return image as it is if height == width: return thum_img # checking if height is greater than width elif height > width: # creating the new mask image of size i,e height of Image square_img = Image.new(thum_img.mode, (height, height)) # pasting the original image on mask image # using paste() function to make it square square_img.paste(thum_img, ((height - width) // 2,0)) # returning the generated square image return square_img # if width is greater than height else: # creating the new mask image of size i,e width of Image square_img = Image.new(thum_img.mode, (width, width)) # pasting the original image on mask image using paste() # function to make it square square_img.paste(thum_img, (0, (width - height) // 2)) # returning the generated square image return square_img # main function if __name__ == \"__main__\": # opening the image from the storage # using Image.open() function orig_img=Image.open('sebastian-molina.jpg') # extracting width and height of an # image from the image size w,h = orig_img.size # calling the function by passing # image width and height as a parameter sq_img = square_thumb(orig_img,w,h) # generating square thumbnail of # required size using thumbnail() function sq_img.thumbnail((400,400)) # saving the thumbnail using save function sq_img.save('Square_thumbnail.jpg')", "e": 30141, "s": 28368, "text": null }, { "code": null, "e": 30149, "s": 30141, "text": "Output:" }, { "code": null, "e": 30381, "s": 30149, "text": "Explanation: We had created the function to generate a square image by passing the image, it’s width and height as a parameter. In the function we had checked three conditions on the basis of that we had generated the square image." }, { "code": null, "e": 30603, "s": 30381, "text": "In the first condition, we had checked if the height of the image is equal to the width or not if True then we had returned the image as it is because when height and width are equal images is already in the square shape." }, { "code": null, "e": 31196, "s": 30603, "text": "In the second condition, if the height of an image is greater than the width, then we created the new mask image using Image.new() function by passing the mode of an image and size as it’s the height (i.e, height, height) and paste the original image on the created mask image using paste() function by passing original image and dimension at which original image is pasted on mask image i.e, from calculated dimension (subtracting the height of original image with a width of the original image and then divide it by 2) to 0, so that original image can be perfectly pasted on the mask image." }, { "code": null, "e": 31724, "s": 31196, "text": "In the third condition, if the width of an image is greater than the height, then we did the same process as we had done in the second condition, but the only change is we had created the mask image of size as it’s the width (i.e, width, width) and in case of pasting we had to pass original image and dimension i.e, from 0 to the calculated dimension (by subtracting the width of the original image with a height of the original image and then divide it by 2 ) so that original image can be perfectly pasted on the mask image." }, { "code": null, "e": 31731, "s": 31724, "text": "Picked" }, { "code": null, "e": 31742, "s": 31731, "text": "Python-pil" }, { "code": null, "e": 31766, "s": 31742, "text": "Technical Scripter 2020" }, { "code": null, "e": 31773, "s": 31766, "text": "Python" }, { "code": null, "e": 31792, "s": 31773, "text": "Technical Scripter" }, { "code": null, "e": 31890, "s": 31792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31899, "s": 31890, "text": "Comments" }, { "code": null, "e": 31912, "s": 31899, "text": "Old Comments" }, { "code": null, "e": 31944, "s": 31912, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31999, "s": 31944, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 32055, "s": 31999, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32094, "s": 32055, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32136, "s": 32094, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32178, "s": 32136, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32200, "s": 32178, "text": "Defaultdict in Python" }, { "code": null, "e": 32231, "s": 32200, "text": "Python | os.path.join() method" }, { "code": null, "e": 32260, "s": 32231, "text": "Create a directory in Python" } ]
Chi-Squared Test for Feature Selection with implementation in Python | by Yaser Sakkaf | Towards Data Science
There are various techniques in machine learning to determining whether our input features are relevant to the outcome to be predicted or not. We can use these techniques to find out and remove unimportant features that do not contribute to the outcome of our model. In a way we select only those features that actually matter, hence these techniques are called as Feature Selection methods. Chi-Squared test can be used for Feature Selection. Let’s dive into the details. There are many methods to determine feature importance which are mainly divided into two groups: 1) Filter feature selection methods2) Wrapper feature selection methods We will only see the first one since our Chi-Squared test falls in this category. Briefly, Filter feature selection methods are those that use some statistical techniques (like Chi-Squared test) considering the data type of the input and target variable to evaluate the relationship between them. There are many other statistical measures that can be used for filter-based feature selection. As such, the choice of statistical measures is highly dependent upon the feature and target variable data types. The data types can either be numerical or categorical. When the data type of our feature to be tested and the target variable are both categorical (i.e. we have a classification problem) we can use Chi-Squared test. The Pearson’s Chi-Squared test, or just Chi-Squared test, is named after the mathematician Karl Pearson. It is also called a “goodness of fit” statistic. Let’s see how to perform this test along with an example in 8 simple steps. For example’s sake let’s consider a very simple dataset with only two columns. We will find out if Gender is related/dependent/associated to the interest in sports or not. ╔════════╦══════════╗║ Gender ║ Interest ║╠════════╬══════════╣║ Male ║ Cricket ║║ Female ║ Tennis ║║ Male ║ Cricket ║║ Male ║ Football ║║ .... ║ .... ║╚════════╩══════════╝ A Hypothesis Test is a statistical method which evaluates two statements(hypothesis) and determines which statement is true. In hypothesis testing the initial statement is called a Null Hypothesis denoted as H0 and the second one that is usually complementary to the first one is called the Alternate Hypothesis denoted as H1. For our example, the hypothesis are:H0: The features Gender and Interest are independent (which means they are not associated).H1: Gender and Interest are not independent (which means they are associated). Basically, the significance level denoted by α (alpha) is a measure of how certain we want to be about our results. Or in simple words significance level is used to determine whether the null hypothesis should be rejected or not. For the null hypothesis to be rejected the p-value(explained later) should be less than the significance level. Lower α values are generally preferred which may be in the range of 0.01 to 0.10. We choose α = 0.05 A table showing the frequency distribution of one variable in rows and another in columns, used to study the correlation between the two variables is called a contingency table (also known as a cross tabulation or crosstab). You will be more clear after seeing the table below: ╔══════════════╦═════════╦══════════╦════════╦═══════════╗║ ║ Cricket ║ Football ║ Tennis ║ Row Total ║╠══════════════╬═════════╬══════════╬════════╬═══════════╣║ Male ║ 20 ║ 30 ║ 15 ║ 65 ║║ Female ║ 20 ║ 15 ║ 30 ║ 65 ║║ Column Total ║ 40 ║ 45 ║ 45 ║ 130 ║╚══════════════╩═════════╩══════════╩════════╩═══════════╝ We can see that out of 130 candidates, in the dataset, there are 20, 30 and 15 males interested in Cricket, Football and Tennis respectively. Similarly 20, 15 and 30 Females are interested in Cricket, Football and Tennis respectively. The values in the table are called as observed values. We calculate the expected frequecy count for each cell. The formula to count expected frequncy is: E = (row total * column total)/grand total The Expected frequency for first cell (i.e. Male-Cricket) will be: E1 = (65 * 40)/130 = 20 We calculate Expected Frequency for rest of the cells and get the table below where values in brackets ‘[]’ denote expected frequencies: ╔══════════════╦═════════╦════════════╦═══════════╦═══════════╗║ ║ Cricket ║ Football ║ Tennis ║ Row Total ║╠══════════════╬═════════╬════════════╬═══════════╬═══════════╣║ Male ║ 20 [20] ║ 30 [22.5] ║ 15 [22.5] ║ 65 ║║ Female ║ 20 [20] ║ 15 [22.5] ║ 30 [22.5] ║ 65 ║║ Column Total ║ 40 ║ 45 ║ 45 ║ 130 ║╚══════════════╩═════════╩════════════╩═══════════╩═══════════╝ The formula to calculate Chi-square value or Χ 2 is: where Χ is not the english aphabet we know but the 22nd Greek alphabet Chi.As shown, Χ 2 is the summation of the squared difference between Observed and Expected frequencies divided by the Expected frequency for all the cells. The calculations are shown below: Χ2 = ((20-20)^2/20) + ((30-22.5)^2/22.5) + ((15-22.5)^2/22.5) + ((20-20)^2/20) + ((15-22.5)^2/22.5) + ((30-22.5)^2/22.5)Χ2 = 0 + 2.5 + 2.5 + 0 + 2.5 + 2.5Χ2 = 10 The degrees of freedom can be calculated as: df = (total_rows - 1) * (total_cols - 1) There are 2 rows and 3 columns in the contingency table, hence our degrees of freedom is 2. We can see the Chi Square distribution tables like this one to find the p-value using the Chi Square and degrees of freedom values. If you opened the link to the table, choose the degrees of freedom value (2) on the left, follow along its row to the closest number to the Chi-Square value (10), and then check the corresponding number in the first row to get the p-value which is 0.005 There are also some websites that calculate the p-value for you like this one.Here we get the p-value as .0067, we can use any one of them, let’s go ahead with the one obtained from the table. In simple words if our p value is less than the significance value we reject the Null Hypothesis and if our p value is greater than the significance value we do not reject it. Since 0.005 is less than our significance value of 0.05 we reject the Null Hypothesis which means that there is as association between Gender and the sport of interest. # required importsfrom scipy.stats import chi2_contingency# we create contingency table same as abovetable = [[20, 30, 15], [20, 15, 30]]# Get chi-square value , p-value, degrees of freedom, expected frequencies using the function chi2_contingencystat, p, dof, expected = chi2_contingency(table)# select significance valuealpha = 0.05# Determine whether to reject or keep your null hypothesisprint('significance=%.3f, p=%.3f' % (alpha, p))if p <= alpha: print('Variables are associated (reject H0)')else: print('Variables are not associated(fail to reject H0)') For simplicity I created a contingency table sing a list of lists. To create a contingency table out of your dataframe columns you can use this crosstab function available in pandas. We have seen how to perform a Chi-Squared Test to check if there some relation between two categorical variables or not. In very few lines we can implement this test using Python’s scipy library. Hope you liked it. Suggestions are always welcome.
[ { "code": null, "e": 645, "s": 172, "text": "There are various techniques in machine learning to determining whether our input features are relevant to the outcome to be predicted or not. We can use these techniques to find out and remove unimportant features that do not contribute to the outcome of our model. In a way we select only those features that actually matter, hence these techniques are called as Feature Selection methods. Chi-Squared test can be used for Feature Selection. Let’s dive into the details." }, { "code": null, "e": 742, "s": 645, "text": "There are many methods to determine feature importance which are mainly divided into two groups:" }, { "code": null, "e": 814, "s": 742, "text": "1) Filter feature selection methods2) Wrapper feature selection methods" }, { "code": null, "e": 896, "s": 814, "text": "We will only see the first one since our Chi-Squared test falls in this category." }, { "code": null, "e": 1111, "s": 896, "text": "Briefly, Filter feature selection methods are those that use some statistical techniques (like Chi-Squared test) considering the data type of the input and target variable to evaluate the relationship between them." }, { "code": null, "e": 1319, "s": 1111, "text": "There are many other statistical measures that can be used for filter-based feature selection. As such, the choice of statistical measures is highly dependent upon the feature and target variable data types." }, { "code": null, "e": 1374, "s": 1319, "text": "The data types can either be numerical or categorical." }, { "code": null, "e": 1535, "s": 1374, "text": "When the data type of our feature to be tested and the target variable are both categorical (i.e. we have a classification problem) we can use Chi-Squared test." }, { "code": null, "e": 1689, "s": 1535, "text": "The Pearson’s Chi-Squared test, or just Chi-Squared test, is named after the mathematician Karl Pearson. It is also called a “goodness of fit” statistic." }, { "code": null, "e": 1765, "s": 1689, "text": "Let’s see how to perform this test along with an example in 8 simple steps." }, { "code": null, "e": 1937, "s": 1765, "text": "For example’s sake let’s consider a very simple dataset with only two columns. We will find out if Gender is related/dependent/associated to the interest in sports or not." }, { "code": null, "e": 2127, "s": 1937, "text": "╔════════╦══════════╗║ Gender ║ Interest ║╠════════╬══════════╣║ Male ║ Cricket ║║ Female ║ Tennis ║║ Male ║ Cricket ║║ Male ║ Football ║║ .... ║ .... ║╚════════╩══════════╝" }, { "code": null, "e": 2454, "s": 2127, "text": "A Hypothesis Test is a statistical method which evaluates two statements(hypothesis) and determines which statement is true. In hypothesis testing the initial statement is called a Null Hypothesis denoted as H0 and the second one that is usually complementary to the first one is called the Alternate Hypothesis denoted as H1." }, { "code": null, "e": 2660, "s": 2454, "text": "For our example, the hypothesis are:H0: The features Gender and Interest are independent (which means they are not associated).H1: Gender and Interest are not independent (which means they are associated)." }, { "code": null, "e": 2776, "s": 2660, "text": "Basically, the significance level denoted by α (alpha) is a measure of how certain we want to be about our results." }, { "code": null, "e": 3002, "s": 2776, "text": "Or in simple words significance level is used to determine whether the null hypothesis should be rejected or not. For the null hypothesis to be rejected the p-value(explained later) should be less than the significance level." }, { "code": null, "e": 3084, "s": 3002, "text": "Lower α values are generally preferred which may be in the range of 0.01 to 0.10." }, { "code": null, "e": 3103, "s": 3084, "text": "We choose α = 0.05" }, { "code": null, "e": 3381, "s": 3103, "text": "A table showing the frequency distribution of one variable in rows and another in columns, used to study the correlation between the two variables is called a contingency table (also known as a cross tabulation or crosstab). You will be more clear after seeing the table below:" }, { "code": null, "e": 3788, "s": 3381, "text": "╔══════════════╦═════════╦══════════╦════════╦═══════════╗║ ║ Cricket ║ Football ║ Tennis ║ Row Total ║╠══════════════╬═════════╬══════════╬════════╬═══════════╣║ Male ║ 20 ║ 30 ║ 15 ║ 65 ║║ Female ║ 20 ║ 15 ║ 30 ║ 65 ║║ Column Total ║ 40 ║ 45 ║ 45 ║ 130 ║╚══════════════╩═════════╩══════════╩════════╩═══════════╝" }, { "code": null, "e": 4023, "s": 3788, "text": "We can see that out of 130 candidates, in the dataset, there are 20, 30 and 15 males interested in Cricket, Football and Tennis respectively. Similarly 20, 15 and 30 Females are interested in Cricket, Football and Tennis respectively." }, { "code": null, "e": 4078, "s": 4023, "text": "The values in the table are called as observed values." }, { "code": null, "e": 4177, "s": 4078, "text": "We calculate the expected frequecy count for each cell. The formula to count expected frequncy is:" }, { "code": null, "e": 4220, "s": 4177, "text": "E = (row total * column total)/grand total" }, { "code": null, "e": 4287, "s": 4220, "text": "The Expected frequency for first cell (i.e. Male-Cricket) will be:" }, { "code": null, "e": 4311, "s": 4287, "text": "E1 = (65 * 40)/130 = 20" }, { "code": null, "e": 4448, "s": 4311, "text": "We calculate Expected Frequency for rest of the cells and get the table below where values in brackets ‘[]’ denote expected frequencies:" }, { "code": null, "e": 4890, "s": 4448, "text": "╔══════════════╦═════════╦════════════╦═══════════╦═══════════╗║ ║ Cricket ║ Football ║ Tennis ║ Row Total ║╠══════════════╬═════════╬════════════╬═══════════╬═══════════╣║ Male ║ 20 [20] ║ 30 [22.5] ║ 15 [22.5] ║ 65 ║║ Female ║ 20 [20] ║ 15 [22.5] ║ 30 [22.5] ║ 65 ║║ Column Total ║ 40 ║ 45 ║ 45 ║ 130 ║╚══════════════╩═════════╩════════════╩═══════════╩═══════════╝" }, { "code": null, "e": 4943, "s": 4890, "text": "The formula to calculate Chi-square value or Χ 2 is:" }, { "code": null, "e": 5204, "s": 4943, "text": "where Χ is not the english aphabet we know but the 22nd Greek alphabet Chi.As shown, Χ 2 is the summation of the squared difference between Observed and Expected frequencies divided by the Expected frequency for all the cells. The calculations are shown below:" }, { "code": null, "e": 5366, "s": 5204, "text": "Χ2 = ((20-20)^2/20) + ((30-22.5)^2/22.5) + ((15-22.5)^2/22.5) + ((20-20)^2/20) + ((15-22.5)^2/22.5) + ((30-22.5)^2/22.5)Χ2 = 0 + 2.5 + 2.5 + 0 + 2.5 + 2.5Χ2 = 10" }, { "code": null, "e": 5411, "s": 5366, "text": "The degrees of freedom can be calculated as:" }, { "code": null, "e": 5452, "s": 5411, "text": "df = (total_rows - 1) * (total_cols - 1)" }, { "code": null, "e": 5544, "s": 5452, "text": "There are 2 rows and 3 columns in the contingency table, hence our degrees of freedom is 2." }, { "code": null, "e": 5676, "s": 5544, "text": "We can see the Chi Square distribution tables like this one to find the p-value using the Chi Square and degrees of freedom values." }, { "code": null, "e": 5930, "s": 5676, "text": "If you opened the link to the table, choose the degrees of freedom value (2) on the left, follow along its row to the closest number to the Chi-Square value (10), and then check the corresponding number in the first row to get the p-value which is 0.005" }, { "code": null, "e": 6123, "s": 5930, "text": "There are also some websites that calculate the p-value for you like this one.Here we get the p-value as .0067, we can use any one of them, let’s go ahead with the one obtained from the table." }, { "code": null, "e": 6299, "s": 6123, "text": "In simple words if our p value is less than the significance value we reject the Null Hypothesis and if our p value is greater than the significance value we do not reject it." }, { "code": null, "e": 6468, "s": 6299, "text": "Since 0.005 is less than our significance value of 0.05 we reject the Null Hypothesis which means that there is as association between Gender and the sport of interest." }, { "code": null, "e": 7038, "s": 6468, "text": "# required importsfrom scipy.stats import chi2_contingency# we create contingency table same as abovetable = [[20, 30, 15], [20, 15, 30]]# Get chi-square value , p-value, degrees of freedom, expected frequencies using the function chi2_contingencystat, p, dof, expected = chi2_contingency(table)# select significance valuealpha = 0.05# Determine whether to reject or keep your null hypothesisprint('significance=%.3f, p=%.3f' % (alpha, p))if p <= alpha: print('Variables are associated (reject H0)')else: print('Variables are not associated(fail to reject H0)')" }, { "code": null, "e": 7221, "s": 7038, "text": "For simplicity I created a contingency table sing a list of lists. To create a contingency table out of your dataframe columns you can use this crosstab function available in pandas." }, { "code": null, "e": 7342, "s": 7221, "text": "We have seen how to perform a Chi-Squared Test to check if there some relation between two categorical variables or not." }, { "code": null, "e": 7417, "s": 7342, "text": "In very few lines we can implement this test using Python’s scipy library." } ]
Find if an array of strings can be chained to form a circle | Set 1
23 Jun, 2022 Given an array of strings, find if the given strings can be chained to form a circle. A string X can be put before another string Y in circle if the last character of X is same as first character of Y.Examples: Input: arr[] = {"geek", "king"} Output: Yes, the given strings can be chained. Note that the last character of first string is same as first character of second string and vice versa is also true. Input: arr[] = {"for", "geek", "rig", "kaf"} Output: Yes, the given strings can be chained. The strings can be chained as "for", "rig", "geek" and "kaf" Input: arr[] = {"aab", "bac", "aaa", "cda"} Output: Yes, the given strings can be chained. The strings can be chained as "aaa", "aab", "bac" and "cda" Input: arr[] = {"aaa", "bbb", "baa", "aab"}; Output: Yes, the given strings can be chained. The strings can be chained as "aaa", "aab", "bbb" and "baa" Input: arr[] = {"aaa"}; Output: Yes Input: arr[] = {"aaa", "bbb"}; Output: No Input : arr[] = ["abc", "efg", "cde", "ghi", "ija"] Output : Yes These strings can be reordered as, “abc”, “cde”, “efg”, “ghi”, “ija” Input : arr[] = [“ijk”, “kji”, “abc”, “cba”] Output : No The idea is to create a directed graph of all characters and then find if their is an eulerian circuit in the graph or not. Graph representation of some string arrays are given in below diagram, If there is an eulerian circuit, then chain can be formed, otherwise not. Note that a directed graph has eulerian circuit only if in degree and out degree of every vertex is same, and all non-zero degree vertices form a single strongly connected component. Following are detailed steps of the algorithm. Create a directed graph g with number of vertices equal to the size of alphabet. We have created a graph with 26 vertices in the below program.Do following for every string in the given array of strings. .....a) Add an edge from first character to last character of the given graph.If the created graph has eulerian circuit, then return true, else return false. Create a directed graph g with number of vertices equal to the size of alphabet. We have created a graph with 26 vertices in the below program. Do following for every string in the given array of strings. .....a) Add an edge from first character to last character of the given graph. .....a) Add an edge from first character to last character of the given graph. If the created graph has eulerian circuit, then return true, else return false. Following are C++ and Python implementations of the above algorithm. C++ Java Python3 // A C++ program to check if a given// directed graph is Eulerian or not#include<iostream>#include <list>#define CHARS 26using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists int *in;public: // Constructor and destructor Graph(int V); ~Graph() { delete [] adj; delete [] in; } // function to add an edge to graph void addEdge(int v, int w) { adj[v].push_back(w); (in[w])++; } // Method to check if this graph is Eulerian or not bool isEulerianCycle(); // Method to check if all non-zero degree // vertices are connected bool isSC(); // Function to do DFS starting from v. Used in isConnected(); void DFSUtil(int v, bool visited[]); Graph getTranspose();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V]; in = new int[V]; for (int i = 0; i < V; i++) in[i] = 0;} /* This function returns true if the directed graph has an eulerian cycle, otherwise returns false */bool Graph::isEulerianCycle(){ // Check if all non-zero degree vertices are connected if (isSC() == false) return false; // Check if in degree and out degree // of every vertex is same for (int i = 0; i < V; i++) if (adj[i].size() != in[i]) return false; return true;} // A recursive function to do DFS starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Function that returns reverse (or transpose) of this graph// This function is needed in isSC()Graph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); (g.in[v])++; } } return g;} // This function returns true if all non-zero// degree vertices of graph are strongly connected.// Please refer// https://www.geeksforgeeks.org/connectivity-in-a-directed-graph/bool Graph::isSC(){ // Mark all the vertices as not visited (For first DFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Find the first vertex with non-zero degree int n; for (n = 0; n < V; n++) if (adj[n].size() > 0) break; // Do DFS traversal starting from first non zero degree vertex. DFSUtil(n, visited); // If DFS traversal doesn’t visit all vertices, then return false. for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(n, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; return true;} // This function takes an of strings and returns true// if the given array of strings can be chained to// form cyclebool canBeChained(string arr[], int n){ // Create a graph with 'alpha' edges Graph g(CHARS); // Create an edge from first character to last character // of every string for (int i = 0; i < n; i++) { string s = arr[i]; g.addEdge(s[0]-'a', s[s.length()-1]-'a'); } // The given array of strings can be chained if there // is an eulerian cycle in the created graph return g.isEulerianCycle();} // Driver program to test above functionsint main(){ string arr1[] = {"for", "geek", "rig", "kaf"}; int n1 = sizeof(arr1)/sizeof(arr1[0]); canBeChained(arr1, n1)? cout << "Can be chained \n" : cout << "Can't be chained \n"; string arr2[] = {"aab", "abb"}; int n2 = sizeof(arr2)/sizeof(arr2[0]); canBeChained(arr2, n2)? cout << "Can be chained \n" : cout << "Can't be chained \n"; return 0;} // Java program to check if a given// directed graph is Eulerian or notimport java.util.ArrayList;import java.util.List; // A class that represents an// undirected graphclass GFG{ static final int CHARS = 26; // No. of verticesint V; // A dynamic array of adjacency listsList<List<Integer>> adj;int[] in; // ConstructorGFG(int V){ this.V = V; in = new int[V]; adj = new ArrayList<>(CHARS); for(int i = 0; i < CHARS; i++) { adj.add(i, new ArrayList<>()); }} // Function to add an edge to graphvoid addEdge(int v, int w){ adj.get(v).add(w); in[w]++;} // Method to check if this graph// is Eulerian or notboolean isEulerianCycle(){ // Check if all non-zero degree // vertices are connected if (!isSC()) return false; // Check if in degree and out // degree of every vertex is same for(int i = 0; i < V; i++) if (adj.get(i).size() != in[i]) return false; return true;} // This function returns true if all// non-zero degree vertices of graph// are strongly connected. Please referboolean isSC(){ // Mark all the vertices as not // visited (For first DFS) boolean[] visited = new boolean[V]; for(int i = 0; i < V; i++) visited[i] = false; // Find the first vertex with // non-zero degree int n; for(n = 0; n < V; n++) if (adj.get(n).size() > 0) break; // Do DFS traversal starting from // first non zero degree vertex. DFSUtil(n, visited); // If DFS traversal doesn't visit all // vertices, then return false. for(int i = 0; i < V; i++) if (adj.get(i).size() > 0 && !visited[i]) return false; // Create a reversed graph GFG gr = getTranspose(); // Mark all the vertices as not // visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Do DFS for reversed graph starting // from first vertex. Starting Vertex // must be same starting point of first DFS gr.DFSUtil(n, visited); // If all vertices are not visited in // second DFS, then return false for(int i = 0; i < V; i++) if (adj.get(i).size() > 0 && !visited[i]) return false; return true;} // Function to do DFS starting from v.// Used in isConnected();// A recursive function to do DFS// starting from vvoid DFSUtil(int v, boolean[] visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(Integer i : adj.get(v)) if (!visited[i]) { DFSUtil(i, visited); }} // Function that returns reverse// (or transpose) of this graph// This function is needed in isSC()GFG getTranspose(){ GFG g = new GFG(V); for(int v = 0; v < V; v++) { // Recur for all the vertices // adjacent to this vertex for(Integer i : adj.get(v)) { g.adj.get(i).add(v); g.in[v]++; } } return g;} // This function takes an of strings// and returns true if the given array// of strings can be chained to form cyclestatic boolean canBeChained(String[] arr, int n){ // Create a graph with 'alpha' edges GFG g = new GFG(CHARS); // Create an edge from first character // to last character of every string for(int i = 0; i < n; i++) { String s = arr[i]; g.addEdge(s.charAt(0) - 'a', s.charAt(s.length() - 1) - 'a'); } // The given array of strings can be // chained if there is an eulerian // cycle in the created graph return g.isEulerianCycle();} // Driver codepublic static void main(String[] args) throws Exception{ String[] arr1 = { "for", "geek", "rig", "kaf" }; int n1 = arr1.length; System.out.println((canBeChained(arr1, n1) ? "Can be chained " : "Can't be chained ")); String[] arr2 = { "aab", "abb" }; int n2 = arr2.length; System.out.println((canBeChained(arr2, n2) ? "Can be chained " : "Can't be chained "));}} // This code is contributed by abhay379201 # Python program to check if a given directed graph is Eulerian or notCHARS = 26 # A class that represents an undirected graphclass Graph(object): def __init__(self, V): self.V = V # No. of vertices self.adj = [[] for x in range(V)] # a dynamic array self.inp = [0] * V # function to add an edge to graph def addEdge(self, v, w): self.adj[v].append(w) self.inp[w]+=1 # Method to check if this graph is Eulerian or not def isSC(self): # Mark all the vertices as not visited (For first DFS) visited = [False] * self.V # Find the first vertex with non-zero degree n = 0 for n in range(self.V): if len(self.adj[n]) > 0: break # Do DFS traversal starting from first non zero degree vertex. self.DFSUtil(n, visited) # If DFS traversal doesn't visit all vertices, then return false. for i in range(self.V): if len(self.adj[i]) > 0 and visited[i] == False: return False # Create a reversed graph gr = self.getTranspose() # Mark all the vertices as not visited (For second DFS) for i in range(self.V): visited[i] = False # Do DFS for reversed graph starting from first vertex. # Starting Vertex must be same starting point of first DFS gr.DFSUtil(n, visited) # If all vertices are not visited in second DFS, then # return false for i in range(self.V): if len(self.adj[i]) > 0 and visited[i] == False: return False return True # This function returns true if the directed graph has an eulerian # cycle, otherwise returns false def isEulerianCycle(self): # Check if all non-zero degree vertices are connected if self.isSC() == False: return False # Check if in degree and out degree of every vertex is same for i in range(self.V): if len(self.adj[i]) != self.inp[i]: return False return True # A recursive function to do DFS starting from v def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v] = True # Recur for all the vertices adjacent to this vertex for i in range(len(self.adj[v])): if not visited[self.adj[v][i]]: self.DFSUtil(self.adj[v][i], visited) # Function that returns reverse (or transpose) of this graph # This function is needed in isSC() def getTranspose(self): g = Graph(self.V) for v in range(self.V): # Recur for all the vertices adjacent to this vertex for i in range(len(self.adj[v])): g.adj[self.adj[v][i]].append(v) g.inp[v]+=1 return g # This function takes an of strings and returns true# if the given array of strings can be chained to# form cycledef canBeChained(arr, n): # Create a graph with 'alpha' edges g = Graph(CHARS) # Create an edge from first character to last character # of every string for i in range(n): s = arr[i] g.addEdge(ord(s[0])-ord('a'), ord(s[len(s)-1])-ord('a')) # The given array of strings can be chained if there # is an eulerian cycle in the created graph return g.isEulerianCycle() # Driver programarr1 = ["for", "geek", "rig", "kaf"]n1 = len(arr1)if canBeChained(arr1, n1): print ("Can be chained")else: print ("Cant be chained") arr2 = ["aab", "abb"]n2 = len(arr2)if canBeChained(arr2, n2): print ("Can be chained")else: print ("Can't be chained") # This code is contributed by BHAVYA JAIN Can be chained Can't be chained Find if an array of strings can be chained to form a circle | Set 2 abhay379201 rajeev0719singh saurabh1990aror amartyaghoshgfg hardikkoriintern Accolite Amazon Euler-Circuit FactSet Graph Strings Accolite Amazon FactSet Strings Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 264, "s": 52, "text": "Given an array of strings, find if the given strings can be chained to form a circle. A string X can be put before another string Y in circle if the last character of X is same as first character of Y.Examples: " }, { "code": null, "e": 1197, "s": 264, "text": "Input: arr[] = {\"geek\", \"king\"}\nOutput: Yes, the given strings can be chained.\nNote that the last character of first string is same\nas first character of second string and vice versa is\nalso true.\n\nInput: arr[] = {\"for\", \"geek\", \"rig\", \"kaf\"}\nOutput: Yes, the given strings can be chained.\nThe strings can be chained as \"for\", \"rig\", \"geek\" \nand \"kaf\"\n\nInput: arr[] = {\"aab\", \"bac\", \"aaa\", \"cda\"}\nOutput: Yes, the given strings can be chained.\nThe strings can be chained as \"aaa\", \"aab\", \"bac\" \nand \"cda\"\n\nInput: arr[] = {\"aaa\", \"bbb\", \"baa\", \"aab\"};\nOutput: Yes, the given strings can be chained.\nThe strings can be chained as \"aaa\", \"aab\", \"bbb\" \nand \"baa\"\n\nInput: arr[] = {\"aaa\"};\nOutput: Yes\n\nInput: arr[] = {\"aaa\", \"bbb\"};\nOutput: No\n\nInput : arr[] = [\"abc\", \"efg\", \"cde\", \"ghi\", \"ija\"]\nOutput : Yes\nThese strings can be reordered as, “abc”, “cde”, “efg”,\n“ghi”, “ija”\n\nInput : arr[] = [“ijk”, “kji”, “abc”, “cba”]\nOutput : No" }, { "code": null, "e": 1393, "s": 1197, "text": "The idea is to create a directed graph of all characters and then find if their is an eulerian circuit in the graph or not. Graph representation of some string arrays are given in below diagram, " }, { "code": null, "e": 1468, "s": 1393, "text": "If there is an eulerian circuit, then chain can be formed, otherwise not. " }, { "code": null, "e": 1651, "s": 1468, "text": "Note that a directed graph has eulerian circuit only if in degree and out degree of every vertex is same, and all non-zero degree vertices form a single strongly connected component." }, { "code": null, "e": 1698, "s": 1651, "text": "Following are detailed steps of the algorithm." }, { "code": null, "e": 2060, "s": 1698, "text": "Create a directed graph g with number of vertices equal to the size of alphabet. We have created a graph with 26 vertices in the below program.Do following for every string in the given array of strings. .....a) Add an edge from first character to last character of the given graph.If the created graph has eulerian circuit, then return true, else return false." }, { "code": null, "e": 2204, "s": 2060, "text": "Create a directed graph g with number of vertices equal to the size of alphabet. We have created a graph with 26 vertices in the below program." }, { "code": null, "e": 2344, "s": 2204, "text": "Do following for every string in the given array of strings. .....a) Add an edge from first character to last character of the given graph." }, { "code": null, "e": 2423, "s": 2344, "text": ".....a) Add an edge from first character to last character of the given graph." }, { "code": null, "e": 2503, "s": 2423, "text": "If the created graph has eulerian circuit, then return true, else return false." }, { "code": null, "e": 2572, "s": 2503, "text": "Following are C++ and Python implementations of the above algorithm." }, { "code": null, "e": 2576, "s": 2572, "text": "C++" }, { "code": null, "e": 2581, "s": 2576, "text": "Java" }, { "code": null, "e": 2589, "s": 2581, "text": "Python3" }, { "code": "// A C++ program to check if a given// directed graph is Eulerian or not#include<iostream>#include <list>#define CHARS 26using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists int *in;public: // Constructor and destructor Graph(int V); ~Graph() { delete [] adj; delete [] in; } // function to add an edge to graph void addEdge(int v, int w) { adj[v].push_back(w); (in[w])++; } // Method to check if this graph is Eulerian or not bool isEulerianCycle(); // Method to check if all non-zero degree // vertices are connected bool isSC(); // Function to do DFS starting from v. Used in isConnected(); void DFSUtil(int v, bool visited[]); Graph getTranspose();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V]; in = new int[V]; for (int i = 0; i < V; i++) in[i] = 0;} /* This function returns true if the directed graph has an eulerian cycle, otherwise returns false */bool Graph::isEulerianCycle(){ // Check if all non-zero degree vertices are connected if (isSC() == false) return false; // Check if in degree and out degree // of every vertex is same for (int i = 0; i < V; i++) if (adj[i].size() != in[i]) return false; return true;} // A recursive function to do DFS starting from vvoid Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Function that returns reverse (or transpose) of this graph// This function is needed in isSC()Graph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); (g.in[v])++; } } return g;} // This function returns true if all non-zero// degree vertices of graph are strongly connected.// Please refer// https://www.geeksforgeeks.org/connectivity-in-a-directed-graph/bool Graph::isSC(){ // Mark all the vertices as not visited (For first DFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Find the first vertex with non-zero degree int n; for (n = 0; n < V; n++) if (adj[n].size() > 0) break; // Do DFS traversal starting from first non zero degree vertex. DFSUtil(n, visited); // If DFS traversal doesn’t visit all vertices, then return false. for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; // Do DFS for reversed graph starting from first vertex. // Starting Vertex must be same starting point of first DFS gr.DFSUtil(n, visited); // If all vertices are not visited in second DFS, then // return false for (int i = 0; i < V; i++) if (adj[i].size() > 0 && visited[i] == false) return false; return true;} // This function takes an of strings and returns true// if the given array of strings can be chained to// form cyclebool canBeChained(string arr[], int n){ // Create a graph with 'alpha' edges Graph g(CHARS); // Create an edge from first character to last character // of every string for (int i = 0; i < n; i++) { string s = arr[i]; g.addEdge(s[0]-'a', s[s.length()-1]-'a'); } // The given array of strings can be chained if there // is an eulerian cycle in the created graph return g.isEulerianCycle();} // Driver program to test above functionsint main(){ string arr1[] = {\"for\", \"geek\", \"rig\", \"kaf\"}; int n1 = sizeof(arr1)/sizeof(arr1[0]); canBeChained(arr1, n1)? cout << \"Can be chained \\n\" : cout << \"Can't be chained \\n\"; string arr2[] = {\"aab\", \"abb\"}; int n2 = sizeof(arr2)/sizeof(arr2[0]); canBeChained(arr2, n2)? cout << \"Can be chained \\n\" : cout << \"Can't be chained \\n\"; return 0;}", "e": 7045, "s": 2589, "text": null }, { "code": "// Java program to check if a given// directed graph is Eulerian or notimport java.util.ArrayList;import java.util.List; // A class that represents an// undirected graphclass GFG{ static final int CHARS = 26; // No. of verticesint V; // A dynamic array of adjacency listsList<List<Integer>> adj;int[] in; // ConstructorGFG(int V){ this.V = V; in = new int[V]; adj = new ArrayList<>(CHARS); for(int i = 0; i < CHARS; i++) { adj.add(i, new ArrayList<>()); }} // Function to add an edge to graphvoid addEdge(int v, int w){ adj.get(v).add(w); in[w]++;} // Method to check if this graph// is Eulerian or notboolean isEulerianCycle(){ // Check if all non-zero degree // vertices are connected if (!isSC()) return false; // Check if in degree and out // degree of every vertex is same for(int i = 0; i < V; i++) if (adj.get(i).size() != in[i]) return false; return true;} // This function returns true if all// non-zero degree vertices of graph// are strongly connected. Please referboolean isSC(){ // Mark all the vertices as not // visited (For first DFS) boolean[] visited = new boolean[V]; for(int i = 0; i < V; i++) visited[i] = false; // Find the first vertex with // non-zero degree int n; for(n = 0; n < V; n++) if (adj.get(n).size() > 0) break; // Do DFS traversal starting from // first non zero degree vertex. DFSUtil(n, visited); // If DFS traversal doesn't visit all // vertices, then return false. for(int i = 0; i < V; i++) if (adj.get(i).size() > 0 && !visited[i]) return false; // Create a reversed graph GFG gr = getTranspose(); // Mark all the vertices as not // visited (For second DFS) for(int i = 0; i < V; i++) visited[i] = false; // Do DFS for reversed graph starting // from first vertex. Starting Vertex // must be same starting point of first DFS gr.DFSUtil(n, visited); // If all vertices are not visited in // second DFS, then return false for(int i = 0; i < V; i++) if (adj.get(i).size() > 0 && !visited[i]) return false; return true;} // Function to do DFS starting from v.// Used in isConnected();// A recursive function to do DFS// starting from vvoid DFSUtil(int v, boolean[] visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(Integer i : adj.get(v)) if (!visited[i]) { DFSUtil(i, visited); }} // Function that returns reverse// (or transpose) of this graph// This function is needed in isSC()GFG getTranspose(){ GFG g = new GFG(V); for(int v = 0; v < V; v++) { // Recur for all the vertices // adjacent to this vertex for(Integer i : adj.get(v)) { g.adj.get(i).add(v); g.in[v]++; } } return g;} // This function takes an of strings// and returns true if the given array// of strings can be chained to form cyclestatic boolean canBeChained(String[] arr, int n){ // Create a graph with 'alpha' edges GFG g = new GFG(CHARS); // Create an edge from first character // to last character of every string for(int i = 0; i < n; i++) { String s = arr[i]; g.addEdge(s.charAt(0) - 'a', s.charAt(s.length() - 1) - 'a'); } // The given array of strings can be // chained if there is an eulerian // cycle in the created graph return g.isEulerianCycle();} // Driver codepublic static void main(String[] args) throws Exception{ String[] arr1 = { \"for\", \"geek\", \"rig\", \"kaf\" }; int n1 = arr1.length; System.out.println((canBeChained(arr1, n1) ? \"Can be chained \" : \"Can't be chained \")); String[] arr2 = { \"aab\", \"abb\" }; int n2 = arr2.length; System.out.println((canBeChained(arr2, n2) ? \"Can be chained \" : \"Can't be chained \"));}} // This code is contributed by abhay379201", "e": 11201, "s": 7045, "text": null }, { "code": "# Python program to check if a given directed graph is Eulerian or notCHARS = 26 # A class that represents an undirected graphclass Graph(object): def __init__(self, V): self.V = V # No. of vertices self.adj = [[] for x in range(V)] # a dynamic array self.inp = [0] * V # function to add an edge to graph def addEdge(self, v, w): self.adj[v].append(w) self.inp[w]+=1 # Method to check if this graph is Eulerian or not def isSC(self): # Mark all the vertices as not visited (For first DFS) visited = [False] * self.V # Find the first vertex with non-zero degree n = 0 for n in range(self.V): if len(self.adj[n]) > 0: break # Do DFS traversal starting from first non zero degree vertex. self.DFSUtil(n, visited) # If DFS traversal doesn't visit all vertices, then return false. for i in range(self.V): if len(self.adj[i]) > 0 and visited[i] == False: return False # Create a reversed graph gr = self.getTranspose() # Mark all the vertices as not visited (For second DFS) for i in range(self.V): visited[i] = False # Do DFS for reversed graph starting from first vertex. # Starting Vertex must be same starting point of first DFS gr.DFSUtil(n, visited) # If all vertices are not visited in second DFS, then # return false for i in range(self.V): if len(self.adj[i]) > 0 and visited[i] == False: return False return True # This function returns true if the directed graph has an eulerian # cycle, otherwise returns false def isEulerianCycle(self): # Check if all non-zero degree vertices are connected if self.isSC() == False: return False # Check if in degree and out degree of every vertex is same for i in range(self.V): if len(self.adj[i]) != self.inp[i]: return False return True # A recursive function to do DFS starting from v def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v] = True # Recur for all the vertices adjacent to this vertex for i in range(len(self.adj[v])): if not visited[self.adj[v][i]]: self.DFSUtil(self.adj[v][i], visited) # Function that returns reverse (or transpose) of this graph # This function is needed in isSC() def getTranspose(self): g = Graph(self.V) for v in range(self.V): # Recur for all the vertices adjacent to this vertex for i in range(len(self.adj[v])): g.adj[self.adj[v][i]].append(v) g.inp[v]+=1 return g # This function takes an of strings and returns true# if the given array of strings can be chained to# form cycledef canBeChained(arr, n): # Create a graph with 'alpha' edges g = Graph(CHARS) # Create an edge from first character to last character # of every string for i in range(n): s = arr[i] g.addEdge(ord(s[0])-ord('a'), ord(s[len(s)-1])-ord('a')) # The given array of strings can be chained if there # is an eulerian cycle in the created graph return g.isEulerianCycle() # Driver programarr1 = [\"for\", \"geek\", \"rig\", \"kaf\"]n1 = len(arr1)if canBeChained(arr1, n1): print (\"Can be chained\")else: print (\"Cant be chained\") arr2 = [\"aab\", \"abb\"]n2 = len(arr2)if canBeChained(arr2, n2): print (\"Can be chained\")else: print (\"Can't be chained\") # This code is contributed by BHAVYA JAIN", "e": 14854, "s": 11201, "text": null }, { "code": null, "e": 14888, "s": 14854, "text": "Can be chained \nCan't be chained " }, { "code": null, "e": 14957, "s": 14888, "text": "Find if an array of strings can be chained to form a circle | Set 2 " }, { "code": null, "e": 14969, "s": 14957, "text": "abhay379201" }, { "code": null, "e": 14985, "s": 14969, "text": "rajeev0719singh" }, { "code": null, "e": 15001, "s": 14985, "text": "saurabh1990aror" }, { "code": null, "e": 15017, "s": 15001, "text": "amartyaghoshgfg" }, { "code": null, "e": 15034, "s": 15017, "text": "hardikkoriintern" }, { "code": null, "e": 15043, "s": 15034, "text": "Accolite" }, { "code": null, "e": 15050, "s": 15043, "text": "Amazon" }, { "code": null, "e": 15064, "s": 15050, "text": "Euler-Circuit" }, { "code": null, "e": 15072, "s": 15064, "text": "FactSet" }, { "code": null, "e": 15078, "s": 15072, "text": "Graph" }, { "code": null, "e": 15086, "s": 15078, "text": "Strings" }, { "code": null, "e": 15095, "s": 15086, "text": "Accolite" }, { "code": null, "e": 15102, "s": 15095, "text": "Amazon" }, { "code": null, "e": 15110, "s": 15102, "text": "FactSet" }, { "code": null, "e": 15118, "s": 15110, "text": "Strings" }, { "code": null, "e": 15124, "s": 15118, "text": "Graph" } ]
Interesting facts about Increment and Decrement operators in Java
08 Jun, 2022 Increment operator is used to increment a value by 1. There are two varieties of increment operator: Post-Increment: Value is first used for computing the result and then incremented. Pre-Increment: Value is incremented first and then the result is computed. Example Java //INCREMENTAL OPERATOR//Let's see what exactly happens when we use these operators with the help of a code. import java.io.*; class GFG { public static void main (String[] args) { //1. Post-Increment Operator int a = 5; int b = 7; int c = a++ + b; //Here 'a' will not incremented immediately, a++ will still return value 5. // c = 5 + 7 and this will evaluate to 12. System.out.println("Post- Increment \n c = "+ c); //2. Pre-Increment Operator int A = 5; int B = 7; int C = ++A + B; //Here 'a' will be incremented immediately, and ++a will return value 6. // C = 6 + 7 and this will evaluate to 13. System.out.println("Pre- Increment \n C = "+ C); //Example- int m = 1, n = 2; int o = m++ + n + ++m; // It goes like m++ = 1, n = 2, ++m = 1+ incremented 'm' from m++ // = 1 + (1+m) = 1+ (1+1) = 3 // o = 1 + 2 + 3 = 6 System.out.println("Example \n o = "+ o); }} Decrement operator is used for decrementing the value by 1. There are two varieties of decrement operators. Post-decrement: Value is first used for computing the result and then decremented. Pre-decrement: Value is decremented first and then the result is computed. Example Java //DECREMETAL OPERATORS//Let's see what exactly happens when we use these operators with the help of a code.import java.io.*; class GFG { public static void main (String[] args) { //1. Post-Decrement Operator int a = 5; int b = 7; int c = a-- + b; //Here 'a' will not decremented immediately, a-- will still return value 5. // c = 5 + 7 and this will evaluate to 12. System.out.println("Post- Decrement \n c = "+ c); //2. Pre-Decrement Operator int A = 5; int B = 7; int C = --A + B; //Here 'a' will be decremented immediately, and --a will return value 4. // C = 4 + 7 and this will evaluate to 11. System.out.println("Pre- Decrement \n C = "+ C); //Example- int m = 3, n = 2; int o = m-- + n + --m; // It goes like m-- = 3, n = 2, --m = (decremented 'm' from 'm--') - 1; // = (m -1) - 1 = (3 -1) -1 = 1 // o = 3 + 2 + 1 = 6 System.out.println("Example \n o = "+ o); }} Now let us do Interesting facts about Increment and Decrement operators: Can only be applied to variables only Nesting of both operators is not allowed They are not operated over final variables Increment and Decrement Operators can not be applied to boolean. Let us discuss these 4 facts as listed above and do implement them as follows: Fact 1: Can be applied to variables only We can apply ++ and — operator only for variables but not for the constant values. If we are trying to apply ++ and — operator on the constant value then we will get a compile-time error which we will be seeing in example 1B after the below example as follows: Example 1: Java // Java program to illustrate Increment// and Decrement Operators// Can be Applied to Variables Only // Main classpublic class GFG { // main driver method public static void main(String[] args) { int a = 10; int b = ++a; // Printing value inside variable System.out.println(b); }} 11 Example 2: Java // Java program to Illustrate Increment and Decrement// operators Can be applied to variables only // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Declaring and initializing variable int a = 10; int b = ++a; // This is change made in above program // which reflects error during compilation b = 10 ++; // Printing its value System.out.println(b); }} Output: Fact 2: Nesting of both ++ and — operators are not allowed Example Java // Java program to Illustrate Nesting Can Not be Applied// to Increment and Decrement Operators // Main classpublic class GFG { // Main driver method public static void main(String[] args) { int a = 10; int b = ++(++a); // Printing the value inside variable System.out.println(b); }} Output: Fact 3: Final variables can’t apply increment and decrement operator The increment and decrement operators can not be applied to final variables because of the simple reason that their value can not be changed. Example Java // Java Program to Illustrate Increment and Decrement// Operators Can not be applied to final variables // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing final variable final int a = 10; int b = ++a; // Trying to print the updated value inside variable System.out.println(b); }} Output: Fact 4: Increment and Decrement Operators can not be applied to boolean We can apply ++ and — operators for all primitive data types except Boolean type as it only has true and false which even sounds impractical. Example Java // Java program to Illustrate Increment and Decrement// Operators Can not be applied boolean data type // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Initially declaring boolean as false boolean b = false; b++; // Trying printing the bool value System.out.println(b); }} Output: This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. solankimayank sweetyty sojwal interesting-facts Java-Data Types school-programming Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 154, "s": 52, "text": "Increment operator is used to increment a value by 1. There are two varieties of increment operator: " }, { "code": null, "e": 237, "s": 154, "text": "Post-Increment: Value is first used for computing the result and then incremented." }, { "code": null, "e": 312, "s": 237, "text": "Pre-Increment: Value is incremented first and then the result is computed." }, { "code": null, "e": 320, "s": 312, "text": "Example" }, { "code": null, "e": 325, "s": 320, "text": "Java" }, { "code": "//INCREMENTAL OPERATOR//Let's see what exactly happens when we use these operators with the help of a code. import java.io.*; class GFG { public static void main (String[] args) { //1. Post-Increment Operator int a = 5; int b = 7; int c = a++ + b; //Here 'a' will not incremented immediately, a++ will still return value 5. // c = 5 + 7 and this will evaluate to 12. System.out.println(\"Post- Increment \\n c = \"+ c); //2. Pre-Increment Operator int A = 5; int B = 7; int C = ++A + B; //Here 'a' will be incremented immediately, and ++a will return value 6. // C = 6 + 7 and this will evaluate to 13. System.out.println(\"Pre- Increment \\n C = \"+ C); //Example- int m = 1, n = 2; int o = m++ + n + ++m; // It goes like m++ = 1, n = 2, ++m = 1+ incremented 'm' from m++ // = 1 + (1+m) = 1+ (1+1) = 3 // o = 1 + 2 + 3 = 6 System.out.println(\"Example \\n o = \"+ o); }}", "e": 1411, "s": 325, "text": null }, { "code": null, "e": 1520, "s": 1411, "text": "Decrement operator is used for decrementing the value by 1. There are two varieties of decrement operators. " }, { "code": null, "e": 1603, "s": 1520, "text": "Post-decrement: Value is first used for computing the result and then decremented." }, { "code": null, "e": 1678, "s": 1603, "text": "Pre-decrement: Value is decremented first and then the result is computed." }, { "code": null, "e": 1686, "s": 1678, "text": "Example" }, { "code": null, "e": 1691, "s": 1686, "text": "Java" }, { "code": "//DECREMETAL OPERATORS//Let's see what exactly happens when we use these operators with the help of a code.import java.io.*; class GFG { public static void main (String[] args) { //1. Post-Decrement Operator int a = 5; int b = 7; int c = a-- + b; //Here 'a' will not decremented immediately, a-- will still return value 5. // c = 5 + 7 and this will evaluate to 12. System.out.println(\"Post- Decrement \\n c = \"+ c); //2. Pre-Decrement Operator int A = 5; int B = 7; int C = --A + B; //Here 'a' will be decremented immediately, and --a will return value 4. // C = 4 + 7 and this will evaluate to 11. System.out.println(\"Pre- Decrement \\n C = \"+ C); //Example- int m = 3, n = 2; int o = m-- + n + --m; // It goes like m-- = 3, n = 2, --m = (decremented 'm' from 'm--') - 1; // = (m -1) - 1 = (3 -1) -1 = 1 // o = 3 + 2 + 1 = 6 System.out.println(\"Example \\n o = \"+ o); }}", "e": 2785, "s": 1691, "text": null }, { "code": null, "e": 2858, "s": 2785, "text": "Now let us do Interesting facts about Increment and Decrement operators:" }, { "code": null, "e": 2896, "s": 2858, "text": "Can only be applied to variables only" }, { "code": null, "e": 2937, "s": 2896, "text": "Nesting of both operators is not allowed" }, { "code": null, "e": 2980, "s": 2937, "text": "They are not operated over final variables" }, { "code": null, "e": 3045, "s": 2980, "text": "Increment and Decrement Operators can not be applied to boolean." }, { "code": null, "e": 3124, "s": 3045, "text": "Let us discuss these 4 facts as listed above and do implement them as follows:" }, { "code": null, "e": 3165, "s": 3124, "text": "Fact 1: Can be applied to variables only" }, { "code": null, "e": 3426, "s": 3165, "text": "We can apply ++ and — operator only for variables but not for the constant values. If we are trying to apply ++ and — operator on the constant value then we will get a compile-time error which we will be seeing in example 1B after the below example as follows:" }, { "code": null, "e": 3437, "s": 3426, "text": "Example 1:" }, { "code": null, "e": 3442, "s": 3437, "text": "Java" }, { "code": "// Java program to illustrate Increment// and Decrement Operators// Can be Applied to Variables Only // Main classpublic class GFG { // main driver method public static void main(String[] args) { int a = 10; int b = ++a; // Printing value inside variable System.out.println(b); }}", "e": 3780, "s": 3442, "text": null }, { "code": null, "e": 3783, "s": 3780, "text": "11" }, { "code": null, "e": 3794, "s": 3783, "text": "Example 2:" }, { "code": null, "e": 3799, "s": 3794, "text": "Java" }, { "code": "// Java program to Illustrate Increment and Decrement// operators Can be applied to variables only // Main classpublic class GFG { // main driver method public static void main(String[] args) { // Declaring and initializing variable int a = 10; int b = ++a; // This is change made in above program // which reflects error during compilation b = 10 ++; // Printing its value System.out.println(b); }}", "e": 4271, "s": 3799, "text": null }, { "code": null, "e": 4279, "s": 4271, "text": "Output:" }, { "code": null, "e": 4339, "s": 4279, "text": "Fact 2: Nesting of both ++ and — operators are not allowed " }, { "code": null, "e": 4347, "s": 4339, "text": "Example" }, { "code": null, "e": 4352, "s": 4347, "text": "Java" }, { "code": "// Java program to Illustrate Nesting Can Not be Applied// to Increment and Decrement Operators // Main classpublic class GFG { // Main driver method public static void main(String[] args) { int a = 10; int b = ++(++a); // Printing the value inside variable System.out.println(b); }}", "e": 4678, "s": 4352, "text": null }, { "code": null, "e": 4687, "s": 4678, "text": "Output: " }, { "code": null, "e": 4756, "s": 4687, "text": "Fact 3: Final variables can’t apply increment and decrement operator" }, { "code": null, "e": 4899, "s": 4756, "text": "The increment and decrement operators can not be applied to final variables because of the simple reason that their value can not be changed. " }, { "code": null, "e": 4907, "s": 4899, "text": "Example" }, { "code": null, "e": 4912, "s": 4907, "text": "Java" }, { "code": "// Java Program to Illustrate Increment and Decrement// Operators Can not be applied to final variables // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing final variable final int a = 10; int b = ++a; // Trying to print the updated value inside variable System.out.println(b); }}", "e": 5316, "s": 4912, "text": null }, { "code": null, "e": 5325, "s": 5316, "text": "Output: " }, { "code": null, "e": 5397, "s": 5325, "text": "Fact 4: Increment and Decrement Operators can not be applied to boolean" }, { "code": null, "e": 5539, "s": 5397, "text": "We can apply ++ and — operators for all primitive data types except Boolean type as it only has true and false which even sounds impractical." }, { "code": null, "e": 5547, "s": 5539, "text": "Example" }, { "code": null, "e": 5552, "s": 5547, "text": "Java" }, { "code": "// Java program to Illustrate Increment and Decrement// Operators Can not be applied boolean data type // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Initially declaring boolean as false boolean b = false; b++; // Trying printing the bool value System.out.println(b); }}", "e": 5923, "s": 5552, "text": null }, { "code": null, "e": 5932, "s": 5923, "text": "Output: " }, { "code": null, "e": 6235, "s": 5932, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 6363, "s": 6235, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 6377, "s": 6363, "text": "solankimayank" }, { "code": null, "e": 6386, "s": 6377, "text": "sweetyty" }, { "code": null, "e": 6393, "s": 6386, "text": "sojwal" }, { "code": null, "e": 6411, "s": 6393, "text": "interesting-facts" }, { "code": null, "e": 6427, "s": 6411, "text": "Java-Data Types" }, { "code": null, "e": 6446, "s": 6427, "text": "school-programming" }, { "code": null, "e": 6451, "s": 6446, "text": "Java" }, { "code": null, "e": 6456, "s": 6451, "text": "Java" }, { "code": null, "e": 6554, "s": 6456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6605, "s": 6554, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6636, "s": 6605, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6655, "s": 6636, "text": "Interfaces in Java" }, { "code": null, "e": 6685, "s": 6655, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6703, "s": 6685, "text": "ArrayList in Java" }, { "code": null, "e": 6723, "s": 6703, "text": "Collections in Java" }, { "code": null, "e": 6738, "s": 6723, "text": "Stream In Java" }, { "code": null, "e": 6770, "s": 6738, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6790, "s": 6770, "text": "Stack Class in Java" } ]
How to remove the first character of string in PHP?
31 Jul, 2021 Remove the very first character of a given string in PHP Examples: Input : Geeksforgeeks Output : eeksforgeeks Input :, Hello geek! Output : Hello geek! Explanation:In PHP to remove characters from beginning we can use ltrim but in that we have to define what we want to remove from a string i.e. removing characters are to be known.Example: <?php $str = "geeks"; // Or we can write ltrim($str, $str[0]); $str = ltrim($str, 'g'); echo $str;?> eeks If string is not known and we want to remove characters from beginning then we can use substr(). Here we can use it by two parameters one is the string and the other is the index. substr() return string from the second parameter index to the end of the string. <?php $str = "geeks"; $str1 = substr($str, 1); echo $str1."\n"; $str1 = substr($str, 2); echo $str1; ?> eeks eks PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. PHP-string Picked Technical Scripter 2018 PHP Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? Split a comma delimited string into an array in PHP Download file from URL using PHP Removing Array Element and Re-Indexing in PHP How to pass JavaScript variables to PHP ? How to fetch data from localserver database and display on HTML table using PHP ? How to Encrypt and Decrypt a PHP String ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2021" }, { "code": null, "e": 85, "s": 28, "text": "Remove the very first character of a given string in PHP" }, { "code": null, "e": 95, "s": 85, "text": "Examples:" }, { "code": null, "e": 183, "s": 95, "text": "Input : Geeksforgeeks\nOutput : eeksforgeeks\n\nInput :, Hello geek!\nOutput : Hello geek!\n" }, { "code": null, "e": 372, "s": 183, "text": "Explanation:In PHP to remove characters from beginning we can use ltrim but in that we have to define what we want to remove from a string i.e. removing characters are to be known.Example:" }, { "code": "<?php $str = \"geeks\"; // Or we can write ltrim($str, $str[0]); $str = ltrim($str, 'g'); echo $str;?>", "e": 489, "s": 372, "text": null }, { "code": null, "e": 495, "s": 489, "text": "eeks\n" }, { "code": null, "e": 756, "s": 495, "text": "If string is not known and we want to remove characters from beginning then we can use substr(). Here we can use it by two parameters one is the string and the other is the index. substr() return string from the second parameter index to the end of the string." }, { "code": "<?php $str = \"geeks\"; $str1 = substr($str, 1); echo $str1.\"\\n\"; $str1 = substr($str, 2); echo $str1; ?>", "e": 875, "s": 756, "text": null }, { "code": null, "e": 885, "s": 875, "text": "eeks\neks\n" }, { "code": null, "e": 1054, "s": 885, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 1065, "s": 1054, "text": "PHP-string" }, { "code": null, "e": 1072, "s": 1065, "text": "Picked" }, { "code": null, "e": 1096, "s": 1072, "text": "Technical Scripter 2018" }, { "code": null, "e": 1100, "s": 1096, "text": "PHP" }, { "code": null, "e": 1119, "s": 1100, "text": "Technical Scripter" }, { "code": null, "e": 1123, "s": 1119, "text": "PHP" }, { "code": null, "e": 1221, "s": 1123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1261, "s": 1221, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1306, "s": 1261, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 1333, "s": 1306, "text": "Comparing two dates in PHP" }, { "code": null, "e": 1369, "s": 1333, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 1421, "s": 1369, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 1454, "s": 1421, "text": "Download file from URL using PHP" }, { "code": null, "e": 1500, "s": 1454, "text": "Removing Array Element and Re-Indexing in PHP" }, { "code": null, "e": 1542, "s": 1500, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 1624, "s": 1542, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" } ]
Object and Collection Initializer in C#
24 Nov, 2021 An object and collection initializer is an interesting and very useful feature of C# language. This feature provides a different way to initialize an object of a class or a collection. This feature is introduced in C# 3.0 or above. The main advantages of using these are to makes your code more readable, provide an easy way to add elements in collections, and mostly used in multi-threading. In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment. It can also place indexers, to initializing fields and properties, this feature is introduced in C# 6.0.Example: In the below example, Geeks class doesn’t contain any constructor, we simply create the object and initialize the value at the same time using curly braces in the main method. This initializing of values is known as object initializer. CSharp // C# program to illustrate// object initializer syntaxusing System; class Geeks { public string author_name { get; set; } public int author_id { get; set; } public int total_article { get; set; }} class GFG { // Main method static public void Main() { // Initialize fields using // an object initializer Geeks obj = new Geeks() { author_name = "Ankita Saini", author_id = 102, total_article = 178}; Console.WriteLine("Author Name: {0}", obj.author_name); Console.WriteLine("Author Id: {0}", obj.author_id); Console.WriteLine("Total no of articles: {0}", obj.total_article); }} Author Name: Ankita Saini Author Id: 102 Total no of articles: 178 Note: When the compiler compiles the above program it assign the values to the object as shown below: Geeks __geeks = new Geeks(); __geeks.author_name = "Ankita Saini"; __geeks.author_id = 102; __geeks. total_article = 178; Geeks obj = __geeks; Collection initializer is also similar to object initializers. The collections are initialized similarly like objects are initialized using an object initializer. Or in other words, generally, we used the Add() method to add elements in collections, but using a collection initializer you can add elements without using Add() method.Example : CSharp // C# program to illustrate how// to create a SortedList using// collection Initializerusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating another SortedList // using collection Initializer to // initialize sortedlist SortedList my_slist = new SortedList() { { "b.09", 234 }, { "b.11", 395 }, { "b.01", 405 }, { "b.67", 100 }, { "b.55", 500 }}; foreach(DictionaryEntry pair in my_slist) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } }} b.01 and 405 b.09 and 234 b.11 and 395 b.55 and 500 b.67 and 100 Important Points: You are allowed to initialize collection and the object at the same time.Example: CSharp var author1 = new Geeks() { author_name = "Soniya", author_id = 103, total_article = 120 }; var author2 = new Geeks() { author_name = "Siya", author_id = 106, total_article = 90 }; var author3 = new Geeks() { author_name = "Arpita", author_id = 111, total_article = 130 }; List<Geeks> author = new List<Geeks>() { author1, author2, author3}; You can also use null as an element in collection initializer.Example: CSharp SortedList my_slist = new SortedList() { { 1.2, "Cat" }, { 1.3, null }, { 1.5, 234 },}; gulshankumarar231 CSharp-Collections-Namespace CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 422, "s": 28, "text": "An object and collection initializer is an interesting and very useful feature of C# language. This feature provides a different way to initialize an object of a class or a collection. This feature is introduced in C# 3.0 or above. The main advantages of using these are to makes your code more readable, provide an easy way to add elements in collections, and mostly used in multi-threading. " }, { "code": null, "e": 1084, "s": 422, "text": "In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment. It can also place indexers, to initializing fields and properties, this feature is introduced in C# 6.0.Example: In the below example, Geeks class doesn’t contain any constructor, we simply create the object and initialize the value at the same time using curly braces in the main method. This initializing of values is known as object initializer." }, { "code": null, "e": 1091, "s": 1084, "text": "CSharp" }, { "code": "// C# program to illustrate// object initializer syntaxusing System; class Geeks { public string author_name { get; set; } public int author_id { get; set; } public int total_article { get; set; }} class GFG { // Main method static public void Main() { // Initialize fields using // an object initializer Geeks obj = new Geeks() { author_name = \"Ankita Saini\", author_id = 102, total_article = 178}; Console.WriteLine(\"Author Name: {0}\", obj.author_name); Console.WriteLine(\"Author Id: {0}\", obj.author_id); Console.WriteLine(\"Total no of articles: {0}\", obj.total_article); }}", "e": 1873, "s": 1091, "text": null }, { "code": null, "e": 1940, "s": 1873, "text": "Author Name: Ankita Saini\nAuthor Id: 102\nTotal no of articles: 178" }, { "code": null, "e": 2044, "s": 1942, "text": "Note: When the compiler compiles the above program it assign the values to the object as shown below:" }, { "code": null, "e": 2190, "s": 2044, "text": "Geeks __geeks = new Geeks();\n__geeks.author_name = \"Ankita Saini\";\n__geeks.author_id = 102;\n__geeks. total_article = 178;\n\nGeeks obj = __geeks; " }, { "code": null, "e": 2533, "s": 2190, "text": "Collection initializer is also similar to object initializers. The collections are initialized similarly like objects are initialized using an object initializer. Or in other words, generally, we used the Add() method to add elements in collections, but using a collection initializer you can add elements without using Add() method.Example :" }, { "code": null, "e": 2540, "s": 2533, "text": "CSharp" }, { "code": "// C# program to illustrate how// to create a SortedList using// collection Initializerusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating another SortedList // using collection Initializer to // initialize sortedlist SortedList my_slist = new SortedList() { { \"b.09\", 234 }, { \"b.11\", 395 }, { \"b.01\", 405 }, { \"b.67\", 100 }, { \"b.55\", 500 }}; foreach(DictionaryEntry pair in my_slist) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } }}", "e": 3267, "s": 2540, "text": null }, { "code": null, "e": 3332, "s": 3267, "text": "b.01 and 405\nb.09 and 234\nb.11 and 395\nb.55 and 500\nb.67 and 100" }, { "code": null, "e": 3352, "s": 3334, "text": "Important Points:" }, { "code": null, "e": 3434, "s": 3352, "text": "You are allowed to initialize collection and the object at the same time.Example:" }, { "code": null, "e": 3441, "s": 3434, "text": "CSharp" }, { "code": "var author1 = new Geeks() { author_name = \"Soniya\", author_id = 103, total_article = 120 }; var author2 = new Geeks() { author_name = \"Siya\", author_id = 106, total_article = 90 }; var author3 = new Geeks() { author_name = \"Arpita\", author_id = 111, total_article = 130 }; List<Geeks> author = new List<Geeks>() { author1, author2, author3};", "e": 4038, "s": 3441, "text": null }, { "code": null, "e": 4109, "s": 4038, "text": "You can also use null as an element in collection initializer.Example:" }, { "code": null, "e": 4116, "s": 4109, "text": "CSharp" }, { "code": "SortedList my_slist = new SortedList() { { 1.2, \"Cat\" }, { 1.3, null }, { 1.5, 234 },};", "e": 4279, "s": 4116, "text": null }, { "code": null, "e": 4297, "s": 4279, "text": "gulshankumarar231" }, { "code": null, "e": 4326, "s": 4297, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 4337, "s": 4326, "text": "CSharp-OOP" }, { "code": null, "e": 4340, "s": 4337, "text": "C#" } ]
Python | Finding relative order of elements in list
20 Mar, 2019 Sometimes we have an unsorted list an we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position to each element destined if the list was sorted. This has a good application in web development and competitive programming domain. Let’s discuss certain ways in which this can be done. Method #1 : Using sorted() + index() + list comprehensionAll the above function can combine to achieve this particular task. The sorted function returns the sorted order and the indexing is done by the index function. List comprehension does the task of doing for whole list elements and integrating both tasks. # Python3 code to demonstrate# Finding relative order of elements in list# using sorted() + index() + list comprehension # initializing listtest_list = [6, 3, 1, 2, 5, 4] # printing original listprint("The original list is : " + str(test_list)) # using sorted() + index() + list comprehension# Finding relative order of elements in listtemp = sorted(test_list) res = [temp.index(i) for i in test_list] # printing resultprint ("The relative ordering list is : " + str(res)) The original list is : [6, 3, 1, 2, 5, 4] The relative ordering list is : [5, 2, 0, 1, 4, 3] Method #2 : Using map() + enumerate() + dictionary comprehension + sorted()The dictionary comprehension is used in place of list comprehension and the sorted list is formed and the index of actual ordering in sorted list are traversed using enumerate to have key-value pair and then are get by map for all the indices in list. # Python3 code to demonstrate# Finding relative order of elements in list# using map() + enumerate() + dictionary comprehension + sorted() # initializing listtest_list = [6, 3, 1, 2, 5, 4] # printing original listprint("The original list is : " + str(test_list)) # using map() + enumerate() + dictionary comprehension + sorted()# Finding relative order of elements in listtemp = {val: key for key, val in enumerate(sorted(test_list))}res = list(map(temp.get, test_list)) # printing resultprint ("The relative ordering list is : " + str(res)) The original list is : [6, 3, 1, 2, 5, 4] The relative ordering list is : [5, 2, 0, 1, 4, 3] Python list-programs Python Python Programs 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Mar, 2019" }, { "code": null, "e": 401, "s": 28, "text": "Sometimes we have an unsorted list an we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position to each element destined if the list was sorted. This has a good application in web development and competitive programming domain. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 713, "s": 401, "text": "Method #1 : Using sorted() + index() + list comprehensionAll the above function can combine to achieve this particular task. The sorted function returns the sorted order and the indexing is done by the index function. List comprehension does the task of doing for whole list elements and integrating both tasks." }, { "code": "# Python3 code to demonstrate# Finding relative order of elements in list# using sorted() + index() + list comprehension # initializing listtest_list = [6, 3, 1, 2, 5, 4] # printing original listprint(\"The original list is : \" + str(test_list)) # using sorted() + index() + list comprehension# Finding relative order of elements in listtemp = sorted(test_list) res = [temp.index(i) for i in test_list] # printing resultprint (\"The relative ordering list is : \" + str(res))", "e": 1193, "s": 713, "text": null }, { "code": null, "e": 1287, "s": 1193, "text": "The original list is : [6, 3, 1, 2, 5, 4]\nThe relative ordering list is : [5, 2, 0, 1, 4, 3]\n" }, { "code": null, "e": 1616, "s": 1289, "text": "Method #2 : Using map() + enumerate() + dictionary comprehension + sorted()The dictionary comprehension is used in place of list comprehension and the sorted list is formed and the index of actual ordering in sorted list are traversed using enumerate to have key-value pair and then are get by map for all the indices in list." }, { "code": "# Python3 code to demonstrate# Finding relative order of elements in list# using map() + enumerate() + dictionary comprehension + sorted() # initializing listtest_list = [6, 3, 1, 2, 5, 4] # printing original listprint(\"The original list is : \" + str(test_list)) # using map() + enumerate() + dictionary comprehension + sorted()# Finding relative order of elements in listtemp = {val: key for key, val in enumerate(sorted(test_list))}res = list(map(temp.get, test_list)) # printing resultprint (\"The relative ordering list is : \" + str(res))", "e": 2162, "s": 1616, "text": null }, { "code": null, "e": 2256, "s": 2162, "text": "The original list is : [6, 3, 1, 2, 5, 4]\nThe relative ordering list is : [5, 2, 0, 1, 4, 3]\n" }, { "code": null, "e": 2277, "s": 2256, "text": "Python list-programs" }, { "code": null, "e": 2284, "s": 2277, "text": "Python" }, { "code": null, "e": 2300, "s": 2284, "text": "Python Programs" }, { "code": null, "e": 2398, "s": 2300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2430, "s": 2398, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2457, "s": 2430, "text": "Python Classes and Objects" }, { "code": null, "e": 2478, "s": 2457, "text": "Python OOPs Concepts" }, { "code": null, "e": 2501, "s": 2478, "text": "Introduction To PYTHON" }, { "code": null, "e": 2557, "s": 2501, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2579, "s": 2557, "text": "Defaultdict in Python" }, { "code": null, "e": 2618, "s": 2579, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2656, "s": 2618, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2693, "s": 2656, "text": "Python Program for Fibonacci numbers" } ]
How to Plot List of X, Y Coordinates in Matplotlib?
17 Dec, 2020 Prerequisites: Matplotlib numpy Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. To plot any data the most basic step starts with creating or loading it, this article discusses all the ways of passing the data to be plotted as list. While passing data as list one important thing to be kept in mind is to keep X,Y Lists of the same size, otherwise it will raise a ValueError. Examples shown in this article use scatter plot, the same approaches can be applied to any other type of graph. In this method, the coordinates are simply passed as two lists. Approach Import module Create a list for X coordinates Create a list for Y coordinate Pass these two lists to plot the function Example: Python3 import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6, 7, 8]y = [2, 3, 1, 3, 1, 4, 2, 3] plt.scatter(x, y)plt.show() Output: Function used: arrange() Syntax: np.arange(start,end,step) Parameters: Start: starting value End: ending value Step: step size, by default it is 1. Approach Import module Create numpy array for coordinates Pass these arrays to plot Example: Python3 # importing Matplotlib and Numpy Packagesimport numpy as npimport matplotlib.pyplot as plt # generating two arrays from 10 to 1 and from 1 to 10x = np.arange(1, 11, 1) y = np.arange(10, 0, -1) # plot our list in X,Y coordinatesplt.scatter(x, y)plt.show() Output: Creating lists of list of all points to be plotted can also one of the ways of achieving our requirement. After creating such a list it cannot be directly passed to plot, first a transpose needs to taken to get x and y coordinates. Approach Import module Create list of lists for coordinates Take transpose Pass the coordinates to the plot Example Python3 # importing Matplotlib and Numpy Packagesimport numpy as npimport matplotlib.pyplot as plt # The data are given as list of lists (2d list)data = np.array([ [1, 4], [2, 2], [3, 7], [4, 6], [5, 0], [6, 3]])# Taking transposex, y = data.T # plot our list in X,Y coordinatesplt.scatter(x, y)plt.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Dec, 2020" }, { "code": null, "e": 69, "s": 53, "text": "Prerequisites: " }, { "code": null, "e": 81, "s": 69, "text": "Matplotlib " }, { "code": null, "e": 88, "s": 81, "text": "numpy " }, { "code": null, "e": 495, "s": 88, "text": "Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. To plot any data the most basic step starts with creating or loading it, this article discusses all the ways of passing the data to be plotted as list. While passing data as list one important thing to be kept in mind is to keep X,Y Lists of the same size, otherwise it will raise a ValueError. " }, { "code": null, "e": 607, "s": 495, "text": "Examples shown in this article use scatter plot, the same approaches can be applied to any other type of graph." }, { "code": null, "e": 671, "s": 607, "text": "In this method, the coordinates are simply passed as two lists." }, { "code": null, "e": 680, "s": 671, "text": "Approach" }, { "code": null, "e": 694, "s": 680, "text": "Import module" }, { "code": null, "e": 726, "s": 694, "text": "Create a list for X coordinates" }, { "code": null, "e": 757, "s": 726, "text": "Create a list for Y coordinate" }, { "code": null, "e": 799, "s": 757, "text": "Pass these two lists to plot the function" }, { "code": null, "e": 809, "s": 799, "text": "Example: " }, { "code": null, "e": 817, "s": 809, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6, 7, 8]y = [2, 3, 1, 3, 1, 4, 2, 3] plt.scatter(x, y)plt.show()", "e": 936, "s": 817, "text": null }, { "code": null, "e": 944, "s": 936, "text": "Output:" }, { "code": null, "e": 969, "s": 944, "text": "Function used: arrange()" }, { "code": null, "e": 1003, "s": 969, "text": "Syntax: np.arange(start,end,step)" }, { "code": null, "e": 1015, "s": 1003, "text": "Parameters:" }, { "code": null, "e": 1037, "s": 1015, "text": "Start: starting value" }, { "code": null, "e": 1055, "s": 1037, "text": "End: ending value" }, { "code": null, "e": 1092, "s": 1055, "text": "Step: step size, by default it is 1." }, { "code": null, "e": 1101, "s": 1092, "text": "Approach" }, { "code": null, "e": 1115, "s": 1101, "text": "Import module" }, { "code": null, "e": 1150, "s": 1115, "text": "Create numpy array for coordinates" }, { "code": null, "e": 1176, "s": 1150, "text": "Pass these arrays to plot" }, { "code": null, "e": 1185, "s": 1176, "text": "Example:" }, { "code": null, "e": 1193, "s": 1185, "text": "Python3" }, { "code": "# importing Matplotlib and Numpy Packagesimport numpy as npimport matplotlib.pyplot as plt # generating two arrays from 10 to 1 and from 1 to 10x = np.arange(1, 11, 1) y = np.arange(10, 0, -1) # plot our list in X,Y coordinatesplt.scatter(x, y)plt.show()", "e": 1453, "s": 1193, "text": null }, { "code": null, "e": 1461, "s": 1453, "text": "Output:" }, { "code": null, "e": 1693, "s": 1461, "text": "Creating lists of list of all points to be plotted can also one of the ways of achieving our requirement. After creating such a list it cannot be directly passed to plot, first a transpose needs to taken to get x and y coordinates." }, { "code": null, "e": 1702, "s": 1693, "text": "Approach" }, { "code": null, "e": 1716, "s": 1702, "text": "Import module" }, { "code": null, "e": 1753, "s": 1716, "text": "Create list of lists for coordinates" }, { "code": null, "e": 1768, "s": 1753, "text": "Take transpose" }, { "code": null, "e": 1801, "s": 1768, "text": "Pass the coordinates to the plot" }, { "code": null, "e": 1809, "s": 1801, "text": "Example" }, { "code": null, "e": 1817, "s": 1809, "text": "Python3" }, { "code": "# importing Matplotlib and Numpy Packagesimport numpy as npimport matplotlib.pyplot as plt # The data are given as list of lists (2d list)data = np.array([ [1, 4], [2, 2], [3, 7], [4, 6], [5, 0], [6, 3]])# Taking transposex, y = data.T # plot our list in X,Y coordinatesplt.scatter(x, y)plt.show()", "e": 2137, "s": 1817, "text": null }, { "code": null, "e": 2146, "s": 2137, "text": "Output: " }, { "code": null, "e": 2153, "s": 2146, "text": "Picked" }, { "code": null, "e": 2171, "s": 2153, "text": "Python-matplotlib" }, { "code": null, "e": 2178, "s": 2171, "text": "Python" } ]
Program to sort string in descending order
23 Jun, 2022 Given a string, sort it in descending order.Examples: Input : alkasingh Output : snlkihgaa Input : nupursingh Output : uusrpnnihg Input : geeksforgeeks Output : ssrokkggfeeee A simple solution is to use library sort function std::sort() C++ Java Python C# PHP Javascript // CPP program to sort a string in descending// order using library function#include <bits/stdc++.h>using namespace std; void descOrder(string s){ sort(s.begin(), s.end(), greater<char>());} int main(){ string s = "geeksforgeeks"; descOrder(s); // function call return 0;} // Java program to sort a string in descending// order using library functionimport java.util.*; class GFG{ static void descOrder(char[] s) { Arrays.sort(s); reverse(s); } static void reverse(char[] a) { int i, n = a.length; char t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String[] args) { char[] s = "geeksforgeeks".toCharArray(); descOrder(s); // function call System.out.println(String.valueOf(s)); }} // This code is contributed by 29AjayKumar # Python program to sort# a string in descending# order using library function def descOrder(s): s.sort(reverse = True) str1 = ''.join(s) print(str1) def main(): s = list('geeksforgeeks') # function call descOrder(s) if __name__=="__main__": main() # This code is contributed by# prabhat kumar singh // C# program to sort a string in descending// order using library functionusing System; class GFG{ static void descOrder(char[] s) { Array.Sort(s); reverse(s); } static void reverse(char[] a) { int i, n = a.Length; char t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void Main(String[] args) { char[] s = "geeksforgeeks".ToCharArray(); descOrder(s); // function call Console.WriteLine(String.Join("",s)); }} // This code is contributed by Rajput-Ji <?php// PHP program to sort a string in descending// order using library function function descOrder($s){ $s = str_split($s); rsort($s); echo implode('', $s);} // Driver Code$s = "geeksforgeeks";descOrder($s); // function call // This code is contributed by ita_c?> <script> // JavaScript program to sort // a string in descending // order using library function function descOrder(s) { s.sort().reverse(); str1 = s.join(""); document.write(str1); } var s = "geeksforgeeks"; s = s.split(""); // function call descOrder(s); </script> Output: ssrokkggfeeee The time complexity is : O(n log n) Auxiliary Space: O(1) An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the characters from ‘z’ to ‘a’ the number of times they occurred in input string.Below is the implementation of above idea: C++ Java Python3 C# Javascript // C++ program to sort a string of characters// in descending order#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to print string in sorted ordervoid sortString(string& str){ // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. int charCount[MAX_CHAR] = { 0 }; // Traverse string and increment // count of characters for (int i = 0; i < str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i] - 'a']++; // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) for (int j = 0; j < charCount[i]; j++) cout << (char)('a' + i);} // Driver program to test above functionint main(){ string s = "alkasingh"; sortString(s); return 0;} // Java program to sort a string of characters// in descending order class GFG{ static int MAX_CHAR = 26; // function to print string in sorted order static void sortString(String str) { // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. int charCount[] = new int[MAX_CHAR]; // Traverse string and increment // count of characters // 'a'-'a' will be 0, 'b'-'a' will be 1, for (int i = 0; i < str.length(); i++) { // so for location of character in count // array we will do str[i]-'a'. charCount[str.charAt(i) - 'a']++; } // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) { for (int j = 0; j < charCount[i]; j++) { System.out.print((char) ('a' + i)); } } } // Driver code public static void main(String[] args) { String s = "alkasingh"; sortString(s); }} // This code is contributed by 29AjayKumar # Python program to sort a string of characters# in descending order MAX_CHAR = 26; # function to print string in sorted orderdef sortString(str): # Hash array to keep count of characters. # Initially count of all charters is # initialized to zero. charCount = [0]*MAX_CHAR; # Traverse string and increment # count of characters for i in range(len(str)): # 'a'-'a' will be 0, 'b'-'a' will be 1, # so for location of character in count # array we will do str[i]-'a'. charCount[ord(str[i]) - ord('a')]+=1; # Traverse the hash array and print # characters for i in range(MAX_CHAR - 1,-1, -1): for j in range(charCount[i]): print(chr(97+i),end=""); # Driver program to test above functions = "alkasingh";sortString(s); # This code is contributed by Princi Singh // C# program to sort a string of characters// in descending orderusing System; class GFG{ static int MAX_CHAR = 26; // function to print string in sorted order static void sortString(String str) { // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. int []charCount = new int[MAX_CHAR]; // Traverse string and increment // count of characters // 'a'-'a' will be 0, 'b'-'a' will be 1, for (int i = 0; i < str.Length; i++) { // so for location of character in // count array we will do str[i]-'a'. charCount[str[i] - 'a']++; } // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) { for (int j = 0; j < charCount[i]; j++) { Console.Write((char) ('a' + i)); } } } // Driver code public static void Main(String[] args) { String s = "alkasingh"; sortString(s); }} // This code is contributed by PrinciRaj1992 <script>// Javascript program to sort a string of characters// in descending order let MAX_CHAR = 26; // function to print string in sorted order function sortString(str) { // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. let charCount = new Array(MAX_CHAR); for(let i = 0; i < charCount.length; i++) { charCount[i] = 0; } // Traverse string and increment // count of characters // 'a'-'a' will be 0, 'b'-'a' will be 1, for (let i = 0; i < str.length; i++) { // so for location of character in count // array we will do str[i]-'a'. charCount[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse the hash array and print // characters for (let i = MAX_CHAR - 1; i >= 0; i--) { for (let j = 0; j < charCount[i]; j++) { document.write(String.fromCharCode ('a'.charCodeAt(0) + i)); } } } // Driver code let s = "alkasingh"; sortString(s); // This code is contributed by avanitrachhadiya2155</script> Output: snlkihgaa Time Complexity: O( n ), where n is the length of input string. Auxiliary Space: O( 1 ).This article is contributed by Aarti_Rathi and Prabhat kumar singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prabhat kumar singh ukasp 29AjayKumar princiraj1992 Rajput-Ji princi singh rdtank avanitrachhadiya2155 as5853535 sachinvinod1904 frequency-counting Hash Sorting Strings Hash Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 109, "s": 53, "text": "Given a string, sort it in descending order.Examples: " }, { "code": null, "e": 235, "s": 109, "text": "Input : alkasingh\nOutput : snlkihgaa \n\nInput : nupursingh\nOutput : uusrpnnihg \n\nInput : geeksforgeeks\nOutput : ssrokkggfeeee " }, { "code": null, "e": 300, "s": 237, "text": "A simple solution is to use library sort function std::sort() " }, { "code": null, "e": 304, "s": 300, "text": "C++" }, { "code": null, "e": 309, "s": 304, "text": "Java" }, { "code": null, "e": 316, "s": 309, "text": "Python" }, { "code": null, "e": 319, "s": 316, "text": "C#" }, { "code": null, "e": 323, "s": 319, "text": "PHP" }, { "code": null, "e": 334, "s": 323, "text": "Javascript" }, { "code": "// CPP program to sort a string in descending// order using library function#include <bits/stdc++.h>using namespace std; void descOrder(string s){ sort(s.begin(), s.end(), greater<char>());} int main(){ string s = \"geeksforgeeks\"; descOrder(s); // function call return 0;}", "e": 619, "s": 334, "text": null }, { "code": "// Java program to sort a string in descending// order using library functionimport java.util.*; class GFG{ static void descOrder(char[] s) { Arrays.sort(s); reverse(s); } static void reverse(char[] a) { int i, n = a.length; char t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String[] args) { char[] s = \"geeksforgeeks\".toCharArray(); descOrder(s); // function call System.out.println(String.valueOf(s)); }} // This code is contributed by 29AjayKumar", "e": 1285, "s": 619, "text": null }, { "code": "# Python program to sort# a string in descending# order using library function def descOrder(s): s.sort(reverse = True) str1 = ''.join(s) print(str1) def main(): s = list('geeksforgeeks') # function call descOrder(s) if __name__==\"__main__\": main() # This code is contributed by# prabhat kumar singh", "e": 1611, "s": 1285, "text": null }, { "code": "// C# program to sort a string in descending// order using library functionusing System; class GFG{ static void descOrder(char[] s) { Array.Sort(s); reverse(s); } static void reverse(char[] a) { int i, n = a.Length; char t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void Main(String[] args) { char[] s = \"geeksforgeeks\".ToCharArray(); descOrder(s); // function call Console.WriteLine(String.Join(\"\",s)); }} // This code is contributed by Rajput-Ji", "e": 2272, "s": 1611, "text": null }, { "code": "<?php// PHP program to sort a string in descending// order using library function function descOrder($s){ $s = str_split($s); rsort($s); echo implode('', $s);} // Driver Code$s = \"geeksforgeeks\";descOrder($s); // function call // This code is contributed by ita_c?>", "e": 2547, "s": 2272, "text": null }, { "code": "<script> // JavaScript program to sort // a string in descending // order using library function function descOrder(s) { s.sort().reverse(); str1 = s.join(\"\"); document.write(str1); } var s = \"geeksforgeeks\"; s = s.split(\"\"); // function call descOrder(s); </script>", "e": 2896, "s": 2547, "text": null }, { "code": null, "e": 2905, "s": 2896, "text": "Output: " }, { "code": null, "e": 2921, "s": 2905, "text": " ssrokkggfeeee " }, { "code": null, "e": 3470, "s": 2921, "text": "The time complexity is : O(n log n) Auxiliary Space: O(1) An efficient approach will be to observe first that there can be a total of 26 unique characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the characters from ‘z’ to ‘a’ the number of times they occurred in input string.Below is the implementation of above idea: " }, { "code": null, "e": 3474, "s": 3470, "text": "C++" }, { "code": null, "e": 3479, "s": 3474, "text": "Java" }, { "code": null, "e": 3487, "s": 3479, "text": "Python3" }, { "code": null, "e": 3490, "s": 3487, "text": "C#" }, { "code": null, "e": 3501, "s": 3490, "text": "Javascript" }, { "code": "// C++ program to sort a string of characters// in descending order#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to print string in sorted ordervoid sortString(string& str){ // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. int charCount[MAX_CHAR] = { 0 }; // Traverse string and increment // count of characters for (int i = 0; i < str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i] - 'a']++; // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) for (int j = 0; j < charCount[i]; j++) cout << (char)('a' + i);} // Driver program to test above functionint main(){ string s = \"alkasingh\"; sortString(s); return 0;}", "e": 4431, "s": 3501, "text": null }, { "code": "// Java program to sort a string of characters// in descending order class GFG{ static int MAX_CHAR = 26; // function to print string in sorted order static void sortString(String str) { // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. int charCount[] = new int[MAX_CHAR]; // Traverse string and increment // count of characters // 'a'-'a' will be 0, 'b'-'a' will be 1, for (int i = 0; i < str.length(); i++) { // so for location of character in count // array we will do str[i]-'a'. charCount[str.charAt(i) - 'a']++; } // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) { for (int j = 0; j < charCount[i]; j++) { System.out.print((char) ('a' + i)); } } } // Driver code public static void main(String[] args) { String s = \"alkasingh\"; sortString(s); }} // This code is contributed by 29AjayKumar", "e": 5578, "s": 4431, "text": null }, { "code": "# Python program to sort a string of characters# in descending order MAX_CHAR = 26; # function to print string in sorted orderdef sortString(str): # Hash array to keep count of characters. # Initially count of all charters is # initialized to zero. charCount = [0]*MAX_CHAR; # Traverse string and increment # count of characters for i in range(len(str)): # 'a'-'a' will be 0, 'b'-'a' will be 1, # so for location of character in count # array we will do str[i]-'a'. charCount[ord(str[i]) - ord('a')]+=1; # Traverse the hash array and print # characters for i in range(MAX_CHAR - 1,-1, -1): for j in range(charCount[i]): print(chr(97+i),end=\"\"); # Driver program to test above functions = \"alkasingh\";sortString(s); # This code is contributed by Princi Singh", "e": 6420, "s": 5578, "text": null }, { "code": "// C# program to sort a string of characters// in descending orderusing System; class GFG{ static int MAX_CHAR = 26; // function to print string in sorted order static void sortString(String str) { // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. int []charCount = new int[MAX_CHAR]; // Traverse string and increment // count of characters // 'a'-'a' will be 0, 'b'-'a' will be 1, for (int i = 0; i < str.Length; i++) { // so for location of character in // count array we will do str[i]-'a'. charCount[str[i] - 'a']++; } // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) { for (int j = 0; j < charCount[i]; j++) { Console.Write((char) ('a' + i)); } } } // Driver code public static void Main(String[] args) { String s = \"alkasingh\"; sortString(s); }} // This code is contributed by PrinciRaj1992", "e": 7568, "s": 6420, "text": null }, { "code": "<script>// Javascript program to sort a string of characters// in descending order let MAX_CHAR = 26; // function to print string in sorted order function sortString(str) { // Hash array to keep count of characters. // Initially count of all charters is // initialized to zero. let charCount = new Array(MAX_CHAR); for(let i = 0; i < charCount.length; i++) { charCount[i] = 0; } // Traverse string and increment // count of characters // 'a'-'a' will be 0, 'b'-'a' will be 1, for (let i = 0; i < str.length; i++) { // so for location of character in count // array we will do str[i]-'a'. charCount[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Traverse the hash array and print // characters for (let i = MAX_CHAR - 1; i >= 0; i--) { for (let j = 0; j < charCount[i]; j++) { document.write(String.fromCharCode ('a'.charCodeAt(0) + i)); } } } // Driver code let s = \"alkasingh\"; sortString(s); // This code is contributed by avanitrachhadiya2155</script>", "e": 8813, "s": 7568, "text": null }, { "code": null, "e": 8823, "s": 8813, "text": "Output: " }, { "code": null, "e": 8833, "s": 8823, "text": "snlkihgaa" }, { "code": null, "e": 9365, "s": 8833, "text": "Time Complexity: O( n ), where n is the length of input string. Auxiliary Space: O( 1 ).This article is contributed by Aarti_Rathi and Prabhat kumar singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9385, "s": 9365, "text": "prabhat kumar singh" }, { "code": null, "e": 9391, "s": 9385, "text": "ukasp" }, { "code": null, "e": 9403, "s": 9391, "text": "29AjayKumar" }, { "code": null, "e": 9417, "s": 9403, "text": "princiraj1992" }, { "code": null, "e": 9427, "s": 9417, "text": "Rajput-Ji" }, { "code": null, "e": 9440, "s": 9427, "text": "princi singh" }, { "code": null, "e": 9447, "s": 9440, "text": "rdtank" }, { "code": null, "e": 9468, "s": 9447, "text": "avanitrachhadiya2155" }, { "code": null, "e": 9478, "s": 9468, "text": "as5853535" }, { "code": null, "e": 9494, "s": 9478, "text": "sachinvinod1904" }, { "code": null, "e": 9513, "s": 9494, "text": "frequency-counting" }, { "code": null, "e": 9518, "s": 9513, "text": "Hash" }, { "code": null, "e": 9526, "s": 9518, "text": "Sorting" }, { "code": null, "e": 9534, "s": 9526, "text": "Strings" }, { "code": null, "e": 9539, "s": 9534, "text": "Hash" }, { "code": null, "e": 9547, "s": 9539, "text": "Strings" }, { "code": null, "e": 9555, "s": 9547, "text": "Sorting" }, { "code": null, "e": 9653, "s": 9555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9738, "s": 9653, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9776, "s": 9738, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9812, "s": 9776, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 9843, "s": 9812, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 9870, "s": 9843, "text": "Count pairs with given sum" }, { "code": null, "e": 9881, "s": 9870, "text": "Merge Sort" }, { "code": null, "e": 9903, "s": 9881, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 9913, "s": 9903, "text": "QuickSort" }, { "code": null, "e": 9928, "s": 9913, "text": "Insertion Sort" } ]
Kotlin | Explicit type casting
24 Feb, 2022 In Smart Casting, we generally use is or !is an operator to check the type of variable, and the compiler automatically casts the variable to the target type, but in explicit type casting we use as operator. Explicit type casting can be done using : Unsafe cast operator: asSafe cast operator: as? Unsafe cast operator: as Safe cast operator: as? Manually, we use the type cast operator as to cast a variable to target type. In the below program, variable str1 of string typecast to target type using as operator. Kotlin fun main(args: Array<String>){ val str1: String = "It works fine" val str2: String = str1 as String // Works println(str1)} Output: It works fine There might be possibility that we can not cast variable to target type and it throws an exception at runtime, that’s why it is called as unsafe casting. When the Integer type is used to cast to the String type, then it throws ClassCastException. Kotlin fun main(args: Array<String>){ val str1: Any = 11 val str2: String = str1 as String // throw exception println(str1)} Output: Exception in thread “main” java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String We can not cast a nullable string to non-nullable string, and it throws an exception TypeCastException. Kotlin fun main(args: Array<String>){ val str1: String? = null val str2: String = str1 as String // throw exception println(str1)} Output: Exception in thread “main” kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String Hence, we have to use target type also as nullable String so that type casting throws no exception. Kotlin fun main(args: Array<String>){ val str1: String? = null val str2: String? = str1 as String? // throw exception println(str1)} Output: null Kotlin also provides a facility of typecasting using safe cast operator as?. If casting is not possible it returns null instead of throwing an ClassCastException exception.Here is an example, in which we are trying to cast Any type of string value that is initially known by the programmer into a nullable string then it works fine. When we initialize the Any with Integer value and try to cast into a nullable string then this typecasting is not possible and returns null to str3. Kotlin fun main(args: Array<String>){ var str1: Any = "Safe casting" val str2: String? = str1 as? String // it works str1 = 11 // type casting not possible so returns null to str3 val str3: String? = str1 as? String val str4: Int? = str1 as? Int // it works println(str2) println(str3) println(str4)} Output: Safe casting null 11 ayushpandey3july varshagumber28 Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android RecyclerView in Kotlin Broadcast Receiver in Android With Example How to Add Views Dynamically and Store Data in Arraylist in Android? Retrofit with Kotlin Coroutine in Android Content Providers in Android with Example How to Add and Customize Back Button of Action Bar in Android? Suspend Function In Kotlin Coroutines Kotlin Higher-Order Functions How to Change the Color of Status Bar in an Android App? How to Communicate Between Fragments in Android?
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2022" }, { "code": null, "e": 279, "s": 28, "text": "In Smart Casting, we generally use is or !is an operator to check the type of variable, and the compiler automatically casts the variable to the target type, but in explicit type casting we use as operator. Explicit type casting can be done using : " }, { "code": null, "e": 327, "s": 279, "text": "Unsafe cast operator: asSafe cast operator: as?" }, { "code": null, "e": 352, "s": 327, "text": "Unsafe cast operator: as" }, { "code": null, "e": 376, "s": 352, "text": "Safe cast operator: as?" }, { "code": null, "e": 547, "s": 378, "text": "Manually, we use the type cast operator as to cast a variable to target type. In the below program, variable str1 of string typecast to target type using as operator. " }, { "code": null, "e": 554, "s": 547, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ val str1: String = \"It works fine\" val str2: String = str1 as String // Works println(str1)}", "e": 692, "s": 554, "text": null }, { "code": null, "e": 702, "s": 692, "text": "Output: " }, { "code": null, "e": 716, "s": 702, "text": "It works fine" }, { "code": null, "e": 965, "s": 716, "text": "There might be possibility that we can not cast variable to target type and it throws an exception at runtime, that’s why it is called as unsafe casting. When the Integer type is used to cast to the String type, then it throws ClassCastException. " }, { "code": null, "e": 972, "s": 965, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ val str1: Any = 11 val str2: String = str1 as String // throw exception println(str1)}", "e": 1104, "s": 972, "text": null }, { "code": null, "e": 1114, "s": 1104, "text": "Output: " }, { "code": null, "e": 1238, "s": 1114, "text": "Exception in thread “main” java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String " }, { "code": null, "e": 1344, "s": 1238, "text": "We can not cast a nullable string to non-nullable string, and it throws an exception TypeCastException. " }, { "code": null, "e": 1351, "s": 1344, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ val str1: String? = null val str2: String = str1 as String // throw exception println(str1)}", "e": 1489, "s": 1351, "text": null }, { "code": null, "e": 1498, "s": 1489, "text": "Output: " }, { "code": null, "e": 1604, "s": 1498, "text": "Exception in thread “main” kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String " }, { "code": null, "e": 1706, "s": 1604, "text": "Hence, we have to use target type also as nullable String so that type casting throws no exception. " }, { "code": null, "e": 1713, "s": 1706, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ val str1: String? = null val str2: String? = str1 as String? // throw exception println(str1)}", "e": 1853, "s": 1713, "text": null }, { "code": null, "e": 1863, "s": 1853, "text": "Output: " }, { "code": null, "e": 1869, "s": 1863, "text": "null " }, { "code": null, "e": 2355, "s": 1871, "text": "Kotlin also provides a facility of typecasting using safe cast operator as?. If casting is not possible it returns null instead of throwing an ClassCastException exception.Here is an example, in which we are trying to cast Any type of string value that is initially known by the programmer into a nullable string then it works fine. When we initialize the Any with Integer value and try to cast into a nullable string then this typecasting is not possible and returns null to str3. " }, { "code": null, "e": 2362, "s": 2355, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ var str1: Any = \"Safe casting\" val str2: String? = str1 as? String // it works str1 = 11 // type casting not possible so returns null to str3 val str3: String? = str1 as? String val str4: Int? = str1 as? Int // it works println(str2) println(str3) println(str4)}", "e": 2700, "s": 2362, "text": null }, { "code": null, "e": 2710, "s": 2700, "text": "Output: " }, { "code": null, "e": 2731, "s": 2710, "text": "Safe casting\nnull\n11" }, { "code": null, "e": 2750, "s": 2733, "text": "ayushpandey3july" }, { "code": null, "e": 2765, "s": 2750, "text": "varshagumber28" }, { "code": null, "e": 2772, "s": 2765, "text": "Kotlin" }, { "code": null, "e": 2870, "s": 2772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2901, "s": 2870, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 2944, "s": 2901, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 3013, "s": 2944, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3055, "s": 3013, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3097, "s": 3055, "text": "Content Providers in Android with Example" }, { "code": null, "e": 3160, "s": 3097, "text": "How to Add and Customize Back Button of Action Bar in Android?" }, { "code": null, "e": 3198, "s": 3160, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 3228, "s": 3198, "text": "Kotlin Higher-Order Functions" }, { "code": null, "e": 3285, "s": 3228, "text": "How to Change the Color of Status Bar in an Android App?" } ]
Minimum Fibonacci terms with sum equal to K
31 May, 2022 Given a number k, find the required minimum number of Fibonacci terms whose sum equal to k. We can choose a Fibonacci number multiple times. Examples: Input : k = 4 Output : 2 Fibonacci term added twice that is 2 + 2 = 4. Other combinations are 1 + 1 + 2. 1 + 1 + 1 + 1 Among all cases first case has the minimum number of terms = 2. Input : k = 17 Output : 3 We can get any sum using Fibonacci numbers as 1 is a Fibonacci number. For example, to get n, we can n times add 1. Here we need to minimize the count of Fibonacci numbers that contribute to sum. So this problem is basically coin change problem with coins having Fibonacci values. By taking some examples, we can notice that With Fibonacci coin values Greedy approach works.Firstly we calculate Fibonacci terms till less than or equal to k. then start from the last term and keep subtracting that term from k until k >(nth term). Also along with this keep increasing the count of the number of terms. When k < (nth Fibonacci term) move to next Fibonacci term which is less than or Equal to k. at last, print the value of count.The stepwise algorithm is: 1. Find all Fibonacci Terms less than or equal to K. 2. Initialize count = 0. 3. j = Index of last calculated Fibonacci Term. 4. while K > 0 do: // Greedy step count += K / (fibo[j]) // Note that division // is repeated subtraction. K = K % (fibo[j]) j--; 5. Print count. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to find minimum number of fibonacci// terms that sum to K.#include <bits/stdc++.h>using namespace std; // Function to calculate Fibonacci Termsvoid calcFiboTerms(vector<int>& fiboTerms, int K){ int i = 3, nextTerm; fiboTerms.push_back(0); fiboTerms.push_back(1); fiboTerms.push_back(1); // Calculate all Fibonacci terms // which are less than or equal to K. while (1) { nextTerm = fiboTerms[i - 1] + fiboTerms[i - 2]; // If next term is greater than K // do not push it in vector and return. if (nextTerm > K) return; fiboTerms.push_back(nextTerm); i++; }} // Function to find the minimum number of// Fibonacci terms having sum equal to K.int findMinTerms(int K){ // Vector to store Fibonacci terms. vector<int> fiboTerms; calcFiboTerms(fiboTerms, K); int count = 0, j = fiboTerms.size() - 1; // Subtract Fibonacci terms from sum K // until sum > 0. while (K > 0) { // Divide sum K by j-th Fibonacci term to find // how many terms it contribute in sum. count += (K / fiboTerms[j]); K %= (fiboTerms[j]); j--; } return count;} // driver codeint main(){ int K = 17; cout << findMinTerms(K); return 0;} // Java code to find the minimum number of Fibonacci terms// that sum to k.import java.util.*; class GFG{ // Function to calculate Fibonacci Terms public static void calcFiboTerms(ArrayList<Integer> fiboterms, int k) { int i = 3, nextTerm = 0; fiboterms.add(0); fiboterms.add(1); fiboterms.add(1); // Calculate all Fibonacci terms // which are less than or equal to k. while(true) { nextTerm = fiboterms.get(i - 1) + fiboterms.get(i - 2); // If next term is greater than k // do not add in arraylist and return. if(nextTerm>k) return; fiboterms.add(nextTerm); i++; } } // Function to find the minimum number of // Fibonacci terms having sum equal to k. public static int fibMinTerms(int k) { // ArrayList to store Fibonacci terms. ArrayList<Integer> fiboterms = new ArrayList<Integer>(); calcFiboTerms(fiboterms,k); int count = 0, j = fiboterms.size() - 1; // Subtract Fibonacci terms from sum k // until sum > 0. while(k > 0) { // Divide sum k by j-th Fibonacci term to find // how many terms it contribute in sum. count += (k / fiboterms.get(j)); k %= (fiboterms.get(j)); j--; } return count; } // driver code public static void main (String[] args) { int k = 17; System.out.println(fibMinTerms(k)); }} /* This code is contributed by Akash Singh*/ # Python3 code to find minimum number# of Fibonacci terms that sum to K. # Function to calculate Fibonacci Termsdef calcFiboTerms(fiboTerms, K): i = 3 fiboTerms.append(0) fiboTerms.append(1) fiboTerms.append(1) # Calculate all Fibonacci terms # which are less than or equal to K. while True: nextTerm = (fiboTerms[i - 1] + fiboTerms[i - 2]) # If next term is greater than K # do not push it in vector and return. if nextTerm > K: return fiboTerms.append(nextTerm) i += 1 # Function to find the minimum number of# Fibonacci terms having sum equal to K.def findMinTerms(K): # Vector to store Fibonacci terms. fiboTerms = [] calcFiboTerms(fiboTerms, K) count, j = 0, len(fiboTerms) - 1 # Subtract Fibonacci terms from # sum K until sum > 0. while K > 0: # Divide sum K by j-th Fibonacci # term to find how many terms it # contribute in sum. count += K // fiboTerms[j] K %= fiboTerms[j] j -= 1 return count # Driver codeif __name__ == "__main__": K = 17 print(findMinTerms(K)) # This code is contributed# by Rituraj Jain // C# code to find the minimum number// of Fibonacci terms that sum to k.using System;using System.Collections.Generic; class GFG{// Function to calculate Fibonacci Termspublic static void calcFiboTerms(List<int> fiboterms, int k){ int i = 3, nextTerm = 0; fiboterms.Add(0); fiboterms.Add(1); fiboterms.Add(1); // Calculate all Fibonacci terms // which are less than or equal to k. while(true) { nextTerm = fiboterms[i - 1] + fiboterms[i - 2]; // If next term is greater than k // do not add in arraylist and return. if(nextTerm > k) return; fiboterms.Add(nextTerm); i++; }} // Function to find the minimum number of// Fibonacci terms having sum equal to k.public static int fibMinTerms(int k){ // List to store Fibonacci terms. List<int> fiboterms = new List<int>(); calcFiboTerms(fiboterms, k); int count = 0, j = fiboterms.Count - 1; // Subtract Fibonacci terms from sum k // until sum > 0. while(k > 0) { // Divide sum k by j-th Fibonacci term to find // how many terms it contribute in sum. count += (k / fiboterms[j]); k %= (fiboterms[j]); j--; } return count;} // Driver Codepublic static void Main (String[] args){ int k = 17; Console.WriteLine(fibMinTerms(k));}} // This code is contributed by PrinciRaj1992 <script> // Javascript code to find minimum// number of fibonacci terms that// sum to K. // Function to calculate Fibonacci Termsfunction calcFiboTerms(fiboTerms, K){ var i = 3, nextTerm; fiboTerms.push(0); fiboTerms.push(1); fiboTerms.push(1); // Calculate all Fibonacci terms // which are less than or equal to K. while (1) { nextTerm = fiboTerms[i - 1] + fiboTerms[i - 2]; // If next term is greater than K // do not push it in vector and return. if (nextTerm > K) return; fiboTerms.push(nextTerm); i++; }} // Function to find the minimum number of// Fibonacci terms having sum equal to K.function findMinTerms(K){ // Vector to store Fibonacci terms. var fiboTerms = []; calcFiboTerms(fiboTerms, K); var count = 0; var j = fiboTerms.length - 1; // Subtract Fibonacci terms from sum K // until sum > 0. while (K > 0) { // Divide sum K by j-th Fibonacci // term to find how many terms it // contribute in sum. count += parseInt(K / fiboTerms[j]); K %= (fiboTerms[j]); j--; } return count;} // Driver codevar K = 17; document.write(findMinTerms(K)); // This code is contributed by SoumikMondal </script> 3 Time Complexity: O(k), where k represents the given input.Auxiliary Space: O(k), where k represents the given input. rituraj_jain Akanksha_Rai princiraj1992 SoumikMondal simmytarika5 samim2000 dp-coin-change Fibonacci Greedy Greedy Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2022" }, { "code": null, "e": 195, "s": 54, "text": "Given a number k, find the required minimum number of Fibonacci terms whose sum equal to k. We can choose a Fibonacci number multiple times." }, { "code": null, "e": 206, "s": 195, "text": "Examples: " }, { "code": null, "e": 420, "s": 206, "text": "Input : k = 4\nOutput : 2\nFibonacci term added twice that is\n2 + 2 = 4. \nOther combinations are \n1 + 1 + 2. \n1 + 1 + 1 + 1\nAmong all cases first case has the \nminimum number of terms = 2.\n\nInput : k = 17\nOutput : 3" }, { "code": null, "e": 1022, "s": 420, "text": "We can get any sum using Fibonacci numbers as 1 is a Fibonacci number. For example, to get n, we can n times add 1. Here we need to minimize the count of Fibonacci numbers that contribute to sum. So this problem is basically coin change problem with coins having Fibonacci values. By taking some examples, we can notice that With Fibonacci coin values Greedy approach works.Firstly we calculate Fibonacci terms till less than or equal to k. then start from the last term and keep subtracting that term from k until k >(nth term). Also along with this keep increasing the count of the number of terms. " }, { "code": null, "e": 1176, "s": 1022, "text": "When k < (nth Fibonacci term) move to next Fibonacci term which is less than or Equal to k. at last, print the value of count.The stepwise algorithm is: " }, { "code": null, "e": 1525, "s": 1176, "text": " 1. Find all Fibonacci Terms less than or equal to K.\n 2. Initialize count = 0.\n 3. j = Index of last calculated Fibonacci Term.\n 4. while K > 0 do:\n \n // Greedy step\n count += K / (fibo[j]) // Note that division \n // is repeated subtraction.\n K = K % (fibo[j])\n j--;\n 5. Print count." }, { "code": null, "e": 1577, "s": 1525, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1581, "s": 1577, "text": "C++" }, { "code": null, "e": 1586, "s": 1581, "text": "Java" }, { "code": null, "e": 1594, "s": 1586, "text": "Python3" }, { "code": null, "e": 1597, "s": 1594, "text": "C#" }, { "code": null, "e": 1608, "s": 1597, "text": "Javascript" }, { "code": "// C++ code to find minimum number of fibonacci// terms that sum to K.#include <bits/stdc++.h>using namespace std; // Function to calculate Fibonacci Termsvoid calcFiboTerms(vector<int>& fiboTerms, int K){ int i = 3, nextTerm; fiboTerms.push_back(0); fiboTerms.push_back(1); fiboTerms.push_back(1); // Calculate all Fibonacci terms // which are less than or equal to K. while (1) { nextTerm = fiboTerms[i - 1] + fiboTerms[i - 2]; // If next term is greater than K // do not push it in vector and return. if (nextTerm > K) return; fiboTerms.push_back(nextTerm); i++; }} // Function to find the minimum number of// Fibonacci terms having sum equal to K.int findMinTerms(int K){ // Vector to store Fibonacci terms. vector<int> fiboTerms; calcFiboTerms(fiboTerms, K); int count = 0, j = fiboTerms.size() - 1; // Subtract Fibonacci terms from sum K // until sum > 0. while (K > 0) { // Divide sum K by j-th Fibonacci term to find // how many terms it contribute in sum. count += (K / fiboTerms[j]); K %= (fiboTerms[j]); j--; } return count;} // driver codeint main(){ int K = 17; cout << findMinTerms(K); return 0;}", "e": 2891, "s": 1608, "text": null }, { "code": "// Java code to find the minimum number of Fibonacci terms// that sum to k.import java.util.*; class GFG{ // Function to calculate Fibonacci Terms public static void calcFiboTerms(ArrayList<Integer> fiboterms, int k) { int i = 3, nextTerm = 0; fiboterms.add(0); fiboterms.add(1); fiboterms.add(1); // Calculate all Fibonacci terms // which are less than or equal to k. while(true) { nextTerm = fiboterms.get(i - 1) + fiboterms.get(i - 2); // If next term is greater than k // do not add in arraylist and return. if(nextTerm>k) return; fiboterms.add(nextTerm); i++; } } // Function to find the minimum number of // Fibonacci terms having sum equal to k. public static int fibMinTerms(int k) { // ArrayList to store Fibonacci terms. ArrayList<Integer> fiboterms = new ArrayList<Integer>(); calcFiboTerms(fiboterms,k); int count = 0, j = fiboterms.size() - 1; // Subtract Fibonacci terms from sum k // until sum > 0. while(k > 0) { // Divide sum k by j-th Fibonacci term to find // how many terms it contribute in sum. count += (k / fiboterms.get(j)); k %= (fiboterms.get(j)); j--; } return count; } // driver code public static void main (String[] args) { int k = 17; System.out.println(fibMinTerms(k)); }} /* This code is contributed by Akash Singh*/", "e": 4626, "s": 2891, "text": null }, { "code": "# Python3 code to find minimum number# of Fibonacci terms that sum to K. # Function to calculate Fibonacci Termsdef calcFiboTerms(fiboTerms, K): i = 3 fiboTerms.append(0) fiboTerms.append(1) fiboTerms.append(1) # Calculate all Fibonacci terms # which are less than or equal to K. while True: nextTerm = (fiboTerms[i - 1] + fiboTerms[i - 2]) # If next term is greater than K # do not push it in vector and return. if nextTerm > K: return fiboTerms.append(nextTerm) i += 1 # Function to find the minimum number of# Fibonacci terms having sum equal to K.def findMinTerms(K): # Vector to store Fibonacci terms. fiboTerms = [] calcFiboTerms(fiboTerms, K) count, j = 0, len(fiboTerms) - 1 # Subtract Fibonacci terms from # sum K until sum > 0. while K > 0: # Divide sum K by j-th Fibonacci # term to find how many terms it # contribute in sum. count += K // fiboTerms[j] K %= fiboTerms[j] j -= 1 return count # Driver codeif __name__ == \"__main__\": K = 17 print(findMinTerms(K)) # This code is contributed# by Rituraj Jain", "e": 5839, "s": 4626, "text": null }, { "code": "// C# code to find the minimum number// of Fibonacci terms that sum to k.using System;using System.Collections.Generic; class GFG{// Function to calculate Fibonacci Termspublic static void calcFiboTerms(List<int> fiboterms, int k){ int i = 3, nextTerm = 0; fiboterms.Add(0); fiboterms.Add(1); fiboterms.Add(1); // Calculate all Fibonacci terms // which are less than or equal to k. while(true) { nextTerm = fiboterms[i - 1] + fiboterms[i - 2]; // If next term is greater than k // do not add in arraylist and return. if(nextTerm > k) return; fiboterms.Add(nextTerm); i++; }} // Function to find the minimum number of// Fibonacci terms having sum equal to k.public static int fibMinTerms(int k){ // List to store Fibonacci terms. List<int> fiboterms = new List<int>(); calcFiboTerms(fiboterms, k); int count = 0, j = fiboterms.Count - 1; // Subtract Fibonacci terms from sum k // until sum > 0. while(k > 0) { // Divide sum k by j-th Fibonacci term to find // how many terms it contribute in sum. count += (k / fiboterms[j]); k %= (fiboterms[j]); j--; } return count;} // Driver Codepublic static void Main (String[] args){ int k = 17; Console.WriteLine(fibMinTerms(k));}} // This code is contributed by PrinciRaj1992", "e": 7330, "s": 5839, "text": null }, { "code": "<script> // Javascript code to find minimum// number of fibonacci terms that// sum to K. // Function to calculate Fibonacci Termsfunction calcFiboTerms(fiboTerms, K){ var i = 3, nextTerm; fiboTerms.push(0); fiboTerms.push(1); fiboTerms.push(1); // Calculate all Fibonacci terms // which are less than or equal to K. while (1) { nextTerm = fiboTerms[i - 1] + fiboTerms[i - 2]; // If next term is greater than K // do not push it in vector and return. if (nextTerm > K) return; fiboTerms.push(nextTerm); i++; }} // Function to find the minimum number of// Fibonacci terms having sum equal to K.function findMinTerms(K){ // Vector to store Fibonacci terms. var fiboTerms = []; calcFiboTerms(fiboTerms, K); var count = 0; var j = fiboTerms.length - 1; // Subtract Fibonacci terms from sum K // until sum > 0. while (K > 0) { // Divide sum K by j-th Fibonacci // term to find how many terms it // contribute in sum. count += parseInt(K / fiboTerms[j]); K %= (fiboTerms[j]); j--; } return count;} // Driver codevar K = 17; document.write(findMinTerms(K)); // This code is contributed by SoumikMondal </script>", "e": 8630, "s": 7330, "text": null }, { "code": null, "e": 8632, "s": 8630, "text": "3" }, { "code": null, "e": 8751, "s": 8634, "text": "Time Complexity: O(k), where k represents the given input.Auxiliary Space: O(k), where k represents the given input." }, { "code": null, "e": 8764, "s": 8751, "text": "rituraj_jain" }, { "code": null, "e": 8777, "s": 8764, "text": "Akanksha_Rai" }, { "code": null, "e": 8791, "s": 8777, "text": "princiraj1992" }, { "code": null, "e": 8804, "s": 8791, "text": "SoumikMondal" }, { "code": null, "e": 8817, "s": 8804, "text": "simmytarika5" }, { "code": null, "e": 8827, "s": 8817, "text": "samim2000" }, { "code": null, "e": 8842, "s": 8827, "text": "dp-coin-change" }, { "code": null, "e": 8852, "s": 8842, "text": "Fibonacci" }, { "code": null, "e": 8859, "s": 8852, "text": "Greedy" }, { "code": null, "e": 8866, "s": 8859, "text": "Greedy" }, { "code": null, "e": 8876, "s": 8866, "text": "Fibonacci" } ]
How to use DataGrid Component in ReactJS ?
13 Apr, 2021 A DataGrid Component helps in displaying the information in a grid-like format of rows and columns. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use DataGrid Component. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid Step 3: After creating the ReactJS application, Install the material-ui module using the following command: npm install @material-ui/data-grid Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import * as React from 'react';import { DataGrid } from '@material-ui/data-grid'; const columns = [ { field: 'id', headerName: 'ID', width: 170 }, { field: 'name', headerName: 'NAME', width: 170 }, { field: 'age', headerName: 'AGE', width: 170 },]; const rows = [ { id: 1, name: 'Gourav', age: 12 }, { id: 2, name: 'Geek', age: 43 }, { id: 3, name: 'Pranav', age: 41 },]; export default function App() { return ( <div style={{ height: 500, width: '80%' }}> <h4>How to use DataGrid Component in ReactJS?</h4> <DataGrid rows={rows} columns={columns} pageSize={2} /> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://material-ui.com/components/data-grid/ Material-UI ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 293, "s": 28, "text": "A DataGrid Component helps in displaying the information in a grid-like format of rows and columns. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use DataGrid Component." }, { "code": null, "e": 343, "s": 293, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 438, "s": 343, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 502, "s": 438, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 534, "s": 502, "text": "npx create-react-app foldername" }, { "code": null, "e": 647, "s": 534, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 747, "s": 647, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 761, "s": 747, "text": "cd foldername" }, { "code": null, "e": 903, "s": 761, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid" }, { "code": null, "e": 1011, "s": 903, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:" }, { "code": null, "e": 1046, "s": 1011, "text": "npm install @material-ui/data-grid" }, { "code": null, "e": 1098, "s": 1046, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1116, "s": 1098, "text": "Project Structure" }, { "code": null, "e": 1246, "s": 1116, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1253, "s": 1246, "text": "App.js" }, { "code": "import * as React from 'react';import { DataGrid } from '@material-ui/data-grid'; const columns = [ { field: 'id', headerName: 'ID', width: 170 }, { field: 'name', headerName: 'NAME', width: 170 }, { field: 'age', headerName: 'AGE', width: 170 },]; const rows = [ { id: 1, name: 'Gourav', age: 12 }, { id: 2, name: 'Geek', age: 43 }, { id: 3, name: 'Pranav', age: 41 },]; export default function App() { return ( <div style={{ height: 500, width: '80%' }}> <h4>How to use DataGrid Component in ReactJS?</h4> <DataGrid rows={rows} columns={columns} pageSize={2} /> </div> );}", "e": 1855, "s": 1253, "text": null }, { "code": null, "e": 1968, "s": 1855, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1978, "s": 1968, "text": "npm start" }, { "code": null, "e": 2077, "s": 1978, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2134, "s": 2077, "text": "Reference: https://material-ui.com/components/data-grid/" }, { "code": null, "e": 2146, "s": 2134, "text": "Material-UI" }, { "code": null, "e": 2154, "s": 2146, "text": "ReactJS" }, { "code": null, "e": 2171, "s": 2154, "text": "Web Technologies" } ]
Python PIL | Image.open() method
17 Jul, 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.open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new(). Syntax: PIL.Image.open(fp, mode=’r’) Parameters: fp – A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.mode – The mode. If given, this argument must be “r”. Returns type: An image object.Raises: IOError – If the file cannot be found, or the image cannot be opened and identified. Image Used: # Imports PIL module from PIL import Image # open method used to open different extension image fileim = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg") # This method will show image in any image viewer im.show() Output:.JPG extension image open. Another Example: Here we used .PNG extension file. Image Used: # Imports PIL module from PIL import Image # open method used to open different extension image fileim = Image.open(r"C:\Users\System-Pc\Desktop\lion.png") # This method will show image in any image viewer im.show() Output:.PNG extension image open. Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Jul, 2019" }, { "code": null, "e": 380, "s": 53, "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": 440, "s": 380, "text": "PIL.Image.open() Opens and identifies the given image file." }, { "code": null, "e": 653, "s": 440, "text": "This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new()." }, { "code": null, "e": 690, "s": 653, "text": "Syntax: PIL.Image.open(fp, mode=’r’)" }, { "code": null, "e": 702, "s": 690, "text": "Parameters:" }, { "code": null, "e": 916, "s": 702, "text": "fp – A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.mode – The mode. If given, this argument must be “r”." }, { "code": null, "e": 1039, "s": 916, "text": "Returns type: An image object.Raises: IOError – If the file cannot be found, or the image cannot be opened and identified." }, { "code": null, "e": 1051, "s": 1039, "text": "Image Used:" }, { "code": " # Imports PIL module from PIL import Image # open method used to open different extension image fileim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\ybear.jpg\") # This method will show image in any image viewer im.show() ", "e": 1277, "s": 1051, "text": null }, { "code": null, "e": 1311, "s": 1277, "text": "Output:.JPG extension image open." }, { "code": null, "e": 1362, "s": 1311, "text": "Another Example: Here we used .PNG extension file." }, { "code": null, "e": 1374, "s": 1362, "text": "Image Used:" }, { "code": " # Imports PIL module from PIL import Image # open method used to open different extension image fileim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\lion.png\") # This method will show image in any image viewer im.show() ", "e": 1599, "s": 1374, "text": null }, { "code": null, "e": 1633, "s": 1599, "text": "Output:.PNG extension image open." }, { "code": null, "e": 1644, "s": 1633, "text": "Python-pil" }, { "code": null, "e": 1651, "s": 1644, "text": "Python" } ]
JavaScript | Program to write data in a text File
19 Feb, 2019 Pre-requisite: How to import a library in JavaScript. Read from here: https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ . There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs.js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system. The following function will create a new file with a given name if there isn’t one, else it will rewrite the file erasing all the previous data in it. Used Function: The writeFile() functions is used for writing operation. Syntax: writeFile( Path, Data, Callback) Parameters: This method accepts three parameters as mentioned above and described below: Path: It takes in relative path from the program to the text File. If the file is to be created in the same folder as that of the program, then give the name of the file only. If file not exists then new file will be created automatically. Data: This argument takes in data which need to write in the file. Callback Function: It is the callback function which further has an argument (err). If the operation fails to write the data, err shows the fault. Example: <script>// Requiring fs module in which// writeFile function is defined.const fs = require('fs') // Data which will write in a file.let data = "Learning how to write in a file." // Write data in 'Output.txt' .fs.writeFile('Output.txt', data, (err) => { // In case of a error throw err. if (err) throw err;})</script> Output: Learning how to write in a file. Note: Above script can be run using NodeJs interpreter in terminal. JavaScript-Misc Technical Scripter 2018 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2019" }, { "code": null, "e": 174, "s": 28, "text": "Pre-requisite: How to import a library in JavaScript. Read from here: https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ ." }, { "code": null, "e": 631, "s": 174, "text": "There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs.js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system. The following function will create a new file with a given name if there isn’t one, else it will rewrite the file erasing all the previous data in it." }, { "code": null, "e": 703, "s": 631, "text": "Used Function: The writeFile() functions is used for writing operation." }, { "code": null, "e": 711, "s": 703, "text": "Syntax:" }, { "code": null, "e": 744, "s": 711, "text": "writeFile( Path, Data, Callback)" }, { "code": null, "e": 833, "s": 744, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 1073, "s": 833, "text": "Path: It takes in relative path from the program to the text File. If the file is to be created in the same folder as that of the program, then give the name of the file only. If file not exists then new file will be created automatically." }, { "code": null, "e": 1140, "s": 1073, "text": "Data: This argument takes in data which need to write in the file." }, { "code": null, "e": 1287, "s": 1140, "text": "Callback Function: It is the callback function which further has an argument (err). If the operation fails to write the data, err shows the fault." }, { "code": null, "e": 1296, "s": 1287, "text": "Example:" }, { "code": "<script>// Requiring fs module in which// writeFile function is defined.const fs = require('fs') // Data which will write in a file.let data = \"Learning how to write in a file.\" // Write data in 'Output.txt' .fs.writeFile('Output.txt', data, (err) => { // In case of a error throw err. if (err) throw err;})</script>", "e": 1627, "s": 1296, "text": null }, { "code": null, "e": 1635, "s": 1627, "text": "Output:" }, { "code": null, "e": 1668, "s": 1635, "text": "Learning how to write in a file." }, { "code": null, "e": 1736, "s": 1668, "text": "Note: Above script can be run using NodeJs interpreter in terminal." }, { "code": null, "e": 1752, "s": 1736, "text": "JavaScript-Misc" }, { "code": null, "e": 1776, "s": 1752, "text": "Technical Scripter 2018" }, { "code": null, "e": 1787, "s": 1776, "text": "JavaScript" }, { "code": null, "e": 1806, "s": 1787, "text": "Technical Scripter" }, { "code": null, "e": 1823, "s": 1806, "text": "Web Technologies" } ]
ES6 | Array
31 Aug, 2021 An array is a homogeneous collection of values. It is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where the array is a reference to the multiple variables, an ES6 array is a single variable that stores multiple elements. We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.Characteristics of an Array: Indexing is available in an array so random access of elements using the array index is possible. Multiple elements can be stored using a single variable name. Traversal through an array becomes easy using a loop. Sorting becomes easy as it can be accomplished by writing fewer lines of code in an array. Array values can be modified or update but can not be deleted. Initializing an array: Initialize or declare an array is peace of cake. The below program implements the initialization of an array. Program: javascript // Initializing while declaringvar JS = ["ES1", "ES2", "ES3", "ES4", "ES5", "ES6"]; // Initializing after declaringJS[0] = "ES6";JS[1] = "ES6";JS[2] = "ES6";JS[3] = "ES6"; Accessing array elements: To access any specific array element we will need to know the index number of that element. The array index number is used to accessing the array elements. The indexing of array always starts with 0. Program: javascript <script>// Initializing while declaringvar JS= ["ES1", "ES2", "ES3", "ES4", "ES5", "ES6"]; // Accessing array elementconsole.log(JS[4])console.log(JS[5])</script> Output: ES5 ES6 Array Object: The Array constructor can be passed as a numeric value that represents the size of the array and array elements are comma-separated values. Program 1: javascript <script>var js = ["ES6", 2015, "ES8", 2017, "ES10", 2019]; // len contains the length of the arrayvar len = js.length;for (var i = 0; i < len; i++) console.log(js[i]); </script> Output: ES6 2015 ES8 2017 ES10 2019 Program 2: javascript <script>var Geeks = new Array(6) for(var i = 0; i < Geeks.length; i++){ Geeks[i] = (i * 2)/3 console.log(Geeks[i])}</script> Output: 0 0.6666666666666666 1.3333333333333333 2 2.6666666666666665 3.3333333333333335 Array Methods: There are lots of array methods introduced in ES6. Note: In JavaScript, arrays use numbered indexes, objects use named indexes. sooda367 akshaysingh98088 ES6 Picked JavaScript 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 Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises 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": "\n31 Aug, 2021" }, { "code": null, "e": 679, "s": 28, "text": "An array is a homogeneous collection of values. It is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where the array is a reference to the multiple variables, an ES6 array is a single variable that stores multiple elements. We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.Characteristics of an Array: " }, { "code": null, "e": 777, "s": 679, "text": "Indexing is available in an array so random access of elements using the array index is possible." }, { "code": null, "e": 839, "s": 777, "text": "Multiple elements can be stored using a single variable name." }, { "code": null, "e": 893, "s": 839, "text": "Traversal through an array becomes easy using a loop." }, { "code": null, "e": 984, "s": 893, "text": "Sorting becomes easy as it can be accomplished by writing fewer lines of code in an array." }, { "code": null, "e": 1047, "s": 984, "text": "Array values can be modified or update but can not be deleted." }, { "code": null, "e": 1182, "s": 1047, "text": "Initializing an array: Initialize or declare an array is peace of cake. The below program implements the initialization of an array. " }, { "code": null, "e": 1193, "s": 1182, "text": "Program: " }, { "code": null, "e": 1204, "s": 1193, "text": "javascript" }, { "code": "// Initializing while declaringvar JS = [\"ES1\", \"ES2\", \"ES3\", \"ES4\", \"ES5\", \"ES6\"]; // Initializing after declaringJS[0] = \"ES6\";JS[1] = \"ES6\";JS[2] = \"ES6\";JS[3] = \"ES6\";", "e": 1376, "s": 1204, "text": null }, { "code": null, "e": 1604, "s": 1376, "text": "Accessing array elements: To access any specific array element we will need to know the index number of that element. The array index number is used to accessing the array elements. The indexing of array always starts with 0. " }, { "code": null, "e": 1615, "s": 1604, "text": "Program: " }, { "code": null, "e": 1626, "s": 1615, "text": "javascript" }, { "code": "<script>// Initializing while declaringvar JS= [\"ES1\", \"ES2\", \"ES3\", \"ES4\", \"ES5\", \"ES6\"]; // Accessing array elementconsole.log(JS[4])console.log(JS[5])</script>", "e": 1789, "s": 1626, "text": null }, { "code": null, "e": 1799, "s": 1789, "text": "Output: " }, { "code": null, "e": 1807, "s": 1799, "text": "ES5\nES6" }, { "code": null, "e": 1962, "s": 1807, "text": "Array Object: The Array constructor can be passed as a numeric value that represents the size of the array and array elements are comma-separated values. " }, { "code": null, "e": 1975, "s": 1962, "text": "Program 1: " }, { "code": null, "e": 1986, "s": 1975, "text": "javascript" }, { "code": "<script>var js = [\"ES6\", 2015, \"ES8\", 2017, \"ES10\", 2019]; // len contains the length of the arrayvar len = js.length;for (var i = 0; i < len; i++) console.log(js[i]); </script> ", "e": 2202, "s": 1986, "text": null }, { "code": null, "e": 2212, "s": 2202, "text": "Output: " }, { "code": null, "e": 2240, "s": 2212, "text": "ES6\n2015\nES8\n2017\nES10\n2019" }, { "code": null, "e": 2253, "s": 2240, "text": "Program 2: " }, { "code": null, "e": 2264, "s": 2253, "text": "javascript" }, { "code": "<script>var Geeks = new Array(6) for(var i = 0; i < Geeks.length; i++){ Geeks[i] = (i * 2)/3 console.log(Geeks[i])}</script> ", "e": 2428, "s": 2264, "text": null }, { "code": null, "e": 2438, "s": 2428, "text": "Output: " }, { "code": null, "e": 2518, "s": 2438, "text": "0\n0.6666666666666666\n1.3333333333333333\n2\n2.6666666666666665\n3.3333333333333335" }, { "code": null, "e": 2586, "s": 2518, "text": "Array Methods: There are lots of array methods introduced in ES6. " }, { "code": null, "e": 2664, "s": 2586, "text": "Note: In JavaScript, arrays use numbered indexes, objects use named indexes. " }, { "code": null, "e": 2673, "s": 2664, "text": "sooda367" }, { "code": null, "e": 2690, "s": 2673, "text": "akshaysingh98088" }, { "code": null, "e": 2694, "s": 2690, "text": "ES6" }, { "code": null, "e": 2701, "s": 2694, "text": "Picked" }, { "code": null, "e": 2712, "s": 2701, "text": "JavaScript" }, { "code": null, "e": 2729, "s": 2712, "text": "Web Technologies" }, { "code": null, "e": 2827, "s": 2729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2888, "s": 2827, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2928, "s": 2888, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2969, "s": 2928, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3011, "s": 2969, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3033, "s": 3011, "text": "JavaScript | Promises" }, { "code": null, "e": 3095, "s": 3033, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3128, "s": 3095, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3189, "s": 3128, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3239, "s": 3189, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Working with the Image Data Type in pillow
26 Jul, 2019 In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow. Image we will be working on : size() method – It helps to get the dimensions of an image. IMG = Image.open(Image_path)croppedIm = IMG.size # import Image modulefrom PIL import Image # open the imagecatIm = Image.open('D:/cat.jpg') # Display the dimensions of the imageprint(catIm.size) Output : (400, 533) Getting height and width separately – It helps us to get the height and width of the image. # import Image modulefrom PIL import Image # Open the imagecatIm = Image.open('D:/cat.jpg') # Create two different variables # The first one will contain width and # the second one will contain heightwidth, height = catIm.size # Display height and widthprint(height)print(width) Output : 400 533 filename() method – It helps us to get the filename of the image. IMG = Image.open(Image_path)croppedIm = IMG.filename # import the Image modulefrom PIL import Image # Open the imagecatIm = Image.open('D:/cat.jpg') # print the filenameprint(catIm.filename) Output : D:/cat.jpg format() method – It helps us to get the format the image is in. IMG = Image.open(Image_path)croppedIm = IMG.format # import the imagefrom PIL import Image # open the imagecatIm = Image.open('D:/cat.jpg') # print the format of the imageprint(catIm.format) Output : JPEG format_description() method – It helps us to get the format description of the image. IMG = Image.open(Image_path)croppedIm = IMG.format_description # import the imagefrom PIL import Image # open the imagecatIm = Image.open('D:/cat.jpg') # print the format description of the imageprint(catIm.format_description) Output : JPEG (ISO 10918) Image-Processing Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Jul, 2019" }, { "code": null, "e": 258, "s": 53, "text": "In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow." }, { "code": null, "e": 288, "s": 258, "text": "Image we will be working on :" }, { "code": null, "e": 348, "s": 288, "text": "size() method – It helps to get the dimensions of an image." }, { "code": null, "e": 397, "s": 348, "text": "IMG = Image.open(Image_path)croppedIm = IMG.size" }, { "code": "# import Image modulefrom PIL import Image # open the imagecatIm = Image.open('D:/cat.jpg') # Display the dimensions of the imageprint(catIm.size)", "e": 546, "s": 397, "text": null }, { "code": null, "e": 555, "s": 546, "text": "Output :" }, { "code": null, "e": 566, "s": 555, "text": "(400, 533)" }, { "code": null, "e": 658, "s": 566, "text": "Getting height and width separately – It helps us to get the height and width of the image." }, { "code": "# import Image modulefrom PIL import Image # Open the imagecatIm = Image.open('D:/cat.jpg') # Create two different variables # The first one will contain width and # the second one will contain heightwidth, height = catIm.size # Display height and widthprint(height)print(width)", "e": 940, "s": 658, "text": null }, { "code": null, "e": 949, "s": 940, "text": "Output :" }, { "code": null, "e": 957, "s": 949, "text": "400\n533" }, { "code": null, "e": 1024, "s": 957, "text": " filename() method – It helps us to get the filename of the image." }, { "code": null, "e": 1077, "s": 1024, "text": "IMG = Image.open(Image_path)croppedIm = IMG.filename" }, { "code": "# import the Image modulefrom PIL import Image # Open the imagecatIm = Image.open('D:/cat.jpg') # print the filenameprint(catIm.filename)", "e": 1217, "s": 1077, "text": null }, { "code": null, "e": 1226, "s": 1217, "text": "Output :" }, { "code": null, "e": 1237, "s": 1226, "text": "D:/cat.jpg" }, { "code": null, "e": 1303, "s": 1237, "text": " format() method – It helps us to get the format the image is in." }, { "code": null, "e": 1354, "s": 1303, "text": "IMG = Image.open(Image_path)croppedIm = IMG.format" }, { "code": "# import the imagefrom PIL import Image # open the imagecatIm = Image.open('D:/cat.jpg') # print the format of the imageprint(catIm.format)", "e": 1496, "s": 1354, "text": null }, { "code": null, "e": 1505, "s": 1496, "text": "Output :" }, { "code": null, "e": 1510, "s": 1505, "text": "JPEG" }, { "code": null, "e": 1597, "s": 1510, "text": " format_description() method – It helps us to get the format description of the image." }, { "code": null, "e": 1660, "s": 1597, "text": "IMG = Image.open(Image_path)croppedIm = IMG.format_description" }, { "code": "# import the imagefrom PIL import Image # open the imagecatIm = Image.open('D:/cat.jpg') # print the format description of the imageprint(catIm.format_description)", "e": 1826, "s": 1660, "text": null }, { "code": null, "e": 1835, "s": 1826, "text": "Output :" }, { "code": null, "e": 1852, "s": 1835, "text": "JPEG (ISO 10918)" }, { "code": null, "e": 1869, "s": 1852, "text": "Image-Processing" }, { "code": null, "e": 1880, "s": 1869, "text": "Python-pil" }, { "code": null, "e": 1887, "s": 1880, "text": "Python" } ]
Java Program to Replace Multiple Characters in a String
06 Jun, 2021 In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() method Using replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters. Syntax: public String replace(char oldch, char newch) Parameters: The old character. The new character. Return Value: It returns a string derived from this string by replacing every occurrence of old character with a new character. Example Java // Java code to demonstrate the// working of replace()public class rep1 {public static void main(String args[]) { // Initialising String String Str = new String("Welcome to geeksforgeeks"); // Using replace to replace characters System.out.print("After replacing all o with T : " ); System.out.println(Str.replace('o', 'T')); // Using replace to replace characters System.out.print("After replacing all e with D : " ); System.out.println(Str.replace('e', 'D')); }} After replacing all o with T : WelcTme tT geeksfTrgeeks After replacing all e with D : WDlcomD to gDDksforgDDks Method 2: Using replaceAll() method This method replaces each substring of the string that matches the given regular expression with the given replace_str. Syntax: public String replaceAll(String regex, String replace_str) Parameters: regex: the regular expression to which this string is to be matched. replace_str: the string which would replace found expression. Return Value: This method returns the resulting String. Example Java // Java code to demonstrate the// working of replaceAll()public class rep2 {public static void main(String args[]) { // Initialising String String Str = new String("Welcome to geeksforgeeks"); // original string System.out.print("Original String : " ); System.out.println(Str); // Using replaceAll to replace regex with replace_str System.out.print("After replacing regex with replace_str : " ); System.out.println(Str.replaceAll("(.*)geeks(.*)", "AKSHIT SAXENA")); }} Original String : Welcome to geeksforgeeks After replacing regex with replace_str : AKSHIT SAXENA Method 3: Using replaceFirst() method This method replaces the first substring of this string that matches the given regular expression with the given replace_str. Syntax: public String replaceFirst(String regex, String replace_str) Parameters regex: The regular expression to which this string is to be matched. replace_str: The string which would replace found expression. Return value: This method returns a resulting string. Example Java // Java code to demonstrate the// working of replaceFirst()public class rep3 {public static void main(String args[]) { // Initialising String String Str = new String("Welcome to geeksforgeeks"); // original string System.out.print("Original String : " ); System.out.println(Str); // Using replaceFirst to replace regex with replace_str // Replaces 1st occurrence of geeks with ASTHA System.out.print("After replacing 1st occurrence of regex with replace_str : " ); System.out.println(Str.replaceFirst("geeks", "Akshit")); }} Original String : Welcome to geeksforgeeks After replacing 1st occurrence of regex with replace_str : Welcome to Akshitforgeeks Java-String-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 178, "s": 28, "text": "In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: " }, { "code": null, "e": 208, "s": 178, "text": "Using String.replace() method" }, { "code": null, "e": 235, "s": 208, "text": "Using replaceAll() method " }, { "code": null, "e": 264, "s": 235, "text": "Using replaceFirst() method " }, { "code": null, "e": 304, "s": 264, "text": "Method 1: Using String.replace() method" }, { "code": null, "e": 431, "s": 304, "text": "This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters." }, { "code": null, "e": 439, "s": 431, "text": "Syntax:" }, { "code": null, "e": 485, "s": 439, "text": "public String replace(char oldch, char newch)" }, { "code": null, "e": 497, "s": 485, "text": "Parameters:" }, { "code": null, "e": 516, "s": 497, "text": "The old character." }, { "code": null, "e": 535, "s": 516, "text": "The new character." }, { "code": null, "e": 663, "s": 535, "text": "Return Value: It returns a string derived from this string by replacing every occurrence of old character with a new character." }, { "code": null, "e": 672, "s": 663, "text": "Example " }, { "code": null, "e": 677, "s": 672, "text": "Java" }, { "code": "// Java code to demonstrate the// working of replace()public class rep1 {public static void main(String args[]) { // Initialising String String Str = new String(\"Welcome to geeksforgeeks\"); // Using replace to replace characters System.out.print(\"After replacing all o with T : \" ); System.out.println(Str.replace('o', 'T')); // Using replace to replace characters System.out.print(\"After replacing all e with D : \" ); System.out.println(Str.replace('e', 'D')); }}", "e": 1205, "s": 677, "text": null }, { "code": null, "e": 1317, "s": 1205, "text": "After replacing all o with T : WelcTme tT geeksfTrgeeks\nAfter replacing all e with D : WDlcomD to gDDksforgDDks" }, { "code": null, "e": 1354, "s": 1317, "text": "Method 2: Using replaceAll() method " }, { "code": null, "e": 1474, "s": 1354, "text": "This method replaces each substring of the string that matches the given regular expression with the given replace_str." }, { "code": null, "e": 1482, "s": 1474, "text": "Syntax:" }, { "code": null, "e": 1541, "s": 1482, "text": "public String replaceAll(String regex, String replace_str)" }, { "code": null, "e": 1553, "s": 1541, "text": "Parameters:" }, { "code": null, "e": 1622, "s": 1553, "text": "regex: the regular expression to which this string is to be matched." }, { "code": null, "e": 1684, "s": 1622, "text": "replace_str: the string which would replace found expression." }, { "code": null, "e": 1740, "s": 1684, "text": "Return Value: This method returns the resulting String." }, { "code": null, "e": 1749, "s": 1740, "text": "Example " }, { "code": null, "e": 1754, "s": 1749, "text": "Java" }, { "code": "// Java code to demonstrate the// working of replaceAll()public class rep2 {public static void main(String args[]) { // Initialising String String Str = new String(\"Welcome to geeksforgeeks\"); // original string System.out.print(\"Original String : \" ); System.out.println(Str); // Using replaceAll to replace regex with replace_str System.out.print(\"After replacing regex with replace_str : \" ); System.out.println(Str.replaceAll(\"(.*)geeks(.*)\", \"AKSHIT SAXENA\")); }}", "e": 2286, "s": 1754, "text": null }, { "code": null, "e": 2384, "s": 2286, "text": "Original String : Welcome to geeksforgeeks\nAfter replacing regex with replace_str : AKSHIT SAXENA" }, { "code": null, "e": 2423, "s": 2384, "text": "Method 3: Using replaceFirst() method " }, { "code": null, "e": 2549, "s": 2423, "text": "This method replaces the first substring of this string that matches the given regular expression with the given replace_str." }, { "code": null, "e": 2557, "s": 2549, "text": "Syntax:" }, { "code": null, "e": 2618, "s": 2557, "text": "public String replaceFirst(String regex, String replace_str)" }, { "code": null, "e": 2629, "s": 2618, "text": "Parameters" }, { "code": null, "e": 2698, "s": 2629, "text": "regex: The regular expression to which this string is to be matched." }, { "code": null, "e": 2760, "s": 2698, "text": "replace_str: The string which would replace found expression." }, { "code": null, "e": 2814, "s": 2760, "text": "Return value: This method returns a resulting string." }, { "code": null, "e": 2822, "s": 2814, "text": "Example" }, { "code": null, "e": 2827, "s": 2822, "text": "Java" }, { "code": "// Java code to demonstrate the// working of replaceFirst()public class rep3 {public static void main(String args[]) { // Initialising String String Str = new String(\"Welcome to geeksforgeeks\"); // original string System.out.print(\"Original String : \" ); System.out.println(Str); // Using replaceFirst to replace regex with replace_str // Replaces 1st occurrence of geeks with ASTHA System.out.print(\"After replacing 1st occurrence of regex with replace_str : \" ); System.out.println(Str.replaceFirst(\"geeks\", \"Akshit\")); }}", "e": 3418, "s": 2827, "text": null }, { "code": null, "e": 3546, "s": 3418, "text": "Original String : Welcome to geeksforgeeks\nAfter replacing 1st occurrence of regex with replace_str : Welcome to Akshitforgeeks" }, { "code": null, "e": 3567, "s": 3546, "text": "Java-String-Programs" }, { "code": null, "e": 3574, "s": 3567, "text": "Picked" }, { "code": null, "e": 3579, "s": 3574, "text": "Java" }, { "code": null, "e": 3593, "s": 3579, "text": "Java Programs" }, { "code": null, "e": 3598, "s": 3593, "text": "Java" } ]
Getting Started with Pygame
30 Jun, 2021 Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games. You can code the games and then use specific commands to change it into an executable file that you can share with your friends to show them the work you have been doing. It includes computer graphics and sound libraries designed to be used with the Python programming language. PyGame 2.0.1 is the latest version at the time of writing this article. By default, Python doesn’t come with PyGame as an in-built Library. So we have to install it using the command prompt. Open a command prompt and type the following command: pip install pygame If you already have PyGame installed, use the following command to check the version: pip show pygame If your Pygame is not updated to the latest version, use the following command: pip install pygame --upgrade If this command shows a ModuleNotFoundError, then it is clear that pygame is not installed. Function used: pygame.init(): This command is used to initiate the pygame module. pygame.display.set_mode((500,500)): This command is used to make a window of desired size, (width, height). The return value is a Surface Object which is the object where we perform different graphical operations. pygame.display.set_caption(title = “”): This command is used to set the title of the window/ board. pygame.event.get(): This is used to empty the event queue. If we do not call this, the window messages will start to pile up and, the game will become unresponsive in the opinion of the operating system. pygame.QUIT: This is used to terminate the event when we click on the close button at the corner of the window. Python3 import pygame pygame.init() # CREATING CANVAScanvas = pygame.display.set_mode((500, 500)) # TITLE OF CANVASpygame.display.set_caption("My Board")exit = False while not exit: for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True pygame.display.update() Output: Blitting is the process of rendering the game object onto the surface. When we create the game object, we should render it. If we don’t render the game object, it will show the black window. In pygame there is a way to do this blitting process, i,e, blit(). It is one of the slowest operations in any game, so we need to be careful while using it as we shouldn’t blit much onto the screen in every frame. Syntax: blit(src, dest) src : It is the source of the image which we want to display on the screen dest : It is the coordinates where we want our image to be displayed. Code: Python3 import pygame pygame.init() color = (255,255,255)position = (0,0) # CREATING CANVAScanvas = pygame.display.set_mode((500,500)) # TITLE OF CANVASpygame.display.set_caption("Show Image") image = pygame.image.load("Screenshot.png")exit = False while not exit: canvas.fill(color) canvas.blit(image, dest = position) for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True pygame.display.update() Output: In Pygame we use rect() method to draw rectangle boxes on the window. Pygame uses Rect objects to store and manipulate rectangular areas. It can be formed by the combination of left, top, width, and height values. Python3 import pygame pygame.init() color = (255,255,255)rect_color = (255,0,0) # CREATING CANVAScanvas = pygame.display.set_mode((500,500)) # TITLE OF CANVASpygame.display.set_caption("Show Image") image = pygame.image.load("Screenshot.png")exit = False while not exit: canvas.fill(color) for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True pygame.draw.rect(canvas, rect_color, pygame.Rect(30,30,60,60)) pygame.display.update() Output : Picked Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 526, "s": 52, "text": "Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games. You can code the games and then use specific commands to change it into an executable file that you can share with your friends to show them the work you have been doing. It includes computer graphics and sound libraries designed to be used with the Python programming language. PyGame 2.0.1 is the latest version at the time of writing this article." }, { "code": null, "e": 700, "s": 526, "text": "By default, Python doesn’t come with PyGame as an in-built Library. So we have to install it using the command prompt. Open a command prompt and type the following command: " }, { "code": null, "e": 719, "s": 700, "text": "pip install pygame" }, { "code": null, "e": 805, "s": 719, "text": "If you already have PyGame installed, use the following command to check the version:" }, { "code": null, "e": 821, "s": 805, "text": "pip show pygame" }, { "code": null, "e": 901, "s": 821, "text": "If your Pygame is not updated to the latest version, use the following command:" }, { "code": null, "e": 930, "s": 901, "text": "pip install pygame --upgrade" }, { "code": null, "e": 1022, "s": 930, "text": "If this command shows a ModuleNotFoundError, then it is clear that pygame is not installed." }, { "code": null, "e": 1037, "s": 1022, "text": "Function used:" }, { "code": null, "e": 1104, "s": 1037, "text": "pygame.init(): This command is used to initiate the pygame module." }, { "code": null, "e": 1318, "s": 1104, "text": "pygame.display.set_mode((500,500)): This command is used to make a window of desired size, (width, height). The return value is a Surface Object which is the object where we perform different graphical operations." }, { "code": null, "e": 1418, "s": 1318, "text": "pygame.display.set_caption(title = “”): This command is used to set the title of the window/ board." }, { "code": null, "e": 1622, "s": 1418, "text": "pygame.event.get(): This is used to empty the event queue. If we do not call this, the window messages will start to pile up and, the game will become unresponsive in the opinion of the operating system." }, { "code": null, "e": 1734, "s": 1622, "text": "pygame.QUIT: This is used to terminate the event when we click on the close button at the corner of the window." }, { "code": null, "e": 1742, "s": 1734, "text": "Python3" }, { "code": "import pygame pygame.init() # CREATING CANVAScanvas = pygame.display.set_mode((500, 500)) # TITLE OF CANVASpygame.display.set_caption(\"My Board\")exit = False while not exit: for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True pygame.display.update()", "e": 2043, "s": 1742, "text": null }, { "code": null, "e": 2051, "s": 2043, "text": "Output:" }, { "code": null, "e": 2309, "s": 2051, "text": "Blitting is the process of rendering the game object onto the surface. When we create the game object, we should render it. If we don’t render the game object, it will show the black window. In pygame there is a way to do this blitting process, i,e, blit()." }, { "code": null, "e": 2456, "s": 2309, "text": "It is one of the slowest operations in any game, so we need to be careful while using it as we shouldn’t blit much onto the screen in every frame." }, { "code": null, "e": 2480, "s": 2456, "text": "Syntax: blit(src, dest)" }, { "code": null, "e": 2555, "s": 2480, "text": "src : It is the source of the image which we want to display on the screen" }, { "code": null, "e": 2625, "s": 2555, "text": "dest : It is the coordinates where we want our image to be displayed." }, { "code": null, "e": 2631, "s": 2625, "text": "Code:" }, { "code": null, "e": 2639, "s": 2631, "text": "Python3" }, { "code": "import pygame pygame.init() color = (255,255,255)position = (0,0) # CREATING CANVAScanvas = pygame.display.set_mode((500,500)) # TITLE OF CANVASpygame.display.set_caption(\"Show Image\") image = pygame.image.load(\"Screenshot.png\")exit = False while not exit: canvas.fill(color) canvas.blit(image, dest = position) for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True pygame.display.update()", "e": 3090, "s": 2639, "text": null }, { "code": null, "e": 3098, "s": 3090, "text": "Output:" }, { "code": null, "e": 3312, "s": 3098, "text": "In Pygame we use rect() method to draw rectangle boxes on the window. Pygame uses Rect objects to store and manipulate rectangular areas. It can be formed by the combination of left, top, width, and height values." }, { "code": null, "e": 3320, "s": 3312, "text": "Python3" }, { "code": "import pygame pygame.init() color = (255,255,255)rect_color = (255,0,0) # CREATING CANVAScanvas = pygame.display.set_mode((500,500)) # TITLE OF CANVASpygame.display.set_caption(\"Show Image\") image = pygame.image.load(\"Screenshot.png\")exit = False while not exit: canvas.fill(color) for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True pygame.draw.rect(canvas, rect_color, pygame.Rect(30,30,60,60)) pygame.display.update()", "e": 3822, "s": 3320, "text": null }, { "code": null, "e": 3831, "s": 3822, "text": "Output :" }, { "code": null, "e": 3838, "s": 3831, "text": "Picked" }, { "code": null, "e": 3852, "s": 3838, "text": "Python-PyGame" }, { "code": null, "e": 3859, "s": 3852, "text": "Python" }, { "code": null, "e": 3957, "s": 3859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3989, "s": 3957, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4016, "s": 3989, "text": "Python Classes and Objects" }, { "code": null, "e": 4047, "s": 4016, "text": "Python | os.path.join() method" }, { "code": null, "e": 4068, "s": 4047, "text": "Python OOPs Concepts" }, { "code": null, "e": 4124, "s": 4068, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4147, "s": 4124, "text": "Introduction To PYTHON" }, { "code": null, "e": 4189, "s": 4147, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4231, "s": 4189, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4270, "s": 4231, "text": "Python | datetime.timedelta() function" } ]
How to Upload a Project on Github?
08 Jul, 2022 A lot of students ask questions about open source. What is open source, how can I contribute to it? Is it helpful if I contribute to open source, and the list goes on relevant to “Open Source”. So what is open source??? According to opensource.com, The term “open-source” refers to something people can modify and share because its design is publicly accessible. The term originated in the context of software development to designate a specific approach to creating computer programs. Today, however, “open-source” designates a broader set of values — what we call “the open source way.” Open source projects, products, or initiatives embrace and celebrate principles of open exchange, collaborative participation, rapid prototyping, transparency, meritocracy, and community-oriented development. i.e., “open-source is what is free to access by all. Anyone can change and distribute its own model”. There are so many blogs available on the internet to learn about open source, software, and their importance. The most common and widely used platform to use for open source is Git and GitHub. The purpose of Git is to manage a project, or a set of files, as they change over time. Git stores this information in a data structure called a repository. A git repository contains, among other things, the following: A set of commit objects. GitHub is a Git repository hosting service, but it adds many of its own features. While Git is a command-line tool, GitHub provides a Web-based graphical interface. It also provides access control and several collaboration features, such as wikis and basic task management tools for every project. Let’s discuss some command used in git to push, pull, commit and do changes to your GitHub repository. First, install Git from the official site https://git-scm.com/downloads and install it in your PC then after creating your profile on Github https://github.com, make a repository and clone (copy the link of your repository) your repository with HTTPS. Now go to Git Bash software and use this command to clone this repository to your PC.git clone [your copy link] git clone [your copy link] Git Bash don’t use ctrl+V to paste any segment so paste your link by using shift+Ins key Now you have cloned your Github repository to your system now add all you relevant codes in that cloned directory to upload it to your GitHub Profile. Now when you will type command git status you will see all those files you have added to the directory in red-colored untracked file segment like this. Here laddu.txt is the unracked file that I have just moved to the directory. Now to add these files into staging area (Staging is a step before the commit process in git. That is, a commit in git is performed in two steps: staging and actually commit. As long as a changeset is in the staging area, git allows you to edit it as you like to replace staged files with other versions of staged files, remove changes from staging, etc.) use commandgit add <files_Name with their respective extensions> git add <files_Name with their respective extensions> Here you can see that now your files are successfully added to the staging area. Now you need to commit these files with a description. And to do so usegit commit -m “Your description” git commit -m “Your description” Now we have committed these changes in our local system and to upload these changes to our remote profile use commandgit remote -v git remote -v Great, Now just one step left this is to push these changes in our Github repository. Use the command below to upload your files or any changes.git push origin master git push origin master Great You have successfully uploaded your files to your GitHub repository. All the files and directories are uploaded to your Github account. Now you can manage, revert, access or do any changes in your repositories like this. Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Working on Git for GUI How to Set Git Username and Password in GitBash? Git - Difference Between Git Fetch and Git Pull How to Set Upstream Branch on Git? Difference Between Git Push Origin and Git Push Origin Master How to Push Git Branch to Remote? How to Undo a Commit in Git ? How to Export Eclipse projects to GitHub? What is a GIT Repository? How to Clone Android Project from GitHub in Android Studio?
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 248, "s": 54, "text": "A lot of students ask questions about open source. What is open source, how can I contribute to it? Is it helpful if I contribute to open source, and the list goes on relevant to “Open Source”." }, { "code": null, "e": 274, "s": 248, "text": "So what is open source???" }, { "code": null, "e": 417, "s": 274, "text": "According to opensource.com, The term “open-source” refers to something people can modify and share because its design is publicly accessible." }, { "code": null, "e": 954, "s": 417, "text": "The term originated in the context of software development to designate a specific approach to creating computer programs. Today, however, “open-source” designates a broader set of values — what we call “the open source way.” Open source projects, products, or initiatives embrace and celebrate principles of open exchange, collaborative participation, rapid prototyping, transparency, meritocracy, and community-oriented development. i.e., “open-source is what is free to access by all. Anyone can change and distribute its own model”." }, { "code": null, "e": 1147, "s": 954, "text": "There are so many blogs available on the internet to learn about open source, software, and their importance. The most common and widely used platform to use for open source is Git and GitHub." }, { "code": null, "e": 1391, "s": 1147, "text": "The purpose of Git is to manage a project, or a set of files, as they change over time. Git stores this information in a data structure called a repository. A git repository contains, among other things, the following: A set of commit objects." }, { "code": null, "e": 1689, "s": 1391, "text": "GitHub is a Git repository hosting service, but it adds many of its own features. While Git is a command-line tool, GitHub provides a Web-based graphical interface. It also provides access control and several collaboration features, such as wikis and basic task management tools for every project." }, { "code": null, "e": 1792, "s": 1689, "text": "Let’s discuss some command used in git to push, pull, commit and do changes to your GitHub repository." }, { "code": null, "e": 2044, "s": 1792, "text": "First, install Git from the official site https://git-scm.com/downloads and install it in your PC then after creating your profile on Github https://github.com, make a repository and clone (copy the link of your repository) your repository with HTTPS." }, { "code": null, "e": 2156, "s": 2044, "text": "Now go to Git Bash software and use this command to clone this repository to your PC.git clone [your copy link]" }, { "code": null, "e": 2183, "s": 2156, "text": "git clone [your copy link]" }, { "code": null, "e": 2272, "s": 2183, "text": "Git Bash don’t use ctrl+V to paste any segment so paste your link by using shift+Ins key" }, { "code": null, "e": 2423, "s": 2272, "text": "Now you have cloned your Github repository to your system now add all you relevant codes in that cloned directory to upload it to your GitHub Profile." }, { "code": null, "e": 2652, "s": 2423, "text": "Now when you will type command git status you will see all those files you have added to the directory in red-colored untracked file segment like this. Here laddu.txt is the unracked file that I have just moved to the directory." }, { "code": null, "e": 3073, "s": 2652, "text": "Now to add these files into staging area (Staging is a step before the commit process in git. That is, a commit in git is performed in two steps: staging and actually commit. As long as a changeset is in the staging area, git allows you to edit it as you like to replace staged files with other versions of staged files, remove changes from staging, etc.) use commandgit add <files_Name with their respective extensions>" }, { "code": null, "e": 3127, "s": 3073, "text": "git add <files_Name with their respective extensions>" }, { "code": null, "e": 3312, "s": 3127, "text": "Here you can see that now your files are successfully added to the staging area. Now you need to commit these files with a description. And to do so usegit commit -m “Your description”" }, { "code": null, "e": 3345, "s": 3312, "text": "git commit -m “Your description”" }, { "code": null, "e": 3476, "s": 3345, "text": "Now we have committed these changes in our local system and to upload these changes to our remote profile use commandgit remote -v" }, { "code": null, "e": 3490, "s": 3476, "text": "git remote -v" }, { "code": null, "e": 3657, "s": 3490, "text": "Great, Now just one step left this is to push these changes in our Github repository. Use the command below to upload your files or any changes.git push origin master" }, { "code": null, "e": 3680, "s": 3657, "text": "git push origin master" }, { "code": null, "e": 3755, "s": 3680, "text": "Great You have successfully uploaded your files to your GitHub repository." }, { "code": null, "e": 3907, "s": 3755, "text": "All the files and directories are uploaded to your Github account. Now you can manage, revert, access or do any changes in your repositories like this." }, { "code": null, "e": 3911, "s": 3907, "text": "Git" }, { "code": null, "e": 4009, "s": 3911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4032, "s": 4009, "text": "Working on Git for GUI" }, { "code": null, "e": 4081, "s": 4032, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 4129, "s": 4081, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 4164, "s": 4129, "text": "How to Set Upstream Branch on Git?" }, { "code": null, "e": 4226, "s": 4164, "text": "Difference Between Git Push Origin and Git Push Origin Master" }, { "code": null, "e": 4260, "s": 4226, "text": "How to Push Git Branch to Remote?" }, { "code": null, "e": 4290, "s": 4260, "text": "How to Undo a Commit in Git ?" }, { "code": null, "e": 4332, "s": 4290, "text": "How to Export Eclipse projects to GitHub?" }, { "code": null, "e": 4358, "s": 4332, "text": "What is a GIT Repository?" } ]
Java Program to Interchange Any Two Rows in the Matrix
11 Mar, 2022 Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required. Examples Input 1: K = 1, L = 2, mat[][] = {{2, 1, 4}, {1, 2, 3}, {3, 6, 2}} Output: mat[][] = {{1, 2, 3}, {2, 1, 4}, {3, 6, 2}} Input 2: K = 1, L = 1, mat[][] = {{2, 1, 4}, {1, 2, 3}} Output: mat[][] = {{2, 1, 4}, {1, 2, 3}} Input 3: K = 2, L = 3, mat[][] = {{2, 1}, {1, 2}, {3, 6}} Output: mat[][] = {{2, 1}, {3, 6}, {1, 2}} Approach If First and Second are same, then print the matrix as it is. Else Loop over the Kth and Lth row of the matrix. Swap the elements ith index of both the rows while traversal. Now after the loop gets over, print the matrix. Below is the code implementation for the above approach: Java // Java program to interchange// two row in a Matriximport java.io.*; class GFG { public static void printMatrix(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) System.out.print(matrix[i][j] + " "); System.out.println(); } } public static void exchangeAnyTwoRows(int[][] matrix, int K, int L) { int[] temp = matrix[K - 1]; matrix[K - 1]= matrix[L - 1]; matrix[L - 1] = temp; // Print matrix printMatrix(matrix); } public static void main(String[] args) { int K = 2, L = 3; int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } }; // calling the exchange row function exchangeAnyTwoRows(mat, K, L); }} 2 1 4 3 6 2 1 2 3 Time Complexity: 0(n), Where n is the length of the row. Space Complexity: 0(1) sagartomar9927 smrmngkmru Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java HashMap in Java with Examples ArrayList in Java Collections in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Mar, 2022" }, { "code": null, "e": 324, "s": 28, "text": "Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required." }, { "code": null, "e": 333, "s": 324, "text": "Examples" }, { "code": null, "e": 1073, "s": 333, "text": "Input 1: K = 1, L = 2,\n\n mat[][] = {{2, 1, 4},\n {1, 2, 3}, \n {3, 6, 2}}\n \nOutput: \n mat[][] = {{1, 2, 3},\n {2, 1, 4}, \n {3, 6, 2}}\n \n\nInput 2: K = 1, L = 1,\n mat[][] = {{2, 1, 4},\n {1, 2, 3}} \n \nOutput: \n mat[][] = {{2, 1, 4},\n {1, 2, 3}} \n \nInput 3: K = 2, L = 3,\n mat[][] = {{2, 1},\n {1, 2}, \n {3, 6}}\n \nOutput: \n mat[][] = {{2, 1},\n {3, 6}, \n {1, 2}}" }, { "code": null, "e": 1082, "s": 1073, "text": "Approach" }, { "code": null, "e": 1144, "s": 1082, "text": "If First and Second are same, then print the matrix as it is." }, { "code": null, "e": 1194, "s": 1144, "text": "Else Loop over the Kth and Lth row of the matrix." }, { "code": null, "e": 1256, "s": 1194, "text": "Swap the elements ith index of both the rows while traversal." }, { "code": null, "e": 1304, "s": 1256, "text": "Now after the loop gets over, print the matrix." }, { "code": null, "e": 1361, "s": 1304, "text": "Below is the code implementation for the above approach:" }, { "code": null, "e": 1366, "s": 1361, "text": "Java" }, { "code": "// Java program to interchange// two row in a Matriximport java.io.*; class GFG { public static void printMatrix(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) System.out.print(matrix[i][j] + \" \"); System.out.println(); } } public static void exchangeAnyTwoRows(int[][] matrix, int K, int L) { int[] temp = matrix[K - 1]; matrix[K - 1]= matrix[L - 1]; matrix[L - 1] = temp; // Print matrix printMatrix(matrix); } public static void main(String[] args) { int K = 2, L = 3; int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } }; // calling the exchange row function exchangeAnyTwoRows(mat, K, L); }}", "e": 2227, "s": 1366, "text": null }, { "code": null, "e": 2251, "s": 2230, "text": "2 1 4 \n3 6 2 \n1 2 3 " }, { "code": null, "e": 2310, "s": 2253, "text": "Time Complexity: 0(n), Where n is the length of the row." }, { "code": null, "e": 2335, "s": 2312, "text": "Space Complexity: 0(1)" }, { "code": null, "e": 2352, "s": 2337, "text": "sagartomar9927" }, { "code": null, "e": 2363, "s": 2352, "text": "smrmngkmru" }, { "code": null, "e": 2370, "s": 2363, "text": "Picked" }, { "code": null, "e": 2375, "s": 2370, "text": "Java" }, { "code": null, "e": 2389, "s": 2375, "text": "Java Programs" }, { "code": null, "e": 2394, "s": 2389, "text": "Java" }, { "code": null, "e": 2492, "s": 2394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2543, "s": 2492, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2574, "s": 2543, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2604, "s": 2574, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2622, "s": 2604, "text": "ArrayList in Java" }, { "code": null, "e": 2642, "s": 2622, "text": "Collections in Java" }, { "code": null, "e": 2670, "s": 2642, "text": "Initializing a List in Java" }, { "code": null, "e": 2696, "s": 2670, "text": "Java Programming Examples" }, { "code": null, "e": 2740, "s": 2696, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 2774, "s": 2740, "text": "Convert Double to Integer in Java" } ]
Overloading of function-call operator in C++
19 Apr, 2021 In this article, we will discuss the Overloading of the function-call operators in C++. The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object. When the function call operator is overloaded, an operator function is created that can be used to pass parameters. It modifies that how the operator is fetched by the object. In Object-Oriented Languages, operator() can be treated as a normal operator, and objects of a class type can call function (named operator()) like making a function call to any other overloaded operator. When the function call operator is overloaded, a new way to call a function is not created rather an operator() function is created that can be passed an arbitrary number of parameters. Program: Below is the program of taking input in a matrix using friend functions first to overload insertion operator and extraction operator and then overloading operator() for taking input for the ith row and the jth column of the matrix and displaying value at the ith row and the jth column stored in the matrix: C++ // C++ program to illustrate the// above concepts#include <bits/stdc++.h>#include <iostream>using namespace std;#define N 3#define M 3 // Matrix Classclass Matrix {private: int arr[N][M]; public: // Overloading of input stream friend istream& operator>>( istream&, Matrix&); // Overloading of output stream friend ostream& operator<<( ostream&, Matrix&); int& operator()(int, int);}; // Function to overload the input// ">>" operatoristream& operator>>(istream& cin, Matrix& m){ int x; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Overloading operator() // to take input cin >> m(i, j); } } return cin;} // Function to overload the output// "<<" operatorostream& operator<<(ostream& cout, Matrix& m){ for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Overloading operator() to // take input m.operator()(i, j); cout << m(i, j) << " "; } cout << endl; } return cout;} // Function to call the operator// function to overload the operatorsint& Matrix::operator()(int i, int j){ return arr[i][j];} // Driver Codeint main(){ Matrix m; printf("Input the matrix:\n"); // Compiler calls operator >> and // passes object cin and object m // as parameter operator>>(cin, m); cin >> m; printf("The matrix is:\n"); // Compiler calls operator << and // passes object cout and object m // as parameter operator<<(cin, m); cout << m; return 0;} Output: C++-Operator Overloading cpp-operator cpp-operator-overloading C++ C++ Programs cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2021" }, { "code": null, "e": 116, "s": 28, "text": "In this article, we will discuss the Overloading of the function-call operators in C++." }, { "code": null, "e": 288, "s": 116, "text": "The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object." }, { "code": null, "e": 404, "s": 288, "text": "When the function call operator is overloaded, an operator function is created that can be used to pass parameters." }, { "code": null, "e": 464, "s": 404, "text": "It modifies that how the operator is fetched by the object." }, { "code": null, "e": 669, "s": 464, "text": "In Object-Oriented Languages, operator() can be treated as a normal operator, and objects of a class type can call function (named operator()) like making a function call to any other overloaded operator." }, { "code": null, "e": 855, "s": 669, "text": "When the function call operator is overloaded, a new way to call a function is not created rather an operator() function is created that can be passed an arbitrary number of parameters." }, { "code": null, "e": 864, "s": 855, "text": "Program:" }, { "code": null, "e": 1172, "s": 864, "text": "Below is the program of taking input in a matrix using friend functions first to overload insertion operator and extraction operator and then overloading operator() for taking input for the ith row and the jth column of the matrix and displaying value at the ith row and the jth column stored in the matrix:" }, { "code": null, "e": 1176, "s": 1172, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <bits/stdc++.h>#include <iostream>using namespace std;#define N 3#define M 3 // Matrix Classclass Matrix {private: int arr[N][M]; public: // Overloading of input stream friend istream& operator>>( istream&, Matrix&); // Overloading of output stream friend ostream& operator<<( ostream&, Matrix&); int& operator()(int, int);}; // Function to overload the input// \">>\" operatoristream& operator>>(istream& cin, Matrix& m){ int x; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Overloading operator() // to take input cin >> m(i, j); } } return cin;} // Function to overload the output// \"<<\" operatorostream& operator<<(ostream& cout, Matrix& m){ for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Overloading operator() to // take input m.operator()(i, j); cout << m(i, j) << \" \"; } cout << endl; } return cout;} // Function to call the operator// function to overload the operatorsint& Matrix::operator()(int i, int j){ return arr[i][j];} // Driver Codeint main(){ Matrix m; printf(\"Input the matrix:\\n\"); // Compiler calls operator >> and // passes object cin and object m // as parameter operator>>(cin, m); cin >> m; printf(\"The matrix is:\\n\"); // Compiler calls operator << and // passes object cout and object m // as parameter operator<<(cin, m); cout << m; return 0;}", "e": 2786, "s": 1176, "text": null }, { "code": null, "e": 2794, "s": 2786, "text": "Output:" }, { "code": null, "e": 2819, "s": 2794, "text": "C++-Operator Overloading" }, { "code": null, "e": 2832, "s": 2819, "text": "cpp-operator" }, { "code": null, "e": 2857, "s": 2832, "text": "cpp-operator-overloading" }, { "code": null, "e": 2861, "s": 2857, "text": "C++" }, { "code": null, "e": 2874, "s": 2861, "text": "C++ Programs" }, { "code": null, "e": 2887, "s": 2874, "text": "cpp-operator" }, { "code": null, "e": 2891, "s": 2887, "text": "CPP" } ]
Python Tkinter – SpinBox
26 Mar, 2020 Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task. Note: For more information, refer to Python GUI – tkinter The Spinbox widget is used to select from a fixed number of values. It is an alternative Entry widget and provides the range of values to the user. Syntax:The syntax to use the Spinbox is given below. w = Spinbox ( master, options) Parameters: master: This parameter is used to represents the parent window. options:There are many options which are available and they can be used as key-value pairs separated by commas. Options:Following are commonly used Option can be used with this widget :- activebackground: This option used to represent the background color when the slider and arrowheads is under the cursor. bg: This option used to represent the normal background color displayed behind the label and indicator. bd: This option used to represent the size of the border around the indicator and the default value is 2 pixels. command: This option is associated with a function to be called when the state is changed. cursor: By using this option, the mouse cursor will change to that pattern when it is over the type. disabledforeground: This option used to represent the foreground color of the widget when it is disabled.. disabledbackground: This option used to represent the background color of the widget when it is disabled.. font: This option used to represent the font used for the text. fg: This option used to represent the color used to render the text. format: This option used to formatting the string and it’s has no default value. from_: This option used to represent the minimum value. justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT. relief: This option used to represent the type of the border and It’s default value is set to SUNKEN. repeatdelay: This option is used to control the button auto repeat and its default value is in milliseconds. repeatinterval: This option is similar to repeatdelay. state: This option used to represent the represents the state of the widget and its default value is NORMAL. textvariable: This option used to control the behaviour of the widget text. to: It specify the maximum limit of the widget value. The other is specified by the from_ option. validate: This option is used to control how the widget value is validated. validatecommand: This option is associated to the function callback which is used for the validation of the widget content. values: This option used to represent the tuple containing the values for this widget. vcmd: This option is same as validation command. width: This option is used to represents the width of the widget. wrap: This option wraps up the up and down button the Spinbox. xscrollcommand: This options is set to the set() method of scrollbar to make this widget horizontally scrollable. Methods:Methods used in this widgets are as follows: delete(startindex, endindex): This method is used to delete the characters present at the specified range. get(startindex, endindex): This method is used to get the characters present in the specified range. identify(x, y): This method is used to identify the widget’s element within the specified range. index(index): This method is used to get the absolute value of the given index. insert(index, string): This method is used to insert the string at the specified index. invoke(element): This method is used to invoke the callback associated with the widget. Example: from tkinter import * root = Tk()root.geometry("300x200") w = Label(root, text ='GeeksForGeeks', font = "50") w.pack() sp = Spinbox(root, from_= 0, to = 20)sp.pack() root.mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Mar, 2020" }, { "code": null, "e": 408, "s": 54, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task." }, { "code": null, "e": 466, "s": 408, "text": "Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 614, "s": 466, "text": "The Spinbox widget is used to select from a fixed number of values. It is an alternative Entry widget and provides the range of values to the user." }, { "code": null, "e": 667, "s": 614, "text": "Syntax:The syntax to use the Spinbox is given below." }, { "code": null, "e": 698, "s": 667, "text": "w = Spinbox ( master, options)" }, { "code": null, "e": 710, "s": 698, "text": "Parameters:" }, { "code": null, "e": 774, "s": 710, "text": "master: This parameter is used to represents the parent window." }, { "code": null, "e": 886, "s": 774, "text": "options:There are many options which are available and they can be used as key-value pairs separated by commas." }, { "code": null, "e": 961, "s": 886, "text": "Options:Following are commonly used Option can be used with this widget :-" }, { "code": null, "e": 1082, "s": 961, "text": "activebackground: This option used to represent the background color when the slider and arrowheads is under the cursor." }, { "code": null, "e": 1186, "s": 1082, "text": "bg: This option used to represent the normal background color displayed behind the label and indicator." }, { "code": null, "e": 1299, "s": 1186, "text": "bd: This option used to represent the size of the border around the indicator and the default value is 2 pixels." }, { "code": null, "e": 1390, "s": 1299, "text": "command: This option is associated with a function to be called when the state is changed." }, { "code": null, "e": 1491, "s": 1390, "text": "cursor: By using this option, the mouse cursor will change to that pattern when it is over the type." }, { "code": null, "e": 1598, "s": 1491, "text": "disabledforeground: This option used to represent the foreground color of the widget when it is disabled.." }, { "code": null, "e": 1705, "s": 1598, "text": "disabledbackground: This option used to represent the background color of the widget when it is disabled.." }, { "code": null, "e": 1769, "s": 1705, "text": "font: This option used to represent the font used for the text." }, { "code": null, "e": 1838, "s": 1769, "text": "fg: This option used to represent the color used to render the text." }, { "code": null, "e": 1919, "s": 1838, "text": "format: This option used to formatting the string and it’s has no default value." }, { "code": null, "e": 1975, "s": 1919, "text": "from_: This option used to represent the minimum value." }, { "code": null, "e": 2063, "s": 1975, "text": "justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT." }, { "code": null, "e": 2165, "s": 2063, "text": "relief: This option used to represent the type of the border and It’s default value is set to SUNKEN." }, { "code": null, "e": 2274, "s": 2165, "text": "repeatdelay: This option is used to control the button auto repeat and its default value is in milliseconds." }, { "code": null, "e": 2329, "s": 2274, "text": "repeatinterval: This option is similar to repeatdelay." }, { "code": null, "e": 2438, "s": 2329, "text": "state: This option used to represent the represents the state of the widget and its default value is NORMAL." }, { "code": null, "e": 2514, "s": 2438, "text": "textvariable: This option used to control the behaviour of the widget text." }, { "code": null, "e": 2612, "s": 2514, "text": "to: It specify the maximum limit of the widget value. The other is specified by the from_ option." }, { "code": null, "e": 2688, "s": 2612, "text": "validate: This option is used to control how the widget value is validated." }, { "code": null, "e": 2812, "s": 2688, "text": "validatecommand: This option is associated to the function callback which is used for the validation of the widget content." }, { "code": null, "e": 2899, "s": 2812, "text": "values: This option used to represent the tuple containing the values for this widget." }, { "code": null, "e": 2948, "s": 2899, "text": "vcmd: This option is same as validation command." }, { "code": null, "e": 3014, "s": 2948, "text": "width: This option is used to represents the width of the widget." }, { "code": null, "e": 3077, "s": 3014, "text": "wrap: This option wraps up the up and down button the Spinbox." }, { "code": null, "e": 3191, "s": 3077, "text": "xscrollcommand: This options is set to the set() method of scrollbar to make this widget horizontally scrollable." }, { "code": null, "e": 3244, "s": 3191, "text": "Methods:Methods used in this widgets are as follows:" }, { "code": null, "e": 3351, "s": 3244, "text": "delete(startindex, endindex): This method is used to delete the characters present at the specified range." }, { "code": null, "e": 3452, "s": 3351, "text": "get(startindex, endindex): This method is used to get the characters present in the specified range." }, { "code": null, "e": 3549, "s": 3452, "text": "identify(x, y): This method is used to identify the widget’s element within the specified range." }, { "code": null, "e": 3629, "s": 3549, "text": "index(index): This method is used to get the absolute value of the given index." }, { "code": null, "e": 3717, "s": 3629, "text": "insert(index, string): This method is used to insert the string at the specified index." }, { "code": null, "e": 3805, "s": 3717, "text": "invoke(element): This method is used to invoke the callback associated with the widget." }, { "code": null, "e": 3814, "s": 3805, "text": "Example:" }, { "code": "from tkinter import * root = Tk()root.geometry(\"300x200\") w = Label(root, text ='GeeksForGeeks', font = \"50\") w.pack() sp = Spinbox(root, from_= 0, to = 20)sp.pack() root.mainloop() ", "e": 4001, "s": 3814, "text": null }, { "code": null, "e": 4009, "s": 4001, "text": "Output:" }, { "code": null, "e": 4024, "s": 4009, "text": "Python-tkinter" }, { "code": null, "e": 4031, "s": 4024, "text": "Python" }, { "code": null, "e": 4129, "s": 4031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4157, "s": 4129, "text": "Read JSON file using Python" }, { "code": null, "e": 4179, "s": 4157, "text": "Python map() function" }, { "code": null, "e": 4229, "s": 4179, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4273, "s": 4229, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 4315, "s": 4273, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4337, "s": 4315, "text": "Enumerate() in Python" }, { "code": null, "e": 4372, "s": 4337, "text": "Read a file line by line in Python" }, { "code": null, "e": 4398, "s": 4372, "text": "Python String | replace()" }, { "code": null, "e": 4430, "s": 4398, "text": "How to Install PIP on Windows ?" } ]
Java Program for Difference between sums of odd and even digits
05 Dec, 2018 Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit). Examples: Input : 1212112 Output : Yes Explanation:- the odd position element is 2+2+1=5 the even position element is 1+1+1+2=5 the difference is 5-5=0.so print yes. Input :12345 Output : No Explanation:- the odd position element is 1+3+5=9 the even position element is 2+4=6 the difference is 9-6=3 not equal to zero. So print no. Method 1: One by one traverse digits and find the two sums. If difference between two sums is 0, print yes, else no. Method 2 : This can be easily solved using divisibility of 11. This condition is only satisfied if the number is divisible by 11. So check the number is divisible by 11 or not. // Java program to check if difference between sum of// odd digits and sum of even digits is 0 or not import java.io.*;import java.util.*; class GFG { public static boolean isDiff(int n) { return (n % 11 == 0); } public static void main(String[] args) { int n = 1243; if (isDiff(n)) System.out.print("Yes"); else System.out.print("No"); }} Yes Please refer complete article on Difference between sums of odd and even digits for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java Java Program to Convert File to a Byte Array SHA-1 Hash Java Program to Find Sum of Array Elements
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2018" }, { "code": null, "e": 207, "s": 28, "text": "Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit)." }, { "code": null, "e": 217, "s": 207, "text": "Examples:" }, { "code": null, "e": 542, "s": 217, "text": "Input : 1212112\nOutput : Yes\nExplanation:-\nthe odd position element is 2+2+1=5\nthe even position element is 1+1+1+2=5\nthe difference is 5-5=0.so print yes.\n\nInput :12345\nOutput : No\nExplanation:-\nthe odd position element is 1+3+5=9\nthe even position element is 2+4=6\nthe difference is 9-6=3 not equal\nto zero. So print no.\n" }, { "code": null, "e": 659, "s": 542, "text": "Method 1: One by one traverse digits and find the two sums. If difference between two sums is 0, print yes, else no." }, { "code": null, "e": 836, "s": 659, "text": "Method 2 : This can be easily solved using divisibility of 11. This condition is only satisfied if the number is divisible by 11. So check the number is divisible by 11 or not." }, { "code": "// Java program to check if difference between sum of// odd digits and sum of even digits is 0 or not import java.io.*;import java.util.*; class GFG { public static boolean isDiff(int n) { return (n % 11 == 0); } public static void main(String[] args) { int n = 1243; if (isDiff(n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}", "e": 1246, "s": 836, "text": null }, { "code": null, "e": 1251, "s": 1246, "text": "Yes\n" }, { "code": null, "e": 1349, "s": 1251, "text": "Please refer complete article on Difference between sums of odd and even digits for more details!" }, { "code": null, "e": 1363, "s": 1349, "text": "Java Programs" }, { "code": null, "e": 1461, "s": 1363, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1509, "s": 1461, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 1548, "s": 1509, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 1599, "s": 1548, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 1633, "s": 1599, "text": "Java Program to Write into a File" }, { "code": null, "e": 1680, "s": 1633, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 1718, "s": 1680, "text": "Java Program to Read a File to String" }, { "code": null, "e": 1750, "s": 1718, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 1795, "s": 1750, "text": "Java Program to Convert File to a Byte Array" }, { "code": null, "e": 1806, "s": 1795, "text": "SHA-1 Hash" } ]
How to get elements of specific class inside a div ?
09 Apr, 2021 In this article, we will find how to get all elements of a specific class inside an HTML div tag. To do this we will use HTML DOM querySelectorAll()method. This method of HTML DOM (document object model) returns all elements in the document that matches a specified CSS selector(s). The syntax to use this method is as follows. Syntax: document.querySelectorAll(CSS-selectors) Example: The CSS selectors would be class, ids, or any HTML tags. Let us learn how to use this method to select elements of a specific class inside an HTML div tag. HTML <!DOCTYPE html><html> <head> <style> #tag { border: 4px solid black; margin: 5px; } </style> </head> <body> <div id="tag"> <p class="example1">HTML</p> <p class="example1">CSS</p> <p class="example1">Javascript</p> <p class="example2">C</p> </div> <br /> <button onclick="changecolor()"> click to Apply change </button> <script> function changecolor() { var x = document.getElementById("tag") .querySelectorAll(".example1"); for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "blue"; } } </script> </body></html> Output:After clicking the “click to Apply change” button, we get the following output. We can see that by selecting a div using getElementById() and then selecting all its elements inside the div using querySelectorAll(), we can apply changes to all its elements. HTML-DOM Picked HTML Web Technologies HTML 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? REST API (Introduction) Hide or show elements in HTML using display property 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": "\n09 Apr, 2021" }, { "code": null, "e": 126, "s": 28, "text": "In this article, we will find how to get all elements of a specific class inside an HTML div tag." }, { "code": null, "e": 356, "s": 126, "text": "To do this we will use HTML DOM querySelectorAll()method. This method of HTML DOM (document object model) returns all elements in the document that matches a specified CSS selector(s). The syntax to use this method is as follows." }, { "code": null, "e": 364, "s": 356, "text": "Syntax:" }, { "code": null, "e": 405, "s": 364, "text": "document.querySelectorAll(CSS-selectors)" }, { "code": null, "e": 570, "s": 405, "text": "Example: The CSS selectors would be class, ids, or any HTML tags. Let us learn how to use this method to select elements of a specific class inside an HTML div tag." }, { "code": null, "e": 575, "s": 570, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> #tag { border: 4px solid black; margin: 5px; } </style> </head> <body> <div id=\"tag\"> <p class=\"example1\">HTML</p> <p class=\"example1\">CSS</p> <p class=\"example1\">Javascript</p> <p class=\"example2\">C</p> </div> <br /> <button onclick=\"changecolor()\"> click to Apply change </button> <script> function changecolor() { var x = document.getElementById(\"tag\") .querySelectorAll(\".example1\"); for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = \"blue\"; } } </script> </body></html>", "e": 1242, "s": 575, "text": null }, { "code": null, "e": 1506, "s": 1242, "text": "Output:After clicking the “click to Apply change” button, we get the following output. We can see that by selecting a div using getElementById() and then selecting all its elements inside the div using querySelectorAll(), we can apply changes to all its elements." }, { "code": null, "e": 1515, "s": 1506, "text": "HTML-DOM" }, { "code": null, "e": 1522, "s": 1515, "text": "Picked" }, { "code": null, "e": 1527, "s": 1522, "text": "HTML" }, { "code": null, "e": 1544, "s": 1527, "text": "Web Technologies" }, { "code": null, "e": 1549, "s": 1544, "text": "HTML" }, { "code": null, "e": 1647, "s": 1549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1695, "s": 1647, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1757, "s": 1695, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1807, "s": 1757, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1831, "s": 1807, "text": "REST API (Introduction)" }, { "code": null, "e": 1884, "s": 1831, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1917, "s": 1884, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1979, "s": 1917, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2040, "s": 1979, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2090, "s": 2040, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to display logged in user information in PHP ?
24 Nov, 2021 In social networking websites like Facebook, Instagram, etc, the username and profile picture of the user that has logged in gets displayed in the header of the website, and that header remains constant, irrespective of the webpage the user has opened. Such functionality can be created by using the session variables. Session variables exist only while the user’s session is active. After the session is complete, the session variables get destroyed. These are unique for each visitor and are generally used to store user-specific information such as the username, profile picture etc, once the user logs in. The session variables are used to display logged in user information in PHP.Project Explanation and Code: This is a simple registration system. The register.php page asks for the desired username, email, and password of the user, and then sends the entered data into the database, once the submit button is clicked. After this, the user is redirected to the index.php page where a welcome message and the username of the logged-in user is displayed.The first step is to create a database, and then a table inside it. The database is named ‘registration’, and the table is named ‘users’. The ‘users’ table will contain 4 fields. id – primary key – auto incrementusername – varchar(100)email – varchar(100)password – varchar(100)The ‘id’ will be the primary key, it means that it will be unique for every registered user. It will also auto-increment for every new registration. The data type for username, email and password will be varchar. The size can be adjusted as per the requirement however, 100 is sufficient.SQL code for the table: id – primary key – auto increment username – varchar(100) email – varchar(100) password – varchar(100)The ‘id’ will be the primary key, it means that it will be unique for every registered user. It will also auto-increment for every new registration. The data type for username, email and password will be varchar. The size can be adjusted as per the requirement however, 100 is sufficient.SQL code for the table: sql CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL) phpMyAdmin after the database and table creation Project folder, containing the necessary files html <?php if (count($errors) > 0) : ?> <div class="error"> <?php foreach ($errors as $error) : ?> <p><?php echo $error ?></p> <?php endforeach ?> </div><?php endif ?> Explanation: The error.php file is responsible for holding the error messages of the system. Suppose the user enters the wrong username and password combination, then in such cases, the error messages will be stored in the $error variable, which will then be displayed to the user using ‘echo; function of PHP.server.php php <?php // Starting the session, necessary// for using session variablessession_start(); // Declaring and hoisting the variables$username = "";$email = "";$errors = array();$_SESSION['success'] = ""; // DBMS connection code -> hostname,// username, password, database name$db = mysqli_connect('localhost', 'root', '', 'registration'); // Registration codeif (isset($_POST['reg_user'])) { // Receiving the values entered and storing // in the variables // Data sanitization is done to prevent // SQL injections $username = mysqli_real_escape_string($db, $_POST['username']); $email = mysqli_real_escape_string($db, $_POST['email']); $password_1 = mysqli_real_escape_string($db, $_POST['password_1']); $password_2 = mysqli_real_escape_string($db, $_POST['password_2']); // Ensuring that the user has not left any input field blank // error messages will be displayed for every blank input if (empty($username)) { array_push($errors, "Username is required"); } if (empty($email)) { array_push($errors, "Email is required"); } if (empty($password_1)) { array_push($errors, "Password is required"); } if ($password_1 != $password_2) { array_push($errors, "The two passwords do not match"); // Checking if the passwords match } // If the form is error free, then register the user if (count($errors) == 0) { // Password encryption to increase data security $password = md5($password_1); // Inserting data into table $query = "INSERT INTO users (username, email, password) VALUES('$username', '$email', '$password')"; mysqli_query($db, $query); // Storing username of the logged in user, // in the session variable $_SESSION['username'] = $username; // Welcome message $_SESSION['success'] = "You have logged in"; // Page on which the user will be // redirected after logging in header('location: index.php'); }} // User loginif (isset($_POST['login_user'])) { // Data sanitization to prevent SQL injection $username = mysqli_real_escape_string($db, $_POST['username']); $password = mysqli_real_escape_string($db, $_POST['password']); // Error message if the input field is left blank if (empty($username)) { array_push($errors, "Username is required"); } if (empty($password)) { array_push($errors, "Password is required"); } // Checking for the errors if (count($errors) == 0) { // Password matching $password = md5($password); $query = "SELECT * FROM users WHERE username= '$username' AND password='$password'"; $results = mysqli_query($db, $query); // $results = 1 means that one user with the // entered username exists if (mysqli_num_rows($results) == 1) { // Storing username in session variable $_SESSION['username'] = $username; // Welcome message $_SESSION['success'] = "You have logged in!"; // Page on which the user is sent // to after logging in header('location: index.php'); } else { // If the username and password doesn't match array_push($errors, "Username or password incorrect"); } }} ?> Explanation: The session is started using session_start() method. After that, the variables are declared and an error array is created. It will store all the error messages. The server.php page is then connected to the ‘registration’ database created earlier. After the user clicks the ‘register’ button on the register.php button, the data entered is sent to the database, and this completes a new registration. However, form validation is done before that to make sure that the user is filling the form correctly. All the fields are required and cannot be left blank.Line 18 – 21: mysqli_real_escape_string escapes the special characters before sending the data to the database. This is essential for database security from SQL injections.Line 25 – 27: These lines makes sure that the user is filling all the input boxes, and whether the ‘password’ and ‘confirm password’ matches. If both the password matches, then the code further runs.Line 29 – 32: Checking whether the password matches or not. Line 35 – 46: If the number of errors until this point is zero, the password is then ‘md5’ encrypted and the data entered is sent to the database. After the registration process is complete, the username is stored in the session variable, and the user is redirected to the index.php page, where he is asked to enter the login credentials.Line 50 – 80: First the username and password entered in sanitized. This is essential to increase database security, as it eliminates the chances of any SQL injection. The user gets an error message if the username or the password field is left blank. If the number of errors until this point of code is found to be 0, then a database check is run. If the username entered by the user is found to be present in the database, then the user successfully logs in. The user is then redirected to the ‘index.php’ page.login.php html <?php include('server.php') ?><!DOCTYPE html><html><head> <title> Login and Registration System - LAMP Stack </title> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <div class="header"> <h2>Login Here!</h2> </div> <form method="post" action="login.php"> <?php include('errors.php'); ?> <div class="input-group"> <label>Enter Username</label> <input type="text" name="username" > </div> <div class="input-group"> <label>Enter Password</label> <input type="password" name="password"> </div> <div class="input-group"> <button type="submit" class="btn" name="login_user"> Login </button> </div> <p> New Here? <a href="register.php"> Click here to register! </a> </p> </form></body> </html> Explanation: Login page of the system. The user has to enter the username and password to successfully log in. After the login button is pressed, the login code written in the server.php page is run, which does all the backend work, like checking whether the username and password match or not.register.php php <?php include('server.php') ?><!DOCTYPE html><html><head> <title> Registration system PHP and MySQL </title> <link rel="stylesheet" type="text/css" href="style.css"></head> <body> <div class="header"> <h2>Register</h2> </div> <form method="post" action="register.php"> <?php include('errors.php'); ?> <div class="input-group"> <label>Enter Username</label> <input type="text" name="username" value="<?php echo $username; ?>"> </div> <div class="input-group"> <label>Email</label> <input type="email" name="email" value="<?php echo $email; ?>"> </div> <div class="input-group"> <label>Enter Password</label> <input type="password" name="password_1"> </div> <div class="input-group"> <label>Confirm password</label> <input type="password" name="password_2"> </div> <div class="input-group"> <button type="submit" class="btn" name="reg_user"> Register </button> </div> <p> Already having an account? <a href="login.php"> Login Here! </a> </p> </form></body></html> Explanation: This page contains the HTML coding of the registration page. The ‘server.php’, and ‘errors.php’ pages are included in lines 01 and 15 respectively. This is necessary to make the backend of the registration system work. The user is asked to enter the username, email, and password to create an account. After the input fields are filled, the data entered is sent to the database table.index.php html <?php // Starting the session, to use and// store data in session variablesession_start(); // If the session variable is empty, this// means the user is yet to login// User will be sent to 'login.php' page// to allow the user to loginif (!isset($_SESSION['username'])) { $_SESSION['msg'] = "You have to log in first"; header('location: login.php');} // Logout button will destroy the session, and// will unset the session variables// User will be headed to 'login.php'// after logging outif (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['username']); header("location: login.php");}?><!DOCTYPE html><html><head> <title>Homepage</title> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <div class="header"> <h2>Home Page</h2> </div> <div class="content"> <!-- Creating notification when the user logs in --> <!-- Accessible only to the users that have logged in already --> <?php if (isset($_SESSION['success'])) : ?> <div class="error success" > <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?> </h3> </div> <?php endif ?> <!-- information of the user logged in --> <!-- welcome message for the logged in user --> <?php if (isset($_SESSION['username'])) : ?> <p> Welcome <strong> <?php echo $_SESSION['username']; ?> </strong> </p> <p> <a href="index.php?logout='1'" style="color: red;"> Click here to Logout </a> </p> <?php endif ?> </div></body></html> Explanation: Line 01 – 19: The username that was stored in the session variable is now displayed back to the user. This session variable can either be destroyed using unset($_SESSION[“products”]) or session_destroy(). However, session_destroy() will destroy all the session variables at once. To destroy only the ‘username’ session variable, it will be better to unset the variable using unset($_SESSION[“products”]).Line 34 – 42: This makes sure that this page is accessible only to those users that are logged in.Line 45 – 50: This displays a personalized welcome message to the user once they log in.CSS File CSS * { margin: 0px; padding: 0px;}body { font-size: 120%; background: #F8F8FF;} .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px;}form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px;}.input-group { margin: 10px 10px 10px 10px;} .input-group label { display: block; text-align: left; margin: 5px; font-size: 20px;}.input-group input { height: 32px; width: 95%; padding: 5px 10px; font-size: 15px; border-radius: 10px; border: 1px solid gray;}.btn { cursor: pointer; padding: 12px; font-size: 16px; color: white; background: #23585a; border: none; border-radius: 10px;}.error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left;}.success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px;} Pictorial Representation: Registration Page User is redirected to this page after logging in. A welcome message is displayed there. Login page of the system User has successfully logged in Incorrect username and password combination The source codes of this project can be obtained from this GitHub repository.After downloading and unzipping the project, follow the given steps to run the program: Download all the files, or clone the repository into your local system. Create a database named ‘registration’, and a table named ‘users’. The MySQL code of the table has been provided above. Use XAMP or WAMP to run the system on localhost. Make sure that the necessary ports to run Apache and MySQL server are free. If not, then you will have to change the port numbers. HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. arorakashish0911 kalrap615 sagar0719kumar HTML-Misc PHP-basics Picked HTML PHP Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Nov, 2021" }, { "code": null, "e": 1293, "s": 54, "text": "In social networking websites like Facebook, Instagram, etc, the username and profile picture of the user that has logged in gets displayed in the header of the website, and that header remains constant, irrespective of the webpage the user has opened. Such functionality can be created by using the session variables. Session variables exist only while the user’s session is active. After the session is complete, the session variables get destroyed. These are unique for each visitor and are generally used to store user-specific information such as the username, profile picture etc, once the user logs in. The session variables are used to display logged in user information in PHP.Project Explanation and Code: This is a simple registration system. The register.php page asks for the desired username, email, and password of the user, and then sends the entered data into the database, once the submit button is clicked. After this, the user is redirected to the index.php page where a welcome message and the username of the logged-in user is displayed.The first step is to create a database, and then a table inside it. The database is named ‘registration’, and the table is named ‘users’. The ‘users’ table will contain 4 fields. " }, { "code": null, "e": 1706, "s": 1293, "text": "id – primary key – auto incrementusername – varchar(100)email – varchar(100)password – varchar(100)The ‘id’ will be the primary key, it means that it will be unique for every registered user. It will also auto-increment for every new registration. The data type for username, email and password will be varchar. The size can be adjusted as per the requirement however, 100 is sufficient.SQL code for the table: " }, { "code": null, "e": 1740, "s": 1706, "text": "id – primary key – auto increment" }, { "code": null, "e": 1764, "s": 1740, "text": "username – varchar(100)" }, { "code": null, "e": 1785, "s": 1764, "text": "email – varchar(100)" }, { "code": null, "e": 2122, "s": 1785, "text": "password – varchar(100)The ‘id’ will be the primary key, it means that it will be unique for every registered user. It will also auto-increment for every new registration. The data type for username, email and password will be varchar. The size can be adjusted as per the requirement however, 100 is sufficient.SQL code for the table: " }, { "code": null, "e": 2126, "s": 2122, "text": "sql" }, { "code": "CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL)", "e": 2310, "s": 2126, "text": null }, { "code": null, "e": 2359, "s": 2310, "text": "phpMyAdmin after the database and table creation" }, { "code": null, "e": 2406, "s": 2359, "text": "Project folder, containing the necessary files" }, { "code": null, "e": 2411, "s": 2406, "text": "html" }, { "code": "<?php if (count($errors) > 0) : ?> <div class=\"error\"> <?php foreach ($errors as $error) : ?> <p><?php echo $error ?></p> <?php endforeach ?> </div><?php endif ?>", "e": 2609, "s": 2411, "text": null }, { "code": null, "e": 2931, "s": 2609, "text": "Explanation: The error.php file is responsible for holding the error messages of the system. Suppose the user enters the wrong username and password combination, then in such cases, the error messages will be stored in the $error variable, which will then be displayed to the user using ‘echo; function of PHP.server.php " }, { "code": null, "e": 2935, "s": 2931, "text": "php" }, { "code": "<?php // Starting the session, necessary// for using session variablessession_start(); // Declaring and hoisting the variables$username = \"\";$email = \"\";$errors = array();$_SESSION['success'] = \"\"; // DBMS connection code -> hostname,// username, password, database name$db = mysqli_connect('localhost', 'root', '', 'registration'); // Registration codeif (isset($_POST['reg_user'])) { // Receiving the values entered and storing // in the variables // Data sanitization is done to prevent // SQL injections $username = mysqli_real_escape_string($db, $_POST['username']); $email = mysqli_real_escape_string($db, $_POST['email']); $password_1 = mysqli_real_escape_string($db, $_POST['password_1']); $password_2 = mysqli_real_escape_string($db, $_POST['password_2']); // Ensuring that the user has not left any input field blank // error messages will be displayed for every blank input if (empty($username)) { array_push($errors, \"Username is required\"); } if (empty($email)) { array_push($errors, \"Email is required\"); } if (empty($password_1)) { array_push($errors, \"Password is required\"); } if ($password_1 != $password_2) { array_push($errors, \"The two passwords do not match\"); // Checking if the passwords match } // If the form is error free, then register the user if (count($errors) == 0) { // Password encryption to increase data security $password = md5($password_1); // Inserting data into table $query = \"INSERT INTO users (username, email, password) VALUES('$username', '$email', '$password')\"; mysqli_query($db, $query); // Storing username of the logged in user, // in the session variable $_SESSION['username'] = $username; // Welcome message $_SESSION['success'] = \"You have logged in\"; // Page on which the user will be // redirected after logging in header('location: index.php'); }} // User loginif (isset($_POST['login_user'])) { // Data sanitization to prevent SQL injection $username = mysqli_real_escape_string($db, $_POST['username']); $password = mysqli_real_escape_string($db, $_POST['password']); // Error message if the input field is left blank if (empty($username)) { array_push($errors, \"Username is required\"); } if (empty($password)) { array_push($errors, \"Password is required\"); } // Checking for the errors if (count($errors) == 0) { // Password matching $password = md5($password); $query = \"SELECT * FROM users WHERE username= '$username' AND password='$password'\"; $results = mysqli_query($db, $query); // $results = 1 means that one user with the // entered username exists if (mysqli_num_rows($results) == 1) { // Storing username in session variable $_SESSION['username'] = $username; // Welcome message $_SESSION['success'] = \"You have logged in!\"; // Page on which the user is sent // to after logging in header('location: index.php'); } else { // If the username and password doesn't match array_push($errors, \"Username or password incorrect\"); } }} ?>", "e": 6386, "s": 2935, "text": null }, { "code": null, "e": 8249, "s": 6386, "text": "Explanation: The session is started using session_start() method. After that, the variables are declared and an error array is created. It will store all the error messages. The server.php page is then connected to the ‘registration’ database created earlier. After the user clicks the ‘register’ button on the register.php button, the data entered is sent to the database, and this completes a new registration. However, form validation is done before that to make sure that the user is filling the form correctly. All the fields are required and cannot be left blank.Line 18 – 21: mysqli_real_escape_string escapes the special characters before sending the data to the database. This is essential for database security from SQL injections.Line 25 – 27: These lines makes sure that the user is filling all the input boxes, and whether the ‘password’ and ‘confirm password’ matches. If both the password matches, then the code further runs.Line 29 – 32: Checking whether the password matches or not. Line 35 – 46: If the number of errors until this point is zero, the password is then ‘md5’ encrypted and the data entered is sent to the database. After the registration process is complete, the username is stored in the session variable, and the user is redirected to the index.php page, where he is asked to enter the login credentials.Line 50 – 80: First the username and password entered in sanitized. This is essential to increase database security, as it eliminates the chances of any SQL injection. The user gets an error message if the username or the password field is left blank. If the number of errors until this point of code is found to be 0, then a database check is run. If the username entered by the user is found to be present in the database, then the user successfully logs in. The user is then redirected to the ‘index.php’ page.login.php " }, { "code": null, "e": 8254, "s": 8249, "text": "html" }, { "code": "<?php include('server.php') ?><!DOCTYPE html><html><head> <title> Login and Registration System - LAMP Stack </title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head><body> <div class=\"header\"> <h2>Login Here!</h2> </div> <form method=\"post\" action=\"login.php\"> <?php include('errors.php'); ?> <div class=\"input-group\"> <label>Enter Username</label> <input type=\"text\" name=\"username\" > </div> <div class=\"input-group\"> <label>Enter Password</label> <input type=\"password\" name=\"password\"> </div> <div class=\"input-group\"> <button type=\"submit\" class=\"btn\" name=\"login_user\"> Login </button> </div> <p> New Here? <a href=\"register.php\"> Click here to register! </a> </p> </form></body> </html>", "e": 9252, "s": 8254, "text": null }, { "code": null, "e": 9561, "s": 9252, "text": "Explanation: Login page of the system. The user has to enter the username and password to successfully log in. After the login button is pressed, the login code written in the server.php page is run, which does all the backend work, like checking whether the username and password match or not.register.php " }, { "code": null, "e": 9565, "s": 9561, "text": "php" }, { "code": "<?php include('server.php') ?><!DOCTYPE html><html><head> <title> Registration system PHP and MySQL </title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head> <body> <div class=\"header\"> <h2>Register</h2> </div> <form method=\"post\" action=\"register.php\"> <?php include('errors.php'); ?> <div class=\"input-group\"> <label>Enter Username</label> <input type=\"text\" name=\"username\" value=\"<?php echo $username; ?>\"> </div> <div class=\"input-group\"> <label>Email</label> <input type=\"email\" name=\"email\" value=\"<?php echo $email; ?>\"> </div> <div class=\"input-group\"> <label>Enter Password</label> <input type=\"password\" name=\"password_1\"> </div> <div class=\"input-group\"> <label>Confirm password</label> <input type=\"password\" name=\"password_2\"> </div> <div class=\"input-group\"> <button type=\"submit\" class=\"btn\" name=\"reg_user\"> Register </button> </div> <p> Already having an account? <a href=\"login.php\"> Login Here! </a> </p> </form></body></html>", "e": 10922, "s": 9565, "text": null }, { "code": null, "e": 11331, "s": 10922, "text": "Explanation: This page contains the HTML coding of the registration page. The ‘server.php’, and ‘errors.php’ pages are included in lines 01 and 15 respectively. This is necessary to make the backend of the registration system work. The user is asked to enter the username, email, and password to create an account. After the input fields are filled, the data entered is sent to the database table.index.php " }, { "code": null, "e": 11336, "s": 11331, "text": "html" }, { "code": "<?php // Starting the session, to use and// store data in session variablesession_start(); // If the session variable is empty, this// means the user is yet to login// User will be sent to 'login.php' page// to allow the user to loginif (!isset($_SESSION['username'])) { $_SESSION['msg'] = \"You have to log in first\"; header('location: login.php');} // Logout button will destroy the session, and// will unset the session variables// User will be headed to 'login.php'// after logging outif (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['username']); header(\"location: login.php\");}?><!DOCTYPE html><html><head> <title>Homepage</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head><body> <div class=\"header\"> <h2>Home Page</h2> </div> <div class=\"content\"> <!-- Creating notification when the user logs in --> <!-- Accessible only to the users that have logged in already --> <?php if (isset($_SESSION['success'])) : ?> <div class=\"error success\" > <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?> </h3> </div> <?php endif ?> <!-- information of the user logged in --> <!-- welcome message for the logged in user --> <?php if (isset($_SESSION['username'])) : ?> <p> Welcome <strong> <?php echo $_SESSION['username']; ?> </strong> </p> <p> <a href=\"index.php?logout='1'\" style=\"color: red;\"> Click here to Logout </a> </p> <?php endif ?> </div></body></html>", "e": 13215, "s": 11336, "text": null }, { "code": null, "e": 13828, "s": 13215, "text": "Explanation: Line 01 – 19: The username that was stored in the session variable is now displayed back to the user. This session variable can either be destroyed using unset($_SESSION[“products”]) or session_destroy(). However, session_destroy() will destroy all the session variables at once. To destroy only the ‘username’ session variable, it will be better to unset the variable using unset($_SESSION[“products”]).Line 34 – 42: This makes sure that this page is accessible only to those users that are logged in.Line 45 – 50: This displays a personalized welcome message to the user once they log in.CSS File " }, { "code": null, "e": 13832, "s": 13828, "text": "CSS" }, { "code": "* { margin: 0px; padding: 0px;}body { font-size: 120%; background: #F8F8FF;} .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px;}form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px;}.input-group { margin: 10px 10px 10px 10px;} .input-group label { display: block; text-align: left; margin: 5px; font-size: 20px;}.input-group input { height: 32px; width: 95%; padding: 5px 10px; font-size: 15px; border-radius: 10px; border: 1px solid gray;}.btn { cursor: pointer; padding: 12px; font-size: 16px; color: white; background: #23585a; border: none; border-radius: 10px;}.error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left;}.success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px;}", "e": 15032, "s": 13832, "text": null }, { "code": null, "e": 15059, "s": 15032, "text": "Pictorial Representation: " }, { "code": null, "e": 15077, "s": 15059, "text": "Registration Page" }, { "code": null, "e": 15167, "s": 15079, "text": "User is redirected to this page after logging in. A welcome message is displayed there." }, { "code": null, "e": 15194, "s": 15169, "text": "Login page of the system" }, { "code": null, "e": 15228, "s": 15196, "text": "User has successfully logged in" }, { "code": null, "e": 15274, "s": 15230, "text": "Incorrect username and password combination" }, { "code": null, "e": 15442, "s": 15276, "text": "The source codes of this project can be obtained from this GitHub repository.After downloading and unzipping the project, follow the given steps to run the program: " }, { "code": null, "e": 15514, "s": 15442, "text": "Download all the files, or clone the repository into your local system." }, { "code": null, "e": 15634, "s": 15514, "text": "Create a database named ‘registration’, and a table named ‘users’. The MySQL code of the table has been provided above." }, { "code": null, "e": 15683, "s": 15634, "text": "Use XAMP or WAMP to run the system on localhost." }, { "code": null, "e": 15814, "s": 15683, "text": "Make sure that the necessary ports to run Apache and MySQL server are free. If not, then you will have to change the port numbers." }, { "code": null, "e": 16008, "s": 15814, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 16177, "s": 16008, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 16194, "s": 16177, "text": "arorakashish0911" }, { "code": null, "e": 16204, "s": 16194, "text": "kalrap615" }, { "code": null, "e": 16219, "s": 16204, "text": "sagar0719kumar" }, { "code": null, "e": 16229, "s": 16219, "text": "HTML-Misc" }, { "code": null, "e": 16240, "s": 16229, "text": "PHP-basics" }, { "code": null, "e": 16247, "s": 16240, "text": "Picked" }, { "code": null, "e": 16252, "s": 16247, "text": "HTML" }, { "code": null, "e": 16256, "s": 16252, "text": "PHP" }, { "code": null, "e": 16273, "s": 16256, "text": "Web Technologies" }, { "code": null, "e": 16300, "s": 16273, "text": "Web technologies Questions" }, { "code": null, "e": 16305, "s": 16300, "text": "HTML" }, { "code": null, "e": 16309, "s": 16305, "text": "PHP" } ]
Length of longest consecutive zeroes in the binary representation of a number.
27 May, 2021 We have a number N. Determine the length of longest consecutive 0’s in its binary representation. Examples: Input : N = 14 Output : 1 Binary representation of 14 is 1110. There is only one 0 in the binary representation. Input : N = 9 Output : 2 A simple approach is to traverse through all bits and keep track of the maximum number of consecutive 0s. C++ Java Python3 C# PHP Javascript // C++ code to determine Length of// longest consecutive zeroes in the// binary representation of a number.#include <bits/stdc++.h>using namespace std; int maxZeros(int N){ // variable to store the length of // longest consecutive 0's int maxm = -1; // to temporary store the consecutive 0's int cnt = 0; while (N) { if (!(N & 1)) { cnt++; N >>= 1; maxm = max(maxm, cnt); } else { maxm = max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm;} // Driver codeint main(){ int N = 14; cout << maxZeros(N) << endl; return 0;} // Java code to determine Length of // longest consecutive zeroes in the// binary representation of a number. public class GFG { static int maxZeros(int N) { // variable to store the length of // longest consecutive 0's int maxm = -1; // to temporary store the consecutive 0's int cnt = 0; while (N != 0) { if ((N & 1) == 0 ) { cnt++; N >>= 1; maxm = Math.max(maxm, cnt); } else { maxm = Math.max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm; } // Driver code public static void main(String args[]) { int N = 14; System.out.println(maxZeros(N)); } // This Code is contributed by ANKITRAI1} # Python3 code to determine Length of# longest consecutive zeroes in the# binary representation of a number.def maxZeros(N): # variable to store the length # of longest consecutive 0's maxm = -1 # to temporary store the # consecutive 0's cnt = 0 while(N): if(not(N & 1)): cnt += 1 N >>= 1 maxm = max(maxm,cnt) else: maxm = max(maxm,cnt) cnt = 0 N >>= 1 return maxm # Driver CodeN = 14print(maxZeros(N)) # This code is written by Shrikant13 // C# code to determine Length of// longest consecutive zeroes in the// binary representation of a number.using System; class GFG{static int maxZeros(int N){ // variable to store the length // of longest consecutive 0's int maxm = -1; // to temporary store the // consecutive 0's int cnt = 0; while (N != 0) { if ((N & 1) == 0 ) { cnt++; N >>= 1; maxm = Math.Max(maxm, cnt); } else { maxm = Math.Max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm;} // Driver codepublic static void Main(){ int N = 14; Console.WriteLine(maxZeros(N));}} // This code is contributed// by anuj_67 <?php// PHP code to determine Length of// longest consecutive zeroes in the// binary representation of a number.function maxZeros($N){ // variable to store the length // of longest consecutive 0's $maxm = -1; // to temporary store the // of consecutive 0's $cnt = 0; while ($N) { if (!($N & 1)) { $cnt++; $N >>= 1; $maxm = max($maxm, $cnt); } else { $maxm = max($maxm, $cnt); $cnt = 0; $N >>= 1; } } return $maxm;} // Driver code$N = 14;echo (maxZeros($N)); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript code to determine Length of // longest consecutive zeroes in the // binary representation of a number. function maxZeros(N) { // variable to store the length // of longest consecutive 0's let maxm = -1; // to temporary store the // consecutive 0's let cnt = 0; while (N != 0) { if ((N & 1) == 0 ) { cnt++; N >>= 1; maxm = Math.max(maxm, cnt); } else { maxm = Math.max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm; } let N = 14; document.write(maxZeros(N)); </script> 1 shrikanth13 ankthon vt_m Shivi_Aggarwal suresh07 Technical Scripter 2018 Bit Magic Technical Scripter 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 Google Online Challenge 2020 Calculate XOR from 1 to n. Find two numbers from their sum and XOR Calculate square of a number without using *, / and pow() Reverse actual bits of the given number Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal Find XOR of two number without using XOR operator Unique element in an array where all elements occur k times except one
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2021" }, { "code": null, "e": 150, "s": 52, "text": "We have a number N. Determine the length of longest consecutive 0’s in its binary representation." }, { "code": null, "e": 161, "s": 150, "text": "Examples: " }, { "code": null, "e": 303, "s": 161, "text": "Input : N = 14\nOutput : 1\nBinary representation of 14 is \n1110. There is only one 0 in\nthe binary representation.\n\nInput : N = 9 \nOutput : 2" }, { "code": null, "e": 410, "s": 303, "text": "A simple approach is to traverse through all bits and keep track of the maximum number of consecutive 0s. " }, { "code": null, "e": 414, "s": 410, "text": "C++" }, { "code": null, "e": 419, "s": 414, "text": "Java" }, { "code": null, "e": 427, "s": 419, "text": "Python3" }, { "code": null, "e": 430, "s": 427, "text": "C#" }, { "code": null, "e": 434, "s": 430, "text": "PHP" }, { "code": null, "e": 445, "s": 434, "text": "Javascript" }, { "code": "// C++ code to determine Length of// longest consecutive zeroes in the// binary representation of a number.#include <bits/stdc++.h>using namespace std; int maxZeros(int N){ // variable to store the length of // longest consecutive 0's int maxm = -1; // to temporary store the consecutive 0's int cnt = 0; while (N) { if (!(N & 1)) { cnt++; N >>= 1; maxm = max(maxm, cnt); } else { maxm = max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm;} // Driver codeint main(){ int N = 14; cout << maxZeros(N) << endl; return 0;}", "e": 1093, "s": 445, "text": null }, { "code": "// Java code to determine Length of // longest consecutive zeroes in the// binary representation of a number. public class GFG { static int maxZeros(int N) { // variable to store the length of // longest consecutive 0's int maxm = -1; // to temporary store the consecutive 0's int cnt = 0; while (N != 0) { if ((N & 1) == 0 ) { cnt++; N >>= 1; maxm = Math.max(maxm, cnt); } else { maxm = Math.max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm; } // Driver code public static void main(String args[]) { int N = 14; System.out.println(maxZeros(N)); } // This Code is contributed by ANKITRAI1}", "e": 1952, "s": 1093, "text": null }, { "code": "# Python3 code to determine Length of# longest consecutive zeroes in the# binary representation of a number.def maxZeros(N): # variable to store the length # of longest consecutive 0's maxm = -1 # to temporary store the # consecutive 0's cnt = 0 while(N): if(not(N & 1)): cnt += 1 N >>= 1 maxm = max(maxm,cnt) else: maxm = max(maxm,cnt) cnt = 0 N >>= 1 return maxm # Driver CodeN = 14print(maxZeros(N)) # This code is written by Shrikant13", "e": 2499, "s": 1952, "text": null }, { "code": "// C# code to determine Length of// longest consecutive zeroes in the// binary representation of a number.using System; class GFG{static int maxZeros(int N){ // variable to store the length // of longest consecutive 0's int maxm = -1; // to temporary store the // consecutive 0's int cnt = 0; while (N != 0) { if ((N & 1) == 0 ) { cnt++; N >>= 1; maxm = Math.Max(maxm, cnt); } else { maxm = Math.Max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm;} // Driver codepublic static void Main(){ int N = 14; Console.WriteLine(maxZeros(N));}} // This code is contributed// by anuj_67", "e": 3221, "s": 2499, "text": null }, { "code": "<?php// PHP code to determine Length of// longest consecutive zeroes in the// binary representation of a number.function maxZeros($N){ // variable to store the length // of longest consecutive 0's $maxm = -1; // to temporary store the // of consecutive 0's $cnt = 0; while ($N) { if (!($N & 1)) { $cnt++; $N >>= 1; $maxm = max($maxm, $cnt); } else { $maxm = max($maxm, $cnt); $cnt = 0; $N >>= 1; } } return $maxm;} // Driver code$N = 14;echo (maxZeros($N)); // This code is contributed// by Shivi_Aggarwal?>", "e": 3869, "s": 3221, "text": null }, { "code": "<script> // Javascript code to determine Length of // longest consecutive zeroes in the // binary representation of a number. function maxZeros(N) { // variable to store the length // of longest consecutive 0's let maxm = -1; // to temporary store the // consecutive 0's let cnt = 0; while (N != 0) { if ((N & 1) == 0 ) { cnt++; N >>= 1; maxm = Math.max(maxm, cnt); } else { maxm = Math.max(maxm, cnt); cnt = 0; N >>= 1; } } return maxm; } let N = 14; document.write(maxZeros(N)); </script>", "e": 4626, "s": 3869, "text": null }, { "code": null, "e": 4628, "s": 4626, "text": "1" }, { "code": null, "e": 4642, "s": 4630, "text": "shrikanth13" }, { "code": null, "e": 4650, "s": 4642, "text": "ankthon" }, { "code": null, "e": 4655, "s": 4650, "text": "vt_m" }, { "code": null, "e": 4670, "s": 4655, "text": "Shivi_Aggarwal" }, { "code": null, "e": 4679, "s": 4670, "text": "suresh07" }, { "code": null, "e": 4703, "s": 4679, "text": "Technical Scripter 2018" }, { "code": null, "e": 4713, "s": 4703, "text": "Bit Magic" }, { "code": null, "e": 4732, "s": 4713, "text": "Technical Scripter" }, { "code": null, "e": 4742, "s": 4732, "text": "Bit Magic" }, { "code": null, "e": 4840, "s": 4742, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4891, "s": 4840, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 4925, "s": 4891, "text": "Builtin functions of GCC compiler" }, { "code": null, "e": 4954, "s": 4925, "text": "Google Online Challenge 2020" }, { "code": null, "e": 4981, "s": 4954, "text": "Calculate XOR from 1 to n." }, { "code": null, "e": 5021, "s": 4981, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 5079, "s": 5021, "text": "Calculate square of a number without using *, / and pow()" }, { "code": null, "e": 5119, "s": 5079, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 5213, "s": 5119, "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": 5263, "s": 5213, "text": "Find XOR of two number without using XOR operator" } ]
How to read all CSV files in a folder in Pandas?
21 Apr, 2021 In this article, we will see how to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content. Import necessary python packages like pandas, glob, and os.Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.csv’Loop over the list of csv files, read that file using pandas.read_csv().Convert each csv file into a dataframe.Display its location, name, and content. Import necessary python packages like pandas, glob, and os. Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.csv’ Loop over the list of csv files, read that file using pandas.read_csv(). Convert each csv file into a dataframe. Display its location, name, and content. Below is the implementation. Python3 # import necessary librariesimport pandas as pdimport osimport glob # use glob to get all the csv files # in the folderpath = os.getcwd()csv_files = glob.glob(os.path.join(path, "*.csv")) # loop over the list of csv filesfor f in csv_files: # read the csv file df = pd.read_csv(f) # print the location and filename print('Location:', f) print('File Name:', f.split("\\")[-1]) # print the content print('Content:') display(df) print() Output: Note: The program reads all CSV files in the folder in which the program itself is present. Picked python-csv Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Apr, 2021" }, { "code": null, "e": 344, "s": 54, "text": "In this article, we will see how to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content." }, { "code": null, "e": 647, "s": 344, "text": "Import necessary python packages like pandas, glob, and os.Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.csv’Loop over the list of csv files, read that file using pandas.read_csv().Convert each csv file into a dataframe.Display its location, name, and content." }, { "code": null, "e": 707, "s": 647, "text": "Import necessary python packages like pandas, glob, and os." }, { "code": null, "e": 800, "s": 707, "text": "Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.csv’" }, { "code": null, "e": 873, "s": 800, "text": "Loop over the list of csv files, read that file using pandas.read_csv()." }, { "code": null, "e": 913, "s": 873, "text": "Convert each csv file into a dataframe." }, { "code": null, "e": 954, "s": 913, "text": "Display its location, name, and content." }, { "code": null, "e": 983, "s": 954, "text": "Below is the implementation." }, { "code": null, "e": 991, "s": 983, "text": "Python3" }, { "code": "# import necessary librariesimport pandas as pdimport osimport glob # use glob to get all the csv files # in the folderpath = os.getcwd()csv_files = glob.glob(os.path.join(path, \"*.csv\")) # loop over the list of csv filesfor f in csv_files: # read the csv file df = pd.read_csv(f) # print the location and filename print('Location:', f) print('File Name:', f.split(\"\\\\\")[-1]) # print the content print('Content:') display(df) print()", "e": 1476, "s": 991, "text": null }, { "code": null, "e": 1484, "s": 1476, "text": "Output:" }, { "code": null, "e": 1576, "s": 1484, "text": "Note: The program reads all CSV files in the folder in which the program itself is present." }, { "code": null, "e": 1583, "s": 1576, "text": "Picked" }, { "code": null, "e": 1594, "s": 1583, "text": "python-csv" }, { "code": null, "e": 1608, "s": 1594, "text": "Python-pandas" }, { "code": null, "e": 1615, "s": 1608, "text": "Python" }, { "code": null, "e": 1713, "s": 1615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1731, "s": 1713, "text": "Python Dictionary" }, { "code": null, "e": 1773, "s": 1731, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1795, "s": 1773, "text": "Enumerate() in Python" }, { "code": null, "e": 1830, "s": 1795, "text": "Read a file line by line in Python" }, { "code": null, "e": 1856, "s": 1830, "text": "Python String | replace()" }, { "code": null, "e": 1888, "s": 1856, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1917, "s": 1888, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1944, "s": 1917, "text": "Python Classes and Objects" }, { "code": null, "e": 1974, "s": 1944, "text": "Iterate over a list in Python" } ]
TimeUnit Class in Java with Examples
29 Sep, 2021 TimeUnit is an Enum available in java.util.concurrent package. TimeUnit as the name implies deals with Time units. TimeUnit provides time representation at a given unit of granularity. It makes available methods to convert time across time units. TimeUnit is useful to know how a given time should be interpreted that is which time unit should be considered. Minute differences between time durations such as in microseconds and nanoseconds can be figured out using TimeUnit. It is used to perform timing and delay operations. It supports nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and days units. For these units, TimeUnit specifies corresponding enum constants: Nanoseconds: One thousandth of a microsecondMicroseconds: One thousandth of a millisecondMilliseconds: One thousandth of a secondSeconds: One secondMinutes: Sixty secondsHours: Sixty minutesDays: Twenty four hours Nanoseconds: One thousandth of a microsecond Microseconds: One thousandth of a millisecond Milliseconds: One thousandth of a second Seconds: One second Minutes: Sixty seconds Hours: Sixty minutes Days: Twenty four hours Example 1: Java // Java program to demonstrate TimeUnit Class import java.util.concurrent.TimeUnit; public class GFG { public static void main(String args[]) { long hours = 96; // Convert given time (hours)in days long days = TimeUnit.DAYS.convert(hours, TimeUnit.HOURS); // Convert days in minutes long minutes = TimeUnit.MINUTES.convert(days, TimeUnit.DAYS); System.out.println(hours + " Hours = " + days + " Days = " + +minutes + " Minutes"); // Convert given time (minutes) to microseconds long micros = TimeUnit.MINUTES.toMicros(minutes); System.out.println(minutes + " Minutes = " + micros + " Microseconds"); // Convert given time (microseconds) to seconds long seconds = TimeUnit.MICROSECONDS.toSeconds(micros); System.out.println(micros + " Microseconds = " + seconds + " Seconds"); // Create TimeUnit object of type Minutes TimeUnit time = TimeUnit.valueOf("MINUTES"); System.out.println("TimeUnit object type: " + time); }} 96 Hours = 4 Days = 5760 Minutes 5760 Minutes = 345600000000 Microseconds 345600000000 Microseconds = 345600 Seconds TimeUnit object type: MINUTES Example 2: Java // Java program to demonstrate TimeUnit Class import java.util.concurrent.TimeUnit; public class GFG implements Runnable { public void run() { // Get array of TimeUnit enum constants using // values() for (TimeUnit unit : TimeUnit.values()) { try { // pause for 1 second TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( unit + " : " + unit.convert(24, TimeUnit.HOURS)); } } public static void main(String args[]) { GFG obj1 = new GFG(); System.out.println("TimeUnit Example"); // Create and start Thread Thread t1 = new Thread(obj1); t1.start(); System.out.println("Now, thread will run for 5 seconds"); try { // Specify Thread join time, here, 5 seconds TimeUnit.SECONDS.timedJoin(t1, 5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread Execution Paused"); System.out.println("Resuming Thread Execution..."); }} TimeUnit Example Now, thread will run for 5 seconds NANOSECONDS : 86400000000000 MICROSECONDS : 86400000000 MILLISECONDS : 86400000 SECONDS : 86400 Thread Execution Paused Resuming Thread Execution... MINUTES : 1440 HOURS : 24 DAYS : 1 Utility methods available in TimeUnit: simmytarika5 Java-Date-Time Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Sep, 2021" }, { "code": null, "e": 556, "s": 28, "text": "TimeUnit is an Enum available in java.util.concurrent package. TimeUnit as the name implies deals with Time units. TimeUnit provides time representation at a given unit of granularity. It makes available methods to convert time across time units. TimeUnit is useful to know how a given time should be interpreted that is which time unit should be considered. Minute differences between time durations such as in microseconds and nanoseconds can be figured out using TimeUnit. It is used to perform timing and delay operations." }, { "code": null, "e": 716, "s": 556, "text": "It supports nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and days units. For these units, TimeUnit specifies corresponding enum constants:" }, { "code": null, "e": 930, "s": 716, "text": "Nanoseconds: One thousandth of a microsecondMicroseconds: One thousandth of a millisecondMilliseconds: One thousandth of a secondSeconds: One secondMinutes: Sixty secondsHours: Sixty minutesDays: Twenty four hours" }, { "code": null, "e": 975, "s": 930, "text": "Nanoseconds: One thousandth of a microsecond" }, { "code": null, "e": 1021, "s": 975, "text": "Microseconds: One thousandth of a millisecond" }, { "code": null, "e": 1062, "s": 1021, "text": "Milliseconds: One thousandth of a second" }, { "code": null, "e": 1082, "s": 1062, "text": "Seconds: One second" }, { "code": null, "e": 1105, "s": 1082, "text": "Minutes: Sixty seconds" }, { "code": null, "e": 1126, "s": 1105, "text": "Hours: Sixty minutes" }, { "code": null, "e": 1150, "s": 1126, "text": "Days: Twenty four hours" }, { "code": null, "e": 1161, "s": 1150, "text": "Example 1:" }, { "code": null, "e": 1166, "s": 1161, "text": "Java" }, { "code": "// Java program to demonstrate TimeUnit Class import java.util.concurrent.TimeUnit; public class GFG { public static void main(String args[]) { long hours = 96; // Convert given time (hours)in days long days = TimeUnit.DAYS.convert(hours, TimeUnit.HOURS); // Convert days in minutes long minutes = TimeUnit.MINUTES.convert(days, TimeUnit.DAYS); System.out.println(hours + \" Hours = \" + days + \" Days = \" + +minutes + \" Minutes\"); // Convert given time (minutes) to microseconds long micros = TimeUnit.MINUTES.toMicros(minutes); System.out.println(minutes + \" Minutes = \" + micros + \" Microseconds\"); // Convert given time (microseconds) to seconds long seconds = TimeUnit.MICROSECONDS.toSeconds(micros); System.out.println(micros + \" Microseconds = \" + seconds + \" Seconds\"); // Create TimeUnit object of type Minutes TimeUnit time = TimeUnit.valueOf(\"MINUTES\"); System.out.println(\"TimeUnit object type: \" + time); }}", "e": 2309, "s": 1166, "text": null }, { "code": null, "e": 2456, "s": 2309, "text": "96 Hours = 4 Days = 5760 Minutes\n5760 Minutes = 345600000000 Microseconds\n345600000000 Microseconds = 345600 Seconds\nTimeUnit object type: MINUTES" }, { "code": null, "e": 2468, "s": 2456, "text": "Example 2: " }, { "code": null, "e": 2473, "s": 2468, "text": "Java" }, { "code": "// Java program to demonstrate TimeUnit Class import java.util.concurrent.TimeUnit; public class GFG implements Runnable { public void run() { // Get array of TimeUnit enum constants using // values() for (TimeUnit unit : TimeUnit.values()) { try { // pause for 1 second TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( unit + \" : \" + unit.convert(24, TimeUnit.HOURS)); } } public static void main(String args[]) { GFG obj1 = new GFG(); System.out.println(\"TimeUnit Example\"); // Create and start Thread Thread t1 = new Thread(obj1); t1.start(); System.out.println(\"Now, thread will run for 5 seconds\"); try { // Specify Thread join time, here, 5 seconds TimeUnit.SECONDS.timedJoin(t1, 5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(\"Thread Execution Paused\"); System.out.println(\"Resuming Thread Execution...\"); }}", "e": 3721, "s": 2473, "text": null }, { "code": null, "e": 3958, "s": 3721, "text": "TimeUnit Example\nNow, thread will run for 5 seconds\nNANOSECONDS : 86400000000000\nMICROSECONDS : 86400000000\nMILLISECONDS : 86400000\nSECONDS : 86400\nThread Execution Paused\nResuming Thread Execution...\nMINUTES : 1440\nHOURS : 24\nDAYS : 1" }, { "code": null, "e": 3998, "s": 3958, "text": "Utility methods available in TimeUnit: " }, { "code": null, "e": 4013, "s": 4000, "text": "simmytarika5" }, { "code": null, "e": 4028, "s": 4013, "text": "Java-Date-Time" }, { "code": null, "e": 4035, "s": 4028, "text": "Picked" }, { "code": null, "e": 4040, "s": 4035, "text": "Java" }, { "code": null, "e": 4045, "s": 4040, "text": "Java" }, { "code": null, "e": 4143, "s": 4045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4158, "s": 4143, "text": "Stream In Java" }, { "code": null, "e": 4179, "s": 4158, "text": "Introduction to Java" }, { "code": null, "e": 4200, "s": 4179, "text": "Constructors in Java" }, { "code": null, "e": 4219, "s": 4200, "text": "Exceptions in Java" }, { "code": null, "e": 4236, "s": 4219, "text": "Generics in Java" }, { "code": null, "e": 4266, "s": 4236, "text": "Functional Interfaces in Java" }, { "code": null, "e": 4292, "s": 4266, "text": "Java Programming Examples" }, { "code": null, "e": 4308, "s": 4292, "text": "Strings in Java" }, { "code": null, "e": 4345, "s": 4308, "text": "Differences between JDK, JRE and JVM" } ]
Python – Rounding button corners in kivy
14 Jan, 2021 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. In this article we will be going to learn how to round the button corners in kivy python. Now one question arises – What is the preferred way to create rounded corners for buttons in kivy? Basically, this is the tricky one. As we know Widgets are always a rectangle, but we can change the background of widgets and put a couple of images for the normal and the downstate of the button by using some properties of buttons like background_normal and background_down properties respectively. Also to round the corners of the button you also must have understood one more property of the button that is the border property. background_down : 1) Background image of the button used for the default graphical representation when the button is pressed. 2) background_down is a StringProperty. background_normal : 1) Background image of the button used for the default graphical representation when the button is not pressed. 2) background_normal is also a StringProperty. border : 1) Border used for BorderImage graphics instruction. Used with background_normal and background_down. Can be used for custom backgrounds. 2) It must be a list of four values: (bottom, right, top, left). 3) border is a ListProperty and defaults to (16, 16, 16, 16) Kivy Tutorial – Learn Kivy with Examples. Syntax of all above properties: Python3 background_normal: 'normal.png'background_down: 'down.png'border: 30, 30, 30, 30 Basic Approach: -> import kivy -> import kivy App -> import button -> set minimum version(optional) -> Extend the class : -> create an image a button -> Do styling -> Use the border property to round the corners of the button -> Arrange call back if needed -> Add and return a button -> Run an instance of the class With these two images called normal.png and down.png, you can start adding your round borders. We are going to use the above 2 images in creating the rounded button. Below is a very simple piece of code and we will try to explain each and everything. border property– The values in border:30, 30, 30, 30 tells us how many pixels on the left, right, top, bottom are going to be used for the border of the button. If you give a border, see for example border: (150, 150, 150, 150), this will behave wrongly and the reason is that we are picking up a border bigger than the actual image. Now below is the code implementing my approach: Python3 ## Sample Python application demonstrating that## how to create button corners round in kivy ################################################## # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # class in which we are creating the imagebuttonclass ButtonApp(App): def build(self): # create a fully styled functional button # Adding images normal.png and down.png btn = Button(text ="Push Me !", background_normal = 'normal.png', background_down = 'down.png', border = (30, 30, 30, 30), size_hint = (.3, .3), pos_hint = {"x":0.35, "y":0.3} ) # Returning the button return btn # creating the object root for ButtonApp() classroot = ButtonApp() # run function runs the whole program# i.e run() method which calls the target# function passed to the constructor.root.run() Output: Note: Widgets are still rectangles. That means that even if you click on the rounded corners, the button still receive the event. abhigoya Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2021" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications." }, { "code": null, "e": 354, "s": 264, "text": "In this article we will be going to learn how to round the button corners in kivy python." }, { "code": null, "e": 453, "s": 354, "text": "Now one question arises – What is the preferred way to create rounded corners for buttons in kivy?" }, { "code": null, "e": 885, "s": 453, "text": "Basically, this is the tricky one. As we know Widgets are always a rectangle, but we can change the background of widgets and put a couple of images for the normal and the downstate of the button by using some properties of buttons like background_normal and background_down properties respectively. Also to round the corners of the button you also must have understood one more property of the button that is the border property. " }, { "code": null, "e": 1051, "s": 885, "text": "background_down : 1) Background image of the button used for the default graphical representation when the button is pressed. 2) background_down is a StringProperty." }, { "code": null, "e": 1230, "s": 1051, "text": "background_normal : 1) Background image of the button used for the default graphical representation when the button is not pressed. 2) background_normal is also a StringProperty." }, { "code": null, "e": 1504, "s": 1230, "text": " border : 1) Border used for BorderImage graphics instruction. Used with background_normal and background_down. Can be used for custom backgrounds. 2) It must be a list of four values: (bottom, right, top, left). 3) border is a ListProperty and defaults to (16, 16, 16, 16)" }, { "code": null, "e": 1548, "s": 1506, "text": "Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 1582, "s": 1548, "text": "Syntax of all above properties: " }, { "code": null, "e": 1590, "s": 1582, "text": "Python3" }, { "code": "background_normal: 'normal.png'background_down: 'down.png'border: 30, 30, 30, 30", "e": 1671, "s": 1590, "text": null }, { "code": null, "e": 2047, "s": 1671, "text": "Basic Approach:\n\n-> import kivy\n-> import kivy App\n-> import button\n-> set minimum version(optional)\n-> Extend the class : \n -> create an image a button\n -> Do styling\n -> Use the border property to round the corners of the button\n -> Arrange call back if needed \n-> Add and return a button\n-> Run an instance of the class" }, { "code": null, "e": 2143, "s": 2047, "text": "With these two images called normal.png and down.png, you can start adding your round borders. " }, { "code": null, "e": 2216, "s": 2145, "text": "We are going to use the above 2 images in creating the rounded button." }, { "code": null, "e": 2301, "s": 2216, "text": "Below is a very simple piece of code and we will try to explain each and everything." }, { "code": null, "e": 2635, "s": 2301, "text": "border property– The values in border:30, 30, 30, 30 tells us how many pixels on the left, right, top, bottom are going to be used for the border of the button. If you give a border, see for example border: (150, 150, 150, 150), this will behave wrongly and the reason is that we are picking up a border bigger than the actual image." }, { "code": null, "e": 2685, "s": 2635, "text": "Now below is the code implementing my approach: " }, { "code": null, "e": 2693, "s": 2685, "text": "Python3" }, { "code": "## Sample Python application demonstrating that## how to create button corners round in kivy ################################################## # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # class in which we are creating the imagebuttonclass ButtonApp(App): def build(self): # create a fully styled functional button # Adding images normal.png and down.png btn = Button(text =\"Push Me !\", background_normal = 'normal.png', background_down = 'down.png', border = (30, 30, 30, 30), size_hint = (.3, .3), pos_hint = {\"x\":0.35, \"y\":0.3} ) # Returning the button return btn # creating the object root for ButtonApp() classroot = ButtonApp() # run function runs the whole program# i.e run() method which calls the target# function passed to the constructor.root.run()", "e": 4357, "s": 2693, "text": null }, { "code": null, "e": 4367, "s": 4357, "text": "Output: " }, { "code": null, "e": 4500, "s": 4369, "text": "Note: Widgets are still rectangles. That means that even if you click on the rounded corners, the button still receive the event. " }, { "code": null, "e": 4509, "s": 4500, "text": "abhigoya" }, { "code": null, "e": 4520, "s": 4509, "text": "Python-gui" }, { "code": null, "e": 4532, "s": 4520, "text": "Python-kivy" }, { "code": null, "e": 4539, "s": 4532, "text": "Python" }, { "code": null, "e": 4637, "s": 4539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4655, "s": 4637, "text": "Python Dictionary" }, { "code": null, "e": 4697, "s": 4655, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4719, "s": 4697, "text": "Enumerate() in Python" }, { "code": null, "e": 4745, "s": 4719, "text": "Python String | replace()" }, { "code": null, "e": 4777, "s": 4745, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4806, "s": 4777, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4833, "s": 4806, "text": "Python Classes and Objects" }, { "code": null, "e": 4863, "s": 4833, "text": "Iterate over a list in Python" }, { "code": null, "e": 4884, "s": 4863, "text": "Python OOPs Concepts" } ]
Check if Two Objects are Equal in R Programming – setequal() Function
15 Jun, 2020 setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters:x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal() function # Vector 1 x1 <- c(1, 2, 3, 4, 5, 6) # Vector 2 x2 <- c(1:6) # Vector 3x3 <- c(2, 3, 4, 5, 6) # Calling setequal() Function setequal(x1, x2) setequal(x1, x3) Output: [1] TRUE [1] FALSE Example 2: # R program to illustrate # the use of setequal() function # Data frame 1 data_x <- data.frame(x1 = c(5, 6, 7), x2 = c(2, 2, 2)) # Data frame 2 data_y <- data.frame(y1 = c(5, 6, 7), y2 = c(2, 2, 2)) # Calling setequal() Functionsetequal(data_x, data_y) Output: [1] TRUE R Array-Functions R DataFrame-Function R Matrix-Function R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? R Programming Language - Introduction How to Change Axis Scales in R Plots? R - if statement How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jun, 2020" }, { "code": null, "e": 244, "s": 28, "text": "setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not." }, { "code": null, "e": 267, "s": 244, "text": "Syntax: setequal(x, y)" }, { "code": null, "e": 318, "s": 267, "text": "Parameters:x and y: Objects with sequence of items" }, { "code": null, "e": 329, "s": 318, "text": "Example 1:" }, { "code": "# R program to illustrate # the use of setequal() function # Vector 1 x1 <- c(1, 2, 3, 4, 5, 6) # Vector 2 x2 <- c(1:6) # Vector 3x3 <- c(2, 3, 4, 5, 6) # Calling setequal() Function setequal(x1, x2) setequal(x1, x3) ", "e": 583, "s": 329, "text": null }, { "code": null, "e": 591, "s": 583, "text": "Output:" }, { "code": null, "e": 611, "s": 591, "text": "[1] TRUE\n[1] FALSE\n" }, { "code": null, "e": 622, "s": 611, "text": "Example 2:" }, { "code": "# R program to illustrate # the use of setequal() function # Data frame 1 data_x <- data.frame(x1 = c(5, 6, 7), x2 = c(2, 2, 2)) # Data frame 2 data_y <- data.frame(y1 = c(5, 6, 7), y2 = c(2, 2, 2)) # Calling setequal() Functionsetequal(data_x, data_y) ", "e": 944, "s": 622, "text": null }, { "code": null, "e": 952, "s": 944, "text": "Output:" }, { "code": null, "e": 962, "s": 952, "text": "[1] TRUE\n" }, { "code": null, "e": 980, "s": 962, "text": "R Array-Functions" }, { "code": null, "e": 1001, "s": 980, "text": "R DataFrame-Function" }, { "code": null, "e": 1019, "s": 1001, "text": "R Matrix-Function" }, { "code": null, "e": 1037, "s": 1019, "text": "R Object-Function" }, { "code": null, "e": 1055, "s": 1037, "text": "R Vector-Function" }, { "code": null, "e": 1066, "s": 1055, "text": "R Language" }, { "code": null, "e": 1164, "s": 1066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1216, "s": 1164, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1268, "s": 1216, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1326, "s": 1268, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1358, "s": 1326, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1393, "s": 1358, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1437, "s": 1393, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1475, "s": 1437, "text": "R Programming Language - Introduction" }, { "code": null, "e": 1513, "s": 1475, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1530, "s": 1513, "text": "R - if statement" } ]
Pandas – Groupby value counts on the DataFrame
15 Mar, 2021 Prerequisites: Pandas Pandas can be employed to count the frequency of each value in the data frame separately. Let’s see how to Groupby values count on the pandas dataframe. To count Groupby values in the pandas dataframe we are going to use groupby() size() and unstack() method. groupby(): groupby() function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs) Parameters : by : mapping, function, str, or iterable axis : int, default 0 level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group. group_keys : When calling apply, add group keys to index to identify pieces squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type Returns : GroupBy object size(): size method is used to get the integer representing the number of elements in object. The size method is return the number of rows times number of columns if DataFrame. Syntax: Dataframe.size() unstack(): unstack method works with the MultiIndex objects in DataFrame, producing a reshaped DataFrame with a new inner-most level of column labels. Syntax: Dataframe.unstack() Import module Create or load data Create data frame Count value of occurrences of each value Print resultant data frame Example1: Python # import pandasimport pandas as pd # create dataframedf = pd.DataFrame({ 'Course': ['BBA', 'BCA', 'BBA', 'BCA', 'BCA'], 'Student Name': ['Rishabh', 'Rahul', 'Suraj', 'Mukul', 'Vinit'], 'Age': [21, 22, 23, 22, 23]}) # print original dataframeprint("original dataframe")display(df) # counts Groupby valuedf = df.groupby(['Course', 'Student Name', 'Age']).size().unstack(fill_value=0) # print dataframeprint("Result :")display(df) Output: Example 2: Python # import pandasimport pandas as pd # create dataframedf = pd.DataFrame({ 'City': ['Saharanpur', 'Meerut', 'Saharanpur', 'Saharanpur', 'Meerut'], 'Employes Name': ['Robin', 'Tushar', 'Rohan', 'Mukul', 'Manoj'], 'Salary': [21000, 22000, 21000, 22000, 22000]}) # print original dataframeprint("original dataframe: ")display(df) # counts Groupby valuedf = df.groupby(['City', 'Employes Name', 'Salary'] ).size().unstack(fill_value=0) # print dataframeprint("result: ")display(df) Output: Picked Python pandas-dataFrame Python Pandas-exercise Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2021" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisites: Pandas" }, { "code": null, "e": 310, "s": 50, "text": "Pandas can be employed to count the frequency of each value in the data frame separately. Let’s see how to Groupby values count on the pandas dataframe. To count Groupby values in the pandas dataframe we are going to use groupby() size() and unstack() method." }, { "code": null, "e": 537, "s": 310, "text": "groupby(): groupby() function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names" }, { "code": null, "e": 546, "s": 537, "text": "Syntax: " }, { "code": null, "e": 661, "s": 546, "text": "DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)" }, { "code": null, "e": 674, "s": 661, "text": "Parameters :" }, { "code": null, "e": 715, "s": 674, "text": "by : mapping, function, str, or iterable" }, { "code": null, "e": 737, "s": 715, "text": "axis : int, default 0" }, { "code": null, "e": 827, "s": 737, "text": "level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels" }, { "code": null, "e": 999, "s": 827, "text": "as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output" }, { "code": null, "e": 1196, "s": 999, "text": "sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group." }, { "code": null, "e": 1272, "s": 1196, "text": "group_keys : When calling apply, add group keys to index to identify pieces" }, { "code": null, "e": 1375, "s": 1272, "text": "squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type" }, { "code": null, "e": 1400, "s": 1375, "text": "Returns : GroupBy object" }, { "code": null, "e": 1577, "s": 1400, "text": "size(): size method is used to get the integer representing the number of elements in object. The size method is return the number of rows times number of columns if DataFrame." }, { "code": null, "e": 1585, "s": 1577, "text": "Syntax:" }, { "code": null, "e": 1602, "s": 1585, "text": "Dataframe.size()" }, { "code": null, "e": 1753, "s": 1602, "text": "unstack(): unstack method works with the MultiIndex objects in DataFrame, producing a reshaped DataFrame with a new inner-most level of column labels." }, { "code": null, "e": 1761, "s": 1753, "text": "Syntax:" }, { "code": null, "e": 1781, "s": 1761, "text": "Dataframe.unstack()" }, { "code": null, "e": 1795, "s": 1781, "text": "Import module" }, { "code": null, "e": 1815, "s": 1795, "text": "Create or load data" }, { "code": null, "e": 1833, "s": 1815, "text": "Create data frame" }, { "code": null, "e": 1874, "s": 1833, "text": "Count value of occurrences of each value" }, { "code": null, "e": 1901, "s": 1874, "text": "Print resultant data frame" }, { "code": null, "e": 1911, "s": 1901, "text": "Example1:" }, { "code": null, "e": 1918, "s": 1911, "text": "Python" }, { "code": "# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({ 'Course': ['BBA', 'BCA', 'BBA', 'BCA', 'BCA'], 'Student Name': ['Rishabh', 'Rahul', 'Suraj', 'Mukul', 'Vinit'], 'Age': [21, 22, 23, 22, 23]}) # print original dataframeprint(\"original dataframe\")display(df) # counts Groupby valuedf = df.groupby(['Course', 'Student Name', 'Age']).size().unstack(fill_value=0) # print dataframeprint(\"Result :\")display(df)", "e": 2361, "s": 1918, "text": null }, { "code": null, "e": 2369, "s": 2361, "text": "Output:" }, { "code": null, "e": 2380, "s": 2369, "text": "Example 2:" }, { "code": null, "e": 2387, "s": 2380, "text": "Python" }, { "code": "# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({ 'City': ['Saharanpur', 'Meerut', 'Saharanpur', 'Saharanpur', 'Meerut'], 'Employes Name': ['Robin', 'Tushar', 'Rohan', 'Mukul', 'Manoj'], 'Salary': [21000, 22000, 21000, 22000, 22000]}) # print original dataframeprint(\"original dataframe: \")display(df) # counts Groupby valuedf = df.groupby(['City', 'Employes Name', 'Salary'] ).size().unstack(fill_value=0) # print dataframeprint(\"result: \")display(df)", "e": 2893, "s": 2387, "text": null }, { "code": null, "e": 2901, "s": 2893, "text": "Output:" }, { "code": null, "e": 2908, "s": 2901, "text": "Picked" }, { "code": null, "e": 2932, "s": 2908, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2955, "s": 2932, "text": "Python Pandas-exercise" }, { "code": null, "e": 2977, "s": 2955, "text": "Python pandas-groupby" }, { "code": null, "e": 2991, "s": 2977, "text": "Python-pandas" }, { "code": null, "e": 2998, "s": 2991, "text": "Python" } ]
Templates in C++ - GeeksQuiz
23 Oct, 2020 x = 1 count = 0 x = 1 count = 1 x = 1.1 count = 0 x = 1 count = 0 x = 1 count = 0 x = 1.1 count = 0 x = 1 count = 0 x = 1 count = 1 x = 1.1 count = 2 7 7.0 7.0 0 0 1 1 2 1 1 0 6 12 2 8 8 8 16 24 8 16 20 28 10 1 10000 256 1 1 #include <iostream> using namespace std; template < class T, int N > T fun (T arr[], int size) { if (size > N) cout << "Not possible"; T max = arr[0]; for (int i = 1; i < size; i++) if (max < arr[i]) max = arr[i]; return max; } int main () { int arr[] = {12, 3, 14}; cout << fun (arr, 3); } Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n23 Oct, 2020" }, { "code": null, "e": 29550, "s": 29498, "text": "x = 1 count = 0\n\nx = 1 count = 1\n\nx = 1.1 count = 0" }, { "code": null, "e": 29602, "s": 29550, "text": "x = 1 count = 0\n\nx = 1 count = 0\n\nx = 1.1 count = 0" }, { "code": null, "e": 29654, "s": 29602, "text": "x = 1 count = 0\n\nx = 1 count = 1\n\nx = 1.1 count = 2" }, { "code": null, "e": 29664, "s": 29654, "text": "7\n7.0\n7.0" }, { "code": null, "e": 29668, "s": 29664, "text": "0\n0" }, { "code": null, "e": 29672, "s": 29668, "text": "1\n1" }, { "code": null, "e": 29676, "s": 29672, "text": "2\n1" }, { "code": null, "e": 29680, "s": 29676, "text": "1\n0" }, { "code": null, "e": 29685, "s": 29680, "text": "6\n12" }, { "code": null, "e": 29689, "s": 29685, "text": "2\n8" }, { "code": null, "e": 29693, "s": 29689, "text": "8\n8" }, { "code": null, "e": 29699, "s": 29693, "text": "16\n24" }, { "code": null, "e": 29704, "s": 29699, "text": "8\n16" }, { "code": null, "e": 29710, "s": 29704, "text": "20\n28" }, { "code": null, "e": 29715, "s": 29710, "text": "10\n1" }, { "code": null, "e": 29725, "s": 29715, "text": "10000\n256" }, { "code": null, "e": 29729, "s": 29725, "text": "1\n1" }, { "code": null, "e": 30068, "s": 29729, "text": "#include <iostream>\nusing namespace std;\n\ntemplate < class T, int N >\n T fun (T arr[], int size)\n{\n if (size > N)\n cout << \"Not possible\";\n T max = arr[0];\n for (int i = 1; i < size; i++)\n if (max < arr[i])\n max = arr[i];\n return max;\n}\n\nint main ()\n{\n int arr[] = {12, 3, 14};\n cout << fun (arr, 3);\n}" } ]
Content editable change event in jQuery - GeeksforGeeks
24 Jul, 2019 In General, jQuery provides various function to handle selectors, selector properties and even documents, etc.Whereas here using jquery change event for content editable. jQuery Change Event:It occurs when the value of an element is changed also this event is fired immediately when the user makes a selection with the mouse or when the field loses focus. Syntax: $(selector).change(function callback); Content Editable:Content Editable is mainly a attribute for all HTML elements .When this attribute is true then that element will display editable content.When it is false the content editable disabled. Attribute: contenteditable="true" Example 1:Let’s take an example program to check the element is editable or has attribute “contenteditable” which is set to true or false using jQuery change event. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> div { padding: 20px; outline: none; } p { color: grey; outline: none; padding: 20px; } </style></head> <body> <div> <h1> Welcome to GeeksforGeeks </h1></div> <p contenteditable="true"> Welcome to GeeksforGeeks </p> <script> //checking div tag as attribute contenteditable $(document).ready(function() { $("div").change(function() { var conattr = $(this).attr('contenteditable'); if (typeof conattr !== typeof undefined && conattr !== false) { //if div tag as attribute contenteditable $(this).css('border', 'solid 2px red'); } else { //if doesn't have div tag as attribute contenteditable $(this).css({ "border": "solid 2px green", "border-radius": "34px" }).attr('contenteditable', 'true') } }).trigger("change"); }); //checking p tag as attribute contenteditable $(document).ready(function() { $("p").change(function() { var conattr = $(this).attr('contenteditable'); if (typeof conattr !== typeof undefined && conattr !== false) { //if p tag as attribute contenteditable $(this).css('border', 'solid 2px red'); } else { //if doesn't have p tag as attribute contenteditable $(this).css({ "border": "solid 2px green", "border-radius": "34px" }).attr('contenteditable', 'true') } }).trigger("change"); }); </script></body> </html> Output: Example 2:Let’s take an example program to make the element editable or non-editable by selecting the dropdown option using jQuery change event. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <style> select { border: 2px solid blue; border-radius: 15px; padding: 5px; outline: none; } p { border: 2px solid #c9c9c9; border-radius: 20px; padding: 15px; outline: none; background: #ffb; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <select name="element"> <option selected="selected" disabled> Select to Edit </option> <option value="true">Make Editable</option> <option value="false">Deny Editable</option> </select> <div></div> <script> $("select") .change(function() { var ele01 = "<p contenteditable='"; $("select option:selected").each(function() { ele01 += $(this).val() + "" + "'>select above to edit me</p>"; }); $("div").html(ele01); if ($("select").val() == "false" || $("select").val() == "") { $("p").css({ "font-weight": "bold", "color": "blue", "font-style": "italic", "cursor": "none" }); } else { $("p").css({ "color": "grey", "font-style": "italic" }); } }) .change(); </script></body> </html> Output: jQuery-Misc Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method How to get the value in an input text box using jQuery ? Difference Between JavaScript and jQuery QR Code Generator using HTML, CSS and jQuery 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25699, "s": 25671, "text": "\n24 Jul, 2019" }, { "code": null, "e": 25870, "s": 25699, "text": "In General, jQuery provides various function to handle selectors, selector properties and even documents, etc.Whereas here using jquery change event for content editable." }, { "code": null, "e": 26055, "s": 25870, "text": "jQuery Change Event:It occurs when the value of an element is changed also this event is fired immediately when the user makes a selection with the mouse or when the field loses focus." }, { "code": null, "e": 26063, "s": 26055, "text": "Syntax:" }, { "code": null, "e": 26103, "s": 26063, "text": "$(selector).change(function callback);\n" }, { "code": null, "e": 26306, "s": 26103, "text": "Content Editable:Content Editable is mainly a attribute for all HTML elements .When this attribute is true then that element will display editable content.When it is false the content editable disabled." }, { "code": null, "e": 26317, "s": 26306, "text": "Attribute:" }, { "code": null, "e": 26341, "s": 26317, "text": "contenteditable=\"true\"\n" }, { "code": null, "e": 26506, "s": 26341, "text": "Example 1:Let’s take an example program to check the element is editable or has attribute “contenteditable” which is set to true or false using jQuery change event." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> div { padding: 20px; outline: none; } p { color: grey; outline: none; padding: 20px; } </style></head> <body> <div> <h1> Welcome to GeeksforGeeks </h1></div> <p contenteditable=\"true\"> Welcome to GeeksforGeeks </p> <script> //checking div tag as attribute contenteditable $(document).ready(function() { $(\"div\").change(function() { var conattr = $(this).attr('contenteditable'); if (typeof conattr !== typeof undefined && conattr !== false) { //if div tag as attribute contenteditable $(this).css('border', 'solid 2px red'); } else { //if doesn't have div tag as attribute contenteditable $(this).css({ \"border\": \"solid 2px green\", \"border-radius\": \"34px\" }).attr('contenteditable', 'true') } }).trigger(\"change\"); }); //checking p tag as attribute contenteditable $(document).ready(function() { $(\"p\").change(function() { var conattr = $(this).attr('contenteditable'); if (typeof conattr !== typeof undefined && conattr !== false) { //if p tag as attribute contenteditable $(this).css('border', 'solid 2px red'); } else { //if doesn't have p tag as attribute contenteditable $(this).css({ \"border\": \"solid 2px green\", \"border-radius\": \"34px\" }).attr('contenteditable', 'true') } }).trigger(\"change\"); }); </script></body> </html>", "e": 28514, "s": 26506, "text": null }, { "code": null, "e": 28522, "s": 28514, "text": "Output:" }, { "code": null, "e": 28667, "s": 28522, "text": "Example 2:Let’s take an example program to make the element editable or non-editable by selecting the dropdown option using jQuery change event." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <style> select { border: 2px solid blue; border-radius: 15px; padding: 5px; outline: none; } p { border: 2px solid #c9c9c9; border-radius: 20px; padding: 15px; outline: none; background: #ffb; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <select name=\"element\"> <option selected=\"selected\" disabled> Select to Edit </option> <option value=\"true\">Make Editable</option> <option value=\"false\">Deny Editable</option> </select> <div></div> <script> $(\"select\") .change(function() { var ele01 = \"<p contenteditable='\"; $(\"select option:selected\").each(function() { ele01 += $(this).val() + \"\" + \"'>select above to edit me</p>\"; }); $(\"div\").html(ele01); if ($(\"select\").val() == \"false\" || $(\"select\").val() == \"\") { $(\"p\").css({ \"font-weight\": \"bold\", \"color\": \"blue\", \"font-style\": \"italic\", \"cursor\": \"none\" }); } else { $(\"p\").css({ \"color\": \"grey\", \"font-style\": \"italic\" }); } }) .change(); </script></body> </html>", "e": 30281, "s": 28667, "text": null }, { "code": null, "e": 30289, "s": 30281, "text": "Output:" }, { "code": null, "e": 30301, "s": 30289, "text": "jQuery-Misc" }, { "code": null, "e": 30308, "s": 30301, "text": "Picked" }, { "code": null, "e": 30315, "s": 30308, "text": "JQuery" }, { "code": null, "e": 30332, "s": 30315, "text": "Web Technologies" }, { "code": null, "e": 30430, "s": 30332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30439, "s": 30430, "text": "Comments" }, { "code": null, "e": 30452, "s": 30439, "text": "Old Comments" }, { "code": null, "e": 30525, "s": 30452, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30548, "s": 30525, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30605, "s": 30548, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 30646, "s": 30605, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 30691, "s": 30646, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 30733, "s": 30691, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30766, "s": 30733, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30828, "s": 30766, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30871, "s": 30828, "text": "How to fetch data from an API in ReactJS ?" } ]
Matplotlib - Subplots() Function
Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility wrapper and helps in creating common layouts of subplots, including the enclosing figure object, in a single call. Plt.subplots(nrows, ncols) The two integer arguments to this function specify the number of rows and columns of the subplot grid. The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2 columns and display 4 different plots in each subplot. import matplotlib.pyplot as plt fig,a = plt.subplots(2,2) import numpy as np x = np.arange(1,5) a[0][0].plot(x,x*x) a[0][0].set_title('square') a[0][1].plot(x,np.sqrt(x)) a[0][1].set_title('square root') a[1][0].plot(x,np.exp(x)) a[1][0].set_title('exp') a[1][1].plot(x,np.log10(x)) a[1][1].set_title('log') plt.show() The above line of code generates the following output − 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2723, "s": 2516, "text": "Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility wrapper and helps in creating common layouts of subplots, including the enclosing figure object, in a single call." }, { "code": null, "e": 2751, "s": 2723, "text": "Plt.subplots(nrows, ncols)\n" }, { "code": null, "e": 3089, "s": 2751, "text": "The two integer arguments to this function specify the number of rows and columns of the subplot grid. The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2 columns and display 4 different plots in each subplot." }, { "code": null, "e": 3409, "s": 3089, "text": "import matplotlib.pyplot as plt\nfig,a = plt.subplots(2,2)\nimport numpy as np\nx = np.arange(1,5)\na[0][0].plot(x,x*x)\na[0][0].set_title('square')\na[0][1].plot(x,np.sqrt(x))\na[0][1].set_title('square root')\na[1][0].plot(x,np.exp(x))\na[1][0].set_title('exp')\na[1][1].plot(x,np.log10(x))\na[1][1].set_title('log')\nplt.show()" }, { "code": null, "e": 3465, "s": 3409, "text": "The above line of code generates the following output −" }, { "code": null, "e": 3498, "s": 3465, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3515, "s": 3498, "text": " Abhilash Nelson" }, { "code": null, "e": 3548, "s": 3515, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 3583, "s": 3548, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3617, "s": 3583, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3652, "s": 3617, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3685, "s": 3652, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 3695, "s": 3685, "text": " Aipython" }, { "code": null, "e": 3730, "s": 3695, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3742, "s": 3730, "text": " Akbar Khan" }, { "code": null, "e": 3775, "s": 3742, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3782, "s": 3775, "text": " Anmol" }, { "code": null, "e": 3789, "s": 3782, "text": " Print" }, { "code": null, "e": 3800, "s": 3789, "text": " Add Notes" } ]
Angular Material - Toolbars
The md-toolbar, an Angular directive is used to show a toolbar which is normally an area above the content to show the title and the relevant buttons. The following table lists out the parameters and description of the different attributes of the md-toolbar. md-scroll-shrink This determines whether the header should shrink away as the user scrolls down, and reveal itself as the user scrolls up. for scrollShrink to work, the toolbar must be a sibling of an md-content element, placed before it. for scrollShrink to work, the toolbar must be a sibling of an md-content element, placed before it. The md-scroll-shrink attribute is only parsed on component initialization, it does not watch for scope changes. The md-scroll-shrink attribute is only parsed on component initialization, it does not watch for scope changes. md-shrink-speed-factor How much to change the speed of the toolbar's shrinking by. For example, if 0.25 is given then the toolbar will shrink at one fourth the rate at which the user scrolls down. By default, it is 0.5. The following example shows the use of toolbar. am_toolbar.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('toolbarController', toolbarController); function toolbarController ($scope) { var self = this; self.allContacts = loadContacts(); self.contacts = [self.allContacts[0]]; function loadContacts() { var contacts = [ 'Roberto Karlos', 'Bob Crestor', 'Nigel Rick', 'Narayana Garner' ]; return contacts.map(function (c, index) { var cParts = c.split(' '); var contact = { name: c, email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase() + '@example.com', image: 'http://lorempixel.com/50/50/people?' + index }; contact._lowername = contact.name.toLowerCase(); return contact; }); } } </script> </head> <body ng-app = "firstApplication"> <div id = "toolbarContainer" ng-controller = "toolbarController as ctrl" layout = "column" ng-cloak> <md-content> <md-toolbar md-scroll-shrink> <div class = "md-toolbar-tools"> <md-button class = "md-icon-button" aria-label = "Settings"> <md-icon class = "material-icons">menu</md-icon> </md-button> <h2> <span>Contacts</span> </h2> <span flex></span> <md-button class = "md-icon-button" aria-label = "More"> <md-icon class = "material-icons">more_vert</md-icon> </md-button> </div> </md-toolbar> <md-list> <md-subheader class = "md-no-sticky">Contacts</md-subheader> <md-list-item class = "md-2-line contact-item" ng-repeat = "(index, contact) in ctrl.allContacts" ng-if = "ctrl.contacts.indexOf(contact) < 0"> <img ng-src = "{{contact.image}}" class = "md-avatar" alt = "{{contact.name}}" /> <div class = "md-list-item-text compact"> <h3>{{contact.name}}</h3> <p>{{contact.email}}</p> </div> <md-divider ng-if = "!$last"></md-divider> </md-list-item> </md-list> <md-list> <md-subheader class = "md-no-sticky">Contacts (With Insets)</md-subheader> <md-list-item class = "md-2-line contact-item" ng-repeat = "(index, contact) in ctrl.allContacts" ng-if = "ctrl.contacts.indexOf(contact) < 0"> <img ng-src = "{{contact.image}}" class = "md-avatar" alt = "{{contact.name}}" /> <div class = "md-list-item-text compact"> <h3>{{contact.name}}</h3> <p>{{contact.email}}</p> </div> <md-divider md-inset ng-if = "!$last"></md-divider> </md-list-item> </md-list> </md-content> </div> </body> </html> Verify the result. {{contact.email}} {{contact.email}} 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2190, "text": "The md-toolbar, an Angular directive is used to show a toolbar which is normally an area above the content to show the title and the relevant buttons." }, { "code": null, "e": 2449, "s": 2341, "text": "The following table lists out the parameters and description of the different attributes of the md-toolbar." }, { "code": null, "e": 2466, "s": 2449, "text": "md-scroll-shrink" }, { "code": null, "e": 2588, "s": 2466, "text": "This determines whether the header should shrink away as the user scrolls down, and reveal itself as the user scrolls up." }, { "code": null, "e": 2688, "s": 2588, "text": "for scrollShrink to work, the toolbar must be a sibling of an md-content element, placed before it." }, { "code": null, "e": 2788, "s": 2688, "text": "for scrollShrink to work, the toolbar must be a sibling of an md-content element, placed before it." }, { "code": null, "e": 2900, "s": 2788, "text": "The md-scroll-shrink attribute is only parsed on component initialization, it does not watch for scope changes." }, { "code": null, "e": 3012, "s": 2900, "text": "The md-scroll-shrink attribute is only parsed on component initialization, it does not watch for scope changes." }, { "code": null, "e": 3035, "s": 3012, "text": "md-shrink-speed-factor" }, { "code": null, "e": 3232, "s": 3035, "text": "How much to change the speed of the toolbar's shrinking by. For example, if 0.25 is given then the toolbar will shrink at one fourth the rate at which the user scrolls down. By default, it is 0.5." }, { "code": null, "e": 3280, "s": 3232, "text": "The following example shows the use of toolbar." }, { "code": null, "e": 3295, "s": 3280, "text": "am_toolbar.htm" }, { "code": null, "e": 7793, "s": 3295, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('toolbarController', toolbarController);\n \n function toolbarController ($scope) { \n var self = this; \n self.allContacts = loadContacts();\n self.contacts = [self.allContacts[0]];\n \n function loadContacts() {\n var contacts = [\n 'Roberto Karlos',\n 'Bob Crestor',\n 'Nigel Rick',\n 'Narayana Garner' \n ];\n \n return contacts.map(function (c, index) {\n var cParts = c.split(' ');\n \n var contact = {\n name: c,\n email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase()\n + '@example.com',\n image: 'http://lorempixel.com/50/50/people?' + index\n };\n \n contact._lowername = contact.name.toLowerCase();\n return contact;\n });\n } \n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"toolbarContainer\" ng-controller = \"toolbarController as ctrl\"\n layout = \"column\" ng-cloak>\n <md-content>\n <md-toolbar md-scroll-shrink>\n <div class = \"md-toolbar-tools\">\n <md-button class = \"md-icon-button\" aria-label = \"Settings\">\n <md-icon class = \"material-icons\">menu</md-icon>\n </md-button>\n \n <h2>\n <span>Contacts</span>\n </h2>\n \n <span flex></span>\n <md-button class = \"md-icon-button\" aria-label = \"More\">\n <md-icon class = \"material-icons\">more_vert</md-icon>\n </md-button>\n </div>\n </md-toolbar>\n \n <md-list>\n <md-subheader class = \"md-no-sticky\">Contacts</md-subheader>\n <md-list-item class = \"md-2-line contact-item\"\n ng-repeat = \"(index, contact) in ctrl.allContacts\"\n ng-if = \"ctrl.contacts.indexOf(contact) < 0\">\n <img ng-src = \"{{contact.image}}\" class = \"md-avatar\"\n alt = \"{{contact.name}}\" />\n \n <div class = \"md-list-item-text compact\">\n <h3>{{contact.name}}</h3>\n <p>{{contact.email}}</p>\n </div>\n \n <md-divider ng-if = \"!$last\"></md-divider>\n </md-list-item>\n </md-list>\n \n <md-list>\n <md-subheader class = \"md-no-sticky\">Contacts (With Insets)</md-subheader>\n <md-list-item class = \"md-2-line contact-item\"\n ng-repeat = \"(index, contact) in ctrl.allContacts\"\n ng-if = \"ctrl.contacts.indexOf(contact) < 0\">\n <img ng-src = \"{{contact.image}}\" class = \"md-avatar\"\n alt = \"{{contact.name}}\" />\n <div class = \"md-list-item-text compact\">\n <h3>{{contact.name}}</h3>\n <p>{{contact.email}}</p>\n </div>\n <md-divider md-inset ng-if = \"!$last\"></md-divider>\n </md-list-item>\n </md-list>\n \n </md-content>\t \n </div>\n </body>\n</html>" }, { "code": null, "e": 7812, "s": 7793, "text": "Verify the result." }, { "code": null, "e": 7830, "s": 7812, "text": "{{contact.email}}" }, { "code": null, "e": 7848, "s": 7830, "text": "{{contact.email}}" }, { "code": null, "e": 7883, "s": 7848, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7897, "s": 7883, "text": " Anadi Sharma" }, { "code": null, "e": 7932, "s": 7897, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7946, "s": 7932, "text": " Anadi Sharma" }, { "code": null, "e": 7981, "s": 7946, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8001, "s": 7981, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8036, "s": 8001, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8053, "s": 8036, "text": " Frahaan Hussain" }, { "code": null, "e": 8086, "s": 8053, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 8098, "s": 8086, "text": " Senol Atac" }, { "code": null, "e": 8133, "s": 8098, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8145, "s": 8133, "text": " Senol Atac" }, { "code": null, "e": 8152, "s": 8145, "text": " Print" }, { "code": null, "e": 8163, "s": 8152, "text": " Add Notes" } ]
AngularJS | Data Binding - GeeksforGeeks
21 May, 2019 Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View. There are many types of bindings but we will focus on -:1) Interpolation2) Property Binding3) Event Binding4) Two-way Binding Interpolation:Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template. Syntax-: class="{{variable_name}}" Eg-:app.component.html <h3>Binding Types</h3><P>Interpolation</P><br><h5>Addition of 3 and 5 with Interpolation is {{3+5}}</h5><h5>Addition of 3 and 5 without Interpolation is 3+5</h5><h2>{{val}}</h2> app.component.ts import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { val: string;} Property Binding: Similar to Java, variables defined in the parent class can be inherited by child class that is templates in this case. The only difference between Interpolation and Property binding is that we should not store non-string values in variables while using interpolation. So if we have to store Boolean or other data types than use Property Binding. Syntax-: [class]="variable_name" app.component.html <h3>Binding Types</h3><p>Property Binding</p><input type="text" ng-bind="{{ Geeks }}"><br><h5>Learning Property binding on {{ Geeks }}</h5><img [src]="image" height="50px" weight="40px"> app.component.ts import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Geeks'; classtype ="text-danger"; Geeks= "GeeksforGeeks"; image="https://media.geeksforgeeks.org /wp-content/uploads/geeksforgeeks-6.png";} Output: Event Binding: An event is created whenever either a key is pressed or on a mouse click. Syntax: <button class="btn btn-block" (click)=showevent($event)>Event</button> showevent(event){ alert("Welcome to GeeksforGeeks"); } app.component.html <h3>Binding Types</h3><P>Event Binding</P><button class="btn btn-block" (click)="Clickme($event)"> Click Here</button> app.component.ts import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Geeks'; Clickme(event) { alert('Welcome to GeeksforGeeks'); }} Output: Two way Binding:In app.module.ts we have to include FormsModule in imports like the way given down also we have to import FormsModule. We have to include FormsModule since ngModel is not a property included in the project we develop using ng new project-name so we have to include it by importing this Module. import { FormsModule } from '@angular/forms'; imports: [ BrowserModule, FormsModule, AppRoutingModule, ], app.component.html <h3>Binding Types</h3><P>Two Way Binding</P><input type="text" placeholder="Enter text" [(ngModel)]="val"><br>{{ val }} app.component.ts import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { val: string;} Output: Picked AngularJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers Angular File Upload What is AOT and JIT Compiler in Angular ? Auth Guards in Angular 9/10/11 How to use <mat-chip-list> and <mat-chip> in Angular Material ? Angular | keyup event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to Display Spinner on the Screen till the data from the API loads using Angular 8 ? Angular 10 (blur) Event How to create module with Routing in Angular 9 ?
[ { "code": null, "e": 28296, "s": 28268, "text": "\n21 May, 2019" }, { "code": null, "e": 28601, "s": 28296, "text": "Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View. There are many types of bindings but we will focus on -:1) Interpolation2) Property Binding3) Event Binding4) Two-way Binding" }, { "code": null, "e": 28846, "s": 28601, "text": "Interpolation:Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template." }, { "code": null, "e": 28882, "s": 28846, "text": "Syntax-: class=\"{{variable_name}}\"\n" }, { "code": null, "e": 28905, "s": 28882, "text": "Eg-:app.component.html" }, { "code": "<h3>Binding Types</h3><P>Interpolation</P><br><h5>Addition of 3 and 5 with Interpolation is {{3+5}}</h5><h5>Addition of 3 and 5 without Interpolation is 3+5</h5><h2>{{val}}</h2>", "e": 29083, "s": 28905, "text": null }, { "code": null, "e": 29100, "s": 29083, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { val: string;}", "e": 29296, "s": 29100, "text": null }, { "code": null, "e": 29660, "s": 29296, "text": "Property Binding: Similar to Java, variables defined in the parent class can be inherited by child class that is templates in this case. The only difference between Interpolation and Property binding is that we should not store non-string values in variables while using interpolation. So if we have to store Boolean or other data types than use Property Binding." }, { "code": null, "e": 29694, "s": 29660, "text": "Syntax-: [class]=\"variable_name\"\n" }, { "code": null, "e": 29713, "s": 29694, "text": "app.component.html" }, { "code": "<h3>Binding Types</h3><p>Property Binding</p><input type=\"text\" ng-bind=\"{{ Geeks }}\"><br><h5>Learning Property binding on {{ Geeks }}</h5><img [src]=\"image\" height=\"50px\" weight=\"40px\">", "e": 29900, "s": 29713, "text": null }, { "code": null, "e": 29917, "s": 29900, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Geeks'; classtype =\"text-danger\"; Geeks= \"GeeksforGeeks\"; image=\"https://media.geeksforgeeks.org /wp-content/uploads/geeksforgeeks-6.png\";}", "e": 30259, "s": 29917, "text": null }, { "code": null, "e": 30267, "s": 30259, "text": "Output:" }, { "code": null, "e": 30356, "s": 30267, "text": "Event Binding: An event is created whenever either a key is pressed or on a mouse click." }, { "code": null, "e": 30364, "s": 30356, "text": "Syntax:" }, { "code": " <button class=\"btn btn-block\" (click)=showevent($event)>Event</button> showevent(event){ alert(\"Welcome to GeeksforGeeks\"); } ", "e": 30502, "s": 30364, "text": null }, { "code": null, "e": 30521, "s": 30502, "text": "app.component.html" }, { "code": "<h3>Binding Types</h3><P>Event Binding</P><button class=\"btn btn-block\" (click)=\"Clickme($event)\"> Click Here</button>", "e": 30643, "s": 30521, "text": null }, { "code": null, "e": 30660, "s": 30643, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'Geeks'; Clickme(event) { alert('Welcome to GeeksforGeeks'); }}", "e": 30920, "s": 30660, "text": null }, { "code": null, "e": 30928, "s": 30920, "text": "Output:" }, { "code": null, "e": 31238, "s": 30928, "text": "Two way Binding:In app.module.ts we have to include FormsModule in imports like the way given down also we have to import FormsModule. We have to include FormsModule since ngModel is not a property included in the project we develop using ng new project-name so we have to include it by importing this Module." }, { "code": null, "e": 31362, "s": 31238, "text": "import { FormsModule } from '@angular/forms';\n\n imports: [\n BrowserModule,\n FormsModule,\n AppRoutingModule,\n ],\n" }, { "code": null, "e": 31381, "s": 31362, "text": "app.component.html" }, { "code": "<h3>Binding Types</h3><P>Two Way Binding</P><input type=\"text\" placeholder=\"Enter text\" [(ngModel)]=\"val\"><br>{{ val }}", "e": 31501, "s": 31381, "text": null }, { "code": null, "e": 31518, "s": 31501, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { val: string;}", "e": 31714, "s": 31518, "text": null }, { "code": null, "e": 31722, "s": 31714, "text": "Output:" }, { "code": null, "e": 31729, "s": 31722, "text": "Picked" }, { "code": null, "e": 31739, "s": 31729, "text": "AngularJS" }, { "code": null, "e": 31837, "s": 31739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31846, "s": 31837, "text": "Comments" }, { "code": null, "e": 31859, "s": 31846, "text": "Old Comments" }, { "code": null, "e": 31903, "s": 31859, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 31923, "s": 31903, "text": "Angular File Upload" }, { "code": null, "e": 31965, "s": 31923, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 31996, "s": 31965, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 32060, "s": 31996, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 32082, "s": 32060, "text": "Angular | keyup event" }, { "code": null, "e": 32135, "s": 32082, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32223, "s": 32135, "text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?" }, { "code": null, "e": 32247, "s": 32223, "text": "Angular 10 (blur) Event" } ]
Koa.js - Routing
Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command. npm install --save koa-router Now that we have Koa-router installed, let’s look at a simple GET route example. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); // Define routes function *getMessage() { this.body = "Hello world!"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello". Our Koa app executes the callback function attached to this route and sends "Hello World!" as the response. We can also have multiple different methods at the same route. For example, var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); _.post('/hello', postMessage); function *getMessage() { this.body = "Hello world!"; }; function *postMessage() { this.body = "You just called the post method at '/hello'!\n"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); To test this request, open your terminal and use cURL to execute the following request curl -X POST "https://localhost:3000/hello" A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following − _.all('/test', allMessage); function *allMessage(){ this.body = "All HTTP calls regardless of the verb will get this response"; }; Print Add Notes Bookmark this page
[ { "code": null, "e": 2368, "s": 2106, "text": "Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command." }, { "code": null, "e": 2399, "s": 2368, "text": "npm install --save koa-router\n" }, { "code": null, "e": 2480, "s": 2399, "text": "Now that we have Koa-router installed, let’s look at a simple GET route example." }, { "code": null, "e": 2816, "s": 2480, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router(); //Instantiate the router\n_.get('/hello', getMessage); // Define routes\n\nfunction *getMessage() {\n this.body = \"Hello world!\";\n};\n\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 3035, "s": 2816, "text": "If we run our application and go to localhost:3000/hello, the server receives a get request at route \"/hello\". Our Koa app executes the callback function attached to this route and sends \"Hello World!\" as the response." }, { "code": null, "e": 3111, "s": 3035, "text": "We can also have multiple different methods at the same route. For example," }, { "code": null, "e": 3528, "s": 3111, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router(); //Instantiate the router\n\n_.get('/hello', getMessage);\n_.post('/hello', postMessage);\n\nfunction *getMessage() {\n\tthis.body = \"Hello world!\";\n};\nfunction *postMessage() {\n this.body = \"You just called the post method at '/hello'!\\n\";\n};\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 3615, "s": 3528, "text": "To test this request, open your terminal and use cURL to execute the following request" }, { "code": null, "e": 3660, "s": 3615, "text": "curl -X POST \"https://localhost:3000/hello\"\n" }, { "code": null, "e": 3829, "s": 3660, "text": "A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following −" }, { "code": null, "e": 3964, "s": 3829, "text": "_.all('/test', allMessage);\n\nfunction *allMessage(){\n this.body = \"All HTTP calls regardless of the verb will get this response\";\n};" }, { "code": null, "e": 3971, "s": 3964, "text": " Print" }, { "code": null, "e": 3982, "s": 3971, "text": " Add Notes" } ]
Binary to decimal and vice-versa in python - GeeksforGeeks
29 Jun, 2021 Write Python code for converting a decimal number to it’s binary equivalent and vice-versa. Example: From decimal to binary Input : 8 Output : 1 0 0 0 From binary to decimal Input : 100 Output : 4 Decimal to binary Keep calling conversion function with n/2 till n > 1, later perform n % 1 to get MSB of converted binary number. Example :- 7 1). 7/2 = Quotient = 3(greater than 1), Remainder = 1. 2). 3/2 = Quotient = 1(not greater than 1), Remainder = 1. 3). 1%2 = Remainder = 1. Therefore, answer is 111. Python3 # Function to print binary number for the# input decimal using recursiondef decimalToBinary(n): if(n > 1): # divide with integral result # (discard remainder) decimalToBinary(n//2) print(n%2, end=' ') # Driver codeif __name__ == '__main__': decimalToBinary(8) print("\n") decimalToBinary(18) print("\n") decimalToBinary(7) print("\n") Output: 1 0 0 0 1 0 0 1 0 1 1 1 Decimal to binary using bin(): Python3 # Function to convert Decimal number# to Binary number def decimalToBinary(n): return bin(n).replace("0b","") # Driver codeif __name__ == '__main__': print(decimalToBinary(8)) print(decimalToBinary(18)) print(decimalToBinary(7)) Output: 1000 10010 111 Binary to decimal Example -: 1011 1). Take modulo of given binary number with 10. (1011 % 10 = 1) 2). Multiply rem with 2 raised to the power it's position from right end. (1 * 2^0) Note that we start counting position with 0. 3). Add result with previously generated result. decimal = decimal + (1 * 2^0) 4). Update binary number by dividing it by 10. (1011 / 10 = 101) 5). Keep repeating upper steps till binary > 0. Final Conversion -: (1 * 2^3) + (0 * 2^2) + (1 * 2^1) + (1 * 2^0) = 11 Python3 # Function calculates the decimal equivalent# to given binary number def binaryToDecimal(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 print(decimal) # Driver codeif __name__ == '__main__': binaryToDecimal(100) binaryToDecimal(101) binaryToDecimal(1001) Output: 4 5 9 Binary to decimal using int(): Python3 # Function to convert Binary number# to Decimal number def binaryToDecimal(n): return int(n,2) # Driver codeif __name__ == '__main__': print(binaryToDecimal('100')) print(binaryToDecimal('101')) print(binaryToDecimal('1001')) Output: 4 5 9 This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. psil123 surindertarika1234 base-conversion Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24686, "s": 24658, "text": "\n29 Jun, 2021" }, { "code": null, "e": 24778, "s": 24686, "text": "Write Python code for converting a decimal number to it’s binary equivalent and vice-versa." }, { "code": null, "e": 24788, "s": 24778, "text": "Example: " }, { "code": null, "e": 24885, "s": 24788, "text": "From decimal to binary\nInput : 8\nOutput : 1 0 0 0\n\nFrom binary to decimal\nInput : 100\nOutput : 4" }, { "code": null, "e": 24905, "s": 24885, "text": "Decimal to binary " }, { "code": null, "e": 25199, "s": 24905, "text": "Keep calling conversion function with n/2 till n > 1,\nlater perform n % 1 to get MSB of converted binary number. \nExample :- 7\n1). 7/2 = Quotient = 3(greater than 1), Remainder = 1.\n2). 3/2 = Quotient = 1(not greater than 1), Remainder = 1.\n3). 1%2 = Remainder = 1.\nTherefore, answer is 111." }, { "code": null, "e": 25207, "s": 25199, "text": "Python3" }, { "code": "# Function to print binary number for the# input decimal using recursiondef decimalToBinary(n): if(n > 1): # divide with integral result # (discard remainder) decimalToBinary(n//2) print(n%2, end=' ') # Driver codeif __name__ == '__main__': decimalToBinary(8) print(\"\\n\") decimalToBinary(18) print(\"\\n\") decimalToBinary(7) print(\"\\n\")", "e": 25604, "s": 25207, "text": null }, { "code": null, "e": 25613, "s": 25604, "text": "Output: " }, { "code": null, "e": 25640, "s": 25613, "text": "1 0 0 0 \n1 0 0 1 0 \n1 1 1 " }, { "code": null, "e": 25672, "s": 25640, "text": "Decimal to binary using bin(): " }, { "code": null, "e": 25680, "s": 25672, "text": "Python3" }, { "code": "# Function to convert Decimal number# to Binary number def decimalToBinary(n): return bin(n).replace(\"0b\",\"\") # Driver codeif __name__ == '__main__': print(decimalToBinary(8)) print(decimalToBinary(18)) print(decimalToBinary(7))", "e": 25921, "s": 25680, "text": null }, { "code": null, "e": 25930, "s": 25921, "text": "Output: " }, { "code": null, "e": 25945, "s": 25930, "text": "1000\n10010\n111" }, { "code": null, "e": 25964, "s": 25945, "text": "Binary to decimal " }, { "code": null, "e": 26481, "s": 25964, "text": "Example -: 1011\n1). Take modulo of given binary number with 10. \n (1011 % 10 = 1)\n2). Multiply rem with 2 raised to the power\n it's position from right end. \n (1 * 2^0)\n Note that we start counting position with 0. \n3). Add result with previously generated result.\n decimal = decimal + (1 * 2^0)\n4). Update binary number by dividing it by 10.\n (1011 / 10 = 101)\n5). Keep repeating upper steps till binary > 0.\n\nFinal Conversion -: (1 * 2^3) + (0 * 2^2) +\n (1 * 2^1) + (1 * 2^0) = 11" }, { "code": null, "e": 26489, "s": 26481, "text": "Python3" }, { "code": "# Function calculates the decimal equivalent# to given binary number def binaryToDecimal(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 print(decimal) # Driver codeif __name__ == '__main__': binaryToDecimal(100) binaryToDecimal(101) binaryToDecimal(1001)", "e": 26910, "s": 26489, "text": null }, { "code": null, "e": 26919, "s": 26910, "text": "Output: " }, { "code": null, "e": 26925, "s": 26919, "text": "4\n5\n9" }, { "code": null, "e": 26957, "s": 26925, "text": "Binary to decimal using int(): " }, { "code": null, "e": 26965, "s": 26957, "text": "Python3" }, { "code": "# Function to convert Binary number# to Decimal number def binaryToDecimal(n): return int(n,2) # Driver codeif __name__ == '__main__': print(binaryToDecimal('100')) print(binaryToDecimal('101')) print(binaryToDecimal('1001'))", "e": 27204, "s": 26965, "text": null }, { "code": null, "e": 27213, "s": 27204, "text": "Output: " }, { "code": null, "e": 27219, "s": 27213, "text": "4\n5\n9" }, { "code": null, "e": 27647, "s": 27219, "text": "This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27655, "s": 27647, "text": "psil123" }, { "code": null, "e": 27674, "s": 27655, "text": "surindertarika1234" }, { "code": null, "e": 27690, "s": 27674, "text": "base-conversion" }, { "code": null, "e": 27697, "s": 27690, "text": "Python" }, { "code": null, "e": 27795, "s": 27697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27804, "s": 27795, "text": "Comments" }, { "code": null, "e": 27817, "s": 27804, "text": "Old Comments" }, { "code": null, "e": 27835, "s": 27817, "text": "Python Dictionary" }, { "code": null, "e": 27870, "s": 27835, "text": "Read a file line by line in Python" }, { "code": null, "e": 27892, "s": 27870, "text": "Enumerate() in Python" }, { "code": null, "e": 27924, "s": 27892, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27954, "s": 27924, "text": "Iterate over a list in Python" }, { "code": null, "e": 27996, "s": 27954, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28022, "s": 27996, "text": "Python String | replace()" }, { "code": null, "e": 28065, "s": 28022, "text": "Python program to convert a list to string" }, { "code": null, "e": 28109, "s": 28065, "text": "Reading and Writing to text files in Python" } ]
D3.js | d3.values() Function - GeeksforGeeks
28 Jun, 2019 The d3.values() function in D3.js is used to return an array containing the property values of the specified object or an associative array. Syntax: d3.values(object) Parameters: This function accepts single parameter object which contains the key, value pairs. Return Value: It returns the values of the given object. Below programs illustrate the d3.values() function in D3.js: Example 1: <!DOCTYPE html><html> <head> <title> d3.values() function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <script> // Initialising an object var month = { "January": 1, "February": 2, "March": 3, "April": 4 }; // Calling the d3.values() function A = d3.values(month); // Getting the values of the given object document.write(A); </script></body> </html> Output: 1, 2, 3, 4 Example 2: <!DOCTYPE html><html> <head> <title> d3.values() function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <script> // Initialising an object var month = { "GeeksforGeeks": 0, "Geeks": 2, "Geek": 3, "gfg": 4 }; // Calling the d3.values() function A = d3.values(month); // Getting the values of the given object document.write(A); </script></body> </html> Output: 0, 2, 3, 4 Reference: https://devdocs.io/d3~5/d3-collection#values D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24222, "s": 24194, "text": "\n28 Jun, 2019" }, { "code": null, "e": 24363, "s": 24222, "text": "The d3.values() function in D3.js is used to return an array containing the property values of the specified object or an associative array." }, { "code": null, "e": 24371, "s": 24363, "text": "Syntax:" }, { "code": null, "e": 24389, "s": 24371, "text": "d3.values(object)" }, { "code": null, "e": 24484, "s": 24389, "text": "Parameters: This function accepts single parameter object which contains the key, value pairs." }, { "code": null, "e": 24541, "s": 24484, "text": "Return Value: It returns the values of the given object." }, { "code": null, "e": 24602, "s": 24541, "text": "Below programs illustrate the d3.values() function in D3.js:" }, { "code": null, "e": 24613, "s": 24602, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> d3.values() function </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body> <script> // Initialising an object var month = { \"January\": 1, \"February\": 2, \"March\": 3, \"April\": 4 }; // Calling the d3.values() function A = d3.values(month); // Getting the values of the given object document.write(A); </script></body> </html> ", "e": 25168, "s": 24613, "text": null }, { "code": null, "e": 25176, "s": 25168, "text": "Output:" }, { "code": null, "e": 25188, "s": 25176, "text": "1, 2, 3, 4\n" }, { "code": null, "e": 25199, "s": 25188, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> d3.values() function </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body> <script> // Initialising an object var month = { \"GeeksforGeeks\": 0, \"Geeks\": 2, \"Geek\": 3, \"gfg\": 4 }; // Calling the d3.values() function A = d3.values(month); // Getting the values of the given object document.write(A); </script></body> </html> ", "e": 25755, "s": 25199, "text": null }, { "code": null, "e": 25763, "s": 25755, "text": "Output:" }, { "code": null, "e": 25775, "s": 25763, "text": "0, 2, 3, 4\n" }, { "code": null, "e": 25831, "s": 25775, "text": "Reference: https://devdocs.io/d3~5/d3-collection#values" }, { "code": null, "e": 25837, "s": 25831, "text": "D3.js" }, { "code": null, "e": 25848, "s": 25837, "text": "JavaScript" }, { "code": null, "e": 25865, "s": 25848, "text": "Web Technologies" }, { "code": null, "e": 25963, "s": 25865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25972, "s": 25963, "text": "Comments" }, { "code": null, "e": 25985, "s": 25972, "text": "Old Comments" }, { "code": null, "e": 26030, "s": 25985, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26091, "s": 26030, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26163, "s": 26091, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26209, "s": 26163, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 26250, "s": 26209, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26292, "s": 26250, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26325, "s": 26292, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26368, "s": 26325, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26430, "s": 26368, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
JavaScript Union of two objects
We have one object like this − const obj1 = { name: " ", email: " " }; and another like this − const obj2 = { name: ['x'], email: ['y']}; We are required to write a JavaScript function that takes in two such objects. and want the output to be the union like this − const output = { name: {" ", [x]}, email: {" ", [y]} }; The code for this will be − const obj1 = { name: " ", email: " " }; const obj2 = { name: ['x'], email: ['y']}; const objectUnion = (obj1 = {}, obj2 = {}) => { const obj3 = { name:[], email:[] }; for(let i in obj1) { obj3[i].push(obj1[i]); } for(let i in obj2) { obj3[i].push(obj2[i]); } return obj3; }; console.log(objectUnion(obj1, obj2)); And the output in the console will be − { name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }
[ { "code": null, "e": 1093, "s": 1062, "text": "We have one object like this −" }, { "code": null, "e": 1133, "s": 1093, "text": "const obj1 = { name: \" \", email: \" \" };" }, { "code": null, "e": 1157, "s": 1133, "text": "and another like this −" }, { "code": null, "e": 1200, "s": 1157, "text": "const obj2 = { name: ['x'], email: ['y']};" }, { "code": null, "e": 1327, "s": 1200, "text": "We are required to write a JavaScript function that takes in two such objects. and want the output to be the union like this −" }, { "code": null, "e": 1383, "s": 1327, "text": "const output = { name: {\" \", [x]}, email: {\" \", [y]} };" }, { "code": null, "e": 1411, "s": 1383, "text": "The code for this will be −" }, { "code": null, "e": 1769, "s": 1411, "text": "const obj1 = { name: \" \", email: \" \" };\nconst obj2 = { name: ['x'], email: ['y']};\nconst objectUnion = (obj1 = {}, obj2 = {}) => {\n const obj3 = {\n name:[],\n email:[]\n };\n for(let i in obj1) {\n obj3[i].push(obj1[i]);\n }\n for(let i in obj2) {\n obj3[i].push(obj2[i]);\n }\n return obj3;\n};\nconsole.log(objectUnion(obj1, obj2));" }, { "code": null, "e": 1809, "s": 1769, "text": "And the output in the console will be −" }, { "code": null, "e": 1861, "s": 1809, "text": "{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }" } ]
How to disable future dates in JavaScript Datepicker?
In order to disable future dates, you need to use maxDate and set the current date. Following is the JavaScript code − Live Demo <!DOCTYPE html> <html lang="en"> <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> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>The selected date is as follows: <input type="text" class="disableFuturedate"></p> <script> $(document).ready(function () { var currentDate = new Date(); $('.disableFuturedate').datepicker({ format: 'dd/mm/yyyy', autoclose:true, endDate: "currentDate", maxDate: currentDate }).on('changeDate', function (ev) { $(this).datepicker('hide'); }); $('.disableFuturedate').keyup(function () { if (this.value.match(/[^0-9]/g)) { this.value = this.value.replace(/[^0-9^-]/g, ''); } }); }); </script> </body> </html> In order to run the above program, I have saved this file with the name index.html. Right click on this file and select option open with live server. This will run in any modern web browser automatically − After that, click the mouse on text box, that will display the date picker as in the below screenshot −
[ { "code": null, "e": 1181, "s": 1062, "text": "In order to disable future dates, you need to use maxDate and set the current date. Following is the JavaScript code −" }, { "code": null, "e": 1192, "s": 1181, "text": " Live Demo" }, { "code": null, "e": 2201, "s": 1192, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<link rel=\"stylesheet\" href=\"//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<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n</head>\n<body>\n<p>The selected date is as follows: <input type=\"text\" class=\"disableFuturedate\"></p>\n<script>\n $(document).ready(function () {\n var currentDate = new Date();\n $('.disableFuturedate').datepicker({\n format: 'dd/mm/yyyy',\n autoclose:true,\n endDate: \"currentDate\",\n maxDate: currentDate\n }).on('changeDate', function (ev) {\n $(this).datepicker('hide');\n });\n $('.disableFuturedate').keyup(function () {\n if (this.value.match(/[^0-9]/g)) {\n this.value = this.value.replace(/[^0-9^-]/g, '');\n }\n });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2351, "s": 2201, "text": "In order to run the above program, I have saved this file with the name index.html. Right click on this file and select option open with live server." }, { "code": null, "e": 2407, "s": 2351, "text": "This will run in any modern web browser automatically −" }, { "code": null, "e": 2511, "s": 2407, "text": "After that, click the mouse on text box, that will display the date picker as in the below\nscreenshot −" } ]
How to implementing START_STICKY for a service?
Before getting into an example, we should know what service is in android. Service is going to do back ground operation without interacting with UI and it works even after activity destroy. START_STICKY - If service is started with START_STICKY return type, it going to work in back ground even if activity is not foreground if android forcefully closed service due to memory problem or some other cases, it will restart service without interaction of the user. This example demonstrates How to implementing START_STICKY for a service. 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:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Start Service" android:textSize = "25sp" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken text view, when user click on text view, it will start service and stop service. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView text = findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isMyServiceRunning(service.class)) { text.setText("Stoped"); stopService(new Intent(MainActivity.this, service.class)); } else { text.setText("Started"); startService(new Intent(MainActivity.this, service.class)); } } }); } private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } } In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code – package com.example.andy.myapplication; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Build; import android.os.IBinder; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; public class service extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); } @TargetApi(Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Notification Service started by user.", Toast.LENGTH_LONG).show(); Log.d("Tutorialspoint.com","Services is working background"); return START_STICKY; } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show(); } } In the above code we have called START_STICKY, now check for service information as shown below – Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <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> <service android:name = ".service"/> </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 – In the above result is an initial screen, Click on Text view, it will start Notification service as shown below – In the above result, service is startd now click on text view, it will stop notification service as shown below - Click here to download the project code
[ { "code": null, "e": 1252, "s": 1062, "text": "Before getting into an example, we should know what service is in android. Service is going to do back ground operation without interacting with UI and it works even after activity destroy." }, { "code": null, "e": 1525, "s": 1252, "text": "START_STICKY - If service is started with START_STICKY return type, it going to work in back ground even if activity is not foreground if android forcefully closed service due to memory problem or some other cases, it will restart service without interaction of the user." }, { "code": null, "e": 1599, "s": 1525, "text": "This example demonstrates How to implementing START_STICKY for a service." }, { "code": null, "e": 1728, "s": 1599, "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": 1793, "s": 1728, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2634, "s": 1793, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout 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:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\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": 2748, "s": 2634, "text": "In the above code, we have taken text view, when user click on text view, it will start service and stop service." }, { "code": null, "e": 2805, "s": 2748, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4236, "s": 2805, "text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (isMyServiceRunning(service.class)) {\n text.setText(\"Stoped\");\n stopService(new Intent(MainActivity.this, service.class));\n } else {\n text.setText(\"Started\");\n startService(new Intent(MainActivity.this, service.class));\n }\n }\n });\n }\n private boolean isMyServiceRunning(Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n}" }, { "code": null, "e": 4430, "s": 4236, "text": "In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –" }, { "code": null, "e": 5786, "s": 4430, "text": "package com.example.andy.myapplication;\nimport android.annotation.TargetApi;\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.media.MediaPlayer;\nimport android.os.Build;\nimport android.os.IBinder;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.NotificationCompat;\nimport android.util.Log;\nimport android.widget.Toast;\npublic class service extends Service {\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n public void onCreate() {\n super.onCreate();\n }\n @TargetApi(Build.VERSION_CODES.O)\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Toast.makeText(this, \"Notification Service started by user.\", Toast.LENGTH_LONG).show();\n Log.d(\"Tutorialspoint.com\",\"Services is working background\");\n return START_STICKY;\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n public void onDestroy() {\n super.onDestroy();\n Toast.makeText(this, \"Notification Service destroyed by user.\", Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 5884, "s": 5786, "text": "In the above code we have called START_STICKY, now check for service information as shown below –" }, { "code": null, "e": 5932, "s": 5884, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 6689, "s": 5932, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\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 <service android:name = \".service\"/>\n </application>\n</manifest>" }, { "code": null, "e": 7036, "s": 6689, "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": 7150, "s": 7036, "text": "In the above result is an initial screen, Click on Text view, it will start Notification service as shown below –" }, { "code": null, "e": 7264, "s": 7150, "text": "In the above result, service is startd now click on text view, it will stop notification service as shown below -" }, { "code": null, "e": 7304, "s": 7264, "text": "Click here to download the project code" } ]
Accepting date strings (MM-dd-yyyy format) using Java regex?
The following is the regular expression to match the date in the dd-MM-yyyy format. ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$ To match a date in a string in that format. Compile the above expression of the compile() method of the Pattern class. Compile the above expression of the compile() method of the Pattern class. Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class. Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class. The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data. The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data. import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatchingDate { public static void main(String[] args) { String date = "01/12/2019"; String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(date); boolean bool = matcher.matches(); if(bool) { System.out.println("Date is valid"); } else { System.out.println("Date is not valid"); } } } Date is valid The matches() method of the String class accepts a regular expression and matches the current string with it and returns true in case of a match and else returns false. Therefore, to verify if the given date (in string format) is in the required format − Get the date string. Invoke the matches() method on it by passing the above regular expression as a parameter to it. import java.util.Scanner; public class Just { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.nextLine(); System.out.println("Enter your Date of birth: "); String dob = sc.nextLine(); //Regular expression to accept date in MM-DD-YYY format String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; boolean result = dob.matches(regex); if(result) { System.out.println("Given date of birth is valid"); } else { System.out.println("Given date of birth is not valid"); } } } Enter your name: Janaki Enter your Date of birth: 26/09/1989 Given date of birth is not valid Enter your name: Janaki Enter your Date of birth: 09/26/1989 Given date of birth is valid
[ { "code": null, "e": 1146, "s": 1062, "text": "The following is the regular expression to match the date in the dd-MM-yyyy format." }, { "code": null, "e": 1198, "s": 1146, "text": "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$" }, { "code": null, "e": 1242, "s": 1198, "text": "To match a date in a string in that format." }, { "code": null, "e": 1317, "s": 1242, "text": "Compile the above expression of the compile() method of the Pattern class." }, { "code": null, "e": 1392, "s": 1317, "text": "Compile the above expression of the compile() method of the Pattern class." }, { "code": null, "e": 1512, "s": 1392, "text": "Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class." }, { "code": null, "e": 1632, "s": 1512, "text": "Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class." }, { "code": null, "e": 1780, "s": 1632, "text": "The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data." }, { "code": null, "e": 1928, "s": 1780, "text": "The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data." }, { "code": null, "e": 2538, "s": 1928, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MatchingDate {\n public static void main(String[] args) {\n String date = \"01/12/2019\";\n String regex = \"^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(date);\n boolean bool = matcher.matches();\n if(bool) {\n System.out.println(\"Date is valid\");\n } else {\n System.out.println(\"Date is not valid\");\n }\n }\n}" }, { "code": null, "e": 2552, "s": 2538, "text": "Date is valid" }, { "code": null, "e": 2807, "s": 2552, "text": "The matches() method of the String class accepts a regular expression and matches the current string with it and returns true in case of a match and else returns false. Therefore, to verify if the given date (in string format) is in the required format −" }, { "code": null, "e": 2828, "s": 2807, "text": "Get the date string." }, { "code": null, "e": 2924, "s": 2828, "text": "Invoke the matches() method on it by passing the above regular expression as a parameter to it." }, { "code": null, "e": 3585, "s": 2924, "text": "import java.util.Scanner;\npublic class Just {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.nextLine();\n System.out.println(\"Enter your Date of birth: \");\n String dob = sc.nextLine();\n //Regular expression to accept date in MM-DD-YYY format\n String regex = \"^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$\";\n boolean result = dob.matches(regex);\n if(result) {\n System.out.println(\"Given date of birth is valid\");\n } else {\n System.out.println(\"Given date of birth is not valid\");\n }\n }\n}" }, { "code": null, "e": 3679, "s": 3585, "text": "Enter your name:\nJanaki\nEnter your Date of birth:\n26/09/1989\nGiven date of birth is not valid" }, { "code": null, "e": 3769, "s": 3679, "text": "Enter your name:\nJanaki\nEnter your Date of birth:\n09/26/1989\nGiven date of birth is valid" } ]
What is the difference between Microtask Queue and Callback Queue in asynchronous JavaScript ? - GeeksforGeeks
27 Jan, 2022 To know the difference between Microtask Queue and Callback Queue, we need to have a clear idea of how does asynchronous JavaScript gets executed and what are the roles that Microtask Queue and Callback Queue play. Functions or operations running parallel with the other functions or operations are called asynchronous functions or operations in JavaScript. Asynchronous JavaScript code requires Callback functions that get executed later after the desired time. Example: Below code illustrates the use of setTimeout() function in JavaScript. Javascript <script> setTimeout(function greet() { console.log("Welcome to GeeksforGeeks!"); }, 2000);</script> Now, after this desired time, the code needs to be passed to the Call Stack, but this Call Stack doesn’t provide a timer by which we can delay the execution of the code. So, it uses the help of a web API setTimeout() which is available in the window global object in the browser. After a certain time period, Call Stack gets the code through Event Loop which fetches the Callback functions to Call Stack. But, Callback functions can’t directly go to the Event loop. So, here comes the role of Microtask Queue and Callback Queue. These Queues work as a mediator, once the timer gets expired the callback functions are put inside these queues serially. And whenever the Call stack is empty, the event loop fetches them to Call Stack in FIFO order. But, we need Microtask Queue and Callback Queue for different purposes. Let’s see the comparison between them. Callback Queue: After the timer gets expired, the callback function is put inside the Callback Queue, and the Event Loop checks if the Call Stack is empty and if empty, pushes the callback function from Callback Queue to Call Stack and the callback function gets removed from the Callback Queue. Then the Call Stack creates an Execution Context and executes it. Microtask Queue: Microtask Queue is like the Callback Queue, but Microtask Queue has higher priority. All the callback functions coming through Promises and Mutation Observer will go inside the Microtask Queue. For example, in the case of .fetch(), the callback function gets to the Microtask Queue. Promise handling always has higher priority so the JavaScript engine executes all the tasks from Microtask Queue and then moves to the Callback Queue. bitwa lexjs javascript-basics JavaScript-ES JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n27 Jan, 2022" }, { "code": null, "e": 25124, "s": 24909, "text": "To know the difference between Microtask Queue and Callback Queue, we need to have a clear idea of how does asynchronous JavaScript gets executed and what are the roles that Microtask Queue and Callback Queue play." }, { "code": null, "e": 25373, "s": 25124, "text": "Functions or operations running parallel with the other functions or operations are called asynchronous functions or operations in JavaScript. Asynchronous JavaScript code requires Callback functions that get executed later after the desired time. " }, { "code": null, "e": 25453, "s": 25373, "text": "Example: Below code illustrates the use of setTimeout() function in JavaScript." }, { "code": null, "e": 25464, "s": 25453, "text": "Javascript" }, { "code": "<script> setTimeout(function greet() { console.log(\"Welcome to GeeksforGeeks!\"); }, 2000);</script>", "e": 25569, "s": 25464, "text": null }, { "code": null, "e": 26035, "s": 25569, "text": "Now, after this desired time, the code needs to be passed to the Call Stack, but this Call Stack doesn’t provide a timer by which we can delay the execution of the code. So, it uses the help of a web API setTimeout() which is available in the window global object in the browser. After a certain time period, Call Stack gets the code through Event Loop which fetches the Callback functions to Call Stack. But, Callback functions can’t directly go to the Event loop." }, { "code": null, "e": 26316, "s": 26035, "text": "So, here comes the role of Microtask Queue and Callback Queue. These Queues work as a mediator, once the timer gets expired the callback functions are put inside these queues serially. And whenever the Call stack is empty, the event loop fetches them to Call Stack in FIFO order. " }, { "code": null, "e": 26427, "s": 26316, "text": "But, we need Microtask Queue and Callback Queue for different purposes. Let’s see the comparison between them." }, { "code": null, "e": 26791, "s": 26427, "text": "Callback Queue: After the timer gets expired, the callback function is put inside the Callback Queue, and the Event Loop checks if the Call Stack is empty and if empty, pushes the callback function from Callback Queue to Call Stack and the callback function gets removed from the Callback Queue. Then the Call Stack creates an Execution Context and executes it. " }, { "code": null, "e": 27242, "s": 26791, "text": "Microtask Queue: Microtask Queue is like the Callback Queue, but Microtask Queue has higher priority. All the callback functions coming through Promises and Mutation Observer will go inside the Microtask Queue. For example, in the case of .fetch(), the callback function gets to the Microtask Queue. Promise handling always has higher priority so the JavaScript engine executes all the tasks from Microtask Queue and then moves to the Callback Queue." }, { "code": null, "e": 27248, "s": 27242, "text": "bitwa" }, { "code": null, "e": 27254, "s": 27248, "text": "lexjs" }, { "code": null, "e": 27272, "s": 27254, "text": "javascript-basics" }, { "code": null, "e": 27286, "s": 27272, "text": "JavaScript-ES" }, { "code": null, "e": 27307, "s": 27286, "text": "JavaScript-Questions" }, { "code": null, "e": 27318, "s": 27307, "text": "JavaScript" }, { "code": null, "e": 27335, "s": 27318, "text": "Web Technologies" }, { "code": null, "e": 27433, "s": 27335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27442, "s": 27433, "text": "Comments" }, { "code": null, "e": 27455, "s": 27442, "text": "Old Comments" }, { "code": null, "e": 27516, "s": 27455, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27557, "s": 27516, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27611, "s": 27557, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27651, "s": 27611, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27713, "s": 27651, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27769, "s": 27713, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27802, "s": 27769, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27864, "s": 27802, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27907, "s": 27864, "text": "How to fetch data from an API in ReactJS ?" } ]
C++ Basic Data types | Practice | GeeksforGeeks
Given a String S. Find out which of the following basic C++ data types it represents and it's size (in bytes). The possible data types are: 1. Integer 2. Float 3. Double 4. Character Example 1: Input: S=a output: 1 Explanation: The string clearly represents char and thus the size of char is displayed. Example 2: Input S=98.45685456 Output: 8 Explanation: The string represents Double. Your Task: You don't need to read input or print anything. Your task is to complete the function BasicDataType() which takes String S as input parameter and displays the size (in bytes) of the datatype it represents. Expected Time Complexity:O(N) Expected Auxillary Space:O(1) Constraints: 1<=|S|<=10 0 arajkakabashi1 week ago tung 0 abhijeetkumarsingh2972 weeks ago Why the compiler is expecting output ‘4’ for the input ‘7.9’? 7.9 is a double! 0 kaloyankostovbg1 month ago class Solution { public: int BasicDataType(std::string s) { if (!isdigit(s[0]) && s.size() == 1) { return 1; // char } if (s.find('.') == -1) { return 4; // int } while (s[0] == '0') { s=s.substr(1); } auto result = double(); auto i = std::istringstream(s); i >> result; if ((result < 1.5E-45 || result > 3.4E+38) || s.substr(s.find('.')).size() > 6) return 8; // double else return 4; // float } }; -1 rahulsingh110582 months ago class Solution { public: int BasicDataType(string s) { // code here int len=s.length(),datasize; int i=0,temp=0; if((s[i]>='0' && s[i]<='9')|| s[i]=='.') { datasize=4; for(i=0;i<len;i++) { if(s[i]=='.') { datasize=4; temp=len-(i+1); break; } } if(temp>=6) { datasize=8; } } else { datasize=1; } return datasize; }}; 0 saurabhkumarmahra2 months ago #include<iostream> using namespace std; int main() { char a; cout<<"The size of the variable is "<<sizeof(a)<<endl; } -1 mdsaif04052 months ago C++ int BasicDataType(string s) { int len = s.length(), size; if (len == 1) { if (isdigit(s[0])) size = 4; else size = 1; } else { int flag = 0; for (int i = 0; i < len; i++) { if (s[i] == '.') { flag = 1; int j = len - i + 1; if (j > 7) size = 8; else size = 4; } } if (!flag) size = 4; } return size; } 0 2017chb10404 months ago if (s.size() == 1) { if ((int (s[0]) - '0')<= 9) { /* code */ return 4; } else { return 1; } } else { for (int i = 0; i < s.size(); ++i) { if (s[i] == '.') { if ((s.size() - (i + 1)) >= 6) { /* code */ // k= "double"; return 8; } else { // k= "float"; return 4; } } else if (i == (s.length() - 1)) { return 4; } else { continue; } } } -5 dakshagrawaldlp4 months ago #include<iostream> using namespace std; int main(){ double s; s=98.45685456; cout<<sizeof(s)<<endl; return 0; } 0 dakshagrawaldlp4 months ago #include<iostream> using namespace std; int main(){ char a,s; s=a; cout<< "Size of s: " <<sizeof(s)<<endl; return 0; } +2 dkaman794 months ago class Solution { public: int BasicDataType(string S) { int l = S.length(), ans; if (l == 1) { //checking if S is integer of size 1 if (isdigit(S[0])) ans = 4; else ans = 1; } else { int flag = 0; for (int i = 0; i < l; i++) { //checking whether S is integer or float/double if (S[i] == '.') { flag = 1; int j = l - i + 1; //checking whether S is double if (j > 7) ans = 8; else ans = 4; } } if (!flag) ans = 4; } return ans; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 409, "s": 226, "text": "Given a String S. Find out which of the following basic C++ data types it represents and it's size (in bytes).\nThe possible data types are:\n1. Integer\n2. Float\n3. Double\n4. Character" }, { "code": null, "e": 420, "s": 409, "text": "Example 1:" }, { "code": null, "e": 530, "s": 420, "text": "Input:\nS=a\noutput:\n1\nExplanation:\nThe string clearly represents char \nand thus the size of char is displayed." }, { "code": null, "e": 541, "s": 530, "text": "Example 2:" }, { "code": null, "e": 616, "s": 541, "text": "Input\nS=98.45685456\nOutput: \n8\nExplanation:\nThe string represents Double.\n" }, { "code": null, "e": 923, "s": 616, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function BasicDataType() which takes String S as input parameter and displays the size (in bytes) of the datatype it represents. \n\nExpected Time Complexity:O(N)\nExpected Auxillary Space:O(1)\n\nConstraints:\n1<=|S|<=10" }, { "code": null, "e": 925, "s": 923, "text": "0" }, { "code": null, "e": 949, "s": 925, "text": "arajkakabashi1 week ago" }, { "code": null, "e": 954, "s": 949, "text": "tung" }, { "code": null, "e": 956, "s": 954, "text": "0" }, { "code": null, "e": 989, "s": 956, "text": "abhijeetkumarsingh2972 weeks ago" }, { "code": null, "e": 1068, "s": 989, "text": "Why the compiler is expecting output ‘4’ for the input ‘7.9’? 7.9 is a double!" }, { "code": null, "e": 1070, "s": 1068, "text": "0" }, { "code": null, "e": 1097, "s": 1070, "text": "kaloyankostovbg1 month ago" }, { "code": null, "e": 1692, "s": 1097, "text": "class Solution {\n public:\n int BasicDataType(std::string s)\n {\n if (!isdigit(s[0]) && s.size() == 1)\n {\n return 1; // char\n }\n if (s.find('.') == -1)\n {\n return 4; // int\n }\n while (s[0] == '0')\n {\n s=s.substr(1);\n }\n \n auto result = double();\n auto i = std::istringstream(s);\n i >> result;\n if ((result < 1.5E-45 || result > 3.4E+38) || s.substr(s.find('.')).size() > 6)\n return 8; // double\n else\n return 4; // float\n }\n};" }, { "code": null, "e": 1695, "s": 1692, "text": "-1" }, { "code": null, "e": 1723, "s": 1695, "text": "rahulsingh110582 months ago" }, { "code": null, "e": 2114, "s": 1723, "text": "class Solution { public: int BasicDataType(string s) { // code here int len=s.length(),datasize; int i=0,temp=0; if((s[i]>='0' && s[i]<='9')|| s[i]=='.') { datasize=4; for(i=0;i<len;i++) { if(s[i]=='.') { datasize=4; temp=len-(i+1);" }, { "code": null, "e": 2365, "s": 2114, "text": " break; } } if(temp>=6) { datasize=8; } } else { datasize=1; } return datasize; }};" }, { "code": null, "e": 2367, "s": 2365, "text": "0" }, { "code": null, "e": 2397, "s": 2367, "text": "saurabhkumarmahra2 months ago" }, { "code": null, "e": 2522, "s": 2397, "text": "#include<iostream>\nusing namespace std;\nint main()\n{\n char a;\n cout<<\"The size of the variable is \"<<sizeof(a)<<endl;\n }" }, { "code": null, "e": 2525, "s": 2522, "text": "-1" }, { "code": null, "e": 2548, "s": 2525, "text": "mdsaif04052 months ago" }, { "code": null, "e": 2552, "s": 2548, "text": "C++" }, { "code": null, "e": 3497, "s": 2552, "text": " int BasicDataType(string s) {\n int len = s.length(), size; \n if (len == 1) { \n if (isdigit(s[0])) \n size = 4; \n else \n size = 1; \n } \n else \n { \n int flag = 0; \n for (int i = 0; i < len; i++) \n { \n if (s[i] == '.') { \n flag = 1; \n int j = len - i + 1; \n if (j > 7) \n size = 8; \n else \n size = 4; \n } \n } \n if (!flag) \n size = 4; \n } \n return size; \n }" }, { "code": null, "e": 3499, "s": 3497, "text": "0" }, { "code": null, "e": 3523, "s": 3499, "text": "2017chb10404 months ago" }, { "code": null, "e": 4502, "s": 3523, "text": " if (s.size() == 1) { if ((int (s[0]) - '0')<= 9) { /* code */ return 4; } else { return 1; } } else { for (int i = 0; i < s.size(); ++i) { if (s[i] == '.') { if ((s.size() - (i + 1)) >= 6) { /* code */ // k= \"double\"; return 8; } else { // k= \"float\"; return 4; } } else if (i == (s.length() - 1)) { return 4; } else { continue; } } }" }, { "code": null, "e": 4505, "s": 4502, "text": "-5" }, { "code": null, "e": 4533, "s": 4505, "text": "dakshagrawaldlp4 months ago" }, { "code": null, "e": 4663, "s": 4533, "text": "#include<iostream>\nusing namespace std;\n\nint main(){\n double s;\n\n s=98.45685456;\n cout<<sizeof(s)<<endl;\n return 0;\n}" }, { "code": null, "e": 4665, "s": 4663, "text": "0" }, { "code": null, "e": 4693, "s": 4665, "text": "dakshagrawaldlp4 months ago" }, { "code": null, "e": 4829, "s": 4693, "text": "#include<iostream>\nusing namespace std;\n\nint main(){\n char a,s;\n s=a;\n cout<< \"Size of s: \" <<sizeof(s)<<endl;\n return 0;\n}" }, { "code": null, "e": 4832, "s": 4829, "text": "+2" }, { "code": null, "e": 4853, "s": 4832, "text": "dkaman794 months ago" }, { "code": null, "e": 5645, "s": 4853, "text": "class Solution {\n public:\n int BasicDataType(string S) {\n int l = S.length(), ans;\n if (l == 1) {\n //checking if S is integer of size 1\n if (isdigit(S[0]))\n ans = 4;\n else\n ans = 1;\n } else {\n int flag = 0;\n for (int i = 0; i < l; i++) {\n //checking whether S is integer or float/double\n if (S[i] == '.') {\n flag = 1;\n int j = l - i + 1;\n //checking whether S is double\n if (j > 7)\n ans = 8;\n else\n ans = 4;\n }\n }\n if (!flag) ans = 4;\n }\n return ans;\n }\n};" }, { "code": null, "e": 5791, "s": 5645, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5827, "s": 5791, "text": " Login to access your submissions. " }, { "code": null, "e": 5837, "s": 5827, "text": "\nProblem\n" }, { "code": null, "e": 5847, "s": 5837, "text": "\nContest\n" }, { "code": null, "e": 5910, "s": 5847, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6058, "s": 5910, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6266, "s": 6058, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6372, "s": 6266, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Bootstrap Form CheckBox
Use checkbox class if you want the user to select any number of options from a list. Use .checkbox-inline class to a series of checkboxes for controls appear on the same line. You can try to run the following code to implement Bootstrap form checkbox Live Demo <!DOCTYPE html> <html> <head> <title>Try v1.2 Bootstrap Online</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <label for = "name"></label>Favourite Live Streaming</label> <div class = "checkbox"> <label> <input type = "checkbox" value = "">Amazon Prime </label> </div> <div class = "checkbox"> <label> <input type = "checkbox" value = "">Hotstar </label> </div> </body> </html>
[ { "code": null, "e": 1238, "s": 1062, "text": "Use checkbox class if you want the user to select any number of options from a list. Use .checkbox-inline class to a series of checkboxes for controls appear on the same line." }, { "code": null, "e": 1313, "s": 1238, "text": "You can try to run the following code to implement Bootstrap form checkbox" }, { "code": null, "e": 1323, "s": 1313, "text": "Live Demo" }, { "code": null, "e": 1977, "s": 1323, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Try v1.2 Bootstrap Online</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <label for = \"name\"></label>Favourite Live Streaming</label>\n <div class = \"checkbox\">\n <label>\n <input type = \"checkbox\" value = \"\">Amazon Prime\n </label>\n </div>\n <div class = \"checkbox\">\n <label>\n <input type = \"checkbox\" value = \"\">Hotstar\n </label>\n </div>\n </body>\n</html>" } ]
What do you mean by a dynamic initialization of variables?
Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an object is to be provided during run time. Dynamic initialization can be achieved using constructors and passing parameters values to the constructors. This type of initialization is required to initialize the class variables during run time. Why we need the dynamic initialization? Dynamic initialization of objects is needed as It utilizes memory efficiently. It utilizes memory efficiently. Various initialization formats can be provided using overloaded constructors. Various initialization formats can be provided using overloaded constructors. It has the flexibility of using different formats of data at run time considering the situation. It has the flexibility of using different formats of data at run time considering the situation. #include <iostream> using namespace std; class simple_interest { float principle , time, rate ,interest; public: simple_interest (float a, float b, float c) { principle = a; time =b; rate = c; } void display ( ) { interest =(principle* rate* time)/100; cout<<"interest ="<<interest ; } }; int main() { float p,r,t; cout<<"principle amount, time and rate"<<endl; cout<<"2000 7.5 2"<<endl; simple_interest s1(2000,7.5,2);//dynamic initialization s1.display(); return 1; } Enter principle amount ,rate and time 2000 7.5 2 Interest =300
[ { "code": null, "e": 1413, "s": 1062, "text": "Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an object is to be provided during run time. Dynamic initialization can be achieved using\nconstructors and passing parameters values to the constructors. This type of initialization is required to initialize the class variables during run time." }, { "code": null, "e": 1453, "s": 1413, "text": "Why we need the dynamic initialization?" }, { "code": null, "e": 1500, "s": 1453, "text": "Dynamic initialization of objects is needed as" }, { "code": null, "e": 1532, "s": 1500, "text": "It utilizes memory efficiently." }, { "code": null, "e": 1564, "s": 1532, "text": "It utilizes memory efficiently." }, { "code": null, "e": 1642, "s": 1564, "text": "Various initialization formats can be provided using overloaded constructors." }, { "code": null, "e": 1720, "s": 1642, "text": "Various initialization formats can be provided using overloaded constructors." }, { "code": null, "e": 1817, "s": 1720, "text": "It has the flexibility of using different formats of data at run time considering the situation." }, { "code": null, "e": 1914, "s": 1817, "text": "It has the flexibility of using different formats of data at run time considering the situation." }, { "code": null, "e": 2477, "s": 1914, "text": "#include <iostream>\nusing namespace std;\nclass simple_interest {\n float principle , time, rate ,interest;\n public:\n simple_interest (float a, float b, float c) {\n principle = a;\n time =b;\n rate = c;\n }\n void display ( ) {\n interest =(principle* rate* time)/100;\n cout<<\"interest =\"<<interest ;\n }\n};\nint main() {\n float p,r,t;\n cout<<\"principle amount, time and rate\"<<endl;\n cout<<\"2000 7.5 2\"<<endl;\n simple_interest s1(2000,7.5,2);//dynamic initialization\n s1.display();\n return 1;\n}" }, { "code": null, "e": 2540, "s": 2477, "text": "Enter principle amount ,rate and time\n2000 7.5 2\nInterest =300" } ]
How to dismiss the Alert with click on outside of the alert in iOS?
Understanding and implementing UIAlert can be tricky especially if you’re new to iOS Development, In this post, we will be seeing how we can dismiss the alert when the user taps outside the alert box. For this demo, we will be using UIAlert class, to configure alerts and action sheets with the message that you want to display and the actions from which to choose. After configuring the alert controller with the actions and style you want, present it using the present(_:animated: completion:) method. UIKit displays alerts and action sheets modally over your app's content. You can read more about it: https://developer.apple.com/documentation/uikit/uialertcontroller So let’s get started, Step 1 − Open Xcode and create a single view application and name it UIAlertSample. Step 2 − In Main. storyboard add one button, and create @IBAction and name it showAlert, @IBAction func showAlert(_ sender: Any) { } So basically, when we tap on the button an alert will be displayed, when the user taps outside the alert the alert will be dismissing. Step 3 − Inside button action showAlert, First create UIAlert object as below let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert) Step 4 − Present the alert and on its completion add a selector as shown below, self.present(uialert, animated: true, completion:{ uialert.view.superview?.isUserInteractionEnabled = true uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside))) }) Step 5 − Add selector function, @objc func dismissOnTapOutside(){ self.dismiss(animated: true, completion: nil) } Step 6 − Run the application, import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func showAlert(_ sender: Any) { let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert) self.present(uialert, animated: true, completion:{ uialert.view.superview?.isUserInteractionEnabled = true uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside))) }) } @objc func dismissOnTapOutside(){ self.dismiss(animated: true, completion: nil) } }
[ { "code": null, "e": 1263, "s": 1062, "text": "Understanding and implementing UIAlert can be tricky especially if you’re new to iOS Development, In this post, we will be seeing how we can dismiss the alert when the user taps outside the alert box." }, { "code": null, "e": 1639, "s": 1263, "text": "For this demo, we will be using UIAlert class, to configure alerts and action sheets with the message that you want to display and the actions from which to choose. After configuring the alert controller with the actions and style you want, present it using the present(_:animated: completion:) method. UIKit displays alerts and action sheets modally over your app's content." }, { "code": null, "e": 1733, "s": 1639, "text": "You can read more about it: https://developer.apple.com/documentation/uikit/uialertcontroller" }, { "code": null, "e": 1755, "s": 1733, "text": "So let’s get started," }, { "code": null, "e": 1839, "s": 1755, "text": "Step 1 − Open Xcode and create a single view application and name it UIAlertSample." }, { "code": null, "e": 1928, "s": 1839, "text": "Step 2 − In Main. storyboard add one button, and create @IBAction and name it showAlert," }, { "code": null, "e": 1972, "s": 1928, "text": "@IBAction func showAlert(_ sender: Any) { }" }, { "code": null, "e": 2107, "s": 1972, "text": "So basically, when we tap on the button an alert will be displayed, when the user taps outside the alert the alert will be dismissing." }, { "code": null, "e": 2185, "s": 2107, "text": "Step 3 − Inside button action showAlert, First create UIAlert object as below" }, { "code": null, "e": 2329, "s": 2185, "text": "let uialert = UIAlertController(title: \"WELCOME\", message: \"Welcome to my tutorials, tap outside to dismiss the alert\", preferredStyle: .alert)" }, { "code": null, "e": 2409, "s": 2329, "text": "Step 4 − Present the alert and on its completion add a selector as shown below," }, { "code": null, "e": 2653, "s": 2409, "text": "self.present(uialert, animated: true, completion:{\n uialert.view.superview?.isUserInteractionEnabled = true\n uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))\n})" }, { "code": null, "e": 2685, "s": 2653, "text": "Step 5 − Add selector function," }, { "code": null, "e": 2770, "s": 2685, "text": "@objc func dismissOnTapOutside(){\n self.dismiss(animated: true, completion: nil)\n}" }, { "code": null, "e": 2800, "s": 2770, "text": "Step 6 − Run the application," }, { "code": null, "e": 3476, "s": 2800, "text": "import UIKit\nclass ViewController: UIViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n }\n @IBAction func showAlert(_ sender: Any) {\n let uialert = UIAlertController(title: \"WELCOME\", message: \"Welcome to my tutorials, tap outside to dismiss the alert\", preferredStyle: .alert)\n self.present(uialert, animated: true, completion:{\n uialert.view.superview?.isUserInteractionEnabled = true\n uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))\n })\n }\n @objc func dismissOnTapOutside(){\n self.dismiss(animated: true, completion: nil)\n }\n}" } ]
C Program to Check Armstrong Number?
A number is called an Armstrong number if the sum of cubes of digits of the number is equal to the number itself. It is a mathematical concept usually used in programming to build basic logic of the programmer Input:370 Output:370 is an Armstrong Number 370 = 3*3*3 + 7*7*7 + 0*0*0 = 27 + 343 + 0 = 370 include <iostream> using namespace std; int main() { int n, num, rem, sum = 0; cin >> n; num = n; while(num != 0) { digit = num % 10; sum += digit * digit * digit; num /= 10; } if(sum == n) printf("%d is an Armstrong number.", n ); else printf("%d is not an Armstrong number.",n); return 0; }
[ { "code": null, "e": 1272, "s": 1062, "text": "A number is called an Armstrong number if the sum of cubes of digits of the number is equal to the number itself. It is a mathematical concept usually used in programming to build basic logic of the programmer" }, { "code": null, "e": 1316, "s": 1272, "text": "Input:370\nOutput:370 is an Armstrong Number" }, { "code": null, "e": 1365, "s": 1316, "text": "370 = 3*3*3 + 7*7*7 + 0*0*0\n= 27 + 343 + 0\n= 370" }, { "code": null, "e": 1713, "s": 1365, "text": "include <iostream>\nusing namespace std;\nint main() {\n int n, num, rem, sum = 0;\n cin >> n;\n num = n;\n while(num != 0) {\n digit = num % 10;\n sum += digit * digit * digit;\n num /= 10;\n }\n if(sum == n)\n printf(\"%d is an Armstrong number.\", n );\n else\n printf(\"%d is not an Armstrong number.\",n);\n return 0;\n}\n" } ]
React Native - Text
In this chapter, we will talk about Text component in React Native. This component can be nested and it can inherit properties from parent to child. This can be useful in many ways. We will show you example of capitalizing the first letter, styling words or parts of the text, etc. The file we are going to create is text_example.js In this step, we will just create a simple container. import React, { Component } from 'react' import TextExample from './text_example.js' const App = () => { return ( <TextExample/> ) } export default App In this step, we will use the inheritance pattern. styles.text will be applied to all Text components. You can also notice how we set other styling properties to some parts of the text. It is important to know that all child elements have parent styles passed to them. import React, { Component } from 'react'; import { View, Text, Image, StyleSheet } from 'react-native' const TextExample = () => { return ( <View style = {styles.container}> <Text style = {styles.text}> <Text style = {styles.capitalLetter}> L </Text> <Text> orem ipsum dolor sit amet, sed do eiusmod. </Text> <Text> Ut enim ad <Text style = {styles.wordBold}>minim </Text> veniam, quis aliquip ex ea commodo consequat. </Text> <Text style = {styles.italicText}> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum. </Text> <Text style = {styles.textShadow}> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </Text> </Text> </View> ) } export default TextExample const styles = StyleSheet.create ({ container: { alignItems: 'center', marginTop: 100, padding: 20 }, text: { color: '#41cdf4', }, capitalLetter: { color: 'red', fontSize: 20 }, wordBold: { fontWeight: 'bold', color: 'black' }, italicText: { color: '#37859b', fontStyle: 'italic' }, textShadow: { textShadowColor: 'red', textShadowOffset: { width: 2, height: 2 }, textShadowRadius : 5 } }) You will receive the following output − 20 Lectures 1.5 hours Anadi Sharma 61 Lectures 6.5 hours A To Z Mentor 40 Lectures 4.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2412, "s": 2344, "text": "In this chapter, we will talk about Text component in React Native." }, { "code": null, "e": 2626, "s": 2412, "text": "This component can be nested and it can inherit properties from parent to child. This can be useful in many ways. We will show you example of capitalizing the first letter, styling words or parts of the text, etc." }, { "code": null, "e": 2677, "s": 2626, "text": "The file we are going to create is text_example.js" }, { "code": null, "e": 2731, "s": 2677, "text": "In this step, we will just create a simple container." }, { "code": null, "e": 2896, "s": 2731, "text": "import React, { Component } from 'react'\nimport TextExample from './text_example.js'\n\nconst App = () => {\n return (\n <TextExample/>\n )\n}\nexport default App" }, { "code": null, "e": 2999, "s": 2896, "text": "In this step, we will use the inheritance pattern. styles.text will be applied to all Text components." }, { "code": null, "e": 3165, "s": 2999, "text": "You can also notice how we set other styling properties to some parts of the text. It is important to know that all child elements have parent styles passed to them." }, { "code": null, "e": 4733, "s": 3165, "text": "import React, { Component } from 'react';\nimport { View, Text, Image, StyleSheet } from 'react-native'\n\nconst TextExample = () => {\n return (\n <View style = {styles.container}>\n <Text style = {styles.text}>\n <Text style = {styles.capitalLetter}>\n L\n </Text>\n \n <Text>\n orem ipsum dolor sit amet, sed do eiusmod.\n </Text>\n \n <Text>\n Ut enim ad <Text style = {styles.wordBold}>minim </Text> veniam,\n quis aliquip ex ea commodo consequat.\n </Text>\n \n <Text style = {styles.italicText}>\n Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.\n </Text>\n \n <Text style = {styles.textShadow}>\n Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia\n deserunt mollit anim id est laborum.\n </Text>\n </Text>\n \n </View>\n )\n}\nexport default TextExample\n\nconst styles = StyleSheet.create ({\n container: {\n alignItems: 'center',\n marginTop: 100,\n padding: 20\n },\n text: {\n color: '#41cdf4',\n },\n capitalLetter: {\n color: 'red',\n fontSize: 20\n },\n wordBold: {\n fontWeight: 'bold',\n color: 'black'\n },\n italicText: {\n color: '#37859b',\n fontStyle: 'italic'\n },\n textShadow: {\n textShadowColor: 'red',\n textShadowOffset: { width: 2, height: 2 },\n textShadowRadius : 5\n }\n})" }, { "code": null, "e": 4773, "s": 4733, "text": "You will receive the following output −" }, { "code": null, "e": 4808, "s": 4773, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4822, "s": 4808, "text": " Anadi Sharma" }, { "code": null, "e": 4857, "s": 4822, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4872, "s": 4857, "text": " A To Z Mentor" }, { "code": null, "e": 4907, "s": 4872, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4935, "s": 4907, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4971, "s": 4935, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4999, "s": 4971, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5034, "s": 4999, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5046, "s": 5034, "text": " Senol Atac" }, { "code": null, "e": 5081, "s": 5046, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5093, "s": 5081, "text": " Senol Atac" }, { "code": null, "e": 5100, "s": 5093, "text": " Print" }, { "code": null, "e": 5111, "s": 5100, "text": " Add Notes" } ]
How to set style display of an html element in a selenium test?
We can set the style display of an html element with Selenium webdriver. The DOM interacts with the elements on the page with the help of Javascript. Selenium executes the Javascript commands by taking the help of the executeScript method. The commands to be executed are passed as arguments to the method. Some operations like setting the style display be performed by Javascript Executor. The getElementById method can be used to locate the element. Then we have to apply the style.display method on the webelement and set the display type. executor.executeScript ("document.getElementById('gsc-i-id1').style.display='block';"); Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ElementStyleSet{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // Javascript executor class with executeScript method JavascriptExecutor j = (JavascriptExecutor) driver; // set the display with style.display method j.executeScript ("document.getElementById('gsc-i-id1').style.display='block';"); driver.close() } }
[ { "code": null, "e": 1369, "s": 1062, "text": "We can set the style display of an html element with Selenium webdriver. The DOM interacts with the elements on the page with the help of Javascript. Selenium executes the Javascript commands by taking the help of the executeScript method. The commands to be executed are passed as arguments to the method." }, { "code": null, "e": 1605, "s": 1369, "text": "Some operations like setting the style display be performed by Javascript Executor. The getElementById method can be used to locate the element. Then we have to apply the style.display method on the webelement and set the display type." }, { "code": null, "e": 1693, "s": 1605, "text": "executor.executeScript\n(\"document.getElementById('gsc-i-id1').style.display='block';\");" }, { "code": null, "e": 1714, "s": 1693, "text": "Code Implementation." }, { "code": null, "e": 2599, "s": 1714, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ElementStyleSet{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // Javascript executor class with executeScript method\n JavascriptExecutor j = (JavascriptExecutor) driver;\n // set the display with style.display method\n j.executeScript (\"document.getElementById('gsc-i-id1').style.display='block';\");\n driver.close()\n }\n}" } ]
Change all even bits in a number to 0 - GeeksforGeeks
31 Jan, 2022 Given a number, change all bits at even positions to 0. Examples: Input : 30 Output : 10 Binary representation of 11110. Bits at Even positions are highlighted. After making all of them 0, we get 01010 Input : 10 Output : 10 Method 1 (Bit Traversal) The idea is to traverse through all even bits. We accumulate all powers of 2 in a number to subtract. Finally we subtract the accumulated value from n to obtain the result. C++ Java Python3 C# PHP Javascript // C++ program to change even// bits to 0.#include <bits/stdc++.h>using namespace std; // Returns modified number with// all even bits 0.int changeEvenBits(int n){ // To store sum of bits // at even positions. int to_subtract = 0; // To store bits to shift int m = 0; // One by one put all even // bits to end for (int x = n; x; x >>= 2) { // If current last bit // is set, add it to ans if (x & 1) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract;} // Driver codeint main(){ int n = 30; cout << changeEvenBits(n) << endl; return 0;} // Java program to change even// bits to 0.import java.util.*;class GFG { // Returns modified number with // all even bits 0. static int changeEvenBits(int n) { // To store sum of bits // at even positions. int to_subtract = 0; // To store bits to shift int m = 0; // One by one put all even // bits to end for (int x = n; x > 0; x >>= 2) { // If current last bit // is set, add it to ans if ((x & 1) > 0) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract; } // Driver code public static void main(String[] args) { int n = 30; System.out.println(changeEvenBits(n)); }}/* This code is contributed by Mr. Somesh Awasthi */ # Python program to change even# bits to 0. # Returns modified number with# all even bits 0. def changeEvenBits(n): # To store sum of bits # at even positions. to_subtract = 0 # To store bits to shift m = 0 # One by one put all even # bits to end x = n while(x): # If current last bit # is set, add it to ans if (x & 1): to_subtract += (1 << m) # Next shift position m += 2 x >>= 2 return n - to_subtract # Driver coden = 30print(changeEvenBits(n)) # This code is contributed by Sachin Bisht // C# program to change even// bits to 0.using System; class GFG { // Returns modified number with // all even bits 0. static int changeEvenBits(int n) { // To store sum of bits // at even positions. int to_subtract = 0; // To store bits to shift int m = 0; // One by one put all even // bits to end for (int x = n; x > 0; x >>= 2) { // If current last bit // is set, add it to ans if ((x & 1) > 0) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract; } // Driver code public static void Main() { int n = 30; Console.Write(changeEvenBits(n)); }} // This code is contributed by nitin mittal. <?php// PHP program to change even// bits to 0. // Returns modified number with// all even bits 0.function changeEvenBits($n){ // To store sum of bits // at even positions. $to_subtract = 0; // To store bits to shift $m = 0; // One by one put all even // bits to end for ($x = $n; $x; $x >>= 2) { // If current last bit // is set, add it to ans if ($x & 1) $to_subtract += (1 << $m); // Next shift position $m += 2; } return $n - $to_subtract;} // Driver code $n = 30; echo changeEvenBits($n) ; // This code is contributed by nitin mittal?> <script> // js program to change even// bits to 0. // Returns modified number with// all even bits 0.function changeEvenBits(n){ // To store sum of bits // at even positions. let to_subtract = 0; // To store bits to shift let m = 0; // One by one put all even // bits to end for (x = n; x; x >>= 2) { // If current last bit // is set, add it to ans if (x & 1) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract;} // Driver code n = 30; document.write( changeEvenBits(n) ); // This code is contributed by sravan kumar </script> 10 Method 2: (Bit masking) C++ Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; int convertEvenBitToOne(int n) { return (n & 0xaaaaaaaa); } int main(){ int n = 30; cout << convertEvenBitToOne(n); return 0;} // Java program using Bitmask to// Change all even bits in a// number to 0import java.io.*; class GFG { static int convertEvenBitToOne(int n) { return (n & 0xaaaaaaaa); } // Driver code public static void main(String[] args) { int n = 30; System.out.println(convertEvenBitToOne(n)); }} // This code is contributed by anuj_67. def convertEvenBitToOne(n): return (n & 0xaaaaaaaa) # Driver coden = 30print(convertEvenBitToOne(n)) # This code is contributed by Sachin Bisht // C# program using Bitmask to// Change all even bits in a// number to 0using System; class GFG { static long convertEvenBitToOne(int n) { return (n & 0xaaaaaaaa); } // Driver code public static void Main() { int n = 30; Console.WriteLine(convertEvenBitToOne(n)); }} // This code is contributed by anuj_67. <?php// PHP program using Bitmask to// Change all even bits in a// number to 0 function convertEvenBitToOne($n){ return ($n & 0xaaaaaaaa);} // Driver Code$n = 30;echo convertEvenBitToOne($n); // This code is contributed by anuj_67.?> <script> // java script program using Bitmask to// Change all even bits in a// number to 0 function convertEvenBitToOne(n){ return (n & 0xaaaaaaaa);} // Driver Coden = 30;document.write(convertEvenBitToOne(n));// This code is contributed by sravan kumar </script> 10 This article is contributed by RISHABH RAJ JHA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m mayanktyagi1709 sravankumar8128 amartyaghoshgfg Samsung Bit Magic Mathematical Samsung 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 Bit Fields in C Bits manipulation (Important tactics) Add two numbers without using arithmetic operators Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25286, "s": 25258, "text": "\n31 Jan, 2022" }, { "code": null, "e": 25342, "s": 25286, "text": "Given a number, change all bits at even positions to 0." }, { "code": null, "e": 25353, "s": 25342, "text": "Examples: " }, { "code": null, "e": 25517, "s": 25353, "text": "Input : 30\nOutput : 10\nBinary representation of 11110. \nBits at Even positions are highlighted. \nAfter making all of them 0, we get 01010\n\nInput : 10\nOutput : 10" }, { "code": null, "e": 25542, "s": 25517, "text": "Method 1 (Bit Traversal)" }, { "code": null, "e": 25716, "s": 25542, "text": "The idea is to traverse through all even bits. We accumulate all powers of 2 in a number to subtract. Finally we subtract the accumulated value from n to obtain the result. " }, { "code": null, "e": 25720, "s": 25716, "text": "C++" }, { "code": null, "e": 25725, "s": 25720, "text": "Java" }, { "code": null, "e": 25733, "s": 25725, "text": "Python3" }, { "code": null, "e": 25736, "s": 25733, "text": "C#" }, { "code": null, "e": 25740, "s": 25736, "text": "PHP" }, { "code": null, "e": 25751, "s": 25740, "text": "Javascript" }, { "code": "// C++ program to change even// bits to 0.#include <bits/stdc++.h>using namespace std; // Returns modified number with// all even bits 0.int changeEvenBits(int n){ // To store sum of bits // at even positions. int to_subtract = 0; // To store bits to shift int m = 0; // One by one put all even // bits to end for (int x = n; x; x >>= 2) { // If current last bit // is set, add it to ans if (x & 1) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract;} // Driver codeint main(){ int n = 30; cout << changeEvenBits(n) << endl; return 0;}", "e": 26407, "s": 25751, "text": null }, { "code": "// Java program to change even// bits to 0.import java.util.*;class GFG { // Returns modified number with // all even bits 0. static int changeEvenBits(int n) { // To store sum of bits // at even positions. int to_subtract = 0; // To store bits to shift int m = 0; // One by one put all even // bits to end for (int x = n; x > 0; x >>= 2) { // If current last bit // is set, add it to ans if ((x & 1) > 0) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract; } // Driver code public static void main(String[] args) { int n = 30; System.out.println(changeEvenBits(n)); }}/* This code is contributed by Mr. Somesh Awasthi */", "e": 27245, "s": 26407, "text": null }, { "code": "# Python program to change even# bits to 0. # Returns modified number with# all even bits 0. def changeEvenBits(n): # To store sum of bits # at even positions. to_subtract = 0 # To store bits to shift m = 0 # One by one put all even # bits to end x = n while(x): # If current last bit # is set, add it to ans if (x & 1): to_subtract += (1 << m) # Next shift position m += 2 x >>= 2 return n - to_subtract # Driver coden = 30print(changeEvenBits(n)) # This code is contributed by Sachin Bisht", "e": 27828, "s": 27245, "text": null }, { "code": "// C# program to change even// bits to 0.using System; class GFG { // Returns modified number with // all even bits 0. static int changeEvenBits(int n) { // To store sum of bits // at even positions. int to_subtract = 0; // To store bits to shift int m = 0; // One by one put all even // bits to end for (int x = n; x > 0; x >>= 2) { // If current last bit // is set, add it to ans if ((x & 1) > 0) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract; } // Driver code public static void Main() { int n = 30; Console.Write(changeEvenBits(n)); }} // This code is contributed by nitin mittal.", "e": 28693, "s": 27828, "text": null }, { "code": "<?php// PHP program to change even// bits to 0. // Returns modified number with// all even bits 0.function changeEvenBits($n){ // To store sum of bits // at even positions. $to_subtract = 0; // To store bits to shift $m = 0; // One by one put all even // bits to end for ($x = $n; $x; $x >>= 2) { // If current last bit // is set, add it to ans if ($x & 1) $to_subtract += (1 << $m); // Next shift position $m += 2; } return $n - $to_subtract;} // Driver code $n = 30; echo changeEvenBits($n) ; // This code is contributed by nitin mittal?>", "e": 29337, "s": 28693, "text": null }, { "code": "<script> // js program to change even// bits to 0. // Returns modified number with// all even bits 0.function changeEvenBits(n){ // To store sum of bits // at even positions. let to_subtract = 0; // To store bits to shift let m = 0; // One by one put all even // bits to end for (x = n; x; x >>= 2) { // If current last bit // is set, add it to ans if (x & 1) to_subtract += (1 << m); // Next shift position m += 2; } return n - to_subtract;} // Driver code n = 30; document.write( changeEvenBits(n) ); // This code is contributed by sravan kumar </script>", "e": 29997, "s": 29337, "text": null }, { "code": null, "e": 30000, "s": 29997, "text": "10" }, { "code": null, "e": 30024, "s": 30000, "text": "Method 2: (Bit masking)" }, { "code": null, "e": 30028, "s": 30024, "text": "C++" }, { "code": null, "e": 30033, "s": 30028, "text": "Java" }, { "code": null, "e": 30041, "s": 30033, "text": "Python3" }, { "code": null, "e": 30044, "s": 30041, "text": "C#" }, { "code": null, "e": 30048, "s": 30044, "text": "PHP" }, { "code": null, "e": 30059, "s": 30048, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int convertEvenBitToOne(int n) { return (n & 0xaaaaaaaa); } int main(){ int n = 30; cout << convertEvenBitToOne(n); return 0;}", "e": 30240, "s": 30059, "text": null }, { "code": "// Java program using Bitmask to// Change all even bits in a// number to 0import java.io.*; class GFG { static int convertEvenBitToOne(int n) { return (n & 0xaaaaaaaa); } // Driver code public static void main(String[] args) { int n = 30; System.out.println(convertEvenBitToOne(n)); }} // This code is contributed by anuj_67.", "e": 30610, "s": 30240, "text": null }, { "code": "def convertEvenBitToOne(n): return (n & 0xaaaaaaaa) # Driver coden = 30print(convertEvenBitToOne(n)) # This code is contributed by Sachin Bisht", "e": 30758, "s": 30610, "text": null }, { "code": "// C# program using Bitmask to// Change all even bits in a// number to 0using System; class GFG { static long convertEvenBitToOne(int n) { return (n & 0xaaaaaaaa); } // Driver code public static void Main() { int n = 30; Console.WriteLine(convertEvenBitToOne(n)); }} // This code is contributed by anuj_67.", "e": 31109, "s": 30758, "text": null }, { "code": "<?php// PHP program using Bitmask to// Change all even bits in a// number to 0 function convertEvenBitToOne($n){ return ($n & 0xaaaaaaaa);} // Driver Code$n = 30;echo convertEvenBitToOne($n); // This code is contributed by anuj_67.?>", "e": 31346, "s": 31109, "text": null }, { "code": "<script> // java script program using Bitmask to// Change all even bits in a// number to 0 function convertEvenBitToOne(n){ return (n & 0xaaaaaaaa);} // Driver Coden = 30;document.write(convertEvenBitToOne(n));// This code is contributed by sravan kumar </script>", "e": 31613, "s": 31346, "text": null }, { "code": null, "e": 31616, "s": 31613, "text": "10" }, { "code": null, "e": 32041, "s": 31616, "text": "This article is contributed by RISHABH RAJ JHA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32054, "s": 32041, "text": "nitin mittal" }, { "code": null, "e": 32059, "s": 32054, "text": "vt_m" }, { "code": null, "e": 32075, "s": 32059, "text": "mayanktyagi1709" }, { "code": null, "e": 32091, "s": 32075, "text": "sravankumar8128" }, { "code": null, "e": 32107, "s": 32091, "text": "amartyaghoshgfg" }, { "code": null, "e": 32115, "s": 32107, "text": "Samsung" }, { "code": null, "e": 32125, "s": 32115, "text": "Bit Magic" }, { "code": null, "e": 32138, "s": 32125, "text": "Mathematical" }, { "code": null, "e": 32146, "s": 32138, "text": "Samsung" }, { "code": null, "e": 32159, "s": 32146, "text": "Mathematical" }, { "code": null, "e": 32169, "s": 32159, "text": "Bit Magic" }, { "code": null, "e": 32267, "s": 32169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32276, "s": 32267, "text": "Comments" }, { "code": null, "e": 32289, "s": 32276, "text": "Old Comments" }, { "code": null, "e": 32335, "s": 32289, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 32365, "s": 32335, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 32381, "s": 32365, "text": "Bit Fields in C" }, { "code": null, "e": 32419, "s": 32381, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 32470, "s": 32419, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 32500, "s": 32470, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32560, "s": 32500, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32575, "s": 32560, "text": "C++ Data Types" }, { "code": null, "e": 32618, "s": 32575, "text": "Set in C++ Standard Template Library (STL)" } ]
How to use ReadKey() method of Console class in C#?
Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET. A common use of the ReadKey() method is that you can halt the program execution. This could be done until a key is pressed by the user. Let us see an example − Live Demo using System; public class Demo { public static void Main() { DateTime date = DateTime.Now; TimeZoneInfo timeZone = TimeZoneInfo.Local; Console.WriteLine("Time Zone = {0}\n", timeZone.IsDaylightSavingTime(date) ? timeZone.DaylightName : timeZone.StandardName); Console.Write(" to exit... "); while (Console.ReadKey().Key != ConsoleKey.Enter) {} } } Time Zone = UTC <Enter> to exit...
[ { "code": null, "e": 1264, "s": 1062, "text": "Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET." }, { "code": null, "e": 1400, "s": 1264, "text": "A common use of the ReadKey() method is that you can halt the program execution. This could be done until a key is pressed by the user." }, { "code": null, "e": 1424, "s": 1400, "text": "Let us see an example −" }, { "code": null, "e": 1435, "s": 1424, "text": " Live Demo" }, { "code": null, "e": 1821, "s": 1435, "text": "using System;\n\npublic class Demo {\n public static void Main() {\n DateTime date = DateTime.Now;\n TimeZoneInfo timeZone = TimeZoneInfo.Local;\n Console.WriteLine(\"Time Zone = {0}\\n\", timeZone.IsDaylightSavingTime(date) ? timeZone.DaylightName : timeZone.StandardName);\n Console.Write(\" to exit... \");\n while (Console.ReadKey().Key != ConsoleKey.Enter) {}\n }\n}" }, { "code": null, "e": 1856, "s": 1821, "text": "Time Zone = UTC\n<Enter> to exit..." } ]
Mean and Mode in SQL Server
28 Mar, 2018 Mean is the average of the given data set calculated by dividing the total sum by the number of values in data set. Example: Input: 1, 2, 3, 4, 5 Output: 3 Explanation: sum = 1 + 2 + 3 + 4 + 5 = 15 number of values = 5 mean = 15 / 5 = 3 Query to find mean in the table SELECT Avg(Column_Name) FROM Table_Name Example: Creating Table: Table Content: Query to find Mean: Mode of a data set is the value that appears most frequently in a series of data. Example: Input: 1, 2, 2, 3, 4, 4, 4, 5, 5, 6 Output: 4 Explanation: 2 occurs 2 times, 5 occurs 2 times 4 occurs 3 times and rest other occurs 1 time So, 4 occurs most frequently and is thus the output. Query to find mode in the table SELECT TOP 1 Column_Name FROM Table_name GROUP BY [Column_Name] ORDER BY COUNT(*) DESC Example: Creating Table: Table Content: Query to find Mode: SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Trigger | Student Database SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS SQL Correlated Subqueries Window functions in SQL
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2018" }, { "code": null, "e": 144, "s": 28, "text": "Mean is the average of the given data set calculated by dividing the total sum by the number of values in data set." }, { "code": null, "e": 153, "s": 144, "text": "Example:" }, { "code": null, "e": 269, "s": 153, "text": "Input: 1, 2, 3, 4, 5 \nOutput: 3\nExplanation: \nsum = 1 + 2 + 3 + 4 + 5 = 15\nnumber of values = 5\nmean = 15 / 5 = 3\n" }, { "code": null, "e": 301, "s": 269, "text": "Query to find mean in the table" }, { "code": null, "e": 344, "s": 301, "text": "SELECT Avg(Column_Name) \nFROM Table_Name\n" }, { "code": null, "e": 353, "s": 344, "text": "Example:" }, { "code": null, "e": 369, "s": 353, "text": "Creating Table:" }, { "code": null, "e": 384, "s": 369, "text": "Table Content:" }, { "code": null, "e": 404, "s": 384, "text": "Query to find Mean:" }, { "code": null, "e": 486, "s": 404, "text": "Mode of a data set is the value that appears most frequently in a series of data." }, { "code": null, "e": 495, "s": 486, "text": "Example:" }, { "code": null, "e": 692, "s": 495, "text": "Input: 1, 2, 2, 3, 4, 4, 4, 5, 5, 6\nOutput: 4\nExplanation:\n2 occurs 2 times, 5 occurs 2 times\n4 occurs 3 times and rest other \noccurs 1 time\nSo, 4 occurs most frequently and \nis thus the output.\n" }, { "code": null, "e": 724, "s": 692, "text": "Query to find mode in the table" }, { "code": null, "e": 816, "s": 724, "text": "SELECT TOP 1 Column_Name\nFROM Table_name\nGROUP BY [Column_Name]\nORDER BY COUNT(*) DESC\n" }, { "code": null, "e": 825, "s": 816, "text": "Example:" }, { "code": null, "e": 841, "s": 825, "text": "Creating Table:" }, { "code": null, "e": 856, "s": 841, "text": "Table Content:" }, { "code": null, "e": 876, "s": 856, "text": "Query to find Mode:" }, { "code": null, "e": 887, "s": 876, "text": "SQL-Server" }, { "code": null, "e": 891, "s": 887, "text": "SQL" }, { "code": null, "e": 895, "s": 891, "text": "SQL" }, { "code": null, "e": 993, "s": 895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1004, "s": 993, "text": "CTE in SQL" }, { "code": null, "e": 1070, "s": 1004, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1101, "s": 1070, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1125, "s": 1101, "text": "SQL Interview Questions" }, { "code": null, "e": 1137, "s": 1125, "text": "SQL | Views" }, { "code": null, "e": 1182, "s": 1137, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1214, "s": 1182, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1253, "s": 1214, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 1279, "s": 1253, "text": "SQL Correlated Subqueries" } ]
How to Take Input from the User in Golang?
10 May, 2020 Scanln function can be used to take the input from the user in the Golang. Below is the example of taking input from the user: // Golang program to show how// to take input from the userpackage main import "fmt" // main functionfunc main() { // Println function is used to // display output in the next line fmt.Println("Enter Your First Name: ") // var then variable name then variable type var first string // Taking input from user fmt.Scanln(&first) fmt.Println("Enter Second Last Name: ") var second string fmt.Scanln(&second) // Print function is used to // display output in the same line fmt.Print("Your Full Name is: ") // Addition of two string fmt.Print(first + " " + second)} Now save this file and execute as shown in the below screenshot: Description About the Program: main Package: When we build reusable pieces of code, we will develop a package as a shared library. But when we develop an executable program, we will use the package “main” for making the package as an executable program. The package “main” tells the Golang compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program. Remember when we build shared libraries, we will not have any main package and main function in the package. fmt.Println is the print function which is used to print the output in the next line. While fmt.Print is used to display output in the same line. Whatever needs to be printed has to be written in inverted commas ” “. var first string is the declaration of the variable first which is of string type. To declare variables following syntax needs to be followed: var var_name data_type var var_name data_type fmt.Scanln(&first) is used to take input from user in the next line. While fmt.Scan is used to take input from user in the same line. Ampersand is necessary to give the reference as to in which variable we have to store the variable. The Last line will simply add the two string of First Name and Last Name and will output the Full Name. Golang-Program Picked Go Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n10 May, 2020" }, { "code": null, "e": 181, "s": 54, "text": "Scanln function can be used to take the input from the user in the Golang. Below is the example of taking input from the user:" }, { "code": "// Golang program to show how// to take input from the userpackage main import \"fmt\" // main functionfunc main() { // Println function is used to // display output in the next line fmt.Println(\"Enter Your First Name: \") // var then variable name then variable type var first string // Taking input from user fmt.Scanln(&first) fmt.Println(\"Enter Second Last Name: \") var second string fmt.Scanln(&second) // Print function is used to // display output in the same line fmt.Print(\"Your Full Name is: \") // Addition of two string fmt.Print(first + \" \" + second)}", "e": 799, "s": 181, "text": null }, { "code": null, "e": 864, "s": 799, "text": "Now save this file and execute as shown in the below screenshot:" }, { "code": null, "e": 895, "s": 864, "text": "Description About the Program:" }, { "code": null, "e": 1449, "s": 895, "text": "main Package: When we build reusable pieces of code, we will develop a package as a shared library. But when we develop an executable program, we will use the package “main” for making the package as an executable program. The package “main” tells the Golang compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program. Remember when we build shared libraries, we will not have any main package and main function in the package." }, { "code": null, "e": 1666, "s": 1449, "text": "fmt.Println is the print function which is used to print the output in the next line. While fmt.Print is used to display output in the same line. Whatever needs to be printed has to be written in inverted commas ” “." }, { "code": null, "e": 1833, "s": 1666, "text": "var first string is the declaration of the variable first which is of string type. To declare variables following syntax needs to be followed: var var_name data_type " }, { "code": null, "e": 1858, "s": 1833, "text": " var var_name data_type " }, { "code": null, "e": 2092, "s": 1858, "text": "fmt.Scanln(&first) is used to take input from user in the next line. While fmt.Scan is used to take input from user in the same line. Ampersand is necessary to give the reference as to in which variable we have to store the variable." }, { "code": null, "e": 2196, "s": 2092, "text": "The Last line will simply add the two string of First Name and Last Name and will output the Full Name." }, { "code": null, "e": 2211, "s": 2196, "text": "Golang-Program" }, { "code": null, "e": 2218, "s": 2211, "text": "Picked" }, { "code": null, "e": 2230, "s": 2218, "text": "Go Language" }, { "code": null, "e": 2246, "s": 2230, "text": "Write From Home" }, { "code": null, "e": 2344, "s": 2246, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2395, "s": 2344, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 2408, "s": 2395, "text": "Arrays in Go" }, { "code": null, "e": 2420, "s": 2408, "text": "Golang Maps" }, { "code": null, "e": 2453, "s": 2420, "text": "How to Split a String in Golang?" }, { "code": null, "e": 2474, "s": 2453, "text": "Interfaces in Golang" }, { "code": null, "e": 2510, "s": 2474, "text": "Convert integer to string in Python" }, { "code": null, "e": 2546, "s": 2510, "text": "Convert string to integer in Python" }, { "code": null, "e": 2607, "s": 2546, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2623, "s": 2607, "text": "Python infinity" } ]
Python | Sort a List according to the Length of the Elements
19 Apr, 2020 In this program, we need to accept a list and sort it based on the length of the elements present within.Examples: Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "ankita", "rinku"]] Output : [['gaurav'], ['ram', 'mohan', 'aman'], ['amy', 'sima', 'ankita', 'rinku']] Note: The first example comprises of Strings whose length can be calculated. The second example comprises of sublists, which is also arranged according to there length. There are many ways of performing this. Anyone can use there own algorithmic technique, but Python provides us with various built-in functions to perform these. The built-in functions include sort() and sorted() along with the key parameter. We can perform these in two ways. One way is to sort the list by creating a new list and another way is to sort within the given list, saving space. The syntax for sorting by creating a new list is: sorted_list = sorted(unsorted_list, key=len) # Python code to sort a list by creating # another list Use of sorted()def Sorting(lst): lst2 = sorted(lst, key=len) return lst2 # Driver codelst = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"]print(Sorting(lst)) The syntax for sorting without creating a new list is: unsorted_list.sort(key=len) # Python code to sort a list without # creating another list Use of sort()def Sorting(lst): lst.sort(key=len) return lst # Driver codelst = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"]print(Sorting(lst)) Output: ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Working:These key function of Python’s while sorting implemented is known as the decorate-sort-undecorate design pattern. It follows the following steps: Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.The list is sorted based upon the natural order of the keys.The decorated elements are replaced by the original elements. Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element. The list is sorted based upon the natural order of the keys. The decorated elements are replaced by the original elements. The code for sorting by creating a new dummy list is: import numpy def Sorting(lst): # list for storing the length of each string in list lenlist=[] for x in lst: lenlist.append(len(x)) # return a list with the index of the sorted # items in the list sortedindex = numpy.argsort(lenlist) # creating a dummy list where we will place the # word according to the sortedindex list lst2 = ['dummy']*len(lst) # print(sortedindex,lenlist) for i in range(len(lst)): # placing element in the lst2 list by taking the # value from original list lst where it should belong # in the sorted list by taking its index from sortedindex lst2[i] = lst[sortedindex[i]] return lst2 # Driver codelst = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"]print(Sorting(lst)) Output: ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Reference: stackoverflow anand27 Python list-programs python-list Python Sorting python-list Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 143, "s": 28, "text": "In this program, we need to accept a list and sort it based on the length of the elements present within.Examples:" }, { "code": null, "e": 710, "s": 143, "text": "Input : list = [\"rohan\", \"amy\", \"sapna\", \"muhammad\",\n \"aakash\", \"raunak\", \"chinmoy\"]\nOutput : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', \n 'chinmoy', 'muhammad']\n\nInput : list = [[\"ram\", \"mohan\", \"aman\"], [\"gaurav\"], \n [\"amy\", \"sima\", \"ankita\", \"rinku\"]]\nOutput : [['gaurav'], ['ram', 'mohan', 'aman'], \n ['amy', 'sima', 'ankita', 'rinku']]\n\nNote: The first example comprises of Strings whose \nlength can be calculated. The second example comprises \nof sublists, which is also arranged according to there \nlength. \n" }, { "code": null, "e": 1101, "s": 710, "text": "There are many ways of performing this. Anyone can use there own algorithmic technique, but Python provides us with various built-in functions to perform these. The built-in functions include sort() and sorted() along with the key parameter. We can perform these in two ways. One way is to sort the list by creating a new list and another way is to sort within the given list, saving space." }, { "code": null, "e": 1151, "s": 1101, "text": "The syntax for sorting by creating a new list is:" }, { "code": null, "e": 1196, "s": 1151, "text": "sorted_list = sorted(unsorted_list, key=len)" }, { "code": "# Python code to sort a list by creating # another list Use of sorted()def Sorting(lst): lst2 = sorted(lst, key=len) return lst2 # Driver codelst = [\"rohan\", \"amy\", \"sapna\", \"muhammad\", \"aakash\", \"raunak\", \"chinmoy\"]print(Sorting(lst))", "e": 1450, "s": 1196, "text": null }, { "code": null, "e": 1505, "s": 1450, "text": "The syntax for sorting without creating a new list is:" }, { "code": null, "e": 1533, "s": 1505, "text": "unsorted_list.sort(key=len)" }, { "code": "# Python code to sort a list without # creating another list Use of sort()def Sorting(lst): lst.sort(key=len) return lst # Driver codelst = [\"rohan\", \"amy\", \"sapna\", \"muhammad\", \"aakash\", \"raunak\", \"chinmoy\"]print(Sorting(lst))", "e": 1779, "s": 1533, "text": null }, { "code": null, "e": 1787, "s": 1779, "text": "Output:" }, { "code": null, "e": 1857, "s": 1787, "text": "['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']\n" }, { "code": null, "e": 2011, "s": 1857, "text": "Working:These key function of Python’s while sorting implemented is known as the decorate-sort-undecorate design pattern. It follows the following steps:" }, { "code": null, "e": 2277, "s": 2011, "text": "Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.The list is sorted based upon the natural order of the keys.The decorated elements are replaced by the original elements." }, { "code": null, "e": 2422, "s": 2277, "text": "Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element." }, { "code": null, "e": 2483, "s": 2422, "text": "The list is sorted based upon the natural order of the keys." }, { "code": null, "e": 2545, "s": 2483, "text": "The decorated elements are replaced by the original elements." }, { "code": null, "e": 2599, "s": 2545, "text": "The code for sorting by creating a new dummy list is:" }, { "code": "import numpy def Sorting(lst): # list for storing the length of each string in list lenlist=[] for x in lst: lenlist.append(len(x)) # return a list with the index of the sorted # items in the list sortedindex = numpy.argsort(lenlist) # creating a dummy list where we will place the # word according to the sortedindex list lst2 = ['dummy']*len(lst) # print(sortedindex,lenlist) for i in range(len(lst)): # placing element in the lst2 list by taking the # value from original list lst where it should belong # in the sorted list by taking its index from sortedindex lst2[i] = lst[sortedindex[i]] return lst2 # Driver codelst = [\"rohan\", \"amy\", \"sapna\", \"muhammad\", \"aakash\", \"raunak\", \"chinmoy\"]print(Sorting(lst))", "e": 3476, "s": 2599, "text": null }, { "code": null, "e": 3484, "s": 3476, "text": "Output:" }, { "code": null, "e": 3554, "s": 3484, "text": "['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']\n" }, { "code": null, "e": 3579, "s": 3554, "text": "Reference: stackoverflow" }, { "code": null, "e": 3587, "s": 3579, "text": "anand27" }, { "code": null, "e": 3608, "s": 3587, "text": "Python list-programs" }, { "code": null, "e": 3620, "s": 3608, "text": "python-list" }, { "code": null, "e": 3627, "s": 3620, "text": "Python" }, { "code": null, "e": 3635, "s": 3627, "text": "Sorting" }, { "code": null, "e": 3647, "s": 3635, "text": "python-list" }, { "code": null, "e": 3655, "s": 3647, "text": "Sorting" }, { "code": null, "e": 3753, "s": 3655, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3795, "s": 3753, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3817, "s": 3795, "text": "Enumerate() in Python" }, { "code": null, "e": 3852, "s": 3817, "text": "Read a file line by line in Python" }, { "code": null, "e": 3878, "s": 3852, "text": "Python String | replace()" }, { "code": null, "e": 3910, "s": 3878, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3921, "s": 3910, "text": "Merge Sort" }, { "code": null, "e": 3943, "s": 3921, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 3953, "s": 3943, "text": "QuickSort" }, { "code": null, "e": 3968, "s": 3953, "text": "Insertion Sort" } ]
How to Create ToDo App using ReactJS ?
02 Apr, 2020 React is a JavaScript library used to develop interactive user interfaces. It is managed by Facebook and a community of individual developers and companies. React mainly focuses on developing single-page web or mobile applications. here, we will create a todo app to understand the basics of reactJS. Modules required: npm React React Bootstrapnpm install react-bootstrap bootstrap npm install react-bootstrap bootstrap Basic setup: Start a project by the following command: NPX: It is a package runner tool that comes with npm 5.2+, npx is easy to use CLI tools. The npx is used for executing Node packages. It greatly simplifies a number of things one of which is checked/run a node package quickly without installing it locally or globally.npx create-react-app todo-react npx create-react-app todo-react Now, goto the foldercd todo-react cd todo-react Start the server- Start the server by typing the following command in terminal:npm startopen http://localhost:3000/ npm start open http://localhost:3000/ Change directory to src:cd src cd src Delete every thing inside the directoryrm * rm * Now create index.js filetouch index.js touch index.js This file will render our app to HTML file which is in public folder. Also create a folder name components with file name app.jsmkdir components && cd components && touch app.js mkdir components && cd components && touch app.js app.js will contain our To-Do app: Edit index.js file in src:import React from 'react';import ReactDOM from 'react-dom';import App from './components/app';import 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render(<App />, document.getElementById('root')); import React from 'react';import ReactDOM from 'react-dom';import App from './components/app';import 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render(<App />, document.getElementById('root')); Edit app.js in components:import React, {Component} from 'react'; // Bootstrap for reactimport Container from 'react-bootstrap/Container';import Row from 'react-bootstrap/Row';import Col from 'react-bootstrap/Col';import Button from 'react-bootstrap/Button';import InputGroup from 'react-bootstrap/InputGroup';import FormControl from 'react-bootstrap/FormControl';import ListGroup from 'react-bootstrap/ListGroup'; class App extends Component { constructor(props) { super(props); // Setting up state this.state = { userInput : "", list:[] } } // Set a user input value updateInput(value){ this.setState({ userInput: value, }); } // Add item if user input in not empty addItem(){ if(this.state.userInput !== '' ){ const userInput = { // Add a random id which is used to delete id : Math.random(), // Add a user value to list value : this.state.userInput }; // Update list const list = [...this.state.list]; list.push(userInput); // reset state this.setState({ list, userInput:"" }); } } // Function to delete item from list use id to delete deleteItem(key){ const list = [...this.state.list]; // Filter values and leave value which we need to delete const updateList = list.filter(item => item.id !== key); // Update list in state this.setState({ list:updateList, }); } render(){ return(<Container> <Row style={{ display: "flex", justifyContent: "center", alignItems: "center", fontSize: '3rem', fontWeight: 'bolder', }} >TODO LIST </Row> <hr/> <Row> <Col md={{ span: 5, offset: 4 }}> <InputGroup className="mb-3"> <FormControl placeholder="add item . . . " size="lg" value = {this.state.userInput} onChange = {item => this.updateInput(item.target.value)} aria-label="add something" aria-describedby="basic-addon2" /> <InputGroup.Append> <Button variant="dark" size="lg" onClick = {()=>this.addItem()} > ADD </Button> </InputGroup.Append> </InputGroup> </Col> </Row> <Row> <Col md={{ span: 5, offset: 4 }}> <ListGroup> {/* map over and print items */} {this.state.list.map(item => {return( <ListGroup.Item variant="dark" action onClick = { () => this.deleteItem(item.id) }> {item.value} </ListGroup.Item> )})} </ListGroup> </Col> </Row> </Container> ); }} export default App; import React, {Component} from 'react'; // Bootstrap for reactimport Container from 'react-bootstrap/Container';import Row from 'react-bootstrap/Row';import Col from 'react-bootstrap/Col';import Button from 'react-bootstrap/Button';import InputGroup from 'react-bootstrap/InputGroup';import FormControl from 'react-bootstrap/FormControl';import ListGroup from 'react-bootstrap/ListGroup'; class App extends Component { constructor(props) { super(props); // Setting up state this.state = { userInput : "", list:[] } } // Set a user input value updateInput(value){ this.setState({ userInput: value, }); } // Add item if user input in not empty addItem(){ if(this.state.userInput !== '' ){ const userInput = { // Add a random id which is used to delete id : Math.random(), // Add a user value to list value : this.state.userInput }; // Update list const list = [...this.state.list]; list.push(userInput); // reset state this.setState({ list, userInput:"" }); } } // Function to delete item from list use id to delete deleteItem(key){ const list = [...this.state.list]; // Filter values and leave value which we need to delete const updateList = list.filter(item => item.id !== key); // Update list in state this.setState({ list:updateList, }); } render(){ return(<Container> <Row style={{ display: "flex", justifyContent: "center", alignItems: "center", fontSize: '3rem', fontWeight: 'bolder', }} >TODO LIST </Row> <hr/> <Row> <Col md={{ span: 5, offset: 4 }}> <InputGroup className="mb-3"> <FormControl placeholder="add item . . . " size="lg" value = {this.state.userInput} onChange = {item => this.updateInput(item.target.value)} aria-label="add something" aria-describedby="basic-addon2" /> <InputGroup.Append> <Button variant="dark" size="lg" onClick = {()=>this.addItem()} > ADD </Button> </InputGroup.Append> </InputGroup> </Col> </Row> <Row> <Col md={{ span: 5, offset: 4 }}> <ListGroup> {/* map over and print items */} {this.state.list.map(item => {return( <ListGroup.Item variant="dark" action onClick = { () => this.deleteItem(item.id) }> {item.value} </ListGroup.Item> )})} </ListGroup> </Col> </Row> </Container> ); }} export default App; Save all files and start the server:npm start npm start Output: Open http://localhost:3000/ in browser: react-js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Apr, 2020" }, { "code": null, "e": 353, "s": 52, "text": "React is a JavaScript library used to develop interactive user interfaces. It is managed by Facebook and a community of individual developers and companies. React mainly focuses on developing single-page web or mobile applications. here, we will create a todo app to understand the basics of reactJS." }, { "code": null, "e": 371, "s": 353, "text": "Modules required:" }, { "code": null, "e": 375, "s": 371, "text": "npm" }, { "code": null, "e": 381, "s": 375, "text": "React" }, { "code": null, "e": 434, "s": 381, "text": "React Bootstrapnpm install react-bootstrap bootstrap" }, { "code": null, "e": 472, "s": 434, "text": "npm install react-bootstrap bootstrap" }, { "code": null, "e": 527, "s": 472, "text": "Basic setup: Start a project by the following command:" }, { "code": null, "e": 827, "s": 527, "text": "NPX: It is a package runner tool that comes with npm 5.2+, npx is easy to use CLI tools. The npx is used for executing Node packages. It greatly simplifies a number of things one of which is checked/run a node package quickly without installing it locally or globally.npx create-react-app todo-react" }, { "code": null, "e": 859, "s": 827, "text": "npx create-react-app todo-react" }, { "code": null, "e": 893, "s": 859, "text": "Now, goto the foldercd todo-react" }, { "code": null, "e": 907, "s": 893, "text": "cd todo-react" }, { "code": null, "e": 1023, "s": 907, "text": "Start the server- Start the server by typing the following command in terminal:npm startopen http://localhost:3000/" }, { "code": null, "e": 1033, "s": 1023, "text": "npm start" }, { "code": null, "e": 1061, "s": 1033, "text": "open http://localhost:3000/" }, { "code": null, "e": 1092, "s": 1061, "text": "Change directory to src:cd src" }, { "code": null, "e": 1099, "s": 1092, "text": "cd src" }, { "code": null, "e": 1143, "s": 1099, "text": "Delete every thing inside the directoryrm *" }, { "code": null, "e": 1148, "s": 1143, "text": "rm *" }, { "code": null, "e": 1188, "s": 1148, "text": "Now create index.js filetouch index.js " }, { "code": null, "e": 1204, "s": 1188, "text": "touch index.js " }, { "code": null, "e": 1382, "s": 1204, "text": "This file will render our app to HTML file which is in public folder. Also create a folder name components with file name app.jsmkdir components && cd components && touch app.js" }, { "code": null, "e": 1432, "s": 1382, "text": "mkdir components && cd components && touch app.js" }, { "code": null, "e": 1467, "s": 1432, "text": "app.js will contain our To-Do app:" }, { "code": null, "e": 1694, "s": 1467, "text": "Edit index.js file in src:import React from 'react';import ReactDOM from 'react-dom';import App from './components/app';import 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render(<App />, document.getElementById('root'));" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import App from './components/app';import 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render(<App />, document.getElementById('root'));", "e": 1895, "s": 1694, "text": null }, { "code": null, "e": 4754, "s": 1895, "text": "Edit app.js in components:import React, {Component} from 'react'; // Bootstrap for reactimport Container from 'react-bootstrap/Container';import Row from 'react-bootstrap/Row';import Col from 'react-bootstrap/Col';import Button from 'react-bootstrap/Button';import InputGroup from 'react-bootstrap/InputGroup';import FormControl from 'react-bootstrap/FormControl';import ListGroup from 'react-bootstrap/ListGroup'; class App extends Component { constructor(props) { super(props); // Setting up state this.state = { userInput : \"\", list:[] } } // Set a user input value updateInput(value){ this.setState({ userInput: value, }); } // Add item if user input in not empty addItem(){ if(this.state.userInput !== '' ){ const userInput = { // Add a random id which is used to delete id : Math.random(), // Add a user value to list value : this.state.userInput }; // Update list const list = [...this.state.list]; list.push(userInput); // reset state this.setState({ list, userInput:\"\" }); } } // Function to delete item from list use id to delete deleteItem(key){ const list = [...this.state.list]; // Filter values and leave value which we need to delete const updateList = list.filter(item => item.id !== key); // Update list in state this.setState({ list:updateList, }); } render(){ return(<Container> <Row style={{ display: \"flex\", justifyContent: \"center\", alignItems: \"center\", fontSize: '3rem', fontWeight: 'bolder', }} >TODO LIST </Row> <hr/> <Row> <Col md={{ span: 5, offset: 4 }}> <InputGroup className=\"mb-3\"> <FormControl placeholder=\"add item . . . \" size=\"lg\" value = {this.state.userInput} onChange = {item => this.updateInput(item.target.value)} aria-label=\"add something\" aria-describedby=\"basic-addon2\" /> <InputGroup.Append> <Button variant=\"dark\" size=\"lg\" onClick = {()=>this.addItem()} > ADD </Button> </InputGroup.Append> </InputGroup> </Col> </Row> <Row> <Col md={{ span: 5, offset: 4 }}> <ListGroup> {/* map over and print items */} {this.state.list.map(item => {return( <ListGroup.Item variant=\"dark\" action onClick = { () => this.deleteItem(item.id) }> {item.value} </ListGroup.Item> )})} </ListGroup> </Col> </Row> </Container> ); }} export default App;" }, { "code": "import React, {Component} from 'react'; // Bootstrap for reactimport Container from 'react-bootstrap/Container';import Row from 'react-bootstrap/Row';import Col from 'react-bootstrap/Col';import Button from 'react-bootstrap/Button';import InputGroup from 'react-bootstrap/InputGroup';import FormControl from 'react-bootstrap/FormControl';import ListGroup from 'react-bootstrap/ListGroup'; class App extends Component { constructor(props) { super(props); // Setting up state this.state = { userInput : \"\", list:[] } } // Set a user input value updateInput(value){ this.setState({ userInput: value, }); } // Add item if user input in not empty addItem(){ if(this.state.userInput !== '' ){ const userInput = { // Add a random id which is used to delete id : Math.random(), // Add a user value to list value : this.state.userInput }; // Update list const list = [...this.state.list]; list.push(userInput); // reset state this.setState({ list, userInput:\"\" }); } } // Function to delete item from list use id to delete deleteItem(key){ const list = [...this.state.list]; // Filter values and leave value which we need to delete const updateList = list.filter(item => item.id !== key); // Update list in state this.setState({ list:updateList, }); } render(){ return(<Container> <Row style={{ display: \"flex\", justifyContent: \"center\", alignItems: \"center\", fontSize: '3rem', fontWeight: 'bolder', }} >TODO LIST </Row> <hr/> <Row> <Col md={{ span: 5, offset: 4 }}> <InputGroup className=\"mb-3\"> <FormControl placeholder=\"add item . . . \" size=\"lg\" value = {this.state.userInput} onChange = {item => this.updateInput(item.target.value)} aria-label=\"add something\" aria-describedby=\"basic-addon2\" /> <InputGroup.Append> <Button variant=\"dark\" size=\"lg\" onClick = {()=>this.addItem()} > ADD </Button> </InputGroup.Append> </InputGroup> </Col> </Row> <Row> <Col md={{ span: 5, offset: 4 }}> <ListGroup> {/* map over and print items */} {this.state.list.map(item => {return( <ListGroup.Item variant=\"dark\" action onClick = { () => this.deleteItem(item.id) }> {item.value} </ListGroup.Item> )})} </ListGroup> </Col> </Row> </Container> ); }} export default App;", "e": 7587, "s": 4754, "text": null }, { "code": null, "e": 7633, "s": 7587, "text": "Save all files and start the server:npm start" }, { "code": null, "e": 7643, "s": 7633, "text": "npm start" }, { "code": null, "e": 7691, "s": 7643, "text": "Output: Open http://localhost:3000/ in browser:" }, { "code": null, "e": 7700, "s": 7691, "text": "react-js" }, { "code": null, "e": 7717, "s": 7700, "text": "Web Technologies" }, { "code": null, "e": 7744, "s": 7717, "text": "Web technologies Questions" } ]
Pair of integers (a, b) which satisfy the given equations
30 Jan, 2022 Given the system of equations a2 + b = n and a + b2 = m. The task is to find the number of pair of positive integers (a, b) which satisfy the equation for given n and m.Examples: Input: n = 9, m = 3 Output: 1 Explanation: Only one pair (3, 0) exists for both equations satisfying the conditions.Input: n = 4, m = 20 Output: 0 Explanation: There are no such pair exists. Approach: The approach is to check for all possible pairs of numbers and check if that pair satisfy both the equations or not. For this we have, a2 + b = n ... (1) a + b2 = m ... (2) For equation (2), => a = m - b2 ... (3) Now for the positive value of a, every value of b must be from 0 to sqrt(m). Obtain the value of a from equations (3). If the pair (a, b) satisfy equation (1), then pair (a, b) is the solution of system of equations. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = m#include <bits/stdc++.h>using namespace std; // Function to count valid pairsint pairCount(int n, int m){ int cnt = 0, b, a; for (b = 0; b <= sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codeint main(){ int n = 9, m = 3; cout << pairCount(n, m) << endl; return 0;} // Java program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = mclass GFG{ // Function to count valid pairsstatic int pairCount(int n, int m){ int cnt = 0, b, a; for (b = 0; b <= Math.sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codepublic static void main(String[] args){ int n = 9, m = 3; System.out.print(pairCount(n, m) +"\n");}} // This code is contributed by 29AjayKumar # Python3 program to count the pair of integers(a, b)# which satisfy the equation# a^2 + b = n and a + b^2 = m # Function to count valid pairsdef pairCount(n, m): cnt = 0; for b in range(int(pow(m, 1/2))): a = m - b * b; if (a * a + b == n): cnt += 1; return cnt; # Driver codeif __name__ == '__main__': n = 9; m = 3; print(pairCount(n, m)); # This code is contributed by 29AjayKumar // C# program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = musing System; class GFG{ // Function to count valid pairsstatic int pairCount(int n, int m){ int cnt = 0, b, a; for (b = 0; b <= Math.Sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codepublic static void Main(String[] args){ int n = 9, m = 3; Console.Write(pairCount(n, m) +"\n");}} // This code is contributed by 29AjayKumar <script>// javascript program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = m // Function to count valid pairsfunction pairCount(n , m){ var cnt = 0, b, a; for (b = 0; b <= Math.sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codevar n = 9, m = 3;document.write(pairCount(n, m)); // This code is contributed by Amit Katiyar</script> 1 Time Complexity: O(sqrt(min(n,m)) Auxiliary Space: O(1) 29AjayKumar amit143katiyar subham348 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modular multiplicative inverse Find first and last digits of a number Find cubic root of a number Program to add two binary strings Count all possible paths from top left to bottom right of a mXn matrix Algorithm to solve Rubik's Cube Program for distance between two points on earth Pascal's Triangle Segment Tree | Set 1 (Sum of given range) Postfix to Infix
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2022" }, { "code": null, "e": 209, "s": 28, "text": "Given the system of equations a2 + b = n and a + b2 = m. The task is to find the number of pair of positive integers (a, b) which satisfy the equation for given n and m.Examples: " }, { "code": null, "e": 402, "s": 209, "text": "Input: n = 9, m = 3 Output: 1 Explanation: Only one pair (3, 0) exists for both equations satisfying the conditions.Input: n = 4, m = 20 Output: 0 Explanation: There are no such pair exists. " }, { "code": null, "e": 551, "s": 404, "text": "Approach: The approach is to check for all possible pairs of numbers and check if that pair satisfy both the equations or not. For this we have, " }, { "code": null, "e": 636, "s": 551, "text": " a2 + b = n ... (1)\n a + b2 = m ... (2)\nFor equation (2), \n=> a = m - b2 ... (3)" }, { "code": null, "e": 715, "s": 638, "text": "Now for the positive value of a, every value of b must be from 0 to sqrt(m)." }, { "code": null, "e": 757, "s": 715, "text": "Obtain the value of a from equations (3)." }, { "code": null, "e": 855, "s": 757, "text": "If the pair (a, b) satisfy equation (1), then pair (a, b) is the solution of system of equations." }, { "code": null, "e": 908, "s": 855, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 912, "s": 908, "text": "C++" }, { "code": null, "e": 917, "s": 912, "text": "Java" }, { "code": null, "e": 925, "s": 917, "text": "Python3" }, { "code": null, "e": 928, "s": 925, "text": "C#" }, { "code": null, "e": 939, "s": 928, "text": "Javascript" }, { "code": "// C++ program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = m#include <bits/stdc++.h>using namespace std; // Function to count valid pairsint pairCount(int n, int m){ int cnt = 0, b, a; for (b = 0; b <= sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codeint main(){ int n = 9, m = 3; cout << pairCount(n, m) << endl; return 0;}", "e": 1410, "s": 939, "text": null }, { "code": "// Java program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = mclass GFG{ // Function to count valid pairsstatic int pairCount(int n, int m){ int cnt = 0, b, a; for (b = 0; b <= Math.sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codepublic static void main(String[] args){ int n = 9, m = 3; System.out.print(pairCount(n, m) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 1935, "s": 1410, "text": null }, { "code": "# Python3 program to count the pair of integers(a, b)# which satisfy the equation# a^2 + b = n and a + b^2 = m # Function to count valid pairsdef pairCount(n, m): cnt = 0; for b in range(int(pow(m, 1/2))): a = m - b * b; if (a * a + b == n): cnt += 1; return cnt; # Driver codeif __name__ == '__main__': n = 9; m = 3; print(pairCount(n, m)); # This code is contributed by 29AjayKumar", "e": 2375, "s": 1935, "text": null }, { "code": "// C# program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = musing System; class GFG{ // Function to count valid pairsstatic int pairCount(int n, int m){ int cnt = 0, b, a; for (b = 0; b <= Math.Sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codepublic static void Main(String[] args){ int n = 9, m = 3; Console.Write(pairCount(n, m) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 2909, "s": 2375, "text": null }, { "code": "<script>// javascript program to count the pair of integers(a, b)// which satisfy the equation// a^2 + b = n and a + b^2 = m // Function to count valid pairsfunction pairCount(n , m){ var cnt = 0, b, a; for (b = 0; b <= Math.sqrt(m); b++) { a = m - b * b; if (a * a + b == n) { cnt++; } } return cnt;} // Driver codevar n = 9, m = 3;document.write(pairCount(n, m)); // This code is contributed by Amit Katiyar</script>", "e": 3382, "s": 2909, "text": null }, { "code": null, "e": 3384, "s": 3382, "text": "1" }, { "code": null, "e": 3420, "s": 3386, "text": "Time Complexity: O(sqrt(min(n,m))" }, { "code": null, "e": 3443, "s": 3420, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 3455, "s": 3443, "text": "29AjayKumar" }, { "code": null, "e": 3470, "s": 3455, "text": "amit143katiyar" }, { "code": null, "e": 3480, "s": 3470, "text": "subham348" }, { "code": null, "e": 3493, "s": 3480, "text": "Mathematical" }, { "code": null, "e": 3506, "s": 3493, "text": "Mathematical" }, { "code": null, "e": 3604, "s": 3506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3635, "s": 3604, "text": "Modular multiplicative inverse" }, { "code": null, "e": 3674, "s": 3635, "text": "Find first and last digits of a number" }, { "code": null, "e": 3702, "s": 3674, "text": "Find cubic root of a number" }, { "code": null, "e": 3736, "s": 3702, "text": "Program to add two binary strings" }, { "code": null, "e": 3807, "s": 3736, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 3839, "s": 3807, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3888, "s": 3839, "text": "Program for distance between two points on earth" }, { "code": null, "e": 3906, "s": 3888, "text": "Pascal's Triangle" }, { "code": null, "e": 3948, "s": 3906, "text": "Segment Tree | Set 1 (Sum of given range)" } ]
Multilevel Paging in Operating System
13 Jun, 2022 Prerequisite – Paging Multilevel Paging is a paging scheme that consists of two or more levels of page tables in a hierarchical manner. It is also known as hierarchical paging. The entries of the level 1 page table are pointers to a level 2 page table and entries of the level 2 page tables are pointers to a level 3 page table and so on. The entries of the last level page table store actual frame information. Level 1 contains a single-page table and the address of that table is stored in PTBR (Page Table Base Register). Why it is required? If the frame size of the main memory is smaller than the page size and the process cannot fit that way then we divide the pages into further pages, and this concept is known as multilevel paging. Virtual address: In multilevel paging whatever may be levels of paging, all the page tables will be stored in the main memory. So it requires more than one memory access to get the physical address of the page frame. One access for each level is needed. Each page table entry except the last level page table entry contains the base address of the next level page table. Reference to actual page frame: Reference to PTE in level 1 page table = PTBR value + Level 1 offset present in virtual address. Reference to PTE in level 2 page table = Base address (present in Level 1 PTE) + Level 2 offset (present in VA). Reference to PTE in level 3 page table= Base address (present in Level 2 PTE) + Level 3 offset (present in VA). Actual page frame address = PTE (present in level 3). Generally, the page table size will be equal to the size of the page. Assumptions: Byte addressable memory and n is the number of bits used to represent virtual address. Important formula: Number of entries in page table: = (virtual address space size) / (page size) = Number of pages Virtual address space size: = 2n B Size of page table: <>= (number of entries in page table)*(size of PTE) If page table size > desired size then create 1 more level. Disadvantage: Extra memory references to access address translation tables can slow programs down by a factor of two or more. Use translation look aside buffer (TLB) to speed up address translation by storing page table entries. Example: Q.Consider a virtual memory system with physical memory of 8GB, a page size of 8KB, and 46-bit virtual address. Assume every page table exactly fits into a single page. If page table entry size is 4B then how many levels of page tables would be required. Explanation: Page size = 8KB = 213 B Virtual address space size = 246 B PTE = 4B = 22 B Number of pages or number of entries in page table, = (virtual address space size) / (page size) = 246B/213 B = 233 Size of page table, = (number of entries in page table)*(size of PTE) = 233*22 B = 235 B To create one more level, Size of page table > page size Number of page tables in last level, = 235 B / 213 B = 222 The base address of these tables is stored in page table [second last level]. Size of page table [second last level] = 222*22B = 224B To create one more level, Size of page table [second last level] > page size Number of page tables in second last level = 224B/213 B = 211 The base address of these tables are stored in page table [third last level] Size of page table [third last level] = 211*22 B = 213 B = page size ∴ 3 levels are required. f20180107 geeky01adarsh GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Normal Forms in DBMS Introduction of Operating System - Set 1 Inter Process Communication (IPC) Differences between TCP and UDP Cache Memory in Computer Organization Banker's Algorithm in Operating System Disk Scheduling Algorithms Introduction of Operating System - Set 1 Introduction of Deadlock in Operating System Inter Process Communication (IPC)
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 75, "s": 52, "text": "Prerequisite – Paging " }, { "code": null, "e": 578, "s": 75, "text": "Multilevel Paging is a paging scheme that consists of two or more levels of page tables in a hierarchical manner. It is also known as hierarchical paging. The entries of the level 1 page table are pointers to a level 2 page table and entries of the level 2 page tables are pointers to a level 3 page table and so on. The entries of the last level page table store actual frame information. Level 1 contains a single-page table and the address of that table is stored in PTBR (Page Table Base Register)." }, { "code": null, "e": 598, "s": 578, "text": "Why it is required?" }, { "code": null, "e": 794, "s": 598, "text": "If the frame size of the main memory is smaller than the page size and the process cannot fit that way then we divide the pages into further pages, and this concept is known as multilevel paging." }, { "code": null, "e": 812, "s": 794, "text": "Virtual address: " }, { "code": null, "e": 1167, "s": 812, "text": "In multilevel paging whatever may be levels of paging, all the page tables will be stored in the main memory. So it requires more than one memory access to get the physical address of the page frame. One access for each level is needed. Each page table entry except the last level page table entry contains the base address of the next level page table. " }, { "code": null, "e": 1200, "s": 1167, "text": "Reference to actual page frame: " }, { "code": null, "e": 1297, "s": 1200, "text": "Reference to PTE in level 1 page table = PTBR value + Level 1 offset present in virtual address." }, { "code": null, "e": 1411, "s": 1297, "text": "Reference to PTE in level 2 page table = Base address (present in Level 1 PTE) + Level 2 offset (present in VA). " }, { "code": null, "e": 1524, "s": 1411, "text": "Reference to PTE in level 3 page table= Base address (present in Level 2 PTE) + Level 3 offset (present in VA). " }, { "code": null, "e": 1580, "s": 1524, "text": "Actual page frame address = PTE (present in level 3). " }, { "code": null, "e": 1651, "s": 1580, "text": "Generally, the page table size will be equal to the size of the page. " }, { "code": null, "e": 1752, "s": 1651, "text": "Assumptions: Byte addressable memory and n is the number of bits used to represent virtual address. " }, { "code": null, "e": 1773, "s": 1752, "text": "Important formula: " }, { "code": null, "e": 1984, "s": 1773, "text": "Number of entries in page table: \n= (virtual address space size) / (page size) \n= Number of pages\n\nVirtual address space size: \n= 2n B \n\nSize of page table: \n<>= (number of entries in page table)*(size of PTE) " }, { "code": null, "e": 2045, "s": 1984, "text": "If page table size > desired size then create 1 more level. " }, { "code": null, "e": 2275, "s": 2045, "text": "Disadvantage: Extra memory references to access address translation tables can slow programs down by a factor of two or more. Use translation look aside buffer (TLB) to speed up address translation by storing page table entries. " }, { "code": null, "e": 2540, "s": 2275, "text": "Example: Q.Consider a virtual memory system with physical memory of 8GB, a page size of 8KB, and 46-bit virtual address. Assume every page table exactly fits into a single page. If page table entry size is 4B then how many levels of page tables would be required. " }, { "code": null, "e": 2554, "s": 2540, "text": "Explanation: " }, { "code": null, "e": 2750, "s": 2554, "text": "Page size = 8KB = 213 B\nVirtual address space size = 246 B\nPTE = 4B = 22 B\n\nNumber of pages or number of entries in page table, \n= (virtual address space size) / (page size) \n= 246B/213 B \n= 233 " }, { "code": null, "e": 2771, "s": 2750, "text": "Size of page table, " }, { "code": null, "e": 2843, "s": 2771, "text": "= (number of entries in page table)*(size of PTE) \n= 233*22 B \n= 235 B " }, { "code": null, "e": 2871, "s": 2843, "text": "To create one more level, " }, { "code": null, "e": 2965, "s": 2871, "text": "Size of page table > page size\n\nNumber of page tables in last level, \n= 235 B / 213 B \n= 222 " }, { "code": null, "e": 3044, "s": 2965, "text": "The base address of these tables is stored in page table [second last level]. " }, { "code": null, "e": 3103, "s": 3044, "text": "Size of page table [second last level] \n= 222*22B \n= 224B " }, { "code": null, "e": 3182, "s": 3103, "text": "To create one more level, Size of page table [second last level] > page size " }, { "code": null, "e": 3247, "s": 3182, "text": "Number of page tables in second last level \n= 224B/213 B \n= 211 " }, { "code": null, "e": 3326, "s": 3247, "text": "The base address of these tables are stored in page table [third last level] " }, { "code": null, "e": 3399, "s": 3326, "text": "Size of page table [third last level] \n= 211*22 B \n= 213 B \n= page size " }, { "code": null, "e": 3425, "s": 3399, "text": "∴ 3 levels are required. " }, { "code": null, "e": 3435, "s": 3425, "text": "f20180107" }, { "code": null, "e": 3449, "s": 3435, "text": "geeky01adarsh" }, { "code": null, "e": 3457, "s": 3449, "text": "GATE CS" }, { "code": null, "e": 3475, "s": 3457, "text": "Operating Systems" }, { "code": null, "e": 3493, "s": 3475, "text": "Operating Systems" }, { "code": null, "e": 3591, "s": 3493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3612, "s": 3591, "text": "Normal Forms in DBMS" }, { "code": null, "e": 3653, "s": 3612, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 3687, "s": 3653, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 3719, "s": 3687, "text": "Differences between TCP and UDP" }, { "code": null, "e": 3757, "s": 3719, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 3796, "s": 3757, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 3823, "s": 3796, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 3864, "s": 3823, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 3909, "s": 3864, "text": "Introduction of Deadlock in Operating System" } ]
K Dimensional Tree | Set 3 (Delete)
17 Sep, 2021 We strongly recommend to refer below posts as a prerequisite of this.K Dimensional Tree | Set 1 (Search and Insert) K Dimensional Tree | Set 2 (Find Minimum)In this post delete is discussed. The operation is to delete a given point from K D Tree. Like Binary Search Tree Delete, we recursively traverse down and search for the point to be deleted. Below are steps are followed for every node visited. 1) If current node contains the point to be deleted If node to be deleted is a leaf node, simply delete it (Same as BST Delete)If node to be deleted has right child as not NULL (Different from BST) Find minimum of current node’s dimension in right subtree.Replace the node with above found minimum and recursively delete minimum in right subtree.Else If node to be deleted has left child as not NULL (Different from BST) Find minimum of current node’s dimension in left subtree.Replace the node with above found minimum and recursively delete minimum in left subtree.Make new left subtree as right child of current node. If node to be deleted is a leaf node, simply delete it (Same as BST Delete) If node to be deleted has right child as not NULL (Different from BST) Find minimum of current node’s dimension in right subtree.Replace the node with above found minimum and recursively delete minimum in right subtree. Find minimum of current node’s dimension in right subtree.Replace the node with above found minimum and recursively delete minimum in right subtree. Find minimum of current node’s dimension in right subtree. Replace the node with above found minimum and recursively delete minimum in right subtree. Else If node to be deleted has left child as not NULL (Different from BST) Find minimum of current node’s dimension in left subtree.Replace the node with above found minimum and recursively delete minimum in left subtree.Make new left subtree as right child of current node. Find minimum of current node’s dimension in left subtree.Replace the node with above found minimum and recursively delete minimum in left subtree.Make new left subtree as right child of current node. Find minimum of current node’s dimension in left subtree. Replace the node with above found minimum and recursively delete minimum in left subtree. Make new left subtree as right child of current node. 2) If current doesn’t contain the point to be deleted If node to be deleted is smaller than current node on current dimension, recur for left subtree.Else recur for right subtree. If node to be deleted is smaller than current node on current dimension, recur for left subtree. Else recur for right subtree. Why 1.b and 1.c are different from BST? In BST delete, if a node’s left child is empty and right is not empty, we replace the node with right child. In K D Tree, doing this would violate the KD tree property as dimension of right child of node is different from node’s dimension. For example, if node divides point by x axis values. then its children divide by y axis, so we can’t simply replace node with right child. Same is true for the case when right child is not empty and left child is empty. 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. Why 1.c doesn’t find max in left subtree and recur for max like 1.b? Doing this violates the property that all equal values are in right subtree. For example, if we delete (!0, 10) in below subtree and replace if with Wrong Way (Equal key in left subtree after deletion) (5, 6) (4, 10) / Delete(5, 6) / (4, 10) ------------> (4, 20) \ (4, 20) Right way (Equal key in right subtree after deletion) (5, 6) (4, 10) / Delete(5, 6) \ (4, 10) ------------> (4, 20) \ (4, 20) Example of Delete: Delete (30, 40): Since right child is not NULL and dimension of node is x, we find the node with minimum x value in right child. The node is (35, 45), we replace (30, 40) with (35, 45) and delete (30, 40). Delete (70, 70): Dimension of node is y. Since right child is NULL, we find the node with minimum y value in left child. The node is (50, 30), we replace (70, 70) with (50, 30) and recursively delete (50, 30) in left subtree. Finally we make the modified left subtree as right subtree of (50, 30). Below is C++ implementation of K D Tree delete. C++ // A C++ program to demonstrate delete in K D tree#include<bits/stdc++.h>using namespace std; const int k = 2; // A structure to represent node of kd treestruct Node{ int point[k]; // To store k dimensional point Node *left, *right;}; // A method to create a node of K D treestruct Node* newNode(int arr[]){ struct Node* temp = new Node; for (int i=0; i<k; i++) temp->point[i] = arr[i]; temp->left = temp->right = NULL; return temp;} // Inserts a new node and returns root of modified tree// The parameter depth is used to decide axis of comparisonNode *insertRec(Node *root, int point[], unsigned depth){ // Tree is empty? if (root == NULL) return newNode(point); // Calculate current dimension (cd) of comparison unsigned cd = depth % k; // Compare the new point with root on current dimension 'cd' // and decide the left or right subtree if (point[cd] < (root->point[cd])) root->left = insertRec(root->left, point, depth + 1); else root->right = insertRec(root->right, point, depth + 1); return root;} // Function to insert a new point with given point in// KD Tree and return new root. It mainly uses above recursive// function "insertRec()"Node* insert(Node *root, int point[]){ return insertRec(root, point, 0);} // A utility function to find minimum of three integersNode *minNode(Node *x, Node *y, Node *z, int d){ Node *res = x; if (y != NULL && y->point[d] < res->point[d]) res = y; if (z != NULL && z->point[d] < res->point[d]) res = z; return res;} // Recursively finds minimum of d'th dimension in KD tree// The parameter depth is used to determine current axis.Node *findMinRec(Node* root, int d, unsigned depth){ // Base cases if (root == NULL) return NULL; // Current dimension is computed using current depth and total // dimensions (k) unsigned cd = depth % k; // Compare point with root with respect to cd (Current dimension) if (cd == d) { if (root->left == NULL) return root; return findMinRec(root->left, d, depth+1); } // If current dimension is different then minimum can be anywhere // in this subtree return minNode(root, findMinRec(root->left, d, depth+1), findMinRec(root->right, d, depth+1), d);} // A wrapper over findMinRec(). Returns minimum of d'th dimensionNode *findMin(Node* root, int d){ // Pass current level or depth as 0 return findMinRec(root, d, 0);} // A utility method to determine if two Points are same// in K Dimensional spacebool arePointsSame(int point1[], int point2[]){ // Compare individual pointinate values for (int i = 0; i < k; ++i) if (point1[i] != point2[i]) return false; return true;} // Copies point p2 to p1void copyPoint(int p1[], int p2[]){ for (int i=0; i<k; i++) p1[i] = p2[i];} // Function to delete a given point 'point[]' from tree with root// as 'root'. depth is current depth and passed as 0 initially.// Returns root of the modified tree.Node *deleteNodeRec(Node *root, int point[], int depth){ // Given point is not present if (root == NULL) return NULL; // Find dimension of current node int cd = depth % k; // If the point to be deleted is present at root if (arePointsSame(root->point, point)) { // 2.b) If right child is not NULL if (root->right != NULL) { // Find minimum of root's dimension in right subtree Node *min = findMin(root->right, cd); // Copy the minimum to root copyPoint(root->point, min->point); // Recursively delete the minimum root->right = deleteNodeRec(root->right, min->point, depth+1); } else if (root->left != NULL) // same as above { Node *min = findMin(root->left, cd); copyPoint(root->point, min->point); root->right = deleteNodeRec(root->left, min->point, depth+1); } else // If node to be deleted is leaf node { delete root; return NULL; } return root; } // 2) If current node doesn't contain point, search downward if (point[cd] < root->point[cd]) root->left = deleteNodeRec(root->left, point, depth+1); else root->right = deleteNodeRec(root->right, point, depth+1); return root;} // Function to delete a given point from K D Tree with 'root' Node* deleteNode(Node *root, int point[]){ // Pass depth as 0 return deleteNodeRec(root, point, 0);} // Driver program to test above functionsint main(){ struct Node *root = NULL; int points[][k] = {{30, 40}, {5, 25}, {70, 70}, {10, 12}, {50, 30}, {35, 45}}; int n = sizeof(points)/sizeof(points[0]); for (int i=0; i<n; i++) root = insert(root, points[i]); // Delete (30, 40); root = deleteNode(root, points[0]); cout << "Root after deletion of (30, 40)\n"; cout << root->point[0] << ", " << root->point[1] << endl; return 0;} Output: Root after deletion of (30, 40) 35, 45 K-Dimensional Tree [Delete] | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersK-Dimensional Tree [Delete] | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TavqLwDGwEs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Source: https://www.cs.umd.edu/class/spring2008/cmsc420/L19.kd-trees.pdfThis article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above aakarsha_chugh surindertarika1234 Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) LRU Cache Implementation Introduction of B-Tree Agents in Artificial Intelligence Red-Black Tree | Set 1 (Introduction) Decision Tree Introduction with example Binary Indexed Tree or Fenwick Tree AVL Tree | Set 2 (Deletion) Disjoint Set Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Sep, 2021" }, { "code": null, "e": 299, "s": 52, "text": "We strongly recommend to refer below posts as a prerequisite of this.K Dimensional Tree | Set 1 (Search and Insert) K Dimensional Tree | Set 2 (Find Minimum)In this post delete is discussed. The operation is to delete a given point from K D Tree." }, { "code": null, "e": 453, "s": 299, "text": "Like Binary Search Tree Delete, we recursively traverse down and search for the point to be deleted. Below are steps are followed for every node visited." }, { "code": null, "e": 506, "s": 453, "text": "1) If current node contains the point to be deleted " }, { "code": null, "e": 1075, "s": 506, "text": "If node to be deleted is a leaf node, simply delete it (Same as BST Delete)If node to be deleted has right child as not NULL (Different from BST) Find minimum of current node’s dimension in right subtree.Replace the node with above found minimum and recursively delete minimum in right subtree.Else If node to be deleted has left child as not NULL (Different from BST) Find minimum of current node’s dimension in left subtree.Replace the node with above found minimum and recursively delete minimum in left subtree.Make new left subtree as right child of current node." }, { "code": null, "e": 1151, "s": 1075, "text": "If node to be deleted is a leaf node, simply delete it (Same as BST Delete)" }, { "code": null, "e": 1371, "s": 1151, "text": "If node to be deleted has right child as not NULL (Different from BST) Find minimum of current node’s dimension in right subtree.Replace the node with above found minimum and recursively delete minimum in right subtree." }, { "code": null, "e": 1520, "s": 1371, "text": "Find minimum of current node’s dimension in right subtree.Replace the node with above found minimum and recursively delete minimum in right subtree." }, { "code": null, "e": 1579, "s": 1520, "text": "Find minimum of current node’s dimension in right subtree." }, { "code": null, "e": 1670, "s": 1579, "text": "Replace the node with above found minimum and recursively delete minimum in right subtree." }, { "code": null, "e": 1945, "s": 1670, "text": "Else If node to be deleted has left child as not NULL (Different from BST) Find minimum of current node’s dimension in left subtree.Replace the node with above found minimum and recursively delete minimum in left subtree.Make new left subtree as right child of current node." }, { "code": null, "e": 2145, "s": 1945, "text": "Find minimum of current node’s dimension in left subtree.Replace the node with above found minimum and recursively delete minimum in left subtree.Make new left subtree as right child of current node." }, { "code": null, "e": 2203, "s": 2145, "text": "Find minimum of current node’s dimension in left subtree." }, { "code": null, "e": 2293, "s": 2203, "text": "Replace the node with above found minimum and recursively delete minimum in left subtree." }, { "code": null, "e": 2347, "s": 2293, "text": "Make new left subtree as right child of current node." }, { "code": null, "e": 2403, "s": 2347, "text": "2) If current doesn’t contain the point to be deleted " }, { "code": null, "e": 2529, "s": 2403, "text": "If node to be deleted is smaller than current node on current dimension, recur for left subtree.Else recur for right subtree." }, { "code": null, "e": 2626, "s": 2529, "text": "If node to be deleted is smaller than current node on current dimension, recur for left subtree." }, { "code": null, "e": 2656, "s": 2626, "text": "Else recur for right subtree." }, { "code": null, "e": 3156, "s": 2656, "text": "Why 1.b and 1.c are different from BST? In BST delete, if a node’s left child is empty and right is not empty, we replace the node with right child. In K D Tree, doing this would violate the KD tree property as dimension of right child of node is different from node’s dimension. For example, if node divides point by x axis values. then its children divide by y axis, so we can’t simply replace node with right child. Same is true for the case when right child is not empty and left child is empty." }, { "code": null, "e": 3165, "s": 3156, "text": "Chapters" }, { "code": null, "e": 3192, "s": 3165, "text": "descriptions off, selected" }, { "code": null, "e": 3242, "s": 3192, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 3265, "s": 3242, "text": "captions off, selected" }, { "code": null, "e": 3273, "s": 3265, "text": "English" }, { "code": null, "e": 3297, "s": 3273, "text": "This is a modal window." }, { "code": null, "e": 3366, "s": 3297, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 3388, "s": 3366, "text": "End of dialog window." }, { "code": null, "e": 3607, "s": 3388, "text": "Why 1.c doesn’t find max in left subtree and recur for max like 1.b? Doing this violates the property that all equal values are in right subtree. For example, if we delete (!0, 10) in below subtree and replace if with " }, { "code": null, "e": 4113, "s": 3607, "text": "Wrong Way (Equal key in left subtree after deletion)\n (5, 6) (4, 10)\n / Delete(5, 6) / \n (4, 10) ------------> (4, 20)\n \\\n (4, 20) \n\nRight way (Equal key in right subtree after deletion)\n (5, 6) (4, 10)\n / Delete(5, 6) \\\n (4, 10) ------------> (4, 20)\n \\\n (4, 20) " }, { "code": null, "e": 4338, "s": 4113, "text": "Example of Delete: Delete (30, 40): Since right child is not NULL and dimension of node is x, we find the node with minimum x value in right child. The node is (35, 45), we replace (30, 40) with (35, 45) and delete (30, 40)." }, { "code": null, "e": 4638, "s": 4338, "text": "Delete (70, 70): Dimension of node is y. Since right child is NULL, we find the node with minimum y value in left child. The node is (50, 30), we replace (70, 70) with (50, 30) and recursively delete (50, 30) in left subtree. Finally we make the modified left subtree as right subtree of (50, 30). " }, { "code": null, "e": 4686, "s": 4638, "text": "Below is C++ implementation of K D Tree delete." }, { "code": null, "e": 4690, "s": 4686, "text": "C++" }, { "code": "// A C++ program to demonstrate delete in K D tree#include<bits/stdc++.h>using namespace std; const int k = 2; // A structure to represent node of kd treestruct Node{ int point[k]; // To store k dimensional point Node *left, *right;}; // A method to create a node of K D treestruct Node* newNode(int arr[]){ struct Node* temp = new Node; for (int i=0; i<k; i++) temp->point[i] = arr[i]; temp->left = temp->right = NULL; return temp;} // Inserts a new node and returns root of modified tree// The parameter depth is used to decide axis of comparisonNode *insertRec(Node *root, int point[], unsigned depth){ // Tree is empty? if (root == NULL) return newNode(point); // Calculate current dimension (cd) of comparison unsigned cd = depth % k; // Compare the new point with root on current dimension 'cd' // and decide the left or right subtree if (point[cd] < (root->point[cd])) root->left = insertRec(root->left, point, depth + 1); else root->right = insertRec(root->right, point, depth + 1); return root;} // Function to insert a new point with given point in// KD Tree and return new root. It mainly uses above recursive// function \"insertRec()\"Node* insert(Node *root, int point[]){ return insertRec(root, point, 0);} // A utility function to find minimum of three integersNode *minNode(Node *x, Node *y, Node *z, int d){ Node *res = x; if (y != NULL && y->point[d] < res->point[d]) res = y; if (z != NULL && z->point[d] < res->point[d]) res = z; return res;} // Recursively finds minimum of d'th dimension in KD tree// The parameter depth is used to determine current axis.Node *findMinRec(Node* root, int d, unsigned depth){ // Base cases if (root == NULL) return NULL; // Current dimension is computed using current depth and total // dimensions (k) unsigned cd = depth % k; // Compare point with root with respect to cd (Current dimension) if (cd == d) { if (root->left == NULL) return root; return findMinRec(root->left, d, depth+1); } // If current dimension is different then minimum can be anywhere // in this subtree return minNode(root, findMinRec(root->left, d, depth+1), findMinRec(root->right, d, depth+1), d);} // A wrapper over findMinRec(). Returns minimum of d'th dimensionNode *findMin(Node* root, int d){ // Pass current level or depth as 0 return findMinRec(root, d, 0);} // A utility method to determine if two Points are same// in K Dimensional spacebool arePointsSame(int point1[], int point2[]){ // Compare individual pointinate values for (int i = 0; i < k; ++i) if (point1[i] != point2[i]) return false; return true;} // Copies point p2 to p1void copyPoint(int p1[], int p2[]){ for (int i=0; i<k; i++) p1[i] = p2[i];} // Function to delete a given point 'point[]' from tree with root// as 'root'. depth is current depth and passed as 0 initially.// Returns root of the modified tree.Node *deleteNodeRec(Node *root, int point[], int depth){ // Given point is not present if (root == NULL) return NULL; // Find dimension of current node int cd = depth % k; // If the point to be deleted is present at root if (arePointsSame(root->point, point)) { // 2.b) If right child is not NULL if (root->right != NULL) { // Find minimum of root's dimension in right subtree Node *min = findMin(root->right, cd); // Copy the minimum to root copyPoint(root->point, min->point); // Recursively delete the minimum root->right = deleteNodeRec(root->right, min->point, depth+1); } else if (root->left != NULL) // same as above { Node *min = findMin(root->left, cd); copyPoint(root->point, min->point); root->right = deleteNodeRec(root->left, min->point, depth+1); } else // If node to be deleted is leaf node { delete root; return NULL; } return root; } // 2) If current node doesn't contain point, search downward if (point[cd] < root->point[cd]) root->left = deleteNodeRec(root->left, point, depth+1); else root->right = deleteNodeRec(root->right, point, depth+1); return root;} // Function to delete a given point from K D Tree with 'root' Node* deleteNode(Node *root, int point[]){ // Pass depth as 0 return deleteNodeRec(root, point, 0);} // Driver program to test above functionsint main(){ struct Node *root = NULL; int points[][k] = {{30, 40}, {5, 25}, {70, 70}, {10, 12}, {50, 30}, {35, 45}}; int n = sizeof(points)/sizeof(points[0]); for (int i=0; i<n; i++) root = insert(root, points[i]); // Delete (30, 40); root = deleteNode(root, points[0]); cout << \"Root after deletion of (30, 40)\\n\"; cout << root->point[0] << \", \" << root->point[1] << endl; return 0;}", "e": 9770, "s": 4690, "text": null }, { "code": null, "e": 9779, "s": 9770, "text": "Output: " }, { "code": null, "e": 9818, "s": 9779, "text": "Root after deletion of (30, 40)\n35, 45" }, { "code": null, "e": 10931, "s": 9818, "text": "K-Dimensional Tree [Delete] | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersK-Dimensional Tree [Delete] | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=TavqLwDGwEs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Source: https://www.cs.umd.edu/class/spring2008/cmsc420/L19.kd-trees.pdfThis article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10946, "s": 10931, "text": "aakarsha_chugh" }, { "code": null, "e": 10965, "s": 10946, "text": "surindertarika1234" }, { "code": null, "e": 10989, "s": 10965, "text": "Advanced Data Structure" }, { "code": null, "e": 11087, "s": 10989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11116, "s": 11087, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 11143, "s": 11116, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 11168, "s": 11143, "text": "LRU Cache Implementation" }, { "code": null, "e": 11191, "s": 11168, "text": "Introduction of B-Tree" }, { "code": null, "e": 11225, "s": 11191, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 11263, "s": 11225, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 11303, "s": 11263, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 11339, "s": 11303, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 11367, "s": 11339, "text": "AVL Tree | Set 2 (Deletion)" } ]